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));
4709 get_set_notification_method (MonoClass* async_builder_class)
4712 GPtrArray* array = mono_class_get_methods_by_name (async_builder_class, "SetNotificationForWaitCompletion", 0x24, FALSE, FALSE, &error);
4713 mono_error_assert_ok (&error);
4714 g_assert (array->len == 1);
4715 MonoMethod* set_notification_method = (MonoMethod *)g_ptr_array_index (array, 0);
4716 g_ptr_array_free (array, TRUE);
4717 return set_notification_method;
4721 set_set_notification_for_wait_completion_flag (StackFrame *frame)
4723 MonoObject* obj = get_this (frame);
4725 MonoClassField *builder_field = mono_class_get_field_from_name (obj->vtable->klass, "<>t__builder");
4726 g_assert (builder_field);
4727 MonoObject* builder;
4729 builder = mono_field_get_value_object_checked (frame->domain, builder_field, obj, &error);
4730 mono_error_assert_ok (&error);
4734 gboolean arg = TRUE;
4736 mono_runtime_invoke_checked (get_set_notification_method (builder->vtable->klass), mono_object_unbox (builder), args, &error);
4737 mono_error_assert_ok (&error);
4738 mono_field_set_value (obj, builder_field, mono_object_unbox (builder));
4741 static MonoMethod* notify_debugger_of_wait_completion_method_cache = NULL;
4744 get_notify_debugger_of_wait_completion_method ()
4746 if (notify_debugger_of_wait_completion_method_cache != NULL)
4747 return notify_debugger_of_wait_completion_method_cache;
4749 MonoClass* task_class = mono_class_load_from_name (mono_defaults.corlib, "System.Threading.Tasks", "Task");
4750 GPtrArray* array = mono_class_get_methods_by_name (task_class, "NotifyDebuggerOfWaitCompletion", 0x24, FALSE, FALSE, &error);
4751 mono_error_assert_ok (&error);
4752 g_assert (array->len == 1);
4753 notify_debugger_of_wait_completion_method_cache = (MonoMethod *)g_ptr_array_index (array, 0);
4754 g_ptr_array_free (array, TRUE);
4755 return notify_debugger_of_wait_completion_method_cache;
4759 process_breakpoint_inner (DebuggerTlsData *tls, gboolean from_signal)
4763 int i, j, suspend_policy;
4764 guint32 native_offset;
4766 BreakpointInstance *inst;
4767 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4768 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4769 EventKind kind = EVENT_KIND_BREAKPOINT;
4770 MonoContext *ctx = &tls->restore_state.ctx;
4772 MonoSeqPointInfo *info;
4776 // FIXME: Speed this up
4778 ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
4779 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4780 g_assert (ji && !ji->is_trampoline);
4781 method = jinfo_get_method (ji);
4783 /* Compute the native offset of the breakpoint from the ip */
4784 native_offset = ip - (guint8*)ji->code_start;
4787 * Skip the instruction causing the breakpoint signal.
4790 mono_arch_skip_breakpoint (ctx, ji);
4792 if (method->wrapper_type || tls->disable_breakpoints)
4795 bp_reqs = g_ptr_array_new ();
4796 ss_reqs = g_ptr_array_new ();
4797 ss_reqs_orig = g_ptr_array_new ();
4799 mono_loader_lock ();
4802 * The ip points to the instruction causing the breakpoint event, which is after
4803 * the offset recorded in the seq point map, so find the prev seq point before ip.
4805 found_sp = mono_find_prev_seq_point_for_native_offset (mono_domain_get (), method, native_offset, &info, &sp);
4808 no_seq_points_found (method, native_offset);
4810 g_assert (found_sp);
4812 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);
4815 for (i = 0; i < breakpoints->len; ++i) {
4816 bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4821 for (j = 0; j < bp->children->len; ++j) {
4822 inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4823 if (inst->ji == ji && inst->il_offset == sp.il_offset && inst->native_offset == sp.native_offset) {
4824 if (bp->req->event_kind == EVENT_KIND_STEP) {
4825 g_ptr_array_add (ss_reqs_orig, bp->req);
4827 g_ptr_array_add (bp_reqs, bp->req);
4832 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4833 /* Maybe a method entry/exit event */
4834 if (sp.il_offset == METHOD_ENTRY_IL_OFFSET)
4835 kind = EVENT_KIND_METHOD_ENTRY;
4836 else if (sp.il_offset == METHOD_EXIT_IL_OFFSET)
4837 kind = EVENT_KIND_METHOD_EXIT;
4840 /* Process single step requests */
4841 for (i = 0; i < ss_reqs_orig->len; ++i) {
4842 EventRequest *req = (EventRequest *)g_ptr_array_index (ss_reqs_orig, i);
4843 SingleStepReq *ss_req = (SingleStepReq *)req->info;
4846 //if we hit async_stepout_method, it's our no matter which thread
4847 if ((ss_req->async_stepout_method != method) && (ss_req->async_id || mono_thread_internal_current () != ss_req->thread)) {
4848 //We have different thread and we don't have async stepping in progress
4849 //it's breakpoint in parallel thread, ignore it
4850 if (ss_req->async_id == 0)
4853 tls->context.valid = FALSE;
4854 tls->async_state.valid = FALSE;
4855 invalidate_frames (tls);
4856 ss_calculate_framecount(tls, ctx);
4857 //make sure we have enough data to get current async method instance id
4858 if (tls->frame_count == 0 || !ensure_jit (tls->frames [0]))
4861 //Check method is async before calling get_this_async_id
4862 MonoDebugMethodAsyncInfo* asyncMethod = mono_debug_lookup_method_async_debug_info (method);
4866 mono_debug_free_method_async_debug_info (asyncMethod);
4868 //breakpoint was hit in parallelly executing async method, ignore it
4869 if (ss_req->async_id != get_this_async_id (tls->frames [0]))
4873 //Update stepping request to new thread/frame_count that we are continuing on
4874 //so continuing with normal stepping works as expected
4875 if (ss_req->async_stepout_method || ss_req->async_id) {
4876 tls->context.valid = FALSE;
4877 tls->async_state.valid = FALSE;
4878 invalidate_frames (tls);
4879 ss_calculate_framecount (tls, ctx);
4880 ss_req->thread = mono_thread_internal_current ();
4881 ss_req->nframes = tls->frame_count;
4884 hit = ss_update (ss_req, ji, &sp, tls, ctx, method);
4886 g_ptr_array_add (ss_reqs, req);
4888 /* Start single stepping again from the current sequence point */
4889 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
4892 if (ss_reqs->len > 0)
4893 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4894 if (bp_reqs->len > 0)
4895 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4896 if (kind != EVENT_KIND_BREAKPOINT)
4897 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4899 mono_loader_unlock ();
4901 g_ptr_array_free (bp_reqs, TRUE);
4902 g_ptr_array_free (ss_reqs, TRUE);
4905 * FIXME: The first event will suspend, so the second will only be sent after the
4909 process_event (EVENT_KIND_STEP, method, 0, ctx, ss_events, suspend_policy);
4911 process_event (kind, method, 0, ctx, bp_events, suspend_policy);
4912 if (enter_leave_events)
4913 process_event (kind, method, 0, ctx, enter_leave_events, suspend_policy);
4916 /* Process a breakpoint/single step event after resuming from a signal handler */
4918 process_signal_event (void (*func) (DebuggerTlsData*, gboolean))
4920 DebuggerTlsData *tls;
4921 MonoThreadUnwindState orig_restore_state;
4924 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4925 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4926 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4927 mono_thread_state_init_from_monoctx (&tls->restore_state, &tls->handler_ctx);
4931 /* This is called when resuming from a signal handler, so it shouldn't return */
4932 memcpy (&ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4933 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4934 mono_restore_context (&ctx);
4935 g_assert_not_reached ();
4939 process_breakpoint (void)
4941 process_signal_event (process_breakpoint_inner);
4945 resume_from_signal_handler (void *sigctx, void *func)
4947 DebuggerTlsData *tls;
4950 /* Save the original context in TLS */
4951 // FIXME: This might not work on an altstack ?
4952 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4954 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer) (gsize) mono_native_thread_id_get ());
4957 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4958 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4959 // clob:c could be added to op_seq_point.
4961 mono_sigctx_to_monoctx (sigctx, &ctx);
4962 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4963 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4964 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4966 MONO_CONTEXT_SET_IP (&ctx, func);
4968 mono_monoctx_to_sigctx (&ctx, sigctx);
4970 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4971 mono_ppc_set_func_into_sigctx (sigctx, func);
4976 mono_debugger_agent_breakpoint_hit (void *sigctx)
4979 * We are called from a signal handler, and running code there causes all kinds of
4980 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4981 * So set up the signal context to return to the real breakpoint handler function.
4983 resume_from_signal_handler (sigctx, process_breakpoint);
4987 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4989 if (frame->managed) {
4990 *(MonoContext*)data = *ctx;
4999 * Called by System.Diagnostics.Debugger:Break ().
5002 mono_debugger_agent_user_break (void)
5004 if (agent_config.enabled) {
5009 /* Obtain a context */
5010 MONO_CONTEXT_SET_IP (&ctx, NULL);
5011 mono_walk_stack_with_ctx (user_break_cb, NULL, (MonoUnwindOptions)0, &ctx);
5012 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
5014 mono_loader_lock ();
5015 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
5016 mono_loader_unlock ();
5018 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
5019 } else if (debug_options.native_debugger_break) {
5025 ss_depth_to_string (StepDepth depth)
5028 case STEP_DEPTH_OVER:
5030 case STEP_DEPTH_OUT:
5032 case STEP_DEPTH_INTO:
5035 g_assert_not_reached ();
5041 process_single_step_inner (DebuggerTlsData *tls, gboolean from_signal)
5046 int il_offset, suspend_policy;
5049 MonoContext *ctx = &tls->restore_state.ctx;
5052 MonoSeqPointInfo *info;
5054 ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
5056 /* Skip the instruction causing the single step */
5058 mono_arch_skip_single_step (ctx);
5060 if (suspend_count > 0) {
5061 /* Fastpath during invokes, see in process_suspend () */
5062 if (suspend_count - tls->resume_count == 0)
5064 process_suspend (tls, ctx);
5069 // FIXME: A suspend race
5072 if (mono_thread_internal_current () != ss_req->thread)
5075 if (log_level > 0) {
5076 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
5078 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);
5081 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
5082 g_assert (ji && !ji->is_trampoline);
5083 method = jinfo_get_method (ji);
5086 if (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
5091 * Stopping in memset makes half-initialized vtypes visible.
5092 * Stopping in memcpy makes half-copied vtypes visible.
5094 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
5098 * This could be in ss_update method, but mono_find_next_seq_point_for_native_offset is pretty expensive method,
5099 * hence we prefer this check here.
5101 if (ss_req->user_assemblies) {
5102 gboolean found = FALSE;
5103 for (int k = 0; ss_req->user_assemblies[k]; k++)
5104 if (ss_req->user_assemblies[k] == method->klass->image->assembly) {
5114 * The ip points to the instruction causing the single step event, which is before
5115 * the offset recorded in the seq point map, so find the next seq point after ip.
5117 if (!mono_find_next_seq_point_for_native_offset (domain, method, (guint8*)ip - (guint8*)ji->code_start, &info, &sp))
5120 il_offset = sp.il_offset;
5122 if (!ss_update (ss_req, ji, &sp, tls, ctx, method))
5125 /* Start single stepping again from the current sequence point */
5126 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
5128 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
5129 (method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
5130 !strcmp (method->name, ".cctor"))
5133 // FIXME: Has to lock earlier
5135 reqs = g_ptr_array_new ();
5137 mono_loader_lock ();
5139 g_ptr_array_add (reqs, ss_req->req);
5141 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
5143 g_ptr_array_free (reqs, TRUE);
5145 mono_loader_unlock ();
5147 process_event (EVENT_KIND_STEP, jinfo_get_method (ji), il_offset, ctx, events, suspend_policy);
5151 process_single_step (void)
5153 process_signal_event (process_single_step_inner);
5157 * mono_debugger_agent_single_step_event:
5159 * Called from a signal handler to handle a single step event.
5162 mono_debugger_agent_single_step_event (void *sigctx)
5164 /* Resume to process_single_step through the signal context */
5166 // FIXME: Since step out/over is implemented using step in, the step in case should
5167 // be as fast as possible. Move the relevant code from process_single_step_inner ()
5170 if (is_debugger_thread ()) {
5172 * This could happen despite our best effors when the runtime calls
5173 * assembly/type resolve hooks.
5174 * FIXME: Breakpoints too.
5178 mono_sigctx_to_monoctx (sigctx, &ctx);
5179 mono_arch_skip_single_step (&ctx);
5180 mono_monoctx_to_sigctx (&ctx, sigctx);
5184 resume_from_signal_handler (sigctx, process_single_step);
5188 debugger_agent_single_step_from_context (MonoContext *ctx)
5190 DebuggerTlsData *tls;
5191 MonoThreadUnwindState orig_restore_state;
5193 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5194 /* Fastpath during invokes, see in process_suspend () */
5195 if (tls && suspend_count && suspend_count - tls->resume_count == 0)
5198 if (is_debugger_thread ())
5203 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
5204 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5205 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5206 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5208 process_single_step_inner (tls, FALSE);
5210 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5211 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5215 debugger_agent_breakpoint_from_context (MonoContext *ctx)
5217 DebuggerTlsData *tls;
5218 MonoThreadUnwindState orig_restore_state;
5221 if (is_debugger_thread ())
5224 orig_ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
5225 MONO_CONTEXT_SET_IP (ctx, orig_ip - 1);
5227 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5229 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5230 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5231 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5233 process_breakpoint_inner (tls, FALSE);
5235 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5236 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5237 if (MONO_CONTEXT_GET_IP (ctx) == orig_ip - 1)
5238 MONO_CONTEXT_SET_IP (ctx, orig_ip);
5242 * start_single_stepping:
5244 * Turn on single stepping. Can be called multiple times, for example,
5245 * by a single step event request + a suspend.
5248 start_single_stepping (void)
5250 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5251 int val = InterlockedIncrement (&ss_count);
5254 mono_arch_start_single_stepping ();
5256 g_assert_not_reached ();
5261 stop_single_stepping (void)
5263 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5264 int val = InterlockedDecrement (&ss_count);
5267 mono_arch_stop_single_stepping ();
5269 g_assert_not_reached ();
5276 * Stop the single stepping operation given by SS_REQ.
5279 ss_stop (SingleStepReq *ss_req)
5284 for (l = ss_req->bps; l; l = l->next) {
5285 clear_breakpoint ((MonoBreakpoint *)l->data);
5287 g_slist_free (ss_req->bps);
5291 ss_req->async_id = 0;
5292 ss_req->async_stepout_method = NULL;
5293 if (ss_req->global) {
5294 stop_single_stepping ();
5295 ss_req->global = FALSE;
5302 * Reject breakpoint if it is a duplicate of one already in list or hash table.
5305 ss_bp_is_unique (GSList *bps, GHashTable *ss_req_bp_cache, MonoMethod *method, guint32 il_offset)
5307 if (ss_req_bp_cache) {
5308 MonoBreakpoint dummy = {method, il_offset, NULL, NULL};
5309 return !g_hash_table_lookup (ss_req_bp_cache, &dummy);
5311 for (GSList *l = bps; l; l = l->next) {
5312 MonoBreakpoint *bp = (MonoBreakpoint *)l->data;
5313 if (bp->method == method && bp->il_offset == il_offset)
5322 * GHashTable equality for a MonoBreakpoint (only care about method and il_offset fields)
5325 ss_bp_eq (gconstpointer ka, gconstpointer kb)
5327 const MonoBreakpoint *s1 = (const MonoBreakpoint *)ka;
5328 const MonoBreakpoint *s2 = (const MonoBreakpoint *)kb;
5329 return (s1->method == s2->method && s1->il_offset == s2->il_offset) ? 1 : 0;
5335 * GHashTable hash for a MonoBreakpoint (only care about method and il_offset fields)
5338 ss_bp_hash (gconstpointer data)
5340 const MonoBreakpoint *s = (const MonoBreakpoint *)data;
5341 guint hash = (guint) (uintptr_t) s->method;
5342 hash ^= ((guint)s->il_offset) << 16; // Assume low bits are more interesting
5343 hash ^= ((guint)s->il_offset) >> 16;
5347 #define MAX_LINEAR_SCAN_BPS 7
5352 * Create a new breakpoint and add it to a step request.
5353 * Will adjust the bp count and cache used by ss_start.
5356 ss_bp_add_one (SingleStepReq *ss_req, int *ss_req_bp_count, GHashTable **ss_req_bp_cache,
5357 MonoMethod *method, guint32 il_offset)
5359 // This list is getting too long, switch to using the hash table
5360 if (!*ss_req_bp_cache && *ss_req_bp_count > MAX_LINEAR_SCAN_BPS) {
5361 *ss_req_bp_cache = g_hash_table_new (ss_bp_hash, ss_bp_eq);
5362 for (GSList *l = ss_req->bps; l; l = l->next)
5363 g_hash_table_insert (*ss_req_bp_cache, l->data, l->data);
5366 if (ss_bp_is_unique (ss_req->bps, *ss_req_bp_cache, method, il_offset)) {
5367 // Create and add breakpoint
5368 MonoBreakpoint *bp = set_breakpoint (method, il_offset, ss_req->req, NULL);
5369 ss_req->bps = g_slist_append (ss_req->bps, bp);
5370 if (*ss_req_bp_cache)
5371 g_hash_table_insert (*ss_req_bp_cache, bp, bp);
5372 (*ss_req_bp_count)++;
5374 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);
5379 is_last_non_empty (SeqPoint* sp, MonoSeqPointInfo *info)
5383 SeqPoint* next = g_new (SeqPoint, sp->next_len);
5384 mono_seq_point_init_next (info, *sp, next);
5385 for (int i = 0; i < sp->next_len; i++) {
5386 if (next [i].flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) {
5387 if (!is_last_non_empty (&next [i], info)) {
5403 * Start the single stepping operation given by SS_REQ from the sequence point SP.
5404 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
5405 * belong to the same thread as CTX.
5406 * If FRAMES is not-null, use that instead of tls->frames for placing breakpoints etc.
5409 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint* sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls,
5410 gboolean step_to_catch, StackFrame **frames, int nframes)
5412 int i, j, frame_index;
5413 SeqPoint *next_sp, *parent_sp = NULL;
5414 SeqPoint local_sp, local_parent_sp;
5416 MonoSeqPointInfo *parent_info;
5417 MonoMethod *parent_sp_method = NULL;
5418 gboolean enable_global = FALSE;
5420 // When 8 or more entries are in bps, we build a hash table to serve as a set of breakpoints.
5421 // Recreating this on each pass is a little wasteful but at least keeps behavior linear.
5422 int ss_req_bp_count = g_slist_length (ss_req->bps);
5423 GHashTable *ss_req_bp_cache = NULL;
5425 /* Stop the previous operation */
5429 * Implement single stepping using breakpoints if possible.
5431 if (step_to_catch) {
5432 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, sp->il_offset);
5436 if (ctx && !frames) {
5437 /* Need parent frames */
5438 if (!tls->context.valid)
5439 mono_thread_state_init_from_monoctx (&tls->context, ctx);
5440 compute_frame_info (tls->thread, tls);
5441 frames = tls->frames;
5442 nframes = tls->frame_count;
5445 MonoDebugMethodAsyncInfo* asyncMethod = mono_debug_lookup_method_async_debug_info (method);
5447 /* Need to stop in catch clauses as well */
5448 for (i = ss_req->depth == STEP_DEPTH_OUT ? 1 : 0; i < nframes; ++i) {
5449 StackFrame *frame = frames [i];
5452 MonoJitInfo *jinfo = frame->ji;
5453 for (j = 0; j < jinfo->num_clauses; ++j) {
5454 // In case of async method we don't want to place breakpoint on last catch handler(which state machine added for whole method)
5455 if (asyncMethod && asyncMethod->num_awaits && i == 0 && j + 1 == jinfo->num_clauses)
5457 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5459 if (mono_find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL, &local_sp))
5460 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, frame->method, local_sp.il_offset);
5465 if (asyncMethod && asyncMethod->num_awaits && nframes && ensure_jit (frames [0])) {
5466 //asyncMethod has value and num_awaits > 0, this means we are inside async method with awaits
5468 // Check if we hit yield_offset during normal stepping, because if we did...
5469 // Go into special async stepping mode which places breakpoint on resumeOffset
5470 // of this await call and sets async_id so we can distinguish it from parallel executions
5471 for (i = 0; i < asyncMethod->num_awaits; i++) {
5472 if (sp->il_offset == asyncMethod->yield_offsets [i]) {
5473 ss_req->async_id = get_this_async_id (frames [0]);
5474 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, asyncMethod->resume_offsets [i]);
5475 if (ss_req_bp_cache)
5476 g_hash_table_destroy (ss_req_bp_cache);
5477 mono_debug_free_method_async_debug_info (asyncMethod);
5481 //If we are at end of async method and doing step-in or step-over...
5482 //Switch to step-out, so whole NotifyDebuggerOfWaitCompletion magic happens...
5483 if (is_last_non_empty (sp, info)) {
5484 ss_req->depth = STEP_DEPTH_OUT;//setting depth to step-out is important, don't inline IF, because code later depends on this
5486 if (ss_req->depth == STEP_DEPTH_OUT) {
5487 set_set_notification_for_wait_completion_flag (frames [0]);
5488 ss_req->async_id = get_this_async_id (frames [0]);
5489 ss_req->async_stepout_method = get_notify_debugger_of_wait_completion_method ();
5490 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, ss_req->async_stepout_method, 0);
5491 if (ss_req_bp_cache)
5492 g_hash_table_destroy (ss_req_bp_cache);
5493 mono_debug_free_method_async_debug_info (asyncMethod);
5499 mono_debug_free_method_async_debug_info (asyncMethod);
5502 * Find the first sequence point in the current or in a previous frame which
5503 * is not the last in its method.
5505 if (ss_req->depth == STEP_DEPTH_OUT) {
5506 /* Ignore seq points in current method */
5507 while (frame_index < nframes) {
5508 StackFrame *frame = frames [frame_index];
5510 method = frame->method;
5511 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5512 sp = (found_sp)? &local_sp : NULL;
5514 if (sp && sp->next_len != 0)
5517 // There could be method calls before the next seq point in the caller when using nested calls
5518 //enable_global = TRUE;
5520 if (sp && sp->next_len == 0) {
5522 while (frame_index < nframes) {
5523 StackFrame *frame = frames [frame_index];
5525 method = frame->method;
5526 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5527 sp = (found_sp)? &local_sp : NULL;
5528 if (sp && sp->next_len != 0)
5534 /* Have to put a breakpoint into a parent frame since the seq points might not cover all control flow out of the method */
5535 while (frame_index < nframes) {
5536 StackFrame *frame = frames [frame_index];
5538 parent_sp_method = frame->method;
5539 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &parent_info, &local_parent_sp);
5540 parent_sp = found_sp ? &local_parent_sp : NULL;
5541 if (found_sp && parent_sp->next_len != 0)
5549 if (sp && sp->next_len > 0) {
5550 SeqPoint* next = g_new(SeqPoint, sp->next_len);
5552 mono_seq_point_init_next (info, *sp, next);
5553 for (i = 0; i < sp->next_len; i++) {
5556 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, next_sp->il_offset);
5562 SeqPoint* next = g_new(SeqPoint, parent_sp->next_len);
5564 mono_seq_point_init_next (parent_info, *parent_sp, next);
5565 for (i = 0; i < parent_sp->next_len; i++) {
5568 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, parent_sp_method, next_sp->il_offset);
5573 if (ss_req->nframes == 0)
5574 ss_req->nframes = nframes;
5576 if ((ss_req->depth == STEP_DEPTH_OVER) && (!sp && !parent_sp)) {
5577 DEBUG_PRINTF (1, "[dbg] No parent frame for step over, transition to step into.\n");
5579 * This is needed since if we leave managed code, and later return to it, step over
5580 * is not going to stop.
5581 * This approach is a bit ugly, since we change the step depth, but it only affects
5582 * clients who reuse the same step request, and only in this special case.
5584 ss_req->depth = STEP_DEPTH_INTO;
5587 if (ss_req->depth == STEP_DEPTH_INTO) {
5588 /* Enable global stepping so we stop at method entry too */
5589 enable_global = TRUE;
5593 * The ctx/frame info computed above will become invalid when we continue.
5595 tls->context.valid = FALSE;
5596 tls->async_state.valid = FALSE;
5597 invalidate_frames (tls);
5600 if (enable_global) {
5601 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5602 ss_req->global = TRUE;
5603 start_single_stepping ();
5604 } else if (!ss_req->bps) {
5605 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5606 ss_req->global = TRUE;
5607 start_single_stepping ();
5609 ss_req->global = FALSE;
5612 if (ss_req_bp_cache)
5613 g_hash_table_destroy (ss_req_bp_cache);
5617 * Start single stepping of thread THREAD
5620 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req)
5622 DebuggerTlsData *tls;
5623 MonoSeqPointInfo *info = NULL;
5624 SeqPoint *sp = NULL;
5627 MonoMethod *method = NULL;
5628 MonoDebugMethodInfo *minfo;
5629 gboolean step_to_catch = FALSE;
5630 gboolean set_ip = FALSE;
5631 StackFrame **frames = NULL;
5634 if (suspend_count == 0)
5635 return ERR_NOT_SUSPENDED;
5637 wait_for_suspend ();
5639 // FIXME: Multiple requests
5641 DEBUG_PRINTF (0, "Received a single step request while the previous one was still active.\n");
5642 return ERR_NOT_IMPLEMENTED;
5645 DEBUG_PRINTF (1, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth));
5647 ss_req = g_new0 (SingleStepReq, 1);
5649 ss_req->thread = thread;
5650 ss_req->size = size;
5651 ss_req->depth = depth;
5652 ss_req->filter = filter;
5655 for (int i = 0; i < req->nmodifiers; i++) {
5656 if (req->modifiers[i].kind == MOD_KIND_ASSEMBLY_ONLY) {
5657 ss_req->user_assemblies = req->modifiers[i].data.assemblies;
5662 mono_loader_lock ();
5663 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5664 mono_loader_unlock ();
5666 if (!tls->context.valid) {
5667 DEBUG_PRINTF (1, "Received a single step request on a thread with no managed frames.");
5668 return ERR_INVALID_ARGUMENT;
5671 if (tls->restore_state.valid && MONO_CONTEXT_GET_IP (&tls->context.ctx) != MONO_CONTEXT_GET_IP (&tls->restore_state.ctx)) {
5673 * Need to start single stepping from restore_state and not from the current state
5676 frames = compute_frame_info_from (thread, tls, &tls->restore_state, &nframes);
5679 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5681 if (tls->catch_state.valid) {
5683 StackFrameInfo frame;
5684 MonoContext new_ctx;
5685 MonoLMF *lmf = NULL;
5688 * We are stopped at a throw site. Stepping should go to the catch site.
5691 /* Find the the jit info for the catch context */
5692 res = mono_find_jit_info_ext (
5693 (MonoDomain *)tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN],
5694 (MonoJitTlsData *)((MonoThreadInfo*)thread->thread_info)->jit_data,
5695 NULL, &tls->catch_state.ctx, &new_ctx, NULL, &lmf, NULL, &frame);
5697 g_assert (frame.type == FRAME_TYPE_MANAGED);
5700 * Find the seq point corresponding to the landing site ip, which is the first seq
5703 found_sp = mono_find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info, &local_sp);
5704 sp = (found_sp)? &local_sp : NULL;
5706 no_seq_points_found (frame.method, frame.native_offset);
5709 method = frame.method;
5711 step_to_catch = TRUE;
5712 /* This make sure the seq point is not skipped by process_single_step () */
5713 ss_req->last_sp = NULL;
5716 if (!step_to_catch) {
5717 StackFrame *frame = NULL;
5720 if (frames && nframes)
5723 compute_frame_info (thread, tls);
5725 if (tls->frame_count)
5726 frame = tls->frames [0];
5729 if (ss_req->size == STEP_SIZE_LINE) {
5731 ss_req->last_method = frame->method;
5732 ss_req->last_line = -1;
5734 minfo = mono_debug_lookup_method (frame->method);
5735 if (minfo && frame->il_offset != -1) {
5736 MonoDebugSourceLocation *loc = mono_debug_method_lookup_location (minfo, frame->il_offset);
5739 ss_req->last_line = loc->row;
5747 if (!method && frame->il_offset != -1) {
5748 /* FIXME: Sort the table and use a binary search */
5749 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5750 sp = (found_sp)? &local_sp : NULL;
5752 no_seq_points_found (frame->method, frame->native_offset);
5754 method = frame->method;
5759 ss_req->start_method = method;
5761 ss_start (ss_req, method, sp, info, set_ip ? &tls->restore_state.ctx : &tls->context.ctx, tls, step_to_catch, frames, nframes);
5764 free_frames (frames, nframes);
5770 ss_destroy (SingleStepReq *req)
5773 g_assert (ss_req == req);
5782 ss_clear_for_assembly (SingleStepReq *req, MonoAssembly *assembly)
5785 gboolean found = TRUE;
5789 for (l = ss_req->bps; l; l = l->next) {
5790 if (breakpoint_matches_assembly ((MonoBreakpoint *)l->data, assembly)) {
5791 clear_breakpoint ((MonoBreakpoint *)l->data);
5792 ss_req->bps = g_slist_delete_link (ss_req->bps, l);
5801 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5804 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5811 if (!agent_config.enabled)
5814 mono_loader_lock ();
5815 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5816 mono_loader_unlock ();
5821 ei.category = mono_string_to_utf8_checked (category, &error);
5822 mono_error_cleanup (&error);
5826 ei.message = mono_string_to_utf8_checked (message, &error);
5827 mono_error_cleanup (&error);
5830 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5832 g_free (ei.category);
5833 g_free (ei.message);
5837 mono_debugger_agent_debug_log_is_enabled (void)
5839 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5840 return agent_config.enabled;
5843 #if defined(PLATFORM_ANDROID) || defined(TARGET_ANDROID)
5845 mono_debugger_agent_unhandled_exception (MonoException *exc)
5854 memset (&ei, 0, sizeof (EventInfo));
5855 ei.exc = (MonoObject*)exc;
5857 mono_loader_lock ();
5858 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5859 mono_loader_unlock ();
5861 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5866 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5867 MonoContext *catch_ctx)
5869 int i, j, suspend_policy;
5871 MonoJitInfo *ji, *catch_ji;
5873 DebuggerTlsData *tls = NULL;
5875 if (thread_to_tls != NULL) {
5876 MonoInternalThread *thread = mono_thread_internal_current ();
5878 mono_loader_lock ();
5879 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5880 mono_loader_unlock ();
5882 if (tls && tls->abort_requested)
5884 if (tls && tls->disable_breakpoints)
5888 memset (&ei, 0, sizeof (EventInfo));
5890 /* Just-In-Time debugging */
5892 if (agent_config.onuncaught && !inited) {
5893 finish_agent_init (FALSE);
5896 * Send an unsolicited EXCEPTION event with a dummy request id.
5898 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5899 ei.exc = (MonoObject*)exc;
5900 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5903 } else if (agent_config.onthrow && !inited) {
5905 gboolean found = FALSE;
5907 for (l = agent_config.onthrow; l; l = l->next) {
5908 char *ex_type = (char *)l->data;
5909 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5911 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5918 finish_agent_init (FALSE);
5921 * Send an unsolicited EXCEPTION event with a dummy request id.
5923 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5924 ei.exc = (MonoObject*)exc;
5925 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5933 ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5935 catch_ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5939 ei.exc = (MonoObject*)exc;
5940 ei.caught = catch_ctx != NULL;
5942 mono_loader_lock ();
5944 /* Treat exceptions which are caught in non-user code as unhandled */
5945 for (i = 0; i < event_requests->len; ++i) {
5946 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
5947 if (req->event_kind != EVENT_KIND_EXCEPTION)
5950 for (j = 0; j < req->nmodifiers; ++j) {
5951 Modifier *mod = &req->modifiers [j];
5953 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5955 gboolean found = FALSE;
5956 MonoAssembly **assemblies = mod->data.assemblies;
5959 for (k = 0; assemblies [k]; ++k)
5960 if (assemblies [k] == jinfo_get_method (catch_ji)->klass->image->assembly)
5969 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5970 mono_loader_unlock ();
5972 if (tls && ei.caught && catch_ctx) {
5973 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5974 tls->catch_state.ctx = *catch_ctx;
5975 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5976 tls->catch_state.valid = TRUE;
5979 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5982 tls->catch_state.valid = FALSE;
5986 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5988 DebuggerTlsData *tls;
5993 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5998 * We're about to invoke an exception filter during the first pass of exception handling.
6000 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
6001 * 'orig_ctx' is the context where the exception has been thrown.
6004 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
6006 * If we're stopped in Filter(), normal stack unwinding would first unwind to
6007 * the call site (line 37) and then continue to Main(), but it would never
6008 * include the throw site (line 32).
6010 * Since exception filters are invoked during the first pass of exception handling,
6011 * the stack frames of the throw site are still intact, so we should include them
6014 * We do this here by saving the context of the throw site in 'tls->filter_state'.
6016 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
6017 * but report the location of the 'throw' to the user.
6021 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
6025 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
6027 DebuggerTlsData *tls;
6032 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
6036 tls->filter_state.valid = FALSE;
6040 * buffer_add_value_full:
6042 * Add the encoding of the value at ADDR described by T to the buffer.
6043 * AS_VTYPE determines whenever to treat primitive types as primitive types or
6047 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
6048 gboolean as_vtype, GHashTable *parent_vtypes)
6051 gboolean boxed_vtype = FALSE;
6054 if (!(*(void**)addr)) {
6055 /* This can happen with compiler generated locals */
6056 //printf ("%s\n", mono_type_full_name (t));
6057 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
6060 g_assert (*(void**)addr);
6061 addr = *(void**)addr;
6066 case MONO_TYPE_BOOLEAN:
6069 case MONO_TYPE_CHAR:
6089 case MONO_TYPE_VOID:
6090 buffer_add_byte (buf, t->type);
6092 case MONO_TYPE_BOOLEAN:
6095 buffer_add_byte (buf, t->type);
6096 buffer_add_int (buf, *(gint8*)addr);
6098 case MONO_TYPE_CHAR:
6101 buffer_add_byte (buf, t->type);
6102 buffer_add_int (buf, *(gint16*)addr);
6107 buffer_add_byte (buf, t->type);
6108 buffer_add_int (buf, *(gint32*)addr);
6113 buffer_add_byte (buf, t->type);
6114 buffer_add_long (buf, *(gint64*)addr);
6118 /* Treat it as a vtype */
6120 case MONO_TYPE_PTR: {
6121 gssize val = *(gssize*)addr;
6123 buffer_add_byte (buf, t->type);
6124 buffer_add_long (buf, val);
6128 case MONO_TYPE_STRING:
6129 case MONO_TYPE_SZARRAY:
6130 case MONO_TYPE_OBJECT:
6131 case MONO_TYPE_CLASS:
6132 case MONO_TYPE_ARRAY:
6133 obj = *(MonoObject**)addr;
6136 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
6138 if (obj->vtable->klass->valuetype) {
6139 t = &obj->vtable->klass->byval_arg;
6140 addr = mono_object_unbox (obj);
6143 } else if (obj->vtable->klass->rank) {
6144 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
6145 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
6146 buffer_add_byte (buf, MONO_TYPE_CLASS);
6148 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
6150 buffer_add_objid (buf, obj);
6154 case MONO_TYPE_VALUETYPE:
6155 case MONO_TYPE_TYPEDBYREF: {
6159 MonoClass *klass = mono_class_from_mono_type (t);
6164 * Handle boxed vtypes recursively referencing themselves using fields.
6167 parent_vtypes = g_hash_table_new (NULL, NULL);
6168 vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
6170 if (CHECK_PROTOCOL_VERSION (2, 33)) {
6171 buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
6172 buffer_add_int (buf, vtype_index - 1);
6174 /* The client can't handle PARENT_VTYPE */
6175 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
6179 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
6183 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
6184 buffer_add_byte (buf, klass->enumtype);
6185 buffer_add_typeid (buf, domain, klass);
6189 while ((f = mono_class_get_fields (klass, &iter))) {
6190 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6192 if (mono_field_is_deleted (f))
6196 buffer_add_int (buf, nfields);
6199 while ((f = mono_class_get_fields (klass, &iter))) {
6200 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6202 if (mono_field_is_deleted (f))
6204 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE, parent_vtypes);
6208 g_hash_table_remove (parent_vtypes, addr);
6209 if (g_hash_table_size (parent_vtypes) == 0) {
6210 g_hash_table_destroy (parent_vtypes);
6211 parent_vtypes = NULL;
6216 case MONO_TYPE_GENERICINST:
6217 if (mono_type_generic_inst_is_valuetype (t)) {
6229 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
6231 buffer_add_value_full (buf, t, addr, domain, FALSE, NULL);
6235 obj_is_of_type (MonoObject *obj, MonoType *t)
6237 MonoClass *klass = obj->vtable->klass;
6238 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
6239 if (mono_class_is_transparent_proxy (klass)) {
6240 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
6241 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
6251 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
6254 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6260 gpointer iter = NULL;
6264 is_enum = decode_byte (buf, &buf, limit);
6265 /* Enums are sent as a normal vtype */
6267 return ERR_NOT_IMPLEMENTED;
6268 klass = decode_typeid (buf, &buf, limit, &d, &err);
6269 if (err != ERR_NONE)
6272 if (t && klass != mono_class_from_mono_type (t)) {
6273 char *name = mono_type_full_name (t);
6274 char *name2 = mono_type_full_name (&klass->byval_arg);
6275 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got %s.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, name2);
6278 return ERR_INVALID_ARGUMENT;
6281 nfields = decode_int (buf, &buf, limit);
6282 while ((f = mono_class_get_fields (klass, &iter))) {
6283 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6285 if (mono_field_is_deleted (f))
6287 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
6288 if (err != ERR_NONE)
6292 g_assert (nfields == 0);
6300 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6304 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
6305 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
6306 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
6307 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
6308 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE) &&
6309 !(t->type == MONO_TYPE_VALUETYPE && type == MONO_TYPE_OBJECT)) {
6310 char *name = mono_type_full_name (t);
6311 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
6313 return ERR_INVALID_ARGUMENT;
6317 case MONO_TYPE_BOOLEAN:
6318 *(guint8*)addr = decode_int (buf, &buf, limit);
6320 case MONO_TYPE_CHAR:
6321 *(gunichar2*)addr = decode_int (buf, &buf, limit);
6324 *(gint8*)addr = decode_int (buf, &buf, limit);
6327 *(guint8*)addr = decode_int (buf, &buf, limit);
6330 *(gint16*)addr = decode_int (buf, &buf, limit);
6333 *(guint16*)addr = decode_int (buf, &buf, limit);
6336 *(gint32*)addr = decode_int (buf, &buf, limit);
6339 *(guint32*)addr = decode_int (buf, &buf, limit);
6342 *(gint64*)addr = decode_long (buf, &buf, limit);
6345 *(guint64*)addr = decode_long (buf, &buf, limit);
6348 *(guint32*)addr = decode_int (buf, &buf, limit);
6351 *(guint64*)addr = decode_long (buf, &buf, limit);
6354 /* We send these as I8, so we get them back as such */
6355 g_assert (type == MONO_TYPE_I8);
6356 *(gssize*)addr = decode_long (buf, &buf, limit);
6358 case MONO_TYPE_GENERICINST:
6359 if (MONO_TYPE_ISSTRUCT (t)) {
6360 /* The client sends these as a valuetype */
6368 /* We send these as vtypes, so we get them back as such */
6369 g_assert (type == MONO_TYPE_VALUETYPE);
6372 case MONO_TYPE_VALUETYPE:
6373 if (type == MONO_TYPE_OBJECT) {
6375 int objid = decode_objid (buf, &buf, limit);
6379 err = get_object (objid, (MonoObject**)&obj);
6380 if (err != ERR_NONE)
6383 return ERR_INVALID_ARGUMENT;
6384 if (obj->vtable->klass != mono_class_from_mono_type (t)) {
6385 DEBUG_PRINTF (1, "Expected type '%s', got object '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6386 return ERR_INVALID_ARGUMENT;
6388 memcpy (addr, mono_object_unbox (obj), mono_class_value_size (obj->vtable->klass, NULL));
6390 err = decode_vtype (t, domain, addr, buf, &buf, limit);
6391 if (err != ERR_NONE)
6397 if (MONO_TYPE_IS_REFERENCE (t)) {
6398 if (type == MONO_TYPE_OBJECT) {
6399 int objid = decode_objid (buf, &buf, limit);
6403 err = get_object (objid, (MonoObject**)&obj);
6404 if (err != ERR_NONE)
6408 if (!obj_is_of_type (obj, t)) {
6409 DEBUG_PRINTF (1, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6410 return ERR_INVALID_ARGUMENT;
6413 if (obj && obj->vtable->domain != domain)
6414 return ERR_INVALID_ARGUMENT;
6416 mono_gc_wbarrier_generic_store (addr, obj);
6417 } else if (type == VALUE_TYPE_ID_NULL) {
6418 *(MonoObject**)addr = NULL;
6419 } else if (type == MONO_TYPE_VALUETYPE) {
6428 /* This can happen when round-tripping boxed vtypes */
6430 * Obtain vtype class.
6431 * Same as the beginning of the handle_vtype case above.
6434 is_enum = decode_byte (buf, &buf, limit);
6436 return ERR_NOT_IMPLEMENTED;
6437 klass = decode_typeid (buf, &buf, limit, &d, &err);
6438 if (err != ERR_NONE)
6441 /* Decode the vtype into a temporary buffer, then box it. */
6442 vtype_buf_size = mono_class_value_size (klass, NULL);
6443 vtype_buf = (guint8 *)g_malloc0 (vtype_buf_size);
6444 g_assert (vtype_buf);
6447 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
6448 if (err != ERR_NONE) {
6452 *(MonoObject**)addr = mono_value_box_checked (d, klass, vtype_buf, &error);
6453 mono_error_cleanup (&error);
6456 char *name = mono_type_full_name (t);
6457 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
6459 return ERR_INVALID_ARGUMENT;
6473 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6477 int type = decode_byte (buf, &buf, limit);
6479 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
6480 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
6481 guint8 *nullable_buf;
6484 * First try decoding it as a Nullable`1
6486 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6487 if (err == ERR_NONE)
6491 * Then try decoding as a primitive value or null.
6493 if (targ->type == type) {
6494 nullable_buf = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
6495 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
6496 if (err != ERR_NONE) {
6497 g_free (nullable_buf);
6500 MonoObject *boxed = mono_value_box_checked (domain, mono_class_from_mono_type (targ), nullable_buf, &error);
6501 if (!is_ok (&error)) {
6502 mono_error_cleanup (&error);
6503 return ERR_INVALID_OBJECT;
6505 mono_nullable_init (addr, boxed, mono_class_from_mono_type (t));
6506 g_free (nullable_buf);
6509 } else if (type == VALUE_TYPE_ID_NULL) {
6510 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
6516 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6520 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
6524 guint8 *addr, *gaddr;
6527 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6528 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6531 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
6532 reg_val = mono_arch_context_get_int_reg (ctx, reg);
6534 buffer_add_value_full (buf, t, ®_val, domain, as_vtype, NULL);
6536 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6537 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6538 addr += (gint32)var->offset;
6540 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6542 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6544 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6547 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6548 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
6549 /* Same as regoffset, but with an indirection */
6550 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6551 addr += (gint32)var->offset;
6553 gaddr = (guint8 *)*(gpointer*)addr;
6555 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL);
6557 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
6558 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
6559 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
6560 MonoGSharedVtMethodRuntimeInfo *info;
6566 g_assert (info_var);
6567 g_assert (locals_var);
6569 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6570 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6571 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6572 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6573 addr += (gint32)info_var->offset;
6574 info = (MonoGSharedVtMethodRuntimeInfo *)*(gpointer*)addr;
6575 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6576 info = (MonoGSharedVtMethodRuntimeInfo *)mono_arch_context_get_int_reg (ctx, reg);
6578 g_assert_not_reached ();
6582 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6583 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6584 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6585 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6586 addr += (gint32)locals_var->offset;
6587 locals = (guint8 *)*(gpointer*)addr;
6588 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6589 locals = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6591 g_assert_not_reached ();
6595 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6597 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6602 g_assert_not_reached ();
6607 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
6611 guint8 *addr, *gaddr;
6613 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6614 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6616 if (MONO_TYPE_IS_REFERENCE (t))
6617 size = sizeof (gpointer);
6619 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6622 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6623 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6625 gboolean is_signed = FALSE;
6628 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6631 // FIXME: Write barriers
6632 mono_gc_memmove_atomic (addr, val, size);
6637 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6642 v = is_signed ? *(gint8*)val : *(guint8*)val;
6645 v = is_signed ? *(gint16*)val : *(guint16*)val;
6648 v = is_signed ? *(gint32*)val : *(guint32*)val;
6651 v = is_signed ? *(gint64*)val : *(guint64*)val;
6654 g_assert_not_reached ();
6657 /* Set value on the stack or in the return ctx */
6658 if (reg_locations [reg]) {
6659 /* Saved on the stack */
6660 DEBUG_PRINTF (1, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v);
6661 *(reg_locations [reg]) = v;
6664 DEBUG_PRINTF (1, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v);
6665 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6668 // FIXME: Move these to mono-context.h/c.
6669 mono_arch_context_set_int_reg (ctx, reg, v);
6671 // FIXME: Can't set registers, so we disable linears
6676 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6677 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6678 addr += (gint32)var->offset;
6680 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6683 addr = *(guint8**)addr;
6689 // FIXME: Write barriers
6690 mono_gc_memmove_atomic (addr, val, size);
6692 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6693 /* Same as regoffset, but with an indirection */
6694 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6695 addr += (gint32)var->offset;
6697 gaddr = (guint8 *)*(gpointer*)addr;
6699 // FIXME: Write barriers
6700 mono_gc_memmove_atomic (gaddr, val, size);
6702 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6706 g_assert_not_reached ();
6711 clear_event_request (int req_id, int etype)
6715 mono_loader_lock ();
6716 for (i = 0; i < event_requests->len; ++i) {
6717 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6719 if (req->id == req_id && req->event_kind == etype) {
6720 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6721 clear_breakpoint ((MonoBreakpoint *)req->info);
6722 if (req->event_kind == EVENT_KIND_STEP)
6723 ss_destroy ((SingleStepReq *)req->info);
6724 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6725 clear_breakpoint ((MonoBreakpoint *)req->info);
6726 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6727 clear_breakpoint ((MonoBreakpoint *)req->info);
6728 g_ptr_array_remove_index_fast (event_requests, i);
6733 mono_loader_unlock ();
6737 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
6741 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6742 m->kind = MOD_KIND_NONE;
6743 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6744 int count = 0, match_count = 0, pos;
6745 MonoAssembly **newassemblies;
6747 for (i = 0; m->data.assemblies [i]; ++i) {
6749 if (m->data.assemblies [i] == assembly)
6754 // +1 because we don't know length and we use last element to check for end
6755 newassemblies = g_new0 (MonoAssembly*, count - match_count + 1);
6758 for (i = 0; i < count; ++i)
6759 if (m->data.assemblies [i] != assembly)
6760 newassemblies [pos ++] = m->data.assemblies [i];
6761 g_assert (pos == count - match_count);
6762 g_free (m->data.assemblies);
6763 m->data.assemblies = newassemblies;
6769 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
6773 for (i = 0; i < req->nmodifiers; ++i) {
6774 Modifier *m = &req->modifiers [i];
6776 clear_assembly_from_modifier (req, m, assembly);
6781 * clear_event_requests_for_assembly:
6783 * Clear all events requests which reference ASSEMBLY.
6786 clear_event_requests_for_assembly (MonoAssembly *assembly)
6791 mono_loader_lock ();
6795 for (i = 0; i < event_requests->len; ++i) {
6796 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6798 clear_assembly_from_modifiers (req, assembly);
6800 if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly ((MonoBreakpoint *)req->info, assembly)) {
6801 clear_event_request (req->id, req->event_kind);
6806 if (req->event_kind == EVENT_KIND_STEP)
6807 ss_clear_for_assembly ((SingleStepReq *)req->info, assembly);
6810 mono_loader_unlock ();
6814 * type_comes_from_assembly:
6816 * GHRFunc that returns TRUE if klass comes from assembly
6819 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6821 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6825 * clear_types_for_assembly:
6827 * Clears types from loaded_classes for a given assembly
6830 clear_types_for_assembly (MonoAssembly *assembly)
6832 MonoDomain *domain = mono_domain_get ();
6833 AgentDomainInfo *info = NULL;
6835 if (!domain || !domain_jit_info (domain))
6836 /* Can happen during shutdown */
6839 info = get_agent_domain_info (domain);
6841 mono_loader_lock ();
6842 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6843 mono_loader_unlock ();
6847 add_thread (gpointer key, gpointer value, gpointer user_data)
6849 MonoInternalThread *thread = (MonoInternalThread *)value;
6850 Buffer *buf = (Buffer *)user_data;
6852 buffer_add_objid (buf, (MonoObject*)thread);
6856 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6859 guint8 *end = invoke->endp;
6863 MonoMethodSignature *sig;
6866 MonoObject *this_arg, *res, *exc;
6869 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6872 MonoStopwatch watch;
6874 if (invoke->method) {
6876 * Invoke this method directly, currently only Environment.Exit () is supported.
6879 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>");
6881 mono_runtime_try_invoke (invoke->method, NULL, invoke->args, &exc, &error);
6882 mono_error_assert_ok (&error);
6884 g_assert_not_reached ();
6887 m = decode_methodid (p, &p, end, &domain, &err);
6888 if (err != ERR_NONE)
6890 sig = mono_method_signature (m);
6892 if (m->klass->valuetype)
6893 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6895 this_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
6896 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6897 /* Should be null */
6898 int type = decode_byte (p, &p, end);
6899 if (type != VALUE_TYPE_ID_NULL) {
6900 DEBUG_PRINTF (1, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6901 return ERR_INVALID_ARGUMENT;
6903 memset (this_buf, 0, mono_class_instance_size (m->klass));
6904 } else if (m->klass->valuetype && !strcmp (m->name, ".ctor")) {
6908 int type = decode_byte (p, &tmp_p, end);
6909 if (type == VALUE_TYPE_ID_NULL) {
6910 memset (this_buf, 0, mono_class_instance_size (m->klass));
6913 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6914 if (err != ERR_NONE)
6918 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6919 if (err != ERR_NONE)
6923 if (!m->klass->valuetype)
6924 this_arg = *(MonoObject**)this_buf;
6928 if (MONO_CLASS_IS_INTERFACE (m->klass)) {
6930 DEBUG_PRINTF (1, "[%p] Error: Interface method invoked without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6931 return ERR_INVALID_ARGUMENT;
6933 m = mono_object_get_virtual_method (this_arg, m);
6934 /* Transform this to the format the rest of the code expects it to be */
6935 if (m->klass->valuetype) {
6936 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6937 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
6939 } else if ((m->flags & METHOD_ATTRIBUTE_VIRTUAL) && !m->klass->valuetype && invoke->flags & INVOKE_FLAG_VIRTUAL) {
6941 DEBUG_PRINTF (1, "[%p] Error: invoke with INVOKE_FLAG_VIRTUAL flag set without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6942 return ERR_INVALID_ARGUMENT;
6944 m = mono_object_get_virtual_method (this_arg, m);
6945 if (m->klass->valuetype) {
6946 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6947 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
6951 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>");
6953 if (this_arg && this_arg->vtable->domain != domain)
6956 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this_arg) {
6957 if (!strcmp (m->name, ".ctor")) {
6958 if (mono_class_is_abstract (m->klass))
6959 return ERR_INVALID_ARGUMENT;
6962 this_arg = mono_object_new_checked (domain, m->klass, &error);
6963 mono_error_assert_ok (&error);
6966 return ERR_INVALID_ARGUMENT;
6970 if (this_arg && !obj_is_of_type (this_arg, &m->klass->byval_arg))
6971 return ERR_INVALID_ARGUMENT;
6973 nargs = decode_int (p, &p, end);
6974 if (nargs != sig->param_count)
6975 return ERR_INVALID_ARGUMENT;
6976 /* Use alloca to get gc tracking */
6977 arg_buf = (guint8 **)g_alloca (nargs * sizeof (gpointer));
6978 memset (arg_buf, 0, nargs * sizeof (gpointer));
6979 args = (gpointer *)g_alloca (nargs * sizeof (gpointer));
6980 for (i = 0; i < nargs; ++i) {
6981 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6982 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6983 if (err != ERR_NONE)
6985 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6988 if (sig->params [i]->byref) {
6989 arg_buf [i] = (guint8 *)g_alloca (sizeof (mgreg_t));
6990 *(gpointer*)arg_buf [i] = args [i];
6991 args [i] = arg_buf [i];
6994 arg_buf [i] = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6995 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6996 if (err != ERR_NONE)
6998 args [i] = arg_buf [i];
7005 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
7006 tls->disable_breakpoints = TRUE;
7008 tls->disable_breakpoints = FALSE;
7011 * Add an LMF frame to link the stack frames on the invoke method with our caller.
7013 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
7014 if (invoke->has_ctx) {
7017 lmf_addr = mono_get_lmf_addr ();
7020 memset (&ext, 0, sizeof (ext));
7021 mono_arch_init_lmf_ext (&ext, *lmf_addr);
7023 ext.debugger_invoke = TRUE;
7024 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
7026 mono_set_lmf ((MonoLMF*)&ext);
7030 mono_stopwatch_start (&watch);
7031 res = mono_runtime_try_invoke (m, m->klass->valuetype ? (gpointer) this_buf : (gpointer) this_arg, args, &exc, &error);
7032 if (exc == NULL && !mono_error_ok (&error)) {
7033 exc = (MonoObject*) mono_error_convert_to_exception (&error);
7035 mono_error_cleanup (&error); /* FIXME report error */
7037 mono_stopwatch_stop (&watch);
7038 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));
7040 buffer_add_byte (buf, 0);
7041 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
7043 gboolean out_this = FALSE;
7044 gboolean out_args = FALSE;
7046 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_THIS) && CHECK_PROTOCOL_VERSION (2, 35))
7048 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_ARGS) && CHECK_PROTOCOL_VERSION (2, 35))
7050 buffer_add_byte (buf, 1 + (out_this ? 2 : 0) + (out_args ? 4 : 0));
7051 if (sig->ret->type == MONO_TYPE_VOID) {
7052 if (!strcmp (m->name, ".ctor")) {
7053 if (!m->klass->valuetype)
7054 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this_arg, domain);
7056 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
7058 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
7060 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
7061 buffer_add_value (buf, sig->ret, &res, domain);
7062 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
7063 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
7064 MonoClass *k = mono_class_from_mono_type (sig->ret);
7065 guint8 *nullable_buf = (guint8 *)g_alloca (mono_class_value_size (k, NULL));
7067 g_assert (nullable_buf);
7068 mono_nullable_init (nullable_buf, res, k);
7069 buffer_add_value (buf, sig->ret, nullable_buf, domain);
7072 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
7078 /* Return the new value of the receiver after the call */
7079 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
7081 buffer_add_int (buf, nargs);
7082 for (i = 0; i < nargs; ++i) {
7083 if (MONO_TYPE_IS_REFERENCE (sig->params [i]))
7084 buffer_add_value (buf, sig->params [i], &args [i], domain);
7085 else if (sig->params [i]->byref)
7086 /* add_value () does an indirection */
7087 buffer_add_value (buf, sig->params [i], &arg_buf [i], domain);
7089 buffer_add_value (buf, sig->params [i], arg_buf [i], domain);
7094 tls->disable_breakpoints = FALSE;
7096 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
7097 if (invoke->has_ctx)
7098 mono_set_lmf ((MonoLMF *)(((gssize)ext.lmf.previous_lmf) & ~3));
7102 // FIXME: byref arguments
7110 * Invoke the method given by tls->pending_invoke in the current thread.
7113 invoke_method (void)
7115 DebuggerTlsData *tls;
7121 MonoContext restore_ctx;
7124 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
7128 * Store the `InvokeData *' in `tls->invoke' until we're done with
7129 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
7132 mono_loader_lock ();
7134 invoke = tls->pending_invoke;
7136 tls->pending_invoke = NULL;
7138 invoke->last_invoke = tls->invoke;
7139 tls->invoke = invoke;
7141 mono_loader_unlock ();
7143 tls->frames_up_to_date = FALSE;
7149 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
7150 buffer_init (&buf, 128);
7153 /* Fail the other invokes as well */
7155 err = do_invoke_method (tls, &buf, invoke, p, &p);
7158 if (tls->abort_requested) {
7159 if (CHECK_PROTOCOL_VERSION (2, 42))
7160 err = ERR_INVOKE_ABORTED;
7163 /* Start suspending before sending the reply */
7164 if (mindex == invoke->nmethods - 1) {
7165 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
7166 for (i = 0; i < invoke->suspend_count; ++i)
7171 send_reply_packet (id, err, &buf);
7176 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
7178 if (invoke->has_ctx)
7179 save_thread_context (&restore_ctx);
7181 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
7182 g_assert (tls->resume_count);
7183 tls->resume_count -= invoke->suspend_count;
7186 DEBUG_PRINTF (1, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer) (gsize) mono_native_thread_id_get (), err, tls->resume_count);
7189 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
7191 * It is possible that mono_thread_internal_abort () was called
7192 * after the mono_runtime_invoke_checked() already returned, but it doesn't matter
7193 * because we reset the abort here.
7196 mono_loader_lock ();
7198 if (tls->abort_requested)
7199 mono_thread_internal_reset_abort (tls->thread);
7201 tls->invoke = tls->invoke->last_invoke;
7202 tls->abort_requested = FALSE;
7204 mono_loader_unlock ();
7213 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
7215 MonoThread *thread = (MonoThread *)value;
7216 DebuggerTlsData *tls;
7219 mono_loader_lock ();
7220 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
7222 res = tls->really_suspended;
7223 mono_loader_unlock ();
7229 get_source_files_for_type (MonoClass *klass)
7231 gpointer iter = NULL;
7233 MonoDebugSourceInfo *sinfo;
7237 files = g_ptr_array_new ();
7239 while ((method = mono_class_get_methods (klass, &iter))) {
7240 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
7241 GPtrArray *source_file_list;
7244 mono_debug_get_seq_points (minfo, NULL, &source_file_list, NULL, NULL, NULL);
7245 for (j = 0; j < source_file_list->len; ++j) {
7246 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, j);
7247 for (i = 0; i < files->len; ++i)
7248 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
7250 if (i == files->len)
7251 g_ptr_array_add (files, g_strdup (sinfo->source_file));
7253 g_ptr_array_free (source_file_list, TRUE);
7261 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
7264 case CMD_VM_VERSION: {
7265 char *build_info, *version;
7267 build_info = mono_get_runtime_build_info ();
7268 version = g_strdup_printf ("mono %s", build_info);
7270 buffer_add_string (buf, version); /* vm version */
7271 buffer_add_int (buf, MAJOR_VERSION);
7272 buffer_add_int (buf, MINOR_VERSION);
7273 g_free (build_info);
7277 case CMD_VM_SET_PROTOCOL_VERSION: {
7278 major_version = decode_int (p, &p, end);
7279 minor_version = decode_int (p, &p, end);
7280 protocol_version_set = TRUE;
7281 DEBUG_PRINTF (1, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version);
7284 case CMD_VM_ALL_THREADS: {
7286 mono_loader_lock ();
7287 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
7288 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
7289 mono_loader_unlock ();
7292 case CMD_VM_SUSPEND:
7294 wait_for_suspend ();
7297 if (suspend_count == 0)
7298 return ERR_NOT_SUSPENDED;
7300 clear_suspended_objs ();
7302 case CMD_VM_DISPOSE:
7303 /* Clear all event requests */
7304 mono_loader_lock ();
7305 while (event_requests->len > 0) {
7306 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
7308 clear_event_request (req->id, req->event_kind);
7310 mono_loader_unlock ();
7312 while (suspend_count > 0)
7314 disconnected = TRUE;
7315 vm_start_event_sent = FALSE;
7318 MonoInternalThread *thread;
7319 DebuggerTlsData *tls;
7320 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7321 MonoClass *env_class;
7323 MonoMethod *exit_method = NULL;
7327 exit_code = decode_int (p, &p, end);
7329 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
7331 /* Have to send a reply before exiting */
7332 send_reply_packet (id, 0, buf);
7334 /* Clear all event requests */
7335 mono_loader_lock ();
7336 while (event_requests->len > 0) {
7337 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
7339 clear_event_request (req->id, req->event_kind);
7341 mono_loader_unlock ();
7344 * The JDWP documentation says that the shutdown is not orderly. It doesn't
7345 * specify whenever a VM_DEATH event is sent. We currently do an orderly
7346 * shutdown by hijacking a thread to execute Environment.Exit (). This is
7347 * better than doing the shutdown ourselves, since it avoids various races.
7351 wait_for_suspend ();
7353 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7354 env_class = mono_class_try_load_from_name (mono_defaults.corlib, "System", "Environment");
7356 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
7359 mono_loader_lock ();
7360 thread = (MonoInternalThread *)mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
7361 mono_loader_unlock ();
7363 if (thread && exit_method) {
7364 mono_loader_lock ();
7365 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
7366 mono_loader_unlock ();
7368 args = g_new0 (gpointer, 1);
7369 args [0] = g_malloc (sizeof (int));
7370 *(int*)(args [0]) = exit_code;
7372 tls->pending_invoke = g_new0 (InvokeData, 1);
7373 tls->pending_invoke->method = exit_method;
7374 tls->pending_invoke->args = args;
7375 tls->pending_invoke->nmethods = 1;
7377 while (suspend_count > 0)
7381 * No thread found, do it ourselves.
7382 * FIXME: This can race with normal shutdown etc.
7384 while (suspend_count > 0)
7387 if (!mono_runtime_try_shutdown ())
7390 mono_environment_exitcode_set (exit_code);
7392 /* Suspend all managed threads since the runtime is going away */
7393 DEBUG_PRINTF (1, "Suspending all threads...\n");
7394 mono_thread_suspend_all_other_threads ();
7395 DEBUG_PRINTF (1, "Shutting down the runtime...\n");
7396 mono_runtime_quit ();
7397 transport_close2 ();
7398 DEBUG_PRINTF (1, "Exiting...\n");
7404 case CMD_VM_INVOKE_METHOD:
7405 case CMD_VM_INVOKE_METHODS: {
7406 int objid = decode_objid (p, &p, end);
7408 DebuggerTlsData *tls;
7409 int i, count, flags, nmethods;
7412 err = get_object (objid, (MonoObject**)&thread);
7413 if (err != ERR_NONE)
7416 flags = decode_int (p, &p, end);
7418 if (command == CMD_VM_INVOKE_METHODS)
7419 nmethods = decode_int (p, &p, end);
7423 // Wait for suspending if it already started
7425 wait_for_suspend ();
7426 if (!is_suspended ())
7427 return ERR_NOT_SUSPENDED;
7429 mono_loader_lock ();
7430 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7431 mono_loader_unlock ();
7434 if (!tls->really_suspended)
7435 /* The thread is still running native code, can't do invokes */
7436 return ERR_NOT_SUSPENDED;
7439 * Store the invoke data into tls, the thread will execute it after it is
7442 if (tls->pending_invoke)
7443 return ERR_NOT_SUSPENDED;
7444 tls->pending_invoke = g_new0 (InvokeData, 1);
7445 tls->pending_invoke->id = id;
7446 tls->pending_invoke->flags = flags;
7447 tls->pending_invoke->p = (guint8 *)g_malloc (end - p);
7448 memcpy (tls->pending_invoke->p, p, end - p);
7449 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
7450 tls->pending_invoke->suspend_count = suspend_count;
7451 tls->pending_invoke->nmethods = nmethods;
7453 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
7454 resume_thread (THREAD_TO_INTERNAL (thread));
7457 count = suspend_count;
7458 for (i = 0; i < count; ++i)
7463 case CMD_VM_ABORT_INVOKE: {
7464 int objid = decode_objid (p, &p, end);
7466 DebuggerTlsData *tls;
7470 err = get_object (objid, (MonoObject**)&thread);
7471 if (err != ERR_NONE)
7474 invoke_id = decode_int (p, &p, end);
7476 mono_loader_lock ();
7477 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7480 if (tls->abort_requested) {
7481 DEBUG_PRINTF (1, "Abort already requested.\n");
7482 mono_loader_unlock ();
7487 * Check whether we're still inside the mono_runtime_invoke_checked() and that it's
7488 * actually the correct invocation.
7490 * Careful, we do not stop the thread that's doing the invocation, so we can't
7491 * inspect its stack. However, invoke_method() also acquires the loader lock
7492 * when it's done, so we're safe here.
7496 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
7497 mono_loader_unlock ();
7498 return ERR_NO_INVOCATION;
7501 tls->abort_requested = TRUE;
7503 mono_thread_internal_abort (THREAD_TO_INTERNAL (thread));
7504 mono_loader_unlock ();
7508 case CMD_VM_SET_KEEPALIVE: {
7509 int timeout = decode_int (p, &p, end);
7510 agent_config.keepalive = timeout;
7512 #ifndef DISABLE_SOCKET_TRANSPORT
7519 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
7520 GHashTableIter iter, kiter;
7525 char *fname, *basename;
7526 gboolean ignore_case;
7527 GSList *class_list, *l;
7528 GPtrArray *res_classes, *res_domains;
7530 fname = decode_string (p, &p, end);
7531 ignore_case = decode_byte (p, &p, end);
7533 basename = dbg_path_get_basename (fname);
7535 res_classes = g_ptr_array_new ();
7536 res_domains = g_ptr_array_new ();
7538 mono_loader_lock ();
7539 g_hash_table_iter_init (&iter, domains);
7540 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7541 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
7543 /* Update 'source_file_to_class' cache */
7544 g_hash_table_iter_init (&kiter, info->loaded_classes);
7545 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
7546 if (!g_hash_table_lookup (info->source_files, klass)) {
7547 files = get_source_files_for_type (klass);
7548 g_hash_table_insert (info->source_files, klass, files);
7550 for (i = 0; i < files->len; ++i) {
7551 char *s = (char *)g_ptr_array_index (files, i);
7552 char *s2 = dbg_path_get_basename (s);
7555 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, s2);
7557 class_list = g_slist_prepend (class_list, klass);
7558 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
7560 class_list = g_slist_prepend (class_list, klass);
7561 g_hash_table_insert (info->source_file_to_class, s2, class_list);
7564 /* The _ignorecase hash contains the lowercase path */
7565 s3 = strdup_tolower (s2);
7566 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
7568 class_list = g_slist_prepend (class_list, klass);
7569 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
7571 class_list = g_slist_prepend (class_list, klass);
7572 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
7584 s = strdup_tolower (basename);
7585 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
7588 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, basename);
7591 for (l = class_list; l; l = l->next) {
7592 klass = (MonoClass *)l->data;
7594 g_ptr_array_add (res_classes, klass);
7595 g_ptr_array_add (res_domains, domain);
7598 mono_loader_unlock ();
7603 buffer_add_int (buf, res_classes->len);
7604 for (i = 0; i < res_classes->len; ++i)
7605 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7606 g_ptr_array_free (res_classes, TRUE);
7607 g_ptr_array_free (res_domains, TRUE);
7610 case CMD_VM_GET_TYPES: {
7611 GHashTableIter iter;
7615 gboolean ignore_case;
7616 GPtrArray *res_classes, *res_domains;
7617 MonoTypeNameParse info;
7619 name = decode_string (p, &p, end);
7620 ignore_case = decode_byte (p, &p, end);
7622 if (!mono_reflection_parse_type (name, &info)) {
7624 mono_reflection_free_type_info (&info);
7625 return ERR_INVALID_ARGUMENT;
7628 res_classes = g_ptr_array_new ();
7629 res_domains = g_ptr_array_new ();
7631 mono_loader_lock ();
7632 g_hash_table_iter_init (&iter, domains);
7633 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7635 gboolean type_resolve;
7639 mono_domain_assemblies_lock (domain);
7640 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7641 ass = (MonoAssembly *)tmp->data;
7645 type_resolve = TRUE;
7646 /* FIXME really okay to call while holding locks? */
7647 t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignore_case, &type_resolve, &error);
7648 mono_error_cleanup (&error);
7650 g_ptr_array_add (res_classes, mono_type_get_class (t));
7651 g_ptr_array_add (res_domains, domain);
7655 mono_domain_assemblies_unlock (domain);
7657 mono_loader_unlock ();
7660 mono_reflection_free_type_info (&info);
7662 buffer_add_int (buf, res_classes->len);
7663 for (i = 0; i < res_classes->len; ++i)
7664 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7665 g_ptr_array_free (res_classes, TRUE);
7666 g_ptr_array_free (res_domains, TRUE);
7669 case CMD_VM_START_BUFFERING:
7670 case CMD_VM_STOP_BUFFERING:
7671 /* Handled in the main loop */
7674 return ERR_NOT_IMPLEMENTED;
7681 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7687 case CMD_EVENT_REQUEST_SET: {
7689 int i, event_kind, suspend_policy, nmodifiers;
7693 MonoThread *step_thread;
7694 int step_thread_id = 0;
7695 StepDepth depth = STEP_DEPTH_INTO;
7696 StepSize size = STEP_SIZE_MIN;
7697 StepFilter filter = STEP_FILTER_NONE;
7701 event_kind = decode_byte (p, &p, end);
7702 suspend_policy = decode_byte (p, &p, end);
7703 nmodifiers = decode_byte (p, &p, end);
7705 req = (EventRequest *)g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7706 req->id = InterlockedIncrement (&event_request_id);
7707 req->event_kind = event_kind;
7708 req->suspend_policy = suspend_policy;
7709 req->nmodifiers = nmodifiers;
7712 for (i = 0; i < nmodifiers; ++i) {
7713 mod = (ModifierKind)decode_byte (p, &p, end);
7715 req->modifiers [i].kind = mod;
7716 if (mod == MOD_KIND_COUNT) {
7717 req->modifiers [i].data.count = decode_int (p, &p, end);
7718 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7719 method = decode_methodid (p, &p, end, &domain, &err);
7720 if (err != ERR_NONE)
7722 location = decode_long (p, &p, end);
7723 } else if (mod == MOD_KIND_STEP) {
7724 step_thread_id = decode_id (p, &p, end);
7725 size = (StepSize)decode_int (p, &p, end);
7726 depth = (StepDepth)decode_int (p, &p, end);
7727 if (CHECK_PROTOCOL_VERSION (2, 16))
7728 filter = (StepFilter)decode_int (p, &p, end);
7729 req->modifiers [i].data.filter = filter;
7730 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7731 /* Treat STEP_THOUGH the same as HIDDEN */
7732 req->modifiers [i].data.filter = (StepFilter)(req->modifiers [i].data.filter | STEP_FILTER_DEBUGGER_STEP_THROUGH);
7733 } else if (mod == MOD_KIND_THREAD_ONLY) {
7734 int id = decode_id (p, &p, end);
7736 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7737 if (err != ERR_NONE) {
7741 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7742 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7744 if (err != ERR_NONE)
7746 req->modifiers [i].caught = decode_byte (p, &p, end);
7747 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7748 if (CHECK_PROTOCOL_VERSION (2, 25))
7749 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7751 req->modifiers [i].subclasses = TRUE;
7752 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" : "");
7754 req->modifiers [i].data.exc_class = exc_class;
7756 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
7758 return ERR_INVALID_ARGUMENT;
7761 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7762 int n = decode_int (p, &p, end);
7765 // +1 because we don't know length and we use last element to check for end
7766 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n + 1);
7767 for (j = 0; j < n; ++j) {
7768 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7769 if (err != ERR_NONE) {
7770 g_free (req->modifiers [i].data.assemblies);
7774 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7775 int n = decode_int (p, &p, end);
7778 modifier = &req->modifiers [i];
7779 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7780 for (j = 0; j < n; ++j) {
7781 char *s = decode_string (p, &p, end);
7785 s2 = strdup_tolower (s);
7786 g_hash_table_insert (modifier->data.source_files, s2, s2);
7790 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7791 int n = decode_int (p, &p, end);
7794 modifier = &req->modifiers [i];
7795 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7796 for (j = 0; j < n; ++j) {
7797 char *s = decode_string (p, &p, end);
7800 g_hash_table_insert (modifier->data.type_names, s, s);
7804 return ERR_NOT_IMPLEMENTED;
7808 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7811 req->info = set_breakpoint (method, location, req, &error);
7812 if (!mono_error_ok (&error)) {
7814 DEBUG_PRINTF (1, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error));
7815 mono_error_cleanup (&error);
7816 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7818 } else if (req->event_kind == EVENT_KIND_STEP) {
7819 g_assert (step_thread_id);
7821 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7822 if (err != ERR_NONE) {
7827 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, filter, req);
7828 if (err != ERR_NONE) {
7832 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7833 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7834 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7835 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7836 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7837 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7839 if (req->nmodifiers) {
7841 return ERR_NOT_IMPLEMENTED;
7845 mono_loader_lock ();
7846 g_ptr_array_add (event_requests, req);
7848 if (agent_config.defer) {
7849 /* Transmit cached data to the client on receipt of the event request */
7850 switch (req->event_kind) {
7851 case EVENT_KIND_APPDOMAIN_CREATE:
7852 /* Emit load events for currently loaded domains */
7853 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7855 case EVENT_KIND_ASSEMBLY_LOAD:
7856 /* Emit load events for currently loaded assemblies */
7857 mono_domain_foreach (send_assemblies_for_domain, NULL);
7859 case EVENT_KIND_THREAD_START:
7860 /* Emit start events for currently started threads */
7861 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7863 case EVENT_KIND_TYPE_LOAD:
7864 /* Emit type load events for currently loaded types */
7865 mono_domain_foreach (send_types_for_domain, NULL);
7871 mono_loader_unlock ();
7873 buffer_add_int (buf, req->id);
7876 case CMD_EVENT_REQUEST_CLEAR: {
7877 int etype = decode_byte (p, &p, end);
7878 int req_id = decode_int (p, &p, end);
7880 // FIXME: Make a faster mapping from req_id to request
7881 mono_loader_lock ();
7882 clear_event_request (req_id, etype);
7883 mono_loader_unlock ();
7886 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7889 mono_loader_lock ();
7891 while (i < event_requests->len) {
7892 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
7894 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7895 clear_breakpoint ((MonoBreakpoint *)req->info);
7897 g_ptr_array_remove_index_fast (event_requests, i);
7903 mono_loader_unlock ();
7907 return ERR_NOT_IMPLEMENTED;
7914 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7920 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7921 buffer_add_domainid (buf, mono_get_root_domain ());
7924 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7925 domain = decode_domainid (p, &p, end, NULL, &err);
7926 if (err != ERR_NONE)
7928 buffer_add_string (buf, domain->friendly_name);
7931 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7936 domain = decode_domainid (p, &p, end, NULL, &err);
7937 if (err != ERR_NONE)
7939 mono_loader_lock ();
7941 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7944 buffer_add_int (buf, count);
7945 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7946 ass = (MonoAssembly *)tmp->data;
7947 buffer_add_assemblyid (buf, domain, ass);
7949 mono_loader_unlock ();
7952 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7953 domain = decode_domainid (p, &p, end, NULL, &err);
7954 if (err != ERR_NONE)
7957 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7960 case CMD_APPDOMAIN_GET_CORLIB: {
7961 domain = decode_domainid (p, &p, end, NULL, &err);
7962 if (err != ERR_NONE)
7965 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7968 case CMD_APPDOMAIN_CREATE_STRING: {
7973 domain = decode_domainid (p, &p, end, NULL, &err);
7974 if (err != ERR_NONE)
7976 s = decode_string (p, &p, end);
7978 o = mono_string_new_checked (domain, s, &error);
7979 if (!is_ok (&error)) {
7980 DEBUG_PRINTF (1, "[dbg] Failed to allocate String object '%s': %s\n", s, mono_error_get_message (&error));
7981 mono_error_cleanup (&error);
7982 return ERR_INVALID_OBJECT;
7984 buffer_add_objid (buf, (MonoObject*)o);
7987 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7990 MonoDomain *domain2;
7993 domain = decode_domainid (p, &p, end, NULL, &err);
7994 if (err != ERR_NONE)
7996 klass = decode_typeid (p, &p, end, &domain2, &err);
7997 if (err != ERR_NONE)
8001 g_assert (domain == domain2);
8003 o = mono_object_new_checked (domain, klass, &error);
8004 mono_error_assert_ok (&error);
8006 err = decode_value (&klass->byval_arg, domain, (guint8 *)mono_object_unbox (o), p, &p, end);
8007 if (err != ERR_NONE)
8010 buffer_add_objid (buf, o);
8014 return ERR_NOT_IMPLEMENTED;
8021 get_assembly_object_command (MonoDomain *domain, MonoAssembly *ass, Buffer *buf, MonoError *error)
8023 HANDLE_FUNCTION_ENTER();
8024 ErrorCode err = ERR_NONE;
8026 MonoReflectionAssemblyHandle o = mono_assembly_get_object_handle (domain, ass, error);
8027 if (MONO_HANDLE_IS_NULL (o)) {
8028 err = ERR_INVALID_OBJECT;
8031 buffer_add_objid (buf, MONO_HANDLE_RAW (MONO_HANDLE_CAST (MonoObject, o)));
8033 HANDLE_FUNCTION_RETURN_VAL (err);
8038 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8044 ass = decode_assemblyid (p, &p, end, &domain, &err);
8045 if (err != ERR_NONE)
8049 case CMD_ASSEMBLY_GET_LOCATION: {
8050 buffer_add_string (buf, mono_image_get_filename (ass->image));
8053 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
8057 if (ass->image->dynamic) {
8058 buffer_add_id (buf, 0);
8060 token = mono_image_get_entry_point (ass->image);
8062 buffer_add_id (buf, 0);
8065 m = mono_get_method_checked (ass->image, token, NULL, NULL, &error);
8067 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8068 buffer_add_methodid (buf, domain, m);
8073 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
8074 buffer_add_moduleid (buf, domain, ass->image);
8077 case CMD_ASSEMBLY_GET_OBJECT: {
8079 err = get_assembly_object_command (domain, ass, buf, &error);
8080 mono_error_cleanup (&error);
8083 case CMD_ASSEMBLY_GET_DOMAIN: {
8084 buffer_add_domainid (buf, domain);
8087 case CMD_ASSEMBLY_GET_TYPE: {
8089 char *s = decode_string (p, &p, end);
8090 gboolean ignorecase = decode_byte (p, &p, end);
8091 MonoTypeNameParse info;
8093 gboolean type_resolve, res;
8094 MonoDomain *d = mono_domain_get ();
8096 /* This is needed to be able to find referenced assemblies */
8097 res = mono_domain_set (domain, FALSE);
8100 if (!mono_reflection_parse_type (s, &info)) {
8103 if (info.assembly.name)
8105 t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignorecase, &type_resolve, &error);
8106 if (!is_ok (&error)) {
8107 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8108 mono_reflection_free_type_info (&info);
8110 return ERR_INVALID_ARGUMENT;
8113 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
8114 mono_reflection_free_type_info (&info);
8117 mono_domain_set (d, TRUE);
8121 case CMD_ASSEMBLY_GET_NAME: {
8123 MonoAssembly *mass = ass;
8125 name = g_strdup_printf (
8126 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
8128 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
8129 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
8130 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
8131 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
8133 buffer_add_string (buf, name);
8138 return ERR_NOT_IMPLEMENTED;
8145 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8151 case CMD_MODULE_GET_INFO: {
8152 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
8155 basename = g_path_get_basename (image->name);
8156 buffer_add_string (buf, basename); // name
8157 buffer_add_string (buf, image->module_name); // scopename
8158 buffer_add_string (buf, image->name); // fqname
8159 buffer_add_string (buf, mono_image_get_guid (image)); // guid
8160 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
8165 return ERR_NOT_IMPLEMENTED;
8172 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8178 case CMD_FIELD_GET_INFO: {
8179 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
8181 buffer_add_string (buf, f->name);
8182 buffer_add_typeid (buf, domain, f->parent);
8183 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
8184 buffer_add_int (buf, f->type->attrs);
8188 return ERR_NOT_IMPLEMENTED;
8195 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
8197 if (val && val->vtable->klass == mono_defaults.runtimetype_class) {
8198 /* Special case these so the client doesn't have to handle Type objects */
8200 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
8201 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
8202 } else if (MONO_TYPE_IS_REFERENCE (t))
8203 buffer_add_value (buf, t, &val, domain);
8205 buffer_add_value (buf, t, mono_object_unbox (val), domain);
8209 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
8215 buffer_add_int (buf, 0);
8219 for (i = 0; i < cinfo->num_attrs; ++i) {
8220 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
8223 buffer_add_int (buf, nattrs);
8225 for (i = 0; i < cinfo->num_attrs; ++i) {
8226 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
8227 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
8228 MonoArray *typed_args, *named_args;
8230 CattrNamedArg *arginfo = NULL;
8233 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
8234 if (!mono_error_ok (&error)) {
8235 DEBUG_PRINTF (2, "[dbg] mono_reflection_create_custom_attr_data_args () failed with: '%s'\n", mono_error_get_message (&error));
8236 mono_error_cleanup (&error);
8237 return ERR_LOADER_ERROR;
8240 buffer_add_methodid (buf, domain, attr->ctor);
8244 buffer_add_int (buf, mono_array_length (typed_args));
8245 for (j = 0; j < mono_array_length (typed_args); ++j) {
8246 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
8248 t = mono_method_signature (attr->ctor)->params [j];
8250 buffer_add_cattr_arg (buf, t, domain, val);
8253 buffer_add_int (buf, 0);
8258 buffer_add_int (buf, mono_array_length (named_args));
8260 for (j = 0; j < mono_array_length (named_args); ++j) {
8261 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
8263 if (arginfo [j].prop) {
8264 buffer_add_byte (buf, 0x54);
8265 buffer_add_propertyid (buf, domain, arginfo [j].prop);
8266 } else if (arginfo [j].field) {
8267 buffer_add_byte (buf, 0x53);
8268 buffer_add_fieldid (buf, domain, arginfo [j].field);
8270 g_assert_not_reached ();
8273 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
8276 buffer_add_int (buf, 0);
8285 /* FIXME: Code duplication with icall.c */
8287 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
8292 mono_class_setup_interfaces (klass, error);
8293 if (!mono_error_ok (error))
8296 for (i = 0; i < klass->interface_count; i++) {
8297 ic = klass->interfaces [i];
8298 g_hash_table_insert (ifaces, ic, ic);
8300 collect_interfaces (ic, ifaces, error);
8301 if (!mono_error_ok (error))
8307 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8319 case CMD_TYPE_GET_INFO: {
8320 buffer_add_string (buf, klass->name_space);
8321 buffer_add_string (buf, klass->name);
8323 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
8324 buffer_add_string (buf, name);
8326 buffer_add_assemblyid (buf, domain, klass->image->assembly);
8327 buffer_add_moduleid (buf, domain, klass->image);
8328 buffer_add_typeid (buf, domain, klass->parent);
8329 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
8330 buffer_add_typeid (buf, domain, klass->element_class);
8332 buffer_add_id (buf, 0);
8333 buffer_add_int (buf, klass->type_token);
8334 buffer_add_byte (buf, klass->rank);
8335 buffer_add_int (buf, mono_class_get_flags (klass));
8337 type = &klass->byval_arg;
8338 // FIXME: Can't decide whenever a class represents a byref type
8341 if (type->type == MONO_TYPE_PTR)
8343 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
8345 if (type->type == MONO_TYPE_VALUETYPE)
8347 if (klass->enumtype)
8349 if (mono_class_is_gtd (klass))
8351 if (mono_class_is_gtd (klass) || mono_class_is_ginst (klass))
8353 buffer_add_byte (buf, b);
8356 while ((nested = mono_class_get_nested_types (klass, &iter)))
8358 buffer_add_int (buf, nnested);
8360 while ((nested = mono_class_get_nested_types (klass, &iter)))
8361 buffer_add_typeid (buf, domain, nested);
8362 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8363 if (mono_class_is_gtd (klass))
8364 buffer_add_typeid (buf, domain, klass);
8365 else if (mono_class_is_ginst (klass))
8366 buffer_add_typeid (buf, domain, mono_class_get_generic_class (klass)->container_class);
8368 buffer_add_id (buf, 0);
8370 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8373 if (mono_class_is_ginst (klass)) {
8374 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
8376 count = inst->type_argc;
8377 buffer_add_int (buf, count);
8378 for (i = 0; i < count; i++)
8379 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8380 } else if (mono_class_is_gtd (klass)) {
8381 MonoGenericContainer *container = mono_class_get_generic_container (klass);
8384 count = container->type_argc;
8385 buffer_add_int (buf, count);
8386 for (i = 0; i < count; i++) {
8387 pklass = mono_class_from_generic_parameter_internal (mono_generic_container_get_param (container, i));
8388 buffer_add_typeid (buf, domain, pklass);
8391 buffer_add_int (buf, 0);
8396 case CMD_TYPE_GET_METHODS: {
8399 gpointer iter = NULL;
8402 mono_class_setup_methods (klass);
8404 nmethods = mono_class_num_methods (klass);
8406 buffer_add_int (buf, nmethods);
8408 while ((m = mono_class_get_methods (klass, &iter))) {
8409 buffer_add_methodid (buf, domain, m);
8412 g_assert (i == nmethods);
8415 case CMD_TYPE_GET_FIELDS: {
8418 gpointer iter = NULL;
8421 nfields = mono_class_num_fields (klass);
8423 buffer_add_int (buf, nfields);
8425 while ((f = mono_class_get_fields (klass, &iter))) {
8426 buffer_add_fieldid (buf, domain, f);
8427 buffer_add_string (buf, f->name);
8428 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
8429 buffer_add_int (buf, f->type->attrs);
8432 g_assert (i == nfields);
8435 case CMD_TYPE_GET_PROPERTIES: {
8438 gpointer iter = NULL;
8441 nprops = mono_class_num_properties (klass);
8443 buffer_add_int (buf, nprops);
8445 while ((p = mono_class_get_properties (klass, &iter))) {
8446 buffer_add_propertyid (buf, domain, p);
8447 buffer_add_string (buf, p->name);
8448 buffer_add_methodid (buf, domain, p->get);
8449 buffer_add_methodid (buf, domain, p->set);
8450 buffer_add_int (buf, p->attrs);
8453 g_assert (i == nprops);
8456 case CMD_TYPE_GET_CATTRS: {
8457 MonoClass *attr_klass;
8458 MonoCustomAttrInfo *cinfo;
8460 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8461 /* attr_klass can be NULL */
8462 if (err != ERR_NONE)
8465 cinfo = mono_custom_attrs_from_class_checked (klass, &error);
8466 if (!is_ok (&error)) {
8467 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8468 return ERR_LOADER_ERROR;
8471 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8472 if (err != ERR_NONE)
8476 case CMD_TYPE_GET_FIELD_CATTRS: {
8477 MonoClass *attr_klass;
8478 MonoCustomAttrInfo *cinfo;
8479 MonoClassField *field;
8481 field = decode_fieldid (p, &p, end, NULL, &err);
8482 if (err != ERR_NONE)
8484 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8485 if (err != ERR_NONE)
8488 cinfo = mono_custom_attrs_from_field_checked (klass, field, &error);
8489 if (!is_ok (&error)) {
8490 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8491 return ERR_LOADER_ERROR;
8494 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8495 if (err != ERR_NONE)
8499 case CMD_TYPE_GET_PROPERTY_CATTRS: {
8500 MonoClass *attr_klass;
8501 MonoCustomAttrInfo *cinfo;
8504 prop = decode_propertyid (p, &p, end, NULL, &err);
8505 if (err != ERR_NONE)
8507 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8508 if (err != ERR_NONE)
8511 cinfo = mono_custom_attrs_from_property_checked (klass, prop, &error);
8512 if (!is_ok (&error)) {
8513 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8514 return ERR_LOADER_ERROR;
8517 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8518 if (err != ERR_NONE)
8522 case CMD_TYPE_GET_VALUES:
8523 case CMD_TYPE_GET_VALUES_2: {
8530 MonoThread *thread_obj;
8531 MonoInternalThread *thread = NULL;
8532 guint32 special_static_type;
8534 if (command == CMD_TYPE_GET_VALUES_2) {
8535 int objid = decode_objid (p, &p, end);
8538 err = get_object (objid, (MonoObject**)&thread_obj);
8539 if (err != ERR_NONE)
8542 thread = THREAD_TO_INTERNAL (thread_obj);
8545 len = decode_int (p, &p, end);
8546 for (i = 0; i < len; ++i) {
8547 f = decode_fieldid (p, &p, end, NULL, &err);
8548 if (err != ERR_NONE)
8551 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8552 return ERR_INVALID_FIELDID;
8553 special_static_type = mono_class_field_get_special_static_type (f);
8554 if (special_static_type != SPECIAL_STATIC_NONE) {
8555 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
8556 return ERR_INVALID_FIELDID;
8559 /* Check that the field belongs to the object */
8561 for (k = klass; k; k = k->parent) {
8562 if (k == f->parent) {
8568 return ERR_INVALID_FIELDID;
8570 vtable = mono_class_vtable (domain, f->parent);
8571 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8572 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val, &error);
8573 if (!is_ok (&error))
8574 return ERR_INVALID_FIELDID;
8575 buffer_add_value (buf, f->type, val, domain);
8580 case CMD_TYPE_SET_VALUES: {
8588 len = decode_int (p, &p, end);
8589 for (i = 0; i < len; ++i) {
8590 f = decode_fieldid (p, &p, end, NULL, &err);
8591 if (err != ERR_NONE)
8594 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8595 return ERR_INVALID_FIELDID;
8596 if (mono_class_field_is_special_static (f))
8597 return ERR_INVALID_FIELDID;
8599 /* Check that the field belongs to the object */
8601 for (k = klass; k; k = k->parent) {
8602 if (k == f->parent) {
8608 return ERR_INVALID_FIELDID;
8610 // FIXME: Check for literal/const
8612 vtable = mono_class_vtable (domain, f->parent);
8613 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8614 err = decode_value (f->type, domain, val, p, &p, end);
8615 if (err != ERR_NONE) {
8619 if (MONO_TYPE_IS_REFERENCE (f->type))
8620 mono_field_static_set_value (vtable, f, *(gpointer*)val);
8622 mono_field_static_set_value (vtable, f, val);
8627 case CMD_TYPE_GET_OBJECT: {
8628 MonoObject *o = (MonoObject*)mono_type_get_object_checked (domain, &klass->byval_arg, &error);
8629 if (!mono_error_ok (&error)) {
8630 mono_error_cleanup (&error);
8631 return ERR_INVALID_OBJECT;
8633 buffer_add_objid (buf, o);
8636 case CMD_TYPE_GET_SOURCE_FILES:
8637 case CMD_TYPE_GET_SOURCE_FILES_2: {
8638 char *source_file, *base;
8642 files = get_source_files_for_type (klass);
8644 buffer_add_int (buf, files->len);
8645 for (i = 0; i < files->len; ++i) {
8646 source_file = (char *)g_ptr_array_index (files, i);
8647 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8648 buffer_add_string (buf, source_file);
8650 base = dbg_path_get_basename (source_file);
8651 buffer_add_string (buf, base);
8654 g_free (source_file);
8656 g_ptr_array_free (files, TRUE);
8659 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8660 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8662 if (err != ERR_NONE)
8664 if (mono_class_is_assignable_from (klass, oklass))
8665 buffer_add_byte (buf, 1);
8667 buffer_add_byte (buf, 0);
8670 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8671 char *name = decode_string (p, &p, end);
8672 int i, flags = decode_int (p, &p, end);
8676 error_init (&error);
8677 array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &error);
8678 if (!is_ok (&error)) {
8679 mono_error_cleanup (&error);
8680 return ERR_LOADER_ERROR;
8682 buffer_add_int (buf, array->len);
8683 for (i = 0; i < array->len; ++i) {
8684 MonoMethod *method = (MonoMethod *)g_ptr_array_index (array, i);
8685 buffer_add_methodid (buf, domain, method);
8688 g_ptr_array_free (array, TRUE);
8692 case CMD_TYPE_GET_INTERFACES: {
8694 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8695 MonoClass *tclass, *iface;
8696 GHashTableIter iter;
8700 for (parent = tclass; parent; parent = parent->parent) {
8701 mono_class_setup_interfaces (parent, &error);
8702 if (!mono_error_ok (&error))
8703 return ERR_LOADER_ERROR;
8704 collect_interfaces (parent, iface_hash, &error);
8705 if (!mono_error_ok (&error))
8706 return ERR_LOADER_ERROR;
8709 buffer_add_int (buf, g_hash_table_size (iface_hash));
8711 g_hash_table_iter_init (&iter, iface_hash);
8712 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8713 buffer_add_typeid (buf, domain, iface);
8714 g_hash_table_destroy (iface_hash);
8717 case CMD_TYPE_GET_INTERFACE_MAP: {
8718 int tindex, ioffset;
8719 gboolean variance_used;
8721 int len, nmethods, i;
8725 len = decode_int (p, &p, end);
8726 mono_class_setup_vtable (klass);
8728 for (tindex = 0; tindex < len; ++tindex) {
8729 iclass = decode_typeid (p, &p, end, NULL, &err);
8730 if (err != ERR_NONE)
8733 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8735 return ERR_INVALID_ARGUMENT;
8737 nmethods = mono_class_num_methods (iclass);
8738 buffer_add_int (buf, nmethods);
8741 while ((method = mono_class_get_methods (iclass, &iter))) {
8742 buffer_add_methodid (buf, domain, method);
8744 for (i = 0; i < nmethods; ++i)
8745 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
8749 case CMD_TYPE_IS_INITIALIZED: {
8750 MonoVTable *vtable = mono_class_vtable (domain, klass);
8753 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8755 buffer_add_int (buf, 0);
8758 case CMD_TYPE_CREATE_INSTANCE: {
8762 obj = mono_object_new_checked (domain, klass, &error);
8763 mono_error_assert_ok (&error);
8764 buffer_add_objid (buf, obj);
8768 return ERR_NOT_IMPLEMENTED;
8775 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8778 MonoDomain *old_domain;
8782 klass = decode_typeid (p, &p, end, &domain, &err);
8783 if (err != ERR_NONE)
8786 old_domain = mono_domain_get ();
8788 mono_domain_set (domain, TRUE);
8790 err = type_commands_internal (command, klass, domain, p, end, buf);
8792 mono_domain_set (old_domain, TRUE);
8798 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8800 MonoMethodHeader *header;
8804 case CMD_METHOD_GET_NAME: {
8805 buffer_add_string (buf, method->name);
8808 case CMD_METHOD_GET_DECLARING_TYPE: {
8809 buffer_add_typeid (buf, domain, method->klass);
8812 case CMD_METHOD_GET_DEBUG_INFO: {
8814 MonoDebugMethodInfo *minfo;
8816 int i, j, n_il_offsets;
8818 GPtrArray *source_file_list;
8819 MonoSymSeqPoint *sym_seq_points;
8821 header = mono_method_get_header_checked (method, &error);
8823 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8824 buffer_add_int (buf, 0);
8825 buffer_add_string (buf, "");
8826 buffer_add_int (buf, 0);
8830 minfo = mono_debug_lookup_method (method);
8832 buffer_add_int (buf, header->code_size);
8833 buffer_add_string (buf, "");
8834 buffer_add_int (buf, 0);
8835 mono_metadata_free_mh (header);
8839 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, &source_files, &sym_seq_points, &n_il_offsets);
8840 buffer_add_int (buf, header->code_size);
8841 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8842 buffer_add_int (buf, source_file_list->len);
8843 for (i = 0; i < source_file_list->len; ++i) {
8844 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
8845 buffer_add_string (buf, sinfo->source_file);
8846 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8847 for (j = 0; j < 16; ++j)
8848 buffer_add_byte (buf, sinfo->hash [j]);
8852 buffer_add_string (buf, source_file);
8854 buffer_add_int (buf, n_il_offsets);
8855 DEBUG_PRINTF (10, "Line number table for method %s:\n", mono_method_full_name (method, TRUE));
8856 for (i = 0; i < n_il_offsets; ++i) {
8857 MonoSymSeqPoint *sp = &sym_seq_points [i];
8858 const char *srcfile = "";
8860 if (source_files [i] != -1) {
8861 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, source_files [i]);
8862 srcfile = sinfo->source_file;
8864 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);
8865 buffer_add_int (buf, sp->il_offset);
8866 buffer_add_int (buf, sp->line);
8867 if (CHECK_PROTOCOL_VERSION (2, 13))
8868 buffer_add_int (buf, source_files [i]);
8869 if (CHECK_PROTOCOL_VERSION (2, 19))
8870 buffer_add_int (buf, sp->column);
8871 if (CHECK_PROTOCOL_VERSION (2, 32)) {
8872 buffer_add_int (buf, sp->end_line);
8873 buffer_add_int (buf, sp->end_column);
8876 g_free (source_file);
8877 g_free (source_files);
8878 g_free (sym_seq_points);
8879 g_ptr_array_free (source_file_list, TRUE);
8880 mono_metadata_free_mh (header);
8883 case CMD_METHOD_GET_PARAM_INFO: {
8884 MonoMethodSignature *sig = mono_method_signature (method);
8888 /* FIXME: mono_class_from_mono_type () and byrefs */
8890 /* FIXME: Use a smaller encoding */
8891 buffer_add_int (buf, sig->call_convention);
8892 buffer_add_int (buf, sig->param_count);
8893 buffer_add_int (buf, sig->generic_param_count);
8894 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
8895 for (i = 0; i < sig->param_count; ++i) {
8897 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
8900 /* Emit parameter names */
8901 names = g_new (char *, sig->param_count);
8902 mono_method_get_param_names (method, (const char **) names);
8903 for (i = 0; i < sig->param_count; ++i)
8904 buffer_add_string (buf, names [i]);
8909 case CMD_METHOD_GET_LOCALS_INFO: {
8912 MonoDebugLocalsInfo *locals;
8913 int *locals_map = NULL;
8915 header = mono_method_get_header_checked (method, &error);
8917 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8918 return ERR_INVALID_ARGUMENT;
8921 locals = mono_debug_lookup_locals (method);
8923 if (CHECK_PROTOCOL_VERSION (2, 43)) {
8925 buffer_add_int (buf, 1);
8926 buffer_add_int (buf, 0);
8927 buffer_add_int (buf, header->code_size);
8929 buffer_add_int (buf, header->num_locals);
8931 for (i = 0; i < header->num_locals; ++i) {
8932 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
8935 for (i = 0; i < header->num_locals; ++i) {
8937 sprintf (lname, "V_%d", i);
8938 buffer_add_string (buf, lname);
8941 for (i = 0; i < header->num_locals; ++i) {
8942 buffer_add_int (buf, 0);
8943 buffer_add_int (buf, header->code_size);
8946 if (CHECK_PROTOCOL_VERSION (2, 43)) {
8948 buffer_add_int (buf, locals->num_blocks);
8950 for (i = 0; i < locals->num_blocks; ++i) {
8951 buffer_add_int (buf, locals->code_blocks [i].start_offset - last_start);
8952 buffer_add_int (buf, locals->code_blocks [i].end_offset - locals->code_blocks [i].start_offset);
8953 last_start = locals->code_blocks [i].start_offset;
8957 num_locals = locals->num_locals;
8958 buffer_add_int (buf, num_locals);
8961 for (i = 0; i < num_locals; ++i) {
8962 g_assert (locals->locals [i].index < header->num_locals);
8963 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [locals->locals [i].index]));
8966 for (i = 0; i < num_locals; ++i)
8967 buffer_add_string (buf, locals->locals [i].name);
8969 for (i = 0; i < num_locals; ++i) {
8970 if (locals->locals [i].block) {
8971 buffer_add_int (buf, locals->locals [i].block->start_offset);
8972 buffer_add_int (buf, locals->locals [i].block->end_offset);
8974 buffer_add_int (buf, 0);
8975 buffer_add_int (buf, header->code_size);
8979 mono_metadata_free_mh (header);
8982 mono_debug_free_locals (locals);
8983 g_free (locals_map);
8987 case CMD_METHOD_GET_INFO:
8988 buffer_add_int (buf, method->flags);
8989 buffer_add_int (buf, method->iflags);
8990 buffer_add_int (buf, method->token);
8991 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8993 if (method->is_generic)
8995 if (mono_method_signature (method)->generic_param_count)
8997 buffer_add_byte (buf, attrs);
8998 if (method->is_generic || method->is_inflated) {
9001 if (method->is_generic) {
9004 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
9006 result = imethod->declaring;
9007 if (imethod->context.class_inst) {
9008 MonoClass *klass = ((MonoMethod *) imethod)->klass;
9009 /*Generic methods gets the context of the GTD.*/
9010 if (mono_class_get_context (klass)) {
9012 result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), &error);
9013 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9018 buffer_add_methodid (buf, domain, result);
9020 buffer_add_id (buf, 0);
9022 if (CHECK_PROTOCOL_VERSION (2, 15)) {
9023 if (mono_method_signature (method)->generic_param_count) {
9026 if (method->is_inflated) {
9027 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
9029 count = inst->type_argc;
9030 buffer_add_int (buf, count);
9032 for (i = 0; i < count; i++)
9033 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
9035 buffer_add_int (buf, 0);
9037 } else if (method->is_generic) {
9038 MonoGenericContainer *container = mono_method_get_generic_container (method);
9040 count = mono_method_signature (method)->generic_param_count;
9041 buffer_add_int (buf, count);
9042 for (i = 0; i < count; i++) {
9043 MonoGenericParam *param = mono_generic_container_get_param (container, i);
9044 MonoClass *pklass = mono_class_from_generic_parameter_internal (param);
9045 buffer_add_typeid (buf, domain, pklass);
9048 buffer_add_int (buf, 0);
9051 buffer_add_int (buf, 0);
9056 case CMD_METHOD_GET_BODY: {
9060 header = mono_method_get_header_checked (method, &error);
9062 mono_error_cleanup (&error); /* FIXME don't swallow the error */
9063 buffer_add_int (buf, 0);
9065 if (CHECK_PROTOCOL_VERSION (2, 18))
9066 buffer_add_int (buf, 0);
9068 buffer_add_int (buf, header->code_size);
9069 for (i = 0; i < header->code_size; ++i)
9070 buffer_add_byte (buf, header->code [i]);
9072 if (CHECK_PROTOCOL_VERSION (2, 18)) {
9073 buffer_add_int (buf, header->num_clauses);
9074 for (i = 0; i < header->num_clauses; ++i) {
9075 MonoExceptionClause *clause = &header->clauses [i];
9077 buffer_add_int (buf, clause->flags);
9078 buffer_add_int (buf, clause->try_offset);
9079 buffer_add_int (buf, clause->try_len);
9080 buffer_add_int (buf, clause->handler_offset);
9081 buffer_add_int (buf, clause->handler_len);
9082 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
9083 buffer_add_typeid (buf, domain, clause->data.catch_class);
9084 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
9085 buffer_add_int (buf, clause->data.filter_offset);
9089 mono_metadata_free_mh (header);
9094 case CMD_METHOD_RESOLVE_TOKEN: {
9095 guint32 token = decode_int (p, &p, end);
9098 switch (mono_metadata_token_code (token)) {
9099 case MONO_TOKEN_STRING: {
9104 s = mono_ldstr_checked (domain, method->klass->image, mono_metadata_token_index (token), &error);
9105 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
9107 s2 = mono_string_to_utf8_checked (s, &error);
9108 mono_error_assert_ok (&error);
9110 buffer_add_byte (buf, TOKEN_TYPE_STRING);
9111 buffer_add_string (buf, s2);
9118 MonoClass *handle_class;
9120 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
9121 val = mono_method_get_wrapper_data (method, token);
9122 handle_class = (MonoClass *)mono_method_get_wrapper_data (method, token + 1);
9124 if (handle_class == NULL) {
9125 // Can't figure out the token type
9126 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
9130 val = mono_ldtoken_checked (method->klass->image, token, &handle_class, NULL, &error);
9132 g_error ("Could not load token due to %s", mono_error_get_message (&error));
9135 if (handle_class == mono_defaults.typehandle_class) {
9136 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
9137 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
9138 buffer_add_typeid (buf, domain, (MonoClass *) val);
9140 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
9141 } else if (handle_class == mono_defaults.fieldhandle_class) {
9142 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
9143 buffer_add_fieldid (buf, domain, (MonoClassField *)val);
9144 } else if (handle_class == mono_defaults.methodhandle_class) {
9145 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
9146 buffer_add_methodid (buf, domain, (MonoMethod *)val);
9147 } else if (handle_class == mono_defaults.string_class) {
9150 s = mono_string_to_utf8_checked ((MonoString *)val, &error);
9151 mono_error_assert_ok (&error);
9152 buffer_add_byte (buf, TOKEN_TYPE_STRING);
9153 buffer_add_string (buf, s);
9156 g_assert_not_reached ();
9163 case CMD_METHOD_GET_CATTRS: {
9165 MonoClass *attr_klass;
9166 MonoCustomAttrInfo *cinfo;
9168 attr_klass = decode_typeid (p, &p, end, NULL, &err);
9169 /* attr_klass can be NULL */
9170 if (err != ERR_NONE)
9173 cinfo = mono_custom_attrs_from_method_checked (method, &error);
9174 if (!is_ok (&error)) {
9175 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
9176 return ERR_LOADER_ERROR;
9179 err = buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
9180 if (err != ERR_NONE)
9184 case CMD_METHOD_MAKE_GENERIC_METHOD: {
9186 MonoType **type_argv;
9190 MonoGenericInst *ginst;
9191 MonoGenericContext tmp_context;
9192 MonoMethod *inflated;
9194 type_argc = decode_int (p, &p, end);
9195 type_argv = g_new0 (MonoType*, type_argc);
9196 for (i = 0; i < type_argc; ++i) {
9197 klass = decode_typeid (p, &p, end, &d, &err);
9198 if (err != ERR_NONE) {
9204 return ERR_INVALID_ARGUMENT;
9206 type_argv [i] = &klass->byval_arg;
9208 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
9210 tmp_context.class_inst = mono_class_is_ginst (method->klass) ? mono_class_get_generic_class (method->klass)->context.class_inst : NULL;
9211 tmp_context.method_inst = ginst;
9213 inflated = mono_class_inflate_generic_method_checked (method, &tmp_context, &error);
9214 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9215 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
9216 return ERR_INVALID_ARGUMENT;
9217 buffer_add_methodid (buf, domain, inflated);
9221 return ERR_NOT_IMPLEMENTED;
9228 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9231 MonoDomain *old_domain;
9235 method = decode_methodid (p, &p, end, &domain, &err);
9236 if (err != ERR_NONE)
9239 old_domain = mono_domain_get ();
9241 mono_domain_set (domain, TRUE);
9243 err = method_commands_internal (command, method, domain, p, end, buf);
9245 mono_domain_set (old_domain, TRUE);
9251 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9253 int objid = decode_objid (p, &p, end);
9255 MonoThread *thread_obj;
9256 MonoInternalThread *thread;
9258 err = get_object (objid, (MonoObject**)&thread_obj);
9259 if (err != ERR_NONE)
9262 thread = THREAD_TO_INTERNAL (thread_obj);
9265 case CMD_THREAD_GET_NAME: {
9267 gunichar2 *s = mono_thread_get_name (thread, &name_len);
9270 buffer_add_int (buf, 0);
9275 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
9277 buffer_add_int (buf, len);
9278 buffer_add_data (buf, (guint8*)name, len);
9283 case CMD_THREAD_GET_FRAME_INFO: {
9284 DebuggerTlsData *tls;
9285 int i, start_frame, length;
9287 // Wait for suspending if it already started
9288 // FIXME: Races with suspend_count
9289 while (!is_suspended ()) {
9291 wait_for_suspend ();
9295 wait_for_suspend ();
9296 if (!is_suspended ())
9297 return ERR_NOT_SUSPENDED;
9300 start_frame = decode_int (p, &p, end);
9301 length = decode_int (p, &p, end);
9303 if (start_frame != 0 || length != -1)
9304 return ERR_NOT_IMPLEMENTED;
9306 mono_loader_lock ();
9307 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9308 mono_loader_unlock ();
9311 compute_frame_info (thread, tls);
9313 buffer_add_int (buf, tls->frame_count);
9314 for (i = 0; i < tls->frame_count; ++i) {
9315 buffer_add_int (buf, tls->frames [i]->id);
9316 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
9317 buffer_add_int (buf, tls->frames [i]->il_offset);
9319 * Instead of passing the frame type directly to the client, we associate
9320 * it with the previous frame using a set of flags. This avoids lots of
9321 * conditional code in the client, since a frame whose type isn't
9322 * FRAME_TYPE_MANAGED has no method, location, etc.
9324 buffer_add_byte (buf, tls->frames [i]->flags);
9329 case CMD_THREAD_GET_STATE:
9330 buffer_add_int (buf, thread->state);
9332 case CMD_THREAD_GET_INFO:
9333 buffer_add_byte (buf, thread->threadpool_thread);
9335 case CMD_THREAD_GET_ID:
9336 buffer_add_long (buf, (guint64)(gsize)thread);
9338 case CMD_THREAD_GET_TID:
9339 buffer_add_long (buf, (guint64)thread->tid);
9341 case CMD_THREAD_SET_IP: {
9342 DebuggerTlsData *tls;
9345 MonoSeqPointInfo *seq_points;
9350 method = decode_methodid (p, &p, end, &domain, &err);
9351 if (err != ERR_NONE)
9353 il_offset = decode_long (p, &p, end);
9355 while (!is_suspended ()) {
9357 wait_for_suspend ();
9360 mono_loader_lock ();
9361 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9362 mono_loader_unlock ();
9365 compute_frame_info (thread, tls);
9366 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
9367 return ERR_INVALID_ARGUMENT;
9369 found_sp = mono_find_seq_point (domain, method, il_offset, &seq_points, &sp);
9371 g_assert (seq_points);
9374 return ERR_INVALID_ARGUMENT;
9376 // FIXME: Check that the ip change is safe
9378 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);
9379 MONO_CONTEXT_SET_IP (&tls->restore_state.ctx, (guint8*)tls->frames [0]->ji->code_start + sp.native_offset);
9383 return ERR_NOT_IMPLEMENTED;
9390 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9394 MonoThread *thread_obj;
9395 MonoInternalThread *thread;
9396 int pos, i, len, frame_idx;
9397 DebuggerTlsData *tls;
9399 MonoDebugMethodJitInfo *jit;
9400 MonoMethodSignature *sig;
9402 MonoMethodHeader *header;
9404 objid = decode_objid (p, &p, end);
9405 err = get_object (objid, (MonoObject**)&thread_obj);
9406 if (err != ERR_NONE)
9409 thread = THREAD_TO_INTERNAL (thread_obj);
9411 id = decode_id (p, &p, end);
9413 mono_loader_lock ();
9414 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9415 mono_loader_unlock ();
9418 for (i = 0; i < tls->frame_count; ++i) {
9419 if (tls->frames [i]->id == id)
9422 if (i == tls->frame_count)
9423 return ERR_INVALID_FRAMEID;
9426 frame = tls->frames [frame_idx];
9428 /* This is supported for frames without has_ctx etc. set */
9429 if (command == CMD_STACK_FRAME_GET_DOMAIN) {
9430 if (CHECK_PROTOCOL_VERSION (2, 38))
9431 buffer_add_domainid (buf, frame->domain);
9435 if (!frame->has_ctx)
9436 return ERR_ABSENT_INFORMATION;
9438 if (!ensure_jit (frame))
9439 return ERR_ABSENT_INFORMATION;
9443 sig = mono_method_signature (frame->actual_method);
9445 if (!jit->has_var_info || !mono_get_seq_points (frame->domain, frame->actual_method))
9447 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
9449 return ERR_ABSENT_INFORMATION;
9452 case CMD_STACK_FRAME_GET_VALUES: {
9454 len = decode_int (p, &p, end);
9455 header = mono_method_get_header_checked (frame->actual_method, &error);
9456 mono_error_assert_ok (&error); /* FIXME report error */
9458 for (i = 0; i < len; ++i) {
9459 pos = decode_int (p, &p, end);
9464 DEBUG_PRINTF (4, "[dbg] send arg %d.\n", pos);
9466 g_assert (pos >= 0 && pos < jit->num_params);
9468 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
9470 MonoDebugLocalsInfo *locals;
9472 locals = mono_debug_lookup_locals (frame->method);
9474 g_assert (pos < locals->num_locals);
9475 pos = locals->locals [pos].index;
9476 mono_debug_free_locals (locals);
9478 g_assert (pos >= 0 && pos < jit->num_locals);
9480 DEBUG_PRINTF (4, "[dbg] send local %d.\n", pos);
9482 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
9485 mono_metadata_free_mh (header);
9488 case CMD_STACK_FRAME_GET_THIS: {
9489 if (frame->api_method->klass->valuetype) {
9490 if (!sig->hasthis) {
9491 MonoObject *p = NULL;
9492 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
9494 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9497 if (!sig->hasthis) {
9498 MonoObject *p = NULL;
9499 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
9501 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9506 case CMD_STACK_FRAME_SET_VALUES: {
9510 MonoDebugVarInfo *var;
9512 len = decode_int (p, &p, end);
9513 header = mono_method_get_header_checked (frame->actual_method, &error);
9514 mono_error_assert_ok (&error); /* FIXME report error */
9516 for (i = 0; i < len; ++i) {
9517 pos = decode_int (p, &p, end);
9522 g_assert (pos >= 0 && pos < jit->num_params);
9524 t = sig->params [pos];
9525 var = &jit->params [pos];
9527 MonoDebugLocalsInfo *locals;
9529 locals = mono_debug_lookup_locals (frame->method);
9531 g_assert (pos < locals->num_locals);
9532 pos = locals->locals [pos].index;
9533 mono_debug_free_locals (locals);
9535 g_assert (pos >= 0 && pos < jit->num_locals);
9537 t = header->locals [pos];
9538 var = &jit->locals [pos];
9541 if (MONO_TYPE_IS_REFERENCE (t))
9542 val_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
9544 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9545 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9546 if (err != ERR_NONE)
9549 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9551 mono_metadata_free_mh (header);
9554 case CMD_STACK_FRAME_GET_DOMAIN: {
9555 if (CHECK_PROTOCOL_VERSION (2, 38))
9556 buffer_add_domainid (buf, frame->domain);
9559 case CMD_STACK_FRAME_SET_THIS: {
9562 MonoDebugVarInfo *var;
9564 t = &frame->actual_method->klass->byval_arg;
9565 /* Checked by the sender */
9566 g_assert (MONO_TYPE_ISSTRUCT (t));
9567 var = jit->this_var;
9570 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9571 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9572 if (err != ERR_NONE)
9575 set_var (&frame->actual_method->klass->this_arg, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9579 return ERR_NOT_IMPLEMENTED;
9586 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9589 int objid, index, len, i, esize;
9593 objid = decode_objid (p, &p, end);
9594 err = get_object (objid, (MonoObject**)&arr);
9595 if (err != ERR_NONE)
9599 case CMD_ARRAY_REF_GET_LENGTH:
9600 buffer_add_int (buf, arr->obj.vtable->klass->rank);
9602 buffer_add_int (buf, arr->max_length);
9603 buffer_add_int (buf, 0);
9605 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
9606 buffer_add_int (buf, arr->bounds [i].length);
9607 buffer_add_int (buf, arr->bounds [i].lower_bound);
9611 case CMD_ARRAY_REF_GET_VALUES:
9612 index = decode_int (p, &p, end);
9613 len = decode_int (p, &p, end);
9615 g_assert (index >= 0 && len >= 0);
9616 // Reordered to avoid integer overflow
9617 g_assert (!(index > arr->max_length - len));
9619 esize = mono_array_element_size (arr->obj.vtable->klass);
9620 for (i = index; i < index + len; ++i) {
9621 elem = (gpointer*)((char*)arr->vector + (i * esize));
9622 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
9625 case CMD_ARRAY_REF_SET_VALUES:
9626 index = decode_int (p, &p, end);
9627 len = decode_int (p, &p, end);
9629 g_assert (index >= 0 && len >= 0);
9630 // Reordered to avoid integer overflow
9631 g_assert (!(index > arr->max_length - len));
9633 esize = mono_array_element_size (arr->obj.vtable->klass);
9634 for (i = index; i < index + len; ++i) {
9635 elem = (gpointer*)((char*)arr->vector + (i * esize));
9637 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, (guint8 *)elem, p, &p, end);
9641 return ERR_NOT_IMPLEMENTED;
9648 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9654 int i, index, length;
9656 gboolean use_utf16 = FALSE;
9658 objid = decode_objid (p, &p, end);
9659 err = get_object (objid, (MonoObject**)&str);
9660 if (err != ERR_NONE)
9664 case CMD_STRING_REF_GET_VALUE:
9665 if (CHECK_PROTOCOL_VERSION (2, 41)) {
9666 for (i = 0; i < mono_string_length (str); ++i)
9667 if (mono_string_chars (str)[i] == 0)
9669 buffer_add_byte (buf, use_utf16 ? 1 : 0);
9672 buffer_add_int (buf, mono_string_length (str) * 2);
9673 buffer_add_data (buf, (guint8*)mono_string_chars (str), mono_string_length (str) * 2);
9676 s = mono_string_to_utf8_checked (str, &error);
9677 mono_error_assert_ok (&error);
9678 buffer_add_string (buf, s);
9682 case CMD_STRING_REF_GET_LENGTH:
9683 buffer_add_long (buf, mono_string_length (str));
9685 case CMD_STRING_REF_GET_CHARS:
9686 index = decode_long (p, &p, end);
9687 length = decode_long (p, &p, end);
9688 if (index > mono_string_length (str) - length)
9689 return ERR_INVALID_ARGUMENT;
9690 c = mono_string_chars (str) + index;
9691 for (i = 0; i < length; ++i)
9692 buffer_add_short (buf, c [i]);
9695 return ERR_NOT_IMPLEMENTED;
9702 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9713 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9714 objid = decode_objid (p, &p, end);
9715 err = get_object (objid, &obj);
9716 if (err != ERR_NONE)
9717 buffer_add_int (buf, 1);
9719 buffer_add_int (buf, 0);
9723 objid = decode_objid (p, &p, end);
9724 err = get_object (objid, &obj);
9725 if (err != ERR_NONE)
9728 MonoClass *obj_type;
9729 gboolean remote_obj = FALSE;
9731 obj_type = obj->vtable->klass;
9732 if (mono_class_is_transparent_proxy (obj_type)) {
9733 obj_type = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
9737 g_assert (obj_type);
9740 case CMD_OBJECT_REF_GET_TYPE:
9741 /* This handles transparent proxies too */
9742 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9744 case CMD_OBJECT_REF_GET_VALUES:
9745 len = decode_int (p, &p, end);
9747 for (i = 0; i < len; ++i) {
9748 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9749 if (err != ERR_NONE)
9752 /* Check that the field belongs to the object */
9754 for (k = obj_type; k; k = k->parent) {
9755 if (k == f->parent) {
9761 return ERR_INVALID_FIELDID;
9763 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9767 if (mono_class_field_is_special_static (f))
9768 return ERR_INVALID_FIELDID;
9770 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9771 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9772 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9773 mono_field_static_get_value_checked (vtable, f, val, &error);
9774 if (!is_ok (&error)) {
9775 mono_error_cleanup (&error); /* FIXME report the error */
9776 return ERR_INVALID_OBJECT;
9778 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9781 guint8 *field_value = NULL;
9784 #ifndef DISABLE_REMOTING
9785 void *field_storage = NULL;
9786 field_value = mono_load_remote_field_checked(obj, obj_type, f, &field_storage, &error);
9787 if (!is_ok (&error)) {
9788 mono_error_cleanup (&error); /* FIXME report the error */
9789 return ERR_INVALID_OBJECT;
9792 g_assert_not_reached ();
9795 field_value = (guint8*)obj + f->offset;
9797 buffer_add_value (buf, f->type, field_value, obj->vtable->domain);
9801 case CMD_OBJECT_REF_SET_VALUES:
9802 len = decode_int (p, &p, end);
9804 for (i = 0; i < len; ++i) {
9805 f = decode_fieldid (p, &p, end, NULL, &err);
9806 if (err != ERR_NONE)
9809 /* Check that the field belongs to the object */
9811 for (k = obj_type; k; k = k->parent) {
9812 if (k == f->parent) {
9818 return ERR_INVALID_FIELDID;
9820 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9824 if (mono_class_field_is_special_static (f))
9825 return ERR_INVALID_FIELDID;
9827 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9828 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9830 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9831 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
9832 if (err != ERR_NONE) {
9836 mono_field_static_set_value (vtable, f, val);
9839 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
9840 if (err != ERR_NONE)
9845 case CMD_OBJECT_REF_GET_ADDRESS:
9846 buffer_add_long (buf, (gssize)obj);
9848 case CMD_OBJECT_REF_GET_DOMAIN:
9849 buffer_add_domainid (buf, obj->vtable->domain);
9851 case CMD_OBJECT_REF_GET_INFO:
9852 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9853 buffer_add_domainid (buf, obj->vtable->domain);
9856 return ERR_NOT_IMPLEMENTED;
9863 command_set_to_string (CommandSet command_set)
9865 switch (command_set) {
9868 case CMD_SET_OBJECT_REF:
9869 return "OBJECT_REF";
9870 case CMD_SET_STRING_REF:
9871 return "STRING_REF";
9872 case CMD_SET_THREAD:
9874 case CMD_SET_ARRAY_REF:
9876 case CMD_SET_EVENT_REQUEST:
9877 return "EVENT_REQUEST";
9878 case CMD_SET_STACK_FRAME:
9879 return "STACK_FRAME";
9880 case CMD_SET_APPDOMAIN:
9882 case CMD_SET_ASSEMBLY:
9884 case CMD_SET_METHOD:
9888 case CMD_SET_MODULE:
9899 static const char* vm_cmds_str [] = {
9907 "SET_PROTOCOL_VERSION",
9910 "GET_TYPES_FOR_SOURCE_FILE",
9915 static const char* thread_cmds_str[] = {
9925 static const char* event_cmds_str[] = {
9928 "REQUEST_CLEAR_ALL_BREAKPOINTS"
9931 static const char* appdomain_cmds_str[] = {
9933 "GET_FRIENDLY_NAME",
9935 "GET_ENTRY_ASSEMBLY",
9938 "CREATE_BOXED_VALUE"
9941 static const char* assembly_cmds_str[] = {
9944 "GET_MANIFEST_MODULE",
9951 static const char* module_cmds_str[] = {
9955 static const char* field_cmds_str[] = {
9959 static const char* method_cmds_str[] = {
9961 "GET_DECLARING_TYPE",
9969 "MAKE_GENERIC_METHOD"
9972 static const char* type_cmds_str[] = {
9980 "IS_ASSIGNABLE_FROM",
9984 "GET_PROPERTY_CATTRS",
9985 "GET_SOURCE_FILES_2",
9987 "GET_METHODS_BY_NAME_FLAGS",
9989 "GET_INTERFACE_MAP",
9993 static const char* stack_frame_cmds_str[] = {
10001 static const char* array_cmds_str[] = {
10007 static const char* string_cmds_str[] = {
10013 static const char* object_cmds_str[] = {
10024 cmd_to_string (CommandSet set, int command)
10031 cmds = vm_cmds_str;
10032 cmds_len = G_N_ELEMENTS (vm_cmds_str);
10034 case CMD_SET_OBJECT_REF:
10035 cmds = object_cmds_str;
10036 cmds_len = G_N_ELEMENTS (object_cmds_str);
10038 case CMD_SET_STRING_REF:
10039 cmds = string_cmds_str;
10040 cmds_len = G_N_ELEMENTS (string_cmds_str);
10042 case CMD_SET_THREAD:
10043 cmds = thread_cmds_str;
10044 cmds_len = G_N_ELEMENTS (thread_cmds_str);
10046 case CMD_SET_ARRAY_REF:
10047 cmds = array_cmds_str;
10048 cmds_len = G_N_ELEMENTS (array_cmds_str);
10050 case CMD_SET_EVENT_REQUEST:
10051 cmds = event_cmds_str;
10052 cmds_len = G_N_ELEMENTS (event_cmds_str);
10054 case CMD_SET_STACK_FRAME:
10055 cmds = stack_frame_cmds_str;
10056 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
10058 case CMD_SET_APPDOMAIN:
10059 cmds = appdomain_cmds_str;
10060 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
10062 case CMD_SET_ASSEMBLY:
10063 cmds = assembly_cmds_str;
10064 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
10066 case CMD_SET_METHOD:
10067 cmds = method_cmds_str;
10068 cmds_len = G_N_ELEMENTS (method_cmds_str);
10071 cmds = type_cmds_str;
10072 cmds_len = G_N_ELEMENTS (type_cmds_str);
10074 case CMD_SET_MODULE:
10075 cmds = module_cmds_str;
10076 cmds_len = G_N_ELEMENTS (module_cmds_str);
10078 case CMD_SET_FIELD:
10079 cmds = field_cmds_str;
10080 cmds_len = G_N_ELEMENTS (field_cmds_str);
10082 case CMD_SET_EVENT:
10083 cmds = event_cmds_str;
10084 cmds_len = G_N_ELEMENTS (event_cmds_str);
10089 if (command > 0 && command <= cmds_len)
10090 return cmds [command - 1];
10096 wait_for_attach (void)
10098 #ifndef DISABLE_SOCKET_TRANSPORT
10099 if (listen_fd == -1) {
10100 DEBUG_PRINTF (1, "[dbg] Invalid listening socket\n");
10104 /* Block and wait for client connection */
10105 conn_fd = socket_transport_accept (listen_fd);
10107 DEBUG_PRINTF (1, "Accepted connection on %d\n", conn_fd);
10108 if (conn_fd == -1) {
10109 DEBUG_PRINTF (1, "[dbg] Bad client connection\n");
10113 g_assert_not_reached ();
10117 disconnected = !transport_handshake ();
10118 if (disconnected) {
10119 DEBUG_PRINTF (1, "Transport handshake failed!\n");
10129 * This thread handles communication with the debugger client using a JDWP
10132 static gsize WINAPI
10133 debugger_thread (void *arg)
10136 int res, len, id, flags, command = 0;
10137 CommandSet command_set = (CommandSet)0;
10138 guint8 header [HEADER_LENGTH];
10139 guint8 *data, *p, *end;
10143 gboolean attach_failed = FALSE;
10145 DEBUG_PRINTF (1, "[dbg] Agent thread started, pid=%p\n", (gpointer) (gsize) mono_native_thread_id_get ());
10147 debugger_thread_id = mono_native_thread_id_get ();
10149 MonoInternalThread *internal = mono_thread_internal_current ();
10150 MonoString *str = mono_string_new_checked (mono_domain_get (), "Debugger agent", &error);
10151 mono_error_assert_ok (&error);
10152 mono_thread_set_name_internal (internal, str, TRUE, FALSE, &error);
10153 mono_error_assert_ok (&error);
10155 internal->state |= ThreadState_Background;
10156 internal->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
10158 if (agent_config.defer) {
10159 if (!wait_for_attach ()) {
10160 DEBUG_PRINTF (1, "[dbg] Can't attach, aborting debugger thread.\n");
10161 attach_failed = TRUE; // Don't abort process when we can't listen
10163 mono_set_is_debugger_attached (TRUE);
10164 /* Send start event to client */
10165 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
10168 mono_set_is_debugger_attached (TRUE);
10171 while (!attach_failed) {
10172 res = transport_recv (header, HEADER_LENGTH);
10174 /* This will break if the socket is closed during shutdown too */
10175 if (res != HEADER_LENGTH) {
10176 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH);
10181 end = header + HEADER_LENGTH;
10183 len = decode_int (p, &p, end);
10184 id = decode_int (p, &p, end);
10185 flags = decode_byte (p, &p, end);
10186 command_set = (CommandSet)decode_byte (p, &p, end);
10187 command = decode_byte (p, &p, end);
10189 g_assert (flags == 0);
10192 const char *cmd_str;
10193 char cmd_num [256];
10195 cmd_str = cmd_to_string (command_set, command);
10197 sprintf (cmd_num, "%d", command);
10201 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);
10204 data = (guint8 *)g_malloc (len - HEADER_LENGTH);
10205 if (len - HEADER_LENGTH > 0)
10207 res = transport_recv (data, len - HEADER_LENGTH);
10208 if (res != len - HEADER_LENGTH) {
10209 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH);
10215 end = data + (len - HEADER_LENGTH);
10217 buffer_init (&buf, 128);
10222 /* Process the request */
10223 switch (command_set) {
10225 err = vm_commands (command, id, p, end, &buf);
10226 if (err == ERR_NONE && command == CMD_VM_INVOKE_METHOD)
10227 /* Sent after the invoke is complete */
10230 case CMD_SET_EVENT_REQUEST:
10231 err = event_commands (command, p, end, &buf);
10233 case CMD_SET_APPDOMAIN:
10234 err = domain_commands (command, p, end, &buf);
10236 case CMD_SET_ASSEMBLY:
10237 err = assembly_commands (command, p, end, &buf);
10239 case CMD_SET_MODULE:
10240 err = module_commands (command, p, end, &buf);
10242 case CMD_SET_FIELD:
10243 err = field_commands (command, p, end, &buf);
10246 err = type_commands (command, p, end, &buf);
10248 case CMD_SET_METHOD:
10249 err = method_commands (command, p, end, &buf);
10251 case CMD_SET_THREAD:
10252 err = thread_commands (command, p, end, &buf);
10254 case CMD_SET_STACK_FRAME:
10255 err = frame_commands (command, p, end, &buf);
10257 case CMD_SET_ARRAY_REF:
10258 err = array_commands (command, p, end, &buf);
10260 case CMD_SET_STRING_REF:
10261 err = string_commands (command, p, end, &buf);
10263 case CMD_SET_OBJECT_REF:
10264 err = object_commands (command, p, end, &buf);
10267 err = ERR_NOT_IMPLEMENTED;
10270 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
10271 buffer_replies = TRUE;
10275 if (buffer_replies) {
10276 buffer_reply_packet (id, err, &buf);
10278 send_reply_packet (id, err, &buf);
10279 //DEBUG_PRINTF (1, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000);
10283 if (err == ERR_NONE && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
10284 send_buffered_reply_packets ();
10285 buffer_replies = FALSE;
10289 buffer_free (&buf);
10291 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
10295 mono_set_is_debugger_attached (FALSE);
10297 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
10298 debugger_thread_exited = TRUE;
10299 mono_coop_cond_signal (&debugger_thread_exited_cond);
10300 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
10302 DEBUG_PRINTF (1, "[dbg] Debugger thread exited.\n");
10304 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
10305 DEBUG_PRINTF (2, "[dbg] Detached - restarting clean debugger thread.\n");
10306 start_debugger_thread ();
10312 #else /* DISABLE_DEBUGGER_AGENT */
10315 mono_debugger_agent_parse_options (char *options)
10317 g_error ("This runtime is configured with the debugger agent disabled.");
10321 mono_debugger_agent_init (void)
10326 mono_debugger_agent_breakpoint_hit (void *sigctx)
10331 mono_debugger_agent_single_step_event (void *sigctx)
10336 mono_debugger_agent_free_domain_info (MonoDomain *domain)
10341 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
10342 MonoContext *catch_ctx)
10347 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
10352 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
10357 mono_debugger_agent_user_break (void)
10363 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
10368 mono_debugger_agent_debug_log_is_enabled (void)
10374 mono_debugger_agent_unhandled_exception (MonoException *exc)
10376 g_assert_not_reached ();
10380 debugger_agent_single_step_from_context (MonoContext *ctx)
10382 g_assert_not_reached ();
10386 debugger_agent_breakpoint_from_context (MonoContext *ctx)
10388 g_assert_not_reached ();