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.
15 #ifdef HAVE_SYS_TYPES_H
16 #include <sys/types.h>
18 #ifdef HAVE_SYS_SELECT_H
19 #include <sys/select.h>
21 #ifdef HAVE_SYS_SOCKET_H
22 #include <sys/socket.h>
24 #ifdef HAVE_NETINET_TCP_H
25 #include <netinet/tcp.h>
27 #ifdef HAVE_NETINET_IN_H
28 #include <netinet/in.h>
48 #ifdef PLATFORM_ANDROID
50 #include <linux/tcp.h>
51 #include <sys/endian.h>
54 #include <mono/metadata/mono-debug.h>
55 #include <mono/metadata/mono-debug-debugger.h>
56 #include <mono/metadata/debug-mono-symfile.h>
57 #include <mono/metadata/gc-internal.h>
58 #include <mono/metadata/environment.h>
59 #include <mono/metadata/threads-types.h>
60 #include <mono/metadata/threadpool-ms.h>
61 #include <mono/metadata/socket-io.h>
62 #include <mono/metadata/assembly.h>
63 #include <mono/metadata/runtime.h>
64 #include <mono/metadata/verify-internals.h>
65 #include <mono/utils/mono-semaphore.h>
66 #include <mono/utils/mono-error-internals.h>
67 #include <mono/utils/mono-stack-unwinding.h>
68 #include <mono/utils/mono-time.h>
69 #include <mono/utils/mono-threads.h>
70 #include <mono/utils/networking.h>
71 #include "debugger-agent.h"
73 #include "seq-points.h"
76 * On iOS we can't use System.Environment.Exit () as it will do the wrong
79 #if !defined (TARGET_IOS)
80 #define TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
84 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
85 #define DISABLE_DEBUGGER_AGENT 1
88 #ifdef DISABLE_SOFT_DEBUG
89 #define DISABLE_DEBUGGER_AGENT 1
92 #ifndef DISABLE_DEBUGGER_AGENT
94 #include <mono/utils/mono-mutex.h>
96 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
119 guint32 il_offset, native_offset;
123 * If method is gshared, this is the actual instance, otherwise this is equal to
126 MonoMethod *actual_method;
128 * This is the method which is visible to debugger clients. Same as method,
129 * except for native-to-managed wrappers.
131 MonoMethod *api_method;
133 MonoDebugMethodJitInfo *jit;
136 mgreg_t *reg_locations [MONO_MAX_IREGS];
138 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
139 * the frame can become invalid.
144 typedef struct _InvokeData InvokeData;
152 /* This is the context which needs to be restored after the invoke */
156 * If this is set, invoke this method with the arguments given by ARGS.
160 guint32 suspend_count;
163 InvokeData *last_invoke;
167 MonoThreadUnwindState context;
169 /* This is computed on demand when it is requested using the wire protocol */
170 /* It is freed up when the thread is resumed */
174 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
177 gboolean frames_up_to_date;
179 * Points to data about a pending invoke which needs to be executed after the thread
182 InvokeData *pending_invoke;
184 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
189 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
190 * within a finite amount of time.
194 * Set to TRUE if this thread is suspended in suspend_current ().
196 gboolean really_suspended;
197 /* Used to pass the context to the breakpoint/single step handler */
198 MonoContext handler_ctx;
199 /* Whenever thread_stop () was called for this thread */
202 /* Whenever to disable breakpoints (used during invokes) */
203 gboolean disable_breakpoints;
206 * Number of times this thread has been resumed using resume_thread ().
208 guint32 resume_count;
210 MonoInternalThread *thread;
213 * Information about the frame which transitioned to native code for running
216 StackFrameInfo async_last_frame;
219 * The context where the stack walk can be started for running threads.
221 MonoThreadUnwindState async_state;
224 * The context used for filter clauses
226 MonoThreadUnwindState filter_state;
228 gboolean abort_requested;
231 * The current mono_runtime_invoke invocation.
236 * The context where single stepping should resume while the thread is suspended because
237 * of an EXCEPTION event.
239 MonoThreadUnwindState catch_state;
242 * The context which needs to be restored after handling a single step/breakpoint
243 * event. This is the same as the ctx at step/breakpoint site, but includes changes
244 * to caller saved registers done by set_var ().
246 MonoThreadUnwindState restore_state;
247 /* Frames computed from restore_state */
248 int restore_frame_count;
249 StackFrame **restore_frames;
251 /* The currently unloading appdomain */
252 MonoDomain *domain_unloading;
257 void (*connect) (const char *address);
258 void (*close1) (void);
259 void (*close2) (void);
260 gboolean (*send) (void *buf, int len);
261 int (*recv) (void *buf, int len);
265 * Wire Protocol definitions
268 #define HEADER_LENGTH 11
270 #define MAJOR_VERSION 2
271 #define MINOR_VERSION 42
275 CMD_SET_OBJECT_REF = 9,
276 CMD_SET_STRING_REF = 10,
278 CMD_SET_ARRAY_REF = 13,
279 CMD_SET_EVENT_REQUEST = 15,
280 CMD_SET_STACK_FRAME = 16,
281 CMD_SET_APPDOMAIN = 20,
282 CMD_SET_ASSEMBLY = 21,
291 EVENT_KIND_VM_START = 0,
292 EVENT_KIND_VM_DEATH = 1,
293 EVENT_KIND_THREAD_START = 2,
294 EVENT_KIND_THREAD_DEATH = 3,
295 EVENT_KIND_APPDOMAIN_CREATE = 4,
296 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
297 EVENT_KIND_METHOD_ENTRY = 6,
298 EVENT_KIND_METHOD_EXIT = 7,
299 EVENT_KIND_ASSEMBLY_LOAD = 8,
300 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
301 EVENT_KIND_BREAKPOINT = 10,
302 EVENT_KIND_STEP = 11,
303 EVENT_KIND_TYPE_LOAD = 12,
304 EVENT_KIND_EXCEPTION = 13,
305 EVENT_KIND_KEEPALIVE = 14,
306 EVENT_KIND_USER_BREAK = 15,
307 EVENT_KIND_USER_LOG = 16
311 SUSPEND_POLICY_NONE = 0,
312 SUSPEND_POLICY_EVENT_THREAD = 1,
313 SUSPEND_POLICY_ALL = 2
318 ERR_INVALID_OBJECT = 20,
319 ERR_INVALID_FIELDID = 25,
320 ERR_INVALID_FRAMEID = 30,
321 ERR_NOT_IMPLEMENTED = 100,
322 ERR_NOT_SUSPENDED = 101,
323 ERR_INVALID_ARGUMENT = 102,
325 ERR_NO_INVOCATION = 104,
326 ERR_ABSENT_INFORMATION = 105,
327 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
328 ERR_INVOKE_ABORTED = 107,
329 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
334 MOD_KIND_THREAD_ONLY = 3,
335 MOD_KIND_LOCATION_ONLY = 7,
336 MOD_KIND_EXCEPTION_ONLY = 8,
338 MOD_KIND_ASSEMBLY_ONLY = 11,
339 MOD_KIND_SOURCE_FILE_ONLY = 12,
340 MOD_KIND_TYPE_NAME_ONLY = 13,
356 STEP_FILTER_NONE = 0,
357 STEP_FILTER_STATIC_CTOR = 1,
358 STEP_FILTER_DEBUGGER_HIDDEN = 2,
359 STEP_FILTER_DEBUGGER_STEP_THROUGH = 4,
360 STEP_FILTER_DEBUGGER_NON_USER_CODE = 8
364 TOKEN_TYPE_STRING = 0,
366 TOKEN_TYPE_FIELD = 2,
367 TOKEN_TYPE_METHOD = 3,
368 TOKEN_TYPE_UNKNOWN = 4
372 VALUE_TYPE_ID_NULL = 0xf0,
373 VALUE_TYPE_ID_TYPE = 0xf1,
374 VALUE_TYPE_ID_PARENT_VTYPE = 0xf2
378 FRAME_FLAG_DEBUGGER_INVOKE = 1,
379 FRAME_FLAG_NATIVE_TRANSITION = 2
383 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
384 INVOKE_FLAG_SINGLE_THREADED = 2,
385 INVOKE_FLAG_RETURN_OUT_THIS = 4,
386 INVOKE_FLAG_RETURN_OUT_ARGS = 8,
387 INVOKE_FLAG_VIRTUAL = 16
391 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
392 } BindingFlagsExtensions;
396 CMD_VM_ALL_THREADS = 2,
401 CMD_VM_INVOKE_METHOD = 7,
402 CMD_VM_SET_PROTOCOL_VERSION = 8,
403 CMD_VM_ABORT_INVOKE = 9,
404 CMD_VM_SET_KEEPALIVE = 10,
405 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
406 CMD_VM_GET_TYPES = 12,
407 CMD_VM_INVOKE_METHODS = 13,
408 CMD_VM_START_BUFFERING = 14,
409 CMD_VM_STOP_BUFFERING = 15
413 CMD_THREAD_GET_FRAME_INFO = 1,
414 CMD_THREAD_GET_NAME = 2,
415 CMD_THREAD_GET_STATE = 3,
416 CMD_THREAD_GET_INFO = 4,
417 CMD_THREAD_GET_ID = 5,
418 CMD_THREAD_GET_TID = 6,
419 CMD_THREAD_SET_IP = 7
423 CMD_EVENT_REQUEST_SET = 1,
424 CMD_EVENT_REQUEST_CLEAR = 2,
425 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
433 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
434 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
435 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
436 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
437 CMD_APPDOMAIN_CREATE_STRING = 5,
438 CMD_APPDOMAIN_GET_CORLIB = 6,
439 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
443 CMD_ASSEMBLY_GET_LOCATION = 1,
444 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
445 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
446 CMD_ASSEMBLY_GET_OBJECT = 4,
447 CMD_ASSEMBLY_GET_TYPE = 5,
448 CMD_ASSEMBLY_GET_NAME = 6
452 CMD_MODULE_GET_INFO = 1,
456 CMD_FIELD_GET_INFO = 1,
460 CMD_METHOD_GET_NAME = 1,
461 CMD_METHOD_GET_DECLARING_TYPE = 2,
462 CMD_METHOD_GET_DEBUG_INFO = 3,
463 CMD_METHOD_GET_PARAM_INFO = 4,
464 CMD_METHOD_GET_LOCALS_INFO = 5,
465 CMD_METHOD_GET_INFO = 6,
466 CMD_METHOD_GET_BODY = 7,
467 CMD_METHOD_RESOLVE_TOKEN = 8,
468 CMD_METHOD_GET_CATTRS = 9,
469 CMD_METHOD_MAKE_GENERIC_METHOD = 10
473 CMD_TYPE_GET_INFO = 1,
474 CMD_TYPE_GET_METHODS = 2,
475 CMD_TYPE_GET_FIELDS = 3,
476 CMD_TYPE_GET_VALUES = 4,
477 CMD_TYPE_GET_OBJECT = 5,
478 CMD_TYPE_GET_SOURCE_FILES = 6,
479 CMD_TYPE_SET_VALUES = 7,
480 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
481 CMD_TYPE_GET_PROPERTIES = 9,
482 CMD_TYPE_GET_CATTRS = 10,
483 CMD_TYPE_GET_FIELD_CATTRS = 11,
484 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
485 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
486 CMD_TYPE_GET_VALUES_2 = 14,
487 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
488 CMD_TYPE_GET_INTERFACES = 16,
489 CMD_TYPE_GET_INTERFACE_MAP = 17,
490 CMD_TYPE_IS_INITIALIZED = 18,
491 CMD_TYPE_CREATE_INSTANCE = 19
495 CMD_STACK_FRAME_GET_VALUES = 1,
496 CMD_STACK_FRAME_GET_THIS = 2,
497 CMD_STACK_FRAME_SET_VALUES = 3,
498 CMD_STACK_FRAME_GET_DOMAIN = 4,
502 CMD_ARRAY_REF_GET_LENGTH = 1,
503 CMD_ARRAY_REF_GET_VALUES = 2,
504 CMD_ARRAY_REF_SET_VALUES = 3,
508 CMD_STRING_REF_GET_VALUE = 1,
509 CMD_STRING_REF_GET_LENGTH = 2,
510 CMD_STRING_REF_GET_CHARS = 3
514 CMD_OBJECT_REF_GET_TYPE = 1,
515 CMD_OBJECT_REF_GET_VALUES = 2,
516 CMD_OBJECT_REF_IS_COLLECTED = 3,
517 CMD_OBJECT_REF_GET_ADDRESS = 4,
518 CMD_OBJECT_REF_GET_DOMAIN = 5,
519 CMD_OBJECT_REF_SET_VALUES = 6,
520 CMD_OBJECT_REF_GET_INFO = 7,
526 int count; /* For kind == MOD_KIND_COUNT */
527 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
528 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
529 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
530 GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
531 GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
532 StepFilter filter; /* For kind == MOD_KIND_STEP */
534 gboolean caught, uncaught, subclasses; /* For kind == MOD_KIND_EXCEPTION_ONLY */
543 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
547 * Describes a single step request.
551 MonoInternalThread *thread;
557 MonoMethod *start_method;
558 MonoMethod *last_method;
560 /* Whenever single stepping is performed using start/stop_single_stepping () */
562 /* The list of breakpoints used to implement step-over */
564 /* The number of frames at the start of a step-over */
569 * Contains additional information for an event
572 /* For EVENT_KIND_EXCEPTION */
574 MonoContext catch_ctx;
576 /* For EVENT_KIND_USER_LOG */
578 char *category, *message;
579 /* For EVENT_KIND_TYPE_LOAD */
583 /* Dummy structure used for the profiler callbacks */
589 guint8 *buf, *p, *end;
592 typedef struct ReplyPacket {
598 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
600 #ifdef PLATFORM_ANDROID
601 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { g_print (__VA_ARGS__); } } while (0)
603 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { fprintf (log_file, __VA_ARGS__); fflush (log_file); } } while (0)
607 #define get_last_sock_error() WSAGetLastError()
608 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
609 #define MONO_EINTR WSAEINTR
611 #define get_last_sock_error() errno
612 #define MONO_EWOULDBLOCK EWOULDBLOCK
613 #define MONO_EINTR EINTR
616 #define CHECK_PROTOCOL_VERSION(major,minor) \
617 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
623 static AgentConfig agent_config;
626 * Whenever the agent is fully initialized.
627 * When using the onuncaught or onthrow options, only some parts of the agent are
628 * initialized on startup, and the full initialization which includes connection
629 * establishment and the startup of the agent thread is only done in response to
632 static gint32 inited;
634 #ifndef DISABLE_SOCKET_TRANSPORT
636 static int listen_fd;
639 static int packet_id = 0;
641 static int objref_id = 0;
643 static int event_request_id = 0;
645 static int frame_id = 0;
647 static GPtrArray *event_requests;
649 static MonoNativeTlsKey debugger_tls_id;
651 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
653 /* Maps MonoInternalThread -> DebuggerTlsData */
654 /* Protected by the loader lock */
655 static MonoGHashTable *thread_to_tls;
657 /* Maps tid -> MonoInternalThread */
658 /* Protected by the loader lock */
659 static MonoGHashTable *tid_to_thread;
661 /* Maps tid -> MonoThread (not MonoInternalThread) */
662 /* Protected by the loader lock */
663 static MonoGHashTable *tid_to_thread_obj;
665 static MonoNativeThreadId debugger_thread_id;
667 static HANDLE debugger_thread_handle;
669 static int log_level;
671 static gboolean embedding;
673 static FILE *log_file;
675 /* Assemblies whose assembly load event has no been sent yet */
676 /* Protected by the dbg lock */
677 static GPtrArray *pending_assembly_loads;
679 /* Whenever the debugger thread has exited */
680 static gboolean debugger_thread_exited;
682 /* Cond variable used to wait for debugger_thread_exited becoming true */
683 static mono_cond_t debugger_thread_exited_cond;
685 /* Mutex for the cond var above */
686 static mono_mutex_t debugger_thread_exited_mutex;
688 static DebuggerProfiler debugger_profiler;
690 /* The single step request instance */
691 static SingleStepReq *ss_req;
693 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
694 /* Number of single stepping operations in progress */
698 /* The protocol version of the client */
699 static int major_version, minor_version;
701 /* Whenever the variables above are set by the client */
702 static gboolean protocol_version_set;
704 /* A hash table containing all active domains */
705 /* Protected by the loader lock */
706 static GHashTable *domains;
708 /* The number of times the runtime is suspended */
709 static gint32 suspend_count;
711 /* Whenever to buffer reply messages and send them together */
712 static gboolean buffer_replies;
714 /* Buffered reply packets */
715 static ReplyPacket reply_packets [128];
718 #define dbg_lock() do { \
720 mono_mutex_lock (&debug_mutex); \
721 MONO_FINISH_TRY_BLOCKING; \
724 #define dbg_unlock() mono_mutex_unlock (&debug_mutex)
725 static mono_mutex_t debug_mutex;
727 static void transport_init (void);
728 static void transport_connect (const char *address);
729 static gboolean transport_handshake (void);
730 static void register_transport (DebuggerTransport *trans);
732 static guint32 WINAPI debugger_thread (void *arg);
734 static void runtime_initialized (MonoProfiler *prof);
736 static void runtime_shutdown (MonoProfiler *prof);
738 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
740 static void thread_end (MonoProfiler *prof, uintptr_t tid);
742 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
744 static void appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain);
746 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
748 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
750 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
752 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
754 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
756 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
758 static void emit_assembly_load (gpointer assembly, gpointer user_data);
760 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
762 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
764 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
766 static void start_single_stepping (void);
768 static void stop_single_stepping (void);
770 static void suspend_current (void);
772 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
774 static void clear_types_for_assembly (MonoAssembly *assembly);
776 static void clear_breakpoints_for_domain (MonoDomain *domain);
778 static void process_profiler_event (EventKind event, gpointer arg);
780 /* Submodule init/cleanup */
781 static void breakpoints_init (void);
782 static void breakpoints_cleanup (void);
784 static void objrefs_init (void);
785 static void objrefs_cleanup (void);
787 static void ids_init (void);
788 static void ids_cleanup (void);
790 static void suspend_init (void);
792 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch,
793 StackFrame **frames, int nframes);
794 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req);
795 static void ss_destroy (SingleStepReq *req);
797 static void start_debugger_thread (void);
798 static void stop_debugger_thread (void);
800 static void finish_agent_init (gboolean on_startup);
802 static void process_profiler_event (EventKind event, gpointer arg);
804 static void invalidate_frames (DebuggerTlsData *tls);
806 #ifndef DISABLE_SOCKET_TRANSPORT
808 register_socket_transport (void);
811 static inline gboolean
812 is_debugger_thread (void)
814 return mono_native_thread_id_equals (mono_native_thread_id_get (), debugger_thread_id);
818 parse_address (char *address, char **host, int *port)
820 char *pos = strchr (address, ':');
822 if (pos == NULL || pos == address)
825 *host = g_malloc (pos - address + 1);
826 strncpy (*host, address, pos - address);
827 (*host) [pos - address] = '\0';
829 *port = atoi (pos + 1);
837 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
838 fprintf (stderr, "Available options:\n");
839 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
840 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
841 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
842 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
843 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
844 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
845 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
846 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
847 fprintf (stderr, " setpgid=y/n\t\t\tWhether to call setpid(0, 0) after startup.\n");
848 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
852 parse_flag (const char *option, char *flag)
854 if (!strcmp (flag, "y"))
856 else if (!strcmp (flag, "n"))
859 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
866 mono_debugger_agent_parse_options (char *options)
873 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
874 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
878 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
880 options = g_strdup_printf ("%s,%s", options, extra);
882 agent_config.enabled = TRUE;
883 agent_config.suspend = TRUE;
884 agent_config.server = FALSE;
885 agent_config.defer = FALSE;
886 agent_config.address = NULL;
888 //agent_config.log_level = 10;
890 args = g_strsplit (options, ",", -1);
891 for (ptr = args; ptr && *ptr; ptr ++) {
894 if (strncmp (arg, "transport=", 10) == 0) {
895 agent_config.transport = g_strdup (arg + 10);
896 } else if (strncmp (arg, "address=", 8) == 0) {
897 agent_config.address = g_strdup (arg + 8);
898 } else if (strncmp (arg, "loglevel=", 9) == 0) {
899 agent_config.log_level = atoi (arg + 9);
900 } else if (strncmp (arg, "logfile=", 8) == 0) {
901 agent_config.log_file = g_strdup (arg + 8);
902 } else if (strncmp (arg, "suspend=", 8) == 0) {
903 agent_config.suspend = parse_flag ("suspend", arg + 8);
904 } else if (strncmp (arg, "server=", 7) == 0) {
905 agent_config.server = parse_flag ("server", arg + 7);
906 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
907 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
908 } else if (strncmp (arg, "onthrow=", 8) == 0) {
909 /* We support multiple onthrow= options */
910 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
911 } else if (strncmp (arg, "onthrow", 7) == 0) {
912 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
913 } else if (strncmp (arg, "help", 4) == 0) {
916 } else if (strncmp (arg, "timeout=", 8) == 0) {
917 agent_config.timeout = atoi (arg + 8);
918 } else if (strncmp (arg, "launch=", 7) == 0) {
919 agent_config.launch = g_strdup (arg + 7);
920 } else if (strncmp (arg, "embedding=", 10) == 0) {
921 agent_config.embedding = atoi (arg + 10) == 1;
922 } else if (strncmp (arg, "keepalive=", 10) == 0) {
923 agent_config.keepalive = atoi (arg + 10);
924 } else if (strncmp (arg, "setpgid=", 8) == 0) {
925 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
932 if (agent_config.server && !agent_config.suspend) {
933 /* Waiting for deferred attachment */
934 agent_config.defer = TRUE;
935 if (agent_config.address == NULL) {
936 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (getpid () % 1000));
940 //agent_config.log_level = 0;
942 if (agent_config.transport == NULL) {
943 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
947 if (agent_config.address == NULL && !agent_config.server) {
948 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
953 if (!strcmp (agent_config.transport, "dt_socket")) {
954 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
955 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
962 mono_debugger_agent_init (void)
964 mono_mutex_init_recursive (&debug_mutex);
966 if (!agent_config.enabled)
971 /* Need to know whenever a thread has acquired the loader mutex */
972 mono_loader_lock_track_ownership (TRUE);
974 event_requests = g_ptr_array_new ();
976 mono_mutex_init (&debugger_thread_exited_mutex);
977 mono_cond_init (&debugger_thread_exited_cond, 0);
979 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
980 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
981 mono_profiler_install_runtime_initialized (runtime_initialized);
982 mono_profiler_install_appdomain (NULL, appdomain_load, appdomain_start_unload, appdomain_unload);
983 mono_profiler_install_thread (thread_startup, thread_end);
984 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
985 mono_profiler_install_jit_end (jit_end);
987 mono_native_tls_alloc (&debugger_tls_id, NULL);
989 /* Needed by the hash_table_new_type () call below */
990 mono_gc_base_init ();
992 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_DEBUGGER, "thread-to-tls table");
993 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls, MONO_ROOT_SOURCE_DEBUGGER, "thread-to-tls table");
995 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread table");
996 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread table");
998 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");
999 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread object table");
1001 pending_assembly_loads = g_ptr_array_new ();
1002 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
1004 log_level = agent_config.log_level;
1006 embedding = agent_config.embedding;
1007 disconnected = TRUE;
1009 if (agent_config.log_file) {
1010 log_file = fopen (agent_config.log_file, "w+");
1012 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
1021 breakpoints_init ();
1024 mini_get_debug_options ()->gen_sdb_seq_points = TRUE;
1026 * This is needed because currently we don't handle liveness info.
1028 mini_get_debug_options ()->mdb_optimizations = TRUE;
1030 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
1031 /* This is needed because we can't set local variables in registers yet */
1032 mono_disable_optimizations (MONO_OPT_LINEARS);
1036 * The stack walk done from thread_interrupt () needs to be signal safe, but it
1037 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
1038 * safe (#3411). So load AOT info eagerly when the debugger is running as a
1041 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
1044 if (agent_config.setpgid)
1048 if (!agent_config.onuncaught && !agent_config.onthrow)
1049 finish_agent_init (TRUE);
1053 * finish_agent_init:
1055 * Finish the initialization of the agent. This involves connecting the transport
1056 * and starting the agent thread. This is either done at startup, or
1057 * in response to some event like an unhandled exception.
1060 finish_agent_init (gboolean on_startup)
1064 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
1067 if (agent_config.launch) {
1070 // FIXME: Generated address
1071 // FIXME: Races with transport_connect ()
1073 argv [0] = agent_config.launch;
1074 argv [1] = agent_config.transport;
1075 argv [2] = agent_config.address;
1078 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1080 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1085 MONO_PREPARE_BLOCKING;
1086 transport_connect (agent_config.address);
1087 MONO_FINISH_BLOCKING;
1090 /* Do some which is usually done after sending the VMStart () event */
1091 vm_start_event_sent = TRUE;
1092 start_debugger_thread ();
1097 mono_debugger_agent_cleanup (void)
1102 stop_debugger_thread ();
1104 breakpoints_cleanup ();
1108 mono_mutex_destroy (&debugger_thread_exited_mutex);
1109 mono_cond_destroy (&debugger_thread_exited_cond);
1116 #ifndef DISABLE_SOCKET_TRANSPORT
1121 * recv() + handle incomplete reads and EINTR
1124 socket_transport_recv (void *buf, int len)
1130 static gint32 last_keepalive;
1135 res = recv (fd, (char *) buf + total, len - total, flags);
1138 if (agent_config.keepalive) {
1139 gboolean need_keepalive = FALSE;
1140 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1141 need_keepalive = TRUE;
1142 } else if (res == -1) {
1143 /* This could happen if recv () is interrupted repeatedly */
1144 msecs = mono_msec_ticks ();
1145 if (msecs - last_keepalive >= agent_config.keepalive) {
1146 need_keepalive = TRUE;
1147 last_keepalive = msecs;
1150 if (need_keepalive) {
1151 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1155 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1160 set_keepalive (void)
1165 if (!agent_config.keepalive || !conn_fd)
1168 tv.tv_sec = agent_config.keepalive / 1000;
1169 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1171 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1172 g_assert (result >= 0);
1176 socket_transport_accept (int socket_fd)
1178 conn_fd = accept (socket_fd, NULL, NULL);
1179 if (conn_fd == -1) {
1180 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1182 DEBUG_PRINTF (1, "Accepted connection from client, connection fd=%d.\n", conn_fd);
1189 socket_transport_send (void *data, int len)
1194 res = send (conn_fd, data, len, 0);
1195 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1203 * socket_transport_connect:
1205 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1208 socket_transport_connect (const char *address)
1210 MonoAddressInfo *result;
1211 MonoAddressEntry *rp;
1212 int sfd = -1, s, res;
1216 if (agent_config.address) {
1217 res = parse_address (agent_config.address, &host, &port);
1218 g_assert (res == 0);
1229 mono_network_init ();
1231 /* Obtain address(es) matching host/port */
1232 s = mono_get_address_info (host, port, MONO_HINT_UNSPECIFIED, &result);
1234 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, s); // FIXME add portable error conversion functions
1239 if (agent_config.server) {
1240 /* Wait for a connection */
1242 struct sockaddr_in addr;
1245 /* No address, generate one */
1246 sfd = socket (AF_INET, SOCK_STREAM, 0);
1249 /* This will bind the socket to a random port */
1250 res = listen (sfd, 16);
1252 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1257 addrlen = sizeof (addr);
1258 memset (&addr, 0, sizeof (addr));
1259 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1260 g_assert (res == 0);
1262 host = (char*)"127.0.0.1";
1263 port = ntohs (addr.sin_port);
1265 /* Emit the address to stdout */
1266 /* FIXME: Should print another interface, not localhost */
1267 printf ("%s:%d\n", host, port);
1269 /* Listen on the provided address */
1270 for (rp = result->entries; rp != NULL; rp = rp->next) {
1271 MonoSocketAddress sockaddr;
1275 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1277 sfd = socket (rp->family, rp->socktype,
1282 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1285 res = bind (sfd, &sockaddr.addr, sock_len);
1289 res = listen (sfd, 16);
1296 mono_free_address_info (result);
1299 if (agent_config.defer)
1302 DEBUG_PRINTF (1, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout);
1304 if (agent_config.timeout) {
1309 tv.tv_usec = agent_config.timeout * 1000;
1311 FD_SET (sfd, &readfds);
1312 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1314 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1319 MONO_PREPARE_BLOCKING;
1320 conn_fd = socket_transport_accept (sfd);
1321 MONO_FINISH_BLOCKING;
1325 DEBUG_PRINTF (1, "Accepted connection from client, socket fd=%d.\n", conn_fd);
1327 /* Connect to the specified address */
1328 /* FIXME: Respect the timeout */
1329 for (rp = result->entries; rp != NULL; rp = rp->next) {
1330 MonoSocketAddress sockaddr;
1333 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1335 sfd = socket (rp->family, rp->socktype,
1340 if (connect (sfd, &sockaddr.addr, sock_len) != -1)
1341 break; /* Success */
1347 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1353 mono_free_address_info (result);
1356 if (!transport_handshake ())
1361 socket_transport_close1 (void)
1363 /* This will interrupt the agent thread */
1364 /* Close the read part only so it can still send back replies */
1365 /* Also shut down the connection listener so that we can exit normally */
1367 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1368 shutdown (conn_fd, SD_BOTH);
1369 shutdown (listen_fd, SD_BOTH);
1370 closesocket (listen_fd);
1372 shutdown (conn_fd, SHUT_RD);
1373 shutdown (listen_fd, SHUT_RDWR);
1379 socket_transport_close2 (void)
1382 shutdown (conn_fd, SD_BOTH);
1384 shutdown (conn_fd, SHUT_RDWR);
1389 register_socket_transport (void)
1391 DebuggerTransport trans;
1393 trans.name = "dt_socket";
1394 trans.connect = socket_transport_connect;
1395 trans.close1 = socket_transport_close1;
1396 trans.close2 = socket_transport_close2;
1397 trans.send = socket_transport_send;
1398 trans.recv = socket_transport_recv;
1400 register_transport (&trans);
1404 * socket_fd_transport_connect:
1408 socket_fd_transport_connect (const char *address)
1412 res = sscanf (address, "%d", &conn_fd);
1414 fprintf (stderr, "debugger-agent: socket-fd transport address is invalid: '%s'\n", address);
1418 if (!transport_handshake ())
1423 register_socket_fd_transport (void)
1425 DebuggerTransport trans;
1427 /* This is the same as the 'dt_socket' transport, but receives an already connected socket fd */
1428 trans.name = "socket-fd";
1429 trans.connect = socket_fd_transport_connect;
1430 trans.close1 = socket_transport_close1;
1431 trans.close2 = socket_transport_close2;
1432 trans.send = socket_transport_send;
1433 trans.recv = socket_transport_recv;
1435 register_transport (&trans);
1438 #endif /* DISABLE_SOCKET_TRANSPORT */
1444 #define MAX_TRANSPORTS 16
1446 static DebuggerTransport *transport;
1448 static DebuggerTransport transports [MAX_TRANSPORTS];
1449 static int ntransports;
1452 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1455 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1457 register_transport (trans);
1461 register_transport (DebuggerTransport *trans)
1463 g_assert (ntransports < MAX_TRANSPORTS);
1465 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1470 transport_init (void)
1474 #ifndef DISABLE_SOCKET_TRANSPORT
1475 register_socket_transport ();
1476 register_socket_fd_transport ();
1479 for (i = 0; i < ntransports; ++i) {
1480 if (!strcmp (agent_config.transport, transports [i].name))
1483 if (i == ntransports) {
1484 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1485 for (i = 0; i < ntransports; ++i)
1486 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1487 fprintf (stderr, "\n");
1490 transport = &transports [i];
1494 transport_connect (const char *address)
1496 transport->connect (address);
1500 transport_close1 (void)
1502 transport->close1 ();
1506 transport_close2 (void)
1508 transport->close2 ();
1512 transport_send (void *buf, int len)
1514 return transport->send (buf, len);
1518 transport_recv (void *buf, int len)
1520 return transport->recv (buf, len);
1524 mono_debugger_agent_transport_handshake (void)
1526 return transport_handshake ();
1530 transport_handshake (void)
1532 char handshake_msg [128];
1536 disconnected = TRUE;
1538 /* Write handshake message */
1539 sprintf (handshake_msg, "DWP-Handshake");
1540 /* Must use try blocking as this can nest into code that runs blocking */
1543 res = transport_send (handshake_msg, strlen (handshake_msg));
1544 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1545 MONO_FINISH_TRY_BLOCKING;
1547 g_assert (res != -1);
1551 res = transport_recv (buf, strlen (handshake_msg));
1552 MONO_FINISH_TRY_BLOCKING;
1553 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg)) != 0)) {
1554 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1559 * To support older clients, the client sends its protocol version after connecting
1560 * using a command. Until that is received, default to our protocol version.
1562 major_version = MAJOR_VERSION;
1563 minor_version = MINOR_VERSION;
1564 protocol_version_set = FALSE;
1566 #ifndef DISABLE_SOCKET_TRANSPORT
1567 // FIXME: Move this somewhere else
1569 * Set TCP_NODELAY on the socket so the client receives events/command
1570 * results immediately.
1574 int result = setsockopt (conn_fd,
1579 g_assert (result >= 0);
1585 disconnected = FALSE;
1590 stop_debugger_thread (void)
1595 MONO_PREPARE_BLOCKING;
1596 transport_close1 ();
1597 MONO_FINISH_BLOCKING;
1600 * Wait for the thread to exit.
1602 * If we continue with the shutdown without waiting for it, then the client might
1603 * not receive an answer to its last command like a resume.
1605 if (!is_debugger_thread ()) {
1608 mono_mutex_lock (&debugger_thread_exited_mutex);
1609 if (!debugger_thread_exited)
1610 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1611 mono_mutex_unlock (&debugger_thread_exited_mutex);
1612 MONO_FINISH_TRY_BLOCKING;
1613 } while (!debugger_thread_exited);
1616 MONO_PREPARE_BLOCKING;
1617 transport_close2 ();
1618 MONO_FINISH_BLOCKING;
1622 start_debugger_thread (void)
1624 debugger_thread_handle = mono_threads_create_thread (debugger_thread, NULL, 0, 0, NULL);
1625 g_assert (debugger_thread_handle);
1629 * Functions to decode protocol data
1633 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1636 g_assert (*endbuf <= limit);
1641 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1644 g_assert (*endbuf <= limit);
1646 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1649 static inline gint64
1650 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1652 guint32 high = decode_int (buf, &buf, limit);
1653 guint32 low = decode_int (buf, &buf, limit);
1657 return ((((guint64)high) << 32) | ((guint64)low));
1661 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1663 return decode_int (buf, endbuf, limit);
1667 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1669 int len = decode_int (buf, &buf, limit);
1677 s = g_malloc (len + 1);
1680 memcpy (s, buf, len);
1689 * Functions to encode protocol data
1693 buffer_init (Buffer *buf, int size)
1695 buf->buf = g_malloc (size);
1697 buf->end = buf->buf + size;
1701 buffer_len (Buffer *buf)
1703 return buf->p - buf->buf;
1707 buffer_make_room (Buffer *buf, int size)
1709 if (buf->end - buf->p < size) {
1710 int new_size = buf->end - buf->buf + size + 32;
1711 guint8 *p = g_realloc (buf->buf, new_size);
1712 size = buf->p - buf->buf;
1715 buf->end = buf->buf + new_size;
1720 buffer_add_byte (Buffer *buf, guint8 val)
1722 buffer_make_room (buf, 1);
1728 buffer_add_short (Buffer *buf, guint32 val)
1730 buffer_make_room (buf, 2);
1731 buf->p [0] = (val >> 8) & 0xff;
1732 buf->p [1] = (val >> 0) & 0xff;
1737 buffer_add_int (Buffer *buf, guint32 val)
1739 buffer_make_room (buf, 4);
1740 buf->p [0] = (val >> 24) & 0xff;
1741 buf->p [1] = (val >> 16) & 0xff;
1742 buf->p [2] = (val >> 8) & 0xff;
1743 buf->p [3] = (val >> 0) & 0xff;
1748 buffer_add_long (Buffer *buf, guint64 l)
1750 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1751 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1755 buffer_add_id (Buffer *buf, int id)
1757 buffer_add_int (buf, (guint64)id);
1761 buffer_add_data (Buffer *buf, guint8 *data, int len)
1763 buffer_make_room (buf, len);
1764 memcpy (buf->p, data, len);
1769 buffer_add_string (Buffer *buf, const char *str)
1774 buffer_add_int (buf, 0);
1777 buffer_add_int (buf, len);
1778 buffer_add_data (buf, (guint8*)str, len);
1783 buffer_add_buffer (Buffer *buf, Buffer *data)
1785 buffer_add_data (buf, data->buf, buffer_len (data));
1789 buffer_free (Buffer *buf)
1795 send_packet (int command_set, int command, Buffer *data)
1801 id = InterlockedIncrement (&packet_id);
1803 len = data->p - data->buf + 11;
1804 buffer_init (&buf, len);
1805 buffer_add_int (&buf, len);
1806 buffer_add_int (&buf, id);
1807 buffer_add_byte (&buf, 0); /* flags */
1808 buffer_add_byte (&buf, command_set);
1809 buffer_add_byte (&buf, command);
1810 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1812 MONO_PREPARE_BLOCKING;
1813 res = transport_send (buf.buf, len);
1814 MONO_FINISH_BLOCKING;
1822 send_reply_packets (int npackets, ReplyPacket *packets)
1829 for (i = 0; i < npackets; ++i)
1830 len += buffer_len (packets [i].data) + 11;
1831 buffer_init (&buf, len);
1832 for (i = 0; i < npackets; ++i) {
1833 buffer_add_int (&buf, buffer_len (packets [i].data) + 11);
1834 buffer_add_int (&buf, packets [i].id);
1835 buffer_add_byte (&buf, 0x80); /* flags */
1836 buffer_add_byte (&buf, (packets [i].error >> 8) & 0xff);
1837 buffer_add_byte (&buf, packets [i].error);
1838 buffer_add_buffer (&buf, packets [i].data);
1841 MONO_PREPARE_BLOCKING;
1842 res = transport_send (buf.buf, len);
1843 MONO_FINISH_BLOCKING;
1851 send_reply_packet (int id, int error, Buffer *data)
1855 memset (&packet, 0, sizeof (ReplyPacket));
1857 packet.error = error;
1860 return send_reply_packets (1, &packet);
1864 send_buffered_reply_packets (void)
1868 send_reply_packets (nreply_packets, reply_packets);
1869 for (i = 0; i < nreply_packets; ++i)
1870 buffer_free (reply_packets [i].data);
1871 DEBUG_PRINTF (1, "[dbg] Sent %d buffered reply packets [at=%lx].\n", nreply_packets, (long)mono_100ns_ticks () / 10000);
1876 buffer_reply_packet (int id, int error, Buffer *data)
1880 if (nreply_packets == 128)
1881 send_buffered_reply_packets ();
1883 p = &reply_packets [nreply_packets];
1886 p->data = g_new0 (Buffer, 1);
1887 buffer_init (p->data, buffer_len (data));
1888 buffer_add_buffer (p->data, data);
1897 * Represents an object accessible by the debugger client.
1900 /* Unique id used in the wire protocol to refer to objects */
1903 * A weakref gc handle pointing to the object. The gc handle is used to
1904 * detect if the object was garbage collected.
1909 /* Maps objid -> ObjRef */
1910 /* Protected by the loader lock */
1911 static GHashTable *objrefs;
1912 /* Protected by the loader lock */
1913 static GHashTable *obj_to_objref;
1914 /* Protected by the dbg lock */
1915 static MonoGHashTable *suspended_objs;
1918 free_objref (gpointer value)
1922 mono_gchandle_free (o->handle);
1930 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1931 obj_to_objref = g_hash_table_new (NULL, NULL);
1932 suspended_objs = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_DEBUGGER, "suspended objects table");
1933 MONO_GC_REGISTER_ROOT_FIXED (suspended_objs, MONO_ROOT_SOURCE_DEBUGGER, "suspended objects table");
1937 objrefs_cleanup (void)
1939 g_hash_table_destroy (objrefs);
1944 * Return an ObjRef for OBJ.
1947 get_objref (MonoObject *obj)
1950 GSList *reflist = NULL, *l;
1956 if (suspend_count) {
1958 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1961 mono_g_hash_table_insert (suspended_objs, obj, NULL);
1965 mono_loader_lock ();
1967 /* FIXME: The tables can grow indefinitely */
1969 if (mono_gc_is_moving ()) {
1971 * Objects can move, so use a hash table mapping hash codes to lists of
1972 * ObjRef structures.
1974 hash = mono_object_hash (obj);
1976 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1977 for (l = reflist; l; l = l->next) {
1979 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1980 mono_loader_unlock ();
1985 /* Use a hash table with masked pointers to internalize object references */
1986 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1987 /* ref might refer to a different object with the same addr which was GCd */
1988 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1989 mono_loader_unlock ();
1994 ref = g_new0 (ObjRef, 1);
1995 ref->id = InterlockedIncrement (&objref_id);
1996 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1998 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
2000 if (mono_gc_is_moving ()) {
2001 reflist = g_slist_append (reflist, ref);
2002 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
2004 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
2007 mono_loader_unlock ();
2013 true_pred (gpointer key, gpointer value, gpointer user_data)
2019 clear_suspended_objs (void)
2022 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
2027 get_objid (MonoObject *obj)
2029 return get_objref (obj)->id;
2033 * Set OBJ to the object identified by OBJID.
2034 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
2038 get_object_allow_null (int objid, MonoObject **obj)
2048 return ERR_INVALID_OBJECT;
2050 mono_loader_lock ();
2052 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
2055 *obj = mono_gchandle_get_target (ref->handle);
2056 mono_loader_unlock ();
2058 return ERR_INVALID_OBJECT;
2061 mono_loader_unlock ();
2062 return ERR_INVALID_OBJECT;
2067 get_object (int objid, MonoObject **obj)
2069 int err = get_object_allow_null (objid, obj);
2074 return ERR_INVALID_OBJECT;
2079 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
2081 return decode_id (buf, endbuf, limit);
2085 buffer_add_objid (Buffer *buf, MonoObject *o)
2087 buffer_add_id (buf, get_objid (o));
2106 * Represents a runtime structure accessible to the debugger client
2109 /* Unique id used in the wire protocol */
2111 /* Domain of the runtime structure, NULL if the domain was unloaded */
2118 MonoAssembly *assembly;
2119 MonoClassField *field;
2121 MonoProperty *property;
2126 /* Maps runtime structure -> Id */
2127 /* Protected by the dbg lock */
2128 GHashTable *val_to_id [ID_NUM];
2129 /* Classes whose class load event has been sent */
2130 /* Protected by the loader lock */
2131 GHashTable *loaded_classes;
2132 /* Maps MonoClass->GPtrArray of file names */
2133 GHashTable *source_files;
2134 /* Maps source file basename -> GSList of classes */
2135 GHashTable *source_file_to_class;
2136 /* Same with ignore-case */
2137 GHashTable *source_file_to_class_ignorecase;
2141 /* Protected by the dbg lock */
2142 static GPtrArray *ids [ID_NUM];
2149 for (i = 0; i < ID_NUM; ++i)
2150 ids [i] = g_ptr_array_new ();
2158 for (i = 0; i < ID_NUM; ++i) {
2160 for (j = 0; j < ids [i]->len; ++j)
2161 g_free (g_ptr_array_index (ids [i], j));
2162 g_ptr_array_free (ids [i], TRUE);
2169 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2171 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
2173 GHashTableIter iter;
2174 GPtrArray *file_names;
2179 for (i = 0; i < ID_NUM; ++i)
2180 if (info->val_to_id [i])
2181 g_hash_table_destroy (info->val_to_id [i]);
2182 g_hash_table_destroy (info->loaded_classes);
2184 g_hash_table_iter_init (&iter, info->source_files);
2185 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2186 for (i = 0; i < file_names->len; ++i)
2187 g_free (g_ptr_array_index (file_names, i));
2188 g_ptr_array_free (file_names, TRUE);
2191 g_hash_table_iter_init (&iter, info->source_file_to_class);
2192 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2197 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2198 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2206 domain_jit_info (domain)->agent_info = NULL;
2208 /* Clear ids referencing structures in the domain */
2210 for (i = 0; i < ID_NUM; ++i) {
2212 for (j = 0; j < ids [i]->len; ++j) {
2213 Id *id = g_ptr_array_index (ids [i], j);
2214 if (id->domain == domain)
2221 mono_loader_lock ();
2222 g_hash_table_remove (domains, domain);
2223 mono_loader_unlock ();
2226 static AgentDomainInfo*
2227 get_agent_domain_info (MonoDomain *domain)
2229 AgentDomainInfo *info = NULL;
2231 mono_domain_lock (domain);
2233 info = domain_jit_info (domain)->agent_info;
2235 info = domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
2236 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2237 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2238 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2239 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2242 mono_domain_unlock (domain);
2248 get_id (MonoDomain *domain, IdType type, gpointer val)
2251 AgentDomainInfo *info;
2256 info = get_agent_domain_info (domain);
2260 if (info->val_to_id [type] == NULL)
2261 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2263 id = g_hash_table_lookup (info->val_to_id [type], val);
2269 id = g_new0 (Id, 1);
2271 id->id = ids [type]->len + 1;
2272 id->domain = domain;
2275 g_hash_table_insert (info->val_to_id [type], val, id);
2276 g_ptr_array_add (ids [type], id);
2283 static inline gpointer
2284 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
2288 int id = decode_id (buf, endbuf, limit);
2297 // FIXME: error handling
2299 g_assert (id > 0 && id <= ids [type]->len);
2301 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2304 if (res->domain == NULL) {
2305 DEBUG_PRINTF (1, "ERR_UNLOADED, id=%d, type=%d.\n", id, type);
2306 *err = ERR_UNLOADED;
2311 *domain = res->domain;
2313 return res->data.val;
2317 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2319 int id = get_id (domain, type, val);
2321 buffer_add_id (buf, id);
2325 static inline MonoClass*
2326 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2330 klass = decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2331 if (G_UNLIKELY (log_level >= 2) && klass) {
2334 s = mono_type_full_name (&klass->byval_arg);
2335 DEBUG_PRINTF (2, "[dbg] recv class [%s]\n", s);
2341 static inline MonoAssembly*
2342 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2344 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2347 static inline MonoImage*
2348 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2350 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2353 static inline MonoMethod*
2354 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2358 m = decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2359 if (G_UNLIKELY (log_level >= 2) && m) {
2362 s = mono_method_full_name (m, TRUE);
2363 DEBUG_PRINTF (2, "[dbg] recv method [%s]\n", s);
2369 static inline MonoClassField*
2370 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2372 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2375 static inline MonoDomain*
2376 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2378 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2381 static inline MonoProperty*
2382 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2384 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2388 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2390 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2391 if (G_UNLIKELY (log_level >= 2) && klass) {
2394 s = mono_type_full_name (&klass->byval_arg);
2395 if (is_debugger_thread ())
2396 DEBUG_PRINTF (2, "[dbg] send class [%s]\n", s);
2398 DEBUG_PRINTF (2, "[%p] send class [%s]\n", (gpointer)mono_native_thread_id_get (), s);
2404 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2406 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2407 if (G_UNLIKELY (log_level >= 2) && method) {
2410 s = mono_method_full_name (method, 1);
2411 DEBUG_PRINTF (2, "[dbg] send method [%s]\n", s);
2417 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2421 id = buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2422 if (G_UNLIKELY (log_level >= 2) && assembly)
2423 DEBUG_PRINTF (2, "[dbg] send assembly [%s][%s][%d]\n", assembly->aname.name, domain->friendly_name, id);
2427 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2429 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2433 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2435 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2439 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2441 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2445 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2447 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2450 static void invoke_method (void);
2457 * save_thread_context:
2459 * Set CTX as the current threads context which is used for computing stack traces.
2460 * This function is signal-safe.
2463 save_thread_context (MonoContext *ctx)
2465 DebuggerTlsData *tls;
2467 tls = mono_native_tls_get_value (debugger_tls_id);
2471 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2473 mono_thread_state_init_from_current (&tls->context);
2476 /* Number of threads suspended */
2478 * If this is equal to the size of thread_to_tls, the runtime is considered
2481 static gint32 threads_suspend_count;
2483 static mono_mutex_t suspend_mutex;
2485 /* Cond variable used to wait for suspend_count becoming 0 */
2486 static mono_cond_t suspend_cond;
2488 /* Semaphore used to wait for a thread becoming suspended */
2489 static MonoSemType suspend_sem;
2494 mono_mutex_init (&suspend_mutex);
2495 mono_cond_init (&suspend_cond, 0);
2496 MONO_SEM_INIT (&suspend_sem, 0);
2501 StackFrameInfo last_frame;
2502 gboolean last_frame_set;
2506 } GetLastFrameUserData;
2509 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2511 GetLastFrameUserData *data = user_data;
2513 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE || info->type == FRAME_TYPE_TRAMPOLINE)
2516 if (!data->last_frame_set) {
2517 /* Store the last frame */
2518 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2519 data->last_frame_set = TRUE;
2522 /* Store the context/lmf for the frame above the last frame */
2523 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2524 data->lmf = info->lmf;
2525 data->domain = info->domain;
2531 copy_unwind_state_from_frame_data (MonoThreadUnwindState *to, GetLastFrameUserData *data, gpointer jit_tls)
2533 memcpy (&to->ctx, &data->ctx, sizeof (MonoContext));
2535 to->unwind_data [MONO_UNWIND_DATA_DOMAIN] = data->domain;
2536 to->unwind_data [MONO_UNWIND_DATA_LMF] = data->lmf;
2537 to->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = jit_tls;
2544 * Process interruption of a thread. This should be signal safe.
2546 * This always runs in the debugger thread.
2549 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, MonoJitInfo *ji)
2552 MonoNativeThreadId tid;
2556 ip = MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx);
2557 tid = mono_thread_info_get_tid (info);
2559 // FIXME: Races when the thread leaves managed code before hitting a single step
2562 if (ji && !ji->is_trampoline) {
2563 /* Running managed code, will be suspended by the single step code */
2564 DEBUG_PRINTF (1, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip);
2567 * Running native code, will be suspended when it returns to/enters
2568 * managed code. Treat it as already suspended.
2569 * This might interrupt the code in process_single_step_inner (), we use the
2570 * tls->suspending flag to avoid races when that happens.
2572 if (!tls->suspended && !tls->suspending) {
2573 GetLastFrameUserData data;
2575 // FIXME: printf is not signal safe, but this is only used during
2576 // debugger debugging
2578 DEBUG_PRINTF (1, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip);
2579 //save_thread_context (&ctx);
2582 /* Already terminated */
2586 * We are in a difficult position: we want to be able to provide stack
2587 * traces for this thread, but we can't use the current ctx+lmf, since
2588 * the thread is still running, so it might return to managed code,
2589 * making these invalid.
2590 * So we start a stack walk and save the first frame, along with the
2591 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2592 * suspended when it returns to managed code, so the parent's ctx should
2595 data.last_frame_set = FALSE;
2596 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, mono_thread_info_get_suspend_state (info), MONO_UNWIND_SIGNAL_SAFE, &data);
2597 if (data.last_frame_set) {
2598 gpointer jit_tls = ((MonoThreadInfo*)tls->thread->thread_info)->jit_data;
2600 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2602 copy_unwind_state_from_frame_data (&tls->async_state, &data, jit_tls);
2603 copy_unwind_state_from_frame_data (&tls->context, &data, jit_tls);
2605 tls->async_state.valid = FALSE;
2608 mono_memory_barrier ();
2610 tls->suspended = TRUE;
2611 MONO_SEM_POST (&suspend_sem);
2617 * reset_native_thread_suspend_state:
2619 * Reset the suspended flag and state on native threads
2622 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2624 DebuggerTlsData *tls = value;
2626 if (!tls->really_suspended && tls->suspended) {
2627 tls->suspended = FALSE;
2629 * The thread might still be running if it was executing native code, so the state won't be invalided by
2630 * suspend_current ().
2632 tls->context.valid = FALSE;
2633 tls->async_state.valid = FALSE;
2634 invalidate_frames (tls);
2639 DebuggerTlsData *tls;
2640 gboolean valid_info;
2643 static SuspendThreadResult
2644 debugger_interrupt_critical (MonoThreadInfo *info, gpointer user_data)
2646 InterruptData *data = user_data;
2649 data->valid_info = TRUE;
2650 ji = mono_jit_info_table_find_internal (
2651 mono_thread_info_get_suspend_state (info)->unwind_data [MONO_UNWIND_DATA_DOMAIN],
2652 MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx),
2656 /* This is signal safe */
2657 thread_interrupt (data->tls, info, ji);
2658 return MonoResumeThread;
2664 * Notify a thread that it needs to suspend.
2667 notify_thread (gpointer key, gpointer value, gpointer user_data)
2669 MonoInternalThread *thread = key;
2670 DebuggerTlsData *tls = value;
2671 MonoNativeThreadId tid = MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid);
2673 if (mono_native_thread_id_equals (mono_native_thread_id_get (), tid) || tls->terminated)
2676 DEBUG_PRINTF (1, "[%p] Interrupting %p...\n", (gpointer)mono_native_thread_id_get (), (gpointer)tid);
2678 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2679 InterruptData interrupt_data = { 0 };
2680 interrupt_data.tls = tls;
2682 mono_thread_info_safe_suspend_and_run ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE, debugger_interrupt_critical, &interrupt_data);
2683 if (!interrupt_data.valid_info) {
2684 DEBUG_PRINTF (1, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer)mono_native_thread_id_get (), (gpointer)tid);
2686 * Attached thread which died without detaching.
2688 tls->terminated = TRUE;
2693 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2695 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2699 if (mono_loader_lock_is_owned_by_self ()) {
2701 * Shortcut for the check in suspend_current (). This speeds up processing
2702 * when executing long running code inside the loader lock, i.e. assembly load
2708 if (is_debugger_thread ())
2711 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2712 if (suspend_count - tls->resume_count > 0)
2713 tls->suspending = TRUE;
2715 DEBUG_PRINTF (1, "[%p] Received single step event for suspending.\n", (gpointer)mono_native_thread_id_get ());
2717 if (suspend_count - tls->resume_count == 0) {
2719 * We are executing a single threaded invoke but the single step for
2720 * suspending is still active.
2721 * FIXME: This slows down single threaded invokes.
2723 DEBUG_PRINTF (1, "[%p] Ignored during single threaded invoke.\n", (gpointer)mono_native_thread_id_get ());
2727 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2729 /* Can't suspend in these methods */
2730 method = jinfo_get_method (ji);
2731 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2734 save_thread_context (ctx);
2742 * Increase the suspend count of the VM. While the suspend count is greater
2743 * than 0, runtime threads are suspended at certain points during execution.
2748 mono_loader_lock ();
2751 mono_mutex_lock (&suspend_mutex);
2752 MONO_FINISH_TRY_BLOCKING;
2756 DEBUG_PRINTF (1, "[%p] Suspending vm...\n", (gpointer)mono_native_thread_id_get ());
2758 if (suspend_count == 1) {
2759 // FIXME: Is it safe to call this inside the lock ?
2760 start_single_stepping ();
2761 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2764 mono_mutex_unlock (&suspend_mutex);
2766 if (suspend_count == 1)
2768 * Suspend creation of new threadpool threads, since they cannot run
2770 mono_threadpool_ms_suspend ();
2772 mono_loader_unlock ();
2778 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2786 g_assert (is_debugger_thread ());
2788 mono_loader_lock ();
2791 mono_mutex_lock (&suspend_mutex);
2792 MONO_FINISH_TRY_BLOCKING;
2794 g_assert (suspend_count > 0);
2797 DEBUG_PRINTF (1, "[%p] Resuming vm, suspend count=%d...\n", (gpointer)mono_native_thread_id_get (), suspend_count);
2799 if (suspend_count == 0) {
2800 // FIXME: Is it safe to call this inside the lock ?
2801 stop_single_stepping ();
2802 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2805 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2806 err = mono_cond_broadcast (&suspend_cond);
2807 g_assert (err == 0);
2809 mono_mutex_unlock (&suspend_mutex);
2810 //g_assert (err == 0);
2812 if (suspend_count == 0)
2813 mono_threadpool_ms_resume ();
2815 mono_loader_unlock ();
2821 * Resume just one thread.
2824 resume_thread (MonoInternalThread *thread)
2827 DebuggerTlsData *tls;
2829 g_assert (is_debugger_thread ());
2831 mono_loader_lock ();
2833 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2837 mono_mutex_lock (&suspend_mutex);
2838 MONO_FINISH_TRY_BLOCKING;
2840 g_assert (suspend_count > 0);
2842 DEBUG_PRINTF (1, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid);
2844 tls->resume_count += suspend_count;
2847 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2848 * but only the one whose resume_count field is > 0 will be resumed.
2850 err = mono_cond_broadcast (&suspend_cond);
2851 g_assert (err == 0);
2853 mono_mutex_unlock (&suspend_mutex);
2854 //g_assert (err == 0);
2856 mono_loader_unlock ();
2860 free_frames (StackFrame **frames, int nframes)
2864 for (i = 0; i < nframes; ++i) {
2865 if (frames [i]->jit)
2866 mono_debug_free_method_jit_info (frames [i]->jit);
2867 g_free (frames [i]);
2873 invalidate_frames (DebuggerTlsData *tls)
2876 tls = mono_native_tls_get_value (debugger_tls_id);
2879 free_frames (tls->frames, tls->frame_count);
2880 tls->frame_count = 0;
2883 free_frames (tls->restore_frames, tls->restore_frame_count);
2884 tls->restore_frame_count = 0;
2885 tls->restore_frames = NULL;
2891 * Suspend the current thread until the runtime is resumed. If the thread has a
2892 * pending invoke, then the invoke is executed before this function returns.
2895 suspend_current (void)
2897 DebuggerTlsData *tls;
2900 g_assert (!is_debugger_thread ());
2902 if (mono_loader_lock_is_owned_by_self ()) {
2904 * If we own the loader mutex, can't suspend until we release it, since the
2905 * whole runtime can deadlock otherwise.
2910 tls = mono_native_tls_get_value (debugger_tls_id);
2914 mono_mutex_lock (&suspend_mutex);
2915 MONO_FINISH_TRY_BLOCKING;
2917 tls->suspending = FALSE;
2918 tls->really_suspended = TRUE;
2920 if (!tls->suspended) {
2921 tls->suspended = TRUE;
2922 MONO_SEM_POST (&suspend_sem);
2925 DEBUG_PRINTF (1, "[%p] Suspended.\n", (gpointer)mono_native_thread_id_get ());
2928 while (suspend_count - tls->resume_count > 0) {
2929 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
2930 g_assert (err == 0);
2932 MONO_FINISH_TRY_BLOCKING;
2934 tls->suspended = FALSE;
2935 tls->really_suspended = FALSE;
2937 threads_suspend_count --;
2939 mono_mutex_unlock (&suspend_mutex);
2941 DEBUG_PRINTF (1, "[%p] Resumed.\n", (gpointer)mono_native_thread_id_get ());
2943 if (tls->pending_invoke) {
2944 /* Save the original context */
2945 tls->pending_invoke->has_ctx = TRUE;
2946 tls->pending_invoke->ctx = tls->context.ctx;
2951 /* The frame info becomes invalid after a resume */
2952 tls->context.valid = FALSE;
2953 tls->async_state.valid = FALSE;
2954 invalidate_frames (tls);
2958 count_thread (gpointer key, gpointer value, gpointer user_data)
2960 DebuggerTlsData *tls = value;
2962 if (!tls->suspended && !tls->terminated)
2963 *(int*)user_data = *(int*)user_data + 1;
2967 count_threads_to_wait_for (void)
2971 mono_loader_lock ();
2972 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2973 mono_loader_unlock ();
2981 * Wait until the runtime is completely suspended.
2984 wait_for_suspend (void)
2986 int nthreads, nwait, err;
2987 gboolean waited = FALSE;
2989 // FIXME: Threads starting/stopping ?
2990 mono_loader_lock ();
2991 nthreads = mono_g_hash_table_size (thread_to_tls);
2992 mono_loader_unlock ();
2995 nwait = count_threads_to_wait_for ();
2997 DEBUG_PRINTF (1, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads);
2998 err = MONO_SEM_WAIT (&suspend_sem);
2999 g_assert (err == 0);
3007 DEBUG_PRINTF (1, "%d threads suspended.\n", nthreads);
3013 * Return whenever the runtime is suspended.
3018 return count_threads_to_wait_for () == 0;
3022 no_seq_points_found (MonoMethod *method, int offset)
3025 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3027 printf ("Unable to find seq points for method '%s', offset 0x%x.\n", mono_method_full_name (method, TRUE), offset);
3031 DebuggerTlsData *tls;
3033 } ComputeFramesUserData;
3036 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3038 ComputeFramesUserData *ud = user_data;
3040 MonoMethod *method, *actual_method, *api_method;
3044 if (info->type != FRAME_TYPE_MANAGED) {
3045 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3046 /* Mark the last frame as an invoke frame */
3048 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3054 method = jinfo_get_method (info->ji);
3056 method = info->method;
3057 actual_method = info->actual_method;
3058 api_method = method;
3063 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3066 if (info->il_offset == -1) {
3067 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3068 if (ud->frames == NULL) {
3069 if (mono_find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL, &sp))
3070 info->il_offset = sp.il_offset;
3072 if (info->il_offset == -1)
3073 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3076 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);
3078 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3079 if (!CHECK_PROTOCOL_VERSION (2, 17))
3080 /* Older clients can't handle this flag */
3082 api_method = mono_marshal_method_from_wrapper (method);
3085 actual_method = api_method;
3086 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3089 frame = g_new0 (StackFrame, 1);
3090 frame->method = method;
3091 frame->actual_method = actual_method;
3092 frame->api_method = api_method;
3093 frame->il_offset = info->il_offset;
3094 frame->native_offset = info->native_offset;
3095 frame->flags = flags;
3096 frame->ji = info->ji;
3097 if (info->reg_locations)
3098 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3101 frame->has_ctx = TRUE;
3103 frame->domain = info->domain;
3105 ud->frames = g_slist_append (ud->frames, frame);
3111 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3113 ComputeFramesUserData *ud = user_data;
3116 * 'tls->filter_ctx' is the location of the throw site.
3118 * mono_walk_stack() will never actually hit the throw site, but unwind
3119 * directly from the filter to the call site; we abort stack unwinding here
3120 * once this happens and resume from the throw site.
3123 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3126 return process_frame (info, ctx, user_data);
3130 * Return a malloc-ed list of StackFrame structures.
3133 compute_frame_info_from (MonoInternalThread *thread, DebuggerTlsData *tls, MonoThreadUnwindState *state, int *out_nframes)
3135 ComputeFramesUserData user_data;
3136 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3141 user_data.tls = tls;
3142 user_data.frames = NULL;
3144 mono_walk_stack_with_state (process_frame, state, opts, &user_data);
3146 nframes = g_slist_length (user_data.frames);
3147 res = g_new0 (StackFrame*, nframes);
3148 l = user_data.frames;
3149 for (i = 0; i < nframes; ++i) {
3153 *out_nframes = nframes;
3159 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3161 ComputeFramesUserData user_data;
3163 int i, findex, new_frame_count;
3164 StackFrame **new_frames, *f;
3165 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3167 // FIXME: Locking on tls
3168 if (tls->frames && tls->frames_up_to_date)
3171 DEBUG_PRINTF (1, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid);
3173 user_data.tls = tls;
3174 user_data.frames = NULL;
3175 if (tls->terminated) {
3176 tls->frame_count = 0;
3178 } if (!tls->really_suspended && tls->async_state.valid) {
3179 /* Have to use the state saved by the signal handler */
3180 process_frame (&tls->async_last_frame, NULL, &user_data);
3181 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3182 } else if (tls->filter_state.valid) {
3184 * We are inside an exception filter.
3186 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3188 if (tls->context.valid)
3189 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3191 * After that, we resume unwinding from the location where the exception has been thrown.
3193 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3194 } else if (tls->context.valid) {
3195 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3198 tls->frame_count = 0;
3202 new_frame_count = g_slist_length (user_data.frames);
3203 new_frames = g_new0 (StackFrame*, new_frame_count);
3205 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3209 * Reuse the id for already existing stack frames, so invokes don't invalidate
3210 * the still valid stack frames.
3212 for (i = 0; i < tls->frame_count; ++i) {
3213 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3214 f->id = tls->frames [i]->id;
3219 if (i >= tls->frame_count)
3220 f->id = InterlockedIncrement (&frame_id);
3222 new_frames [findex ++] = f;
3225 g_slist_free (user_data.frames);
3227 invalidate_frames (tls);
3229 tls->frames = new_frames;
3230 tls->frame_count = new_frame_count;
3231 tls->frames_up_to_date = TRUE;
3235 * GHFunc to emit an appdomain creation event
3236 * @param key Don't care
3237 * @param value A loaded appdomain
3238 * @param user_data Don't care
3241 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3243 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3244 g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
3248 * GHFunc to emit a thread start event
3249 * @param key A thread id
3250 * @param value A thread object
3251 * @param user_data Don't care
3254 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3256 if (!mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (GPOINTER_TO_UINT (key)), debugger_thread_id))
3257 process_profiler_event (EVENT_KIND_THREAD_START, value);
3261 * GFunc to emit an assembly load event
3262 * @param value A loaded assembly
3263 * @param user_data Don't care
3266 emit_assembly_load (gpointer value, gpointer user_data)
3268 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3272 * GFunc to emit a type load event
3273 * @param value A loaded type
3274 * @param user_data Don't care
3277 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3279 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3283 strdup_tolower (char *s)
3288 for (p = s2; *p; ++p)
3294 * Same as g_path_get_basename () but handles windows paths as well,
3295 * which can occur in .mdb files created by pdb2mdb.
3298 dbg_path_get_basename (const char *filename)
3302 if (!filename || strchr (filename, '/') || !strchr (filename, '\\'))
3303 return g_path_get_basename (filename);
3307 /* No separator -> filename */
3308 r = strrchr (filename, '\\');
3310 return g_strdup (filename);
3312 /* Trailing slash, remove component */
3314 char *copy = g_strdup (filename);
3315 copy [r-filename] = 0;
3316 r = strrchr (copy, '\\');
3320 return g_strdup ("/");
3322 r = g_strdup (&r[1]);
3327 return g_strdup (&r[1]);
3331 init_jit_info_dbg_attrs (MonoJitInfo *ji)
3333 static MonoClass *hidden_klass, *step_through_klass, *non_user_klass;
3334 MonoCustomAttrInfo *ainfo;
3336 if (ji->dbg_attrs_inited)
3339 if (!hidden_klass) {
3340 hidden_klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3341 g_assert (hidden_klass);
3343 if (!step_through_klass) {
3344 step_through_klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3345 g_assert (step_through_klass);
3347 if (!non_user_klass) {
3348 non_user_klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute");
3349 g_assert (non_user_klass);
3352 ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji));
3354 if (mono_custom_attrs_has_attr (ainfo, hidden_klass))
3355 ji->dbg_hidden = TRUE;
3356 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3357 ji->dbg_step_through = TRUE;
3358 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3359 ji->dbg_non_user_code = TRUE;
3360 mono_custom_attrs_free (ainfo);
3363 ainfo = mono_custom_attrs_from_class (jinfo_get_method (ji)->klass);
3365 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3366 ji->dbg_step_through = TRUE;
3367 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3368 ji->dbg_non_user_code = TRUE;
3369 mono_custom_attrs_free (ainfo);
3372 mono_memory_barrier ();
3373 ji->dbg_attrs_inited = TRUE;
3381 * create_event_list:
3383 * Return a list of event request ids matching EVENT, starting from REQS, which
3384 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3386 * We return request ids, instead of requests, to simplify threading, since
3387 * requests could be deleted anytime when the loader lock is not held.
3388 * LOCKING: Assumes the loader lock is held.
3391 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3394 GSList *events = NULL;
3396 *suspend_policy = SUSPEND_POLICY_NONE;
3399 reqs = event_requests;
3404 for (i = 0; i < reqs->len; ++i) {
3405 EventRequest *req = g_ptr_array_index (reqs, i);
3406 if (req->event_kind == event) {
3407 gboolean filtered = FALSE;
3410 for (j = 0; j < req->nmodifiers; ++j) {
3411 Modifier *mod = &req->modifiers [j];
3413 if (mod->kind == MOD_KIND_COUNT) {
3415 if (mod->data.count > 0) {
3416 if (mod->data.count > 0) {
3418 if (mod->data.count == 0)
3422 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3423 if (mod->data.thread != mono_thread_internal_current ())
3425 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3426 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3428 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3430 if (ei->caught && !mod->caught)
3432 if (!ei->caught && !mod->uncaught)
3434 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3436 gboolean found = FALSE;
3437 MonoAssembly **assemblies = mod->data.assemblies;
3440 for (k = 0; assemblies [k]; ++k)
3441 if (assemblies [k] == jinfo_get_method (ji)->klass->image->assembly)
3446 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3447 gpointer iter = NULL;
3449 MonoDebugSourceInfo *sinfo;
3450 char *source_file, *s;
3451 gboolean found = FALSE;
3453 GPtrArray *source_file_list;
3455 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3456 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3459 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, NULL, NULL, NULL);
3460 for (i = 0; i < source_file_list->len; ++i) {
3461 sinfo = g_ptr_array_index (source_file_list, i);
3463 * Do a case-insesitive match by converting the file name to
3466 s = strdup_tolower (sinfo->source_file);
3467 if (g_hash_table_lookup (mod->data.source_files, s))
3470 char *s2 = dbg_path_get_basename (sinfo->source_file);
3471 char *s3 = strdup_tolower (s2);
3473 if (g_hash_table_lookup (mod->data.source_files, s3))
3480 g_ptr_array_free (source_file_list, TRUE);
3485 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3488 s = mono_type_full_name (&ei->klass->byval_arg);
3489 if (!g_hash_table_lookup (mod->data.type_names, s))
3492 } else if (mod->kind == MOD_KIND_STEP) {
3493 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3494 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3495 !strcmp (jinfo_get_method (ji)->name, ".cctor") &&
3496 (jinfo_get_method (ji) != ((SingleStepReq*)req->info)->start_method))
3498 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3499 init_jit_info_dbg_attrs (ji);
3503 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3504 init_jit_info_dbg_attrs (ji);
3505 if (ji->dbg_step_through)
3508 if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3509 init_jit_info_dbg_attrs (ji);
3510 if (ji->dbg_non_user_code)
3517 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3518 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3523 /* Send a VM START/DEATH event by default */
3524 if (event == EVENT_KIND_VM_START)
3525 events = g_slist_append (events, GINT_TO_POINTER (0));
3526 if (event == EVENT_KIND_VM_DEATH)
3527 events = g_slist_append (events, GINT_TO_POINTER (0));
3532 static G_GNUC_UNUSED const char*
3533 event_to_string (EventKind event)
3536 case EVENT_KIND_VM_START: return "VM_START";
3537 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3538 case EVENT_KIND_THREAD_START: return "THREAD_START";
3539 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3540 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3541 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3542 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3543 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3544 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3545 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3546 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3547 case EVENT_KIND_STEP: return "STEP";
3548 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3549 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3550 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3551 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3552 case EVENT_KIND_USER_LOG: return "USER_LOG";
3554 g_assert_not_reached ();
3562 * Send an event to the client, suspending the vm if needed.
3563 * LOCKING: Since this can suspend the calling thread, no locks should be held
3565 * The EVENTS list is freed by this function.
3568 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3572 MonoDomain *domain = mono_domain_get ();
3573 MonoThread *thread = NULL;
3574 MonoObject *keepalive_obj = NULL;
3575 gboolean send_success = FALSE;
3580 DEBUG_PRINTF (2, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event));
3584 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3585 // FIXME: We miss those events
3586 DEBUG_PRINTF (2, "VM start event not sent yet: dropping %s\n", event_to_string (event));
3590 if (vm_death_event_sent) {
3591 DEBUG_PRINTF (2, "VM death event has been sent: dropping %s\n", event_to_string (event));
3595 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3596 DEBUG_PRINTF (2, "Mono runtime is shutting down: dropping %s\n", event_to_string (event));
3601 DEBUG_PRINTF (2, "Debugger client is not connected: dropping %s\n", event_to_string (event));
3605 if (event == EVENT_KIND_KEEPALIVE)
3606 suspend_policy = SUSPEND_POLICY_NONE;
3611 if (agent_config.defer) {
3612 /* Make sure the thread id is always set when doing deferred debugging */
3613 if (is_debugger_thread ()) {
3614 /* Don't suspend on events from the debugger thread */
3615 suspend_policy = SUSPEND_POLICY_NONE;
3616 thread = mono_thread_get_main ();
3618 else thread = mono_thread_current ();
3620 if (is_debugger_thread () && event != EVENT_KIND_VM_DEATH)
3621 // FIXME: Send these with a NULL thread, don't suspend the current thread
3626 nevents = g_slist_length (events);
3627 buffer_init (&buf, 128);
3628 buffer_add_byte (&buf, suspend_policy);
3629 buffer_add_int (&buf, nevents);
3631 for (l = events; l; l = l->next) {
3632 buffer_add_byte (&buf, event); // event kind
3633 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3638 thread = mono_thread_current ();
3640 if (event == EVENT_KIND_VM_START && arg != NULL)
3643 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3646 case EVENT_KIND_THREAD_START:
3647 case EVENT_KIND_THREAD_DEATH:
3649 case EVENT_KIND_APPDOMAIN_CREATE:
3650 case EVENT_KIND_APPDOMAIN_UNLOAD:
3651 buffer_add_domainid (&buf, arg);
3653 case EVENT_KIND_METHOD_ENTRY:
3654 case EVENT_KIND_METHOD_EXIT:
3655 buffer_add_methodid (&buf, domain, arg);
3657 case EVENT_KIND_ASSEMBLY_LOAD:
3658 buffer_add_assemblyid (&buf, domain, arg);
3660 case EVENT_KIND_ASSEMBLY_UNLOAD: {
3661 DebuggerTlsData *tls;
3663 /* The domain the assembly belonged to is not equal to the current domain */
3664 tls = mono_native_tls_get_value (debugger_tls_id);
3666 g_assert (tls->domain_unloading);
3668 buffer_add_assemblyid (&buf, tls->domain_unloading, arg);
3671 case EVENT_KIND_TYPE_LOAD:
3672 buffer_add_typeid (&buf, domain, arg);
3674 case EVENT_KIND_BREAKPOINT:
3675 case EVENT_KIND_STEP:
3676 buffer_add_methodid (&buf, domain, arg);
3677 buffer_add_long (&buf, il_offset);
3679 case EVENT_KIND_VM_START:
3680 buffer_add_domainid (&buf, mono_get_root_domain ());
3682 case EVENT_KIND_VM_DEATH:
3683 if (CHECK_PROTOCOL_VERSION (2, 27))
3684 buffer_add_int (&buf, mono_environment_exitcode_get ());
3686 case EVENT_KIND_EXCEPTION: {
3687 EventInfo *ei = arg;
3688 buffer_add_objid (&buf, ei->exc);
3690 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3691 * later after the suspension. (#12494).
3693 keepalive_obj = ei->exc;
3696 case EVENT_KIND_USER_BREAK:
3698 case EVENT_KIND_USER_LOG: {
3699 EventInfo *ei = arg;
3700 buffer_add_int (&buf, ei->level);
3701 buffer_add_string (&buf, ei->category ? ei->category : "");
3702 buffer_add_string (&buf, ei->message ? ei->message : "");
3705 case EVENT_KIND_KEEPALIVE:
3706 suspend_policy = SUSPEND_POLICY_NONE;
3709 g_assert_not_reached ();
3713 if (event == EVENT_KIND_VM_START) {
3714 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3715 if (!agent_config.defer)
3716 start_debugger_thread ();
3719 if (event == EVENT_KIND_VM_DEATH) {
3720 vm_death_event_sent = TRUE;
3721 suspend_policy = SUSPEND_POLICY_NONE;
3724 if (mono_runtime_is_shutting_down ())
3725 suspend_policy = SUSPEND_POLICY_NONE;
3727 if (suspend_policy != SUSPEND_POLICY_NONE) {
3729 * Save the thread context and start suspending before sending the packet,
3730 * since we could be receiving the resume request before send_packet ()
3733 save_thread_context (ctx);
3737 /* This will keep this object alive */
3738 get_objref (keepalive_obj);
3741 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3745 g_slist_free (events);
3748 if (!send_success) {
3749 DEBUG_PRINTF (2, "Sending command %s failed.\n", event_to_string (event));
3753 if (event == EVENT_KIND_VM_START) {
3754 vm_start_event_sent = TRUE;
3757 DEBUG_PRINTF (1, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer)mono_native_thread_id_get (), nevents, event_to_string (event), ecount, suspend_policy);
3759 switch (suspend_policy) {
3760 case SUSPEND_POLICY_NONE:
3762 case SUSPEND_POLICY_ALL:
3765 case SUSPEND_POLICY_EVENT_THREAD:
3769 g_assert_not_reached ();
3774 process_profiler_event (EventKind event, gpointer arg)
3778 EventInfo ei, *ei_arg = NULL;
3780 if (event == EVENT_KIND_TYPE_LOAD) {
3785 mono_loader_lock ();
3786 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3787 mono_loader_unlock ();
3789 process_event (event, arg, 0, NULL, events, suspend_policy);
3793 runtime_initialized (MonoProfiler *prof)
3795 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3796 if (agent_config.defer)
3797 start_debugger_thread ();
3801 runtime_shutdown (MonoProfiler *prof)
3803 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3805 mono_debugger_agent_cleanup ();
3809 thread_startup (MonoProfiler *prof, uintptr_t tid)
3811 MonoInternalThread *thread = mono_thread_internal_current ();
3812 MonoInternalThread *old_thread;
3813 DebuggerTlsData *tls;
3815 if (mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (tid), debugger_thread_id))
3818 g_assert (mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (tid), MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid)));
3820 mono_loader_lock ();
3821 old_thread = mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3822 mono_loader_unlock ();
3824 if (thread == old_thread) {
3826 * For some reason, thread_startup () might be called for the same thread
3827 * multiple times (attach ?).
3829 DEBUG_PRINTF (1, "[%p] thread_start () called multiple times for %p, ignored.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3833 * thread_end () might not be called for some threads, and the tid could
3836 DEBUG_PRINTF (1, "[%p] Removing stale data for tid %p.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3837 mono_loader_lock ();
3838 mono_g_hash_table_remove (thread_to_tls, old_thread);
3839 mono_g_hash_table_remove (tid_to_thread, GUINT_TO_POINTER (tid));
3840 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3841 mono_loader_unlock ();
3845 tls = mono_native_tls_get_value (debugger_tls_id);
3847 // FIXME: Free this somewhere
3848 tls = g_new0 (DebuggerTlsData, 1);
3849 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread, MONO_ROOT_SOURCE_DEBUGGER, "debugger thread reference");
3850 tls->thread = thread;
3851 mono_native_tls_set_value (debugger_tls_id, tls);
3853 DEBUG_PRINTF (1, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3855 mono_loader_lock ();
3856 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3857 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3858 mono_g_hash_table_insert (tid_to_thread_obj, GUINT_TO_POINTER (tid), mono_thread_current ());
3859 mono_loader_unlock ();
3861 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3864 * suspend_vm () could have missed this thread, so wait for a resume.
3870 thread_end (MonoProfiler *prof, uintptr_t tid)
3872 MonoInternalThread *thread;
3873 DebuggerTlsData *tls = NULL;
3875 mono_loader_lock ();
3876 thread = mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3878 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3879 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3881 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3882 tls->terminated = TRUE;
3883 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3884 MONO_GC_UNREGISTER_ROOT (tls->thread);
3888 mono_loader_unlock ();
3890 /* We might be called for threads started before we registered the start callback */
3892 DEBUG_PRINTF (1, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3894 if (mono_native_thread_id_equals (mono_native_thread_id_get (), MONO_UINT_TO_NATIVE_THREAD_ID (tid))
3895 && !mono_native_tls_get_value (debugger_tls_id)
3898 * This can happen on darwin since we deregister threads using pthread dtors.
3899 * process_profiler_event () and the code it calls cannot handle a null TLS value.
3904 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3909 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3911 mono_loader_lock ();
3912 g_hash_table_insert (domains, domain, domain);
3913 mono_loader_unlock ();
3915 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3919 appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain)
3921 DebuggerTlsData *tls;
3923 /* This might be called during shutdown on the debugger thread from the CMD_VM_EXIT code */
3924 if (is_debugger_thread ())
3928 * Remember the currently unloading appdomain as it is needed to generate
3929 * proper ids for unloading assemblies.
3931 tls = mono_native_tls_get_value (debugger_tls_id);
3933 tls->domain_unloading = domain;
3937 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3939 DebuggerTlsData *tls;
3941 if (is_debugger_thread ())
3944 tls = mono_native_tls_get_value (debugger_tls_id);
3946 tls->domain_unloading = NULL;
3948 clear_breakpoints_for_domain (domain);
3950 mono_loader_lock ();
3951 /* Invalidate each thread's frame stack */
3952 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3953 mono_loader_unlock ();
3955 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3959 * invalidate_each_thread:
3961 * A GHFunc to invalidate frames.
3962 * value must be a DebuggerTlsData*
3965 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3967 invalidate_frames (value);
3971 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3973 /* Sent later in jit_end () */
3975 g_ptr_array_add (pending_assembly_loads, assembly);
3980 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3982 if (is_debugger_thread ())
3985 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3987 clear_event_requests_for_assembly (assembly);
3988 clear_types_for_assembly (assembly);
3992 send_type_load (MonoClass *klass)
3994 gboolean type_load = FALSE;
3995 MonoDomain *domain = mono_domain_get ();
3996 AgentDomainInfo *info = NULL;
3998 info = get_agent_domain_info (domain);
4000 mono_loader_lock ();
4002 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
4004 g_hash_table_insert (info->loaded_classes, klass, klass);
4007 mono_loader_unlock ();
4010 emit_type_load (klass, klass, NULL);
4014 * Emit load events for all types currently loaded in the domain.
4015 * Takes the loader and domain locks.
4016 * user_data is unused.
4019 send_types_for_domain (MonoDomain *domain, void *user_data)
4021 AgentDomainInfo *info = NULL;
4023 info = get_agent_domain_info (domain);
4026 mono_loader_lock ();
4027 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4028 mono_loader_unlock ();
4032 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
4035 * We emit type load events when the first method of the type is JITted,
4036 * since the class load profiler callbacks might be called with the
4037 * loader lock held. They could also occur in the debugger thread.
4038 * Same for assembly load events.
4041 MonoAssembly *assembly = NULL;
4043 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4045 if (pending_assembly_loads->len > 0) {
4046 assembly = g_ptr_array_index (pending_assembly_loads, 0);
4047 g_ptr_array_remove_index (pending_assembly_loads, 0);
4052 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4058 send_type_load (method->klass);
4061 add_pending_breakpoints (method, jinfo);
4065 * BREAKPOINTS/SINGLE STEPPING
4069 * Contains information about an inserted breakpoint.
4072 long il_offset, native_offset;
4076 } BreakpointInstance;
4079 * Contains generic information about a breakpoint.
4083 * The method where the breakpoint is placed. Can be NULL in which case it
4084 * is inserted into every method. This is used to implement method entry/
4085 * exit events. Can be a generic method definition, in which case the
4086 * breakpoint is inserted into every instance.
4092 * A list of BreakpointInstance structures describing where the breakpoint
4093 * was inserted. There could be more than one because of
4094 * generics/appdomains/method entry/exit.
4096 GPtrArray *children;
4099 /* List of breakpoints */
4100 /* Protected by the loader lock */
4101 static GPtrArray *breakpoints;
4102 /* Maps breakpoint locations to the number of breakpoints at that location */
4103 static GHashTable *bp_locs;
4106 breakpoints_init (void)
4108 breakpoints = g_ptr_array_new ();
4109 bp_locs = g_hash_table_new (NULL, NULL);
4113 * insert_breakpoint:
4115 * Insert the breakpoint described by BP into the method described by
4119 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4122 BreakpointInstance *inst;
4123 SeqPointIterator it;
4124 gboolean it_has_sp = FALSE;
4127 mono_error_init (error);
4129 mono_seq_point_iterator_init (&it, seq_points);
4130 while (mono_seq_point_iterator_next (&it)) {
4131 if (it.seq_point.il_offset == bp->il_offset) {
4139 * The set of IL offsets with seq points doesn't completely match the
4140 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4142 mono_seq_point_iterator_init (&it, seq_points);
4143 while (mono_seq_point_iterator_next (&it)) {
4144 if (it.seq_point.il_offset != METHOD_ENTRY_IL_OFFSET &&
4145 it.seq_point.il_offset != METHOD_EXIT_IL_OFFSET &&
4146 it.seq_point.il_offset + 1 == bp->il_offset) {
4154 char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d", mono_method_full_name (jinfo_get_method (ji), TRUE), bp->il_offset);
4156 mono_seq_point_iterator_init (&it, seq_points);
4157 while (mono_seq_point_iterator_next (&it))
4158 DEBUG_PRINTF (1, "%d\n", it.seq_point.il_offset);
4161 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4162 g_warning ("%s", s);
4166 g_warning ("%s", s);
4172 inst = g_new0 (BreakpointInstance, 1);
4173 inst->il_offset = it.seq_point.il_offset;
4174 inst->native_offset = it.seq_point.native_offset;
4175 inst->ip = (guint8*)ji->code_start + it.seq_point.native_offset;
4177 inst->domain = domain;
4179 mono_loader_lock ();
4181 g_ptr_array_add (bp->children, inst);
4183 mono_loader_unlock ();
4186 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4187 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4190 if (it.seq_point.native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4191 DEBUG_PRINTF (1, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset);
4192 } else if (count == 0) {
4193 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4194 mono_arch_set_breakpoint (ji, inst->ip);
4200 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);
4204 remove_breakpoint (BreakpointInstance *inst)
4206 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4208 MonoJitInfo *ji = inst->ji;
4209 guint8 *ip = inst->ip;
4212 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4213 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4216 g_assert (count > 0);
4218 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4219 mono_arch_clear_breakpoint (ji, ip);
4220 DEBUG_PRINTF (1, "[dbg] Clear breakpoint at %s [%p].\n", mono_method_full_name (jinfo_get_method (ji), TRUE), ip);
4228 * This doesn't take any locks.
4230 static inline gboolean
4231 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4237 if (method == bp->method)
4239 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4242 if (bp->method->is_inflated && method->is_inflated) {
4243 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4244 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4246 /* Open generic methods should match closed generic methods of the same class */
4247 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4248 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4249 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4251 /* FIXME: Handle !mvar */
4252 if (t1->type != MONO_TYPE_MVAR)
4263 * add_pending_breakpoints:
4265 * Insert pending breakpoints into the newly JITted method METHOD.
4268 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4271 MonoSeqPointInfo *seq_points;
4273 MonoMethod *jmethod;
4278 domain = mono_domain_get ();
4280 mono_loader_lock ();
4282 for (i = 0; i < breakpoints->len; ++i) {
4283 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4284 gboolean found = FALSE;
4286 if (!bp_matches_method (bp, method))
4289 for (j = 0; j < bp->children->len; ++j) {
4290 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4297 MonoMethod *declaring = NULL;
4299 jmethod = jinfo_get_method (ji);
4300 if (jmethod->is_inflated)
4301 declaring = mono_method_get_declaring_generic_method (jmethod);
4303 mono_domain_lock (domain);
4304 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, jmethod);
4305 if (!seq_points && declaring)
4306 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, declaring);
4307 mono_domain_unlock (domain);
4309 /* Could be AOT code */
4311 g_assert (seq_points);
4313 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4317 mono_loader_unlock ();
4321 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4327 mono_error_init (error);
4329 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4331 /* Might be AOTed code */
4332 code = mono_aot_get_method (domain, method);
4334 ji = mono_jit_info_table_find (domain, code);
4339 insert_breakpoint (seq_points, domain, ji, bp, error);
4343 clear_breakpoint (MonoBreakpoint *bp);
4348 * Set a breakpoint at IL_OFFSET in METHOD.
4349 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4350 * METHOD can also be a generic method definition, in which case a breakpoint
4351 * is placed in all instances of the method.
4352 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4355 static MonoBreakpoint*
4356 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4359 GHashTableIter iter, iter2;
4362 MonoSeqPointInfo *seq_points;
4364 GPtrArray *method_domains;
4365 GPtrArray *method_seq_points;
4369 mono_error_init (error);
4372 // - suspend/resume the vm to prevent code patching problems
4373 // - multiple breakpoints on the same location
4374 // - dynamic methods
4377 bp = g_new0 (MonoBreakpoint, 1);
4378 bp->method = method;
4379 bp->il_offset = il_offset;
4381 bp->children = g_ptr_array_new ();
4383 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);
4385 methods = g_ptr_array_new ();
4386 method_domains = g_ptr_array_new ();
4387 method_seq_points = g_ptr_array_new ();
4389 mono_loader_lock ();
4390 g_hash_table_iter_init (&iter, domains);
4391 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4392 mono_domain_lock (domain);
4393 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4394 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4395 if (bp_matches_method (bp, m)) {
4396 /* Save the info locally to simplify the code inside the domain lock */
4397 g_ptr_array_add (methods, m);
4398 g_ptr_array_add (method_domains, domain);
4399 g_ptr_array_add (method_seq_points, seq_points);
4402 mono_domain_unlock (domain);
4405 for (i = 0; i < methods->len; ++i) {
4406 m = g_ptr_array_index (methods, i);
4407 domain = g_ptr_array_index (method_domains, i);
4408 seq_points = g_ptr_array_index (method_seq_points, i);
4409 set_bp_in_method (domain, m, seq_points, bp, error);
4412 g_ptr_array_add (breakpoints, bp);
4413 mono_loader_unlock ();
4415 g_ptr_array_free (methods, TRUE);
4416 g_ptr_array_free (method_domains, TRUE);
4417 g_ptr_array_free (method_seq_points, TRUE);
4419 if (error && !mono_error_ok (error)) {
4420 clear_breakpoint (bp);
4428 clear_breakpoint (MonoBreakpoint *bp)
4432 // FIXME: locking, races
4433 for (i = 0; i < bp->children->len; ++i) {
4434 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4436 remove_breakpoint (inst);
4441 mono_loader_lock ();
4442 g_ptr_array_remove (breakpoints, bp);
4443 mono_loader_unlock ();
4445 g_ptr_array_free (bp->children, TRUE);
4450 breakpoints_cleanup (void)
4454 mono_loader_lock ();
4456 while (i < event_requests->len) {
4457 EventRequest *req = g_ptr_array_index (event_requests, i);
4459 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4460 clear_breakpoint (req->info);
4461 g_ptr_array_remove_index_fast (event_requests, i);
4468 for (i = 0; i < breakpoints->len; ++i)
4469 g_free (g_ptr_array_index (breakpoints, i));
4471 g_ptr_array_free (breakpoints, TRUE);
4472 g_hash_table_destroy (bp_locs);
4477 mono_loader_unlock ();
4481 * clear_breakpoints_for_domain:
4483 * Clear breakpoint instances which reference DOMAIN.
4486 clear_breakpoints_for_domain (MonoDomain *domain)
4490 /* This could be called after shutdown */
4494 mono_loader_lock ();
4495 for (i = 0; i < breakpoints->len; ++i) {
4496 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4499 while (j < bp->children->len) {
4500 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4502 if (inst->domain == domain) {
4503 remove_breakpoint (inst);
4507 g_ptr_array_remove_index_fast (bp->children, j);
4513 mono_loader_unlock ();
4519 * Return FALSE if single stepping needs to continue.
4522 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp, DebuggerTlsData *tls, MonoContext *ctx)
4524 MonoDebugMethodInfo *minfo;
4525 MonoDebugSourceLocation *loc = NULL;
4526 gboolean hit = TRUE;
4529 if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK)) {
4531 * These seq points are inserted by the JIT after calls, step over needs to skip them.
4533 DEBUG_PRINTF (1, "[%p] Seq point at nonempty stack %x while stepping over, continuing single stepping.\n", (gpointer)mono_native_thread_id_get (), sp->il_offset);
4537 if (req->depth == STEP_DEPTH_OVER && hit) {
4538 if (!tls->context.valid)
4539 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4540 compute_frame_info (tls->thread, tls);
4541 if (req->nframes && tls->frame_count && tls->frame_count > req->nframes) {
4542 /* Hit the breakpoint in a recursive call */
4543 DEBUG_PRINTF (1, "[%p] Breakpoint at lower frame while stepping over, continuing single stepping.\n", (gpointer)mono_native_thread_id_get ());
4548 if (req->depth == STEP_DEPTH_INTO && req->size == STEP_SIZE_MIN && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) && ss_req->start_method){
4549 method = jinfo_get_method (ji);
4550 if (!tls->context.valid)
4551 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4552 compute_frame_info (tls->thread, tls);
4553 if (ss_req->start_method == method && req->nframes && tls->frame_count == req->nframes) {//Check also frame count(could be recursion)
4554 DEBUG_PRINTF (1, "[%p] Seq point at nonempty stack %x while stepping in, continuing single stepping.\n", (gpointer)mono_native_thread_id_get (), sp->il_offset);
4559 if (req->size != STEP_SIZE_LINE)
4562 /* Have to check whenever a different source line was reached */
4563 method = jinfo_get_method (ji);
4564 minfo = mono_debug_lookup_method (method);
4567 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4570 DEBUG_PRINTF (1, "[%p] No line number info for il offset %x, continuing single stepping.\n", (gpointer)mono_native_thread_id_get (), sp->il_offset);
4571 ss_req->last_method = method;
4573 } else if (loc && method == ss_req->last_method && loc->row == ss_req->last_line) {
4574 DEBUG_PRINTF (1, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer)mono_native_thread_id_get (), loc->row);
4579 ss_req->last_method = method;
4580 ss_req->last_line = loc->row;
4581 mono_debug_free_source_location (loc);
4588 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4590 return bp->method && bp->method->klass->image->assembly == assembly;
4594 process_breakpoint_inner (DebuggerTlsData *tls, gboolean from_signal)
4598 int i, j, suspend_policy;
4599 guint32 native_offset;
4601 BreakpointInstance *inst;
4602 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4603 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4604 EventKind kind = EVENT_KIND_BREAKPOINT;
4605 MonoContext *ctx = &tls->restore_state.ctx;
4607 MonoSeqPointInfo *info;
4611 // FIXME: Speed this up
4613 ip = MONO_CONTEXT_GET_IP (ctx);
4614 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4615 g_assert (ji && !ji->is_trampoline);
4616 method = jinfo_get_method (ji);
4618 /* Compute the native offset of the breakpoint from the ip */
4619 native_offset = ip - (guint8*)ji->code_start;
4622 * Skip the instruction causing the breakpoint signal.
4625 mono_arch_skip_breakpoint (ctx, ji);
4627 if (method->wrapper_type || tls->disable_breakpoints)
4630 bp_reqs = g_ptr_array_new ();
4631 ss_reqs = g_ptr_array_new ();
4632 ss_reqs_orig = g_ptr_array_new ();
4634 mono_loader_lock ();
4637 * The ip points to the instruction causing the breakpoint event, which is after
4638 * the offset recorded in the seq point map, so find the prev seq point before ip.
4640 found_sp = mono_find_prev_seq_point_for_native_offset (mono_domain_get (), method, native_offset, &info, &sp);
4643 no_seq_points_found (method, native_offset);
4645 g_assert (found_sp);
4647 DEBUG_PRINTF (1, "[%p] Breakpoint hit, method=%s, ip=%p, [il=0x%x,native=0x%x].\n", (gpointer)mono_native_thread_id_get (), method->name, ip, sp.il_offset, native_offset);
4650 for (i = 0; i < breakpoints->len; ++i) {
4651 bp = g_ptr_array_index (breakpoints, i);
4656 for (j = 0; j < bp->children->len; ++j) {
4657 inst = g_ptr_array_index (bp->children, j);
4658 if (inst->ji == ji && inst->il_offset == sp.il_offset && inst->native_offset == sp.native_offset) {
4659 if (bp->req->event_kind == EVENT_KIND_STEP) {
4660 g_ptr_array_add (ss_reqs_orig, bp->req);
4662 g_ptr_array_add (bp_reqs, bp->req);
4667 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4668 /* Maybe a method entry/exit event */
4669 if (sp.il_offset == METHOD_ENTRY_IL_OFFSET)
4670 kind = EVENT_KIND_METHOD_ENTRY;
4671 else if (sp.il_offset == METHOD_EXIT_IL_OFFSET)
4672 kind = EVENT_KIND_METHOD_EXIT;
4675 /* Process single step requests */
4676 for (i = 0; i < ss_reqs_orig->len; ++i) {
4677 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4678 SingleStepReq *ss_req = req->info;
4681 if (mono_thread_internal_current () != ss_req->thread)
4684 hit = ss_update (ss_req, ji, &sp, tls, ctx);
4686 g_ptr_array_add (ss_reqs, req);
4688 /* Start single stepping again from the current sequence point */
4689 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
4692 if (ss_reqs->len > 0)
4693 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4694 if (bp_reqs->len > 0)
4695 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4696 if (kind != EVENT_KIND_BREAKPOINT)
4697 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4699 mono_loader_unlock ();
4701 g_ptr_array_free (bp_reqs, TRUE);
4702 g_ptr_array_free (ss_reqs, TRUE);
4705 * FIXME: The first event will suspend, so the second will only be sent after the
4709 process_event (EVENT_KIND_STEP, method, 0, ctx, ss_events, suspend_policy);
4711 process_event (kind, method, 0, ctx, bp_events, suspend_policy);
4712 if (enter_leave_events)
4713 process_event (kind, method, 0, ctx, enter_leave_events, suspend_policy);
4716 /* Process a breakpoint/single step event after resuming from a signal handler */
4718 process_signal_event (void (*func) (DebuggerTlsData*, gboolean))
4720 DebuggerTlsData *tls;
4721 MonoThreadUnwindState orig_restore_state;
4724 tls = mono_native_tls_get_value (debugger_tls_id);
4725 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4726 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4727 mono_thread_state_init_from_monoctx (&tls->restore_state, &tls->handler_ctx);
4731 /* This is called when resuming from a signal handler, so it shouldn't return */
4732 memcpy (&ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4733 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4734 mono_restore_context (&ctx);
4735 g_assert_not_reached ();
4739 process_breakpoint (void)
4741 process_signal_event (process_breakpoint_inner);
4745 resume_from_signal_handler (void *sigctx, void *func)
4747 DebuggerTlsData *tls;
4750 /* Save the original context in TLS */
4751 // FIXME: This might not work on an altstack ?
4752 tls = mono_native_tls_get_value (debugger_tls_id);
4754 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer)mono_native_thread_id_get ());
4757 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4758 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4759 // clob:c could be added to op_seq_point.
4761 mono_sigctx_to_monoctx (sigctx, &ctx);
4762 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4763 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4764 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4766 MONO_CONTEXT_SET_IP (&ctx, func);
4768 mono_monoctx_to_sigctx (&ctx, sigctx);
4770 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4771 mono_ppc_set_func_into_sigctx (sigctx, func);
4776 mono_debugger_agent_breakpoint_hit (void *sigctx)
4779 * We are called from a signal handler, and running code there causes all kinds of
4780 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4781 * So set up the signal context to return to the real breakpoint handler function.
4783 resume_from_signal_handler (sigctx, process_breakpoint);
4787 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4789 if (frame->managed) {
4790 *(MonoContext*)data = *ctx;
4799 * Called by System.Diagnostics.Debugger:Break ().
4802 mono_debugger_agent_user_break (void)
4804 if (agent_config.enabled) {
4809 /* Obtain a context */
4810 MONO_CONTEXT_SET_IP (&ctx, NULL);
4811 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4812 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4814 mono_loader_lock ();
4815 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4816 mono_loader_unlock ();
4818 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4819 } else if (debug_options.native_debugger_break) {
4825 ss_depth_to_string (StepDepth depth)
4828 case STEP_DEPTH_OVER:
4830 case STEP_DEPTH_OUT:
4832 case STEP_DEPTH_INTO:
4835 g_assert_not_reached ();
4841 process_single_step_inner (DebuggerTlsData *tls, gboolean from_signal)
4846 int il_offset, suspend_policy;
4849 MonoContext *ctx = &tls->restore_state.ctx;
4852 MonoSeqPointInfo *info;
4854 ip = MONO_CONTEXT_GET_IP (ctx);
4856 /* Skip the instruction causing the single step */
4858 mono_arch_skip_single_step (ctx);
4860 if (suspend_count > 0) {
4861 process_suspend (tls, ctx);
4866 // FIXME: A suspend race
4869 if (mono_thread_internal_current () != ss_req->thread)
4872 if (log_level > 0) {
4873 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4875 DEBUG_PRINTF (1, "[%p] Single step event (depth=%s) at %s (%p)[0x%x], sp %p, last sp %p\n", (gpointer)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);
4878 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4879 g_assert (ji && !ji->is_trampoline);
4880 method = jinfo_get_method (ji);
4883 if (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4888 * Stopping in memset makes half-initialized vtypes visible.
4889 * Stopping in memcpy makes half-copied vtypes visible.
4891 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
4895 * The ip points to the instruction causing the single step event, which is before
4896 * the offset recorded in the seq point map, so find the next seq point after ip.
4898 if (!mono_find_next_seq_point_for_native_offset (domain, method, (guint8*)ip - (guint8*)ji->code_start, &info, &sp))
4901 il_offset = sp.il_offset;
4903 if (!ss_update (ss_req, ji, &sp, tls, ctx))
4906 /* Start single stepping again from the current sequence point */
4907 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
4909 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
4910 (method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4911 !strcmp (method->name, ".cctor"))
4914 // FIXME: Has to lock earlier
4916 reqs = g_ptr_array_new ();
4918 mono_loader_lock ();
4920 g_ptr_array_add (reqs, ss_req->req);
4922 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4924 g_ptr_array_free (reqs, TRUE);
4926 mono_loader_unlock ();
4928 process_event (EVENT_KIND_STEP, jinfo_get_method (ji), il_offset, ctx, events, suspend_policy);
4932 process_single_step (void)
4934 process_signal_event (process_single_step_inner);
4938 * mono_debugger_agent_single_step_event:
4940 * Called from a signal handler to handle a single step event.
4943 mono_debugger_agent_single_step_event (void *sigctx)
4945 /* Resume to process_single_step through the signal context */
4947 // FIXME: Since step out/over is implemented using step in, the step in case should
4948 // be as fast as possible. Move the relevant code from process_single_step_inner ()
4951 if (is_debugger_thread ()) {
4953 * This could happen despite our best effors when the runtime calls
4954 * assembly/type resolve hooks.
4955 * FIXME: Breakpoints too.
4959 mono_sigctx_to_monoctx (sigctx, &ctx);
4960 mono_arch_skip_single_step (&ctx);
4961 mono_monoctx_to_sigctx (&ctx, sigctx);
4965 resume_from_signal_handler (sigctx, process_single_step);
4969 debugger_agent_single_step_from_context (MonoContext *ctx)
4971 DebuggerTlsData *tls;
4972 MonoThreadUnwindState orig_restore_state;
4974 if (is_debugger_thread ())
4977 tls = mono_native_tls_get_value (debugger_tls_id);
4980 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4981 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4982 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
4983 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
4985 process_single_step_inner (tls, FALSE);
4987 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4988 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4992 debugger_agent_breakpoint_from_context (MonoContext *ctx)
4994 DebuggerTlsData *tls;
4995 MonoThreadUnwindState orig_restore_state;
4998 if (is_debugger_thread ())
5001 orig_ip = MONO_CONTEXT_GET_IP (ctx);
5002 MONO_CONTEXT_SET_IP (ctx, orig_ip - 1);
5004 tls = mono_native_tls_get_value (debugger_tls_id);
5006 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5007 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5008 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5010 process_breakpoint_inner (tls, FALSE);
5012 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5013 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5014 if (MONO_CONTEXT_GET_IP (ctx) == orig_ip - 1)
5015 MONO_CONTEXT_SET_IP (ctx, orig_ip);
5019 * start_single_stepping:
5021 * Turn on single stepping. Can be called multiple times, for example,
5022 * by a single step event request + a suspend.
5025 start_single_stepping (void)
5027 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5028 int val = InterlockedIncrement (&ss_count);
5031 mono_arch_start_single_stepping ();
5033 g_assert_not_reached ();
5038 stop_single_stepping (void)
5040 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5041 int val = InterlockedDecrement (&ss_count);
5044 mono_arch_stop_single_stepping ();
5046 g_assert_not_reached ();
5053 * Stop the single stepping operation given by SS_REQ.
5056 ss_stop (SingleStepReq *ss_req)
5061 for (l = ss_req->bps; l; l = l->next) {
5062 clear_breakpoint (l->data);
5064 g_slist_free (ss_req->bps);
5068 if (ss_req->global) {
5069 stop_single_stepping ();
5070 ss_req->global = FALSE;
5077 * Start the single stepping operation given by SS_REQ from the sequence point SP.
5078 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
5079 * belong to the same thread as CTX.
5080 * If FRAMES is not-null, use that instead of tls->frames for placing breakpoints etc.
5083 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint* sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls,
5084 gboolean step_to_catch, StackFrame **frames, int nframes)
5086 int i, j, frame_index;
5087 SeqPoint *next_sp, *parent_sp = NULL;
5088 SeqPoint local_sp, local_parent_sp;
5091 MonoSeqPointInfo *parent_info;
5092 MonoMethod *parent_sp_method = NULL;
5093 gboolean enable_global = FALSE;
5095 /* Stop the previous operation */
5099 * Implement single stepping using breakpoints if possible.
5101 if (step_to_catch) {
5102 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
5103 ss_req->bps = g_slist_append (ss_req->bps, bp);
5107 if (ctx && !frames) {
5108 /* Need parent frames */
5109 if (!tls->context.valid)
5110 mono_thread_state_init_from_monoctx (&tls->context, ctx);
5111 compute_frame_info (tls->thread, tls);
5112 frames = tls->frames;
5113 nframes = tls->frame_count;
5117 * Find the first sequence point in the current or in a previous frame which
5118 * is not the last in its method.
5120 if (ss_req->depth == STEP_DEPTH_OUT) {
5121 /* Ignore seq points in current method */
5122 while (frame_index < nframes) {
5123 StackFrame *frame = frames [frame_index];
5125 method = frame->method;
5126 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5127 sp = (found_sp)? &local_sp : NULL;
5129 if (sp && sp->next_len != 0)
5132 // There could be method calls before the next seq point in the caller when using nested calls
5133 //enable_global = TRUE;
5135 if (sp && sp->next_len == 0) {
5137 while (frame_index < nframes) {
5138 StackFrame *frame = frames [frame_index];
5140 method = frame->method;
5141 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5142 sp = (found_sp)? &local_sp : NULL;
5143 if (sp && sp->next_len != 0)
5149 /* Have to put a breakpoint into a parent frame since the seq points might not cover all control flow out of the method */
5150 while (frame_index < nframes) {
5151 StackFrame *frame = frames [frame_index];
5153 parent_sp_method = frame->method;
5154 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &parent_info, &local_parent_sp);
5155 parent_sp = found_sp ? &local_parent_sp : NULL;
5156 if (found_sp && parent_sp->next_len != 0)
5164 if (sp && sp->next_len > 0) {
5165 SeqPoint* next = g_new(SeqPoint, sp->next_len);
5167 mono_seq_point_init_next (info, *sp, next);
5168 for (i = 0; i < sp->next_len; i++) {
5171 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
5172 ss_req->bps = g_slist_append (ss_req->bps, bp);
5178 SeqPoint* next = g_new(SeqPoint, parent_sp->next_len);
5180 mono_seq_point_init_next (parent_info, *parent_sp, next);
5181 for (i = 0; i < parent_sp->next_len; i++) {
5184 bp = set_breakpoint (parent_sp_method, next_sp->il_offset, ss_req->req, NULL);
5185 ss_req->bps = g_slist_append (ss_req->bps, bp);
5190 if (ss_req->nframes == 0)
5191 ss_req->nframes = nframes;
5193 if ((ss_req->depth == STEP_DEPTH_OVER) && (!sp && !parent_sp)) {
5194 DEBUG_PRINTF (1, "[dbg] No parent frame for step over, transition to step into.\n");
5196 * This is needed since if we leave managed code, and later return to it, step over
5197 * is not going to stop.
5198 * This approach is a bit ugly, since we change the step depth, but it only affects
5199 * clients who reuse the same step request, and only in this special case.
5201 ss_req->depth = STEP_DEPTH_INTO;
5204 if (ss_req->depth == STEP_DEPTH_OVER) {
5205 /* Need to stop in catch clauses as well */
5206 for (i = 0; i < nframes; ++i) {
5207 StackFrame *frame = frames [i];
5210 MonoJitInfo *jinfo = frame->ji;
5211 for (j = 0; j < jinfo->num_clauses; ++j) {
5212 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5214 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);
5215 sp = (found_sp)? &local_sp : NULL;
5217 bp = set_breakpoint (frame->method, sp->il_offset, ss_req->req, NULL);
5218 ss_req->bps = g_slist_append (ss_req->bps, bp);
5225 if (ss_req->depth == STEP_DEPTH_INTO) {
5226 /* Enable global stepping so we stop at method entry too */
5227 enable_global = TRUE;
5231 * The ctx/frame info computed above will become invalid when we continue.
5233 tls->context.valid = FALSE;
5234 tls->async_state.valid = FALSE;
5235 invalidate_frames (tls);
5238 if (enable_global) {
5239 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5240 ss_req->global = TRUE;
5241 start_single_stepping ();
5242 } else if (!ss_req->bps) {
5243 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5244 ss_req->global = TRUE;
5245 start_single_stepping ();
5247 ss_req->global = FALSE;
5252 * Start single stepping of thread THREAD
5255 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req)
5257 DebuggerTlsData *tls;
5258 MonoSeqPointInfo *info = NULL;
5259 SeqPoint *sp = NULL;
5262 MonoMethod *method = NULL;
5263 MonoDebugMethodInfo *minfo;
5264 gboolean step_to_catch = FALSE;
5265 gboolean set_ip = FALSE;
5266 StackFrame **frames = NULL;
5269 if (suspend_count == 0)
5270 return ERR_NOT_SUSPENDED;
5272 wait_for_suspend ();
5274 // FIXME: Multiple requests
5276 DEBUG_PRINTF (0, "Received a single step request while the previous one was still active.\n");
5277 return ERR_NOT_IMPLEMENTED;
5280 DEBUG_PRINTF (1, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth));
5282 ss_req = g_new0 (SingleStepReq, 1);
5284 ss_req->thread = thread;
5285 ss_req->size = size;
5286 ss_req->depth = depth;
5287 ss_req->filter = filter;
5290 mono_loader_lock ();
5291 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5292 mono_loader_unlock ();
5294 g_assert (tls->context.valid);
5296 if (tls->restore_state.valid && MONO_CONTEXT_GET_IP (&tls->context.ctx) != MONO_CONTEXT_GET_IP (&tls->restore_state.ctx)) {
5298 * Need to start single stepping from restore_state and not from the current state
5301 frames = compute_frame_info_from (thread, tls, &tls->restore_state, &nframes);
5304 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5306 if (tls->catch_state.valid) {
5308 StackFrameInfo frame;
5309 MonoContext new_ctx;
5310 MonoLMF *lmf = NULL;
5313 * We are stopped at a throw site. Stepping should go to the catch site.
5316 /* Find the the jit info for the catch context */
5317 res = mono_find_jit_info_ext (tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], ((MonoThreadInfo*)thread->thread_info)->jit_data, NULL, &tls->catch_state.ctx, &new_ctx, NULL, &lmf, NULL, &frame);
5319 g_assert (frame.type == FRAME_TYPE_MANAGED);
5322 * Find the seq point corresponding to the landing site ip, which is the first seq
5325 found_sp = mono_find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info, &local_sp);
5326 sp = (found_sp)? &local_sp : NULL;
5328 no_seq_points_found (frame.method, frame.native_offset);
5331 method = frame.method;
5333 step_to_catch = TRUE;
5334 /* This make sure the seq point is not skipped by process_single_step () */
5335 ss_req->last_sp = NULL;
5338 if (!step_to_catch) {
5339 StackFrame *frame = NULL;
5342 if (frames && nframes)
5345 compute_frame_info (thread, tls);
5347 if (tls->frame_count)
5348 frame = tls->frames [0];
5351 if (ss_req->size == STEP_SIZE_LINE) {
5353 ss_req->last_method = frame->method;
5354 ss_req->last_line = -1;
5356 minfo = mono_debug_lookup_method (frame->method);
5357 if (minfo && frame->il_offset != -1) {
5358 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
5361 ss_req->last_line = loc->row;
5369 if (!method && frame->il_offset != -1) {
5370 /* FIXME: Sort the table and use a binary search */
5371 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5372 sp = (found_sp)? &local_sp : NULL;
5374 no_seq_points_found (frame->method, frame->native_offset);
5376 method = frame->method;
5381 ss_req->start_method = method;
5383 ss_start (ss_req, method, sp, info, set_ip ? &tls->restore_state.ctx : &tls->context.ctx, tls, step_to_catch, frames, nframes);
5386 free_frames (frames, nframes);
5392 ss_destroy (SingleStepReq *req)
5395 g_assert (ss_req == req);
5404 ss_clear_for_assembly (SingleStepReq *req, MonoAssembly *assembly)
5407 gboolean found = TRUE;
5411 for (l = ss_req->bps; l; l = l->next) {
5412 if (breakpoint_matches_assembly (l->data, assembly)) {
5413 clear_breakpoint (l->data);
5414 ss_req->bps = g_slist_delete_link (ss_req->bps, l);
5423 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5426 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5432 if (!agent_config.enabled)
5435 mono_loader_lock ();
5436 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5437 mono_loader_unlock ();
5440 ei.category = category ? mono_string_to_utf8 (category) : NULL;
5441 ei.message = message ? mono_string_to_utf8 (message) : NULL;
5443 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5445 g_free (ei.category);
5446 g_free (ei.message);
5450 mono_debugger_agent_debug_log_is_enabled (void)
5452 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5453 return agent_config.enabled;
5456 #if defined(PLATFORM_ANDROID) || defined(TARGET_ANDROID)
5458 mono_debugger_agent_unhandled_exception (MonoException *exc)
5467 memset (&ei, 0, sizeof (EventInfo));
5468 ei.exc = (MonoObject*)exc;
5470 mono_loader_lock ();
5471 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5472 mono_loader_unlock ();
5474 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5479 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5480 MonoContext *catch_ctx)
5482 int i, j, suspend_policy;
5484 MonoJitInfo *ji, *catch_ji;
5486 DebuggerTlsData *tls = NULL;
5488 if (thread_to_tls != NULL) {
5489 MonoInternalThread *thread = mono_thread_internal_current ();
5491 mono_loader_lock ();
5492 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5493 mono_loader_unlock ();
5495 if (tls && tls->abort_requested)
5497 if (tls && tls->disable_breakpoints)
5501 memset (&ei, 0, sizeof (EventInfo));
5503 /* Just-In-Time debugging */
5505 if (agent_config.onuncaught && !inited) {
5506 finish_agent_init (FALSE);
5509 * Send an unsolicited EXCEPTION event with a dummy request id.
5511 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5512 ei.exc = (MonoObject*)exc;
5513 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5516 } else if (agent_config.onthrow && !inited) {
5518 gboolean found = FALSE;
5520 for (l = agent_config.onthrow; l; l = l->next) {
5521 char *ex_type = l->data;
5522 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5524 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5531 finish_agent_init (FALSE);
5534 * Send an unsolicited EXCEPTION event with a dummy request id.
5536 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5537 ei.exc = (MonoObject*)exc;
5538 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5546 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5548 catch_ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5552 ei.exc = (MonoObject*)exc;
5553 ei.caught = catch_ctx != NULL;
5555 mono_loader_lock ();
5557 /* Treat exceptions which are caught in non-user code as unhandled */
5558 for (i = 0; i < event_requests->len; ++i) {
5559 EventRequest *req = g_ptr_array_index (event_requests, i);
5560 if (req->event_kind != EVENT_KIND_EXCEPTION)
5563 for (j = 0; j < req->nmodifiers; ++j) {
5564 Modifier *mod = &req->modifiers [j];
5566 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5568 gboolean found = FALSE;
5569 MonoAssembly **assemblies = mod->data.assemblies;
5572 for (k = 0; assemblies [k]; ++k)
5573 if (assemblies [k] == jinfo_get_method (catch_ji)->klass->image->assembly)
5582 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5583 mono_loader_unlock ();
5585 if (tls && ei.caught && catch_ctx) {
5586 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5587 tls->catch_state.ctx = *catch_ctx;
5588 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5589 tls->catch_state.valid = TRUE;
5592 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5595 tls->catch_state.valid = FALSE;
5599 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5601 DebuggerTlsData *tls;
5606 tls = mono_native_tls_get_value (debugger_tls_id);
5611 * We're about to invoke an exception filter during the first pass of exception handling.
5613 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5614 * 'orig_ctx' is the context where the exception has been thrown.
5617 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5619 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5620 * the call site (line 37) and then continue to Main(), but it would never
5621 * include the throw site (line 32).
5623 * Since exception filters are invoked during the first pass of exception handling,
5624 * the stack frames of the throw site are still intact, so we should include them
5627 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5629 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5630 * but report the location of the 'throw' to the user.
5634 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5638 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5640 DebuggerTlsData *tls;
5645 tls = mono_native_tls_get_value (debugger_tls_id);
5649 tls->filter_state.valid = FALSE;
5653 * buffer_add_value_full:
5655 * Add the encoding of the value at ADDR described by T to the buffer.
5656 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5660 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5661 gboolean as_vtype, GHashTable *parent_vtypes)
5664 gboolean boxed_vtype = FALSE;
5667 if (!(*(void**)addr)) {
5668 /* This can happen with compiler generated locals */
5669 //printf ("%s\n", mono_type_full_name (t));
5670 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5673 g_assert (*(void**)addr);
5674 addr = *(void**)addr;
5679 case MONO_TYPE_BOOLEAN:
5682 case MONO_TYPE_CHAR:
5702 case MONO_TYPE_VOID:
5703 buffer_add_byte (buf, t->type);
5705 case MONO_TYPE_BOOLEAN:
5708 buffer_add_byte (buf, t->type);
5709 buffer_add_int (buf, *(gint8*)addr);
5711 case MONO_TYPE_CHAR:
5714 buffer_add_byte (buf, t->type);
5715 buffer_add_int (buf, *(gint16*)addr);
5720 buffer_add_byte (buf, t->type);
5721 buffer_add_int (buf, *(gint32*)addr);
5726 buffer_add_byte (buf, t->type);
5727 buffer_add_long (buf, *(gint64*)addr);
5731 /* Treat it as a vtype */
5733 case MONO_TYPE_PTR: {
5734 gssize val = *(gssize*)addr;
5736 buffer_add_byte (buf, t->type);
5737 buffer_add_long (buf, val);
5741 case MONO_TYPE_STRING:
5742 case MONO_TYPE_SZARRAY:
5743 case MONO_TYPE_OBJECT:
5744 case MONO_TYPE_CLASS:
5745 case MONO_TYPE_ARRAY:
5746 obj = *(MonoObject**)addr;
5749 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5751 if (obj->vtable->klass->valuetype) {
5752 t = &obj->vtable->klass->byval_arg;
5753 addr = mono_object_unbox (obj);
5756 } else if (obj->vtable->klass->rank) {
5757 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5758 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5759 buffer_add_byte (buf, MONO_TYPE_CLASS);
5761 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5763 buffer_add_objid (buf, obj);
5767 case MONO_TYPE_VALUETYPE:
5768 case MONO_TYPE_TYPEDBYREF: {
5772 MonoClass *klass = mono_class_from_mono_type (t);
5777 * Handle boxed vtypes recursively referencing themselves using fields.
5780 parent_vtypes = g_hash_table_new (NULL, NULL);
5781 vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
5783 if (CHECK_PROTOCOL_VERSION (2, 33)) {
5784 buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
5785 buffer_add_int (buf, vtype_index - 1);
5787 /* The client can't handle PARENT_VTYPE */
5788 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5792 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
5796 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5797 buffer_add_byte (buf, klass->enumtype);
5798 buffer_add_typeid (buf, domain, klass);
5802 while ((f = mono_class_get_fields (klass, &iter))) {
5803 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5805 if (mono_field_is_deleted (f))
5809 buffer_add_int (buf, nfields);
5812 while ((f = mono_class_get_fields (klass, &iter))) {
5813 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5815 if (mono_field_is_deleted (f))
5817 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE, parent_vtypes);
5821 g_hash_table_remove (parent_vtypes, addr);
5822 if (g_hash_table_size (parent_vtypes) == 0) {
5823 g_hash_table_destroy (parent_vtypes);
5824 parent_vtypes = NULL;
5829 case MONO_TYPE_GENERICINST:
5830 if (mono_type_generic_inst_is_valuetype (t)) {
5842 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5844 buffer_add_value_full (buf, t, addr, domain, FALSE, NULL);
5848 obj_is_of_type (MonoObject *obj, MonoType *t)
5850 MonoClass *klass = obj->vtable->klass;
5851 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5852 if (mono_class_is_transparent_proxy (klass)) {
5853 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5854 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5864 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5867 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5873 gpointer iter = NULL;
5877 is_enum = decode_byte (buf, &buf, limit);
5878 /* Enums are sent as a normal vtype */
5880 return ERR_NOT_IMPLEMENTED;
5881 klass = decode_typeid (buf, &buf, limit, &d, &err);
5885 if (t && klass != mono_class_from_mono_type (t)) {
5886 char *name = mono_type_full_name (t);
5887 char *name2 = mono_type_full_name (&klass->byval_arg);
5888 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got %s.\n", (gpointer)mono_native_thread_id_get (), name, name2);
5891 return ERR_INVALID_ARGUMENT;
5894 nfields = decode_int (buf, &buf, limit);
5895 while ((f = mono_class_get_fields (klass, &iter))) {
5896 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5898 if (mono_field_is_deleted (f))
5900 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5905 g_assert (nfields == 0);
5913 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5917 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5918 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5919 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5920 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5921 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE) &&
5922 !(t->type == MONO_TYPE_VALUETYPE && type == MONO_TYPE_OBJECT)) {
5923 char *name = mono_type_full_name (t);
5924 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)mono_native_thread_id_get (), name, type);
5926 return ERR_INVALID_ARGUMENT;
5930 case MONO_TYPE_BOOLEAN:
5931 *(guint8*)addr = decode_int (buf, &buf, limit);
5933 case MONO_TYPE_CHAR:
5934 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5937 *(gint8*)addr = decode_int (buf, &buf, limit);
5940 *(guint8*)addr = decode_int (buf, &buf, limit);
5943 *(gint16*)addr = decode_int (buf, &buf, limit);
5946 *(guint16*)addr = decode_int (buf, &buf, limit);
5949 *(gint32*)addr = decode_int (buf, &buf, limit);
5952 *(guint32*)addr = decode_int (buf, &buf, limit);
5955 *(gint64*)addr = decode_long (buf, &buf, limit);
5958 *(guint64*)addr = decode_long (buf, &buf, limit);
5961 *(guint32*)addr = decode_int (buf, &buf, limit);
5964 *(guint64*)addr = decode_long (buf, &buf, limit);
5967 /* We send these as I8, so we get them back as such */
5968 g_assert (type == MONO_TYPE_I8);
5969 *(gssize*)addr = decode_long (buf, &buf, limit);
5971 case MONO_TYPE_GENERICINST:
5972 if (MONO_TYPE_ISSTRUCT (t)) {
5973 /* The client sends these as a valuetype */
5981 /* We send these as vtypes, so we get them back as such */
5982 g_assert (type == MONO_TYPE_VALUETYPE);
5985 case MONO_TYPE_VALUETYPE:
5986 if (type == MONO_TYPE_OBJECT) {
5988 int objid = decode_objid (buf, &buf, limit);
5992 err = get_object (objid, (MonoObject**)&obj);
5996 return ERR_INVALID_ARGUMENT;
5997 if (obj->vtable->klass != mono_class_from_mono_type (t)) {
5998 DEBUG_PRINTF (1, "Expected type '%s', got object '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
5999 return ERR_INVALID_ARGUMENT;
6001 memcpy (addr, mono_object_unbox (obj), mono_class_value_size (obj->vtable->klass, NULL));
6003 err = decode_vtype (t, domain, addr, buf, &buf, limit);
6010 if (MONO_TYPE_IS_REFERENCE (t)) {
6011 if (type == MONO_TYPE_OBJECT) {
6012 int objid = decode_objid (buf, &buf, limit);
6016 err = get_object (objid, (MonoObject**)&obj);
6021 if (!obj_is_of_type (obj, t)) {
6022 DEBUG_PRINTF (1, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6023 return ERR_INVALID_ARGUMENT;
6026 if (obj && obj->vtable->domain != domain)
6027 return ERR_INVALID_ARGUMENT;
6029 mono_gc_wbarrier_generic_store (addr, obj);
6030 } else if (type == VALUE_TYPE_ID_NULL) {
6031 *(MonoObject**)addr = NULL;
6032 } else if (type == MONO_TYPE_VALUETYPE) {
6040 /* This can happen when round-tripping boxed vtypes */
6042 * Obtain vtype class.
6043 * Same as the beginning of the handle_vtype case above.
6046 is_enum = decode_byte (buf, &buf, limit);
6048 return ERR_NOT_IMPLEMENTED;
6049 klass = decode_typeid (buf, &buf, limit, &d, &err);
6053 /* Decode the vtype into a temporary buffer, then box it. */
6054 vtype_buf_size = mono_class_value_size (klass, NULL);
6055 vtype_buf = g_malloc0 (vtype_buf_size);
6056 g_assert (vtype_buf);
6059 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
6064 *(MonoObject**)addr = mono_value_box (d, klass, vtype_buf);
6067 char *name = mono_type_full_name (t);
6068 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)mono_native_thread_id_get (), name, type);
6070 return ERR_INVALID_ARGUMENT;
6084 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6087 int type = decode_byte (buf, &buf, limit);
6089 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
6090 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
6091 guint8 *nullable_buf;
6094 * First try decoding it as a Nullable`1
6096 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6101 * Then try decoding as a primitive value or null.
6103 if (targ->type == type) {
6104 nullable_buf = g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
6105 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
6107 g_free (nullable_buf);
6110 mono_nullable_init (addr, mono_value_box (domain, mono_class_from_mono_type (targ), nullable_buf), mono_class_from_mono_type (t));
6111 g_free (nullable_buf);
6114 } else if (type == VALUE_TYPE_ID_NULL) {
6115 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
6121 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6125 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
6129 guint8 *addr, *gaddr;
6132 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6133 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6136 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
6137 reg_val = mono_arch_context_get_int_reg (ctx, reg);
6139 buffer_add_value_full (buf, t, ®_val, domain, as_vtype, NULL);
6141 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6142 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6143 addr += (gint32)var->offset;
6145 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6147 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6149 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6152 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6153 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
6154 /* Same as regoffset, but with an indirection */
6155 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6156 addr += (gint32)var->offset;
6158 gaddr = *(gpointer*)addr;
6160 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL);
6162 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
6163 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
6164 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
6165 MonoGSharedVtMethodRuntimeInfo *info;
6171 g_assert (info_var);
6172 g_assert (locals_var);
6174 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6175 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6176 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6177 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6178 addr += (gint32)info_var->offset;
6179 info = *(gpointer*)addr;
6180 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6181 info = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6183 g_assert_not_reached ();
6187 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6188 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6189 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6190 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6191 addr += (gint32)locals_var->offset;
6192 locals = *(gpointer*)addr;
6193 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6194 locals = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6196 g_assert_not_reached ();
6200 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6202 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6207 g_assert_not_reached ();
6212 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
6216 guint8 *addr, *gaddr;
6218 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6219 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6221 if (MONO_TYPE_IS_REFERENCE (t))
6222 size = sizeof (gpointer);
6224 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6227 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6228 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6230 gboolean is_signed = FALSE;
6233 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6236 // FIXME: Write barriers
6237 mono_gc_memmove_atomic (addr, val, size);
6242 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6247 v = is_signed ? *(gint8*)val : *(guint8*)val;
6250 v = is_signed ? *(gint16*)val : *(guint16*)val;
6253 v = is_signed ? *(gint32*)val : *(guint32*)val;
6256 v = is_signed ? *(gint64*)val : *(guint64*)val;
6259 g_assert_not_reached ();
6262 /* Set value on the stack or in the return ctx */
6263 if (reg_locations [reg]) {
6264 /* Saved on the stack */
6265 DEBUG_PRINTF (1, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v);
6266 *(reg_locations [reg]) = v;
6269 DEBUG_PRINTF (1, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v);
6270 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6273 // FIXME: Move these to mono-context.h/c.
6274 mono_arch_context_set_int_reg (ctx, reg, v);
6276 // FIXME: Can't set registers, so we disable linears
6281 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6282 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6283 addr += (gint32)var->offset;
6285 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6288 addr = *(guint8**)addr;
6294 // FIXME: Write barriers
6295 mono_gc_memmove_atomic (addr, val, size);
6297 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6298 /* Same as regoffset, but with an indirection */
6299 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6300 addr += (gint32)var->offset;
6302 gaddr = *(gpointer*)addr;
6304 // FIXME: Write barriers
6305 mono_gc_memmove_atomic (gaddr, val, size);
6307 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6311 g_assert_not_reached ();
6316 clear_event_request (int req_id, int etype)
6320 mono_loader_lock ();
6321 for (i = 0; i < event_requests->len; ++i) {
6322 EventRequest *req = g_ptr_array_index (event_requests, i);
6324 if (req->id == req_id && req->event_kind == etype) {
6325 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6326 clear_breakpoint (req->info);
6327 if (req->event_kind == EVENT_KIND_STEP)
6328 ss_destroy (req->info);
6329 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6330 clear_breakpoint (req->info);
6331 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6332 clear_breakpoint (req->info);
6333 g_ptr_array_remove_index_fast (event_requests, i);
6338 mono_loader_unlock ();
6342 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
6346 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6347 m->kind = MOD_KIND_NONE;
6348 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6349 int count = 0, match_count = 0, pos;
6350 MonoAssembly **newassemblies;
6352 for (i = 0; m->data.assemblies [i]; ++i) {
6354 if (m->data.assemblies [i] == assembly)
6359 newassemblies = g_new0 (MonoAssembly*, count - match_count);
6362 for (i = 0; i < count; ++i)
6363 if (m->data.assemblies [i] != assembly)
6364 newassemblies [pos ++] = m->data.assemblies [i];
6365 g_assert (pos == count - match_count);
6366 g_free (m->data.assemblies);
6367 m->data.assemblies = newassemblies;
6373 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
6377 for (i = 0; i < req->nmodifiers; ++i) {
6378 Modifier *m = &req->modifiers [i];
6380 clear_assembly_from_modifier (req, m, assembly);
6385 * clear_event_requests_for_assembly:
6387 * Clear all events requests which reference ASSEMBLY.
6390 clear_event_requests_for_assembly (MonoAssembly *assembly)
6395 mono_loader_lock ();
6399 for (i = 0; i < event_requests->len; ++i) {
6400 EventRequest *req = g_ptr_array_index (event_requests, i);
6402 clear_assembly_from_modifiers (req, assembly);
6404 if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly (req->info, assembly)) {
6405 clear_event_request (req->id, req->event_kind);
6410 if (req->event_kind == EVENT_KIND_STEP)
6411 ss_clear_for_assembly (req->info, assembly);
6414 mono_loader_unlock ();
6418 * type_comes_from_assembly:
6420 * GHRFunc that returns TRUE if klass comes from assembly
6423 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6425 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6429 * clear_types_for_assembly:
6431 * Clears types from loaded_classes for a given assembly
6434 clear_types_for_assembly (MonoAssembly *assembly)
6436 MonoDomain *domain = mono_domain_get ();
6437 AgentDomainInfo *info = NULL;
6439 if (!domain || !domain_jit_info (domain))
6440 /* Can happen during shutdown */
6443 info = get_agent_domain_info (domain);
6445 mono_loader_lock ();
6446 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6447 mono_loader_unlock ();
6451 add_thread (gpointer key, gpointer value, gpointer user_data)
6453 MonoInternalThread *thread = value;
6454 Buffer *buf = user_data;
6456 buffer_add_objid (buf, (MonoObject*)thread);
6460 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6462 guint8 *end = invoke->endp;
6465 MonoMethodSignature *sig;
6468 MonoObject *this_arg, *res, *exc;
6471 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6474 MonoStopwatch watch;
6476 if (invoke->method) {
6478 * Invoke this method directly, currently only Environment.Exit () is supported.
6481 DEBUG_PRINTF (1, "[%p] Invoking method '%s' on receiver '%s'.\n", (gpointer)mono_native_thread_id_get (), mono_method_full_name (invoke->method, TRUE), this_arg ? this_arg->vtable->klass->name : "<null>");
6482 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
6483 g_assert_not_reached ();
6486 m = decode_methodid (p, &p, end, &domain, &err);
6489 sig = mono_method_signature (m);
6491 if (m->klass->valuetype)
6492 this_buf = g_alloca (mono_class_instance_size (m->klass));
6494 this_buf = g_alloca (sizeof (MonoObject*));
6495 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6496 /* Should be null */
6497 int type = decode_byte (p, &p, end);
6498 if (type != VALUE_TYPE_ID_NULL) {
6499 DEBUG_PRINTF (1, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer)mono_native_thread_id_get ());
6500 return ERR_INVALID_ARGUMENT;
6502 memset (this_buf, 0, mono_class_instance_size (m->klass));
6503 } else if (m->klass->valuetype && !strcmp (m->name, ".ctor")) {
6507 int type = decode_byte (p, &tmp_p, end);
6508 if (type == VALUE_TYPE_ID_NULL) {
6509 memset (this_buf, 0, mono_class_instance_size (m->klass));
6512 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6517 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6522 if (!m->klass->valuetype)
6523 this_arg = *(MonoObject**)this_buf;
6527 if (MONO_CLASS_IS_INTERFACE (m->klass)) {
6529 DEBUG_PRINTF (1, "[%p] Error: Interface method invoked without this argument.\n", (gpointer)mono_native_thread_id_get ());
6530 return ERR_INVALID_ARGUMENT;
6532 m = mono_object_get_virtual_method (this_arg, m);
6533 /* Transform this to the format the rest of the code expects it to be */
6534 if (m->klass->valuetype) {
6535 this_buf = g_alloca (mono_class_instance_size (m->klass));
6536 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
6538 } else if ((m->flags & METHOD_ATTRIBUTE_VIRTUAL) && !m->klass->valuetype && invoke->flags & INVOKE_FLAG_VIRTUAL) {
6540 DEBUG_PRINTF (1, "[%p] Error: invoke with INVOKE_FLAG_VIRTUAL flag set without this argument.\n", (gpointer)mono_native_thread_id_get ());
6541 return ERR_INVALID_ARGUMENT;
6543 m = mono_object_get_virtual_method (this_arg, m);
6544 if (m->klass->valuetype) {
6545 this_buf = g_alloca (mono_class_instance_size (m->klass));
6546 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
6550 DEBUG_PRINTF (1, "[%p] Invoking method '%s' on receiver '%s'.\n", (gpointer)mono_native_thread_id_get (), mono_method_full_name (m, TRUE), this_arg ? this_arg->vtable->klass->name : "<null>");
6552 if (this_arg && this_arg->vtable->domain != domain)
6555 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this_arg) {
6556 if (!strcmp (m->name, ".ctor")) {
6557 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
6558 return ERR_INVALID_ARGUMENT;
6560 this_arg = mono_object_new (domain, m->klass);
6562 return ERR_INVALID_ARGUMENT;
6566 if (this_arg && !obj_is_of_type (this_arg, &m->klass->byval_arg))
6567 return ERR_INVALID_ARGUMENT;
6569 nargs = decode_int (p, &p, end);
6570 if (nargs != sig->param_count)
6571 return ERR_INVALID_ARGUMENT;
6572 /* Use alloca to get gc tracking */
6573 arg_buf = g_alloca (nargs * sizeof (gpointer));
6574 memset (arg_buf, 0, nargs * sizeof (gpointer));
6575 args = g_alloca (nargs * sizeof (gpointer));
6576 for (i = 0; i < nargs; ++i) {
6577 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6578 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6581 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6584 if (sig->params [i]->byref) {
6585 arg_buf [i] = g_alloca (sizeof (mgreg_t));
6586 *(gpointer*)arg_buf [i] = args [i];
6587 args [i] = arg_buf [i];
6590 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6591 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6594 args [i] = arg_buf [i];
6601 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6602 tls->disable_breakpoints = TRUE;
6604 tls->disable_breakpoints = FALSE;
6607 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6609 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6610 if (invoke->has_ctx) {
6613 lmf_addr = mono_get_lmf_addr ();
6616 memset (&ext, 0, sizeof (ext));
6617 mono_arch_init_lmf_ext (&ext, *lmf_addr);
6619 ext.debugger_invoke = TRUE;
6620 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6622 mono_set_lmf ((MonoLMF*)&ext);
6626 mono_stopwatch_start (&watch);
6627 if (m->klass->valuetype)
6628 res = mono_runtime_invoke (m, this_buf, args, &exc);
6630 res = mono_runtime_invoke (m, this_arg, args, &exc);
6631 mono_stopwatch_stop (&watch);
6632 DEBUG_PRINTF (1, "[%p] Invoke result: %p, exc: %s, time: %ld ms.\n", (gpointer)mono_native_thread_id_get (), res, exc ? exc->vtable->klass->name : NULL, (long)mono_stopwatch_elapsed_ms (&watch));
6634 buffer_add_byte (buf, 0);
6635 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6637 gboolean out_this = FALSE;
6638 gboolean out_args = FALSE;
6640 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_THIS) && CHECK_PROTOCOL_VERSION (2, 35))
6642 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_ARGS) && CHECK_PROTOCOL_VERSION (2, 35))
6644 buffer_add_byte (buf, 1 + (out_this ? 2 : 0) + (out_args ? 4 : 0));
6645 if (sig->ret->type == MONO_TYPE_VOID) {
6646 if (!strcmp (m->name, ".ctor")) {
6647 if (!m->klass->valuetype)
6648 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this_arg, domain);
6650 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
6652 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6654 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6655 buffer_add_value (buf, sig->ret, &res, domain);
6656 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6657 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6658 MonoClass *k = mono_class_from_mono_type (sig->ret);
6659 guint8 *nullable_buf = g_alloca (mono_class_value_size (k, NULL));
6661 g_assert (nullable_buf);
6662 mono_nullable_init (nullable_buf, res, k);
6663 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6666 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6672 /* Return the new value of the receiver after the call */
6673 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
6675 buffer_add_int (buf, nargs);
6676 for (i = 0; i < nargs; ++i) {
6677 if (MONO_TYPE_IS_REFERENCE (sig->params [i]))
6678 buffer_add_value (buf, sig->params [i], &args [i], domain);
6679 else if (sig->params [i]->byref)
6680 /* add_value () does an indirection */
6681 buffer_add_value (buf, sig->params [i], &arg_buf [i], domain);
6683 buffer_add_value (buf, sig->params [i], arg_buf [i], domain);
6688 tls->disable_breakpoints = FALSE;
6690 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6691 if (invoke->has_ctx)
6692 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
6696 // FIXME: byref arguments
6704 * Invoke the method given by tls->pending_invoke in the current thread.
6707 invoke_method (void)
6709 DebuggerTlsData *tls;
6714 MonoContext restore_ctx;
6717 tls = mono_native_tls_get_value (debugger_tls_id);
6721 * Store the `InvokeData *' in `tls->invoke' until we're done with
6722 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6725 mono_loader_lock ();
6727 invoke = tls->pending_invoke;
6729 tls->pending_invoke = NULL;
6731 invoke->last_invoke = tls->invoke;
6732 tls->invoke = invoke;
6734 mono_loader_unlock ();
6736 tls->frames_up_to_date = FALSE;
6742 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6743 buffer_init (&buf, 128);
6746 /* Fail the other invokes as well */
6748 err = do_invoke_method (tls, &buf, invoke, p, &p);
6751 if (tls->abort_requested) {
6752 if (CHECK_PROTOCOL_VERSION (2, 42))
6753 err = ERR_INVOKE_ABORTED;
6756 /* Start suspending before sending the reply */
6757 if (mindex == invoke->nmethods - 1) {
6758 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6759 for (i = 0; i < invoke->suspend_count; ++i)
6764 send_reply_packet (id, err, &buf);
6769 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6771 if (invoke->has_ctx)
6772 save_thread_context (&restore_ctx);
6774 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6775 g_assert (tls->resume_count);
6776 tls->resume_count -= invoke->suspend_count;
6779 DEBUG_PRINTF (1, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer)mono_native_thread_id_get (), err, tls->resume_count);
6782 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6784 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
6785 * after the mono_runtime_invoke() already returned, but it doesn't matter
6786 * because we reset the abort here.
6789 mono_loader_lock ();
6791 if (tls->abort_requested)
6792 mono_thread_internal_reset_abort (tls->thread);
6794 tls->invoke = tls->invoke->last_invoke;
6795 tls->abort_requested = FALSE;
6797 mono_loader_unlock ();
6806 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6808 MonoThread *thread = value;
6809 DebuggerTlsData *tls;
6812 mono_loader_lock ();
6813 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6815 res = tls->really_suspended;
6816 mono_loader_unlock ();
6822 get_source_files_for_type (MonoClass *klass)
6824 gpointer iter = NULL;
6826 MonoDebugSourceInfo *sinfo;
6830 files = g_ptr_array_new ();
6832 while ((method = mono_class_get_methods (klass, &iter))) {
6833 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6834 GPtrArray *source_file_list;
6837 mono_debug_get_seq_points (minfo, NULL, &source_file_list, NULL, NULL, NULL);
6838 for (j = 0; j < source_file_list->len; ++j) {
6839 sinfo = g_ptr_array_index (source_file_list, j);
6840 for (i = 0; i < files->len; ++i)
6841 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6843 if (i == files->len)
6844 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6846 g_ptr_array_free (source_file_list, TRUE);
6854 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6857 case CMD_VM_VERSION: {
6858 char *build_info, *version;
6860 build_info = mono_get_runtime_build_info ();
6861 version = g_strdup_printf ("mono %s", build_info);
6863 buffer_add_string (buf, version); /* vm version */
6864 buffer_add_int (buf, MAJOR_VERSION);
6865 buffer_add_int (buf, MINOR_VERSION);
6866 g_free (build_info);
6870 case CMD_VM_SET_PROTOCOL_VERSION: {
6871 major_version = decode_int (p, &p, end);
6872 minor_version = decode_int (p, &p, end);
6873 protocol_version_set = TRUE;
6874 DEBUG_PRINTF (1, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version);
6877 case CMD_VM_ALL_THREADS: {
6879 mono_loader_lock ();
6880 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6881 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6882 mono_loader_unlock ();
6885 case CMD_VM_SUSPEND:
6887 wait_for_suspend ();
6890 if (suspend_count == 0)
6891 return ERR_NOT_SUSPENDED;
6893 clear_suspended_objs ();
6895 case CMD_VM_DISPOSE:
6896 /* Clear all event requests */
6897 mono_loader_lock ();
6898 while (event_requests->len > 0) {
6899 EventRequest *req = g_ptr_array_index (event_requests, 0);
6901 clear_event_request (req->id, req->event_kind);
6903 mono_loader_unlock ();
6905 while (suspend_count > 0)
6907 disconnected = TRUE;
6908 vm_start_event_sent = FALSE;
6911 MonoInternalThread *thread;
6912 DebuggerTlsData *tls;
6913 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6914 MonoClass *env_class;
6916 MonoMethod *exit_method = NULL;
6920 exit_code = decode_int (p, &p, end);
6922 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6924 /* Have to send a reply before exiting */
6925 send_reply_packet (id, 0, buf);
6927 /* Clear all event requests */
6928 mono_loader_lock ();
6929 while (event_requests->len > 0) {
6930 EventRequest *req = g_ptr_array_index (event_requests, 0);
6932 clear_event_request (req->id, req->event_kind);
6934 mono_loader_unlock ();
6937 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6938 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6939 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6940 * better than doing the shutdown ourselves, since it avoids various races.
6944 wait_for_suspend ();
6946 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6947 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
6949 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6952 mono_loader_lock ();
6953 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6954 mono_loader_unlock ();
6956 if (thread && exit_method) {
6957 mono_loader_lock ();
6958 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6959 mono_loader_unlock ();
6961 args = g_new0 (gpointer, 1);
6962 args [0] = g_malloc (sizeof (int));
6963 *(int*)(args [0]) = exit_code;
6965 tls->pending_invoke = g_new0 (InvokeData, 1);
6966 tls->pending_invoke->method = exit_method;
6967 tls->pending_invoke->args = args;
6968 tls->pending_invoke->nmethods = 1;
6970 while (suspend_count > 0)
6974 * No thread found, do it ourselves.
6975 * FIXME: This can race with normal shutdown etc.
6977 while (suspend_count > 0)
6980 if (!mono_runtime_try_shutdown ())
6983 mono_environment_exitcode_set (exit_code);
6985 /* Suspend all managed threads since the runtime is going away */
6986 DEBUG_PRINTF (1, "Suspending all threads...\n");
6987 mono_thread_suspend_all_other_threads ();
6988 DEBUG_PRINTF (1, "Shutting down the runtime...\n");
6989 mono_runtime_quit ();
6990 transport_close2 ();
6991 DEBUG_PRINTF (1, "Exiting...\n");
6997 case CMD_VM_INVOKE_METHOD:
6998 case CMD_VM_INVOKE_METHODS: {
6999 int objid = decode_objid (p, &p, end);
7001 DebuggerTlsData *tls;
7002 int i, count, err, flags, nmethods;
7004 err = get_object (objid, (MonoObject**)&thread);
7008 flags = decode_int (p, &p, end);
7010 if (command == CMD_VM_INVOKE_METHODS)
7011 nmethods = decode_int (p, &p, end);
7015 // Wait for suspending if it already started
7017 wait_for_suspend ();
7018 if (!is_suspended ())
7019 return ERR_NOT_SUSPENDED;
7021 mono_loader_lock ();
7022 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7023 mono_loader_unlock ();
7026 if (!tls->really_suspended)
7027 /* The thread is still running native code, can't do invokes */
7028 return ERR_NOT_SUSPENDED;
7031 * Store the invoke data into tls, the thread will execute it after it is
7034 if (tls->pending_invoke)
7035 return ERR_NOT_SUSPENDED;
7036 tls->pending_invoke = g_new0 (InvokeData, 1);
7037 tls->pending_invoke->id = id;
7038 tls->pending_invoke->flags = flags;
7039 tls->pending_invoke->p = g_malloc (end - p);
7040 memcpy (tls->pending_invoke->p, p, end - p);
7041 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
7042 tls->pending_invoke->suspend_count = suspend_count;
7043 tls->pending_invoke->nmethods = nmethods;
7045 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
7046 resume_thread (THREAD_TO_INTERNAL (thread));
7049 count = suspend_count;
7050 for (i = 0; i < count; ++i)
7055 case CMD_VM_ABORT_INVOKE: {
7056 int objid = decode_objid (p, &p, end);
7058 DebuggerTlsData *tls;
7061 err = get_object (objid, (MonoObject**)&thread);
7065 invoke_id = decode_int (p, &p, end);
7067 mono_loader_lock ();
7068 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7071 if (tls->abort_requested) {
7072 DEBUG_PRINTF (1, "Abort already requested.\n");
7073 mono_loader_unlock ();
7078 * Check whether we're still inside the mono_runtime_invoke() and that it's
7079 * actually the correct invocation.
7081 * Careful, we do not stop the thread that's doing the invocation, so we can't
7082 * inspect its stack. However, invoke_method() also acquires the loader lock
7083 * when it's done, so we're safe here.
7087 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
7088 mono_loader_unlock ();
7089 return ERR_NO_INVOCATION;
7092 tls->abort_requested = TRUE;
7094 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
7095 mono_loader_unlock ();
7099 case CMD_VM_SET_KEEPALIVE: {
7100 int timeout = decode_int (p, &p, end);
7101 agent_config.keepalive = timeout;
7103 #ifndef DISABLE_SOCKET_TRANSPORT
7110 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
7111 GHashTableIter iter, kiter;
7116 char *fname, *basename;
7117 gboolean ignore_case;
7118 GSList *class_list, *l;
7119 GPtrArray *res_classes, *res_domains;
7121 fname = decode_string (p, &p, end);
7122 ignore_case = decode_byte (p, &p, end);
7124 basename = dbg_path_get_basename (fname);
7126 res_classes = g_ptr_array_new ();
7127 res_domains = g_ptr_array_new ();
7129 mono_loader_lock ();
7130 g_hash_table_iter_init (&iter, domains);
7131 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7132 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
7134 /* Update 'source_file_to_class' cache */
7135 g_hash_table_iter_init (&kiter, info->loaded_classes);
7136 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
7137 if (!g_hash_table_lookup (info->source_files, klass)) {
7138 files = get_source_files_for_type (klass);
7139 g_hash_table_insert (info->source_files, klass, files);
7141 for (i = 0; i < files->len; ++i) {
7142 char *s = g_ptr_array_index (files, i);
7143 char *s2 = dbg_path_get_basename (s);
7146 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
7148 class_list = g_slist_prepend (class_list, klass);
7149 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
7151 class_list = g_slist_prepend (class_list, klass);
7152 g_hash_table_insert (info->source_file_to_class, s2, class_list);
7155 /* The _ignorecase hash contains the lowercase path */
7156 s3 = strdup_tolower (s2);
7157 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
7159 class_list = g_slist_prepend (class_list, klass);
7160 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
7162 class_list = g_slist_prepend (class_list, klass);
7163 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
7175 s = strdup_tolower (basename);
7176 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
7179 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
7182 for (l = class_list; l; l = l->next) {
7185 g_ptr_array_add (res_classes, klass);
7186 g_ptr_array_add (res_domains, domain);
7189 mono_loader_unlock ();
7194 buffer_add_int (buf, res_classes->len);
7195 for (i = 0; i < res_classes->len; ++i)
7196 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
7197 g_ptr_array_free (res_classes, TRUE);
7198 g_ptr_array_free (res_domains, TRUE);
7201 case CMD_VM_GET_TYPES: {
7202 GHashTableIter iter;
7206 gboolean ignore_case;
7207 GPtrArray *res_classes, *res_domains;
7208 MonoTypeNameParse info;
7210 name = decode_string (p, &p, end);
7211 ignore_case = decode_byte (p, &p, end);
7213 if (!mono_reflection_parse_type (name, &info)) {
7215 mono_reflection_free_type_info (&info);
7216 return ERR_INVALID_ARGUMENT;
7219 res_classes = g_ptr_array_new ();
7220 res_domains = g_ptr_array_new ();
7222 mono_loader_lock ();
7223 g_hash_table_iter_init (&iter, domains);
7224 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7226 gboolean type_resolve;
7230 mono_domain_assemblies_lock (domain);
7231 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7235 type_resolve = TRUE;
7236 t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
7238 g_ptr_array_add (res_classes, mono_type_get_class (t));
7239 g_ptr_array_add (res_domains, domain);
7243 mono_domain_assemblies_unlock (domain);
7245 mono_loader_unlock ();
7248 mono_reflection_free_type_info (&info);
7250 buffer_add_int (buf, res_classes->len);
7251 for (i = 0; i < res_classes->len; ++i)
7252 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
7253 g_ptr_array_free (res_classes, TRUE);
7254 g_ptr_array_free (res_domains, TRUE);
7257 case CMD_VM_START_BUFFERING:
7258 case CMD_VM_STOP_BUFFERING:
7259 /* Handled in the main loop */
7262 return ERR_NOT_IMPLEMENTED;
7269 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7275 case CMD_EVENT_REQUEST_SET: {
7277 int i, event_kind, suspend_policy, nmodifiers, mod;
7280 MonoThread *step_thread;
7281 int size = 0, depth = 0, filter = 0, step_thread_id = 0;
7285 event_kind = decode_byte (p, &p, end);
7286 suspend_policy = decode_byte (p, &p, end);
7287 nmodifiers = decode_byte (p, &p, end);
7289 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7290 req->id = InterlockedIncrement (&event_request_id);
7291 req->event_kind = event_kind;
7292 req->suspend_policy = suspend_policy;
7293 req->nmodifiers = nmodifiers;
7296 for (i = 0; i < nmodifiers; ++i) {
7297 mod = decode_byte (p, &p, end);
7299 req->modifiers [i].kind = mod;
7300 if (mod == MOD_KIND_COUNT) {
7301 req->modifiers [i].data.count = decode_int (p, &p, end);
7302 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7303 method = decode_methodid (p, &p, end, &domain, &err);
7306 location = decode_long (p, &p, end);
7307 } else if (mod == MOD_KIND_STEP) {
7308 step_thread_id = decode_id (p, &p, end);
7309 size = decode_int (p, &p, end);
7310 depth = decode_int (p, &p, end);
7311 if (CHECK_PROTOCOL_VERSION (2, 16))
7312 filter = decode_int (p, &p, end);
7313 req->modifiers [i].data.filter = filter;
7314 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7315 /* Treat STEP_THOUGH the same as HIDDEN */
7316 req->modifiers [i].data.filter |= STEP_FILTER_DEBUGGER_STEP_THROUGH;
7317 } else if (mod == MOD_KIND_THREAD_ONLY) {
7318 int id = decode_id (p, &p, end);
7320 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7325 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7326 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7330 req->modifiers [i].caught = decode_byte (p, &p, end);
7331 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7332 if (CHECK_PROTOCOL_VERSION (2, 25))
7333 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7335 req->modifiers [i].subclasses = TRUE;
7336 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" : "");
7338 req->modifiers [i].data.exc_class = exc_class;
7340 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
7342 return ERR_INVALID_ARGUMENT;
7345 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7346 int n = decode_int (p, &p, end);
7349 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
7350 for (j = 0; j < n; ++j) {
7351 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7353 g_free (req->modifiers [i].data.assemblies);
7357 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7358 int n = decode_int (p, &p, end);
7361 modifier = &req->modifiers [i];
7362 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7363 for (j = 0; j < n; ++j) {
7364 char *s = decode_string (p, &p, end);
7368 s2 = strdup_tolower (s);
7369 g_hash_table_insert (modifier->data.source_files, s2, s2);
7373 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7374 int n = decode_int (p, &p, end);
7377 modifier = &req->modifiers [i];
7378 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7379 for (j = 0; j < n; ++j) {
7380 char *s = decode_string (p, &p, end);
7383 g_hash_table_insert (modifier->data.type_names, s, s);
7387 return ERR_NOT_IMPLEMENTED;
7391 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7394 req->info = set_breakpoint (method, location, req, &error);
7395 if (!mono_error_ok (&error)) {
7397 DEBUG_PRINTF (1, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error));
7398 mono_error_cleanup (&error);
7399 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7401 } else if (req->event_kind == EVENT_KIND_STEP) {
7402 g_assert (step_thread_id);
7404 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7410 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, filter, req);
7415 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7416 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7417 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7418 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7419 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7420 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7422 if (req->nmodifiers) {
7424 return ERR_NOT_IMPLEMENTED;
7428 mono_loader_lock ();
7429 g_ptr_array_add (event_requests, req);
7431 if (agent_config.defer) {
7432 /* Transmit cached data to the client on receipt of the event request */
7433 switch (req->event_kind) {
7434 case EVENT_KIND_APPDOMAIN_CREATE:
7435 /* Emit load events for currently loaded domains */
7436 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7438 case EVENT_KIND_ASSEMBLY_LOAD:
7439 /* Emit load events for currently loaded assemblies */
7440 mono_assembly_foreach (emit_assembly_load, NULL);
7442 case EVENT_KIND_THREAD_START:
7443 /* Emit start events for currently started threads */
7444 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7446 case EVENT_KIND_TYPE_LOAD:
7447 /* Emit type load events for currently loaded types */
7448 mono_domain_foreach (send_types_for_domain, NULL);
7454 mono_loader_unlock ();
7456 buffer_add_int (buf, req->id);
7459 case CMD_EVENT_REQUEST_CLEAR: {
7460 int etype = decode_byte (p, &p, end);
7461 int req_id = decode_int (p, &p, end);
7463 // FIXME: Make a faster mapping from req_id to request
7464 mono_loader_lock ();
7465 clear_event_request (req_id, etype);
7466 mono_loader_unlock ();
7469 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7472 mono_loader_lock ();
7474 while (i < event_requests->len) {
7475 EventRequest *req = g_ptr_array_index (event_requests, i);
7477 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7478 clear_breakpoint (req->info);
7480 g_ptr_array_remove_index_fast (event_requests, i);
7486 mono_loader_unlock ();
7490 return ERR_NOT_IMPLEMENTED;
7497 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7503 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7504 buffer_add_domainid (buf, mono_get_root_domain ());
7507 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7508 domain = decode_domainid (p, &p, end, NULL, &err);
7511 buffer_add_string (buf, domain->friendly_name);
7514 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7519 domain = decode_domainid (p, &p, end, NULL, &err);
7522 mono_loader_lock ();
7524 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7527 buffer_add_int (buf, count);
7528 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7530 buffer_add_assemblyid (buf, domain, ass);
7532 mono_loader_unlock ();
7535 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7536 domain = decode_domainid (p, &p, end, NULL, &err);
7540 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7543 case CMD_APPDOMAIN_GET_CORLIB: {
7544 domain = decode_domainid (p, &p, end, NULL, &err);
7548 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7551 case CMD_APPDOMAIN_CREATE_STRING: {
7555 domain = decode_domainid (p, &p, end, NULL, &err);
7558 s = decode_string (p, &p, end);
7560 o = mono_string_new (domain, s);
7561 buffer_add_objid (buf, (MonoObject*)o);
7564 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7566 MonoDomain *domain2;
7569 domain = decode_domainid (p, &p, end, NULL, &err);
7572 klass = decode_typeid (p, &p, end, &domain2, &err);
7577 g_assert (domain == domain2);
7579 o = mono_object_new (domain, klass);
7581 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
7585 buffer_add_objid (buf, o);
7589 return ERR_NOT_IMPLEMENTED;
7596 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7602 ass = decode_assemblyid (p, &p, end, &domain, &err);
7607 case CMD_ASSEMBLY_GET_LOCATION: {
7608 buffer_add_string (buf, mono_image_get_filename (ass->image));
7611 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7615 if (ass->image->dynamic) {
7616 buffer_add_id (buf, 0);
7618 token = mono_image_get_entry_point (ass->image);
7620 buffer_add_id (buf, 0);
7622 m = mono_get_method (ass->image, token, NULL);
7623 buffer_add_methodid (buf, domain, m);
7628 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7629 buffer_add_moduleid (buf, domain, ass->image);
7632 case CMD_ASSEMBLY_GET_OBJECT: {
7633 MonoObject *o = (MonoObject*)mono_assembly_get_object (domain, ass);
7634 buffer_add_objid (buf, o);
7637 case CMD_ASSEMBLY_GET_TYPE: {
7638 char *s = decode_string (p, &p, end);
7639 gboolean ignorecase = decode_byte (p, &p, end);
7640 MonoTypeNameParse info;
7642 gboolean type_resolve, res;
7643 MonoDomain *d = mono_domain_get ();
7645 /* This is needed to be able to find referenced assemblies */
7646 res = mono_domain_set (domain, FALSE);
7649 if (!mono_reflection_parse_type (s, &info)) {
7652 if (info.assembly.name)
7654 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
7656 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
7657 mono_reflection_free_type_info (&info);
7660 mono_domain_set (d, TRUE);
7664 case CMD_ASSEMBLY_GET_NAME: {
7666 MonoAssembly *mass = ass;
7668 name = g_strdup_printf (
7669 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7671 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7672 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7673 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7674 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7676 buffer_add_string (buf, name);
7681 return ERR_NOT_IMPLEMENTED;
7688 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7694 case CMD_MODULE_GET_INFO: {
7695 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7698 basename = g_path_get_basename (image->name);
7699 buffer_add_string (buf, basename); // name
7700 buffer_add_string (buf, image->module_name); // scopename
7701 buffer_add_string (buf, image->name); // fqname
7702 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7703 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7708 return ERR_NOT_IMPLEMENTED;
7715 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7721 case CMD_FIELD_GET_INFO: {
7722 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
7724 buffer_add_string (buf, f->name);
7725 buffer_add_typeid (buf, domain, f->parent);
7726 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7727 buffer_add_int (buf, f->type->attrs);
7731 return ERR_NOT_IMPLEMENTED;
7738 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7740 if (val && val->vtable->klass == mono_defaults.monotype_class) {
7741 /* Special case these so the client doesn't have to handle Type objects */
7743 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7744 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7745 } else if (MONO_TYPE_IS_REFERENCE (t))
7746 buffer_add_value (buf, t, &val, domain);
7748 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7752 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7758 buffer_add_int (buf, 0);
7762 for (i = 0; i < cinfo->num_attrs; ++i) {
7763 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7766 buffer_add_int (buf, nattrs);
7768 for (i = 0; i < cinfo->num_attrs; ++i) {
7769 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7770 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7771 MonoArray *typed_args, *named_args;
7773 CattrNamedArg *arginfo = NULL;
7776 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
7777 if (!mono_error_ok (&error)) {
7778 DEBUG_PRINTF (2, "[dbg] mono_reflection_create_custom_attr_data_args () failed with: '%s'\n", mono_error_get_message (&error));
7779 mono_error_cleanup (&error);
7780 return ERR_LOADER_ERROR;
7783 buffer_add_methodid (buf, domain, attr->ctor);
7787 buffer_add_int (buf, mono_array_length (typed_args));
7788 for (j = 0; j < mono_array_length (typed_args); ++j) {
7789 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7791 t = mono_method_signature (attr->ctor)->params [j];
7793 buffer_add_cattr_arg (buf, t, domain, val);
7796 buffer_add_int (buf, 0);
7801 buffer_add_int (buf, mono_array_length (named_args));
7803 for (j = 0; j < mono_array_length (named_args); ++j) {
7804 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7806 if (arginfo [j].prop) {
7807 buffer_add_byte (buf, 0x54);
7808 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7809 } else if (arginfo [j].field) {
7810 buffer_add_byte (buf, 0x53);
7811 buffer_add_fieldid (buf, domain, arginfo [j].field);
7813 g_assert_not_reached ();
7816 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7819 buffer_add_int (buf, 0);
7828 /* FIXME: Code duplication with icall.c */
7830 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7835 mono_class_setup_interfaces (klass, error);
7836 if (!mono_error_ok (error))
7839 for (i = 0; i < klass->interface_count; i++) {
7840 ic = klass->interfaces [i];
7841 g_hash_table_insert (ifaces, ic, ic);
7843 collect_interfaces (ic, ifaces, error);
7844 if (!mono_error_ok (error))
7850 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7860 case CMD_TYPE_GET_INFO: {
7861 buffer_add_string (buf, klass->name_space);
7862 buffer_add_string (buf, klass->name);
7864 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7865 buffer_add_string (buf, name);
7867 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7868 buffer_add_moduleid (buf, domain, klass->image);
7869 buffer_add_typeid (buf, domain, klass->parent);
7870 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7871 buffer_add_typeid (buf, domain, klass->element_class);
7873 buffer_add_id (buf, 0);
7874 buffer_add_int (buf, klass->type_token);
7875 buffer_add_byte (buf, klass->rank);
7876 buffer_add_int (buf, klass->flags);
7878 type = &klass->byval_arg;
7879 // FIXME: Can't decide whenever a class represents a byref type
7882 if (type->type == MONO_TYPE_PTR)
7884 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7886 if (type->type == MONO_TYPE_VALUETYPE)
7888 if (klass->enumtype)
7890 if (klass->generic_container)
7892 if (klass->generic_container || klass->generic_class)
7894 buffer_add_byte (buf, b);
7897 while ((nested = mono_class_get_nested_types (klass, &iter)))
7899 buffer_add_int (buf, nnested);
7901 while ((nested = mono_class_get_nested_types (klass, &iter)))
7902 buffer_add_typeid (buf, domain, nested);
7903 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7904 if (klass->generic_container)
7905 buffer_add_typeid (buf, domain, klass);
7906 else if (klass->generic_class)
7907 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7909 buffer_add_id (buf, 0);
7911 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7914 if (klass->generic_class) {
7915 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7917 count = inst->type_argc;
7918 buffer_add_int (buf, count);
7919 for (i = 0; i < count; i++)
7920 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7921 } else if (klass->generic_container) {
7922 MonoGenericContainer *container = klass->generic_container;
7925 count = container->type_argc;
7926 buffer_add_int (buf, count);
7927 for (i = 0; i < count; i++) {
7928 pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
7929 buffer_add_typeid (buf, domain, pklass);
7932 buffer_add_int (buf, 0);
7937 case CMD_TYPE_GET_METHODS: {
7940 gpointer iter = NULL;
7943 mono_class_setup_methods (klass);
7945 nmethods = mono_class_num_methods (klass);
7947 buffer_add_int (buf, nmethods);
7949 while ((m = mono_class_get_methods (klass, &iter))) {
7950 buffer_add_methodid (buf, domain, m);
7953 g_assert (i == nmethods);
7956 case CMD_TYPE_GET_FIELDS: {
7959 gpointer iter = NULL;
7962 nfields = mono_class_num_fields (klass);
7964 buffer_add_int (buf, nfields);
7966 while ((f = mono_class_get_fields (klass, &iter))) {
7967 buffer_add_fieldid (buf, domain, f);
7968 buffer_add_string (buf, f->name);
7969 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7970 buffer_add_int (buf, f->type->attrs);
7973 g_assert (i == nfields);
7976 case CMD_TYPE_GET_PROPERTIES: {
7979 gpointer iter = NULL;
7982 nprops = mono_class_num_properties (klass);
7984 buffer_add_int (buf, nprops);
7986 while ((p = mono_class_get_properties (klass, &iter))) {
7987 buffer_add_propertyid (buf, domain, p);
7988 buffer_add_string (buf, p->name);
7989 buffer_add_methodid (buf, domain, p->get);
7990 buffer_add_methodid (buf, domain, p->set);
7991 buffer_add_int (buf, p->attrs);
7994 g_assert (i == nprops);
7997 case CMD_TYPE_GET_CATTRS: {
7998 MonoClass *attr_klass;
7999 MonoCustomAttrInfo *cinfo;
8001 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8002 /* attr_klass can be NULL */
8006 cinfo = mono_custom_attrs_from_class (klass);
8008 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8013 case CMD_TYPE_GET_FIELD_CATTRS: {
8014 MonoClass *attr_klass;
8015 MonoCustomAttrInfo *cinfo;
8016 MonoClassField *field;
8018 field = decode_fieldid (p, &p, end, NULL, &err);
8021 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8025 cinfo = mono_custom_attrs_from_field (klass, field);
8027 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8032 case CMD_TYPE_GET_PROPERTY_CATTRS: {
8033 MonoClass *attr_klass;
8034 MonoCustomAttrInfo *cinfo;
8037 prop = decode_propertyid (p, &p, end, NULL, &err);
8040 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8044 cinfo = mono_custom_attrs_from_property (klass, prop);
8046 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8051 case CMD_TYPE_GET_VALUES:
8052 case CMD_TYPE_GET_VALUES_2: {
8059 MonoThread *thread_obj;
8060 MonoInternalThread *thread = NULL;
8061 guint32 special_static_type;
8063 if (command == CMD_TYPE_GET_VALUES_2) {
8064 int objid = decode_objid (p, &p, end);
8067 err = get_object (objid, (MonoObject**)&thread_obj);
8071 thread = THREAD_TO_INTERNAL (thread_obj);
8074 len = decode_int (p, &p, end);
8075 for (i = 0; i < len; ++i) {
8076 f = decode_fieldid (p, &p, end, NULL, &err);
8080 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8081 return ERR_INVALID_FIELDID;
8082 special_static_type = mono_class_field_get_special_static_type (f);
8083 if (special_static_type != SPECIAL_STATIC_NONE) {
8084 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
8085 return ERR_INVALID_FIELDID;
8088 /* Check that the field belongs to the object */
8090 for (k = klass; k; k = k->parent) {
8091 if (k == f->parent) {
8097 return ERR_INVALID_FIELDID;
8099 vtable = mono_class_vtable (domain, f->parent);
8100 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8101 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
8102 buffer_add_value (buf, f->type, val, domain);
8107 case CMD_TYPE_SET_VALUES: {
8115 len = decode_int (p, &p, end);
8116 for (i = 0; i < len; ++i) {
8117 f = decode_fieldid (p, &p, end, NULL, &err);
8121 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8122 return ERR_INVALID_FIELDID;
8123 if (mono_class_field_is_special_static (f))
8124 return ERR_INVALID_FIELDID;
8126 /* Check that the field belongs to the object */
8128 for (k = klass; k; k = k->parent) {
8129 if (k == f->parent) {
8135 return ERR_INVALID_FIELDID;
8137 // FIXME: Check for literal/const
8139 vtable = mono_class_vtable (domain, f->parent);
8140 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8141 err = decode_value (f->type, domain, val, p, &p, end);
8146 if (MONO_TYPE_IS_REFERENCE (f->type))
8147 mono_field_static_set_value (vtable, f, *(gpointer*)val);
8149 mono_field_static_set_value (vtable, f, val);
8154 case CMD_TYPE_GET_OBJECT: {
8155 MonoObject *o = (MonoObject*)mono_type_get_object (domain, &klass->byval_arg);
8156 buffer_add_objid (buf, o);
8159 case CMD_TYPE_GET_SOURCE_FILES:
8160 case CMD_TYPE_GET_SOURCE_FILES_2: {
8161 char *source_file, *base;
8165 files = get_source_files_for_type (klass);
8167 buffer_add_int (buf, files->len);
8168 for (i = 0; i < files->len; ++i) {
8169 source_file = g_ptr_array_index (files, i);
8170 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8171 buffer_add_string (buf, source_file);
8173 base = dbg_path_get_basename (source_file);
8174 buffer_add_string (buf, base);
8177 g_free (source_file);
8179 g_ptr_array_free (files, TRUE);
8182 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8183 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8187 if (mono_class_is_assignable_from (klass, oklass))
8188 buffer_add_byte (buf, 1);
8190 buffer_add_byte (buf, 0);
8193 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8194 char *name = decode_string (p, &p, end);
8195 int i, flags = decode_int (p, &p, end);
8196 MonoException *ex = NULL;
8197 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
8200 return ERR_LOADER_ERROR;
8201 buffer_add_int (buf, array->len);
8202 for (i = 0; i < array->len; ++i) {
8203 MonoMethod *method = g_ptr_array_index (array, i);
8204 buffer_add_methodid (buf, domain, method);
8207 g_ptr_array_free (array, TRUE);
8211 case CMD_TYPE_GET_INTERFACES: {
8213 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8215 MonoClass *tclass, *iface;
8216 GHashTableIter iter;
8220 for (parent = tclass; parent; parent = parent->parent) {
8221 mono_class_setup_interfaces (parent, &error);
8222 if (!mono_error_ok (&error))
8223 return ERR_LOADER_ERROR;
8224 collect_interfaces (parent, iface_hash, &error);
8225 if (!mono_error_ok (&error))
8226 return ERR_LOADER_ERROR;
8229 buffer_add_int (buf, g_hash_table_size (iface_hash));
8231 g_hash_table_iter_init (&iter, iface_hash);
8232 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8233 buffer_add_typeid (buf, domain, iface);
8234 g_hash_table_destroy (iface_hash);
8237 case CMD_TYPE_GET_INTERFACE_MAP: {
8238 int tindex, ioffset;
8239 gboolean variance_used;
8241 int len, nmethods, i;
8245 len = decode_int (p, &p, end);
8246 mono_class_setup_vtable (klass);
8248 for (tindex = 0; tindex < len; ++tindex) {
8249 iclass = decode_typeid (p, &p, end, NULL, &err);
8253 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8255 return ERR_INVALID_ARGUMENT;
8257 nmethods = mono_class_num_methods (iclass);
8258 buffer_add_int (buf, nmethods);
8261 while ((method = mono_class_get_methods (iclass, &iter))) {
8262 buffer_add_methodid (buf, domain, method);
8264 for (i = 0; i < nmethods; ++i)
8265 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
8269 case CMD_TYPE_IS_INITIALIZED: {
8270 MonoVTable *vtable = mono_class_vtable (domain, klass);
8273 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8275 buffer_add_int (buf, 0);
8278 case CMD_TYPE_CREATE_INSTANCE: {
8281 obj = mono_object_new (domain, klass);
8282 buffer_add_objid (buf, obj);
8286 return ERR_NOT_IMPLEMENTED;
8293 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8296 MonoDomain *old_domain;
8300 klass = decode_typeid (p, &p, end, &domain, &err);
8304 old_domain = mono_domain_get ();
8306 mono_domain_set (domain, TRUE);
8308 err = type_commands_internal (command, klass, domain, p, end, buf);
8310 mono_domain_set (old_domain, TRUE);
8316 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8318 MonoMethodHeader *header;
8322 case CMD_METHOD_GET_NAME: {
8323 buffer_add_string (buf, method->name);
8326 case CMD_METHOD_GET_DECLARING_TYPE: {
8327 buffer_add_typeid (buf, domain, method->klass);
8330 case CMD_METHOD_GET_DEBUG_INFO: {
8331 MonoDebugMethodInfo *minfo;
8333 int i, j, n_il_offsets;
8335 GPtrArray *source_file_list;
8336 MonoSymSeqPoint *sym_seq_points;
8338 header = mono_method_get_header (method);
8340 buffer_add_int (buf, 0);
8341 buffer_add_string (buf, "");
8342 buffer_add_int (buf, 0);
8346 minfo = mono_debug_lookup_method (method);
8348 buffer_add_int (buf, header->code_size);
8349 buffer_add_string (buf, "");
8350 buffer_add_int (buf, 0);
8351 mono_metadata_free_mh (header);
8355 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, &source_files, &sym_seq_points, &n_il_offsets);
8356 buffer_add_int (buf, header->code_size);
8357 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8358 buffer_add_int (buf, source_file_list->len);
8359 for (i = 0; i < source_file_list->len; ++i) {
8360 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
8361 buffer_add_string (buf, sinfo->source_file);
8362 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8363 for (j = 0; j < 16; ++j)
8364 buffer_add_byte (buf, sinfo->hash [j]);
8368 buffer_add_string (buf, source_file);
8370 buffer_add_int (buf, n_il_offsets);
8371 DEBUG_PRINTF (10, "Line number table for method %s:\n", mono_method_full_name (method, TRUE));
8372 for (i = 0; i < n_il_offsets; ++i) {
8373 MonoSymSeqPoint *sp = &sym_seq_points [i];
8374 const char *srcfile = "";
8376 if (source_files [i] != -1) {
8377 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
8378 srcfile = sinfo->source_file;
8380 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);
8381 buffer_add_int (buf, sp->il_offset);
8382 buffer_add_int (buf, sp->line);
8383 if (CHECK_PROTOCOL_VERSION (2, 13))
8384 buffer_add_int (buf, source_files [i]);
8385 if (CHECK_PROTOCOL_VERSION (2, 19))
8386 buffer_add_int (buf, sp->column);
8387 if (CHECK_PROTOCOL_VERSION (2, 32)) {
8388 buffer_add_int (buf, sp->end_line);
8389 buffer_add_int (buf, sp->end_column);
8392 g_free (source_file);
8393 g_free (source_files);
8394 g_free (sym_seq_points);
8395 g_ptr_array_free (source_file_list, TRUE);
8396 mono_metadata_free_mh (header);
8399 case CMD_METHOD_GET_PARAM_INFO: {
8400 MonoMethodSignature *sig = mono_method_signature (method);
8404 /* FIXME: mono_class_from_mono_type () and byrefs */
8406 /* FIXME: Use a smaller encoding */
8407 buffer_add_int (buf, sig->call_convention);
8408 buffer_add_int (buf, sig->param_count);
8409 buffer_add_int (buf, sig->generic_param_count);
8410 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
8411 for (i = 0; i < sig->param_count; ++i) {
8413 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
8416 /* Emit parameter names */
8417 names = g_new (char *, sig->param_count);
8418 mono_method_get_param_names (method, (const char **) names);
8419 for (i = 0; i < sig->param_count; ++i)
8420 buffer_add_string (buf, names [i]);
8425 case CMD_METHOD_GET_LOCALS_INFO: {
8427 MonoDebugLocalsInfo *locals;
8428 int *locals_map = NULL;
8430 header = mono_method_get_header (method);
8432 return ERR_INVALID_ARGUMENT;
8434 locals = mono_debug_lookup_locals (method);
8436 buffer_add_int (buf, header->num_locals);
8438 for (i = 0; i < header->num_locals; ++i) {
8439 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
8442 for (i = 0; i < header->num_locals; ++i) {
8444 sprintf (lname, "V_%d", i);
8445 buffer_add_string (buf, lname);
8448 for (i = 0; i < header->num_locals; ++i) {
8449 buffer_add_int (buf, 0);
8450 buffer_add_int (buf, header->code_size);
8453 num_locals = locals->num_locals;
8454 buffer_add_int (buf, num_locals);
8457 for (i = 0; i < num_locals; ++i) {
8458 g_assert (locals->locals [i].index < header->num_locals);
8459 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [locals->locals [i].index]));
8462 for (i = 0; i < num_locals; ++i)
8463 buffer_add_string (buf, locals->locals [i].name);
8465 for (i = 0; i < num_locals; ++i) {
8466 if (locals->locals [i].block) {
8467 buffer_add_int (buf, locals->locals [i].block->start_offset);
8468 buffer_add_int (buf, locals->locals [i].block->end_offset);
8470 buffer_add_int (buf, 0);
8471 buffer_add_int (buf, header->code_size);
8475 mono_metadata_free_mh (header);
8478 mono_debug_free_locals (locals);
8479 g_free (locals_map);
8483 case CMD_METHOD_GET_INFO:
8484 buffer_add_int (buf, method->flags);
8485 buffer_add_int (buf, method->iflags);
8486 buffer_add_int (buf, method->token);
8487 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8489 if (method->is_generic)
8491 if (mono_method_signature (method)->generic_param_count)
8493 buffer_add_byte (buf, attrs);
8494 if (method->is_generic || method->is_inflated) {
8497 if (method->is_generic) {
8500 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8502 result = imethod->declaring;
8503 if (imethod->context.class_inst) {
8504 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8505 /*Generic methods gets the context of the GTD.*/
8506 if (mono_class_get_context (klass)) {
8508 result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), &error);
8509 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8514 buffer_add_methodid (buf, domain, result);
8516 buffer_add_id (buf, 0);
8518 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8519 if (mono_method_signature (method)->generic_param_count) {
8522 if (method->is_inflated) {
8523 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
8525 count = inst->type_argc;
8526 buffer_add_int (buf, count);
8528 for (i = 0; i < count; i++)
8529 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8531 buffer_add_int (buf, 0);
8533 } else if (method->is_generic) {
8534 MonoGenericContainer *container = mono_method_get_generic_container (method);
8536 count = mono_method_signature (method)->generic_param_count;
8537 buffer_add_int (buf, count);
8538 for (i = 0; i < count; i++) {
8539 MonoGenericParam *param = mono_generic_container_get_param (container, i);
8540 MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
8541 buffer_add_typeid (buf, domain, pklass);
8544 buffer_add_int (buf, 0);
8547 buffer_add_int (buf, 0);
8552 case CMD_METHOD_GET_BODY: {
8555 header = mono_method_get_header (method);
8557 buffer_add_int (buf, 0);
8559 if (CHECK_PROTOCOL_VERSION (2, 18))
8560 buffer_add_int (buf, 0);
8562 buffer_add_int (buf, header->code_size);
8563 for (i = 0; i < header->code_size; ++i)
8564 buffer_add_byte (buf, header->code [i]);
8566 if (CHECK_PROTOCOL_VERSION (2, 18)) {
8567 buffer_add_int (buf, header->num_clauses);
8568 for (i = 0; i < header->num_clauses; ++i) {
8569 MonoExceptionClause *clause = &header->clauses [i];
8571 buffer_add_int (buf, clause->flags);
8572 buffer_add_int (buf, clause->try_offset);
8573 buffer_add_int (buf, clause->try_len);
8574 buffer_add_int (buf, clause->handler_offset);
8575 buffer_add_int (buf, clause->handler_len);
8576 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
8577 buffer_add_typeid (buf, domain, clause->data.catch_class);
8578 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8579 buffer_add_int (buf, clause->data.filter_offset);
8583 mono_metadata_free_mh (header);
8588 case CMD_METHOD_RESOLVE_TOKEN: {
8589 guint32 token = decode_int (p, &p, end);
8592 switch (mono_metadata_token_code (token)) {
8593 case MONO_TOKEN_STRING: {
8597 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
8600 s2 = mono_string_to_utf8 (s);
8602 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8603 buffer_add_string (buf, s2);
8609 MonoClass *handle_class;
8611 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8612 val = mono_method_get_wrapper_data (method, token);
8613 handle_class = mono_method_get_wrapper_data (method, token + 1);
8615 if (handle_class == NULL) {
8616 // Can't figure out the token type
8617 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8622 val = mono_ldtoken_checked (method->klass->image, token, &handle_class, NULL, &error);
8624 g_error ("Could not load token due to %s", mono_error_get_message (&error));
8627 if (handle_class == mono_defaults.typehandle_class) {
8628 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8629 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8630 buffer_add_typeid (buf, domain, (MonoClass *) val);
8632 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
8633 } else if (handle_class == mono_defaults.fieldhandle_class) {
8634 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8635 buffer_add_fieldid (buf, domain, val);
8636 } else if (handle_class == mono_defaults.methodhandle_class) {
8637 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8638 buffer_add_methodid (buf, domain, val);
8639 } else if (handle_class == mono_defaults.string_class) {
8642 s = mono_string_to_utf8 (val);
8643 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8644 buffer_add_string (buf, s);
8647 g_assert_not_reached ();
8654 case CMD_METHOD_GET_CATTRS: {
8655 MonoClass *attr_klass;
8656 MonoCustomAttrInfo *cinfo;
8658 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8659 /* attr_klass can be NULL */
8663 cinfo = mono_custom_attrs_from_method (method);
8665 err = buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
8670 case CMD_METHOD_MAKE_GENERIC_METHOD: {
8672 MonoType **type_argv;
8676 MonoGenericInst *ginst;
8677 MonoGenericContext tmp_context;
8678 MonoMethod *inflated;
8680 type_argc = decode_int (p, &p, end);
8681 type_argv = g_new0 (MonoType*, type_argc);
8682 for (i = 0; i < type_argc; ++i) {
8683 klass = decode_typeid (p, &p, end, &d, &err);
8690 return ERR_INVALID_ARGUMENT;
8692 type_argv [i] = &klass->byval_arg;
8694 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
8696 tmp_context.class_inst = method->klass->generic_class ? method->klass->generic_class->context.class_inst : NULL;
8697 tmp_context.method_inst = ginst;
8699 inflated = mono_class_inflate_generic_method_checked (method, &tmp_context, &error);
8700 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8701 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
8702 return ERR_INVALID_ARGUMENT;
8703 buffer_add_methodid (buf, domain, inflated);
8707 return ERR_NOT_IMPLEMENTED;
8714 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8717 MonoDomain *old_domain;
8721 method = decode_methodid (p, &p, end, &domain, &err);
8725 old_domain = mono_domain_get ();
8727 mono_domain_set (domain, TRUE);
8729 err = method_commands_internal (command, method, domain, p, end, buf);
8731 mono_domain_set (old_domain, TRUE);
8737 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8739 int objid = decode_objid (p, &p, end);
8741 MonoThread *thread_obj;
8742 MonoInternalThread *thread;
8744 err = get_object (objid, (MonoObject**)&thread_obj);
8748 thread = THREAD_TO_INTERNAL (thread_obj);
8751 case CMD_THREAD_GET_NAME: {
8753 gunichar2 *s = mono_thread_get_name (thread, &name_len);
8756 buffer_add_int (buf, 0);
8761 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
8763 buffer_add_int (buf, len);
8764 buffer_add_data (buf, (guint8*)name, len);
8769 case CMD_THREAD_GET_FRAME_INFO: {
8770 DebuggerTlsData *tls;
8771 int i, start_frame, length;
8773 // Wait for suspending if it already started
8774 // FIXME: Races with suspend_count
8775 while (!is_suspended ()) {
8777 wait_for_suspend ();
8781 wait_for_suspend ();
8782 if (!is_suspended ())
8783 return ERR_NOT_SUSPENDED;
8786 start_frame = decode_int (p, &p, end);
8787 length = decode_int (p, &p, end);
8789 if (start_frame != 0 || length != -1)
8790 return ERR_NOT_IMPLEMENTED;
8792 mono_loader_lock ();
8793 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8794 mono_loader_unlock ();
8797 compute_frame_info (thread, tls);
8799 buffer_add_int (buf, tls->frame_count);
8800 for (i = 0; i < tls->frame_count; ++i) {
8801 buffer_add_int (buf, tls->frames [i]->id);
8802 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
8803 buffer_add_int (buf, tls->frames [i]->il_offset);
8805 * Instead of passing the frame type directly to the client, we associate
8806 * it with the previous frame using a set of flags. This avoids lots of
8807 * conditional code in the client, since a frame whose type isn't
8808 * FRAME_TYPE_MANAGED has no method, location, etc.
8810 buffer_add_byte (buf, tls->frames [i]->flags);
8815 case CMD_THREAD_GET_STATE:
8816 buffer_add_int (buf, thread->state);
8818 case CMD_THREAD_GET_INFO:
8819 buffer_add_byte (buf, thread->threadpool_thread);
8821 case CMD_THREAD_GET_ID:
8822 buffer_add_long (buf, (guint64)(gsize)thread);
8824 case CMD_THREAD_GET_TID:
8825 buffer_add_long (buf, (guint64)thread->tid);
8827 case CMD_THREAD_SET_IP: {
8828 DebuggerTlsData *tls;
8831 MonoSeqPointInfo *seq_points;
8836 method = decode_methodid (p, &p, end, &domain, &err);
8839 il_offset = decode_long (p, &p, end);
8841 while (!is_suspended ()) {
8843 wait_for_suspend ();
8846 mono_loader_lock ();
8847 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8848 mono_loader_unlock ();
8851 compute_frame_info (thread, tls);
8852 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
8853 return ERR_INVALID_ARGUMENT;
8855 found_sp = mono_find_seq_point (domain, method, il_offset, &seq_points, &sp);
8857 g_assert (seq_points);
8860 return ERR_INVALID_ARGUMENT;
8862 // FIXME: Check that the ip change is safe
8864 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);
8865 MONO_CONTEXT_SET_IP (&tls->restore_state.ctx, (guint8*)tls->frames [0]->ji->code_start + sp.native_offset);
8869 return ERR_NOT_IMPLEMENTED;
8876 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8880 MonoThread *thread_obj;
8881 MonoInternalThread *thread;
8882 int pos, i, len, frame_idx;
8883 DebuggerTlsData *tls;
8885 MonoDebugMethodJitInfo *jit;
8886 MonoMethodSignature *sig;
8888 MonoMethodHeader *header;
8890 objid = decode_objid (p, &p, end);
8891 err = get_object (objid, (MonoObject**)&thread_obj);
8895 thread = THREAD_TO_INTERNAL (thread_obj);
8897 id = decode_id (p, &p, end);
8899 mono_loader_lock ();
8900 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8901 mono_loader_unlock ();
8904 for (i = 0; i < tls->frame_count; ++i) {
8905 if (tls->frames [i]->id == id)
8908 if (i == tls->frame_count)
8909 return ERR_INVALID_FRAMEID;
8912 frame = tls->frames [frame_idx];
8914 /* This is supported for frames without has_ctx etc. set */
8915 if (command == CMD_STACK_FRAME_GET_DOMAIN) {
8916 if (CHECK_PROTOCOL_VERSION (2, 38))
8917 buffer_add_domainid (buf, frame->domain);
8921 if (!frame->has_ctx)
8922 return ERR_ABSENT_INFORMATION;
8925 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
8926 if (!frame->jit && frame->api_method->is_inflated)
8927 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
8931 /* This could happen for aot images with no jit debug info */
8932 s = mono_method_full_name (frame->api_method, TRUE);
8933 DEBUG_PRINTF (1, "[dbg] No debug information found for '%s'.\n", s);
8935 return ERR_ABSENT_INFORMATION;
8940 sig = mono_method_signature (frame->actual_method);
8942 if (!mono_get_seq_points (frame->domain, frame->actual_method))
8944 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
8946 return ERR_ABSENT_INFORMATION;
8949 case CMD_STACK_FRAME_GET_VALUES: {
8950 len = decode_int (p, &p, end);
8951 header = mono_method_get_header (frame->actual_method);
8953 for (i = 0; i < len; ++i) {
8954 pos = decode_int (p, &p, end);
8959 DEBUG_PRINTF (4, "[dbg] send arg %d.\n", pos);
8961 g_assert (pos >= 0 && pos < jit->num_params);
8963 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
8965 MonoDebugLocalsInfo *locals;
8967 locals = mono_debug_lookup_locals (frame->method);
8969 g_assert (pos < locals->num_locals);
8970 pos = locals->locals [pos].index;
8971 mono_debug_free_locals (locals);
8973 g_assert (pos >= 0 && pos < jit->num_locals);
8975 DEBUG_PRINTF (4, "[dbg] send local %d.\n", pos);
8977 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
8980 mono_metadata_free_mh (header);
8983 case CMD_STACK_FRAME_GET_THIS: {
8984 if (frame->api_method->klass->valuetype) {
8985 if (!sig->hasthis) {
8986 MonoObject *p = NULL;
8987 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
8989 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8992 if (!sig->hasthis) {
8993 MonoObject *p = NULL;
8994 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
8996 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9001 case CMD_STACK_FRAME_SET_VALUES: {
9004 MonoDebugVarInfo *var;
9006 len = decode_int (p, &p, end);
9007 header = mono_method_get_header (frame->actual_method);
9009 for (i = 0; i < len; ++i) {
9010 pos = decode_int (p, &p, end);
9015 g_assert (pos >= 0 && pos < jit->num_params);
9017 t = sig->params [pos];
9018 var = &jit->params [pos];
9020 MonoDebugLocalsInfo *locals;
9022 locals = mono_debug_lookup_locals (frame->method);
9024 g_assert (pos < locals->num_locals);
9025 pos = locals->locals [pos].index;
9026 mono_debug_free_locals (locals);
9028 g_assert (pos >= 0 && pos < jit->num_locals);
9030 t = header->locals [pos];
9031 var = &jit->locals [pos];
9034 if (MONO_TYPE_IS_REFERENCE (t))
9035 val_buf = g_alloca (sizeof (MonoObject*));
9037 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9038 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9042 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9044 mono_metadata_free_mh (header);
9047 case CMD_STACK_FRAME_GET_DOMAIN: {
9048 if (CHECK_PROTOCOL_VERSION (2, 38))
9049 buffer_add_domainid (buf, frame->domain);
9053 return ERR_NOT_IMPLEMENTED;
9060 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9063 int objid, err, index, len, i, esize;
9066 objid = decode_objid (p, &p, end);
9067 err = get_object (objid, (MonoObject**)&arr);
9072 case CMD_ARRAY_REF_GET_LENGTH:
9073 buffer_add_int (buf, arr->obj.vtable->klass->rank);
9075 buffer_add_int (buf, arr->max_length);
9076 buffer_add_int (buf, 0);
9078 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
9079 buffer_add_int (buf, arr->bounds [i].length);
9080 buffer_add_int (buf, arr->bounds [i].lower_bound);
9084 case CMD_ARRAY_REF_GET_VALUES:
9085 index = decode_int (p, &p, end);
9086 len = decode_int (p, &p, end);
9088 g_assert (index >= 0 && len >= 0);
9089 // Reordered to avoid integer overflow
9090 g_assert (!(index > arr->max_length - len));
9092 esize = mono_array_element_size (arr->obj.vtable->klass);
9093 for (i = index; i < index + len; ++i) {
9094 elem = (gpointer*)((char*)arr->vector + (i * esize));
9095 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
9098 case CMD_ARRAY_REF_SET_VALUES:
9099 index = decode_int (p, &p, end);
9100 len = decode_int (p, &p, end);
9102 g_assert (index >= 0 && len >= 0);
9103 // Reordered to avoid integer overflow
9104 g_assert (!(index > arr->max_length - len));
9106 esize = mono_array_element_size (arr->obj.vtable->klass);
9107 for (i = index; i < index + len; ++i) {
9108 elem = (gpointer*)((char*)arr->vector + (i * esize));
9110 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
9114 return ERR_NOT_IMPLEMENTED;
9121 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9126 int i, index, length;
9128 gboolean use_utf16 = FALSE;
9130 objid = decode_objid (p, &p, end);
9131 err = get_object (objid, (MonoObject**)&str);
9136 case CMD_STRING_REF_GET_VALUE:
9137 if (CHECK_PROTOCOL_VERSION (2, 41)) {
9138 for (i = 0; i < mono_string_length (str); ++i)
9139 if (mono_string_chars (str)[i] == 0)
9141 buffer_add_byte (buf, use_utf16 ? 1 : 0);
9144 buffer_add_int (buf, mono_string_length (str) * 2);
9145 buffer_add_data (buf, (guint8*)mono_string_chars (str), mono_string_length (str) * 2);
9147 s = mono_string_to_utf8 (str);
9148 buffer_add_string (buf, s);
9152 case CMD_STRING_REF_GET_LENGTH:
9153 buffer_add_long (buf, mono_string_length (str));
9155 case CMD_STRING_REF_GET_CHARS:
9156 index = decode_long (p, &p, end);
9157 length = decode_long (p, &p, end);
9158 if (index > mono_string_length (str) - length)
9159 return ERR_INVALID_ARGUMENT;
9160 c = mono_string_chars (str) + index;
9161 for (i = 0; i < length; ++i)
9162 buffer_add_short (buf, c [i]);
9165 return ERR_NOT_IMPLEMENTED;
9172 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9181 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9182 objid = decode_objid (p, &p, end);
9183 err = get_object (objid, &obj);
9185 buffer_add_int (buf, 1);
9187 buffer_add_int (buf, 0);
9191 objid = decode_objid (p, &p, end);
9192 err = get_object (objid, &obj);
9196 MonoClass *obj_type;
9198 obj_type = obj->vtable->klass;
9199 if (mono_class_is_transparent_proxy (obj_type))
9200 obj_type = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
9202 g_assert (obj_type);
9205 case CMD_OBJECT_REF_GET_TYPE:
9206 /* This handles transparent proxies too */
9207 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9209 case CMD_OBJECT_REF_GET_VALUES:
9210 len = decode_int (p, &p, end);
9212 for (i = 0; i < len; ++i) {
9213 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9217 /* Check that the field belongs to the object */
9219 for (k = obj_type; k; k = k->parent) {
9220 if (k == f->parent) {
9226 return ERR_INVALID_FIELDID;
9228 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9232 if (mono_class_field_is_special_static (f))
9233 return ERR_INVALID_FIELDID;
9235 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9236 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9237 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9238 mono_field_static_get_value (vtable, f, val);
9239 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9242 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
9246 case CMD_OBJECT_REF_SET_VALUES:
9247 len = decode_int (p, &p, end);
9249 for (i = 0; i < len; ++i) {
9250 f = decode_fieldid (p, &p, end, NULL, &err);
9254 /* Check that the field belongs to the object */
9256 for (k = obj_type; k; k = k->parent) {
9257 if (k == f->parent) {
9263 return ERR_INVALID_FIELDID;
9265 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9269 if (mono_class_field_is_special_static (f))
9270 return ERR_INVALID_FIELDID;
9272 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9273 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9275 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9276 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
9281 mono_field_static_set_value (vtable, f, val);
9284 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
9290 case CMD_OBJECT_REF_GET_ADDRESS:
9291 buffer_add_long (buf, (gssize)obj);
9293 case CMD_OBJECT_REF_GET_DOMAIN:
9294 buffer_add_domainid (buf, obj->vtable->domain);
9296 case CMD_OBJECT_REF_GET_INFO:
9297 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9298 buffer_add_domainid (buf, obj->vtable->domain);
9301 return ERR_NOT_IMPLEMENTED;
9308 command_set_to_string (CommandSet command_set)
9310 switch (command_set) {
9313 case CMD_SET_OBJECT_REF:
9314 return "OBJECT_REF";
9315 case CMD_SET_STRING_REF:
9316 return "STRING_REF";
9317 case CMD_SET_THREAD:
9319 case CMD_SET_ARRAY_REF:
9321 case CMD_SET_EVENT_REQUEST:
9322 return "EVENT_REQUEST";
9323 case CMD_SET_STACK_FRAME:
9324 return "STACK_FRAME";
9325 case CMD_SET_APPDOMAIN:
9327 case CMD_SET_ASSEMBLY:
9329 case CMD_SET_METHOD:
9333 case CMD_SET_MODULE:
9344 static const char* vm_cmds_str [] = {
9352 "SET_PROTOCOL_VERSION",
9355 "GET_TYPES_FOR_SOURCE_FILE",
9360 static const char* thread_cmds_str[] = {
9370 static const char* event_cmds_str[] = {
9373 "REQUEST_CLEAR_ALL_BREAKPOINTS"
9376 static const char* appdomain_cmds_str[] = {
9378 "GET_FRIENDLY_NAME",
9380 "GET_ENTRY_ASSEMBLY",
9383 "CREATE_BOXED_VALUE"
9386 static const char* assembly_cmds_str[] = {
9389 "GET_MANIFEST_MODULE",
9395 static const char* module_cmds_str[] = {
9399 static const char* field_cmds_str[] = {
9403 static const char* method_cmds_str[] = {
9405 "GET_DECLARING_TYPE",
9413 "MAKE_GENERIC_METHOD"
9416 static const char* type_cmds_str[] = {
9424 "IS_ASSIGNABLE_FROM",
9428 "GET_PROPERTY_CATTRS",
9429 "GET_SOURCE_FILES_2",
9431 "GET_METHODS_BY_NAME_FLAGS",
9433 "GET_INTERFACE_MAP",
9437 static const char* stack_frame_cmds_str[] = {
9444 static const char* array_cmds_str[] = {
9450 static const char* string_cmds_str[] = {
9456 static const char* object_cmds_str[] = {
9467 cmd_to_string (CommandSet set, int command)
9475 cmds_len = G_N_ELEMENTS (vm_cmds_str);
9477 case CMD_SET_OBJECT_REF:
9478 cmds = object_cmds_str;
9479 cmds_len = G_N_ELEMENTS (object_cmds_str);
9481 case CMD_SET_STRING_REF:
9482 cmds = string_cmds_str;
9483 cmds_len = G_N_ELEMENTS (string_cmds_str);
9485 case CMD_SET_THREAD:
9486 cmds = thread_cmds_str;
9487 cmds_len = G_N_ELEMENTS (thread_cmds_str);
9489 case CMD_SET_ARRAY_REF:
9490 cmds = array_cmds_str;
9491 cmds_len = G_N_ELEMENTS (array_cmds_str);
9493 case CMD_SET_EVENT_REQUEST:
9494 cmds = event_cmds_str;
9495 cmds_len = G_N_ELEMENTS (event_cmds_str);
9497 case CMD_SET_STACK_FRAME:
9498 cmds = stack_frame_cmds_str;
9499 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
9501 case CMD_SET_APPDOMAIN:
9502 cmds = appdomain_cmds_str;
9503 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
9505 case CMD_SET_ASSEMBLY:
9506 cmds = assembly_cmds_str;
9507 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
9509 case CMD_SET_METHOD:
9510 cmds = method_cmds_str;
9511 cmds_len = G_N_ELEMENTS (method_cmds_str);
9514 cmds = type_cmds_str;
9515 cmds_len = G_N_ELEMENTS (type_cmds_str);
9517 case CMD_SET_MODULE:
9518 cmds = module_cmds_str;
9519 cmds_len = G_N_ELEMENTS (module_cmds_str);
9522 cmds = field_cmds_str;
9523 cmds_len = G_N_ELEMENTS (field_cmds_str);
9526 cmds = event_cmds_str;
9527 cmds_len = G_N_ELEMENTS (event_cmds_str);
9532 if (command > 0 && command <= cmds_len)
9533 return cmds [command - 1];
9539 wait_for_attach (void)
9541 #ifndef DISABLE_SOCKET_TRANSPORT
9542 if (listen_fd == -1) {
9543 DEBUG_PRINTF (1, "[dbg] Invalid listening socket\n");
9547 /* Block and wait for client connection */
9548 MONO_PREPARE_BLOCKING;
9549 conn_fd = socket_transport_accept (listen_fd);
9550 MONO_FINISH_BLOCKING;
9552 DEBUG_PRINTF (1, "Accepted connection on %d\n", conn_fd);
9553 if (conn_fd == -1) {
9554 DEBUG_PRINTF (1, "[dbg] Bad client connection\n");
9558 g_assert_not_reached ();
9562 disconnected = !transport_handshake ();
9564 DEBUG_PRINTF (1, "Transport handshake failed!\n");
9574 * This thread handles communication with the debugger client using a JDWP
9577 static guint32 WINAPI
9578 debugger_thread (void *arg)
9580 int res, len, id, flags, command_set = 0, command = 0;
9581 guint8 header [HEADER_LENGTH];
9582 guint8 *data, *p, *end;
9586 gboolean attach_failed = FALSE;
9588 DEBUG_PRINTF (1, "[dbg] Agent thread started, pid=%p\n", (gpointer)mono_native_thread_id_get ());
9590 debugger_thread_id = mono_native_thread_id_get ();
9592 mono_jit_thread_attach (mono_get_root_domain ());
9594 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
9596 mono_set_is_debugger_attached (TRUE);
9598 if (agent_config.defer) {
9599 if (!wait_for_attach ()) {
9600 DEBUG_PRINTF (1, "[dbg] Can't attach, aborting debugger thread.\n");
9601 attach_failed = TRUE; // Don't abort process when we can't listen
9603 /* Send start event to client */
9604 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
9608 while (!attach_failed) {
9609 MONO_PREPARE_BLOCKING;
9610 res = transport_recv (header, HEADER_LENGTH);
9611 MONO_FINISH_BLOCKING;
9613 /* This will break if the socket is closed during shutdown too */
9614 if (res != HEADER_LENGTH) {
9615 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH);
9620 end = header + HEADER_LENGTH;
9622 len = decode_int (p, &p, end);
9623 id = decode_int (p, &p, end);
9624 flags = decode_byte (p, &p, end);
9625 command_set = decode_byte (p, &p, end);
9626 command = decode_byte (p, &p, end);
9628 g_assert (flags == 0);
9631 const char *cmd_str;
9634 cmd_str = cmd_to_string (command_set, command);
9636 sprintf (cmd_num, "%d", command);
9640 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);
9643 data = g_malloc (len - HEADER_LENGTH);
9644 if (len - HEADER_LENGTH > 0)
9646 MONO_PREPARE_BLOCKING;
9647 res = transport_recv (data, len - HEADER_LENGTH);
9648 MONO_FINISH_BLOCKING;
9649 if (res != len - HEADER_LENGTH) {
9650 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH);
9656 end = data + (len - HEADER_LENGTH);
9658 buffer_init (&buf, 128);
9663 /* Process the request */
9664 switch (command_set) {
9666 err = vm_commands (command, id, p, end, &buf);
9667 if (!err && command == CMD_VM_INVOKE_METHOD)
9668 /* Sent after the invoke is complete */
9671 case CMD_SET_EVENT_REQUEST:
9672 err = event_commands (command, p, end, &buf);
9674 case CMD_SET_APPDOMAIN:
9675 err = domain_commands (command, p, end, &buf);
9677 case CMD_SET_ASSEMBLY:
9678 err = assembly_commands (command, p, end, &buf);
9680 case CMD_SET_MODULE:
9681 err = module_commands (command, p, end, &buf);
9684 err = field_commands (command, p, end, &buf);
9687 err = type_commands (command, p, end, &buf);
9689 case CMD_SET_METHOD:
9690 err = method_commands (command, p, end, &buf);
9692 case CMD_SET_THREAD:
9693 err = thread_commands (command, p, end, &buf);
9695 case CMD_SET_STACK_FRAME:
9696 err = frame_commands (command, p, end, &buf);
9698 case CMD_SET_ARRAY_REF:
9699 err = array_commands (command, p, end, &buf);
9701 case CMD_SET_STRING_REF:
9702 err = string_commands (command, p, end, &buf);
9704 case CMD_SET_OBJECT_REF:
9705 err = object_commands (command, p, end, &buf);
9708 err = ERR_NOT_IMPLEMENTED;
9711 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
9712 buffer_replies = TRUE;
9716 if (buffer_replies) {
9717 buffer_reply_packet (id, err, &buf);
9719 send_reply_packet (id, err, &buf);
9720 //DEBUG_PRINTF (1, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000);
9724 if (!err && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
9725 send_buffered_reply_packets ();
9726 buffer_replies = FALSE;
9732 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
9736 mono_set_is_debugger_attached (FALSE);
9739 mono_mutex_lock (&debugger_thread_exited_mutex);
9740 debugger_thread_exited = TRUE;
9741 mono_cond_signal (&debugger_thread_exited_cond);
9742 mono_mutex_unlock (&debugger_thread_exited_mutex);
9743 MONO_FINISH_TRY_BLOCKING;
9745 DEBUG_PRINTF (1, "[dbg] Debugger thread exited.\n");
9747 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
9748 DEBUG_PRINTF (2, "[dbg] Detached - restarting clean debugger thread.\n");
9749 start_debugger_thread ();
9755 #else /* DISABLE_DEBUGGER_AGENT */
9758 mono_debugger_agent_parse_options (char *options)
9760 g_error ("This runtime is configured with the debugger agent disabled.");
9764 mono_debugger_agent_init (void)
9769 mono_debugger_agent_breakpoint_hit (void *sigctx)
9774 mono_debugger_agent_single_step_event (void *sigctx)
9779 mono_debugger_agent_free_domain_info (MonoDomain *domain)
9784 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
9785 MonoContext *catch_ctx)
9790 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9795 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9800 mono_debugger_agent_user_break (void)
9806 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
9811 mono_debugger_agent_debug_log_is_enabled (void)
9817 mono_debugger_agent_unhandled_exception (MonoException *exc)
9819 g_assert_not_reached ();
9823 debugger_agent_single_step_from_context (MonoContext *ctx)
9825 g_assert_not_reached ();
9829 debugger_agent_breakpoint_from_context (MonoContext *ctx)
9831 g_assert_not_reached ();