2 * debugger-agent.c: Soft Debugger back-end module
5 * Zoltan Varga (vargaz@gmail.com)
7 * Copyright 2009-2010 Novell, Inc.
8 * Copyright 2011 Xamarin Inc.
9 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
16 #ifdef HAVE_SYS_TYPES_H
17 #include <sys/types.h>
19 #ifdef HAVE_SYS_SELECT_H
20 #include <sys/select.h>
22 #ifdef HAVE_SYS_SOCKET_H
23 #include <sys/socket.h>
25 #ifdef HAVE_NETINET_TCP_H
26 #include <netinet/tcp.h>
28 #ifdef HAVE_NETINET_IN_H
29 #include <netinet/in.h>
49 #ifdef PLATFORM_ANDROID
51 #include <linux/tcp.h>
52 #include <sys/endian.h>
55 #include <mono/metadata/mono-debug.h>
56 #include <mono/metadata/mono-debug-debugger.h>
57 #include <mono/metadata/debug-mono-symfile.h>
58 #include <mono/metadata/gc-internals.h>
59 #include <mono/metadata/environment.h>
60 #include <mono/metadata/threads-types.h>
61 #include <mono/metadata/threadpool-ms.h>
62 #include <mono/metadata/socket-io.h>
63 #include <mono/metadata/assembly.h>
64 #include <mono/metadata/runtime.h>
65 #include <mono/metadata/verify-internals.h>
66 #include <mono/metadata/reflection-internals.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 "debugger-agent.h"
76 #include "seq-points.h"
79 * On iOS we can't use System.Environment.Exit () as it will do the wrong
82 #if !defined (TARGET_IOS)
83 #define TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
87 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
88 #define DISABLE_DEBUGGER_AGENT 1
91 #ifdef DISABLE_SOFT_DEBUG
92 #define DISABLE_DEBUGGER_AGENT 1
95 #ifndef DISABLE_DEBUGGER_AGENT
97 #include <mono/utils/mono-os-mutex.h>
99 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
122 guint32 il_offset, native_offset;
126 * If method is gshared, this is the actual instance, otherwise this is equal to
129 MonoMethod *actual_method;
131 * This is the method which is visible to debugger clients. Same as method,
132 * except for native-to-managed wrappers.
134 MonoMethod *api_method;
136 MonoDebugMethodJitInfo *jit;
139 mgreg_t *reg_locations [MONO_MAX_IREGS];
141 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
142 * the frame can become invalid.
147 typedef struct _InvokeData InvokeData;
155 /* This is the context which needs to be restored after the invoke */
159 * If this is set, invoke this method with the arguments given by ARGS.
163 guint32 suspend_count;
166 InvokeData *last_invoke;
170 MonoThreadUnwindState context;
172 /* This is computed on demand when it is requested using the wire protocol */
173 /* It is freed up when the thread is resumed */
177 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
180 gboolean frames_up_to_date;
182 * Points to data about a pending invoke which needs to be executed after the thread
185 InvokeData *pending_invoke;
187 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
192 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
193 * within a finite amount of time.
197 * Set to TRUE if this thread is suspended in suspend_current ().
199 gboolean really_suspended;
200 /* Used to pass the context to the breakpoint/single step handler */
201 MonoContext handler_ctx;
202 /* Whenever thread_stop () was called for this thread */
205 /* Whenever to disable breakpoints (used during invokes) */
206 gboolean disable_breakpoints;
209 * Number of times this thread has been resumed using resume_thread ().
211 guint32 resume_count;
213 MonoInternalThread *thread;
216 * Information about the frame which transitioned to native code for running
219 StackFrameInfo async_last_frame;
222 * The context where the stack walk can be started for running threads.
224 MonoThreadUnwindState async_state;
227 * The context used for filter clauses
229 MonoThreadUnwindState filter_state;
231 gboolean abort_requested;
234 * The current mono_runtime_invoke_checked invocation.
239 * The context where single stepping should resume while the thread is suspended because
240 * of an EXCEPTION event.
242 MonoThreadUnwindState catch_state;
245 * The context which needs to be restored after handling a single step/breakpoint
246 * event. This is the same as the ctx at step/breakpoint site, but includes changes
247 * to caller saved registers done by set_var ().
249 MonoThreadUnwindState restore_state;
250 /* Frames computed from restore_state */
251 int restore_frame_count;
252 StackFrame **restore_frames;
254 /* The currently unloading appdomain */
255 MonoDomain *domain_unloading;
260 void (*connect) (const char *address);
261 void (*close1) (void);
262 void (*close2) (void);
263 gboolean (*send) (void *buf, int len);
264 int (*recv) (void *buf, int len);
268 * Wire Protocol definitions
271 #define HEADER_LENGTH 11
273 #define MAJOR_VERSION 2
274 #define MINOR_VERSION 42
278 CMD_SET_OBJECT_REF = 9,
279 CMD_SET_STRING_REF = 10,
281 CMD_SET_ARRAY_REF = 13,
282 CMD_SET_EVENT_REQUEST = 15,
283 CMD_SET_STACK_FRAME = 16,
284 CMD_SET_APPDOMAIN = 20,
285 CMD_SET_ASSEMBLY = 21,
294 EVENT_KIND_VM_START = 0,
295 EVENT_KIND_VM_DEATH = 1,
296 EVENT_KIND_THREAD_START = 2,
297 EVENT_KIND_THREAD_DEATH = 3,
298 EVENT_KIND_APPDOMAIN_CREATE = 4,
299 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
300 EVENT_KIND_METHOD_ENTRY = 6,
301 EVENT_KIND_METHOD_EXIT = 7,
302 EVENT_KIND_ASSEMBLY_LOAD = 8,
303 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
304 EVENT_KIND_BREAKPOINT = 10,
305 EVENT_KIND_STEP = 11,
306 EVENT_KIND_TYPE_LOAD = 12,
307 EVENT_KIND_EXCEPTION = 13,
308 EVENT_KIND_KEEPALIVE = 14,
309 EVENT_KIND_USER_BREAK = 15,
310 EVENT_KIND_USER_LOG = 16
314 SUSPEND_POLICY_NONE = 0,
315 SUSPEND_POLICY_EVENT_THREAD = 1,
316 SUSPEND_POLICY_ALL = 2
321 ERR_INVALID_OBJECT = 20,
322 ERR_INVALID_FIELDID = 25,
323 ERR_INVALID_FRAMEID = 30,
324 ERR_NOT_IMPLEMENTED = 100,
325 ERR_NOT_SUSPENDED = 101,
326 ERR_INVALID_ARGUMENT = 102,
328 ERR_NO_INVOCATION = 104,
329 ERR_ABSENT_INFORMATION = 105,
330 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
331 ERR_INVOKE_ABORTED = 107,
332 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
337 MOD_KIND_THREAD_ONLY = 3,
338 MOD_KIND_LOCATION_ONLY = 7,
339 MOD_KIND_EXCEPTION_ONLY = 8,
341 MOD_KIND_ASSEMBLY_ONLY = 11,
342 MOD_KIND_SOURCE_FILE_ONLY = 12,
343 MOD_KIND_TYPE_NAME_ONLY = 13,
359 STEP_FILTER_NONE = 0,
360 STEP_FILTER_STATIC_CTOR = 1,
361 STEP_FILTER_DEBUGGER_HIDDEN = 2,
362 STEP_FILTER_DEBUGGER_STEP_THROUGH = 4,
363 STEP_FILTER_DEBUGGER_NON_USER_CODE = 8
367 TOKEN_TYPE_STRING = 0,
369 TOKEN_TYPE_FIELD = 2,
370 TOKEN_TYPE_METHOD = 3,
371 TOKEN_TYPE_UNKNOWN = 4
375 VALUE_TYPE_ID_NULL = 0xf0,
376 VALUE_TYPE_ID_TYPE = 0xf1,
377 VALUE_TYPE_ID_PARENT_VTYPE = 0xf2
381 FRAME_FLAG_DEBUGGER_INVOKE = 1,
382 FRAME_FLAG_NATIVE_TRANSITION = 2
386 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
387 INVOKE_FLAG_SINGLE_THREADED = 2,
388 INVOKE_FLAG_RETURN_OUT_THIS = 4,
389 INVOKE_FLAG_RETURN_OUT_ARGS = 8,
390 INVOKE_FLAG_VIRTUAL = 16
394 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
395 } BindingFlagsExtensions;
399 CMD_VM_ALL_THREADS = 2,
404 CMD_VM_INVOKE_METHOD = 7,
405 CMD_VM_SET_PROTOCOL_VERSION = 8,
406 CMD_VM_ABORT_INVOKE = 9,
407 CMD_VM_SET_KEEPALIVE = 10,
408 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
409 CMD_VM_GET_TYPES = 12,
410 CMD_VM_INVOKE_METHODS = 13,
411 CMD_VM_START_BUFFERING = 14,
412 CMD_VM_STOP_BUFFERING = 15
416 CMD_THREAD_GET_FRAME_INFO = 1,
417 CMD_THREAD_GET_NAME = 2,
418 CMD_THREAD_GET_STATE = 3,
419 CMD_THREAD_GET_INFO = 4,
420 CMD_THREAD_GET_ID = 5,
421 CMD_THREAD_GET_TID = 6,
422 CMD_THREAD_SET_IP = 7
426 CMD_EVENT_REQUEST_SET = 1,
427 CMD_EVENT_REQUEST_CLEAR = 2,
428 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
436 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
437 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
438 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
439 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
440 CMD_APPDOMAIN_CREATE_STRING = 5,
441 CMD_APPDOMAIN_GET_CORLIB = 6,
442 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
446 CMD_ASSEMBLY_GET_LOCATION = 1,
447 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
448 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
449 CMD_ASSEMBLY_GET_OBJECT = 4,
450 CMD_ASSEMBLY_GET_TYPE = 5,
451 CMD_ASSEMBLY_GET_NAME = 6
455 CMD_MODULE_GET_INFO = 1,
459 CMD_FIELD_GET_INFO = 1,
463 CMD_METHOD_GET_NAME = 1,
464 CMD_METHOD_GET_DECLARING_TYPE = 2,
465 CMD_METHOD_GET_DEBUG_INFO = 3,
466 CMD_METHOD_GET_PARAM_INFO = 4,
467 CMD_METHOD_GET_LOCALS_INFO = 5,
468 CMD_METHOD_GET_INFO = 6,
469 CMD_METHOD_GET_BODY = 7,
470 CMD_METHOD_RESOLVE_TOKEN = 8,
471 CMD_METHOD_GET_CATTRS = 9,
472 CMD_METHOD_MAKE_GENERIC_METHOD = 10
476 CMD_TYPE_GET_INFO = 1,
477 CMD_TYPE_GET_METHODS = 2,
478 CMD_TYPE_GET_FIELDS = 3,
479 CMD_TYPE_GET_VALUES = 4,
480 CMD_TYPE_GET_OBJECT = 5,
481 CMD_TYPE_GET_SOURCE_FILES = 6,
482 CMD_TYPE_SET_VALUES = 7,
483 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
484 CMD_TYPE_GET_PROPERTIES = 9,
485 CMD_TYPE_GET_CATTRS = 10,
486 CMD_TYPE_GET_FIELD_CATTRS = 11,
487 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
488 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
489 CMD_TYPE_GET_VALUES_2 = 14,
490 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
491 CMD_TYPE_GET_INTERFACES = 16,
492 CMD_TYPE_GET_INTERFACE_MAP = 17,
493 CMD_TYPE_IS_INITIALIZED = 18,
494 CMD_TYPE_CREATE_INSTANCE = 19
498 CMD_STACK_FRAME_GET_VALUES = 1,
499 CMD_STACK_FRAME_GET_THIS = 2,
500 CMD_STACK_FRAME_SET_VALUES = 3,
501 CMD_STACK_FRAME_GET_DOMAIN = 4,
505 CMD_ARRAY_REF_GET_LENGTH = 1,
506 CMD_ARRAY_REF_GET_VALUES = 2,
507 CMD_ARRAY_REF_SET_VALUES = 3,
511 CMD_STRING_REF_GET_VALUE = 1,
512 CMD_STRING_REF_GET_LENGTH = 2,
513 CMD_STRING_REF_GET_CHARS = 3
517 CMD_OBJECT_REF_GET_TYPE = 1,
518 CMD_OBJECT_REF_GET_VALUES = 2,
519 CMD_OBJECT_REF_IS_COLLECTED = 3,
520 CMD_OBJECT_REF_GET_ADDRESS = 4,
521 CMD_OBJECT_REF_GET_DOMAIN = 5,
522 CMD_OBJECT_REF_SET_VALUES = 6,
523 CMD_OBJECT_REF_GET_INFO = 7,
529 int count; /* For kind == MOD_KIND_COUNT */
530 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
531 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
532 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
533 GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
534 GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
535 StepFilter filter; /* For kind == MOD_KIND_STEP */
537 gboolean caught, uncaught, subclasses; /* For kind == MOD_KIND_EXCEPTION_ONLY */
546 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
550 * Describes a single step request.
554 MonoInternalThread *thread;
560 MonoMethod *start_method;
561 MonoMethod *last_method;
563 /* Whenever single stepping is performed using start/stop_single_stepping () */
565 /* The list of breakpoints used to implement step-over */
567 /* The number of frames at the start of a step-over */
572 * Contains additional information for an event
575 /* For EVENT_KIND_EXCEPTION */
577 MonoContext catch_ctx;
579 /* For EVENT_KIND_USER_LOG */
581 char *category, *message;
582 /* For EVENT_KIND_TYPE_LOAD */
586 /* Dummy structure used for the profiler callbacks */
592 guint8 *buf, *p, *end;
595 typedef struct ReplyPacket {
601 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
603 #ifdef PLATFORM_ANDROID
604 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { g_print (__VA_ARGS__); } } while (0)
606 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { fprintf (log_file, __VA_ARGS__); fflush (log_file); } } while (0)
610 #define get_last_sock_error() WSAGetLastError()
611 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
612 #define MONO_EINTR WSAEINTR
614 #define get_last_sock_error() errno
615 #define MONO_EWOULDBLOCK EWOULDBLOCK
616 #define MONO_EINTR EINTR
619 #define CHECK_PROTOCOL_VERSION(major,minor) \
620 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
626 static AgentConfig agent_config;
629 * Whenever the agent is fully initialized.
630 * When using the onuncaught or onthrow options, only some parts of the agent are
631 * initialized on startup, and the full initialization which includes connection
632 * establishment and the startup of the agent thread is only done in response to
635 static gint32 inited;
637 #ifndef DISABLE_SOCKET_TRANSPORT
639 static int listen_fd;
642 static int packet_id = 0;
644 static int objref_id = 0;
646 static int event_request_id = 0;
648 static int frame_id = 0;
650 static GPtrArray *event_requests;
652 static MonoNativeTlsKey debugger_tls_id;
654 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
656 /* Maps MonoInternalThread -> DebuggerTlsData */
657 /* Protected by the loader lock */
658 static MonoGHashTable *thread_to_tls;
660 /* Maps tid -> MonoInternalThread */
661 /* Protected by the loader lock */
662 static MonoGHashTable *tid_to_thread;
664 /* Maps tid -> MonoThread (not MonoInternalThread) */
665 /* Protected by the loader lock */
666 static MonoGHashTable *tid_to_thread_obj;
668 static MonoNativeThreadId debugger_thread_id;
670 static HANDLE debugger_thread_handle;
672 static int log_level;
674 static gboolean embedding;
676 static FILE *log_file;
678 /* Assemblies whose assembly load event has no been sent yet */
679 /* Protected by the dbg lock */
680 static GPtrArray *pending_assembly_loads;
682 /* Whenever the debugger thread has exited */
683 static gboolean debugger_thread_exited;
685 /* Cond variable used to wait for debugger_thread_exited becoming true */
686 static MonoCoopCond debugger_thread_exited_cond;
688 /* Mutex for the cond var above */
689 static MonoCoopMutex debugger_thread_exited_mutex;
691 static DebuggerProfiler debugger_profiler;
693 /* The single step request instance */
694 static SingleStepReq *ss_req;
696 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
697 /* Number of single stepping operations in progress */
701 /* The protocol version of the client */
702 static int major_version, minor_version;
704 /* Whenever the variables above are set by the client */
705 static gboolean protocol_version_set;
707 /* A hash table containing all active domains */
708 /* Protected by the loader lock */
709 static GHashTable *domains;
711 /* The number of times the runtime is suspended */
712 static gint32 suspend_count;
714 /* Whenever to buffer reply messages and send them together */
715 static gboolean buffer_replies;
717 /* Buffered reply packets */
718 static ReplyPacket reply_packets [128];
721 #define dbg_lock() mono_coop_mutex_lock (&debug_mutex)
722 #define dbg_unlock() mono_coop_mutex_unlock (&debug_mutex)
723 static MonoCoopMutex debug_mutex;
725 static void transport_init (void);
726 static void transport_connect (const char *address);
727 static gboolean transport_handshake (void);
728 static void register_transport (DebuggerTransport *trans);
730 static guint32 WINAPI debugger_thread (void *arg);
732 static void runtime_initialized (MonoProfiler *prof);
734 static void runtime_shutdown (MonoProfiler *prof);
736 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
738 static void thread_end (MonoProfiler *prof, uintptr_t tid);
740 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
742 static void appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain);
744 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
746 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
748 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
750 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
752 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
754 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
756 static void emit_assembly_load (gpointer assembly, gpointer user_data);
758 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
760 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
762 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
764 static void start_single_stepping (void);
766 static void stop_single_stepping (void);
768 static void suspend_current (void);
770 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
772 static void clear_types_for_assembly (MonoAssembly *assembly);
774 static void clear_breakpoints_for_domain (MonoDomain *domain);
776 static void process_profiler_event (EventKind event, gpointer arg);
778 /* Submodule init/cleanup */
779 static void breakpoints_init (void);
780 static void breakpoints_cleanup (void);
782 static void objrefs_init (void);
783 static void objrefs_cleanup (void);
785 static void ids_init (void);
786 static void ids_cleanup (void);
788 static void suspend_init (void);
790 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch,
791 StackFrame **frames, int nframes);
792 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req);
793 static void ss_destroy (SingleStepReq *req);
795 static void start_debugger_thread (void);
796 static void stop_debugger_thread (void);
798 static void finish_agent_init (gboolean on_startup);
800 static void process_profiler_event (EventKind event, gpointer arg);
802 static void invalidate_frames (DebuggerTlsData *tls);
804 #ifndef DISABLE_SOCKET_TRANSPORT
806 register_socket_transport (void);
809 static inline gboolean
810 is_debugger_thread (void)
812 return mono_native_thread_id_equals (mono_native_thread_id_get (), debugger_thread_id);
816 parse_address (char *address, char **host, int *port)
818 char *pos = strchr (address, ':');
820 if (pos == NULL || pos == address)
823 *host = (char *)g_malloc (pos - address + 1);
824 strncpy (*host, address, pos - address);
825 (*host) [pos - address] = '\0';
827 *port = atoi (pos + 1);
835 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
836 fprintf (stderr, "Available options:\n");
837 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
838 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
839 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
840 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
841 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
842 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
843 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
844 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
845 fprintf (stderr, " setpgid=y/n\t\t\tWhether to call setpid(0, 0) after startup.\n");
846 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
850 parse_flag (const char *option, char *flag)
852 if (!strcmp (flag, "y"))
854 else if (!strcmp (flag, "n"))
857 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
864 mono_debugger_agent_parse_options (char *options)
871 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
872 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
876 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
878 options = g_strdup_printf ("%s,%s", options, extra);
880 agent_config.enabled = TRUE;
881 agent_config.suspend = TRUE;
882 agent_config.server = FALSE;
883 agent_config.defer = FALSE;
884 agent_config.address = NULL;
886 //agent_config.log_level = 10;
888 args = g_strsplit (options, ",", -1);
889 for (ptr = args; ptr && *ptr; ptr ++) {
892 if (strncmp (arg, "transport=", 10) == 0) {
893 agent_config.transport = g_strdup (arg + 10);
894 } else if (strncmp (arg, "address=", 8) == 0) {
895 agent_config.address = g_strdup (arg + 8);
896 } else if (strncmp (arg, "loglevel=", 9) == 0) {
897 agent_config.log_level = atoi (arg + 9);
898 } else if (strncmp (arg, "logfile=", 8) == 0) {
899 agent_config.log_file = g_strdup (arg + 8);
900 } else if (strncmp (arg, "suspend=", 8) == 0) {
901 agent_config.suspend = parse_flag ("suspend", arg + 8);
902 } else if (strncmp (arg, "server=", 7) == 0) {
903 agent_config.server = parse_flag ("server", arg + 7);
904 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
905 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
906 } else if (strncmp (arg, "onthrow=", 8) == 0) {
907 /* We support multiple onthrow= options */
908 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
909 } else if (strncmp (arg, "onthrow", 7) == 0) {
910 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
911 } else if (strncmp (arg, "help", 4) == 0) {
914 } else if (strncmp (arg, "timeout=", 8) == 0) {
915 agent_config.timeout = atoi (arg + 8);
916 } else if (strncmp (arg, "launch=", 7) == 0) {
917 agent_config.launch = g_strdup (arg + 7);
918 } else if (strncmp (arg, "embedding=", 10) == 0) {
919 agent_config.embedding = atoi (arg + 10) == 1;
920 } else if (strncmp (arg, "keepalive=", 10) == 0) {
921 agent_config.keepalive = atoi (arg + 10);
922 } else if (strncmp (arg, "setpgid=", 8) == 0) {
923 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
930 if (agent_config.server && !agent_config.suspend) {
931 /* Waiting for deferred attachment */
932 agent_config.defer = TRUE;
933 if (agent_config.address == NULL) {
934 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (getpid () % 1000));
938 //agent_config.log_level = 0;
940 if (agent_config.transport == NULL) {
941 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
945 if (agent_config.address == NULL && !agent_config.server) {
946 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
951 if (!strcmp (agent_config.transport, "dt_socket")) {
952 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
953 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
960 mono_debugger_agent_init (void)
962 mono_coop_mutex_init_recursive (&debug_mutex);
964 if (!agent_config.enabled)
969 /* Need to know whenever a thread has acquired the loader mutex */
970 mono_loader_lock_track_ownership (TRUE);
972 event_requests = g_ptr_array_new ();
974 mono_coop_mutex_init (&debugger_thread_exited_mutex);
975 mono_coop_cond_init (&debugger_thread_exited_cond);
977 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
978 mono_profiler_set_events ((MonoProfileFlags)(MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS));
979 mono_profiler_install_runtime_initialized (runtime_initialized);
980 mono_profiler_install_appdomain (NULL, appdomain_load, appdomain_start_unload, appdomain_unload);
981 mono_profiler_install_thread (thread_startup, thread_end);
982 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
983 mono_profiler_install_jit_end (jit_end);
985 mono_native_tls_alloc (&debugger_tls_id, NULL);
987 /* Needed by the hash_table_new_type () call below */
988 mono_gc_base_init ();
990 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_DEBUGGER, "thread-to-tls table");
991 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls, MONO_ROOT_SOURCE_DEBUGGER, "thread-to-tls table");
993 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread table");
994 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread table");
996 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");
997 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread object table");
999 pending_assembly_loads = g_ptr_array_new ();
1000 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
1002 log_level = agent_config.log_level;
1004 embedding = agent_config.embedding;
1005 disconnected = TRUE;
1007 if (agent_config.log_file) {
1008 log_file = fopen (agent_config.log_file, "w+");
1010 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
1019 breakpoints_init ();
1022 mini_get_debug_options ()->gen_sdb_seq_points = TRUE;
1024 * This is needed because currently we don't handle liveness info.
1026 mini_get_debug_options ()->mdb_optimizations = TRUE;
1028 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
1029 /* This is needed because we can't set local variables in registers yet */
1030 mono_disable_optimizations (MONO_OPT_LINEARS);
1034 * The stack walk done from thread_interrupt () needs to be signal safe, but it
1035 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
1036 * safe (#3411). So load AOT info eagerly when the debugger is running as a
1039 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
1042 if (agent_config.setpgid)
1046 if (!agent_config.onuncaught && !agent_config.onthrow)
1047 finish_agent_init (TRUE);
1051 * finish_agent_init:
1053 * Finish the initialization of the agent. This involves connecting the transport
1054 * and starting the agent thread. This is either done at startup, or
1055 * in response to some event like an unhandled exception.
1058 finish_agent_init (gboolean on_startup)
1062 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
1065 if (agent_config.launch) {
1068 // FIXME: Generated address
1069 // FIXME: Races with transport_connect ()
1071 argv [0] = agent_config.launch;
1072 argv [1] = agent_config.transport;
1073 argv [2] = agent_config.address;
1076 res = g_spawn_async_with_pipes (NULL, argv, NULL, (GSpawnFlags)0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1078 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1083 transport_connect (agent_config.address);
1086 /* Do some which is usually done after sending the VMStart () event */
1087 vm_start_event_sent = TRUE;
1088 start_debugger_thread ();
1093 mono_debugger_agent_cleanup (void)
1098 stop_debugger_thread ();
1100 breakpoints_cleanup ();
1109 #ifndef DISABLE_SOCKET_TRANSPORT
1114 * recv() + handle incomplete reads and EINTR
1117 socket_transport_recv (void *buf, int len)
1123 static gint64 last_keepalive;
1130 res = recv (fd, (char *) buf + total, len - total, flags);
1133 if (agent_config.keepalive) {
1134 gboolean need_keepalive = FALSE;
1135 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1136 need_keepalive = TRUE;
1137 } else if (res == -1) {
1138 /* This could happen if recv () is interrupted repeatedly */
1139 msecs = mono_msec_ticks ();
1140 if (msecs - last_keepalive >= agent_config.keepalive) {
1141 need_keepalive = TRUE;
1142 last_keepalive = msecs;
1145 if (need_keepalive) {
1146 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1150 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1158 set_keepalive (void)
1163 if (!agent_config.keepalive || !conn_fd)
1166 tv.tv_sec = agent_config.keepalive / 1000;
1167 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1169 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1170 g_assert (result >= 0);
1174 socket_transport_accept (int socket_fd)
1177 conn_fd = accept (socket_fd, NULL, NULL);
1180 if (conn_fd == -1) {
1181 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1183 DEBUG_PRINTF (1, "Accepted connection from client, connection fd=%d.\n", conn_fd);
1190 socket_transport_send (void *data, int len)
1197 res = send (conn_fd, data, len, 0);
1198 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1209 * socket_transport_connect:
1211 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1214 socket_transport_connect (const char *address)
1216 MonoAddressInfo *result;
1217 MonoAddressEntry *rp;
1218 int sfd = -1, s, res;
1222 if (agent_config.address) {
1223 res = parse_address (agent_config.address, &host, &port);
1224 g_assert (res == 0);
1235 mono_network_init ();
1237 /* Obtain address(es) matching host/port */
1238 s = mono_get_address_info (host, port, MONO_HINT_UNSPECIFIED, &result);
1240 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, s); // FIXME add portable error conversion functions
1245 if (agent_config.server) {
1246 /* Wait for a connection */
1248 struct sockaddr_in addr;
1251 /* No address, generate one */
1252 sfd = socket (AF_INET, SOCK_STREAM, 0);
1255 /* This will bind the socket to a random port */
1256 res = listen (sfd, 16);
1258 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1263 addrlen = sizeof (addr);
1264 memset (&addr, 0, sizeof (addr));
1265 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1266 g_assert (res == 0);
1268 host = (char*)"127.0.0.1";
1269 port = ntohs (addr.sin_port);
1271 /* Emit the address to stdout */
1272 /* FIXME: Should print another interface, not localhost */
1273 printf ("%s:%d\n", host, port);
1275 /* Listen on the provided address */
1276 for (rp = result->entries; rp != NULL; rp = rp->next) {
1277 MonoSocketAddress sockaddr;
1281 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1283 sfd = socket (rp->family, rp->socktype,
1288 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1291 res = bind (sfd, &sockaddr.addr, sock_len);
1295 res = listen (sfd, 16);
1302 mono_free_address_info (result);
1305 if (agent_config.defer)
1308 DEBUG_PRINTF (1, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout);
1310 if (agent_config.timeout) {
1315 tv.tv_usec = agent_config.timeout * 1000;
1317 FD_SET (sfd, &readfds);
1320 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1324 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1329 conn_fd = socket_transport_accept (sfd);
1333 DEBUG_PRINTF (1, "Accepted connection from client, socket fd=%d.\n", conn_fd);
1335 /* Connect to the specified address */
1336 /* FIXME: Respect the timeout */
1337 for (rp = result->entries; rp != NULL; rp = rp->next) {
1338 MonoSocketAddress sockaddr;
1341 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1343 sfd = socket (rp->family, rp->socktype,
1349 res = connect (sfd, &sockaddr.addr, sock_len);
1353 break; /* Success */
1361 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1367 mono_free_address_info (result);
1370 if (!transport_handshake ())
1375 socket_transport_close1 (void)
1377 /* This will interrupt the agent thread */
1378 /* Close the read part only so it can still send back replies */
1379 /* Also shut down the connection listener so that we can exit normally */
1381 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1382 shutdown (conn_fd, SD_BOTH);
1383 shutdown (listen_fd, SD_BOTH);
1384 closesocket (listen_fd);
1386 shutdown (conn_fd, SHUT_RD);
1387 shutdown (listen_fd, SHUT_RDWR);
1395 socket_transport_close2 (void)
1398 shutdown (conn_fd, SD_BOTH);
1400 shutdown (conn_fd, SHUT_RDWR);
1405 register_socket_transport (void)
1407 DebuggerTransport trans;
1409 trans.name = "dt_socket";
1410 trans.connect = socket_transport_connect;
1411 trans.close1 = socket_transport_close1;
1412 trans.close2 = socket_transport_close2;
1413 trans.send = socket_transport_send;
1414 trans.recv = socket_transport_recv;
1416 register_transport (&trans);
1420 * socket_fd_transport_connect:
1424 socket_fd_transport_connect (const char *address)
1428 res = sscanf (address, "%d", &conn_fd);
1430 fprintf (stderr, "debugger-agent: socket-fd transport address is invalid: '%s'\n", address);
1434 if (!transport_handshake ())
1439 register_socket_fd_transport (void)
1441 DebuggerTransport trans;
1443 /* This is the same as the 'dt_socket' transport, but receives an already connected socket fd */
1444 trans.name = "socket-fd";
1445 trans.connect = socket_fd_transport_connect;
1446 trans.close1 = socket_transport_close1;
1447 trans.close2 = socket_transport_close2;
1448 trans.send = socket_transport_send;
1449 trans.recv = socket_transport_recv;
1451 register_transport (&trans);
1454 #endif /* DISABLE_SOCKET_TRANSPORT */
1460 #define MAX_TRANSPORTS 16
1462 static DebuggerTransport *transport;
1464 static DebuggerTransport transports [MAX_TRANSPORTS];
1465 static int ntransports;
1468 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1471 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1473 register_transport (trans);
1477 register_transport (DebuggerTransport *trans)
1479 g_assert (ntransports < MAX_TRANSPORTS);
1481 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1486 transport_init (void)
1490 #ifndef DISABLE_SOCKET_TRANSPORT
1491 register_socket_transport ();
1492 register_socket_fd_transport ();
1495 for (i = 0; i < ntransports; ++i) {
1496 if (!strcmp (agent_config.transport, transports [i].name))
1499 if (i == ntransports) {
1500 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1501 for (i = 0; i < ntransports; ++i)
1502 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1503 fprintf (stderr, "\n");
1506 transport = &transports [i];
1510 transport_connect (const char *address)
1512 transport->connect (address);
1516 transport_close1 (void)
1518 transport->close1 ();
1522 transport_close2 (void)
1524 transport->close2 ();
1528 transport_send (void *buf, int len)
1530 return transport->send (buf, len);
1534 transport_recv (void *buf, int len)
1536 return transport->recv (buf, len);
1540 mono_debugger_agent_transport_handshake (void)
1542 return transport_handshake ();
1546 transport_handshake (void)
1548 char handshake_msg [128];
1552 disconnected = TRUE;
1554 /* Write handshake message */
1555 sprintf (handshake_msg, "DWP-Handshake");
1558 res = transport_send (handshake_msg, strlen (handshake_msg));
1559 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1561 g_assert (res != -1);
1564 res = transport_recv (buf, strlen (handshake_msg));
1565 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg)) != 0)) {
1566 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1571 * To support older clients, the client sends its protocol version after connecting
1572 * using a command. Until that is received, default to our protocol version.
1574 major_version = MAJOR_VERSION;
1575 minor_version = MINOR_VERSION;
1576 protocol_version_set = FALSE;
1578 #ifndef DISABLE_SOCKET_TRANSPORT
1579 // FIXME: Move this somewhere else
1581 * Set TCP_NODELAY on the socket so the client receives events/command
1582 * results immediately.
1586 int result = setsockopt (conn_fd,
1591 g_assert (result >= 0);
1597 disconnected = FALSE;
1602 stop_debugger_thread (void)
1607 transport_close1 ();
1610 * Wait for the thread to exit.
1612 * If we continue with the shutdown without waiting for it, then the client might
1613 * not receive an answer to its last command like a resume.
1615 if (!is_debugger_thread ()) {
1617 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
1618 if (!debugger_thread_exited)
1619 mono_coop_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1620 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
1621 } while (!debugger_thread_exited);
1624 transport_close2 ();
1628 start_debugger_thread (void)
1630 debugger_thread_handle = mono_threads_create_thread (debugger_thread, NULL, 0, 0, NULL);
1631 g_assert (debugger_thread_handle);
1635 * Functions to decode protocol data
1639 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1642 g_assert (*endbuf <= limit);
1647 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1650 g_assert (*endbuf <= limit);
1652 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1655 static inline gint64
1656 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1658 guint32 high = decode_int (buf, &buf, limit);
1659 guint32 low = decode_int (buf, &buf, limit);
1663 return ((((guint64)high) << 32) | ((guint64)low));
1667 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1669 return decode_int (buf, endbuf, limit);
1673 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1675 int len = decode_int (buf, &buf, limit);
1683 s = (char *)g_malloc (len + 1);
1686 memcpy (s, buf, len);
1695 * Functions to encode protocol data
1699 buffer_init (Buffer *buf, int size)
1701 buf->buf = (guint8 *)g_malloc (size);
1703 buf->end = buf->buf + size;
1707 buffer_len (Buffer *buf)
1709 return buf->p - buf->buf;
1713 buffer_make_room (Buffer *buf, int size)
1715 if (buf->end - buf->p < size) {
1716 int new_size = buf->end - buf->buf + size + 32;
1717 guint8 *p = (guint8 *)g_realloc (buf->buf, new_size);
1718 size = buf->p - buf->buf;
1721 buf->end = buf->buf + new_size;
1726 buffer_add_byte (Buffer *buf, guint8 val)
1728 buffer_make_room (buf, 1);
1734 buffer_add_short (Buffer *buf, guint32 val)
1736 buffer_make_room (buf, 2);
1737 buf->p [0] = (val >> 8) & 0xff;
1738 buf->p [1] = (val >> 0) & 0xff;
1743 buffer_add_int (Buffer *buf, guint32 val)
1745 buffer_make_room (buf, 4);
1746 buf->p [0] = (val >> 24) & 0xff;
1747 buf->p [1] = (val >> 16) & 0xff;
1748 buf->p [2] = (val >> 8) & 0xff;
1749 buf->p [3] = (val >> 0) & 0xff;
1754 buffer_add_long (Buffer *buf, guint64 l)
1756 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1757 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1761 buffer_add_id (Buffer *buf, int id)
1763 buffer_add_int (buf, (guint64)id);
1767 buffer_add_data (Buffer *buf, guint8 *data, int len)
1769 buffer_make_room (buf, len);
1770 memcpy (buf->p, data, len);
1775 buffer_add_string (Buffer *buf, const char *str)
1780 buffer_add_int (buf, 0);
1783 buffer_add_int (buf, len);
1784 buffer_add_data (buf, (guint8*)str, len);
1789 buffer_add_buffer (Buffer *buf, Buffer *data)
1791 buffer_add_data (buf, data->buf, buffer_len (data));
1795 buffer_free (Buffer *buf)
1801 send_packet (int command_set, int command, Buffer *data)
1807 id = InterlockedIncrement (&packet_id);
1809 len = data->p - data->buf + 11;
1810 buffer_init (&buf, len);
1811 buffer_add_int (&buf, len);
1812 buffer_add_int (&buf, id);
1813 buffer_add_byte (&buf, 0); /* flags */
1814 buffer_add_byte (&buf, command_set);
1815 buffer_add_byte (&buf, command);
1816 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1818 res = transport_send (buf.buf, len);
1826 send_reply_packets (int npackets, ReplyPacket *packets)
1833 for (i = 0; i < npackets; ++i)
1834 len += buffer_len (packets [i].data) + 11;
1835 buffer_init (&buf, len);
1836 for (i = 0; i < npackets; ++i) {
1837 buffer_add_int (&buf, buffer_len (packets [i].data) + 11);
1838 buffer_add_int (&buf, packets [i].id);
1839 buffer_add_byte (&buf, 0x80); /* flags */
1840 buffer_add_byte (&buf, (packets [i].error >> 8) & 0xff);
1841 buffer_add_byte (&buf, packets [i].error);
1842 buffer_add_buffer (&buf, packets [i].data);
1845 res = transport_send (buf.buf, len);
1853 send_reply_packet (int id, int error, Buffer *data)
1857 memset (&packet, 0, sizeof (ReplyPacket));
1859 packet.error = error;
1862 return send_reply_packets (1, &packet);
1866 send_buffered_reply_packets (void)
1870 send_reply_packets (nreply_packets, reply_packets);
1871 for (i = 0; i < nreply_packets; ++i)
1872 buffer_free (reply_packets [i].data);
1873 DEBUG_PRINTF (1, "[dbg] Sent %d buffered reply packets [at=%lx].\n", nreply_packets, (long)mono_100ns_ticks () / 10000);
1878 buffer_reply_packet (int id, int error, Buffer *data)
1882 if (nreply_packets == 128)
1883 send_buffered_reply_packets ();
1885 p = &reply_packets [nreply_packets];
1888 p->data = g_new0 (Buffer, 1);
1889 buffer_init (p->data, buffer_len (data));
1890 buffer_add_buffer (p->data, data);
1899 * Represents an object accessible by the debugger client.
1902 /* Unique id used in the wire protocol to refer to objects */
1905 * A weakref gc handle pointing to the object. The gc handle is used to
1906 * detect if the object was garbage collected.
1911 /* Maps objid -> ObjRef */
1912 /* Protected by the loader lock */
1913 static GHashTable *objrefs;
1914 /* Protected by the loader lock */
1915 static GHashTable *obj_to_objref;
1916 /* Protected by the dbg lock */
1917 static MonoGHashTable *suspended_objs;
1920 free_objref (gpointer value)
1922 ObjRef *o = (ObjRef *)value;
1924 mono_gchandle_free (o->handle);
1932 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1933 obj_to_objref = g_hash_table_new (NULL, NULL);
1934 suspended_objs = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_DEBUGGER, "suspended objects table");
1935 MONO_GC_REGISTER_ROOT_FIXED (suspended_objs, MONO_ROOT_SOURCE_DEBUGGER, "suspended objects table");
1939 objrefs_cleanup (void)
1941 g_hash_table_destroy (objrefs);
1946 * Return an ObjRef for OBJ.
1949 get_objref (MonoObject *obj)
1952 GSList *reflist = NULL, *l;
1958 if (suspend_count) {
1960 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1963 mono_g_hash_table_insert (suspended_objs, obj, NULL);
1967 mono_loader_lock ();
1969 /* FIXME: The tables can grow indefinitely */
1971 if (mono_gc_is_moving ()) {
1973 * Objects can move, so use a hash table mapping hash codes to lists of
1974 * ObjRef structures.
1976 hash = mono_object_hash (obj);
1978 reflist = (GSList *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1979 for (l = reflist; l; l = l->next) {
1980 ref = (ObjRef *)l->data;
1981 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1982 mono_loader_unlock ();
1987 /* Use a hash table with masked pointers to internalize object references */
1988 ref = (ObjRef *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1989 /* ref might refer to a different object with the same addr which was GCd */
1990 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1991 mono_loader_unlock ();
1996 ref = g_new0 (ObjRef, 1);
1997 ref->id = InterlockedIncrement (&objref_id);
1998 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
2000 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
2002 if (mono_gc_is_moving ()) {
2003 reflist = g_slist_append (reflist, ref);
2004 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
2006 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
2009 mono_loader_unlock ();
2015 true_pred (gpointer key, gpointer value, gpointer user_data)
2021 clear_suspended_objs (void)
2024 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
2029 get_objid (MonoObject *obj)
2031 return get_objref (obj)->id;
2035 * Set OBJ to the object identified by OBJID.
2036 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
2040 get_object_allow_null (int objid, MonoObject **obj)
2050 return ERR_INVALID_OBJECT;
2052 mono_loader_lock ();
2054 ref = (ObjRef *)g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
2057 *obj = mono_gchandle_get_target (ref->handle);
2058 mono_loader_unlock ();
2060 return ERR_INVALID_OBJECT;
2063 mono_loader_unlock ();
2064 return ERR_INVALID_OBJECT;
2069 get_object (int objid, MonoObject **obj)
2071 ErrorCode err = get_object_allow_null (objid, obj);
2073 if (err != ERR_NONE)
2076 return ERR_INVALID_OBJECT;
2081 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
2083 return decode_id (buf, endbuf, limit);
2087 buffer_add_objid (Buffer *buf, MonoObject *o)
2089 buffer_add_id (buf, get_objid (o));
2108 * Represents a runtime structure accessible to the debugger client
2111 /* Unique id used in the wire protocol */
2113 /* Domain of the runtime structure, NULL if the domain was unloaded */
2120 MonoAssembly *assembly;
2121 MonoClassField *field;
2123 MonoProperty *property;
2128 /* Maps runtime structure -> Id */
2129 /* Protected by the dbg lock */
2130 GHashTable *val_to_id [ID_NUM];
2131 /* Classes whose class load event has been sent */
2132 /* Protected by the loader lock */
2133 GHashTable *loaded_classes;
2134 /* Maps MonoClass->GPtrArray of file names */
2135 GHashTable *source_files;
2136 /* Maps source file basename -> GSList of classes */
2137 GHashTable *source_file_to_class;
2138 /* Same with ignore-case */
2139 GHashTable *source_file_to_class_ignorecase;
2143 /* Protected by the dbg lock */
2144 static GPtrArray *ids [ID_NUM];
2151 for (i = 0; i < ID_NUM; ++i)
2152 ids [i] = g_ptr_array_new ();
2160 for (i = 0; i < ID_NUM; ++i) {
2162 for (j = 0; j < ids [i]->len; ++j)
2163 g_free (g_ptr_array_index (ids [i], j));
2164 g_ptr_array_free (ids [i], TRUE);
2171 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2173 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2175 GHashTableIter iter;
2176 GPtrArray *file_names;
2181 for (i = 0; i < ID_NUM; ++i)
2182 if (info->val_to_id [i])
2183 g_hash_table_destroy (info->val_to_id [i]);
2184 g_hash_table_destroy (info->loaded_classes);
2186 g_hash_table_iter_init (&iter, info->source_files);
2187 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2188 for (i = 0; i < file_names->len; ++i)
2189 g_free (g_ptr_array_index (file_names, i));
2190 g_ptr_array_free (file_names, TRUE);
2193 g_hash_table_iter_init (&iter, info->source_file_to_class);
2194 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2199 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2200 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2208 domain_jit_info (domain)->agent_info = NULL;
2210 /* Clear ids referencing structures in the domain */
2212 for (i = 0; i < ID_NUM; ++i) {
2214 for (j = 0; j < ids [i]->len; ++j) {
2215 Id *id = (Id *)g_ptr_array_index (ids [i], j);
2216 if (id->domain == domain)
2223 mono_loader_lock ();
2224 g_hash_table_remove (domains, domain);
2225 mono_loader_unlock ();
2228 static AgentDomainInfo*
2229 get_agent_domain_info (MonoDomain *domain)
2231 AgentDomainInfo *info = NULL;
2233 mono_domain_lock (domain);
2235 info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2237 info = g_new0 (AgentDomainInfo, 1);
2238 domain_jit_info (domain)->agent_info = info;
2239 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2240 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2241 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2242 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2245 mono_domain_unlock (domain);
2251 get_id (MonoDomain *domain, IdType type, gpointer val)
2254 AgentDomainInfo *info;
2259 info = get_agent_domain_info (domain);
2263 if (info->val_to_id [type] == NULL)
2264 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2266 id = (Id *)g_hash_table_lookup (info->val_to_id [type], val);
2272 id = g_new0 (Id, 1);
2274 id->id = ids [type]->len + 1;
2275 id->domain = domain;
2278 g_hash_table_insert (info->val_to_id [type], val, id);
2279 g_ptr_array_add (ids [type], id);
2286 static inline gpointer
2287 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, ErrorCode *err)
2291 int id = decode_id (buf, endbuf, limit);
2300 // FIXME: error handling
2302 g_assert (id > 0 && id <= ids [type]->len);
2304 res = (Id *)g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2307 if (res->domain == NULL) {
2308 DEBUG_PRINTF (1, "ERR_UNLOADED, id=%d, type=%d.\n", id, type);
2309 *err = ERR_UNLOADED;
2314 *domain = res->domain;
2316 return res->data.val;
2320 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2322 int id = get_id (domain, type, val);
2324 buffer_add_id (buf, id);
2328 static inline MonoClass*
2329 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2333 klass = (MonoClass *)decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2334 if (G_UNLIKELY (log_level >= 2) && klass) {
2337 s = mono_type_full_name (&klass->byval_arg);
2338 DEBUG_PRINTF (2, "[dbg] recv class [%s]\n", s);
2344 static inline MonoAssembly*
2345 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2347 return (MonoAssembly *)decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2350 static inline MonoImage*
2351 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2353 return (MonoImage *)decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2356 static inline MonoMethod*
2357 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2361 m = (MonoMethod *)decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2362 if (G_UNLIKELY (log_level >= 2) && m) {
2365 s = mono_method_full_name (m, TRUE);
2366 DEBUG_PRINTF (2, "[dbg] recv method [%s]\n", s);
2372 static inline MonoClassField*
2373 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2375 return (MonoClassField *)decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2378 static inline MonoDomain*
2379 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2381 return (MonoDomain *)decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2384 static inline MonoProperty*
2385 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2387 return (MonoProperty *)decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2391 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2393 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2394 if (G_UNLIKELY (log_level >= 2) && klass) {
2397 s = mono_type_full_name (&klass->byval_arg);
2398 if (is_debugger_thread ())
2399 DEBUG_PRINTF (2, "[dbg] send class [%s]\n", s);
2401 DEBUG_PRINTF (2, "[%p] send class [%s]\n", (gpointer) (gsize) mono_native_thread_id_get (), s);
2407 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2409 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2410 if (G_UNLIKELY (log_level >= 2) && method) {
2413 s = mono_method_full_name (method, 1);
2414 DEBUG_PRINTF (2, "[dbg] send method [%s]\n", s);
2420 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2424 id = buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2425 if (G_UNLIKELY (log_level >= 2) && assembly)
2426 DEBUG_PRINTF (2, "[dbg] send assembly [%s][%s][%d]\n", assembly->aname.name, domain->friendly_name, id);
2430 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2432 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2436 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2438 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2442 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2444 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2448 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2450 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2453 static void invoke_method (void);
2460 * save_thread_context:
2462 * Set CTX as the current threads context which is used for computing stack traces.
2463 * This function is signal-safe.
2466 save_thread_context (MonoContext *ctx)
2468 DebuggerTlsData *tls;
2470 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2474 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2476 mono_thread_state_init_from_current (&tls->context);
2479 /* Number of threads suspended */
2481 * If this is equal to the size of thread_to_tls, the runtime is considered
2484 static gint32 threads_suspend_count;
2486 static MonoCoopMutex suspend_mutex;
2488 /* Cond variable used to wait for suspend_count becoming 0 */
2489 static MonoCoopCond suspend_cond;
2491 /* Semaphore used to wait for a thread becoming suspended */
2492 static MonoCoopSem suspend_sem;
2497 mono_coop_mutex_init (&suspend_mutex);
2498 mono_coop_cond_init (&suspend_cond);
2499 mono_coop_sem_init (&suspend_sem, 0);
2504 StackFrameInfo last_frame;
2505 gboolean last_frame_set;
2509 } GetLastFrameUserData;
2512 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2514 GetLastFrameUserData *data = (GetLastFrameUserData *)user_data;
2516 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE || info->type == FRAME_TYPE_TRAMPOLINE)
2519 if (!data->last_frame_set) {
2520 /* Store the last frame */
2521 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2522 data->last_frame_set = TRUE;
2525 /* Store the context/lmf for the frame above the last frame */
2526 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2527 data->lmf = info->lmf;
2528 data->domain = info->domain;
2534 copy_unwind_state_from_frame_data (MonoThreadUnwindState *to, GetLastFrameUserData *data, gpointer jit_tls)
2536 memcpy (&to->ctx, &data->ctx, sizeof (MonoContext));
2538 to->unwind_data [MONO_UNWIND_DATA_DOMAIN] = data->domain;
2539 to->unwind_data [MONO_UNWIND_DATA_LMF] = data->lmf;
2540 to->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = jit_tls;
2547 * Process interruption of a thread. This should be signal safe.
2549 * This always runs in the debugger thread.
2552 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, MonoJitInfo *ji)
2555 MonoNativeThreadId tid;
2559 ip = MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx);
2560 tid = mono_thread_info_get_tid (info);
2562 // FIXME: Races when the thread leaves managed code before hitting a single step
2565 if (ji && !ji->is_trampoline) {
2566 /* Running managed code, will be suspended by the single step code */
2567 DEBUG_PRINTF (1, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip);
2570 * Running native code, will be suspended when it returns to/enters
2571 * managed code. Treat it as already suspended.
2572 * This might interrupt the code in process_single_step_inner (), we use the
2573 * tls->suspending flag to avoid races when that happens.
2575 if (!tls->suspended && !tls->suspending) {
2576 GetLastFrameUserData data;
2578 // FIXME: printf is not signal safe, but this is only used during
2579 // debugger debugging
2581 DEBUG_PRINTF (1, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip);
2582 //save_thread_context (&ctx);
2585 /* Already terminated */
2589 * We are in a difficult position: we want to be able to provide stack
2590 * traces for this thread, but we can't use the current ctx+lmf, since
2591 * the thread is still running, so it might return to managed code,
2592 * making these invalid.
2593 * So we start a stack walk and save the first frame, along with the
2594 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2595 * suspended when it returns to managed code, so the parent's ctx should
2598 data.last_frame_set = FALSE;
2599 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, mono_thread_info_get_suspend_state (info), MONO_UNWIND_SIGNAL_SAFE, &data);
2600 if (data.last_frame_set) {
2601 gpointer jit_tls = ((MonoThreadInfo*)tls->thread->thread_info)->jit_data;
2603 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2605 copy_unwind_state_from_frame_data (&tls->async_state, &data, jit_tls);
2606 copy_unwind_state_from_frame_data (&tls->context, &data, jit_tls);
2608 tls->async_state.valid = FALSE;
2611 mono_memory_barrier ();
2613 tls->suspended = TRUE;
2614 mono_coop_sem_post (&suspend_sem);
2620 * reset_native_thread_suspend_state:
2622 * Reset the suspended flag and state on native threads
2625 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2627 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2629 if (!tls->really_suspended && tls->suspended) {
2630 tls->suspended = FALSE;
2632 * The thread might still be running if it was executing native code, so the state won't be invalided by
2633 * suspend_current ().
2635 tls->context.valid = FALSE;
2636 tls->async_state.valid = FALSE;
2637 invalidate_frames (tls);
2642 DebuggerTlsData *tls;
2643 gboolean valid_info;
2646 static SuspendThreadResult
2647 debugger_interrupt_critical (MonoThreadInfo *info, gpointer user_data)
2649 InterruptData *data = (InterruptData *)user_data;
2652 data->valid_info = TRUE;
2653 ji = mono_jit_info_table_find_internal (
2654 (MonoDomain *)mono_thread_info_get_suspend_state (info)->unwind_data [MONO_UNWIND_DATA_DOMAIN],
2655 (char *)MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx),
2659 /* This is signal safe */
2660 thread_interrupt (data->tls, info, ji);
2661 return MonoResumeThread;
2667 * Notify a thread that it needs to suspend.
2670 notify_thread (gpointer key, gpointer value, gpointer user_data)
2672 MonoInternalThread *thread = (MonoInternalThread *)key;
2673 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2674 MonoNativeThreadId tid = MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid);
2676 if (mono_native_thread_id_equals (mono_native_thread_id_get (), tid) || tls->terminated)
2679 DEBUG_PRINTF (1, "[%p] Interrupting %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2681 /* This is _not_ equivalent to mono_thread_internal_abort () */
2682 InterruptData interrupt_data = { 0 };
2683 interrupt_data.tls = tls;
2685 mono_thread_info_safe_suspend_and_run ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE, debugger_interrupt_critical, &interrupt_data);
2686 if (!interrupt_data.valid_info) {
2687 DEBUG_PRINTF (1, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2689 * Attached thread which died without detaching.
2691 tls->terminated = TRUE;
2696 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2698 guint8 *ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
2702 if (mono_loader_lock_is_owned_by_self ()) {
2704 * Shortcut for the check in suspend_current (). This speeds up processing
2705 * when executing long running code inside the loader lock, i.e. assembly load
2711 if (is_debugger_thread ())
2714 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2715 if (suspend_count - tls->resume_count > 0)
2716 tls->suspending = TRUE;
2718 DEBUG_PRINTF (1, "[%p] Received single step event for suspending.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2720 if (suspend_count - tls->resume_count == 0) {
2722 * We are executing a single threaded invoke but the single step for
2723 * suspending is still active.
2724 * FIXME: This slows down single threaded invokes.
2726 DEBUG_PRINTF (1, "[%p] Ignored during single threaded invoke.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2730 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2732 /* Can't suspend in these methods */
2733 method = jinfo_get_method (ji);
2734 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2737 save_thread_context (ctx);
2745 * Increase the suspend count of the VM. While the suspend count is greater
2746 * than 0, runtime threads are suspended at certain points during execution.
2751 mono_loader_lock ();
2753 mono_coop_mutex_lock (&suspend_mutex);
2757 DEBUG_PRINTF (1, "[%p] Suspending vm...\n", (gpointer) (gsize) mono_native_thread_id_get ());
2759 if (suspend_count == 1) {
2760 // FIXME: Is it safe to call this inside the lock ?
2761 start_single_stepping ();
2762 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2765 mono_coop_mutex_unlock (&suspend_mutex);
2767 if (suspend_count == 1)
2769 * Suspend creation of new threadpool threads, since they cannot run
2771 mono_threadpool_ms_suspend ();
2773 mono_loader_unlock ();
2779 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2787 g_assert (is_debugger_thread ());
2789 mono_loader_lock ();
2791 mono_coop_mutex_lock (&suspend_mutex);
2793 g_assert (suspend_count > 0);
2796 DEBUG_PRINTF (1, "[%p] Resuming vm, suspend count=%d...\n", (gpointer) (gsize) mono_native_thread_id_get (), suspend_count);
2798 if (suspend_count == 0) {
2799 // FIXME: Is it safe to call this inside the lock ?
2800 stop_single_stepping ();
2801 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2804 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2805 err = mono_coop_cond_broadcast (&suspend_cond);
2806 g_assert (err == 0);
2808 mono_coop_mutex_unlock (&suspend_mutex);
2809 //g_assert (err == 0);
2811 if (suspend_count == 0)
2812 mono_threadpool_ms_resume ();
2814 mono_loader_unlock ();
2820 * Resume just one thread.
2823 resume_thread (MonoInternalThread *thread)
2826 DebuggerTlsData *tls;
2828 g_assert (is_debugger_thread ());
2830 mono_loader_lock ();
2832 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
2835 mono_coop_mutex_lock (&suspend_mutex);
2837 g_assert (suspend_count > 0);
2839 DEBUG_PRINTF (1, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid);
2841 tls->resume_count += suspend_count;
2844 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2845 * but only the one whose resume_count field is > 0 will be resumed.
2847 err = mono_coop_cond_broadcast (&suspend_cond);
2848 g_assert (err == 0);
2850 mono_coop_mutex_unlock (&suspend_mutex);
2851 //g_assert (err == 0);
2853 mono_loader_unlock ();
2857 free_frames (StackFrame **frames, int nframes)
2861 for (i = 0; i < nframes; ++i) {
2862 if (frames [i]->jit)
2863 mono_debug_free_method_jit_info (frames [i]->jit);
2864 g_free (frames [i]);
2870 invalidate_frames (DebuggerTlsData *tls)
2873 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2876 free_frames (tls->frames, tls->frame_count);
2877 tls->frame_count = 0;
2880 free_frames (tls->restore_frames, tls->restore_frame_count);
2881 tls->restore_frame_count = 0;
2882 tls->restore_frames = NULL;
2888 * Suspend the current thread until the runtime is resumed. If the thread has a
2889 * pending invoke, then the invoke is executed before this function returns.
2892 suspend_current (void)
2894 DebuggerTlsData *tls;
2897 g_assert (!is_debugger_thread ());
2899 if (mono_loader_lock_is_owned_by_self ()) {
2901 * If we own the loader mutex, can't suspend until we release it, since the
2902 * whole runtime can deadlock otherwise.
2907 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2910 mono_coop_mutex_lock (&suspend_mutex);
2912 tls->suspending = FALSE;
2913 tls->really_suspended = TRUE;
2915 if (!tls->suspended) {
2916 tls->suspended = TRUE;
2917 mono_coop_sem_post (&suspend_sem);
2920 DEBUG_PRINTF (1, "[%p] Suspended.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2922 while (suspend_count - tls->resume_count > 0) {
2923 err = mono_coop_cond_wait (&suspend_cond, &suspend_mutex);
2924 g_assert (err == 0);
2927 tls->suspended = FALSE;
2928 tls->really_suspended = FALSE;
2930 threads_suspend_count --;
2932 mono_coop_mutex_unlock (&suspend_mutex);
2934 DEBUG_PRINTF (1, "[%p] Resumed.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2936 if (tls->pending_invoke) {
2937 /* Save the original context */
2938 tls->pending_invoke->has_ctx = TRUE;
2939 tls->pending_invoke->ctx = tls->context.ctx;
2944 /* The frame info becomes invalid after a resume */
2945 tls->context.valid = FALSE;
2946 tls->async_state.valid = FALSE;
2947 invalidate_frames (tls);
2951 count_thread (gpointer key, gpointer value, gpointer user_data)
2953 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2955 if (!tls->suspended && !tls->terminated)
2956 *(int*)user_data = *(int*)user_data + 1;
2960 count_threads_to_wait_for (void)
2964 mono_loader_lock ();
2965 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2966 mono_loader_unlock ();
2974 * Wait until the runtime is completely suspended.
2977 wait_for_suspend (void)
2979 int nthreads, nwait, err;
2980 gboolean waited = FALSE;
2982 // FIXME: Threads starting/stopping ?
2983 mono_loader_lock ();
2984 nthreads = mono_g_hash_table_size (thread_to_tls);
2985 mono_loader_unlock ();
2988 nwait = count_threads_to_wait_for ();
2990 DEBUG_PRINTF (1, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads);
2991 err = mono_coop_sem_wait (&suspend_sem, MONO_SEM_FLAGS_NONE);
2992 g_assert (err == 0);
3000 DEBUG_PRINTF (1, "%d threads suspended.\n", nthreads);
3006 * Return whenever the runtime is suspended.
3011 return count_threads_to_wait_for () == 0;
3015 no_seq_points_found (MonoMethod *method, int offset)
3018 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3020 printf ("Unable to find seq points for method '%s', offset 0x%x.\n", mono_method_full_name (method, TRUE), offset);
3024 DebuggerTlsData *tls;
3026 } ComputeFramesUserData;
3029 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3031 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3033 MonoMethod *method, *actual_method, *api_method;
3037 if (info->type != FRAME_TYPE_MANAGED) {
3038 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3039 /* Mark the last frame as an invoke frame */
3041 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3047 method = jinfo_get_method (info->ji);
3049 method = info->method;
3050 actual_method = info->actual_method;
3051 api_method = method;
3056 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3059 if (info->il_offset == -1) {
3060 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3061 if (ud->frames == NULL) {
3062 if (mono_find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL, &sp))
3063 info->il_offset = sp.il_offset;
3065 if (info->il_offset == -1)
3066 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3069 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);
3071 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3072 if (!CHECK_PROTOCOL_VERSION (2, 17))
3073 /* Older clients can't handle this flag */
3075 api_method = mono_marshal_method_from_wrapper (method);
3078 actual_method = api_method;
3079 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3082 frame = g_new0 (StackFrame, 1);
3083 frame->method = method;
3084 frame->actual_method = actual_method;
3085 frame->api_method = api_method;
3086 frame->il_offset = info->il_offset;
3087 frame->native_offset = info->native_offset;
3088 frame->flags = flags;
3089 frame->ji = info->ji;
3090 if (info->reg_locations)
3091 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3094 frame->has_ctx = TRUE;
3096 frame->domain = info->domain;
3098 ud->frames = g_slist_append (ud->frames, frame);
3104 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3106 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3109 * 'tls->filter_ctx' is the location of the throw site.
3111 * mono_walk_stack() will never actually hit the throw site, but unwind
3112 * directly from the filter to the call site; we abort stack unwinding here
3113 * once this happens and resume from the throw site.
3116 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3119 return process_frame (info, ctx, user_data);
3123 * Return a malloc-ed list of StackFrame structures.
3126 compute_frame_info_from (MonoInternalThread *thread, DebuggerTlsData *tls, MonoThreadUnwindState *state, int *out_nframes)
3128 ComputeFramesUserData user_data;
3129 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3134 user_data.tls = tls;
3135 user_data.frames = NULL;
3137 mono_walk_stack_with_state (process_frame, state, opts, &user_data);
3139 nframes = g_slist_length (user_data.frames);
3140 res = g_new0 (StackFrame*, nframes);
3141 l = user_data.frames;
3142 for (i = 0; i < nframes; ++i) {
3143 res [i] = (StackFrame *)l->data;
3146 *out_nframes = nframes;
3152 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3154 ComputeFramesUserData user_data;
3156 int i, findex, new_frame_count;
3157 StackFrame **new_frames, *f;
3158 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3160 // FIXME: Locking on tls
3161 if (tls->frames && tls->frames_up_to_date)
3164 DEBUG_PRINTF (1, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid);
3166 user_data.tls = tls;
3167 user_data.frames = NULL;
3168 if (tls->terminated) {
3169 tls->frame_count = 0;
3171 } if (!tls->really_suspended && tls->async_state.valid) {
3172 /* Have to use the state saved by the signal handler */
3173 process_frame (&tls->async_last_frame, NULL, &user_data);
3174 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3175 } else if (tls->filter_state.valid) {
3177 * We are inside an exception filter.
3179 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3181 if (tls->context.valid)
3182 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3184 * After that, we resume unwinding from the location where the exception has been thrown.
3186 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3187 } else if (tls->context.valid) {
3188 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3191 tls->frame_count = 0;
3195 new_frame_count = g_slist_length (user_data.frames);
3196 new_frames = g_new0 (StackFrame*, new_frame_count);
3198 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3199 f = (StackFrame *)tmp->data;
3202 * Reuse the id for already existing stack frames, so invokes don't invalidate
3203 * the still valid stack frames.
3205 for (i = 0; i < tls->frame_count; ++i) {
3206 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3207 f->id = tls->frames [i]->id;
3212 if (i >= tls->frame_count)
3213 f->id = InterlockedIncrement (&frame_id);
3215 new_frames [findex ++] = f;
3218 g_slist_free (user_data.frames);
3220 invalidate_frames (tls);
3222 tls->frames = new_frames;
3223 tls->frame_count = new_frame_count;
3224 tls->frames_up_to_date = TRUE;
3228 * GHFunc to emit an appdomain creation event
3229 * @param key Don't care
3230 * @param value A loaded appdomain
3231 * @param user_data Don't care
3234 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3236 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3237 g_hash_table_foreach (get_agent_domain_info ((MonoDomain *)value)->loaded_classes, emit_type_load, NULL);
3241 * GHFunc to emit a thread start event
3242 * @param key A thread id
3243 * @param value A thread object
3244 * @param user_data Don't care
3247 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3249 if (!mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (GPOINTER_TO_UINT (key)), debugger_thread_id))
3250 process_profiler_event (EVENT_KIND_THREAD_START, value);
3254 * GFunc to emit an assembly load event
3255 * @param value A loaded assembly
3256 * @param user_data Don't care
3259 emit_assembly_load (gpointer value, gpointer user_data)
3261 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3265 * GFunc to emit a type load event
3266 * @param value A loaded type
3267 * @param user_data Don't care
3270 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3272 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3276 strdup_tolower (char *s)
3281 for (p = s2; *p; ++p)
3287 * Same as g_path_get_basename () but handles windows paths as well,
3288 * which can occur in .mdb files created by pdb2mdb.
3291 dbg_path_get_basename (const char *filename)
3295 if (!filename || strchr (filename, '/') || !strchr (filename, '\\'))
3296 return g_path_get_basename (filename);
3300 /* No separator -> filename */
3301 r = strrchr (filename, '\\');
3303 return g_strdup (filename);
3305 /* Trailing slash, remove component */
3307 char *copy = g_strdup (filename);
3308 copy [r-filename] = 0;
3309 r = strrchr (copy, '\\');
3313 return g_strdup ("/");
3315 r = g_strdup (&r[1]);
3320 return g_strdup (&r[1]);
3324 init_jit_info_dbg_attrs (MonoJitInfo *ji)
3326 static MonoClass *hidden_klass, *step_through_klass, *non_user_klass;
3328 MonoCustomAttrInfo *ainfo;
3330 if (ji->dbg_attrs_inited)
3334 hidden_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3336 if (!step_through_klass)
3337 step_through_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3339 if (!non_user_klass)
3340 non_user_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute");
3342 ainfo = mono_custom_attrs_from_method_checked (jinfo_get_method (ji), &error);
3343 mono_error_cleanup (&error); /* FIXME don't swallow the error? */
3345 if (mono_custom_attrs_has_attr (ainfo, hidden_klass))
3346 ji->dbg_hidden = TRUE;
3347 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3348 ji->dbg_step_through = TRUE;
3349 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3350 ji->dbg_non_user_code = TRUE;
3351 mono_custom_attrs_free (ainfo);
3354 ainfo = mono_custom_attrs_from_class_checked (jinfo_get_method (ji)->klass, &error);
3355 mono_error_cleanup (&error); /* FIXME don't swallow the error? */
3357 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3358 ji->dbg_step_through = TRUE;
3359 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3360 ji->dbg_non_user_code = TRUE;
3361 mono_custom_attrs_free (ainfo);
3364 mono_memory_barrier ();
3365 ji->dbg_attrs_inited = TRUE;
3373 * create_event_list:
3375 * Return a list of event request ids matching EVENT, starting from REQS, which
3376 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3378 * We return request ids, instead of requests, to simplify threading, since
3379 * requests could be deleted anytime when the loader lock is not held.
3380 * LOCKING: Assumes the loader lock is held.
3383 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3386 GSList *events = NULL;
3388 *suspend_policy = SUSPEND_POLICY_NONE;
3391 reqs = event_requests;
3396 for (i = 0; i < reqs->len; ++i) {
3397 EventRequest *req = (EventRequest *)g_ptr_array_index (reqs, i);
3398 if (req->event_kind == event) {
3399 gboolean filtered = FALSE;
3402 for (j = 0; j < req->nmodifiers; ++j) {
3403 Modifier *mod = &req->modifiers [j];
3405 if (mod->kind == MOD_KIND_COUNT) {
3407 if (mod->data.count > 0) {
3408 if (mod->data.count > 0) {
3410 if (mod->data.count == 0)
3414 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3415 if (mod->data.thread != mono_thread_internal_current ())
3417 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3418 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3420 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3422 if (ei->caught && !mod->caught)
3424 if (!ei->caught && !mod->uncaught)
3426 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3428 gboolean found = FALSE;
3429 MonoAssembly **assemblies = mod->data.assemblies;
3432 for (k = 0; assemblies [k]; ++k)
3433 if (assemblies [k] == jinfo_get_method (ji)->klass->image->assembly)
3438 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3439 gpointer iter = NULL;
3441 MonoDebugSourceInfo *sinfo;
3442 char *source_file, *s;
3443 gboolean found = FALSE;
3445 GPtrArray *source_file_list;
3447 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3448 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3451 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, NULL, NULL, NULL);
3452 for (i = 0; i < source_file_list->len; ++i) {
3453 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
3455 * Do a case-insesitive match by converting the file name to
3458 s = strdup_tolower (sinfo->source_file);
3459 if (g_hash_table_lookup (mod->data.source_files, s))
3462 char *s2 = dbg_path_get_basename (sinfo->source_file);
3463 char *s3 = strdup_tolower (s2);
3465 if (g_hash_table_lookup (mod->data.source_files, s3))
3472 g_ptr_array_free (source_file_list, TRUE);
3477 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3480 s = mono_type_full_name (&ei->klass->byval_arg);
3481 if (!g_hash_table_lookup (mod->data.type_names, s))
3484 } else if (mod->kind == MOD_KIND_STEP) {
3485 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3486 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3487 !strcmp (jinfo_get_method (ji)->name, ".cctor") &&
3488 (jinfo_get_method (ji) != ((SingleStepReq*)req->info)->start_method))
3490 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3491 init_jit_info_dbg_attrs (ji);
3495 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3496 init_jit_info_dbg_attrs (ji);
3497 if (ji->dbg_step_through)
3500 if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3501 init_jit_info_dbg_attrs (ji);
3502 if (ji->dbg_non_user_code)
3509 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3510 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3515 /* Send a VM START/DEATH event by default */
3516 if (event == EVENT_KIND_VM_START)
3517 events = g_slist_append (events, GINT_TO_POINTER (0));
3518 if (event == EVENT_KIND_VM_DEATH)
3519 events = g_slist_append (events, GINT_TO_POINTER (0));
3524 static G_GNUC_UNUSED const char*
3525 event_to_string (EventKind event)
3528 case EVENT_KIND_VM_START: return "VM_START";
3529 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3530 case EVENT_KIND_THREAD_START: return "THREAD_START";
3531 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3532 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3533 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3534 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3535 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3536 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3537 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3538 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3539 case EVENT_KIND_STEP: return "STEP";
3540 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3541 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3542 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3543 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3544 case EVENT_KIND_USER_LOG: return "USER_LOG";
3546 g_assert_not_reached ();
3554 * Send an event to the client, suspending the vm if needed.
3555 * LOCKING: Since this can suspend the calling thread, no locks should be held
3557 * The EVENTS list is freed by this function.
3560 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3564 MonoDomain *domain = mono_domain_get ();
3565 MonoThread *thread = NULL;
3566 MonoObject *keepalive_obj = NULL;
3567 gboolean send_success = FALSE;
3572 DEBUG_PRINTF (2, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event));
3576 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3577 // FIXME: We miss those events
3578 DEBUG_PRINTF (2, "VM start event not sent yet: dropping %s\n", event_to_string (event));
3582 if (vm_death_event_sent) {
3583 DEBUG_PRINTF (2, "VM death event has been sent: dropping %s\n", event_to_string (event));
3587 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3588 DEBUG_PRINTF (2, "Mono runtime is shutting down: dropping %s\n", event_to_string (event));
3593 DEBUG_PRINTF (2, "Debugger client is not connected: dropping %s\n", event_to_string (event));
3597 if (event == EVENT_KIND_KEEPALIVE)
3598 suspend_policy = SUSPEND_POLICY_NONE;
3603 if (agent_config.defer) {
3604 /* Make sure the thread id is always set when doing deferred debugging */
3605 if (is_debugger_thread ()) {
3606 /* Don't suspend on events from the debugger thread */
3607 suspend_policy = SUSPEND_POLICY_NONE;
3608 thread = mono_thread_get_main ();
3610 else thread = mono_thread_current ();
3612 if (is_debugger_thread () && event != EVENT_KIND_VM_DEATH)
3613 // FIXME: Send these with a NULL thread, don't suspend the current thread
3618 nevents = g_slist_length (events);
3619 buffer_init (&buf, 128);
3620 buffer_add_byte (&buf, suspend_policy);
3621 buffer_add_int (&buf, nevents);
3623 for (l = events; l; l = l->next) {
3624 buffer_add_byte (&buf, event); // event kind
3625 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3630 thread = mono_thread_current ();
3632 if (event == EVENT_KIND_VM_START && arg != NULL)
3633 thread = (MonoThread *)arg;
3635 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3638 case EVENT_KIND_THREAD_START:
3639 case EVENT_KIND_THREAD_DEATH:
3641 case EVENT_KIND_APPDOMAIN_CREATE:
3642 case EVENT_KIND_APPDOMAIN_UNLOAD:
3643 buffer_add_domainid (&buf, (MonoDomain *)arg);
3645 case EVENT_KIND_METHOD_ENTRY:
3646 case EVENT_KIND_METHOD_EXIT:
3647 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3649 case EVENT_KIND_ASSEMBLY_LOAD:
3650 buffer_add_assemblyid (&buf, domain, (MonoAssembly *)arg);
3652 case EVENT_KIND_ASSEMBLY_UNLOAD: {
3653 DebuggerTlsData *tls;
3655 /* The domain the assembly belonged to is not equal to the current domain */
3656 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3658 g_assert (tls->domain_unloading);
3660 buffer_add_assemblyid (&buf, tls->domain_unloading, (MonoAssembly *)arg);
3663 case EVENT_KIND_TYPE_LOAD:
3664 buffer_add_typeid (&buf, domain, (MonoClass *)arg);
3666 case EVENT_KIND_BREAKPOINT:
3667 case EVENT_KIND_STEP:
3668 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3669 buffer_add_long (&buf, il_offset);
3671 case EVENT_KIND_VM_START:
3672 buffer_add_domainid (&buf, mono_get_root_domain ());
3674 case EVENT_KIND_VM_DEATH:
3675 if (CHECK_PROTOCOL_VERSION (2, 27))
3676 buffer_add_int (&buf, mono_environment_exitcode_get ());
3678 case EVENT_KIND_EXCEPTION: {
3679 EventInfo *ei = (EventInfo *)arg;
3680 buffer_add_objid (&buf, ei->exc);
3682 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3683 * later after the suspension. (#12494).
3685 keepalive_obj = ei->exc;
3688 case EVENT_KIND_USER_BREAK:
3690 case EVENT_KIND_USER_LOG: {
3691 EventInfo *ei = (EventInfo *)arg;
3692 buffer_add_int (&buf, ei->level);
3693 buffer_add_string (&buf, ei->category ? ei->category : "");
3694 buffer_add_string (&buf, ei->message ? ei->message : "");
3697 case EVENT_KIND_KEEPALIVE:
3698 suspend_policy = SUSPEND_POLICY_NONE;
3701 g_assert_not_reached ();
3705 if (event == EVENT_KIND_VM_START) {
3706 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3707 if (!agent_config.defer)
3708 start_debugger_thread ();
3711 if (event == EVENT_KIND_VM_DEATH) {
3712 vm_death_event_sent = TRUE;
3713 suspend_policy = SUSPEND_POLICY_NONE;
3716 if (mono_runtime_is_shutting_down ())
3717 suspend_policy = SUSPEND_POLICY_NONE;
3719 if (suspend_policy != SUSPEND_POLICY_NONE) {
3721 * Save the thread context and start suspending before sending the packet,
3722 * since we could be receiving the resume request before send_packet ()
3725 save_thread_context (ctx);
3729 /* This will keep this object alive */
3730 get_objref (keepalive_obj);
3733 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3737 g_slist_free (events);
3740 if (!send_success) {
3741 DEBUG_PRINTF (2, "Sending command %s failed.\n", event_to_string (event));
3745 if (event == EVENT_KIND_VM_START) {
3746 vm_start_event_sent = TRUE;
3749 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);
3751 switch (suspend_policy) {
3752 case SUSPEND_POLICY_NONE:
3754 case SUSPEND_POLICY_ALL:
3757 case SUSPEND_POLICY_EVENT_THREAD:
3761 g_assert_not_reached ();
3766 process_profiler_event (EventKind event, gpointer arg)
3770 EventInfo ei, *ei_arg = NULL;
3772 if (event == EVENT_KIND_TYPE_LOAD) {
3773 ei.klass = (MonoClass *)arg;
3777 mono_loader_lock ();
3778 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3779 mono_loader_unlock ();
3781 process_event (event, arg, 0, NULL, events, suspend_policy);
3785 runtime_initialized (MonoProfiler *prof)
3787 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3788 if (agent_config.defer)
3789 start_debugger_thread ();
3793 runtime_shutdown (MonoProfiler *prof)
3795 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3797 mono_debugger_agent_cleanup ();
3801 thread_startup (MonoProfiler *prof, uintptr_t tid)
3803 MonoInternalThread *thread = mono_thread_internal_current ();
3804 MonoInternalThread *old_thread;
3805 DebuggerTlsData *tls;
3807 if (mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (tid), debugger_thread_id))
3810 g_assert (mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (tid), MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid)));
3812 mono_loader_lock ();
3813 old_thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3814 mono_loader_unlock ();
3816 if (thread == old_thread) {
3818 * For some reason, thread_startup () might be called for the same thread
3819 * multiple times (attach ?).
3821 DEBUG_PRINTF (1, "[%p] thread_start () called multiple times for %p, ignored.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3825 * thread_end () might not be called for some threads, and the tid could
3828 DEBUG_PRINTF (1, "[%p] Removing stale data for tid %p.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3829 mono_loader_lock ();
3830 mono_g_hash_table_remove (thread_to_tls, old_thread);
3831 mono_g_hash_table_remove (tid_to_thread, GUINT_TO_POINTER (tid));
3832 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3833 mono_loader_unlock ();
3837 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3839 // FIXME: Free this somewhere
3840 tls = g_new0 (DebuggerTlsData, 1);
3841 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread, MONO_ROOT_SOURCE_DEBUGGER, "debugger thread reference");
3842 tls->thread = thread;
3843 mono_native_tls_set_value (debugger_tls_id, tls);
3845 DEBUG_PRINTF (1, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3847 mono_loader_lock ();
3848 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3849 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3850 mono_g_hash_table_insert (tid_to_thread_obj, GUINT_TO_POINTER (tid), mono_thread_current ());
3851 mono_loader_unlock ();
3853 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3856 * suspend_vm () could have missed this thread, so wait for a resume.
3862 thread_end (MonoProfiler *prof, uintptr_t tid)
3864 MonoInternalThread *thread;
3865 DebuggerTlsData *tls = NULL;
3867 mono_loader_lock ();
3868 thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3870 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3871 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
3873 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3874 tls->terminated = TRUE;
3875 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3876 MONO_GC_UNREGISTER_ROOT (tls->thread);
3880 mono_loader_unlock ();
3882 /* We might be called for threads started before we registered the start callback */
3884 DEBUG_PRINTF (1, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3886 if (mono_native_thread_id_equals (mono_native_thread_id_get (), MONO_UINT_TO_NATIVE_THREAD_ID (tid))
3887 && !mono_native_tls_get_value (debugger_tls_id)
3890 * This can happen on darwin since we deregister threads using pthread dtors.
3891 * process_profiler_event () and the code it calls cannot handle a null TLS value.
3896 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3901 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3903 mono_loader_lock ();
3904 g_hash_table_insert (domains, domain, domain);
3905 mono_loader_unlock ();
3907 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3911 appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain)
3913 DebuggerTlsData *tls;
3915 /* This might be called during shutdown on the debugger thread from the CMD_VM_EXIT code */
3916 if (is_debugger_thread ())
3920 * Remember the currently unloading appdomain as it is needed to generate
3921 * proper ids for unloading assemblies.
3923 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3925 tls->domain_unloading = domain;
3929 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3931 DebuggerTlsData *tls;
3933 if (is_debugger_thread ())
3936 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3938 tls->domain_unloading = NULL;
3940 clear_breakpoints_for_domain (domain);
3942 mono_loader_lock ();
3943 /* Invalidate each thread's frame stack */
3944 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3945 mono_loader_unlock ();
3947 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3951 * invalidate_each_thread:
3953 * A GHFunc to invalidate frames.
3954 * value must be a DebuggerTlsData*
3957 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3959 invalidate_frames ((DebuggerTlsData *)value);
3963 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3965 /* Sent later in jit_end () */
3967 g_ptr_array_add (pending_assembly_loads, assembly);
3972 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3974 if (is_debugger_thread ())
3977 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3979 clear_event_requests_for_assembly (assembly);
3980 clear_types_for_assembly (assembly);
3984 send_type_load (MonoClass *klass)
3986 gboolean type_load = FALSE;
3987 MonoDomain *domain = mono_domain_get ();
3988 AgentDomainInfo *info = NULL;
3990 info = get_agent_domain_info (domain);
3992 mono_loader_lock ();
3994 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
3996 g_hash_table_insert (info->loaded_classes, klass, klass);
3999 mono_loader_unlock ();
4002 emit_type_load (klass, klass, NULL);
4006 * Emit load events for all types currently loaded in the domain.
4007 * Takes the loader and domain locks.
4008 * user_data is unused.
4011 send_types_for_domain (MonoDomain *domain, void *user_data)
4013 AgentDomainInfo *info = NULL;
4015 info = get_agent_domain_info (domain);
4018 mono_loader_lock ();
4019 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4020 mono_loader_unlock ();
4024 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
4027 * We emit type load events when the first method of the type is JITted,
4028 * since the class load profiler callbacks might be called with the
4029 * loader lock held. They could also occur in the debugger thread.
4030 * Same for assembly load events.
4033 MonoAssembly *assembly = NULL;
4035 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4037 if (pending_assembly_loads->len > 0) {
4038 assembly = (MonoAssembly *)g_ptr_array_index (pending_assembly_loads, 0);
4039 g_ptr_array_remove_index (pending_assembly_loads, 0);
4044 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4050 send_type_load (method->klass);
4053 add_pending_breakpoints (method, jinfo);
4057 * BREAKPOINTS/SINGLE STEPPING
4061 * Contains information about an inserted breakpoint.
4064 long il_offset, native_offset;
4068 } BreakpointInstance;
4071 * Contains generic information about a breakpoint.
4075 * The method where the breakpoint is placed. Can be NULL in which case it
4076 * is inserted into every method. This is used to implement method entry/
4077 * exit events. Can be a generic method definition, in which case the
4078 * breakpoint is inserted into every instance.
4084 * A list of BreakpointInstance structures describing where the breakpoint
4085 * was inserted. There could be more than one because of
4086 * generics/appdomains/method entry/exit.
4088 GPtrArray *children;
4091 /* List of breakpoints */
4092 /* Protected by the loader lock */
4093 static GPtrArray *breakpoints;
4094 /* Maps breakpoint locations to the number of breakpoints at that location */
4095 static GHashTable *bp_locs;
4098 breakpoints_init (void)
4100 breakpoints = g_ptr_array_new ();
4101 bp_locs = g_hash_table_new (NULL, NULL);
4105 * insert_breakpoint:
4107 * Insert the breakpoint described by BP into the method described by
4111 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4114 BreakpointInstance *inst;
4115 SeqPointIterator it;
4116 gboolean it_has_sp = FALSE;
4119 mono_error_init (error);
4121 mono_seq_point_iterator_init (&it, seq_points);
4122 while (mono_seq_point_iterator_next (&it)) {
4123 if (it.seq_point.il_offset == bp->il_offset) {
4131 * The set of IL offsets with seq points doesn't completely match the
4132 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4134 mono_seq_point_iterator_init (&it, seq_points);
4135 while (mono_seq_point_iterator_next (&it)) {
4136 if (it.seq_point.il_offset != METHOD_ENTRY_IL_OFFSET &&
4137 it.seq_point.il_offset != METHOD_EXIT_IL_OFFSET &&
4138 it.seq_point.il_offset + 1 == bp->il_offset) {
4146 char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d", mono_method_full_name (jinfo_get_method (ji), TRUE), bp->il_offset);
4148 mono_seq_point_iterator_init (&it, seq_points);
4149 while (mono_seq_point_iterator_next (&it))
4150 DEBUG_PRINTF (1, "%d\n", it.seq_point.il_offset);
4153 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4154 g_warning ("%s", s);
4158 g_warning ("%s", s);
4164 inst = g_new0 (BreakpointInstance, 1);
4165 inst->il_offset = it.seq_point.il_offset;
4166 inst->native_offset = it.seq_point.native_offset;
4167 inst->ip = (guint8*)ji->code_start + it.seq_point.native_offset;
4169 inst->domain = domain;
4171 mono_loader_lock ();
4173 g_ptr_array_add (bp->children, inst);
4175 mono_loader_unlock ();
4178 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4179 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4182 if (it.seq_point.native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4183 DEBUG_PRINTF (1, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset);
4184 } else if (count == 0) {
4185 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4186 mono_arch_set_breakpoint (ji, inst->ip);
4192 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);
4196 remove_breakpoint (BreakpointInstance *inst)
4198 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4200 MonoJitInfo *ji = inst->ji;
4201 guint8 *ip = inst->ip;
4204 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4205 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4208 g_assert (count > 0);
4210 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4211 mono_arch_clear_breakpoint (ji, ip);
4212 DEBUG_PRINTF (1, "[dbg] Clear breakpoint at %s [%p].\n", mono_method_full_name (jinfo_get_method (ji), TRUE), ip);
4220 * This doesn't take any locks.
4222 static inline gboolean
4223 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4229 if (method == bp->method)
4231 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4234 if (bp->method->is_inflated && method->is_inflated) {
4235 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4236 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4238 /* Open generic methods should match closed generic methods of the same class */
4239 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4240 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4241 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4243 /* FIXME: Handle !mvar */
4244 if (t1->type != MONO_TYPE_MVAR)
4255 * add_pending_breakpoints:
4257 * Insert pending breakpoints into the newly JITted method METHOD.
4260 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4263 MonoSeqPointInfo *seq_points;
4265 MonoMethod *jmethod;
4270 domain = mono_domain_get ();
4272 mono_loader_lock ();
4274 for (i = 0; i < breakpoints->len; ++i) {
4275 MonoBreakpoint *bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4276 gboolean found = FALSE;
4278 if (!bp_matches_method (bp, method))
4281 for (j = 0; j < bp->children->len; ++j) {
4282 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4289 MonoMethod *declaring = NULL;
4291 jmethod = jinfo_get_method (ji);
4292 if (jmethod->is_inflated)
4293 declaring = mono_method_get_declaring_generic_method (jmethod);
4295 mono_domain_lock (domain);
4296 seq_points = (MonoSeqPointInfo *)g_hash_table_lookup (domain_jit_info (domain)->seq_points, jmethod);
4297 if (!seq_points && declaring)
4298 seq_points = (MonoSeqPointInfo *)g_hash_table_lookup (domain_jit_info (domain)->seq_points, declaring);
4299 mono_domain_unlock (domain);
4301 /* Could be AOT code */
4303 g_assert (seq_points);
4305 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4309 mono_loader_unlock ();
4313 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4319 mono_error_init (error);
4321 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4325 /* Might be AOTed code */
4326 code = mono_aot_get_method_checked (domain, method, &oerror);
4328 mono_error_assert_ok (&oerror);
4329 ji = mono_jit_info_table_find (domain, (char *)code);
4334 insert_breakpoint (seq_points, domain, ji, bp, error);
4338 clear_breakpoint (MonoBreakpoint *bp);
4343 * Set a breakpoint at IL_OFFSET in METHOD.
4344 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4345 * METHOD can also be a generic method definition, in which case a breakpoint
4346 * is placed in all instances of the method.
4347 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4350 static MonoBreakpoint*
4351 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4354 GHashTableIter iter, iter2;
4357 MonoSeqPointInfo *seq_points;
4359 GPtrArray *method_domains;
4360 GPtrArray *method_seq_points;
4364 mono_error_init (error);
4367 // - suspend/resume the vm to prevent code patching problems
4368 // - multiple breakpoints on the same location
4369 // - dynamic methods
4372 bp = g_new0 (MonoBreakpoint, 1);
4373 bp->method = method;
4374 bp->il_offset = il_offset;
4376 bp->children = g_ptr_array_new ();
4378 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);
4380 methods = g_ptr_array_new ();
4381 method_domains = g_ptr_array_new ();
4382 method_seq_points = g_ptr_array_new ();
4384 mono_loader_lock ();
4385 g_hash_table_iter_init (&iter, domains);
4386 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4387 mono_domain_lock (domain);
4388 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4389 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4390 if (bp_matches_method (bp, m)) {
4391 /* Save the info locally to simplify the code inside the domain lock */
4392 g_ptr_array_add (methods, m);
4393 g_ptr_array_add (method_domains, domain);
4394 g_ptr_array_add (method_seq_points, seq_points);
4397 mono_domain_unlock (domain);
4400 for (i = 0; i < methods->len; ++i) {
4401 m = (MonoMethod *)g_ptr_array_index (methods, i);
4402 domain = (MonoDomain *)g_ptr_array_index (method_domains, i);
4403 seq_points = (MonoSeqPointInfo *)g_ptr_array_index (method_seq_points, i);
4404 set_bp_in_method (domain, m, seq_points, bp, error);
4407 g_ptr_array_add (breakpoints, bp);
4408 mono_loader_unlock ();
4410 g_ptr_array_free (methods, TRUE);
4411 g_ptr_array_free (method_domains, TRUE);
4412 g_ptr_array_free (method_seq_points, TRUE);
4414 if (error && !mono_error_ok (error)) {
4415 clear_breakpoint (bp);
4423 clear_breakpoint (MonoBreakpoint *bp)
4427 // FIXME: locking, races
4428 for (i = 0; i < bp->children->len; ++i) {
4429 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, i);
4431 remove_breakpoint (inst);
4436 mono_loader_lock ();
4437 g_ptr_array_remove (breakpoints, bp);
4438 mono_loader_unlock ();
4440 g_ptr_array_free (bp->children, TRUE);
4445 breakpoints_cleanup (void)
4449 mono_loader_lock ();
4451 while (i < event_requests->len) {
4452 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
4454 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4455 clear_breakpoint ((MonoBreakpoint *)req->info);
4456 g_ptr_array_remove_index_fast (event_requests, i);
4463 for (i = 0; i < breakpoints->len; ++i)
4464 g_free (g_ptr_array_index (breakpoints, i));
4466 g_ptr_array_free (breakpoints, TRUE);
4467 g_hash_table_destroy (bp_locs);
4472 mono_loader_unlock ();
4476 * clear_breakpoints_for_domain:
4478 * Clear breakpoint instances which reference DOMAIN.
4481 clear_breakpoints_for_domain (MonoDomain *domain)
4485 /* This could be called after shutdown */
4489 mono_loader_lock ();
4490 for (i = 0; i < breakpoints->len; ++i) {
4491 MonoBreakpoint *bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4494 while (j < bp->children->len) {
4495 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4497 if (inst->domain == domain) {
4498 remove_breakpoint (inst);
4502 g_ptr_array_remove_index_fast (bp->children, j);
4508 mono_loader_unlock ();
4514 * Return FALSE if single stepping needs to continue.
4517 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp, DebuggerTlsData *tls, MonoContext *ctx)
4519 MonoDebugMethodInfo *minfo;
4520 MonoDebugSourceLocation *loc = NULL;
4521 gboolean hit = TRUE;
4524 if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK)) {
4526 * These seq points are inserted by the JIT after calls, step over needs to skip them.
4528 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);
4532 if (req->depth == STEP_DEPTH_OVER && hit) {
4533 if (!tls->context.valid)
4534 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4535 compute_frame_info (tls->thread, tls);
4536 if (req->nframes && tls->frame_count && tls->frame_count > req->nframes) {
4537 /* Hit the breakpoint in a recursive call */
4538 DEBUG_PRINTF (1, "[%p] Breakpoint at lower frame while stepping over, continuing single stepping.\n", (gpointer) (gsize) mono_native_thread_id_get ());
4543 if (req->depth == STEP_DEPTH_INTO && req->size == STEP_SIZE_MIN && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) && ss_req->start_method){
4544 method = jinfo_get_method (ji);
4545 if (!tls->context.valid)
4546 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4547 compute_frame_info (tls->thread, tls);
4548 if (ss_req->start_method == method && req->nframes && tls->frame_count == req->nframes) {//Check also frame count(could be recursion)
4549 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);
4554 if (req->size != STEP_SIZE_LINE)
4557 /* Have to check whenever a different source line was reached */
4558 method = jinfo_get_method (ji);
4559 minfo = mono_debug_lookup_method (method);
4562 loc = mono_debug_method_lookup_location (minfo, sp->il_offset);
4565 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);
4566 ss_req->last_method = method;
4568 } else if (loc && method == ss_req->last_method && loc->row == ss_req->last_line) {
4569 DEBUG_PRINTF (1, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer) (gsize) mono_native_thread_id_get (), loc->row);
4574 ss_req->last_method = method;
4575 ss_req->last_line = loc->row;
4576 mono_debug_free_source_location (loc);
4583 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4585 return bp->method && bp->method->klass->image->assembly == assembly;
4589 process_breakpoint_inner (DebuggerTlsData *tls, gboolean from_signal)
4593 int i, j, suspend_policy;
4594 guint32 native_offset;
4596 BreakpointInstance *inst;
4597 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4598 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4599 EventKind kind = EVENT_KIND_BREAKPOINT;
4600 MonoContext *ctx = &tls->restore_state.ctx;
4602 MonoSeqPointInfo *info;
4606 // FIXME: Speed this up
4608 ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
4609 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4610 g_assert (ji && !ji->is_trampoline);
4611 method = jinfo_get_method (ji);
4613 /* Compute the native offset of the breakpoint from the ip */
4614 native_offset = ip - (guint8*)ji->code_start;
4617 * Skip the instruction causing the breakpoint signal.
4620 mono_arch_skip_breakpoint (ctx, ji);
4622 if (method->wrapper_type || tls->disable_breakpoints)
4625 bp_reqs = g_ptr_array_new ();
4626 ss_reqs = g_ptr_array_new ();
4627 ss_reqs_orig = g_ptr_array_new ();
4629 mono_loader_lock ();
4632 * The ip points to the instruction causing the breakpoint event, which is after
4633 * the offset recorded in the seq point map, so find the prev seq point before ip.
4635 found_sp = mono_find_prev_seq_point_for_native_offset (mono_domain_get (), method, native_offset, &info, &sp);
4638 no_seq_points_found (method, native_offset);
4640 g_assert (found_sp);
4642 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);
4645 for (i = 0; i < breakpoints->len; ++i) {
4646 bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4651 for (j = 0; j < bp->children->len; ++j) {
4652 inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4653 if (inst->ji == ji && inst->il_offset == sp.il_offset && inst->native_offset == sp.native_offset) {
4654 if (bp->req->event_kind == EVENT_KIND_STEP) {
4655 g_ptr_array_add (ss_reqs_orig, bp->req);
4657 g_ptr_array_add (bp_reqs, bp->req);
4662 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4663 /* Maybe a method entry/exit event */
4664 if (sp.il_offset == METHOD_ENTRY_IL_OFFSET)
4665 kind = EVENT_KIND_METHOD_ENTRY;
4666 else if (sp.il_offset == METHOD_EXIT_IL_OFFSET)
4667 kind = EVENT_KIND_METHOD_EXIT;
4670 /* Process single step requests */
4671 for (i = 0; i < ss_reqs_orig->len; ++i) {
4672 EventRequest *req = (EventRequest *)g_ptr_array_index (ss_reqs_orig, i);
4673 SingleStepReq *ss_req = (SingleStepReq *)req->info;
4676 if (mono_thread_internal_current () != ss_req->thread)
4679 hit = ss_update (ss_req, ji, &sp, tls, ctx);
4681 g_ptr_array_add (ss_reqs, req);
4683 /* Start single stepping again from the current sequence point */
4684 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
4687 if (ss_reqs->len > 0)
4688 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4689 if (bp_reqs->len > 0)
4690 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4691 if (kind != EVENT_KIND_BREAKPOINT)
4692 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4694 mono_loader_unlock ();
4696 g_ptr_array_free (bp_reqs, TRUE);
4697 g_ptr_array_free (ss_reqs, TRUE);
4700 * FIXME: The first event will suspend, so the second will only be sent after the
4704 process_event (EVENT_KIND_STEP, method, 0, ctx, ss_events, suspend_policy);
4706 process_event (kind, method, 0, ctx, bp_events, suspend_policy);
4707 if (enter_leave_events)
4708 process_event (kind, method, 0, ctx, enter_leave_events, suspend_policy);
4711 /* Process a breakpoint/single step event after resuming from a signal handler */
4713 process_signal_event (void (*func) (DebuggerTlsData*, gboolean))
4715 DebuggerTlsData *tls;
4716 MonoThreadUnwindState orig_restore_state;
4719 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4720 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4721 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4722 mono_thread_state_init_from_monoctx (&tls->restore_state, &tls->handler_ctx);
4726 /* This is called when resuming from a signal handler, so it shouldn't return */
4727 memcpy (&ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4728 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4729 mono_restore_context (&ctx);
4730 g_assert_not_reached ();
4734 process_breakpoint (void)
4736 process_signal_event (process_breakpoint_inner);
4740 resume_from_signal_handler (void *sigctx, void *func)
4742 DebuggerTlsData *tls;
4745 /* Save the original context in TLS */
4746 // FIXME: This might not work on an altstack ?
4747 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4749 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer) (gsize) mono_native_thread_id_get ());
4752 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4753 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4754 // clob:c could be added to op_seq_point.
4756 mono_sigctx_to_monoctx (sigctx, &ctx);
4757 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4758 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4759 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4761 MONO_CONTEXT_SET_IP (&ctx, func);
4763 mono_monoctx_to_sigctx (&ctx, sigctx);
4765 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4766 mono_ppc_set_func_into_sigctx (sigctx, func);
4771 mono_debugger_agent_breakpoint_hit (void *sigctx)
4774 * We are called from a signal handler, and running code there causes all kinds of
4775 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4776 * So set up the signal context to return to the real breakpoint handler function.
4778 resume_from_signal_handler (sigctx, process_breakpoint);
4782 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4784 if (frame->managed) {
4785 *(MonoContext*)data = *ctx;
4794 * Called by System.Diagnostics.Debugger:Break ().
4797 mono_debugger_agent_user_break (void)
4799 if (agent_config.enabled) {
4804 /* Obtain a context */
4805 MONO_CONTEXT_SET_IP (&ctx, NULL);
4806 mono_walk_stack_with_ctx (user_break_cb, NULL, (MonoUnwindOptions)0, &ctx);
4807 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4809 mono_loader_lock ();
4810 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4811 mono_loader_unlock ();
4813 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4814 } else if (debug_options.native_debugger_break) {
4820 ss_depth_to_string (StepDepth depth)
4823 case STEP_DEPTH_OVER:
4825 case STEP_DEPTH_OUT:
4827 case STEP_DEPTH_INTO:
4830 g_assert_not_reached ();
4836 process_single_step_inner (DebuggerTlsData *tls, gboolean from_signal)
4841 int il_offset, suspend_policy;
4844 MonoContext *ctx = &tls->restore_state.ctx;
4847 MonoSeqPointInfo *info;
4849 ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
4851 /* Skip the instruction causing the single step */
4853 mono_arch_skip_single_step (ctx);
4855 if (suspend_count > 0) {
4856 /* Fastpath during invokes, see in process_suspend () */
4857 if (suspend_count - tls->resume_count == 0)
4859 process_suspend (tls, ctx);
4864 // FIXME: A suspend race
4867 if (mono_thread_internal_current () != ss_req->thread)
4870 if (log_level > 0) {
4871 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4873 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);
4876 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4877 g_assert (ji && !ji->is_trampoline);
4878 method = jinfo_get_method (ji);
4881 if (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4886 * Stopping in memset makes half-initialized vtypes visible.
4887 * Stopping in memcpy makes half-copied vtypes visible.
4889 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
4893 * The ip points to the instruction causing the single step event, which is before
4894 * the offset recorded in the seq point map, so find the next seq point after ip.
4896 if (!mono_find_next_seq_point_for_native_offset (domain, method, (guint8*)ip - (guint8*)ji->code_start, &info, &sp))
4899 il_offset = sp.il_offset;
4901 if (!ss_update (ss_req, ji, &sp, tls, ctx))
4904 /* Start single stepping again from the current sequence point */
4905 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
4907 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
4908 (method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4909 !strcmp (method->name, ".cctor"))
4912 // FIXME: Has to lock earlier
4914 reqs = g_ptr_array_new ();
4916 mono_loader_lock ();
4918 g_ptr_array_add (reqs, ss_req->req);
4920 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4922 g_ptr_array_free (reqs, TRUE);
4924 mono_loader_unlock ();
4926 process_event (EVENT_KIND_STEP, jinfo_get_method (ji), il_offset, ctx, events, suspend_policy);
4930 process_single_step (void)
4932 process_signal_event (process_single_step_inner);
4936 * mono_debugger_agent_single_step_event:
4938 * Called from a signal handler to handle a single step event.
4941 mono_debugger_agent_single_step_event (void *sigctx)
4943 /* Resume to process_single_step through the signal context */
4945 // FIXME: Since step out/over is implemented using step in, the step in case should
4946 // be as fast as possible. Move the relevant code from process_single_step_inner ()
4949 if (is_debugger_thread ()) {
4951 * This could happen despite our best effors when the runtime calls
4952 * assembly/type resolve hooks.
4953 * FIXME: Breakpoints too.
4957 mono_sigctx_to_monoctx (sigctx, &ctx);
4958 mono_arch_skip_single_step (&ctx);
4959 mono_monoctx_to_sigctx (&ctx, sigctx);
4963 resume_from_signal_handler (sigctx, process_single_step);
4967 debugger_agent_single_step_from_context (MonoContext *ctx)
4969 DebuggerTlsData *tls;
4970 MonoThreadUnwindState orig_restore_state;
4972 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4973 /* Fastpath during invokes, see in process_suspend () */
4974 if (tls && suspend_count && suspend_count - tls->resume_count == 0)
4977 if (is_debugger_thread ())
4982 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4983 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4984 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
4985 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
4987 process_single_step_inner (tls, FALSE);
4989 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4990 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4994 debugger_agent_breakpoint_from_context (MonoContext *ctx)
4996 DebuggerTlsData *tls;
4997 MonoThreadUnwindState orig_restore_state;
5000 if (is_debugger_thread ())
5003 orig_ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
5004 MONO_CONTEXT_SET_IP (ctx, orig_ip - 1);
5006 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5008 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5009 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5010 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5012 process_breakpoint_inner (tls, FALSE);
5014 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5015 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5016 if (MONO_CONTEXT_GET_IP (ctx) == orig_ip - 1)
5017 MONO_CONTEXT_SET_IP (ctx, orig_ip);
5021 * start_single_stepping:
5023 * Turn on single stepping. Can be called multiple times, for example,
5024 * by a single step event request + a suspend.
5027 start_single_stepping (void)
5029 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5030 int val = InterlockedIncrement (&ss_count);
5033 mono_arch_start_single_stepping ();
5035 g_assert_not_reached ();
5040 stop_single_stepping (void)
5042 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5043 int val = InterlockedDecrement (&ss_count);
5046 mono_arch_stop_single_stepping ();
5048 g_assert_not_reached ();
5055 * Stop the single stepping operation given by SS_REQ.
5058 ss_stop (SingleStepReq *ss_req)
5063 for (l = ss_req->bps; l; l = l->next) {
5064 clear_breakpoint ((MonoBreakpoint *)l->data);
5066 g_slist_free (ss_req->bps);
5070 if (ss_req->global) {
5071 stop_single_stepping ();
5072 ss_req->global = FALSE;
5079 * Start the single stepping operation given by SS_REQ from the sequence point SP.
5080 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
5081 * belong to the same thread as CTX.
5082 * If FRAMES is not-null, use that instead of tls->frames for placing breakpoints etc.
5085 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint* sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls,
5086 gboolean step_to_catch, StackFrame **frames, int nframes)
5088 int i, j, frame_index;
5089 SeqPoint *next_sp, *parent_sp = NULL;
5090 SeqPoint local_sp, local_parent_sp;
5093 MonoSeqPointInfo *parent_info;
5094 MonoMethod *parent_sp_method = NULL;
5095 gboolean enable_global = FALSE;
5097 /* Stop the previous operation */
5101 * Implement single stepping using breakpoints if possible.
5103 if (step_to_catch) {
5104 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
5105 ss_req->bps = g_slist_append (ss_req->bps, bp);
5109 if (ctx && !frames) {
5110 /* Need parent frames */
5111 if (!tls->context.valid)
5112 mono_thread_state_init_from_monoctx (&tls->context, ctx);
5113 compute_frame_info (tls->thread, tls);
5114 frames = tls->frames;
5115 nframes = tls->frame_count;
5119 * Find the first sequence point in the current or in a previous frame which
5120 * is not the last in its method.
5122 if (ss_req->depth == STEP_DEPTH_OUT) {
5123 /* Ignore seq points in current method */
5124 while (frame_index < nframes) {
5125 StackFrame *frame = frames [frame_index];
5127 method = frame->method;
5128 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5129 sp = (found_sp)? &local_sp : NULL;
5131 if (sp && sp->next_len != 0)
5134 // There could be method calls before the next seq point in the caller when using nested calls
5135 //enable_global = TRUE;
5137 if (sp && sp->next_len == 0) {
5139 while (frame_index < nframes) {
5140 StackFrame *frame = frames [frame_index];
5142 method = frame->method;
5143 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5144 sp = (found_sp)? &local_sp : NULL;
5145 if (sp && sp->next_len != 0)
5151 /* Have to put a breakpoint into a parent frame since the seq points might not cover all control flow out of the method */
5152 while (frame_index < nframes) {
5153 StackFrame *frame = frames [frame_index];
5155 parent_sp_method = frame->method;
5156 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &parent_info, &local_parent_sp);
5157 parent_sp = found_sp ? &local_parent_sp : NULL;
5158 if (found_sp && parent_sp->next_len != 0)
5166 if (sp && sp->next_len > 0) {
5167 SeqPoint* next = g_new(SeqPoint, sp->next_len);
5169 mono_seq_point_init_next (info, *sp, next);
5170 for (i = 0; i < sp->next_len; i++) {
5173 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
5174 ss_req->bps = g_slist_append (ss_req->bps, bp);
5180 SeqPoint* next = g_new(SeqPoint, parent_sp->next_len);
5182 mono_seq_point_init_next (parent_info, *parent_sp, next);
5183 for (i = 0; i < parent_sp->next_len; i++) {
5186 bp = set_breakpoint (parent_sp_method, next_sp->il_offset, ss_req->req, NULL);
5187 ss_req->bps = g_slist_append (ss_req->bps, bp);
5192 if (ss_req->nframes == 0)
5193 ss_req->nframes = nframes;
5195 if ((ss_req->depth == STEP_DEPTH_OVER) && (!sp && !parent_sp)) {
5196 DEBUG_PRINTF (1, "[dbg] No parent frame for step over, transition to step into.\n");
5198 * This is needed since if we leave managed code, and later return to it, step over
5199 * is not going to stop.
5200 * This approach is a bit ugly, since we change the step depth, but it only affects
5201 * clients who reuse the same step request, and only in this special case.
5203 ss_req->depth = STEP_DEPTH_INTO;
5206 if (ss_req->depth == STEP_DEPTH_OVER) {
5207 /* Need to stop in catch clauses as well */
5208 for (i = 0; i < nframes; ++i) {
5209 StackFrame *frame = frames [i];
5212 MonoJitInfo *jinfo = frame->ji;
5213 for (j = 0; j < jinfo->num_clauses; ++j) {
5214 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5216 found_sp = mono_find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL, &local_sp);
5217 sp = (found_sp)? &local_sp : NULL;
5219 bp = set_breakpoint (frame->method, sp->il_offset, ss_req->req, NULL);
5220 ss_req->bps = g_slist_append (ss_req->bps, bp);
5227 if (ss_req->depth == STEP_DEPTH_INTO) {
5228 /* Enable global stepping so we stop at method entry too */
5229 enable_global = TRUE;
5233 * The ctx/frame info computed above will become invalid when we continue.
5235 tls->context.valid = FALSE;
5236 tls->async_state.valid = FALSE;
5237 invalidate_frames (tls);
5240 if (enable_global) {
5241 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5242 ss_req->global = TRUE;
5243 start_single_stepping ();
5244 } else if (!ss_req->bps) {
5245 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5246 ss_req->global = TRUE;
5247 start_single_stepping ();
5249 ss_req->global = FALSE;
5254 * Start single stepping of thread THREAD
5257 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req)
5259 DebuggerTlsData *tls;
5260 MonoSeqPointInfo *info = NULL;
5261 SeqPoint *sp = NULL;
5264 MonoMethod *method = NULL;
5265 MonoDebugMethodInfo *minfo;
5266 gboolean step_to_catch = FALSE;
5267 gboolean set_ip = FALSE;
5268 StackFrame **frames = NULL;
5271 if (suspend_count == 0)
5272 return ERR_NOT_SUSPENDED;
5274 wait_for_suspend ();
5276 // FIXME: Multiple requests
5278 DEBUG_PRINTF (0, "Received a single step request while the previous one was still active.\n");
5279 return ERR_NOT_IMPLEMENTED;
5282 DEBUG_PRINTF (1, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth));
5284 ss_req = g_new0 (SingleStepReq, 1);
5286 ss_req->thread = thread;
5287 ss_req->size = size;
5288 ss_req->depth = depth;
5289 ss_req->filter = filter;
5292 mono_loader_lock ();
5293 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5294 mono_loader_unlock ();
5296 g_assert (tls->context.valid);
5298 if (tls->restore_state.valid && MONO_CONTEXT_GET_IP (&tls->context.ctx) != MONO_CONTEXT_GET_IP (&tls->restore_state.ctx)) {
5300 * Need to start single stepping from restore_state and not from the current state
5303 frames = compute_frame_info_from (thread, tls, &tls->restore_state, &nframes);
5306 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5308 if (tls->catch_state.valid) {
5310 StackFrameInfo frame;
5311 MonoContext new_ctx;
5312 MonoLMF *lmf = NULL;
5315 * We are stopped at a throw site. Stepping should go to the catch site.
5318 /* Find the the jit info for the catch context */
5319 res = mono_find_jit_info_ext (
5320 (MonoDomain *)tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN],
5321 (MonoJitTlsData *)((MonoThreadInfo*)thread->thread_info)->jit_data,
5322 NULL, &tls->catch_state.ctx, &new_ctx, NULL, &lmf, NULL, &frame);
5324 g_assert (frame.type == FRAME_TYPE_MANAGED);
5327 * Find the seq point corresponding to the landing site ip, which is the first seq
5330 found_sp = mono_find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info, &local_sp);
5331 sp = (found_sp)? &local_sp : NULL;
5333 no_seq_points_found (frame.method, frame.native_offset);
5336 method = frame.method;
5338 step_to_catch = TRUE;
5339 /* This make sure the seq point is not skipped by process_single_step () */
5340 ss_req->last_sp = NULL;
5343 if (!step_to_catch) {
5344 StackFrame *frame = NULL;
5347 if (frames && nframes)
5350 compute_frame_info (thread, tls);
5352 if (tls->frame_count)
5353 frame = tls->frames [0];
5356 if (ss_req->size == STEP_SIZE_LINE) {
5358 ss_req->last_method = frame->method;
5359 ss_req->last_line = -1;
5361 minfo = mono_debug_lookup_method (frame->method);
5362 if (minfo && frame->il_offset != -1) {
5363 MonoDebugSourceLocation *loc = mono_debug_method_lookup_location (minfo, frame->il_offset);
5366 ss_req->last_line = loc->row;
5374 if (!method && frame->il_offset != -1) {
5375 /* FIXME: Sort the table and use a binary search */
5376 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5377 sp = (found_sp)? &local_sp : NULL;
5379 no_seq_points_found (frame->method, frame->native_offset);
5381 method = frame->method;
5386 ss_req->start_method = method;
5388 ss_start (ss_req, method, sp, info, set_ip ? &tls->restore_state.ctx : &tls->context.ctx, tls, step_to_catch, frames, nframes);
5391 free_frames (frames, nframes);
5397 ss_destroy (SingleStepReq *req)
5400 g_assert (ss_req == req);
5409 ss_clear_for_assembly (SingleStepReq *req, MonoAssembly *assembly)
5412 gboolean found = TRUE;
5416 for (l = ss_req->bps; l; l = l->next) {
5417 if (breakpoint_matches_assembly ((MonoBreakpoint *)l->data, assembly)) {
5418 clear_breakpoint ((MonoBreakpoint *)l->data);
5419 ss_req->bps = g_slist_delete_link (ss_req->bps, l);
5428 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5431 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5437 if (!agent_config.enabled)
5440 mono_loader_lock ();
5441 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5442 mono_loader_unlock ();
5445 ei.category = category ? mono_string_to_utf8 (category) : NULL;
5446 ei.message = message ? mono_string_to_utf8 (message) : NULL;
5448 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5450 g_free (ei.category);
5451 g_free (ei.message);
5455 mono_debugger_agent_debug_log_is_enabled (void)
5457 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5458 return agent_config.enabled;
5461 #if defined(PLATFORM_ANDROID) || defined(TARGET_ANDROID)
5463 mono_debugger_agent_unhandled_exception (MonoException *exc)
5472 memset (&ei, 0, sizeof (EventInfo));
5473 ei.exc = (MonoObject*)exc;
5475 mono_loader_lock ();
5476 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5477 mono_loader_unlock ();
5479 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5484 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5485 MonoContext *catch_ctx)
5487 int i, j, suspend_policy;
5489 MonoJitInfo *ji, *catch_ji;
5491 DebuggerTlsData *tls = NULL;
5493 if (thread_to_tls != NULL) {
5494 MonoInternalThread *thread = mono_thread_internal_current ();
5496 mono_loader_lock ();
5497 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5498 mono_loader_unlock ();
5500 if (tls && tls->abort_requested)
5502 if (tls && tls->disable_breakpoints)
5506 memset (&ei, 0, sizeof (EventInfo));
5508 /* Just-In-Time debugging */
5510 if (agent_config.onuncaught && !inited) {
5511 finish_agent_init (FALSE);
5514 * Send an unsolicited EXCEPTION event with a dummy request id.
5516 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5517 ei.exc = (MonoObject*)exc;
5518 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5521 } else if (agent_config.onthrow && !inited) {
5523 gboolean found = FALSE;
5525 for (l = agent_config.onthrow; l; l = l->next) {
5526 char *ex_type = (char *)l->data;
5527 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5529 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5536 finish_agent_init (FALSE);
5539 * Send an unsolicited EXCEPTION event with a dummy request id.
5541 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5542 ei.exc = (MonoObject*)exc;
5543 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5551 ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5553 catch_ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5557 ei.exc = (MonoObject*)exc;
5558 ei.caught = catch_ctx != NULL;
5560 mono_loader_lock ();
5562 /* Treat exceptions which are caught in non-user code as unhandled */
5563 for (i = 0; i < event_requests->len; ++i) {
5564 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
5565 if (req->event_kind != EVENT_KIND_EXCEPTION)
5568 for (j = 0; j < req->nmodifiers; ++j) {
5569 Modifier *mod = &req->modifiers [j];
5571 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5573 gboolean found = FALSE;
5574 MonoAssembly **assemblies = mod->data.assemblies;
5577 for (k = 0; assemblies [k]; ++k)
5578 if (assemblies [k] == jinfo_get_method (catch_ji)->klass->image->assembly)
5587 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5588 mono_loader_unlock ();
5590 if (tls && ei.caught && catch_ctx) {
5591 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5592 tls->catch_state.ctx = *catch_ctx;
5593 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5594 tls->catch_state.valid = TRUE;
5597 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5600 tls->catch_state.valid = FALSE;
5604 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5606 DebuggerTlsData *tls;
5611 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5616 * We're about to invoke an exception filter during the first pass of exception handling.
5618 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5619 * 'orig_ctx' is the context where the exception has been thrown.
5622 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5624 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5625 * the call site (line 37) and then continue to Main(), but it would never
5626 * include the throw site (line 32).
5628 * Since exception filters are invoked during the first pass of exception handling,
5629 * the stack frames of the throw site are still intact, so we should include them
5632 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5634 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5635 * but report the location of the 'throw' to the user.
5639 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5643 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5645 DebuggerTlsData *tls;
5650 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5654 tls->filter_state.valid = FALSE;
5658 * buffer_add_value_full:
5660 * Add the encoding of the value at ADDR described by T to the buffer.
5661 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5665 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5666 gboolean as_vtype, GHashTable *parent_vtypes)
5669 gboolean boxed_vtype = FALSE;
5672 if (!(*(void**)addr)) {
5673 /* This can happen with compiler generated locals */
5674 //printf ("%s\n", mono_type_full_name (t));
5675 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5678 g_assert (*(void**)addr);
5679 addr = *(void**)addr;
5684 case MONO_TYPE_BOOLEAN:
5687 case MONO_TYPE_CHAR:
5707 case MONO_TYPE_VOID:
5708 buffer_add_byte (buf, t->type);
5710 case MONO_TYPE_BOOLEAN:
5713 buffer_add_byte (buf, t->type);
5714 buffer_add_int (buf, *(gint8*)addr);
5716 case MONO_TYPE_CHAR:
5719 buffer_add_byte (buf, t->type);
5720 buffer_add_int (buf, *(gint16*)addr);
5725 buffer_add_byte (buf, t->type);
5726 buffer_add_int (buf, *(gint32*)addr);
5731 buffer_add_byte (buf, t->type);
5732 buffer_add_long (buf, *(gint64*)addr);
5736 /* Treat it as a vtype */
5738 case MONO_TYPE_PTR: {
5739 gssize val = *(gssize*)addr;
5741 buffer_add_byte (buf, t->type);
5742 buffer_add_long (buf, val);
5746 case MONO_TYPE_STRING:
5747 case MONO_TYPE_SZARRAY:
5748 case MONO_TYPE_OBJECT:
5749 case MONO_TYPE_CLASS:
5750 case MONO_TYPE_ARRAY:
5751 obj = *(MonoObject**)addr;
5754 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5756 if (obj->vtable->klass->valuetype) {
5757 t = &obj->vtable->klass->byval_arg;
5758 addr = mono_object_unbox (obj);
5761 } else if (obj->vtable->klass->rank) {
5762 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5763 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5764 buffer_add_byte (buf, MONO_TYPE_CLASS);
5766 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5768 buffer_add_objid (buf, obj);
5772 case MONO_TYPE_VALUETYPE:
5773 case MONO_TYPE_TYPEDBYREF: {
5777 MonoClass *klass = mono_class_from_mono_type (t);
5782 * Handle boxed vtypes recursively referencing themselves using fields.
5785 parent_vtypes = g_hash_table_new (NULL, NULL);
5786 vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
5788 if (CHECK_PROTOCOL_VERSION (2, 33)) {
5789 buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
5790 buffer_add_int (buf, vtype_index - 1);
5792 /* The client can't handle PARENT_VTYPE */
5793 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5797 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
5801 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5802 buffer_add_byte (buf, klass->enumtype);
5803 buffer_add_typeid (buf, domain, klass);
5807 while ((f = mono_class_get_fields (klass, &iter))) {
5808 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5810 if (mono_field_is_deleted (f))
5814 buffer_add_int (buf, nfields);
5817 while ((f = mono_class_get_fields (klass, &iter))) {
5818 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5820 if (mono_field_is_deleted (f))
5822 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE, parent_vtypes);
5826 g_hash_table_remove (parent_vtypes, addr);
5827 if (g_hash_table_size (parent_vtypes) == 0) {
5828 g_hash_table_destroy (parent_vtypes);
5829 parent_vtypes = NULL;
5834 case MONO_TYPE_GENERICINST:
5835 if (mono_type_generic_inst_is_valuetype (t)) {
5847 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5849 buffer_add_value_full (buf, t, addr, domain, FALSE, NULL);
5853 obj_is_of_type (MonoObject *obj, MonoType *t)
5855 MonoClass *klass = obj->vtable->klass;
5856 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5857 if (mono_class_is_transparent_proxy (klass)) {
5858 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5859 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5869 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5872 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5878 gpointer iter = NULL;
5882 is_enum = decode_byte (buf, &buf, limit);
5883 /* Enums are sent as a normal vtype */
5885 return ERR_NOT_IMPLEMENTED;
5886 klass = decode_typeid (buf, &buf, limit, &d, &err);
5887 if (err != ERR_NONE)
5890 if (t && klass != mono_class_from_mono_type (t)) {
5891 char *name = mono_type_full_name (t);
5892 char *name2 = mono_type_full_name (&klass->byval_arg);
5893 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got %s.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, name2);
5896 return ERR_INVALID_ARGUMENT;
5899 nfields = decode_int (buf, &buf, limit);
5900 while ((f = mono_class_get_fields (klass, &iter))) {
5901 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5903 if (mono_field_is_deleted (f))
5905 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5906 if (err != ERR_NONE)
5910 g_assert (nfields == 0);
5918 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5922 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5923 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5924 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5925 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5926 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE) &&
5927 !(t->type == MONO_TYPE_VALUETYPE && type == MONO_TYPE_OBJECT)) {
5928 char *name = mono_type_full_name (t);
5929 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
5931 return ERR_INVALID_ARGUMENT;
5935 case MONO_TYPE_BOOLEAN:
5936 *(guint8*)addr = decode_int (buf, &buf, limit);
5938 case MONO_TYPE_CHAR:
5939 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5942 *(gint8*)addr = decode_int (buf, &buf, limit);
5945 *(guint8*)addr = decode_int (buf, &buf, limit);
5948 *(gint16*)addr = decode_int (buf, &buf, limit);
5951 *(guint16*)addr = decode_int (buf, &buf, limit);
5954 *(gint32*)addr = decode_int (buf, &buf, limit);
5957 *(guint32*)addr = decode_int (buf, &buf, limit);
5960 *(gint64*)addr = decode_long (buf, &buf, limit);
5963 *(guint64*)addr = decode_long (buf, &buf, limit);
5966 *(guint32*)addr = decode_int (buf, &buf, limit);
5969 *(guint64*)addr = decode_long (buf, &buf, limit);
5972 /* We send these as I8, so we get them back as such */
5973 g_assert (type == MONO_TYPE_I8);
5974 *(gssize*)addr = decode_long (buf, &buf, limit);
5976 case MONO_TYPE_GENERICINST:
5977 if (MONO_TYPE_ISSTRUCT (t)) {
5978 /* The client sends these as a valuetype */
5986 /* We send these as vtypes, so we get them back as such */
5987 g_assert (type == MONO_TYPE_VALUETYPE);
5990 case MONO_TYPE_VALUETYPE:
5991 if (type == MONO_TYPE_OBJECT) {
5993 int objid = decode_objid (buf, &buf, limit);
5997 err = get_object (objid, (MonoObject**)&obj);
5998 if (err != ERR_NONE)
6001 return ERR_INVALID_ARGUMENT;
6002 if (obj->vtable->klass != mono_class_from_mono_type (t)) {
6003 DEBUG_PRINTF (1, "Expected type '%s', got object '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6004 return ERR_INVALID_ARGUMENT;
6006 memcpy (addr, mono_object_unbox (obj), mono_class_value_size (obj->vtable->klass, NULL));
6008 err = decode_vtype (t, domain, addr, buf, &buf, limit);
6009 if (err != ERR_NONE)
6015 if (MONO_TYPE_IS_REFERENCE (t)) {
6016 if (type == MONO_TYPE_OBJECT) {
6017 int objid = decode_objid (buf, &buf, limit);
6021 err = get_object (objid, (MonoObject**)&obj);
6022 if (err != ERR_NONE)
6026 if (!obj_is_of_type (obj, t)) {
6027 DEBUG_PRINTF (1, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6028 return ERR_INVALID_ARGUMENT;
6031 if (obj && obj->vtable->domain != domain)
6032 return ERR_INVALID_ARGUMENT;
6034 mono_gc_wbarrier_generic_store (addr, obj);
6035 } else if (type == VALUE_TYPE_ID_NULL) {
6036 *(MonoObject**)addr = NULL;
6037 } else if (type == MONO_TYPE_VALUETYPE) {
6046 /* This can happen when round-tripping boxed vtypes */
6048 * Obtain vtype class.
6049 * Same as the beginning of the handle_vtype case above.
6052 is_enum = decode_byte (buf, &buf, limit);
6054 return ERR_NOT_IMPLEMENTED;
6055 klass = decode_typeid (buf, &buf, limit, &d, &err);
6056 if (err != ERR_NONE)
6059 /* Decode the vtype into a temporary buffer, then box it. */
6060 vtype_buf_size = mono_class_value_size (klass, NULL);
6061 vtype_buf = (guint8 *)g_malloc0 (vtype_buf_size);
6062 g_assert (vtype_buf);
6065 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
6066 if (err != ERR_NONE) {
6070 *(MonoObject**)addr = mono_value_box_checked (d, klass, vtype_buf, &error);
6071 mono_error_cleanup (&error);
6074 char *name = mono_type_full_name (t);
6075 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
6077 return ERR_INVALID_ARGUMENT;
6091 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6095 int type = decode_byte (buf, &buf, limit);
6097 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
6098 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
6099 guint8 *nullable_buf;
6102 * First try decoding it as a Nullable`1
6104 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6105 if (err == ERR_NONE)
6109 * Then try decoding as a primitive value or null.
6111 if (targ->type == type) {
6112 nullable_buf = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
6113 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
6114 if (err != ERR_NONE) {
6115 g_free (nullable_buf);
6118 MonoObject *boxed = mono_value_box_checked (domain, mono_class_from_mono_type (targ), nullable_buf, &error);
6119 if (!is_ok (&error)) {
6120 mono_error_cleanup (&error);
6121 return ERR_INVALID_OBJECT;
6123 mono_nullable_init (addr, boxed, mono_class_from_mono_type (t));
6124 g_free (nullable_buf);
6127 } else if (type == VALUE_TYPE_ID_NULL) {
6128 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
6134 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6138 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
6142 guint8 *addr, *gaddr;
6145 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6146 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6149 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
6150 reg_val = mono_arch_context_get_int_reg (ctx, reg);
6152 buffer_add_value_full (buf, t, ®_val, domain, as_vtype, NULL);
6154 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6155 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6156 addr += (gint32)var->offset;
6158 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6160 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6162 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6165 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6166 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
6167 /* Same as regoffset, but with an indirection */
6168 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6169 addr += (gint32)var->offset;
6171 gaddr = (guint8 *)*(gpointer*)addr;
6173 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL);
6175 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
6176 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
6177 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
6178 MonoGSharedVtMethodRuntimeInfo *info;
6184 g_assert (info_var);
6185 g_assert (locals_var);
6187 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6188 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6189 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6190 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6191 addr += (gint32)info_var->offset;
6192 info = (MonoGSharedVtMethodRuntimeInfo *)*(gpointer*)addr;
6193 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6194 info = (MonoGSharedVtMethodRuntimeInfo *)mono_arch_context_get_int_reg (ctx, reg);
6196 g_assert_not_reached ();
6200 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6201 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6202 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6203 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6204 addr += (gint32)locals_var->offset;
6205 locals = (guint8 *)*(gpointer*)addr;
6206 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6207 locals = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6209 g_assert_not_reached ();
6213 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6215 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6220 g_assert_not_reached ();
6225 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
6229 guint8 *addr, *gaddr;
6231 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6232 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6234 if (MONO_TYPE_IS_REFERENCE (t))
6235 size = sizeof (gpointer);
6237 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6240 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6241 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6243 gboolean is_signed = FALSE;
6246 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6249 // FIXME: Write barriers
6250 mono_gc_memmove_atomic (addr, val, size);
6255 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6260 v = is_signed ? *(gint8*)val : *(guint8*)val;
6263 v = is_signed ? *(gint16*)val : *(guint16*)val;
6266 v = is_signed ? *(gint32*)val : *(guint32*)val;
6269 v = is_signed ? *(gint64*)val : *(guint64*)val;
6272 g_assert_not_reached ();
6275 /* Set value on the stack or in the return ctx */
6276 if (reg_locations [reg]) {
6277 /* Saved on the stack */
6278 DEBUG_PRINTF (1, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v);
6279 *(reg_locations [reg]) = v;
6282 DEBUG_PRINTF (1, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v);
6283 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6286 // FIXME: Move these to mono-context.h/c.
6287 mono_arch_context_set_int_reg (ctx, reg, v);
6289 // FIXME: Can't set registers, so we disable linears
6294 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6295 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6296 addr += (gint32)var->offset;
6298 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6301 addr = *(guint8**)addr;
6307 // FIXME: Write barriers
6308 mono_gc_memmove_atomic (addr, val, size);
6310 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6311 /* Same as regoffset, but with an indirection */
6312 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6313 addr += (gint32)var->offset;
6315 gaddr = (guint8 *)*(gpointer*)addr;
6317 // FIXME: Write barriers
6318 mono_gc_memmove_atomic (gaddr, val, size);
6320 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6324 g_assert_not_reached ();
6329 clear_event_request (int req_id, int etype)
6333 mono_loader_lock ();
6334 for (i = 0; i < event_requests->len; ++i) {
6335 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6337 if (req->id == req_id && req->event_kind == etype) {
6338 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6339 clear_breakpoint ((MonoBreakpoint *)req->info);
6340 if (req->event_kind == EVENT_KIND_STEP)
6341 ss_destroy ((SingleStepReq *)req->info);
6342 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6343 clear_breakpoint ((MonoBreakpoint *)req->info);
6344 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6345 clear_breakpoint ((MonoBreakpoint *)req->info);
6346 g_ptr_array_remove_index_fast (event_requests, i);
6351 mono_loader_unlock ();
6355 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
6359 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6360 m->kind = MOD_KIND_NONE;
6361 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6362 int count = 0, match_count = 0, pos;
6363 MonoAssembly **newassemblies;
6365 for (i = 0; m->data.assemblies [i]; ++i) {
6367 if (m->data.assemblies [i] == assembly)
6372 newassemblies = g_new0 (MonoAssembly*, count - match_count);
6375 for (i = 0; i < count; ++i)
6376 if (m->data.assemblies [i] != assembly)
6377 newassemblies [pos ++] = m->data.assemblies [i];
6378 g_assert (pos == count - match_count);
6379 g_free (m->data.assemblies);
6380 m->data.assemblies = newassemblies;
6386 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
6390 for (i = 0; i < req->nmodifiers; ++i) {
6391 Modifier *m = &req->modifiers [i];
6393 clear_assembly_from_modifier (req, m, assembly);
6398 * clear_event_requests_for_assembly:
6400 * Clear all events requests which reference ASSEMBLY.
6403 clear_event_requests_for_assembly (MonoAssembly *assembly)
6408 mono_loader_lock ();
6412 for (i = 0; i < event_requests->len; ++i) {
6413 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6415 clear_assembly_from_modifiers (req, assembly);
6417 if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly ((MonoBreakpoint *)req->info, assembly)) {
6418 clear_event_request (req->id, req->event_kind);
6423 if (req->event_kind == EVENT_KIND_STEP)
6424 ss_clear_for_assembly ((SingleStepReq *)req->info, assembly);
6427 mono_loader_unlock ();
6431 * type_comes_from_assembly:
6433 * GHRFunc that returns TRUE if klass comes from assembly
6436 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6438 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6442 * clear_types_for_assembly:
6444 * Clears types from loaded_classes for a given assembly
6447 clear_types_for_assembly (MonoAssembly *assembly)
6449 MonoDomain *domain = mono_domain_get ();
6450 AgentDomainInfo *info = NULL;
6452 if (!domain || !domain_jit_info (domain))
6453 /* Can happen during shutdown */
6456 info = get_agent_domain_info (domain);
6458 mono_loader_lock ();
6459 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6460 mono_loader_unlock ();
6464 add_thread (gpointer key, gpointer value, gpointer user_data)
6466 MonoInternalThread *thread = (MonoInternalThread *)value;
6467 Buffer *buf = (Buffer *)user_data;
6469 buffer_add_objid (buf, (MonoObject*)thread);
6473 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6476 guint8 *end = invoke->endp;
6480 MonoMethodSignature *sig;
6483 MonoObject *this_arg, *res, *exc;
6486 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6489 MonoStopwatch watch;
6491 if (invoke->method) {
6493 * Invoke this method directly, currently only Environment.Exit () is supported.
6496 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>");
6498 mono_runtime_try_invoke (invoke->method, NULL, invoke->args, &exc, &error);
6499 mono_error_assert_ok (&error);
6501 g_assert_not_reached ();
6504 m = decode_methodid (p, &p, end, &domain, &err);
6505 if (err != ERR_NONE)
6507 sig = mono_method_signature (m);
6509 if (m->klass->valuetype)
6510 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6512 this_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
6513 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6514 /* Should be null */
6515 int type = decode_byte (p, &p, end);
6516 if (type != VALUE_TYPE_ID_NULL) {
6517 DEBUG_PRINTF (1, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6518 return ERR_INVALID_ARGUMENT;
6520 memset (this_buf, 0, mono_class_instance_size (m->klass));
6521 } else if (m->klass->valuetype && !strcmp (m->name, ".ctor")) {
6525 int type = decode_byte (p, &tmp_p, end);
6526 if (type == VALUE_TYPE_ID_NULL) {
6527 memset (this_buf, 0, mono_class_instance_size (m->klass));
6530 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6531 if (err != ERR_NONE)
6535 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6536 if (err != ERR_NONE)
6540 if (!m->klass->valuetype)
6541 this_arg = *(MonoObject**)this_buf;
6545 if (MONO_CLASS_IS_INTERFACE (m->klass)) {
6547 DEBUG_PRINTF (1, "[%p] Error: Interface method invoked without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6548 return ERR_INVALID_ARGUMENT;
6550 m = mono_object_get_virtual_method (this_arg, m);
6551 /* Transform this to the format the rest of the code expects it to be */
6552 if (m->klass->valuetype) {
6553 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6554 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
6556 } else if ((m->flags & METHOD_ATTRIBUTE_VIRTUAL) && !m->klass->valuetype && invoke->flags & INVOKE_FLAG_VIRTUAL) {
6558 DEBUG_PRINTF (1, "[%p] Error: invoke with INVOKE_FLAG_VIRTUAL flag set without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6559 return ERR_INVALID_ARGUMENT;
6561 m = mono_object_get_virtual_method (this_arg, m);
6562 if (m->klass->valuetype) {
6563 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6564 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
6568 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>");
6570 if (this_arg && this_arg->vtable->domain != domain)
6573 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this_arg) {
6574 if (!strcmp (m->name, ".ctor")) {
6575 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
6576 return ERR_INVALID_ARGUMENT;
6579 this_arg = mono_object_new_checked (domain, m->klass, &error);
6580 mono_error_assert_ok (&error);
6583 return ERR_INVALID_ARGUMENT;
6587 if (this_arg && !obj_is_of_type (this_arg, &m->klass->byval_arg))
6588 return ERR_INVALID_ARGUMENT;
6590 nargs = decode_int (p, &p, end);
6591 if (nargs != sig->param_count)
6592 return ERR_INVALID_ARGUMENT;
6593 /* Use alloca to get gc tracking */
6594 arg_buf = (guint8 **)g_alloca (nargs * sizeof (gpointer));
6595 memset (arg_buf, 0, nargs * sizeof (gpointer));
6596 args = (gpointer *)g_alloca (nargs * sizeof (gpointer));
6597 for (i = 0; i < nargs; ++i) {
6598 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6599 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6600 if (err != ERR_NONE)
6602 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6605 if (sig->params [i]->byref) {
6606 arg_buf [i] = (guint8 *)g_alloca (sizeof (mgreg_t));
6607 *(gpointer*)arg_buf [i] = args [i];
6608 args [i] = arg_buf [i];
6611 arg_buf [i] = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6612 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6613 if (err != ERR_NONE)
6615 args [i] = arg_buf [i];
6622 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6623 tls->disable_breakpoints = TRUE;
6625 tls->disable_breakpoints = FALSE;
6628 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6630 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6631 if (invoke->has_ctx) {
6634 lmf_addr = mono_get_lmf_addr ();
6637 memset (&ext, 0, sizeof (ext));
6638 mono_arch_init_lmf_ext (&ext, *lmf_addr);
6640 ext.debugger_invoke = TRUE;
6641 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6643 mono_set_lmf ((MonoLMF*)&ext);
6647 mono_stopwatch_start (&watch);
6648 res = mono_runtime_try_invoke (m, m->klass->valuetype ? (gpointer) this_buf : (gpointer) this_arg, args, &exc, &error);
6649 if (exc == NULL && !mono_error_ok (&error)) {
6650 exc = (MonoObject*) mono_error_convert_to_exception (&error);
6652 mono_error_cleanup (&error); /* FIXME report error */
6654 mono_stopwatch_stop (&watch);
6655 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));
6657 buffer_add_byte (buf, 0);
6658 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6660 gboolean out_this = FALSE;
6661 gboolean out_args = FALSE;
6663 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_THIS) && CHECK_PROTOCOL_VERSION (2, 35))
6665 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_ARGS) && CHECK_PROTOCOL_VERSION (2, 35))
6667 buffer_add_byte (buf, 1 + (out_this ? 2 : 0) + (out_args ? 4 : 0));
6668 if (sig->ret->type == MONO_TYPE_VOID) {
6669 if (!strcmp (m->name, ".ctor")) {
6670 if (!m->klass->valuetype)
6671 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this_arg, domain);
6673 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
6675 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6677 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6678 buffer_add_value (buf, sig->ret, &res, domain);
6679 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6680 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6681 MonoClass *k = mono_class_from_mono_type (sig->ret);
6682 guint8 *nullable_buf = (guint8 *)g_alloca (mono_class_value_size (k, NULL));
6684 g_assert (nullable_buf);
6685 mono_nullable_init (nullable_buf, res, k);
6686 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6689 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6695 /* Return the new value of the receiver after the call */
6696 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
6698 buffer_add_int (buf, nargs);
6699 for (i = 0; i < nargs; ++i) {
6700 if (MONO_TYPE_IS_REFERENCE (sig->params [i]))
6701 buffer_add_value (buf, sig->params [i], &args [i], domain);
6702 else if (sig->params [i]->byref)
6703 /* add_value () does an indirection */
6704 buffer_add_value (buf, sig->params [i], &arg_buf [i], domain);
6706 buffer_add_value (buf, sig->params [i], arg_buf [i], domain);
6711 tls->disable_breakpoints = FALSE;
6713 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6714 if (invoke->has_ctx)
6715 mono_set_lmf ((MonoLMF *)(((gssize)ext.lmf.previous_lmf) & ~3));
6719 // FIXME: byref arguments
6727 * Invoke the method given by tls->pending_invoke in the current thread.
6730 invoke_method (void)
6732 DebuggerTlsData *tls;
6738 MonoContext restore_ctx;
6741 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
6745 * Store the `InvokeData *' in `tls->invoke' until we're done with
6746 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6749 mono_loader_lock ();
6751 invoke = tls->pending_invoke;
6753 tls->pending_invoke = NULL;
6755 invoke->last_invoke = tls->invoke;
6756 tls->invoke = invoke;
6758 mono_loader_unlock ();
6760 tls->frames_up_to_date = FALSE;
6766 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6767 buffer_init (&buf, 128);
6770 /* Fail the other invokes as well */
6772 err = do_invoke_method (tls, &buf, invoke, p, &p);
6775 if (tls->abort_requested) {
6776 if (CHECK_PROTOCOL_VERSION (2, 42))
6777 err = ERR_INVOKE_ABORTED;
6780 /* Start suspending before sending the reply */
6781 if (mindex == invoke->nmethods - 1) {
6782 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6783 for (i = 0; i < invoke->suspend_count; ++i)
6788 send_reply_packet (id, err, &buf);
6793 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6795 if (invoke->has_ctx)
6796 save_thread_context (&restore_ctx);
6798 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6799 g_assert (tls->resume_count);
6800 tls->resume_count -= invoke->suspend_count;
6803 DEBUG_PRINTF (1, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer) (gsize) mono_native_thread_id_get (), err, tls->resume_count);
6806 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6808 * It is possible that mono_thread_internal_abort () was called
6809 * after the mono_runtime_invoke_checked() already returned, but it doesn't matter
6810 * because we reset the abort here.
6813 mono_loader_lock ();
6815 if (tls->abort_requested)
6816 mono_thread_internal_reset_abort (tls->thread);
6818 tls->invoke = tls->invoke->last_invoke;
6819 tls->abort_requested = FALSE;
6821 mono_loader_unlock ();
6830 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6832 MonoThread *thread = (MonoThread *)value;
6833 DebuggerTlsData *tls;
6836 mono_loader_lock ();
6837 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
6839 res = tls->really_suspended;
6840 mono_loader_unlock ();
6846 get_source_files_for_type (MonoClass *klass)
6848 gpointer iter = NULL;
6850 MonoDebugSourceInfo *sinfo;
6854 files = g_ptr_array_new ();
6856 while ((method = mono_class_get_methods (klass, &iter))) {
6857 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6858 GPtrArray *source_file_list;
6861 mono_debug_get_seq_points (minfo, NULL, &source_file_list, NULL, NULL, NULL);
6862 for (j = 0; j < source_file_list->len; ++j) {
6863 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, j);
6864 for (i = 0; i < files->len; ++i)
6865 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6867 if (i == files->len)
6868 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6870 g_ptr_array_free (source_file_list, TRUE);
6878 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6881 case CMD_VM_VERSION: {
6882 char *build_info, *version;
6884 build_info = mono_get_runtime_build_info ();
6885 version = g_strdup_printf ("mono %s", build_info);
6887 buffer_add_string (buf, version); /* vm version */
6888 buffer_add_int (buf, MAJOR_VERSION);
6889 buffer_add_int (buf, MINOR_VERSION);
6890 g_free (build_info);
6894 case CMD_VM_SET_PROTOCOL_VERSION: {
6895 major_version = decode_int (p, &p, end);
6896 minor_version = decode_int (p, &p, end);
6897 protocol_version_set = TRUE;
6898 DEBUG_PRINTF (1, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version);
6901 case CMD_VM_ALL_THREADS: {
6903 mono_loader_lock ();
6904 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6905 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6906 mono_loader_unlock ();
6909 case CMD_VM_SUSPEND:
6911 wait_for_suspend ();
6914 if (suspend_count == 0)
6915 return ERR_NOT_SUSPENDED;
6917 clear_suspended_objs ();
6919 case CMD_VM_DISPOSE:
6920 /* Clear all event requests */
6921 mono_loader_lock ();
6922 while (event_requests->len > 0) {
6923 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
6925 clear_event_request (req->id, req->event_kind);
6927 mono_loader_unlock ();
6929 while (suspend_count > 0)
6931 disconnected = TRUE;
6932 vm_start_event_sent = FALSE;
6935 MonoInternalThread *thread;
6936 DebuggerTlsData *tls;
6937 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6938 MonoClass *env_class;
6940 MonoMethod *exit_method = NULL;
6944 exit_code = decode_int (p, &p, end);
6946 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6948 /* Have to send a reply before exiting */
6949 send_reply_packet (id, 0, buf);
6951 /* Clear all event requests */
6952 mono_loader_lock ();
6953 while (event_requests->len > 0) {
6954 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
6956 clear_event_request (req->id, req->event_kind);
6958 mono_loader_unlock ();
6961 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6962 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6963 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6964 * better than doing the shutdown ourselves, since it avoids various races.
6968 wait_for_suspend ();
6970 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6971 env_class = mono_class_try_load_from_name (mono_defaults.corlib, "System", "Environment");
6973 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6976 mono_loader_lock ();
6977 thread = (MonoInternalThread *)mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6978 mono_loader_unlock ();
6980 if (thread && exit_method) {
6981 mono_loader_lock ();
6982 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
6983 mono_loader_unlock ();
6985 args = g_new0 (gpointer, 1);
6986 args [0] = g_malloc (sizeof (int));
6987 *(int*)(args [0]) = exit_code;
6989 tls->pending_invoke = g_new0 (InvokeData, 1);
6990 tls->pending_invoke->method = exit_method;
6991 tls->pending_invoke->args = args;
6992 tls->pending_invoke->nmethods = 1;
6994 while (suspend_count > 0)
6998 * No thread found, do it ourselves.
6999 * FIXME: This can race with normal shutdown etc.
7001 while (suspend_count > 0)
7004 if (!mono_runtime_try_shutdown ())
7007 mono_environment_exitcode_set (exit_code);
7009 /* Suspend all managed threads since the runtime is going away */
7010 DEBUG_PRINTF (1, "Suspending all threads...\n");
7011 mono_thread_suspend_all_other_threads ();
7012 DEBUG_PRINTF (1, "Shutting down the runtime...\n");
7013 mono_runtime_quit ();
7014 transport_close2 ();
7015 DEBUG_PRINTF (1, "Exiting...\n");
7021 case CMD_VM_INVOKE_METHOD:
7022 case CMD_VM_INVOKE_METHODS: {
7023 int objid = decode_objid (p, &p, end);
7025 DebuggerTlsData *tls;
7026 int i, count, flags, nmethods;
7029 err = get_object (objid, (MonoObject**)&thread);
7030 if (err != ERR_NONE)
7033 flags = decode_int (p, &p, end);
7035 if (command == CMD_VM_INVOKE_METHODS)
7036 nmethods = decode_int (p, &p, end);
7040 // Wait for suspending if it already started
7042 wait_for_suspend ();
7043 if (!is_suspended ())
7044 return ERR_NOT_SUSPENDED;
7046 mono_loader_lock ();
7047 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7048 mono_loader_unlock ();
7051 if (!tls->really_suspended)
7052 /* The thread is still running native code, can't do invokes */
7053 return ERR_NOT_SUSPENDED;
7056 * Store the invoke data into tls, the thread will execute it after it is
7059 if (tls->pending_invoke)
7060 return ERR_NOT_SUSPENDED;
7061 tls->pending_invoke = g_new0 (InvokeData, 1);
7062 tls->pending_invoke->id = id;
7063 tls->pending_invoke->flags = flags;
7064 tls->pending_invoke->p = (guint8 *)g_malloc (end - p);
7065 memcpy (tls->pending_invoke->p, p, end - p);
7066 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
7067 tls->pending_invoke->suspend_count = suspend_count;
7068 tls->pending_invoke->nmethods = nmethods;
7070 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
7071 resume_thread (THREAD_TO_INTERNAL (thread));
7074 count = suspend_count;
7075 for (i = 0; i < count; ++i)
7080 case CMD_VM_ABORT_INVOKE: {
7081 int objid = decode_objid (p, &p, end);
7083 DebuggerTlsData *tls;
7087 err = get_object (objid, (MonoObject**)&thread);
7088 if (err != ERR_NONE)
7091 invoke_id = decode_int (p, &p, end);
7093 mono_loader_lock ();
7094 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7097 if (tls->abort_requested) {
7098 DEBUG_PRINTF (1, "Abort already requested.\n");
7099 mono_loader_unlock ();
7104 * Check whether we're still inside the mono_runtime_invoke_checked() and that it's
7105 * actually the correct invocation.
7107 * Careful, we do not stop the thread that's doing the invocation, so we can't
7108 * inspect its stack. However, invoke_method() also acquires the loader lock
7109 * when it's done, so we're safe here.
7113 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
7114 mono_loader_unlock ();
7115 return ERR_NO_INVOCATION;
7118 tls->abort_requested = TRUE;
7120 mono_thread_internal_abort (THREAD_TO_INTERNAL (thread));
7121 mono_loader_unlock ();
7125 case CMD_VM_SET_KEEPALIVE: {
7126 int timeout = decode_int (p, &p, end);
7127 agent_config.keepalive = timeout;
7129 #ifndef DISABLE_SOCKET_TRANSPORT
7136 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
7137 GHashTableIter iter, kiter;
7142 char *fname, *basename;
7143 gboolean ignore_case;
7144 GSList *class_list, *l;
7145 GPtrArray *res_classes, *res_domains;
7147 fname = decode_string (p, &p, end);
7148 ignore_case = decode_byte (p, &p, end);
7150 basename = dbg_path_get_basename (fname);
7152 res_classes = g_ptr_array_new ();
7153 res_domains = g_ptr_array_new ();
7155 mono_loader_lock ();
7156 g_hash_table_iter_init (&iter, domains);
7157 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7158 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
7160 /* Update 'source_file_to_class' cache */
7161 g_hash_table_iter_init (&kiter, info->loaded_classes);
7162 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
7163 if (!g_hash_table_lookup (info->source_files, klass)) {
7164 files = get_source_files_for_type (klass);
7165 g_hash_table_insert (info->source_files, klass, files);
7167 for (i = 0; i < files->len; ++i) {
7168 char *s = (char *)g_ptr_array_index (files, i);
7169 char *s2 = dbg_path_get_basename (s);
7172 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, s2);
7174 class_list = g_slist_prepend (class_list, klass);
7175 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
7177 class_list = g_slist_prepend (class_list, klass);
7178 g_hash_table_insert (info->source_file_to_class, s2, class_list);
7181 /* The _ignorecase hash contains the lowercase path */
7182 s3 = strdup_tolower (s2);
7183 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
7185 class_list = g_slist_prepend (class_list, klass);
7186 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
7188 class_list = g_slist_prepend (class_list, klass);
7189 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
7201 s = strdup_tolower (basename);
7202 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
7205 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, basename);
7208 for (l = class_list; l; l = l->next) {
7209 klass = (MonoClass *)l->data;
7211 g_ptr_array_add (res_classes, klass);
7212 g_ptr_array_add (res_domains, domain);
7215 mono_loader_unlock ();
7220 buffer_add_int (buf, res_classes->len);
7221 for (i = 0; i < res_classes->len; ++i)
7222 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7223 g_ptr_array_free (res_classes, TRUE);
7224 g_ptr_array_free (res_domains, TRUE);
7227 case CMD_VM_GET_TYPES: {
7228 GHashTableIter iter;
7232 gboolean ignore_case;
7233 GPtrArray *res_classes, *res_domains;
7234 MonoTypeNameParse info;
7236 name = decode_string (p, &p, end);
7237 ignore_case = decode_byte (p, &p, end);
7239 if (!mono_reflection_parse_type (name, &info)) {
7241 mono_reflection_free_type_info (&info);
7242 return ERR_INVALID_ARGUMENT;
7245 res_classes = g_ptr_array_new ();
7246 res_domains = g_ptr_array_new ();
7248 mono_loader_lock ();
7249 g_hash_table_iter_init (&iter, domains);
7250 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7252 gboolean type_resolve;
7256 mono_domain_assemblies_lock (domain);
7257 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7258 ass = (MonoAssembly *)tmp->data;
7262 type_resolve = TRUE;
7263 /* FIXME really okay to call while holding locks? */
7264 t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignore_case, &type_resolve, &error);
7265 mono_error_cleanup (&error);
7267 g_ptr_array_add (res_classes, mono_type_get_class (t));
7268 g_ptr_array_add (res_domains, domain);
7272 mono_domain_assemblies_unlock (domain);
7274 mono_loader_unlock ();
7277 mono_reflection_free_type_info (&info);
7279 buffer_add_int (buf, res_classes->len);
7280 for (i = 0; i < res_classes->len; ++i)
7281 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7282 g_ptr_array_free (res_classes, TRUE);
7283 g_ptr_array_free (res_domains, TRUE);
7286 case CMD_VM_START_BUFFERING:
7287 case CMD_VM_STOP_BUFFERING:
7288 /* Handled in the main loop */
7291 return ERR_NOT_IMPLEMENTED;
7298 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7304 case CMD_EVENT_REQUEST_SET: {
7306 int i, event_kind, suspend_policy, nmodifiers;
7310 MonoThread *step_thread;
7311 int step_thread_id = 0;
7312 StepDepth depth = STEP_DEPTH_INTO;
7313 StepSize size = STEP_SIZE_MIN;
7314 StepFilter filter = STEP_FILTER_NONE;
7318 event_kind = decode_byte (p, &p, end);
7319 suspend_policy = decode_byte (p, &p, end);
7320 nmodifiers = decode_byte (p, &p, end);
7322 req = (EventRequest *)g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7323 req->id = InterlockedIncrement (&event_request_id);
7324 req->event_kind = event_kind;
7325 req->suspend_policy = suspend_policy;
7326 req->nmodifiers = nmodifiers;
7329 for (i = 0; i < nmodifiers; ++i) {
7330 mod = (ModifierKind)decode_byte (p, &p, end);
7332 req->modifiers [i].kind = mod;
7333 if (mod == MOD_KIND_COUNT) {
7334 req->modifiers [i].data.count = decode_int (p, &p, end);
7335 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7336 method = decode_methodid (p, &p, end, &domain, &err);
7337 if (err != ERR_NONE)
7339 location = decode_long (p, &p, end);
7340 } else if (mod == MOD_KIND_STEP) {
7341 step_thread_id = decode_id (p, &p, end);
7342 size = (StepSize)decode_int (p, &p, end);
7343 depth = (StepDepth)decode_int (p, &p, end);
7344 if (CHECK_PROTOCOL_VERSION (2, 16))
7345 filter = (StepFilter)decode_int (p, &p, end);
7346 req->modifiers [i].data.filter = filter;
7347 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7348 /* Treat STEP_THOUGH the same as HIDDEN */
7349 req->modifiers [i].data.filter = (StepFilter)(req->modifiers [i].data.filter | STEP_FILTER_DEBUGGER_STEP_THROUGH);
7350 } else if (mod == MOD_KIND_THREAD_ONLY) {
7351 int id = decode_id (p, &p, end);
7353 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7354 if (err != ERR_NONE) {
7358 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7359 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7361 if (err != ERR_NONE)
7363 req->modifiers [i].caught = decode_byte (p, &p, end);
7364 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7365 if (CHECK_PROTOCOL_VERSION (2, 25))
7366 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7368 req->modifiers [i].subclasses = TRUE;
7369 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" : "");
7371 req->modifiers [i].data.exc_class = exc_class;
7373 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
7375 return ERR_INVALID_ARGUMENT;
7378 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7379 int n = decode_int (p, &p, end);
7382 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
7383 for (j = 0; j < n; ++j) {
7384 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7385 if (err != ERR_NONE) {
7386 g_free (req->modifiers [i].data.assemblies);
7390 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7391 int n = decode_int (p, &p, end);
7394 modifier = &req->modifiers [i];
7395 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7396 for (j = 0; j < n; ++j) {
7397 char *s = decode_string (p, &p, end);
7401 s2 = strdup_tolower (s);
7402 g_hash_table_insert (modifier->data.source_files, s2, s2);
7406 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7407 int n = decode_int (p, &p, end);
7410 modifier = &req->modifiers [i];
7411 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7412 for (j = 0; j < n; ++j) {
7413 char *s = decode_string (p, &p, end);
7416 g_hash_table_insert (modifier->data.type_names, s, s);
7420 return ERR_NOT_IMPLEMENTED;
7424 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7427 req->info = set_breakpoint (method, location, req, &error);
7428 if (!mono_error_ok (&error)) {
7430 DEBUG_PRINTF (1, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error));
7431 mono_error_cleanup (&error);
7432 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7434 } else if (req->event_kind == EVENT_KIND_STEP) {
7435 g_assert (step_thread_id);
7437 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7438 if (err != ERR_NONE) {
7443 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, filter, req);
7444 if (err != ERR_NONE) {
7448 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7449 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7450 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7451 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7452 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7453 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7455 if (req->nmodifiers) {
7457 return ERR_NOT_IMPLEMENTED;
7461 mono_loader_lock ();
7462 g_ptr_array_add (event_requests, req);
7464 if (agent_config.defer) {
7465 /* Transmit cached data to the client on receipt of the event request */
7466 switch (req->event_kind) {
7467 case EVENT_KIND_APPDOMAIN_CREATE:
7468 /* Emit load events for currently loaded domains */
7469 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7471 case EVENT_KIND_ASSEMBLY_LOAD:
7472 /* Emit load events for currently loaded assemblies */
7473 mono_assembly_foreach (emit_assembly_load, NULL);
7475 case EVENT_KIND_THREAD_START:
7476 /* Emit start events for currently started threads */
7477 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7479 case EVENT_KIND_TYPE_LOAD:
7480 /* Emit type load events for currently loaded types */
7481 mono_domain_foreach (send_types_for_domain, NULL);
7487 mono_loader_unlock ();
7489 buffer_add_int (buf, req->id);
7492 case CMD_EVENT_REQUEST_CLEAR: {
7493 int etype = decode_byte (p, &p, end);
7494 int req_id = decode_int (p, &p, end);
7496 // FIXME: Make a faster mapping from req_id to request
7497 mono_loader_lock ();
7498 clear_event_request (req_id, etype);
7499 mono_loader_unlock ();
7502 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7505 mono_loader_lock ();
7507 while (i < event_requests->len) {
7508 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
7510 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7511 clear_breakpoint ((MonoBreakpoint *)req->info);
7513 g_ptr_array_remove_index_fast (event_requests, i);
7519 mono_loader_unlock ();
7523 return ERR_NOT_IMPLEMENTED;
7530 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7536 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7537 buffer_add_domainid (buf, mono_get_root_domain ());
7540 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7541 domain = decode_domainid (p, &p, end, NULL, &err);
7542 if (err != ERR_NONE)
7544 buffer_add_string (buf, domain->friendly_name);
7547 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7552 domain = decode_domainid (p, &p, end, NULL, &err);
7553 if (err != ERR_NONE)
7555 mono_loader_lock ();
7557 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7560 buffer_add_int (buf, count);
7561 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7562 ass = (MonoAssembly *)tmp->data;
7563 buffer_add_assemblyid (buf, domain, ass);
7565 mono_loader_unlock ();
7568 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7569 domain = decode_domainid (p, &p, end, NULL, &err);
7570 if (err != ERR_NONE)
7573 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7576 case CMD_APPDOMAIN_GET_CORLIB: {
7577 domain = decode_domainid (p, &p, end, NULL, &err);
7578 if (err != ERR_NONE)
7581 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7584 case CMD_APPDOMAIN_CREATE_STRING: {
7588 domain = decode_domainid (p, &p, end, NULL, &err);
7589 if (err != ERR_NONE)
7591 s = decode_string (p, &p, end);
7593 o = mono_string_new (domain, s);
7594 buffer_add_objid (buf, (MonoObject*)o);
7597 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7600 MonoDomain *domain2;
7603 domain = decode_domainid (p, &p, end, NULL, &err);
7604 if (err != ERR_NONE)
7606 klass = decode_typeid (p, &p, end, &domain2, &err);
7607 if (err != ERR_NONE)
7611 g_assert (domain == domain2);
7613 o = mono_object_new_checked (domain, klass, &error);
7614 mono_error_assert_ok (&error);
7616 err = decode_value (&klass->byval_arg, domain, (guint8 *)mono_object_unbox (o), p, &p, end);
7617 if (err != ERR_NONE)
7620 buffer_add_objid (buf, o);
7624 return ERR_NOT_IMPLEMENTED;
7631 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7637 ass = decode_assemblyid (p, &p, end, &domain, &err);
7638 if (err != ERR_NONE)
7642 case CMD_ASSEMBLY_GET_LOCATION: {
7643 buffer_add_string (buf, mono_image_get_filename (ass->image));
7646 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7650 if (ass->image->dynamic) {
7651 buffer_add_id (buf, 0);
7653 token = mono_image_get_entry_point (ass->image);
7655 buffer_add_id (buf, 0);
7658 m = mono_get_method_checked (ass->image, token, NULL, NULL, &error);
7660 mono_error_cleanup (&error); /* FIXME don't swallow the error */
7661 buffer_add_methodid (buf, domain, m);
7666 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7667 buffer_add_moduleid (buf, domain, ass->image);
7670 case CMD_ASSEMBLY_GET_OBJECT: {
7672 MonoObject *o = (MonoObject*)mono_assembly_get_object_checked (domain, ass, &error);
7674 mono_error_cleanup (&error); /* FIXME don't swallow the error */
7675 return ERR_INVALID_OBJECT;
7677 buffer_add_objid (buf, o);
7680 case CMD_ASSEMBLY_GET_TYPE: {
7682 char *s = decode_string (p, &p, end);
7683 gboolean ignorecase = decode_byte (p, &p, end);
7684 MonoTypeNameParse info;
7686 gboolean type_resolve, res;
7687 MonoDomain *d = mono_domain_get ();
7689 /* This is needed to be able to find referenced assemblies */
7690 res = mono_domain_set (domain, FALSE);
7693 if (!mono_reflection_parse_type (s, &info)) {
7696 if (info.assembly.name)
7698 t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignorecase, &type_resolve, &error);
7699 if (!is_ok (&error)) {
7700 mono_error_cleanup (&error); /* FIXME don't swallow the error */
7701 mono_reflection_free_type_info (&info);
7703 return ERR_INVALID_ARGUMENT;
7706 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
7707 mono_reflection_free_type_info (&info);
7710 mono_domain_set (d, TRUE);
7714 case CMD_ASSEMBLY_GET_NAME: {
7716 MonoAssembly *mass = ass;
7718 name = g_strdup_printf (
7719 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7721 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7722 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7723 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7724 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7726 buffer_add_string (buf, name);
7731 return ERR_NOT_IMPLEMENTED;
7738 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7744 case CMD_MODULE_GET_INFO: {
7745 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7748 basename = g_path_get_basename (image->name);
7749 buffer_add_string (buf, basename); // name
7750 buffer_add_string (buf, image->module_name); // scopename
7751 buffer_add_string (buf, image->name); // fqname
7752 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7753 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7758 return ERR_NOT_IMPLEMENTED;
7765 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7771 case CMD_FIELD_GET_INFO: {
7772 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
7774 buffer_add_string (buf, f->name);
7775 buffer_add_typeid (buf, domain, f->parent);
7776 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7777 buffer_add_int (buf, f->type->attrs);
7781 return ERR_NOT_IMPLEMENTED;
7788 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7790 if (val && val->vtable->klass == mono_defaults.runtimetype_class) {
7791 /* Special case these so the client doesn't have to handle Type objects */
7793 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7794 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7795 } else if (MONO_TYPE_IS_REFERENCE (t))
7796 buffer_add_value (buf, t, &val, domain);
7798 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7802 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7808 buffer_add_int (buf, 0);
7812 for (i = 0; i < cinfo->num_attrs; ++i) {
7813 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7816 buffer_add_int (buf, nattrs);
7818 for (i = 0; i < cinfo->num_attrs; ++i) {
7819 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7820 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7821 MonoArray *typed_args, *named_args;
7823 CattrNamedArg *arginfo = NULL;
7826 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
7827 if (!mono_error_ok (&error)) {
7828 DEBUG_PRINTF (2, "[dbg] mono_reflection_create_custom_attr_data_args () failed with: '%s'\n", mono_error_get_message (&error));
7829 mono_error_cleanup (&error);
7830 return ERR_LOADER_ERROR;
7833 buffer_add_methodid (buf, domain, attr->ctor);
7837 buffer_add_int (buf, mono_array_length (typed_args));
7838 for (j = 0; j < mono_array_length (typed_args); ++j) {
7839 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7841 t = mono_method_signature (attr->ctor)->params [j];
7843 buffer_add_cattr_arg (buf, t, domain, val);
7846 buffer_add_int (buf, 0);
7851 buffer_add_int (buf, mono_array_length (named_args));
7853 for (j = 0; j < mono_array_length (named_args); ++j) {
7854 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7856 if (arginfo [j].prop) {
7857 buffer_add_byte (buf, 0x54);
7858 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7859 } else if (arginfo [j].field) {
7860 buffer_add_byte (buf, 0x53);
7861 buffer_add_fieldid (buf, domain, arginfo [j].field);
7863 g_assert_not_reached ();
7866 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7869 buffer_add_int (buf, 0);
7878 /* FIXME: Code duplication with icall.c */
7880 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7885 mono_class_setup_interfaces (klass, error);
7886 if (!mono_error_ok (error))
7889 for (i = 0; i < klass->interface_count; i++) {
7890 ic = klass->interfaces [i];
7891 g_hash_table_insert (ifaces, ic, ic);
7893 collect_interfaces (ic, ifaces, error);
7894 if (!mono_error_ok (error))
7900 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7912 case CMD_TYPE_GET_INFO: {
7913 buffer_add_string (buf, klass->name_space);
7914 buffer_add_string (buf, klass->name);
7916 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7917 buffer_add_string (buf, name);
7919 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7920 buffer_add_moduleid (buf, domain, klass->image);
7921 buffer_add_typeid (buf, domain, klass->parent);
7922 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7923 buffer_add_typeid (buf, domain, klass->element_class);
7925 buffer_add_id (buf, 0);
7926 buffer_add_int (buf, klass->type_token);
7927 buffer_add_byte (buf, klass->rank);
7928 buffer_add_int (buf, klass->flags);
7930 type = &klass->byval_arg;
7931 // FIXME: Can't decide whenever a class represents a byref type
7934 if (type->type == MONO_TYPE_PTR)
7936 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7938 if (type->type == MONO_TYPE_VALUETYPE)
7940 if (klass->enumtype)
7942 if (klass->generic_container)
7944 if (klass->generic_container || klass->generic_class)
7946 buffer_add_byte (buf, b);
7949 while ((nested = mono_class_get_nested_types (klass, &iter)))
7951 buffer_add_int (buf, nnested);
7953 while ((nested = mono_class_get_nested_types (klass, &iter)))
7954 buffer_add_typeid (buf, domain, nested);
7955 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7956 if (klass->generic_container)
7957 buffer_add_typeid (buf, domain, klass);
7958 else if (klass->generic_class)
7959 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7961 buffer_add_id (buf, 0);
7963 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7966 if (klass->generic_class) {
7967 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7969 count = inst->type_argc;
7970 buffer_add_int (buf, count);
7971 for (i = 0; i < count; i++)
7972 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7973 } else if (klass->generic_container) {
7974 MonoGenericContainer *container = klass->generic_container;
7977 count = container->type_argc;
7978 buffer_add_int (buf, count);
7979 for (i = 0; i < count; i++) {
7980 pklass = mono_class_from_generic_parameter_internal (mono_generic_container_get_param (container, i));
7981 buffer_add_typeid (buf, domain, pklass);
7984 buffer_add_int (buf, 0);
7989 case CMD_TYPE_GET_METHODS: {
7992 gpointer iter = NULL;
7995 mono_class_setup_methods (klass);
7997 nmethods = mono_class_num_methods (klass);
7999 buffer_add_int (buf, nmethods);
8001 while ((m = mono_class_get_methods (klass, &iter))) {
8002 buffer_add_methodid (buf, domain, m);
8005 g_assert (i == nmethods);
8008 case CMD_TYPE_GET_FIELDS: {
8011 gpointer iter = NULL;
8014 nfields = mono_class_num_fields (klass);
8016 buffer_add_int (buf, nfields);
8018 while ((f = mono_class_get_fields (klass, &iter))) {
8019 buffer_add_fieldid (buf, domain, f);
8020 buffer_add_string (buf, f->name);
8021 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
8022 buffer_add_int (buf, f->type->attrs);
8025 g_assert (i == nfields);
8028 case CMD_TYPE_GET_PROPERTIES: {
8031 gpointer iter = NULL;
8034 nprops = mono_class_num_properties (klass);
8036 buffer_add_int (buf, nprops);
8038 while ((p = mono_class_get_properties (klass, &iter))) {
8039 buffer_add_propertyid (buf, domain, p);
8040 buffer_add_string (buf, p->name);
8041 buffer_add_methodid (buf, domain, p->get);
8042 buffer_add_methodid (buf, domain, p->set);
8043 buffer_add_int (buf, p->attrs);
8046 g_assert (i == nprops);
8049 case CMD_TYPE_GET_CATTRS: {
8050 MonoClass *attr_klass;
8051 MonoCustomAttrInfo *cinfo;
8053 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8054 /* attr_klass can be NULL */
8055 if (err != ERR_NONE)
8058 cinfo = mono_custom_attrs_from_class_checked (klass, &error);
8059 if (!is_ok (&error)) {
8060 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8061 return ERR_LOADER_ERROR;
8064 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8065 if (err != ERR_NONE)
8069 case CMD_TYPE_GET_FIELD_CATTRS: {
8070 MonoClass *attr_klass;
8071 MonoCustomAttrInfo *cinfo;
8072 MonoClassField *field;
8074 field = decode_fieldid (p, &p, end, NULL, &err);
8075 if (err != ERR_NONE)
8077 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8078 if (err != ERR_NONE)
8081 cinfo = mono_custom_attrs_from_field_checked (klass, field, &error);
8082 if (!is_ok (&error)) {
8083 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8084 return ERR_LOADER_ERROR;
8087 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8088 if (err != ERR_NONE)
8092 case CMD_TYPE_GET_PROPERTY_CATTRS: {
8093 MonoClass *attr_klass;
8094 MonoCustomAttrInfo *cinfo;
8097 prop = decode_propertyid (p, &p, end, NULL, &err);
8098 if (err != ERR_NONE)
8100 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8101 if (err != ERR_NONE)
8104 cinfo = mono_custom_attrs_from_property_checked (klass, prop, &error);
8105 if (!is_ok (&error)) {
8106 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8107 return ERR_LOADER_ERROR;
8110 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8111 if (err != ERR_NONE)
8115 case CMD_TYPE_GET_VALUES:
8116 case CMD_TYPE_GET_VALUES_2: {
8123 MonoThread *thread_obj;
8124 MonoInternalThread *thread = NULL;
8125 guint32 special_static_type;
8127 if (command == CMD_TYPE_GET_VALUES_2) {
8128 int objid = decode_objid (p, &p, end);
8131 err = get_object (objid, (MonoObject**)&thread_obj);
8132 if (err != ERR_NONE)
8135 thread = THREAD_TO_INTERNAL (thread_obj);
8138 len = decode_int (p, &p, end);
8139 for (i = 0; i < len; ++i) {
8140 f = decode_fieldid (p, &p, end, NULL, &err);
8141 if (err != ERR_NONE)
8144 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8145 return ERR_INVALID_FIELDID;
8146 special_static_type = mono_class_field_get_special_static_type (f);
8147 if (special_static_type != SPECIAL_STATIC_NONE) {
8148 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
8149 return ERR_INVALID_FIELDID;
8152 /* Check that the field belongs to the object */
8154 for (k = klass; k; k = k->parent) {
8155 if (k == f->parent) {
8161 return ERR_INVALID_FIELDID;
8163 vtable = mono_class_vtable (domain, f->parent);
8164 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8165 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val, &error);
8166 if (!is_ok (&error))
8167 return ERR_INVALID_FIELDID;
8168 buffer_add_value (buf, f->type, val, domain);
8173 case CMD_TYPE_SET_VALUES: {
8181 len = decode_int (p, &p, end);
8182 for (i = 0; i < len; ++i) {
8183 f = decode_fieldid (p, &p, end, NULL, &err);
8184 if (err != ERR_NONE)
8187 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8188 return ERR_INVALID_FIELDID;
8189 if (mono_class_field_is_special_static (f))
8190 return ERR_INVALID_FIELDID;
8192 /* Check that the field belongs to the object */
8194 for (k = klass; k; k = k->parent) {
8195 if (k == f->parent) {
8201 return ERR_INVALID_FIELDID;
8203 // FIXME: Check for literal/const
8205 vtable = mono_class_vtable (domain, f->parent);
8206 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8207 err = decode_value (f->type, domain, val, p, &p, end);
8208 if (err != ERR_NONE) {
8212 if (MONO_TYPE_IS_REFERENCE (f->type))
8213 mono_field_static_set_value (vtable, f, *(gpointer*)val);
8215 mono_field_static_set_value (vtable, f, val);
8220 case CMD_TYPE_GET_OBJECT: {
8221 MonoObject *o = (MonoObject*)mono_type_get_object_checked (domain, &klass->byval_arg, &error);
8222 if (!mono_error_ok (&error)) {
8223 mono_error_cleanup (&error);
8224 return ERR_INVALID_OBJECT;
8226 buffer_add_objid (buf, o);
8229 case CMD_TYPE_GET_SOURCE_FILES:
8230 case CMD_TYPE_GET_SOURCE_FILES_2: {
8231 char *source_file, *base;
8235 files = get_source_files_for_type (klass);
8237 buffer_add_int (buf, files->len);
8238 for (i = 0; i < files->len; ++i) {
8239 source_file = (char *)g_ptr_array_index (files, i);
8240 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8241 buffer_add_string (buf, source_file);
8243 base = dbg_path_get_basename (source_file);
8244 buffer_add_string (buf, base);
8247 g_free (source_file);
8249 g_ptr_array_free (files, TRUE);
8252 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8253 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8255 if (err != ERR_NONE)
8257 if (mono_class_is_assignable_from (klass, oklass))
8258 buffer_add_byte (buf, 1);
8260 buffer_add_byte (buf, 0);
8263 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8264 char *name = decode_string (p, &p, end);
8265 int i, flags = decode_int (p, &p, end);
8266 MonoException *ex = NULL;
8267 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
8270 return ERR_LOADER_ERROR;
8271 buffer_add_int (buf, array->len);
8272 for (i = 0; i < array->len; ++i) {
8273 MonoMethod *method = (MonoMethod *)g_ptr_array_index (array, i);
8274 buffer_add_methodid (buf, domain, method);
8277 g_ptr_array_free (array, TRUE);
8281 case CMD_TYPE_GET_INTERFACES: {
8283 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8284 MonoClass *tclass, *iface;
8285 GHashTableIter iter;
8289 for (parent = tclass; parent; parent = parent->parent) {
8290 mono_class_setup_interfaces (parent, &error);
8291 if (!mono_error_ok (&error))
8292 return ERR_LOADER_ERROR;
8293 collect_interfaces (parent, iface_hash, &error);
8294 if (!mono_error_ok (&error))
8295 return ERR_LOADER_ERROR;
8298 buffer_add_int (buf, g_hash_table_size (iface_hash));
8300 g_hash_table_iter_init (&iter, iface_hash);
8301 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8302 buffer_add_typeid (buf, domain, iface);
8303 g_hash_table_destroy (iface_hash);
8306 case CMD_TYPE_GET_INTERFACE_MAP: {
8307 int tindex, ioffset;
8308 gboolean variance_used;
8310 int len, nmethods, i;
8314 len = decode_int (p, &p, end);
8315 mono_class_setup_vtable (klass);
8317 for (tindex = 0; tindex < len; ++tindex) {
8318 iclass = decode_typeid (p, &p, end, NULL, &err);
8319 if (err != ERR_NONE)
8322 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8324 return ERR_INVALID_ARGUMENT;
8326 nmethods = mono_class_num_methods (iclass);
8327 buffer_add_int (buf, nmethods);
8330 while ((method = mono_class_get_methods (iclass, &iter))) {
8331 buffer_add_methodid (buf, domain, method);
8333 for (i = 0; i < nmethods; ++i)
8334 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
8338 case CMD_TYPE_IS_INITIALIZED: {
8339 MonoVTable *vtable = mono_class_vtable (domain, klass);
8342 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8344 buffer_add_int (buf, 0);
8347 case CMD_TYPE_CREATE_INSTANCE: {
8351 obj = mono_object_new_checked (domain, klass, &error);
8352 mono_error_assert_ok (&error);
8353 buffer_add_objid (buf, obj);
8357 return ERR_NOT_IMPLEMENTED;
8364 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8367 MonoDomain *old_domain;
8371 klass = decode_typeid (p, &p, end, &domain, &err);
8372 if (err != ERR_NONE)
8375 old_domain = mono_domain_get ();
8377 mono_domain_set (domain, TRUE);
8379 err = type_commands_internal (command, klass, domain, p, end, buf);
8381 mono_domain_set (old_domain, TRUE);
8387 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8389 MonoMethodHeader *header;
8393 case CMD_METHOD_GET_NAME: {
8394 buffer_add_string (buf, method->name);
8397 case CMD_METHOD_GET_DECLARING_TYPE: {
8398 buffer_add_typeid (buf, domain, method->klass);
8401 case CMD_METHOD_GET_DEBUG_INFO: {
8403 MonoDebugMethodInfo *minfo;
8405 int i, j, n_il_offsets;
8407 GPtrArray *source_file_list;
8408 MonoSymSeqPoint *sym_seq_points;
8410 header = mono_method_get_header_checked (method, &error);
8412 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8413 buffer_add_int (buf, 0);
8414 buffer_add_string (buf, "");
8415 buffer_add_int (buf, 0);
8419 minfo = mono_debug_lookup_method (method);
8421 buffer_add_int (buf, header->code_size);
8422 buffer_add_string (buf, "");
8423 buffer_add_int (buf, 0);
8424 mono_metadata_free_mh (header);
8428 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, &source_files, &sym_seq_points, &n_il_offsets);
8429 buffer_add_int (buf, header->code_size);
8430 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8431 buffer_add_int (buf, source_file_list->len);
8432 for (i = 0; i < source_file_list->len; ++i) {
8433 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
8434 buffer_add_string (buf, sinfo->source_file);
8435 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8436 for (j = 0; j < 16; ++j)
8437 buffer_add_byte (buf, sinfo->hash [j]);
8441 buffer_add_string (buf, source_file);
8443 buffer_add_int (buf, n_il_offsets);
8444 DEBUG_PRINTF (10, "Line number table for method %s:\n", mono_method_full_name (method, TRUE));
8445 for (i = 0; i < n_il_offsets; ++i) {
8446 MonoSymSeqPoint *sp = &sym_seq_points [i];
8447 const char *srcfile = "";
8449 if (source_files [i] != -1) {
8450 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, source_files [i]);
8451 srcfile = sinfo->source_file;
8453 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);
8454 buffer_add_int (buf, sp->il_offset);
8455 buffer_add_int (buf, sp->line);
8456 if (CHECK_PROTOCOL_VERSION (2, 13))
8457 buffer_add_int (buf, source_files [i]);
8458 if (CHECK_PROTOCOL_VERSION (2, 19))
8459 buffer_add_int (buf, sp->column);
8460 if (CHECK_PROTOCOL_VERSION (2, 32)) {
8461 buffer_add_int (buf, sp->end_line);
8462 buffer_add_int (buf, sp->end_column);
8465 g_free (source_file);
8466 g_free (source_files);
8467 g_free (sym_seq_points);
8468 g_ptr_array_free (source_file_list, TRUE);
8469 mono_metadata_free_mh (header);
8472 case CMD_METHOD_GET_PARAM_INFO: {
8473 MonoMethodSignature *sig = mono_method_signature (method);
8477 /* FIXME: mono_class_from_mono_type () and byrefs */
8479 /* FIXME: Use a smaller encoding */
8480 buffer_add_int (buf, sig->call_convention);
8481 buffer_add_int (buf, sig->param_count);
8482 buffer_add_int (buf, sig->generic_param_count);
8483 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
8484 for (i = 0; i < sig->param_count; ++i) {
8486 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
8489 /* Emit parameter names */
8490 names = g_new (char *, sig->param_count);
8491 mono_method_get_param_names (method, (const char **) names);
8492 for (i = 0; i < sig->param_count; ++i)
8493 buffer_add_string (buf, names [i]);
8498 case CMD_METHOD_GET_LOCALS_INFO: {
8501 MonoDebugLocalsInfo *locals;
8502 int *locals_map = NULL;
8504 header = mono_method_get_header_checked (method, &error);
8506 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8507 return ERR_INVALID_ARGUMENT;
8510 locals = mono_debug_lookup_locals (method);
8512 buffer_add_int (buf, header->num_locals);
8514 for (i = 0; i < header->num_locals; ++i) {
8515 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
8518 for (i = 0; i < header->num_locals; ++i) {
8520 sprintf (lname, "V_%d", i);
8521 buffer_add_string (buf, lname);
8524 for (i = 0; i < header->num_locals; ++i) {
8525 buffer_add_int (buf, 0);
8526 buffer_add_int (buf, header->code_size);
8529 num_locals = locals->num_locals;
8530 buffer_add_int (buf, num_locals);
8533 for (i = 0; i < num_locals; ++i) {
8534 g_assert (locals->locals [i].index < header->num_locals);
8535 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [locals->locals [i].index]));
8538 for (i = 0; i < num_locals; ++i)
8539 buffer_add_string (buf, locals->locals [i].name);
8541 for (i = 0; i < num_locals; ++i) {
8542 if (locals->locals [i].block) {
8543 buffer_add_int (buf, locals->locals [i].block->start_offset);
8544 buffer_add_int (buf, locals->locals [i].block->end_offset);
8546 buffer_add_int (buf, 0);
8547 buffer_add_int (buf, header->code_size);
8551 mono_metadata_free_mh (header);
8554 mono_debug_free_locals (locals);
8555 g_free (locals_map);
8559 case CMD_METHOD_GET_INFO:
8560 buffer_add_int (buf, method->flags);
8561 buffer_add_int (buf, method->iflags);
8562 buffer_add_int (buf, method->token);
8563 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8565 if (method->is_generic)
8567 if (mono_method_signature (method)->generic_param_count)
8569 buffer_add_byte (buf, attrs);
8570 if (method->is_generic || method->is_inflated) {
8573 if (method->is_generic) {
8576 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8578 result = imethod->declaring;
8579 if (imethod->context.class_inst) {
8580 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8581 /*Generic methods gets the context of the GTD.*/
8582 if (mono_class_get_context (klass)) {
8584 result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), &error);
8585 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8590 buffer_add_methodid (buf, domain, result);
8592 buffer_add_id (buf, 0);
8594 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8595 if (mono_method_signature (method)->generic_param_count) {
8598 if (method->is_inflated) {
8599 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
8601 count = inst->type_argc;
8602 buffer_add_int (buf, count);
8604 for (i = 0; i < count; i++)
8605 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8607 buffer_add_int (buf, 0);
8609 } else if (method->is_generic) {
8610 MonoGenericContainer *container = mono_method_get_generic_container (method);
8612 count = mono_method_signature (method)->generic_param_count;
8613 buffer_add_int (buf, count);
8614 for (i = 0; i < count; i++) {
8615 MonoGenericParam *param = mono_generic_container_get_param (container, i);
8616 MonoClass *pklass = mono_class_from_generic_parameter_internal (param);
8617 buffer_add_typeid (buf, domain, pklass);
8620 buffer_add_int (buf, 0);
8623 buffer_add_int (buf, 0);
8628 case CMD_METHOD_GET_BODY: {
8632 header = mono_method_get_header_checked (method, &error);
8634 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8635 buffer_add_int (buf, 0);
8637 if (CHECK_PROTOCOL_VERSION (2, 18))
8638 buffer_add_int (buf, 0);
8640 buffer_add_int (buf, header->code_size);
8641 for (i = 0; i < header->code_size; ++i)
8642 buffer_add_byte (buf, header->code [i]);
8644 if (CHECK_PROTOCOL_VERSION (2, 18)) {
8645 buffer_add_int (buf, header->num_clauses);
8646 for (i = 0; i < header->num_clauses; ++i) {
8647 MonoExceptionClause *clause = &header->clauses [i];
8649 buffer_add_int (buf, clause->flags);
8650 buffer_add_int (buf, clause->try_offset);
8651 buffer_add_int (buf, clause->try_len);
8652 buffer_add_int (buf, clause->handler_offset);
8653 buffer_add_int (buf, clause->handler_len);
8654 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
8655 buffer_add_typeid (buf, domain, clause->data.catch_class);
8656 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8657 buffer_add_int (buf, clause->data.filter_offset);
8661 mono_metadata_free_mh (header);
8666 case CMD_METHOD_RESOLVE_TOKEN: {
8667 guint32 token = decode_int (p, &p, end);
8670 switch (mono_metadata_token_code (token)) {
8671 case MONO_TOKEN_STRING: {
8676 s = mono_ldstr_checked (domain, method->klass->image, mono_metadata_token_index (token), &error);
8677 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
8679 s2 = mono_string_to_utf8 (s);
8681 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8682 buffer_add_string (buf, s2);
8688 MonoClass *handle_class;
8690 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8691 val = mono_method_get_wrapper_data (method, token);
8692 handle_class = (MonoClass *)mono_method_get_wrapper_data (method, token + 1);
8694 if (handle_class == NULL) {
8695 // Can't figure out the token type
8696 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8701 val = mono_ldtoken_checked (method->klass->image, token, &handle_class, NULL, &error);
8703 g_error ("Could not load token due to %s", mono_error_get_message (&error));
8706 if (handle_class == mono_defaults.typehandle_class) {
8707 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8708 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8709 buffer_add_typeid (buf, domain, (MonoClass *) val);
8711 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
8712 } else if (handle_class == mono_defaults.fieldhandle_class) {
8713 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8714 buffer_add_fieldid (buf, domain, (MonoClassField *)val);
8715 } else if (handle_class == mono_defaults.methodhandle_class) {
8716 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8717 buffer_add_methodid (buf, domain, (MonoMethod *)val);
8718 } else if (handle_class == mono_defaults.string_class) {
8721 s = mono_string_to_utf8 ((MonoString *)val);
8722 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8723 buffer_add_string (buf, s);
8726 g_assert_not_reached ();
8733 case CMD_METHOD_GET_CATTRS: {
8735 MonoClass *attr_klass;
8736 MonoCustomAttrInfo *cinfo;
8738 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8739 /* attr_klass can be NULL */
8740 if (err != ERR_NONE)
8743 cinfo = mono_custom_attrs_from_method_checked (method, &error);
8744 if (!is_ok (&error)) {
8745 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8746 return ERR_LOADER_ERROR;
8749 err = buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
8750 if (err != ERR_NONE)
8754 case CMD_METHOD_MAKE_GENERIC_METHOD: {
8756 MonoType **type_argv;
8760 MonoGenericInst *ginst;
8761 MonoGenericContext tmp_context;
8762 MonoMethod *inflated;
8764 type_argc = decode_int (p, &p, end);
8765 type_argv = g_new0 (MonoType*, type_argc);
8766 for (i = 0; i < type_argc; ++i) {
8767 klass = decode_typeid (p, &p, end, &d, &err);
8768 if (err != ERR_NONE) {
8774 return ERR_INVALID_ARGUMENT;
8776 type_argv [i] = &klass->byval_arg;
8778 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
8780 tmp_context.class_inst = method->klass->generic_class ? method->klass->generic_class->context.class_inst : NULL;
8781 tmp_context.method_inst = ginst;
8783 inflated = mono_class_inflate_generic_method_checked (method, &tmp_context, &error);
8784 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8785 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
8786 return ERR_INVALID_ARGUMENT;
8787 buffer_add_methodid (buf, domain, inflated);
8791 return ERR_NOT_IMPLEMENTED;
8798 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8801 MonoDomain *old_domain;
8805 method = decode_methodid (p, &p, end, &domain, &err);
8806 if (err != ERR_NONE)
8809 old_domain = mono_domain_get ();
8811 mono_domain_set (domain, TRUE);
8813 err = method_commands_internal (command, method, domain, p, end, buf);
8815 mono_domain_set (old_domain, TRUE);
8821 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8823 int objid = decode_objid (p, &p, end);
8825 MonoThread *thread_obj;
8826 MonoInternalThread *thread;
8828 err = get_object (objid, (MonoObject**)&thread_obj);
8829 if (err != ERR_NONE)
8832 thread = THREAD_TO_INTERNAL (thread_obj);
8835 case CMD_THREAD_GET_NAME: {
8837 gunichar2 *s = mono_thread_get_name (thread, &name_len);
8840 buffer_add_int (buf, 0);
8845 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
8847 buffer_add_int (buf, len);
8848 buffer_add_data (buf, (guint8*)name, len);
8853 case CMD_THREAD_GET_FRAME_INFO: {
8854 DebuggerTlsData *tls;
8855 int i, start_frame, length;
8857 // Wait for suspending if it already started
8858 // FIXME: Races with suspend_count
8859 while (!is_suspended ()) {
8861 wait_for_suspend ();
8865 wait_for_suspend ();
8866 if (!is_suspended ())
8867 return ERR_NOT_SUSPENDED;
8870 start_frame = decode_int (p, &p, end);
8871 length = decode_int (p, &p, end);
8873 if (start_frame != 0 || length != -1)
8874 return ERR_NOT_IMPLEMENTED;
8876 mono_loader_lock ();
8877 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
8878 mono_loader_unlock ();
8881 compute_frame_info (thread, tls);
8883 buffer_add_int (buf, tls->frame_count);
8884 for (i = 0; i < tls->frame_count; ++i) {
8885 buffer_add_int (buf, tls->frames [i]->id);
8886 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
8887 buffer_add_int (buf, tls->frames [i]->il_offset);
8889 * Instead of passing the frame type directly to the client, we associate
8890 * it with the previous frame using a set of flags. This avoids lots of
8891 * conditional code in the client, since a frame whose type isn't
8892 * FRAME_TYPE_MANAGED has no method, location, etc.
8894 buffer_add_byte (buf, tls->frames [i]->flags);
8899 case CMD_THREAD_GET_STATE:
8900 buffer_add_int (buf, thread->state);
8902 case CMD_THREAD_GET_INFO:
8903 buffer_add_byte (buf, thread->threadpool_thread);
8905 case CMD_THREAD_GET_ID:
8906 buffer_add_long (buf, (guint64)(gsize)thread);
8908 case CMD_THREAD_GET_TID:
8909 buffer_add_long (buf, (guint64)thread->tid);
8911 case CMD_THREAD_SET_IP: {
8912 DebuggerTlsData *tls;
8915 MonoSeqPointInfo *seq_points;
8920 method = decode_methodid (p, &p, end, &domain, &err);
8921 if (err != ERR_NONE)
8923 il_offset = decode_long (p, &p, end);
8925 while (!is_suspended ()) {
8927 wait_for_suspend ();
8930 mono_loader_lock ();
8931 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
8932 mono_loader_unlock ();
8935 compute_frame_info (thread, tls);
8936 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
8937 return ERR_INVALID_ARGUMENT;
8939 found_sp = mono_find_seq_point (domain, method, il_offset, &seq_points, &sp);
8941 g_assert (seq_points);
8944 return ERR_INVALID_ARGUMENT;
8946 // FIXME: Check that the ip change is safe
8948 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);
8949 MONO_CONTEXT_SET_IP (&tls->restore_state.ctx, (guint8*)tls->frames [0]->ji->code_start + sp.native_offset);
8953 return ERR_NOT_IMPLEMENTED;
8960 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8964 MonoThread *thread_obj;
8965 MonoInternalThread *thread;
8966 int pos, i, len, frame_idx;
8967 DebuggerTlsData *tls;
8969 MonoDebugMethodJitInfo *jit;
8970 MonoMethodSignature *sig;
8972 MonoMethodHeader *header;
8974 objid = decode_objid (p, &p, end);
8975 err = get_object (objid, (MonoObject**)&thread_obj);
8976 if (err != ERR_NONE)
8979 thread = THREAD_TO_INTERNAL (thread_obj);
8981 id = decode_id (p, &p, end);
8983 mono_loader_lock ();
8984 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
8985 mono_loader_unlock ();
8988 for (i = 0; i < tls->frame_count; ++i) {
8989 if (tls->frames [i]->id == id)
8992 if (i == tls->frame_count)
8993 return ERR_INVALID_FRAMEID;
8996 frame = tls->frames [frame_idx];
8998 /* This is supported for frames without has_ctx etc. set */
8999 if (command == CMD_STACK_FRAME_GET_DOMAIN) {
9000 if (CHECK_PROTOCOL_VERSION (2, 38))
9001 buffer_add_domainid (buf, frame->domain);
9005 if (!frame->has_ctx)
9006 return ERR_ABSENT_INFORMATION;
9009 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
9010 if (!frame->jit && frame->api_method->is_inflated)
9011 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
9015 /* This could happen for aot images with no jit debug info */
9016 s = mono_method_full_name (frame->api_method, TRUE);
9017 DEBUG_PRINTF (1, "[dbg] No debug information found for '%s'.\n", s);
9019 return ERR_ABSENT_INFORMATION;
9024 sig = mono_method_signature (frame->actual_method);
9026 if (!mono_get_seq_points (frame->domain, frame->actual_method))
9028 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
9030 return ERR_ABSENT_INFORMATION;
9033 case CMD_STACK_FRAME_GET_VALUES: {
9035 len = decode_int (p, &p, end);
9036 header = mono_method_get_header_checked (frame->actual_method, &error);
9037 mono_error_assert_ok (&error); /* FIXME report error */
9039 for (i = 0; i < len; ++i) {
9040 pos = decode_int (p, &p, end);
9045 DEBUG_PRINTF (4, "[dbg] send arg %d.\n", pos);
9047 g_assert (pos >= 0 && pos < jit->num_params);
9049 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
9051 MonoDebugLocalsInfo *locals;
9053 locals = mono_debug_lookup_locals (frame->method);
9055 g_assert (pos < locals->num_locals);
9056 pos = locals->locals [pos].index;
9057 mono_debug_free_locals (locals);
9059 g_assert (pos >= 0 && pos < jit->num_locals);
9061 DEBUG_PRINTF (4, "[dbg] send local %d.\n", pos);
9063 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
9066 mono_metadata_free_mh (header);
9069 case CMD_STACK_FRAME_GET_THIS: {
9070 if (frame->api_method->klass->valuetype) {
9071 if (!sig->hasthis) {
9072 MonoObject *p = NULL;
9073 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
9075 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9078 if (!sig->hasthis) {
9079 MonoObject *p = NULL;
9080 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
9082 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9087 case CMD_STACK_FRAME_SET_VALUES: {
9091 MonoDebugVarInfo *var;
9093 len = decode_int (p, &p, end);
9094 header = mono_method_get_header_checked (frame->actual_method, &error);
9095 mono_error_assert_ok (&error); /* FIXME report error */
9097 for (i = 0; i < len; ++i) {
9098 pos = decode_int (p, &p, end);
9103 g_assert (pos >= 0 && pos < jit->num_params);
9105 t = sig->params [pos];
9106 var = &jit->params [pos];
9108 MonoDebugLocalsInfo *locals;
9110 locals = mono_debug_lookup_locals (frame->method);
9112 g_assert (pos < locals->num_locals);
9113 pos = locals->locals [pos].index;
9114 mono_debug_free_locals (locals);
9116 g_assert (pos >= 0 && pos < jit->num_locals);
9118 t = header->locals [pos];
9119 var = &jit->locals [pos];
9122 if (MONO_TYPE_IS_REFERENCE (t))
9123 val_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
9125 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9126 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9127 if (err != ERR_NONE)
9130 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9132 mono_metadata_free_mh (header);
9135 case CMD_STACK_FRAME_GET_DOMAIN: {
9136 if (CHECK_PROTOCOL_VERSION (2, 38))
9137 buffer_add_domainid (buf, frame->domain);
9141 return ERR_NOT_IMPLEMENTED;
9148 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9151 int objid, index, len, i, esize;
9155 objid = decode_objid (p, &p, end);
9156 err = get_object (objid, (MonoObject**)&arr);
9157 if (err != ERR_NONE)
9161 case CMD_ARRAY_REF_GET_LENGTH:
9162 buffer_add_int (buf, arr->obj.vtable->klass->rank);
9164 buffer_add_int (buf, arr->max_length);
9165 buffer_add_int (buf, 0);
9167 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
9168 buffer_add_int (buf, arr->bounds [i].length);
9169 buffer_add_int (buf, arr->bounds [i].lower_bound);
9173 case CMD_ARRAY_REF_GET_VALUES:
9174 index = decode_int (p, &p, end);
9175 len = decode_int (p, &p, end);
9177 g_assert (index >= 0 && len >= 0);
9178 // Reordered to avoid integer overflow
9179 g_assert (!(index > arr->max_length - len));
9181 esize = mono_array_element_size (arr->obj.vtable->klass);
9182 for (i = index; i < index + len; ++i) {
9183 elem = (gpointer*)((char*)arr->vector + (i * esize));
9184 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
9187 case CMD_ARRAY_REF_SET_VALUES:
9188 index = decode_int (p, &p, end);
9189 len = decode_int (p, &p, end);
9191 g_assert (index >= 0 && len >= 0);
9192 // Reordered to avoid integer overflow
9193 g_assert (!(index > arr->max_length - len));
9195 esize = mono_array_element_size (arr->obj.vtable->klass);
9196 for (i = index; i < index + len; ++i) {
9197 elem = (gpointer*)((char*)arr->vector + (i * esize));
9199 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, (guint8 *)elem, p, &p, end);
9203 return ERR_NOT_IMPLEMENTED;
9210 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9216 int i, index, length;
9218 gboolean use_utf16 = FALSE;
9220 objid = decode_objid (p, &p, end);
9221 err = get_object (objid, (MonoObject**)&str);
9222 if (err != ERR_NONE)
9226 case CMD_STRING_REF_GET_VALUE:
9227 if (CHECK_PROTOCOL_VERSION (2, 41)) {
9228 for (i = 0; i < mono_string_length (str); ++i)
9229 if (mono_string_chars (str)[i] == 0)
9231 buffer_add_byte (buf, use_utf16 ? 1 : 0);
9234 buffer_add_int (buf, mono_string_length (str) * 2);
9235 buffer_add_data (buf, (guint8*)mono_string_chars (str), mono_string_length (str) * 2);
9237 s = mono_string_to_utf8 (str);
9238 buffer_add_string (buf, s);
9242 case CMD_STRING_REF_GET_LENGTH:
9243 buffer_add_long (buf, mono_string_length (str));
9245 case CMD_STRING_REF_GET_CHARS:
9246 index = decode_long (p, &p, end);
9247 length = decode_long (p, &p, end);
9248 if (index > mono_string_length (str) - length)
9249 return ERR_INVALID_ARGUMENT;
9250 c = mono_string_chars (str) + index;
9251 for (i = 0; i < length; ++i)
9252 buffer_add_short (buf, c [i]);
9255 return ERR_NOT_IMPLEMENTED;
9262 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9273 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9274 objid = decode_objid (p, &p, end);
9275 err = get_object (objid, &obj);
9276 if (err != ERR_NONE)
9277 buffer_add_int (buf, 1);
9279 buffer_add_int (buf, 0);
9283 objid = decode_objid (p, &p, end);
9284 err = get_object (objid, &obj);
9285 if (err != ERR_NONE)
9288 MonoClass *obj_type;
9289 gboolean remote_obj = FALSE;
9291 obj_type = obj->vtable->klass;
9292 if (mono_class_is_transparent_proxy (obj_type)) {
9293 obj_type = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
9297 g_assert (obj_type);
9300 case CMD_OBJECT_REF_GET_TYPE:
9301 /* This handles transparent proxies too */
9302 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9304 case CMD_OBJECT_REF_GET_VALUES:
9305 len = decode_int (p, &p, end);
9307 for (i = 0; i < len; ++i) {
9308 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9309 if (err != ERR_NONE)
9312 /* Check that the field belongs to the object */
9314 for (k = obj_type; k; k = k->parent) {
9315 if (k == f->parent) {
9321 return ERR_INVALID_FIELDID;
9323 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9327 if (mono_class_field_is_special_static (f))
9328 return ERR_INVALID_FIELDID;
9330 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9331 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9332 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9333 mono_field_static_get_value_checked (vtable, f, val, &error);
9334 if (!is_ok (&error)) {
9335 mono_error_cleanup (&error); /* FIXME report the error */
9336 return ERR_INVALID_OBJECT;
9338 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9341 guint8 *field_value = NULL;
9342 void *field_storage = NULL;
9345 #ifndef DISABLE_REMOTING
9346 field_value = mono_load_remote_field_checked(obj, obj_type, f, &field_storage, &error);
9347 if (!is_ok (&error)) {
9348 mono_error_cleanup (&error); /* FIXME report the error */
9349 return ERR_INVALID_OBJECT;
9352 g_assert_not_reached ();
9355 field_value = (guint8*)obj + f->offset;
9357 buffer_add_value (buf, f->type, field_value, obj->vtable->domain);
9361 case CMD_OBJECT_REF_SET_VALUES:
9362 len = decode_int (p, &p, end);
9364 for (i = 0; i < len; ++i) {
9365 f = decode_fieldid (p, &p, end, NULL, &err);
9366 if (err != ERR_NONE)
9369 /* Check that the field belongs to the object */
9371 for (k = obj_type; k; k = k->parent) {
9372 if (k == f->parent) {
9378 return ERR_INVALID_FIELDID;
9380 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9384 if (mono_class_field_is_special_static (f))
9385 return ERR_INVALID_FIELDID;
9387 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9388 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9390 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9391 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
9392 if (err != ERR_NONE) {
9396 mono_field_static_set_value (vtable, f, val);
9399 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
9400 if (err != ERR_NONE)
9405 case CMD_OBJECT_REF_GET_ADDRESS:
9406 buffer_add_long (buf, (gssize)obj);
9408 case CMD_OBJECT_REF_GET_DOMAIN:
9409 buffer_add_domainid (buf, obj->vtable->domain);
9411 case CMD_OBJECT_REF_GET_INFO:
9412 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9413 buffer_add_domainid (buf, obj->vtable->domain);
9416 return ERR_NOT_IMPLEMENTED;
9423 command_set_to_string (CommandSet command_set)
9425 switch (command_set) {
9428 case CMD_SET_OBJECT_REF:
9429 return "OBJECT_REF";
9430 case CMD_SET_STRING_REF:
9431 return "STRING_REF";
9432 case CMD_SET_THREAD:
9434 case CMD_SET_ARRAY_REF:
9436 case CMD_SET_EVENT_REQUEST:
9437 return "EVENT_REQUEST";
9438 case CMD_SET_STACK_FRAME:
9439 return "STACK_FRAME";
9440 case CMD_SET_APPDOMAIN:
9442 case CMD_SET_ASSEMBLY:
9444 case CMD_SET_METHOD:
9448 case CMD_SET_MODULE:
9459 static const char* vm_cmds_str [] = {
9467 "SET_PROTOCOL_VERSION",
9470 "GET_TYPES_FOR_SOURCE_FILE",
9475 static const char* thread_cmds_str[] = {
9485 static const char* event_cmds_str[] = {
9488 "REQUEST_CLEAR_ALL_BREAKPOINTS"
9491 static const char* appdomain_cmds_str[] = {
9493 "GET_FRIENDLY_NAME",
9495 "GET_ENTRY_ASSEMBLY",
9498 "CREATE_BOXED_VALUE"
9501 static const char* assembly_cmds_str[] = {
9504 "GET_MANIFEST_MODULE",
9510 static const char* module_cmds_str[] = {
9514 static const char* field_cmds_str[] = {
9518 static const char* method_cmds_str[] = {
9520 "GET_DECLARING_TYPE",
9528 "MAKE_GENERIC_METHOD"
9531 static const char* type_cmds_str[] = {
9539 "IS_ASSIGNABLE_FROM",
9543 "GET_PROPERTY_CATTRS",
9544 "GET_SOURCE_FILES_2",
9546 "GET_METHODS_BY_NAME_FLAGS",
9548 "GET_INTERFACE_MAP",
9552 static const char* stack_frame_cmds_str[] = {
9559 static const char* array_cmds_str[] = {
9565 static const char* string_cmds_str[] = {
9571 static const char* object_cmds_str[] = {
9582 cmd_to_string (CommandSet set, int command)
9590 cmds_len = G_N_ELEMENTS (vm_cmds_str);
9592 case CMD_SET_OBJECT_REF:
9593 cmds = object_cmds_str;
9594 cmds_len = G_N_ELEMENTS (object_cmds_str);
9596 case CMD_SET_STRING_REF:
9597 cmds = string_cmds_str;
9598 cmds_len = G_N_ELEMENTS (string_cmds_str);
9600 case CMD_SET_THREAD:
9601 cmds = thread_cmds_str;
9602 cmds_len = G_N_ELEMENTS (thread_cmds_str);
9604 case CMD_SET_ARRAY_REF:
9605 cmds = array_cmds_str;
9606 cmds_len = G_N_ELEMENTS (array_cmds_str);
9608 case CMD_SET_EVENT_REQUEST:
9609 cmds = event_cmds_str;
9610 cmds_len = G_N_ELEMENTS (event_cmds_str);
9612 case CMD_SET_STACK_FRAME:
9613 cmds = stack_frame_cmds_str;
9614 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
9616 case CMD_SET_APPDOMAIN:
9617 cmds = appdomain_cmds_str;
9618 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
9620 case CMD_SET_ASSEMBLY:
9621 cmds = assembly_cmds_str;
9622 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
9624 case CMD_SET_METHOD:
9625 cmds = method_cmds_str;
9626 cmds_len = G_N_ELEMENTS (method_cmds_str);
9629 cmds = type_cmds_str;
9630 cmds_len = G_N_ELEMENTS (type_cmds_str);
9632 case CMD_SET_MODULE:
9633 cmds = module_cmds_str;
9634 cmds_len = G_N_ELEMENTS (module_cmds_str);
9637 cmds = field_cmds_str;
9638 cmds_len = G_N_ELEMENTS (field_cmds_str);
9641 cmds = event_cmds_str;
9642 cmds_len = G_N_ELEMENTS (event_cmds_str);
9647 if (command > 0 && command <= cmds_len)
9648 return cmds [command - 1];
9654 wait_for_attach (void)
9656 #ifndef DISABLE_SOCKET_TRANSPORT
9657 if (listen_fd == -1) {
9658 DEBUG_PRINTF (1, "[dbg] Invalid listening socket\n");
9662 /* Block and wait for client connection */
9663 conn_fd = socket_transport_accept (listen_fd);
9665 DEBUG_PRINTF (1, "Accepted connection on %d\n", conn_fd);
9666 if (conn_fd == -1) {
9667 DEBUG_PRINTF (1, "[dbg] Bad client connection\n");
9671 g_assert_not_reached ();
9675 disconnected = !transport_handshake ();
9677 DEBUG_PRINTF (1, "Transport handshake failed!\n");
9687 * This thread handles communication with the debugger client using a JDWP
9690 static guint32 WINAPI
9691 debugger_thread (void *arg)
9694 int res, len, id, flags, command = 0;
9695 CommandSet command_set = (CommandSet)0;
9696 guint8 header [HEADER_LENGTH];
9697 guint8 *data, *p, *end;
9701 gboolean attach_failed = FALSE;
9703 DEBUG_PRINTF (1, "[dbg] Agent thread started, pid=%p\n", (gpointer) (gsize) mono_native_thread_id_get ());
9705 debugger_thread_id = mono_native_thread_id_get ();
9707 MonoThread *thread = mono_thread_attach (mono_get_root_domain ());
9708 mono_thread_set_name_internal (thread->internal_thread, mono_string_new (mono_get_root_domain (), "Debugger agent"), TRUE, &error);
9709 mono_error_assert_ok (&error);
9711 thread->internal_thread->state |= ThreadState_Background;
9712 thread->internal_thread->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
9714 mono_set_is_debugger_attached (TRUE);
9716 if (agent_config.defer) {
9717 if (!wait_for_attach ()) {
9718 DEBUG_PRINTF (1, "[dbg] Can't attach, aborting debugger thread.\n");
9719 attach_failed = TRUE; // Don't abort process when we can't listen
9721 /* Send start event to client */
9722 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
9726 while (!attach_failed) {
9727 res = transport_recv (header, HEADER_LENGTH);
9729 /* This will break if the socket is closed during shutdown too */
9730 if (res != HEADER_LENGTH) {
9731 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH);
9736 end = header + HEADER_LENGTH;
9738 len = decode_int (p, &p, end);
9739 id = decode_int (p, &p, end);
9740 flags = decode_byte (p, &p, end);
9741 command_set = (CommandSet)decode_byte (p, &p, end);
9742 command = decode_byte (p, &p, end);
9744 g_assert (flags == 0);
9747 const char *cmd_str;
9750 cmd_str = cmd_to_string (command_set, command);
9752 sprintf (cmd_num, "%d", command);
9756 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);
9759 data = (guint8 *)g_malloc (len - HEADER_LENGTH);
9760 if (len - HEADER_LENGTH > 0)
9762 res = transport_recv (data, len - HEADER_LENGTH);
9763 if (res != len - HEADER_LENGTH) {
9764 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH);
9770 end = data + (len - HEADER_LENGTH);
9772 buffer_init (&buf, 128);
9777 /* Process the request */
9778 switch (command_set) {
9780 err = vm_commands (command, id, p, end, &buf);
9781 if (err == ERR_NONE && command == CMD_VM_INVOKE_METHOD)
9782 /* Sent after the invoke is complete */
9785 case CMD_SET_EVENT_REQUEST:
9786 err = event_commands (command, p, end, &buf);
9788 case CMD_SET_APPDOMAIN:
9789 err = domain_commands (command, p, end, &buf);
9791 case CMD_SET_ASSEMBLY:
9792 err = assembly_commands (command, p, end, &buf);
9794 case CMD_SET_MODULE:
9795 err = module_commands (command, p, end, &buf);
9798 err = field_commands (command, p, end, &buf);
9801 err = type_commands (command, p, end, &buf);
9803 case CMD_SET_METHOD:
9804 err = method_commands (command, p, end, &buf);
9806 case CMD_SET_THREAD:
9807 err = thread_commands (command, p, end, &buf);
9809 case CMD_SET_STACK_FRAME:
9810 err = frame_commands (command, p, end, &buf);
9812 case CMD_SET_ARRAY_REF:
9813 err = array_commands (command, p, end, &buf);
9815 case CMD_SET_STRING_REF:
9816 err = string_commands (command, p, end, &buf);
9818 case CMD_SET_OBJECT_REF:
9819 err = object_commands (command, p, end, &buf);
9822 err = ERR_NOT_IMPLEMENTED;
9825 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
9826 buffer_replies = TRUE;
9830 if (buffer_replies) {
9831 buffer_reply_packet (id, err, &buf);
9833 send_reply_packet (id, err, &buf);
9834 //DEBUG_PRINTF (1, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000);
9838 if (err == ERR_NONE && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
9839 send_buffered_reply_packets ();
9840 buffer_replies = FALSE;
9846 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
9850 mono_set_is_debugger_attached (FALSE);
9852 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
9853 debugger_thread_exited = TRUE;
9854 mono_coop_cond_signal (&debugger_thread_exited_cond);
9855 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
9857 DEBUG_PRINTF (1, "[dbg] Debugger thread exited.\n");
9859 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
9860 DEBUG_PRINTF (2, "[dbg] Detached - restarting clean debugger thread.\n");
9861 start_debugger_thread ();
9867 #else /* DISABLE_DEBUGGER_AGENT */
9870 mono_debugger_agent_parse_options (char *options)
9872 g_error ("This runtime is configured with the debugger agent disabled.");
9876 mono_debugger_agent_init (void)
9881 mono_debugger_agent_breakpoint_hit (void *sigctx)
9886 mono_debugger_agent_single_step_event (void *sigctx)
9891 mono_debugger_agent_free_domain_info (MonoDomain *domain)
9896 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
9897 MonoContext *catch_ctx)
9902 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9907 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9912 mono_debugger_agent_user_break (void)
9918 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
9923 mono_debugger_agent_debug_log_is_enabled (void)
9929 mono_debugger_agent_unhandled_exception (MonoException *exc)
9931 g_assert_not_reached ();
9935 debugger_agent_single_step_from_context (MonoContext *ctx)
9937 g_assert_not_reached ();
9941 debugger_agent_breakpoint_from_context (MonoContext *ctx)
9943 g_assert_not_reached ();