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 gsize 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 GetCurrentThreadId () == 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 (GetCurrentThreadId () != debugger_thread_id) {
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 (GetCurrentThreadId () == debugger_thread_id)
2396 DEBUG_PRINTF (2, "[dbg] send class [%s]\n", s);
2398 DEBUG_PRINTF (2, "[%p] send class [%s]\n", (gpointer)GetCurrentThreadId (), 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;
2505 } GetLastFrameUserData;
2508 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2510 GetLastFrameUserData *data = user_data;
2512 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE || info->type == FRAME_TYPE_TRAMPOLINE)
2515 if (!data->last_frame_set) {
2516 /* Store the last frame */
2517 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2518 data->last_frame_set = TRUE;
2521 /* Store the context/lmf for the frame above the last frame */
2522 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2523 data->lmf = info->lmf;
2531 * Process interruption of a thread. This should be signal safe.
2534 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, MonoJitInfo *ji)
2538 MonoNativeThreadId tid;
2542 ip = MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx);
2543 tid = mono_thread_info_get_tid (info);
2545 // FIXME: Races when the thread leaves managed code before hitting a single step
2548 if (ji && !ji->is_trampoline) {
2549 /* Running managed code, will be suspended by the single step code */
2550 DEBUG_PRINTF (1, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip);
2553 * Running native code, will be suspended when it returns to/enters
2554 * managed code. Treat it as already suspended.
2555 * This might interrupt the code in process_single_step_inner (), we use the
2556 * tls->suspending flag to avoid races when that happens.
2558 if (!tls->suspended && !tls->suspending) {
2560 GetLastFrameUserData data;
2562 // FIXME: printf is not signal safe, but this is only used during
2563 // debugger debugging
2565 DEBUG_PRINTF (1, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip);
2566 //save_thread_context (&ctx);
2569 /* Already terminated */
2573 * We are in a difficult position: we want to be able to provide stack
2574 * traces for this thread, but we can't use the current ctx+lmf, since
2575 * the thread is still running, so it might return to managed code,
2576 * making these invalid.
2577 * So we start a stack walk and save the first frame, along with the
2578 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2579 * suspended when it returns to managed code, so the parent's ctx should
2582 data.last_frame_set = FALSE;
2583 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, mono_thread_info_get_suspend_state (info), MONO_UNWIND_SIGNAL_SAFE, &data);
2584 if (data.last_frame_set) {
2585 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2586 res = mono_thread_state_init_from_monoctx (&tls->async_state, &ctx);
2588 mono_thread_state_init_from_monoctx (&tls->context, &ctx);
2591 memcpy (&tls->async_state.ctx, &data.ctx, sizeof (MonoContext));
2592 tls->async_state.unwind_data [MONO_UNWIND_DATA_LMF] = data.lmf;
2593 tls->async_state.unwind_data [MONO_UNWIND_DATA_JIT_TLS] = ((MonoThreadInfo*)tls->thread->thread_info)->jit_data;
2595 tls->async_state.valid = FALSE;
2598 mono_memory_barrier ();
2600 tls->suspended = TRUE;
2601 MONO_SEM_POST (&suspend_sem);
2607 * reset_native_thread_suspend_state:
2609 * Reset the suspended flag and state on native threads
2612 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2614 DebuggerTlsData *tls = value;
2616 if (!tls->really_suspended && tls->suspended) {
2617 tls->suspended = FALSE;
2619 * The thread might still be running if it was executing native code, so the state won't be invalided by
2620 * suspend_current ().
2622 tls->context.valid = FALSE;
2623 tls->async_state.valid = FALSE;
2624 invalidate_frames (tls);
2629 DebuggerTlsData *tls;
2630 gboolean valid_info;
2633 static SuspendThreadResult
2634 debugger_interrupt_critical (MonoThreadInfo *info, gpointer user_data)
2636 InterruptData *data = user_data;
2639 data->valid_info = TRUE;
2640 ji = mono_jit_info_table_find_internal (
2641 mono_thread_info_get_suspend_state (info)->unwind_data [MONO_UNWIND_DATA_DOMAIN],
2642 MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx),
2646 /* This is signal safe */
2647 thread_interrupt (data->tls, info, ji);
2648 return MonoResumeThread;
2654 * Notify a thread that it needs to suspend.
2657 notify_thread (gpointer key, gpointer value, gpointer user_data)
2659 MonoInternalThread *thread = key;
2660 DebuggerTlsData *tls = value;
2661 gsize tid = thread->tid;
2663 if (GetCurrentThreadId () == tid || tls->terminated)
2666 DEBUG_PRINTF (1, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid);
2668 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2669 InterruptData interrupt_data = { 0 };
2670 interrupt_data.tls = tls;
2672 mono_thread_info_safe_suspend_and_run ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE, debugger_interrupt_critical, &interrupt_data);
2673 if (!interrupt_data.valid_info) {
2674 DEBUG_PRINTF (1, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid);
2676 * Attached thread which died without detaching.
2678 tls->terminated = TRUE;
2683 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2685 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2689 if (mono_loader_lock_is_owned_by_self ()) {
2691 * Shortcut for the check in suspend_current (). This speeds up processing
2692 * when executing long running code inside the loader lock, i.e. assembly load
2698 if (debugger_thread_id == GetCurrentThreadId ())
2701 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2702 if (suspend_count - tls->resume_count > 0)
2703 tls->suspending = TRUE;
2705 DEBUG_PRINTF (1, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ());
2707 if (suspend_count - tls->resume_count == 0) {
2709 * We are executing a single threaded invoke but the single step for
2710 * suspending is still active.
2711 * FIXME: This slows down single threaded invokes.
2713 DEBUG_PRINTF (1, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ());
2717 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2719 /* Can't suspend in these methods */
2720 method = jinfo_get_method (ji);
2721 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2724 save_thread_context (ctx);
2732 * Increase the suspend count of the VM. While the suspend count is greater
2733 * than 0, runtime threads are suspended at certain points during execution.
2738 mono_loader_lock ();
2741 mono_mutex_lock (&suspend_mutex);
2742 MONO_FINISH_TRY_BLOCKING;
2746 DEBUG_PRINTF (1, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ());
2748 if (suspend_count == 1) {
2749 // FIXME: Is it safe to call this inside the lock ?
2750 start_single_stepping ();
2751 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2754 mono_mutex_unlock (&suspend_mutex);
2756 if (suspend_count == 1)
2758 * Suspend creation of new threadpool threads, since they cannot run
2760 mono_threadpool_ms_suspend ();
2762 mono_loader_unlock ();
2768 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2776 g_assert (debugger_thread_id == GetCurrentThreadId ());
2778 mono_loader_lock ();
2781 mono_mutex_lock (&suspend_mutex);
2782 MONO_FINISH_TRY_BLOCKING;
2784 g_assert (suspend_count > 0);
2787 DEBUG_PRINTF (1, "[%p] Resuming vm, suspend count=%d...\n", (gpointer)GetCurrentThreadId (), suspend_count);
2789 if (suspend_count == 0) {
2790 // FIXME: Is it safe to call this inside the lock ?
2791 stop_single_stepping ();
2792 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2795 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2796 err = mono_cond_broadcast (&suspend_cond);
2797 g_assert (err == 0);
2799 mono_mutex_unlock (&suspend_mutex);
2800 //g_assert (err == 0);
2802 if (suspend_count == 0)
2803 mono_threadpool_ms_resume ();
2805 mono_loader_unlock ();
2811 * Resume just one thread.
2814 resume_thread (MonoInternalThread *thread)
2817 DebuggerTlsData *tls;
2819 g_assert (debugger_thread_id == GetCurrentThreadId ());
2821 mono_loader_lock ();
2823 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2827 mono_mutex_lock (&suspend_mutex);
2828 MONO_FINISH_TRY_BLOCKING;
2830 g_assert (suspend_count > 0);
2832 DEBUG_PRINTF (1, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid);
2834 tls->resume_count += suspend_count;
2837 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2838 * but only the one whose resume_count field is > 0 will be resumed.
2840 err = mono_cond_broadcast (&suspend_cond);
2841 g_assert (err == 0);
2843 mono_mutex_unlock (&suspend_mutex);
2844 //g_assert (err == 0);
2846 mono_loader_unlock ();
2850 free_frames (StackFrame **frames, int nframes)
2854 for (i = 0; i < nframes; ++i) {
2855 if (frames [i]->jit)
2856 mono_debug_free_method_jit_info (frames [i]->jit);
2857 g_free (frames [i]);
2863 invalidate_frames (DebuggerTlsData *tls)
2866 tls = mono_native_tls_get_value (debugger_tls_id);
2869 free_frames (tls->frames, tls->frame_count);
2870 tls->frame_count = 0;
2873 free_frames (tls->restore_frames, tls->restore_frame_count);
2874 tls->restore_frame_count = 0;
2875 tls->restore_frames = NULL;
2881 * Suspend the current thread until the runtime is resumed. If the thread has a
2882 * pending invoke, then the invoke is executed before this function returns.
2885 suspend_current (void)
2887 DebuggerTlsData *tls;
2890 g_assert (debugger_thread_id != GetCurrentThreadId ());
2892 if (mono_loader_lock_is_owned_by_self ()) {
2894 * If we own the loader mutex, can't suspend until we release it, since the
2895 * whole runtime can deadlock otherwise.
2900 tls = mono_native_tls_get_value (debugger_tls_id);
2904 mono_mutex_lock (&suspend_mutex);
2905 MONO_FINISH_TRY_BLOCKING;
2907 tls->suspending = FALSE;
2908 tls->really_suspended = TRUE;
2910 if (!tls->suspended) {
2911 tls->suspended = TRUE;
2912 MONO_SEM_POST (&suspend_sem);
2915 DEBUG_PRINTF (1, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ());
2918 while (suspend_count - tls->resume_count > 0) {
2919 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
2920 g_assert (err == 0);
2922 MONO_FINISH_TRY_BLOCKING;
2924 tls->suspended = FALSE;
2925 tls->really_suspended = FALSE;
2927 threads_suspend_count --;
2929 mono_mutex_unlock (&suspend_mutex);
2931 DEBUG_PRINTF (1, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ());
2933 if (tls->pending_invoke) {
2934 /* Save the original context */
2935 tls->pending_invoke->has_ctx = TRUE;
2936 tls->pending_invoke->ctx = tls->context.ctx;
2941 /* The frame info becomes invalid after a resume */
2942 tls->context.valid = FALSE;
2943 tls->async_state.valid = FALSE;
2944 invalidate_frames (tls);
2948 count_thread (gpointer key, gpointer value, gpointer user_data)
2950 DebuggerTlsData *tls = value;
2952 if (!tls->suspended && !tls->terminated)
2953 *(int*)user_data = *(int*)user_data + 1;
2957 count_threads_to_wait_for (void)
2961 mono_loader_lock ();
2962 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2963 mono_loader_unlock ();
2971 * Wait until the runtime is completely suspended.
2974 wait_for_suspend (void)
2976 int nthreads, nwait, err;
2977 gboolean waited = FALSE;
2979 // FIXME: Threads starting/stopping ?
2980 mono_loader_lock ();
2981 nthreads = mono_g_hash_table_size (thread_to_tls);
2982 mono_loader_unlock ();
2985 nwait = count_threads_to_wait_for ();
2987 DEBUG_PRINTF (1, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads);
2988 err = MONO_SEM_WAIT (&suspend_sem);
2989 g_assert (err == 0);
2997 DEBUG_PRINTF (1, "%d threads suspended.\n", nthreads);
3003 * Return whenever the runtime is suspended.
3008 return count_threads_to_wait_for () == 0;
3012 no_seq_points_found (MonoMethod *method)
3015 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3017 printf ("Unable to find seq points for method '%s'.\n", mono_method_full_name (method, TRUE));
3021 DebuggerTlsData *tls;
3023 } ComputeFramesUserData;
3026 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3028 ComputeFramesUserData *ud = user_data;
3030 MonoMethod *method, *actual_method, *api_method;
3034 if (info->type != FRAME_TYPE_MANAGED) {
3035 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3036 /* Mark the last frame as an invoke frame */
3038 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3044 method = jinfo_get_method (info->ji);
3046 method = info->method;
3047 actual_method = info->actual_method;
3048 api_method = method;
3053 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3056 if (info->il_offset == -1) {
3057 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3058 if (ud->frames == NULL) {
3059 if (mono_find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL, &sp))
3060 info->il_offset = sp.il_offset;
3062 if (info->il_offset == -1)
3063 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3066 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);
3068 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3069 if (!CHECK_PROTOCOL_VERSION (2, 17))
3070 /* Older clients can't handle this flag */
3072 api_method = mono_marshal_method_from_wrapper (method);
3075 actual_method = api_method;
3076 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3079 frame = g_new0 (StackFrame, 1);
3080 frame->method = method;
3081 frame->actual_method = actual_method;
3082 frame->api_method = api_method;
3083 frame->il_offset = info->il_offset;
3084 frame->native_offset = info->native_offset;
3085 frame->flags = flags;
3086 frame->ji = info->ji;
3087 if (info->reg_locations)
3088 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3091 frame->has_ctx = TRUE;
3093 frame->domain = info->domain;
3095 ud->frames = g_slist_append (ud->frames, frame);
3101 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3103 ComputeFramesUserData *ud = user_data;
3106 * 'tls->filter_ctx' is the location of the throw site.
3108 * mono_walk_stack() will never actually hit the throw site, but unwind
3109 * directly from the filter to the call site; we abort stack unwinding here
3110 * once this happens and resume from the throw site.
3113 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3116 return process_frame (info, ctx, user_data);
3120 * Return a malloc-ed list of StackFrame structures.
3123 compute_frame_info_from (MonoInternalThread *thread, DebuggerTlsData *tls, MonoThreadUnwindState *state, int *out_nframes)
3125 ComputeFramesUserData user_data;
3126 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3131 user_data.tls = tls;
3132 user_data.frames = NULL;
3134 mono_walk_stack_with_state (process_frame, state, opts, &user_data);
3136 nframes = g_slist_length (user_data.frames);
3137 res = g_new0 (StackFrame*, nframes);
3138 l = user_data.frames;
3139 for (i = 0; i < nframes; ++i) {
3143 *out_nframes = nframes;
3149 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3151 ComputeFramesUserData user_data;
3153 int i, findex, new_frame_count;
3154 StackFrame **new_frames, *f;
3155 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3157 // FIXME: Locking on tls
3158 if (tls->frames && tls->frames_up_to_date)
3161 DEBUG_PRINTF (1, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid);
3163 user_data.tls = tls;
3164 user_data.frames = NULL;
3165 if (tls->terminated) {
3166 tls->frame_count = 0;
3168 } if (!tls->really_suspended && tls->async_state.valid) {
3169 /* Have to use the state saved by the signal handler */
3170 process_frame (&tls->async_last_frame, NULL, &user_data);
3171 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3172 } else if (tls->filter_state.valid) {
3174 * We are inside an exception filter.
3176 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3178 if (tls->context.valid)
3179 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3181 * After that, we resume unwinding from the location where the exception has been thrown.
3183 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3184 } else if (tls->context.valid) {
3185 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3188 tls->frame_count = 0;
3192 new_frame_count = g_slist_length (user_data.frames);
3193 new_frames = g_new0 (StackFrame*, new_frame_count);
3195 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3199 * Reuse the id for already existing stack frames, so invokes don't invalidate
3200 * the still valid stack frames.
3202 for (i = 0; i < tls->frame_count; ++i) {
3203 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3204 f->id = tls->frames [i]->id;
3209 if (i >= tls->frame_count)
3210 f->id = InterlockedIncrement (&frame_id);
3212 new_frames [findex ++] = f;
3215 g_slist_free (user_data.frames);
3217 invalidate_frames (tls);
3219 tls->frames = new_frames;
3220 tls->frame_count = new_frame_count;
3221 tls->frames_up_to_date = TRUE;
3225 * GHFunc to emit an appdomain creation event
3226 * @param key Don't care
3227 * @param value A loaded appdomain
3228 * @param user_data Don't care
3231 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3233 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3234 g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
3238 * GHFunc to emit a thread start event
3239 * @param key A thread id
3240 * @param value A thread object
3241 * @param user_data Don't care
3244 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3246 if (GPOINTER_TO_INT (key) != debugger_thread_id)
3247 process_profiler_event (EVENT_KIND_THREAD_START, value);
3251 * GFunc to emit an assembly load event
3252 * @param value A loaded assembly
3253 * @param user_data Don't care
3256 emit_assembly_load (gpointer value, gpointer user_data)
3258 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3262 * GFunc to emit a type load event
3263 * @param value A loaded type
3264 * @param user_data Don't care
3267 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3269 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3273 strdup_tolower (char *s)
3278 for (p = s2; *p; ++p)
3284 * Same as g_path_get_basename () but handles windows paths as well,
3285 * which can occur in .mdb files created by pdb2mdb.
3288 dbg_path_get_basename (const char *filename)
3292 if (!filename || strchr (filename, '/') || !strchr (filename, '\\'))
3293 return g_path_get_basename (filename);
3297 /* No separator -> filename */
3298 r = strrchr (filename, '\\');
3300 return g_strdup (filename);
3302 /* Trailing slash, remove component */
3304 char *copy = g_strdup (filename);
3305 copy [r-filename] = 0;
3306 r = strrchr (copy, '\\');
3310 return g_strdup ("/");
3312 r = g_strdup (&r[1]);
3317 return g_strdup (&r[1]);
3321 init_jit_info_dbg_attrs (MonoJitInfo *ji)
3323 static MonoClass *hidden_klass, *step_through_klass, *non_user_klass;
3324 MonoCustomAttrInfo *ainfo;
3326 if (ji->dbg_attrs_inited)
3329 if (!hidden_klass) {
3330 hidden_klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3331 g_assert (hidden_klass);
3333 if (!step_through_klass) {
3334 step_through_klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3335 g_assert (step_through_klass);
3337 if (!non_user_klass) {
3338 non_user_klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute");
3339 g_assert (non_user_klass);
3342 ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji));
3344 if (mono_custom_attrs_has_attr (ainfo, hidden_klass))
3345 ji->dbg_hidden = TRUE;
3346 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3347 ji->dbg_step_through = TRUE;
3348 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3349 ji->dbg_non_user_code = TRUE;
3350 mono_custom_attrs_free (ainfo);
3353 ainfo = mono_custom_attrs_from_class (jinfo_get_method (ji)->klass);
3355 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3356 ji->dbg_step_through = TRUE;
3357 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3358 ji->dbg_non_user_code = TRUE;
3359 mono_custom_attrs_free (ainfo);
3362 mono_memory_barrier ();
3363 ji->dbg_attrs_inited = TRUE;
3371 * create_event_list:
3373 * Return a list of event request ids matching EVENT, starting from REQS, which
3374 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3376 * We return request ids, instead of requests, to simplify threading, since
3377 * requests could be deleted anytime when the loader lock is not held.
3378 * LOCKING: Assumes the loader lock is held.
3381 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3384 GSList *events = NULL;
3386 *suspend_policy = SUSPEND_POLICY_NONE;
3389 reqs = event_requests;
3394 for (i = 0; i < reqs->len; ++i) {
3395 EventRequest *req = g_ptr_array_index (reqs, i);
3396 if (req->event_kind == event) {
3397 gboolean filtered = FALSE;
3400 for (j = 0; j < req->nmodifiers; ++j) {
3401 Modifier *mod = &req->modifiers [j];
3403 if (mod->kind == MOD_KIND_COUNT) {
3405 if (mod->data.count > 0) {
3406 if (mod->data.count > 0) {
3408 if (mod->data.count == 0)
3412 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3413 if (mod->data.thread != mono_thread_internal_current ())
3415 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3416 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3418 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3420 if (ei->caught && !mod->caught)
3422 if (!ei->caught && !mod->uncaught)
3424 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3426 gboolean found = FALSE;
3427 MonoAssembly **assemblies = mod->data.assemblies;
3430 for (k = 0; assemblies [k]; ++k)
3431 if (assemblies [k] == jinfo_get_method (ji)->klass->image->assembly)
3436 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3437 gpointer iter = NULL;
3439 MonoDebugSourceInfo *sinfo;
3440 char *source_file, *s;
3441 gboolean found = FALSE;
3443 GPtrArray *source_file_list;
3445 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3446 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3449 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, NULL, NULL, NULL);
3450 for (i = 0; i < source_file_list->len; ++i) {
3451 sinfo = g_ptr_array_index (source_file_list, i);
3453 * Do a case-insesitive match by converting the file name to
3456 s = strdup_tolower (sinfo->source_file);
3457 if (g_hash_table_lookup (mod->data.source_files, s))
3460 char *s2 = dbg_path_get_basename (sinfo->source_file);
3461 char *s3 = strdup_tolower (s2);
3463 if (g_hash_table_lookup (mod->data.source_files, s3))
3470 g_ptr_array_free (source_file_list, TRUE);
3475 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3478 s = mono_type_full_name (&ei->klass->byval_arg);
3479 if (!g_hash_table_lookup (mod->data.type_names, s))
3482 } else if (mod->kind == MOD_KIND_STEP) {
3483 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3484 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3485 !strcmp (jinfo_get_method (ji)->name, ".cctor") &&
3486 (jinfo_get_method (ji) != ((SingleStepReq*)req->info)->start_method))
3488 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3489 init_jit_info_dbg_attrs (ji);
3493 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3494 init_jit_info_dbg_attrs (ji);
3495 if (ji->dbg_step_through)
3498 if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3499 init_jit_info_dbg_attrs (ji);
3500 if (ji->dbg_non_user_code)
3507 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3508 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3513 /* Send a VM START/DEATH event by default */
3514 if (event == EVENT_KIND_VM_START)
3515 events = g_slist_append (events, GINT_TO_POINTER (0));
3516 if (event == EVENT_KIND_VM_DEATH)
3517 events = g_slist_append (events, GINT_TO_POINTER (0));
3522 static G_GNUC_UNUSED const char*
3523 event_to_string (EventKind event)
3526 case EVENT_KIND_VM_START: return "VM_START";
3527 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3528 case EVENT_KIND_THREAD_START: return "THREAD_START";
3529 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3530 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3531 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3532 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3533 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3534 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3535 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3536 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3537 case EVENT_KIND_STEP: return "STEP";
3538 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3539 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3540 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3541 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3542 case EVENT_KIND_USER_LOG: return "USER_LOG";
3544 g_assert_not_reached ();
3552 * Send an event to the client, suspending the vm if needed.
3553 * LOCKING: Since this can suspend the calling thread, no locks should be held
3555 * The EVENTS list is freed by this function.
3558 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3562 MonoDomain *domain = mono_domain_get ();
3563 MonoThread *thread = NULL;
3564 MonoObject *keepalive_obj = NULL;
3565 gboolean send_success = FALSE;
3570 DEBUG_PRINTF (2, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event));
3574 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3575 // FIXME: We miss those events
3576 DEBUG_PRINTF (2, "VM start event not sent yet: dropping %s\n", event_to_string (event));
3580 if (vm_death_event_sent) {
3581 DEBUG_PRINTF (2, "VM death event has been sent: dropping %s\n", event_to_string (event));
3585 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3586 DEBUG_PRINTF (2, "Mono runtime is shutting down: dropping %s\n", event_to_string (event));
3591 DEBUG_PRINTF (2, "Debugger client is not connected: dropping %s\n", event_to_string (event));
3595 if (event == EVENT_KIND_KEEPALIVE)
3596 suspend_policy = SUSPEND_POLICY_NONE;
3601 if (agent_config.defer) {
3602 /* Make sure the thread id is always set when doing deferred debugging */
3603 if (debugger_thread_id == GetCurrentThreadId ()) {
3604 /* Don't suspend on events from the debugger thread */
3605 suspend_policy = SUSPEND_POLICY_NONE;
3606 thread = mono_thread_get_main ();
3608 else thread = mono_thread_current ();
3610 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3611 // FIXME: Send these with a NULL thread, don't suspend the current thread
3616 nevents = g_slist_length (events);
3617 buffer_init (&buf, 128);
3618 buffer_add_byte (&buf, suspend_policy);
3619 buffer_add_int (&buf, nevents);
3621 for (l = events; l; l = l->next) {
3622 buffer_add_byte (&buf, event); // event kind
3623 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3628 thread = mono_thread_current ();
3630 if (event == EVENT_KIND_VM_START && arg != NULL)
3633 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3636 case EVENT_KIND_THREAD_START:
3637 case EVENT_KIND_THREAD_DEATH:
3639 case EVENT_KIND_APPDOMAIN_CREATE:
3640 case EVENT_KIND_APPDOMAIN_UNLOAD:
3641 buffer_add_domainid (&buf, arg);
3643 case EVENT_KIND_METHOD_ENTRY:
3644 case EVENT_KIND_METHOD_EXIT:
3645 buffer_add_methodid (&buf, domain, arg);
3647 case EVENT_KIND_ASSEMBLY_LOAD:
3648 buffer_add_assemblyid (&buf, domain, arg);
3650 case EVENT_KIND_ASSEMBLY_UNLOAD: {
3651 DebuggerTlsData *tls;
3653 /* The domain the assembly belonged to is not equal to the current domain */
3654 tls = mono_native_tls_get_value (debugger_tls_id);
3656 g_assert (tls->domain_unloading);
3658 buffer_add_assemblyid (&buf, tls->domain_unloading, arg);
3661 case EVENT_KIND_TYPE_LOAD:
3662 buffer_add_typeid (&buf, domain, arg);
3664 case EVENT_KIND_BREAKPOINT:
3665 case EVENT_KIND_STEP:
3666 buffer_add_methodid (&buf, domain, arg);
3667 buffer_add_long (&buf, il_offset);
3669 case EVENT_KIND_VM_START:
3670 buffer_add_domainid (&buf, mono_get_root_domain ());
3672 case EVENT_KIND_VM_DEATH:
3673 if (CHECK_PROTOCOL_VERSION (2, 27))
3674 buffer_add_int (&buf, mono_environment_exitcode_get ());
3676 case EVENT_KIND_EXCEPTION: {
3677 EventInfo *ei = arg;
3678 buffer_add_objid (&buf, ei->exc);
3680 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3681 * later after the suspension. (#12494).
3683 keepalive_obj = ei->exc;
3686 case EVENT_KIND_USER_BREAK:
3688 case EVENT_KIND_USER_LOG: {
3689 EventInfo *ei = arg;
3690 buffer_add_int (&buf, ei->level);
3691 buffer_add_string (&buf, ei->category ? ei->category : "");
3692 buffer_add_string (&buf, ei->message ? ei->message : "");
3695 case EVENT_KIND_KEEPALIVE:
3696 suspend_policy = SUSPEND_POLICY_NONE;
3699 g_assert_not_reached ();
3703 if (event == EVENT_KIND_VM_START) {
3704 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3705 if (!agent_config.defer)
3706 start_debugger_thread ();
3709 if (event == EVENT_KIND_VM_DEATH) {
3710 vm_death_event_sent = TRUE;
3711 suspend_policy = SUSPEND_POLICY_NONE;
3714 if (mono_runtime_is_shutting_down ())
3715 suspend_policy = SUSPEND_POLICY_NONE;
3717 if (suspend_policy != SUSPEND_POLICY_NONE) {
3719 * Save the thread context and start suspending before sending the packet,
3720 * since we could be receiving the resume request before send_packet ()
3723 save_thread_context (ctx);
3727 /* This will keep this object alive */
3728 get_objref (keepalive_obj);
3731 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3735 g_slist_free (events);
3738 if (!send_success) {
3739 DEBUG_PRINTF (2, "Sending command %s failed.\n", event_to_string (event));
3743 if (event == EVENT_KIND_VM_START) {
3744 vm_start_event_sent = TRUE;
3747 DEBUG_PRINTF (1, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer)GetCurrentThreadId (), nevents, event_to_string (event), ecount, suspend_policy);
3749 switch (suspend_policy) {
3750 case SUSPEND_POLICY_NONE:
3752 case SUSPEND_POLICY_ALL:
3755 case SUSPEND_POLICY_EVENT_THREAD:
3759 g_assert_not_reached ();
3764 process_profiler_event (EventKind event, gpointer arg)
3768 EventInfo ei, *ei_arg = NULL;
3770 if (event == EVENT_KIND_TYPE_LOAD) {
3775 mono_loader_lock ();
3776 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3777 mono_loader_unlock ();
3779 process_event (event, arg, 0, NULL, events, suspend_policy);
3783 runtime_initialized (MonoProfiler *prof)
3785 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3786 if (agent_config.defer)
3787 start_debugger_thread ();
3791 runtime_shutdown (MonoProfiler *prof)
3793 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3795 mono_debugger_agent_cleanup ();
3799 thread_startup (MonoProfiler *prof, uintptr_t tid)
3801 MonoInternalThread *thread = mono_thread_internal_current ();
3802 MonoInternalThread *old_thread;
3803 DebuggerTlsData *tls;
3805 if (tid == debugger_thread_id)
3808 g_assert (thread->tid == tid);
3810 mono_loader_lock ();
3811 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3812 mono_loader_unlock ();
3814 if (thread == old_thread) {
3816 * For some reason, thread_startup () might be called for the same thread
3817 * multiple times (attach ?).
3819 DEBUG_PRINTF (1, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid);
3823 * thread_end () might not be called for some threads, and the tid could
3826 DEBUG_PRINTF (1, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid);
3827 mono_loader_lock ();
3828 mono_g_hash_table_remove (thread_to_tls, old_thread);
3829 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3830 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3831 mono_loader_unlock ();
3835 tls = mono_native_tls_get_value (debugger_tls_id);
3837 // FIXME: Free this somewhere
3838 tls = g_new0 (DebuggerTlsData, 1);
3839 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread, MONO_ROOT_SOURCE_DEBUGGER, "debugger thread reference");
3840 tls->thread = thread;
3841 mono_native_tls_set_value (debugger_tls_id, tls);
3843 DEBUG_PRINTF (1, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3845 mono_loader_lock ();
3846 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3847 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3848 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3849 mono_loader_unlock ();
3851 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3854 * suspend_vm () could have missed this thread, so wait for a resume.
3860 thread_end (MonoProfiler *prof, uintptr_t tid)
3862 MonoInternalThread *thread;
3863 DebuggerTlsData *tls = NULL;
3865 mono_loader_lock ();
3866 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3868 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3869 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3871 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3872 tls->terminated = TRUE;
3873 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3874 MONO_GC_UNREGISTER_ROOT (tls->thread);
3878 mono_loader_unlock ();
3880 /* We might be called for threads started before we registered the start callback */
3882 DEBUG_PRINTF (1, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3884 if (GetCurrentThreadId () == tid && !mono_native_tls_get_value (debugger_tls_id)) {
3886 * This can happen on darwin since we deregister threads using pthread dtors.
3887 * process_profiler_event () and the code it calls cannot handle a null TLS value.
3892 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3897 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3899 mono_loader_lock ();
3900 g_hash_table_insert (domains, domain, domain);
3901 mono_loader_unlock ();
3903 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3907 appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain)
3909 DebuggerTlsData *tls;
3911 /* This might be called during shutdown on the debugger thread from the CMD_VM_EXIT code */
3912 if (is_debugger_thread ())
3916 * Remember the currently unloading appdomain as it is needed to generate
3917 * proper ids for unloading assemblies.
3919 tls = mono_native_tls_get_value (debugger_tls_id);
3921 tls->domain_unloading = domain;
3925 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3927 DebuggerTlsData *tls;
3929 if (is_debugger_thread ())
3932 tls = mono_native_tls_get_value (debugger_tls_id);
3934 tls->domain_unloading = NULL;
3936 clear_breakpoints_for_domain (domain);
3938 mono_loader_lock ();
3939 /* Invalidate each thread's frame stack */
3940 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3941 mono_loader_unlock ();
3943 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3947 * invalidate_each_thread:
3949 * A GHFunc to invalidate frames.
3950 * value must be a DebuggerTlsData*
3953 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3955 invalidate_frames (value);
3959 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3961 /* Sent later in jit_end () */
3963 g_ptr_array_add (pending_assembly_loads, assembly);
3968 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3970 if (is_debugger_thread ())
3973 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3975 clear_event_requests_for_assembly (assembly);
3976 clear_types_for_assembly (assembly);
3980 send_type_load (MonoClass *klass)
3982 gboolean type_load = FALSE;
3983 MonoDomain *domain = mono_domain_get ();
3984 AgentDomainInfo *info = NULL;
3986 info = get_agent_domain_info (domain);
3988 mono_loader_lock ();
3990 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
3992 g_hash_table_insert (info->loaded_classes, klass, klass);
3995 mono_loader_unlock ();
3998 emit_type_load (klass, klass, NULL);
4002 * Emit load events for all types currently loaded in the domain.
4003 * Takes the loader and domain locks.
4004 * user_data is unused.
4007 send_types_for_domain (MonoDomain *domain, void *user_data)
4009 AgentDomainInfo *info = NULL;
4011 info = get_agent_domain_info (domain);
4014 mono_loader_lock ();
4015 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4016 mono_loader_unlock ();
4020 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
4023 * We emit type load events when the first method of the type is JITted,
4024 * since the class load profiler callbacks might be called with the
4025 * loader lock held. They could also occur in the debugger thread.
4026 * Same for assembly load events.
4029 MonoAssembly *assembly = NULL;
4031 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4033 if (pending_assembly_loads->len > 0) {
4034 assembly = g_ptr_array_index (pending_assembly_loads, 0);
4035 g_ptr_array_remove_index (pending_assembly_loads, 0);
4040 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4046 send_type_load (method->klass);
4049 add_pending_breakpoints (method, jinfo);
4053 * BREAKPOINTS/SINGLE STEPPING
4057 * Contains information about an inserted breakpoint.
4060 long il_offset, native_offset;
4064 } BreakpointInstance;
4067 * Contains generic information about a breakpoint.
4071 * The method where the breakpoint is placed. Can be NULL in which case it
4072 * is inserted into every method. This is used to implement method entry/
4073 * exit events. Can be a generic method definition, in which case the
4074 * breakpoint is inserted into every instance.
4080 * A list of BreakpointInstance structures describing where the breakpoint
4081 * was inserted. There could be more than one because of
4082 * generics/appdomains/method entry/exit.
4084 GPtrArray *children;
4087 /* List of breakpoints */
4088 /* Protected by the loader lock */
4089 static GPtrArray *breakpoints;
4090 /* Maps breakpoint locations to the number of breakpoints at that location */
4091 static GHashTable *bp_locs;
4094 breakpoints_init (void)
4096 breakpoints = g_ptr_array_new ();
4097 bp_locs = g_hash_table_new (NULL, NULL);
4101 * insert_breakpoint:
4103 * Insert the breakpoint described by BP into the method described by
4107 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4110 BreakpointInstance *inst;
4111 SeqPointIterator it;
4112 gboolean it_has_sp = FALSE;
4115 mono_error_init (error);
4117 mono_seq_point_iterator_init (&it, seq_points);
4118 while (mono_seq_point_iterator_next (&it)) {
4119 if (it.seq_point.il_offset == bp->il_offset) {
4127 * The set of IL offsets with seq points doesn't completely match the
4128 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4130 mono_seq_point_iterator_init (&it, seq_points);
4131 while (mono_seq_point_iterator_next (&it)) {
4132 if (it.seq_point.il_offset != METHOD_ENTRY_IL_OFFSET &&
4133 it.seq_point.il_offset != METHOD_EXIT_IL_OFFSET &&
4134 it.seq_point.il_offset + 1 == bp->il_offset) {
4142 char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d", mono_method_full_name (jinfo_get_method (ji), TRUE), bp->il_offset);
4144 mono_seq_point_iterator_init (&it, seq_points);
4145 while (mono_seq_point_iterator_next (&it))
4146 DEBUG_PRINTF (1, "%d\n", it.seq_point.il_offset);
4149 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4150 g_warning ("%s", s);
4154 g_warning ("%s", s);
4160 inst = g_new0 (BreakpointInstance, 1);
4161 inst->il_offset = it.seq_point.il_offset;
4162 inst->native_offset = it.seq_point.native_offset;
4163 inst->ip = (guint8*)ji->code_start + it.seq_point.native_offset;
4165 inst->domain = domain;
4167 mono_loader_lock ();
4169 g_ptr_array_add (bp->children, inst);
4171 mono_loader_unlock ();
4174 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4175 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4178 if (it.seq_point.native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4179 DEBUG_PRINTF (1, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset);
4180 } else if (count == 0) {
4181 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4182 mono_arch_set_breakpoint (ji, inst->ip);
4188 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);
4192 remove_breakpoint (BreakpointInstance *inst)
4194 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4196 MonoJitInfo *ji = inst->ji;
4197 guint8 *ip = inst->ip;
4200 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4201 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4204 g_assert (count > 0);
4206 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4207 mono_arch_clear_breakpoint (ji, ip);
4208 DEBUG_PRINTF (1, "[dbg] Clear breakpoint at %s [%p].\n", mono_method_full_name (jinfo_get_method (ji), TRUE), ip);
4216 * This doesn't take any locks.
4218 static inline gboolean
4219 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4225 if (method == bp->method)
4227 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4230 if (bp->method->is_inflated && method->is_inflated) {
4231 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4232 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4234 /* Open generic methods should match closed generic methods of the same class */
4235 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4236 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4237 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4239 /* FIXME: Handle !mvar */
4240 if (t1->type != MONO_TYPE_MVAR)
4251 * add_pending_breakpoints:
4253 * Insert pending breakpoints into the newly JITted method METHOD.
4256 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4259 MonoSeqPointInfo *seq_points;
4261 MonoMethod *jmethod;
4266 domain = mono_domain_get ();
4268 mono_loader_lock ();
4270 for (i = 0; i < breakpoints->len; ++i) {
4271 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4272 gboolean found = FALSE;
4274 if (!bp_matches_method (bp, method))
4277 for (j = 0; j < bp->children->len; ++j) {
4278 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4285 MonoMethod *declaring = NULL;
4287 jmethod = jinfo_get_method (ji);
4288 if (jmethod->is_inflated)
4289 declaring = mono_method_get_declaring_generic_method (jmethod);
4291 mono_domain_lock (domain);
4292 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, jmethod);
4293 if (!seq_points && declaring)
4294 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, declaring);
4295 mono_domain_unlock (domain);
4297 /* Could be AOT code */
4299 g_assert (seq_points);
4301 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4305 mono_loader_unlock ();
4309 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4315 mono_error_init (error);
4317 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4319 /* Might be AOTed code */
4320 code = mono_aot_get_method (domain, method);
4322 ji = mono_jit_info_table_find (domain, code);
4327 insert_breakpoint (seq_points, domain, ji, bp, error);
4331 clear_breakpoint (MonoBreakpoint *bp);
4336 * Set a breakpoint at IL_OFFSET in METHOD.
4337 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4338 * METHOD can also be a generic method definition, in which case a breakpoint
4339 * is placed in all instances of the method.
4340 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4343 static MonoBreakpoint*
4344 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4347 GHashTableIter iter, iter2;
4350 MonoSeqPointInfo *seq_points;
4352 GPtrArray *method_domains;
4353 GPtrArray *method_seq_points;
4357 mono_error_init (error);
4360 // - suspend/resume the vm to prevent code patching problems
4361 // - multiple breakpoints on the same location
4362 // - dynamic methods
4365 bp = g_new0 (MonoBreakpoint, 1);
4366 bp->method = method;
4367 bp->il_offset = il_offset;
4369 bp->children = g_ptr_array_new ();
4371 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);
4373 methods = g_ptr_array_new ();
4374 method_domains = g_ptr_array_new ();
4375 method_seq_points = g_ptr_array_new ();
4377 mono_loader_lock ();
4378 g_hash_table_iter_init (&iter, domains);
4379 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4380 mono_domain_lock (domain);
4381 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4382 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4383 if (bp_matches_method (bp, m)) {
4384 /* Save the info locally to simplify the code inside the domain lock */
4385 g_ptr_array_add (methods, m);
4386 g_ptr_array_add (method_domains, domain);
4387 g_ptr_array_add (method_seq_points, seq_points);
4390 mono_domain_unlock (domain);
4393 for (i = 0; i < methods->len; ++i) {
4394 m = g_ptr_array_index (methods, i);
4395 domain = g_ptr_array_index (method_domains, i);
4396 seq_points = g_ptr_array_index (method_seq_points, i);
4397 set_bp_in_method (domain, m, seq_points, bp, error);
4400 g_ptr_array_add (breakpoints, bp);
4401 mono_loader_unlock ();
4403 g_ptr_array_free (methods, TRUE);
4404 g_ptr_array_free (method_domains, TRUE);
4405 g_ptr_array_free (method_seq_points, TRUE);
4407 if (error && !mono_error_ok (error)) {
4408 clear_breakpoint (bp);
4416 clear_breakpoint (MonoBreakpoint *bp)
4420 // FIXME: locking, races
4421 for (i = 0; i < bp->children->len; ++i) {
4422 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4424 remove_breakpoint (inst);
4429 mono_loader_lock ();
4430 g_ptr_array_remove (breakpoints, bp);
4431 mono_loader_unlock ();
4433 g_ptr_array_free (bp->children, TRUE);
4438 breakpoints_cleanup (void)
4442 mono_loader_lock ();
4444 while (i < event_requests->len) {
4445 EventRequest *req = g_ptr_array_index (event_requests, i);
4447 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4448 clear_breakpoint (req->info);
4449 g_ptr_array_remove_index_fast (event_requests, i);
4456 for (i = 0; i < breakpoints->len; ++i)
4457 g_free (g_ptr_array_index (breakpoints, i));
4459 g_ptr_array_free (breakpoints, TRUE);
4460 g_hash_table_destroy (bp_locs);
4465 mono_loader_unlock ();
4469 * clear_breakpoints_for_domain:
4471 * Clear breakpoint instances which reference DOMAIN.
4474 clear_breakpoints_for_domain (MonoDomain *domain)
4478 /* This could be called after shutdown */
4482 mono_loader_lock ();
4483 for (i = 0; i < breakpoints->len; ++i) {
4484 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4487 while (j < bp->children->len) {
4488 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4490 if (inst->domain == domain) {
4491 remove_breakpoint (inst);
4495 g_ptr_array_remove_index_fast (bp->children, j);
4501 mono_loader_unlock ();
4507 * Return FALSE if single stepping needs to continue.
4510 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp, DebuggerTlsData *tls, MonoContext *ctx)
4512 MonoDebugMethodInfo *minfo;
4513 MonoDebugSourceLocation *loc = NULL;
4514 gboolean hit = TRUE;
4517 if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK)) {
4519 * These seq points are inserted by the JIT after calls, step over needs to skip them.
4521 DEBUG_PRINTF (1, "[%p] Seq point at nonempty stack %x while stepping over, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset);
4525 if (req->depth == STEP_DEPTH_OVER && hit) {
4526 if (!tls->context.valid)
4527 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4528 compute_frame_info (tls->thread, tls);
4529 if (req->nframes && tls->frame_count && tls->frame_count > req->nframes) {
4530 /* Hit the breakpoint in a recursive call */
4531 DEBUG_PRINTF (1, "[%p] Breakpoint at lower frame while stepping over, continuing single stepping.\n", (gpointer)GetCurrentThreadId ());
4536 if (req->depth == STEP_DEPTH_INTO && req->size == STEP_SIZE_MIN && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) && ss_req->start_method){
4537 method = jinfo_get_method (ji);
4538 if (!tls->context.valid)
4539 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4540 compute_frame_info (tls->thread, tls);
4541 if (ss_req->start_method == method && req->nframes && tls->frame_count == req->nframes) {//Check also frame count(could be recursion)
4542 DEBUG_PRINTF (1, "[%p] Seq point at nonempty stack %x while stepping in, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset);
4547 if (req->size != STEP_SIZE_LINE)
4550 /* Have to check whenever a different source line was reached */
4551 method = jinfo_get_method (ji);
4552 minfo = mono_debug_lookup_method (method);
4555 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4558 DEBUG_PRINTF (1, "[%p] No line number info for il offset %x, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset);
4559 ss_req->last_method = method;
4561 } else if (loc && method == ss_req->last_method && loc->row == ss_req->last_line) {
4562 DEBUG_PRINTF (1, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer)GetCurrentThreadId (), loc->row);
4567 ss_req->last_method = method;
4568 ss_req->last_line = loc->row;
4569 mono_debug_free_source_location (loc);
4576 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4578 return bp->method && bp->method->klass->image->assembly == assembly;
4582 process_breakpoint_inner (DebuggerTlsData *tls, gboolean from_signal)
4586 int i, j, suspend_policy;
4587 guint32 native_offset;
4589 BreakpointInstance *inst;
4590 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4591 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4592 EventKind kind = EVENT_KIND_BREAKPOINT;
4593 MonoContext *ctx = &tls->restore_state.ctx;
4595 MonoSeqPointInfo *info;
4599 // FIXME: Speed this up
4601 ip = MONO_CONTEXT_GET_IP (ctx);
4602 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4603 g_assert (ji && !ji->is_trampoline);
4604 method = jinfo_get_method (ji);
4606 /* Compute the native offset of the breakpoint from the ip */
4607 native_offset = ip - (guint8*)ji->code_start;
4610 * Skip the instruction causing the breakpoint signal.
4613 mono_arch_skip_breakpoint (ctx, ji);
4615 if (method->wrapper_type || tls->disable_breakpoints)
4618 bp_reqs = g_ptr_array_new ();
4619 ss_reqs = g_ptr_array_new ();
4620 ss_reqs_orig = g_ptr_array_new ();
4622 mono_loader_lock ();
4625 * The ip points to the instruction causing the breakpoint event, which is after
4626 * the offset recorded in the seq point map, so find the prev seq point before ip.
4628 found_sp = mono_find_prev_seq_point_for_native_offset (mono_domain_get (), method, native_offset, &info, &sp);
4631 no_seq_points_found (method);
4633 g_assert (found_sp);
4635 DEBUG_PRINTF (1, "[%p] Breakpoint hit, method=%s, ip=%p, [il=0x%x,native=0x%x].\n", (gpointer)GetCurrentThreadId (), method->name, ip, sp.il_offset, native_offset);
4638 for (i = 0; i < breakpoints->len; ++i) {
4639 bp = g_ptr_array_index (breakpoints, i);
4644 for (j = 0; j < bp->children->len; ++j) {
4645 inst = g_ptr_array_index (bp->children, j);
4646 if (inst->ji == ji && inst->il_offset == sp.il_offset && inst->native_offset == sp.native_offset) {
4647 if (bp->req->event_kind == EVENT_KIND_STEP) {
4648 g_ptr_array_add (ss_reqs_orig, bp->req);
4650 g_ptr_array_add (bp_reqs, bp->req);
4655 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4656 /* Maybe a method entry/exit event */
4657 if (sp.il_offset == METHOD_ENTRY_IL_OFFSET)
4658 kind = EVENT_KIND_METHOD_ENTRY;
4659 else if (sp.il_offset == METHOD_EXIT_IL_OFFSET)
4660 kind = EVENT_KIND_METHOD_EXIT;
4663 /* Process single step requests */
4664 for (i = 0; i < ss_reqs_orig->len; ++i) {
4665 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4666 SingleStepReq *ss_req = req->info;
4669 if (mono_thread_internal_current () != ss_req->thread)
4672 hit = ss_update (ss_req, ji, &sp, tls, ctx);
4674 g_ptr_array_add (ss_reqs, req);
4676 /* Start single stepping again from the current sequence point */
4677 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
4680 if (ss_reqs->len > 0)
4681 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4682 if (bp_reqs->len > 0)
4683 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4684 if (kind != EVENT_KIND_BREAKPOINT)
4685 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4687 mono_loader_unlock ();
4689 g_ptr_array_free (bp_reqs, TRUE);
4690 g_ptr_array_free (ss_reqs, TRUE);
4693 * FIXME: The first event will suspend, so the second will only be sent after the
4697 process_event (EVENT_KIND_STEP, method, 0, ctx, ss_events, suspend_policy);
4699 process_event (kind, method, 0, ctx, bp_events, suspend_policy);
4700 if (enter_leave_events)
4701 process_event (kind, method, 0, ctx, enter_leave_events, suspend_policy);
4704 /* Process a breakpoint/single step event after resuming from a signal handler */
4706 process_signal_event (void (*func) (DebuggerTlsData*, gboolean))
4708 DebuggerTlsData *tls;
4709 MonoThreadUnwindState orig_restore_state;
4712 tls = mono_native_tls_get_value (debugger_tls_id);
4713 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4714 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4715 mono_thread_state_init_from_monoctx (&tls->restore_state, &tls->handler_ctx);
4719 /* This is called when resuming from a signal handler, so it shouldn't return */
4720 memcpy (&ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4721 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4722 mono_restore_context (&ctx);
4723 g_assert_not_reached ();
4727 process_breakpoint (void)
4729 process_signal_event (process_breakpoint_inner);
4733 resume_from_signal_handler (void *sigctx, void *func)
4735 DebuggerTlsData *tls;
4738 /* Save the original context in TLS */
4739 // FIXME: This might not work on an altstack ?
4740 tls = mono_native_tls_get_value (debugger_tls_id);
4742 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer)GetCurrentThreadId ());
4745 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4746 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4747 // clob:c could be added to op_seq_point.
4749 mono_sigctx_to_monoctx (sigctx, &ctx);
4750 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4751 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4752 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4754 MONO_CONTEXT_SET_IP (&ctx, func);
4756 mono_monoctx_to_sigctx (&ctx, sigctx);
4758 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4759 mono_ppc_set_func_into_sigctx (sigctx, func);
4764 mono_debugger_agent_breakpoint_hit (void *sigctx)
4767 * We are called from a signal handler, and running code there causes all kinds of
4768 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4769 * So set up the signal context to return to the real breakpoint handler function.
4771 resume_from_signal_handler (sigctx, process_breakpoint);
4775 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4777 if (frame->managed) {
4778 *(MonoContext*)data = *ctx;
4787 * Called by System.Diagnostics.Debugger:Break ().
4790 mono_debugger_agent_user_break (void)
4792 if (agent_config.enabled) {
4797 /* Obtain a context */
4798 MONO_CONTEXT_SET_IP (&ctx, NULL);
4799 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4800 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4802 mono_loader_lock ();
4803 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4804 mono_loader_unlock ();
4806 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4807 } else if (debug_options.native_debugger_break) {
4813 ss_depth_to_string (StepDepth depth)
4816 case STEP_DEPTH_OVER:
4818 case STEP_DEPTH_OUT:
4820 case STEP_DEPTH_INTO:
4823 g_assert_not_reached ();
4829 process_single_step_inner (DebuggerTlsData *tls, gboolean from_signal)
4834 int il_offset, suspend_policy;
4837 MonoContext *ctx = &tls->restore_state.ctx;
4840 MonoSeqPointInfo *info;
4842 ip = MONO_CONTEXT_GET_IP (ctx);
4844 /* Skip the instruction causing the single step */
4846 mono_arch_skip_single_step (ctx);
4848 if (suspend_count > 0) {
4849 process_suspend (tls, ctx);
4854 // FIXME: A suspend race
4857 if (mono_thread_internal_current () != ss_req->thread)
4860 if (log_level > 0) {
4861 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4863 DEBUG_PRINTF (1, "[%p] Single step event (depth=%s) at %s (%p)[0x%x], sp %p, last sp %p\n", (gpointer)GetCurrentThreadId (), 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);
4866 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4867 g_assert (ji && !ji->is_trampoline);
4868 method = jinfo_get_method (ji);
4871 if (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4876 * Stopping in memset makes half-initialized vtypes visible.
4877 * Stopping in memcpy makes half-copied vtypes visible.
4879 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
4883 * The ip points to the instruction causing the single step event, which is before
4884 * the offset recorded in the seq point map, so find the next seq point after ip.
4886 if (!mono_find_next_seq_point_for_native_offset (domain, method, (guint8*)ip - (guint8*)ji->code_start, &info, &sp))
4889 il_offset = sp.il_offset;
4891 if (!ss_update (ss_req, ji, &sp, tls, ctx))
4894 /* Start single stepping again from the current sequence point */
4895 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
4897 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
4898 (method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4899 !strcmp (method->name, ".cctor"))
4902 // FIXME: Has to lock earlier
4904 reqs = g_ptr_array_new ();
4906 mono_loader_lock ();
4908 g_ptr_array_add (reqs, ss_req->req);
4910 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4912 g_ptr_array_free (reqs, TRUE);
4914 mono_loader_unlock ();
4916 process_event (EVENT_KIND_STEP, jinfo_get_method (ji), il_offset, ctx, events, suspend_policy);
4920 process_single_step (void)
4922 process_signal_event (process_single_step_inner);
4926 * mono_debugger_agent_single_step_event:
4928 * Called from a signal handler to handle a single step event.
4931 mono_debugger_agent_single_step_event (void *sigctx)
4933 /* Resume to process_single_step through the signal context */
4935 // FIXME: Since step out/over is implemented using step in, the step in case should
4936 // be as fast as possible. Move the relevant code from process_single_step_inner ()
4939 if (GetCurrentThreadId () == debugger_thread_id) {
4941 * This could happen despite our best effors when the runtime calls
4942 * assembly/type resolve hooks.
4943 * FIXME: Breakpoints too.
4947 mono_sigctx_to_monoctx (sigctx, &ctx);
4948 mono_arch_skip_single_step (&ctx);
4949 mono_monoctx_to_sigctx (&ctx, sigctx);
4953 resume_from_signal_handler (sigctx, process_single_step);
4957 debugger_agent_single_step_from_context (MonoContext *ctx)
4959 DebuggerTlsData *tls;
4960 MonoThreadUnwindState orig_restore_state;
4962 if (GetCurrentThreadId () == debugger_thread_id)
4965 tls = mono_native_tls_get_value (debugger_tls_id);
4968 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4969 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4970 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
4971 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
4973 process_single_step_inner (tls, FALSE);
4975 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4976 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4980 debugger_agent_breakpoint_from_context (MonoContext *ctx)
4982 DebuggerTlsData *tls;
4983 MonoThreadUnwindState orig_restore_state;
4986 if (GetCurrentThreadId () == debugger_thread_id)
4989 orig_ip = MONO_CONTEXT_GET_IP (ctx);
4990 MONO_CONTEXT_SET_IP (ctx, orig_ip - 1);
4992 tls = mono_native_tls_get_value (debugger_tls_id);
4994 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4995 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
4996 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
4998 process_breakpoint_inner (tls, FALSE);
5000 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5001 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5002 if (MONO_CONTEXT_GET_IP (ctx) == orig_ip - 1)
5003 MONO_CONTEXT_SET_IP (ctx, orig_ip);
5007 * start_single_stepping:
5009 * Turn on single stepping. Can be called multiple times, for example,
5010 * by a single step event request + a suspend.
5013 start_single_stepping (void)
5015 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5016 int val = InterlockedIncrement (&ss_count);
5019 mono_arch_start_single_stepping ();
5021 g_assert_not_reached ();
5026 stop_single_stepping (void)
5028 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5029 int val = InterlockedDecrement (&ss_count);
5032 mono_arch_stop_single_stepping ();
5034 g_assert_not_reached ();
5041 * Stop the single stepping operation given by SS_REQ.
5044 ss_stop (SingleStepReq *ss_req)
5049 for (l = ss_req->bps; l; l = l->next) {
5050 clear_breakpoint (l->data);
5052 g_slist_free (ss_req->bps);
5056 if (ss_req->global) {
5057 stop_single_stepping ();
5058 ss_req->global = FALSE;
5065 * Start the single stepping operation given by SS_REQ from the sequence point SP.
5066 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
5067 * belong to the same thread as CTX.
5068 * If FRAMES is not-null, use that instead of tls->frames for placing breakpoints etc.
5071 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint* sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls,
5072 gboolean step_to_catch, StackFrame **frames, int nframes)
5074 int i, j, frame_index;
5075 SeqPoint *next_sp, *parent_sp = NULL;
5076 SeqPoint local_sp, local_parent_sp;
5079 MonoSeqPointInfo *parent_info;
5080 MonoMethod *parent_sp_method = NULL;
5081 gboolean enable_global = FALSE;
5083 /* Stop the previous operation */
5087 * Implement single stepping using breakpoints if possible.
5089 if (step_to_catch) {
5090 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
5091 ss_req->bps = g_slist_append (ss_req->bps, bp);
5095 if (ctx && !frames) {
5096 /* Need parent frames */
5097 if (!tls->context.valid)
5098 mono_thread_state_init_from_monoctx (&tls->context, ctx);
5099 compute_frame_info (tls->thread, tls);
5100 frames = tls->frames;
5101 nframes = tls->frame_count;
5105 * Find the first sequence point in the current or in a previous frame which
5106 * is not the last in its method.
5108 if (ss_req->depth == STEP_DEPTH_OUT) {
5109 /* Ignore seq points in current method */
5110 while (frame_index < nframes) {
5111 StackFrame *frame = frames [frame_index];
5113 method = frame->method;
5114 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5115 sp = (found_sp)? &local_sp : NULL;
5117 if (sp && sp->next_len != 0)
5120 // There could be method calls before the next seq point in the caller when using nested calls
5121 //enable_global = TRUE;
5123 if (sp && sp->next_len == 0) {
5125 while (frame_index < nframes) {
5126 StackFrame *frame = frames [frame_index];
5128 method = frame->method;
5129 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5130 sp = (found_sp)? &local_sp : NULL;
5131 if (sp && sp->next_len != 0)
5137 /* Have to put a breakpoint into a parent frame since the seq points might not cover all control flow out of the method */
5138 while (frame_index < nframes) {
5139 StackFrame *frame = frames [frame_index];
5141 parent_sp_method = frame->method;
5142 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &parent_info, &local_parent_sp);
5143 parent_sp = found_sp ? &local_parent_sp : NULL;
5144 if (found_sp && parent_sp->next_len != 0)
5152 if (sp && sp->next_len > 0) {
5153 SeqPoint* next = g_new(SeqPoint, sp->next_len);
5155 mono_seq_point_init_next (info, *sp, next);
5156 for (i = 0; i < sp->next_len; i++) {
5159 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
5160 ss_req->bps = g_slist_append (ss_req->bps, bp);
5166 SeqPoint* next = g_new(SeqPoint, parent_sp->next_len);
5168 mono_seq_point_init_next (parent_info, *parent_sp, next);
5169 for (i = 0; i < parent_sp->next_len; i++) {
5172 bp = set_breakpoint (parent_sp_method, next_sp->il_offset, ss_req->req, NULL);
5173 ss_req->bps = g_slist_append (ss_req->bps, bp);
5178 if (ss_req->nframes == 0)
5179 ss_req->nframes = nframes;
5181 if ((ss_req->depth == STEP_DEPTH_OVER) && (!sp && !parent_sp)) {
5182 DEBUG_PRINTF (1, "[dbg] No parent frame for step over, transition to step into.\n");
5184 * This is needed since if we leave managed code, and later return to it, step over
5185 * is not going to stop.
5186 * This approach is a bit ugly, since we change the step depth, but it only affects
5187 * clients who reuse the same step request, and only in this special case.
5189 ss_req->depth = STEP_DEPTH_INTO;
5192 if (ss_req->depth == STEP_DEPTH_OVER) {
5193 /* Need to stop in catch clauses as well */
5194 for (i = 0; i < nframes; ++i) {
5195 StackFrame *frame = frames [i];
5198 MonoJitInfo *jinfo = frame->ji;
5199 for (j = 0; j < jinfo->num_clauses; ++j) {
5200 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5202 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);
5203 sp = (found_sp)? &local_sp : NULL;
5205 bp = set_breakpoint (frame->method, sp->il_offset, ss_req->req, NULL);
5206 ss_req->bps = g_slist_append (ss_req->bps, bp);
5213 if (ss_req->depth == STEP_DEPTH_INTO) {
5214 /* Enable global stepping so we stop at method entry too */
5215 enable_global = TRUE;
5219 * The ctx/frame info computed above will become invalid when we continue.
5221 tls->context.valid = FALSE;
5222 tls->async_state.valid = FALSE;
5223 invalidate_frames (tls);
5226 if (enable_global) {
5227 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5228 ss_req->global = TRUE;
5229 start_single_stepping ();
5230 } else if (!ss_req->bps) {
5231 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5232 ss_req->global = TRUE;
5233 start_single_stepping ();
5235 ss_req->global = FALSE;
5240 * Start single stepping of thread THREAD
5243 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req)
5245 DebuggerTlsData *tls;
5246 MonoSeqPointInfo *info = NULL;
5247 SeqPoint *sp = NULL;
5250 MonoMethod *method = NULL;
5251 MonoDebugMethodInfo *minfo;
5252 gboolean step_to_catch = FALSE;
5253 gboolean set_ip = FALSE;
5254 StackFrame **frames = NULL;
5257 if (suspend_count == 0)
5258 return ERR_NOT_SUSPENDED;
5260 wait_for_suspend ();
5262 // FIXME: Multiple requests
5264 DEBUG_PRINTF (0, "Received a single step request while the previous one was still active.\n");
5265 return ERR_NOT_IMPLEMENTED;
5268 DEBUG_PRINTF (1, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth));
5270 ss_req = g_new0 (SingleStepReq, 1);
5272 ss_req->thread = thread;
5273 ss_req->size = size;
5274 ss_req->depth = depth;
5275 ss_req->filter = filter;
5278 mono_loader_lock ();
5279 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5280 mono_loader_unlock ();
5282 g_assert (tls->context.valid);
5284 if (tls->restore_state.valid && MONO_CONTEXT_GET_IP (&tls->context.ctx) != MONO_CONTEXT_GET_IP (&tls->restore_state.ctx)) {
5286 * Need to start single stepping from restore_state and not from the current state
5289 frames = compute_frame_info_from (thread, tls, &tls->restore_state, &nframes);
5292 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5294 if (tls->catch_state.valid) {
5296 StackFrameInfo frame;
5297 MonoContext new_ctx;
5298 MonoLMF *lmf = NULL;
5301 * We are stopped at a throw site. Stepping should go to the catch site.
5304 /* Find the the jit info for the catch context */
5305 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);
5307 g_assert (frame.type == FRAME_TYPE_MANAGED);
5310 * Find the seq point corresponding to the landing site ip, which is the first seq
5313 found_sp = mono_find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info, &local_sp);
5314 sp = (found_sp)? &local_sp : NULL;
5316 no_seq_points_found (frame.method);
5319 method = frame.method;
5321 step_to_catch = TRUE;
5322 /* This make sure the seq point is not skipped by process_single_step () */
5323 ss_req->last_sp = NULL;
5326 if (!step_to_catch) {
5327 StackFrame *frame = NULL;
5330 if (frames && nframes)
5333 compute_frame_info (thread, tls);
5335 if (tls->frame_count)
5336 frame = tls->frames [0];
5339 if (ss_req->size == STEP_SIZE_LINE) {
5341 ss_req->last_method = frame->method;
5342 ss_req->last_line = -1;
5344 minfo = mono_debug_lookup_method (frame->method);
5345 if (minfo && frame->il_offset != -1) {
5346 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
5349 ss_req->last_line = loc->row;
5357 if (!method && frame->il_offset != -1) {
5358 /* FIXME: Sort the table and use a binary search */
5359 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5360 sp = (found_sp)? &local_sp : NULL;
5362 no_seq_points_found (frame->method);
5364 method = frame->method;
5369 ss_req->start_method = method;
5371 ss_start (ss_req, method, sp, info, set_ip ? &tls->restore_state.ctx : &tls->context.ctx, tls, step_to_catch, frames, nframes);
5374 free_frames (frames, nframes);
5380 ss_destroy (SingleStepReq *req)
5383 g_assert (ss_req == req);
5392 ss_clear_for_assembly (SingleStepReq *req, MonoAssembly *assembly)
5395 gboolean found = TRUE;
5399 for (l = ss_req->bps; l; l = l->next) {
5400 if (breakpoint_matches_assembly (l->data, assembly)) {
5401 clear_breakpoint (l->data);
5402 ss_req->bps = g_slist_delete_link (ss_req->bps, l);
5411 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5414 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5420 if (!agent_config.enabled)
5423 mono_loader_lock ();
5424 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5425 mono_loader_unlock ();
5428 ei.category = category ? mono_string_to_utf8 (category) : NULL;
5429 ei.message = message ? mono_string_to_utf8 (message) : NULL;
5431 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5433 g_free (ei.category);
5434 g_free (ei.message);
5438 mono_debugger_agent_debug_log_is_enabled (void)
5440 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5441 return agent_config.enabled;
5444 #if defined(PLATFORM_ANDROID) || defined(TARGET_ANDROID)
5446 mono_debugger_agent_unhandled_exception (MonoException *exc)
5455 memset (&ei, 0, sizeof (EventInfo));
5456 ei.exc = (MonoObject*)exc;
5458 mono_loader_lock ();
5459 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5460 mono_loader_unlock ();
5462 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5467 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5468 MonoContext *catch_ctx)
5470 int i, j, suspend_policy;
5472 MonoJitInfo *ji, *catch_ji;
5474 DebuggerTlsData *tls = NULL;
5476 if (thread_to_tls != NULL) {
5477 MonoInternalThread *thread = mono_thread_internal_current ();
5479 mono_loader_lock ();
5480 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5481 mono_loader_unlock ();
5483 if (tls && tls->abort_requested)
5485 if (tls && tls->disable_breakpoints)
5489 memset (&ei, 0, sizeof (EventInfo));
5491 /* Just-In-Time debugging */
5493 if (agent_config.onuncaught && !inited) {
5494 finish_agent_init (FALSE);
5497 * Send an unsolicited EXCEPTION event with a dummy request id.
5499 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5500 ei.exc = (MonoObject*)exc;
5501 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5504 } else if (agent_config.onthrow && !inited) {
5506 gboolean found = FALSE;
5508 for (l = agent_config.onthrow; l; l = l->next) {
5509 char *ex_type = l->data;
5510 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5512 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5519 finish_agent_init (FALSE);
5522 * Send an unsolicited EXCEPTION event with a dummy request id.
5524 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5525 ei.exc = (MonoObject*)exc;
5526 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5534 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5536 catch_ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5540 ei.exc = (MonoObject*)exc;
5541 ei.caught = catch_ctx != NULL;
5543 mono_loader_lock ();
5545 /* Treat exceptions which are caught in non-user code as unhandled */
5546 for (i = 0; i < event_requests->len; ++i) {
5547 EventRequest *req = g_ptr_array_index (event_requests, i);
5548 if (req->event_kind != EVENT_KIND_EXCEPTION)
5551 for (j = 0; j < req->nmodifiers; ++j) {
5552 Modifier *mod = &req->modifiers [j];
5554 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5556 gboolean found = FALSE;
5557 MonoAssembly **assemblies = mod->data.assemblies;
5560 for (k = 0; assemblies [k]; ++k)
5561 if (assemblies [k] == jinfo_get_method (catch_ji)->klass->image->assembly)
5570 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5571 mono_loader_unlock ();
5573 if (tls && ei.caught && catch_ctx) {
5574 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5575 tls->catch_state.ctx = *catch_ctx;
5576 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5577 tls->catch_state.valid = TRUE;
5580 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5583 tls->catch_state.valid = FALSE;
5587 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5589 DebuggerTlsData *tls;
5594 tls = mono_native_tls_get_value (debugger_tls_id);
5599 * We're about to invoke an exception filter during the first pass of exception handling.
5601 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5602 * 'orig_ctx' is the context where the exception has been thrown.
5605 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5607 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5608 * the call site (line 37) and then continue to Main(), but it would never
5609 * include the throw site (line 32).
5611 * Since exception filters are invoked during the first pass of exception handling,
5612 * the stack frames of the throw site are still intact, so we should include them
5615 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5617 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5618 * but report the location of the 'throw' to the user.
5622 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5626 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5628 DebuggerTlsData *tls;
5633 tls = mono_native_tls_get_value (debugger_tls_id);
5637 tls->filter_state.valid = FALSE;
5641 * buffer_add_value_full:
5643 * Add the encoding of the value at ADDR described by T to the buffer.
5644 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5648 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5649 gboolean as_vtype, GHashTable *parent_vtypes)
5652 gboolean boxed_vtype = FALSE;
5655 if (!(*(void**)addr)) {
5656 /* This can happen with compiler generated locals */
5657 //printf ("%s\n", mono_type_full_name (t));
5658 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5661 g_assert (*(void**)addr);
5662 addr = *(void**)addr;
5667 case MONO_TYPE_BOOLEAN:
5670 case MONO_TYPE_CHAR:
5690 case MONO_TYPE_VOID:
5691 buffer_add_byte (buf, t->type);
5693 case MONO_TYPE_BOOLEAN:
5696 buffer_add_byte (buf, t->type);
5697 buffer_add_int (buf, *(gint8*)addr);
5699 case MONO_TYPE_CHAR:
5702 buffer_add_byte (buf, t->type);
5703 buffer_add_int (buf, *(gint16*)addr);
5708 buffer_add_byte (buf, t->type);
5709 buffer_add_int (buf, *(gint32*)addr);
5714 buffer_add_byte (buf, t->type);
5715 buffer_add_long (buf, *(gint64*)addr);
5719 /* Treat it as a vtype */
5721 case MONO_TYPE_PTR: {
5722 gssize val = *(gssize*)addr;
5724 buffer_add_byte (buf, t->type);
5725 buffer_add_long (buf, val);
5729 case MONO_TYPE_STRING:
5730 case MONO_TYPE_SZARRAY:
5731 case MONO_TYPE_OBJECT:
5732 case MONO_TYPE_CLASS:
5733 case MONO_TYPE_ARRAY:
5734 obj = *(MonoObject**)addr;
5737 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5739 if (obj->vtable->klass->valuetype) {
5740 t = &obj->vtable->klass->byval_arg;
5741 addr = mono_object_unbox (obj);
5744 } else if (obj->vtable->klass->rank) {
5745 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5746 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5747 buffer_add_byte (buf, MONO_TYPE_CLASS);
5749 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5751 buffer_add_objid (buf, obj);
5755 case MONO_TYPE_VALUETYPE:
5756 case MONO_TYPE_TYPEDBYREF: {
5760 MonoClass *klass = mono_class_from_mono_type (t);
5765 * Handle boxed vtypes recursively referencing themselves using fields.
5768 parent_vtypes = g_hash_table_new (NULL, NULL);
5769 vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
5771 if (CHECK_PROTOCOL_VERSION (2, 33)) {
5772 buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
5773 buffer_add_int (buf, vtype_index - 1);
5775 /* The client can't handle PARENT_VTYPE */
5776 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5780 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
5784 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5785 buffer_add_byte (buf, klass->enumtype);
5786 buffer_add_typeid (buf, domain, klass);
5790 while ((f = mono_class_get_fields (klass, &iter))) {
5791 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5793 if (mono_field_is_deleted (f))
5797 buffer_add_int (buf, nfields);
5800 while ((f = mono_class_get_fields (klass, &iter))) {
5801 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5803 if (mono_field_is_deleted (f))
5805 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE, parent_vtypes);
5809 g_hash_table_remove (parent_vtypes, addr);
5810 if (g_hash_table_size (parent_vtypes) == 0) {
5811 g_hash_table_destroy (parent_vtypes);
5812 parent_vtypes = NULL;
5817 case MONO_TYPE_GENERICINST:
5818 if (mono_type_generic_inst_is_valuetype (t)) {
5830 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5832 buffer_add_value_full (buf, t, addr, domain, FALSE, NULL);
5836 obj_is_of_type (MonoObject *obj, MonoType *t)
5838 MonoClass *klass = obj->vtable->klass;
5839 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5840 if (mono_class_is_transparent_proxy (klass)) {
5841 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5842 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5852 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5855 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5861 gpointer iter = NULL;
5865 is_enum = decode_byte (buf, &buf, limit);
5866 /* Enums are sent as a normal vtype */
5868 return ERR_NOT_IMPLEMENTED;
5869 klass = decode_typeid (buf, &buf, limit, &d, &err);
5873 if (t && klass != mono_class_from_mono_type (t)) {
5874 char *name = mono_type_full_name (t);
5875 char *name2 = mono_type_full_name (&klass->byval_arg);
5876 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got %s.\n", (gpointer)GetCurrentThreadId (), name, name2);
5879 return ERR_INVALID_ARGUMENT;
5882 nfields = decode_int (buf, &buf, limit);
5883 while ((f = mono_class_get_fields (klass, &iter))) {
5884 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5886 if (mono_field_is_deleted (f))
5888 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5893 g_assert (nfields == 0);
5901 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5905 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5906 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5907 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5908 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5909 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE) &&
5910 !(t->type == MONO_TYPE_VALUETYPE && type == MONO_TYPE_OBJECT)) {
5911 char *name = mono_type_full_name (t);
5912 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type);
5914 return ERR_INVALID_ARGUMENT;
5918 case MONO_TYPE_BOOLEAN:
5919 *(guint8*)addr = decode_int (buf, &buf, limit);
5921 case MONO_TYPE_CHAR:
5922 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5925 *(gint8*)addr = decode_int (buf, &buf, limit);
5928 *(guint8*)addr = decode_int (buf, &buf, limit);
5931 *(gint16*)addr = decode_int (buf, &buf, limit);
5934 *(guint16*)addr = decode_int (buf, &buf, limit);
5937 *(gint32*)addr = decode_int (buf, &buf, limit);
5940 *(guint32*)addr = decode_int (buf, &buf, limit);
5943 *(gint64*)addr = decode_long (buf, &buf, limit);
5946 *(guint64*)addr = decode_long (buf, &buf, limit);
5949 *(guint32*)addr = decode_int (buf, &buf, limit);
5952 *(guint64*)addr = decode_long (buf, &buf, limit);
5955 /* We send these as I8, so we get them back as such */
5956 g_assert (type == MONO_TYPE_I8);
5957 *(gssize*)addr = decode_long (buf, &buf, limit);
5959 case MONO_TYPE_GENERICINST:
5960 if (MONO_TYPE_ISSTRUCT (t)) {
5961 /* The client sends these as a valuetype */
5969 /* We send these as vtypes, so we get them back as such */
5970 g_assert (type == MONO_TYPE_VALUETYPE);
5973 case MONO_TYPE_VALUETYPE:
5974 if (type == MONO_TYPE_OBJECT) {
5976 int objid = decode_objid (buf, &buf, limit);
5980 err = get_object (objid, (MonoObject**)&obj);
5984 return ERR_INVALID_ARGUMENT;
5985 if (obj->vtable->klass != mono_class_from_mono_type (t)) {
5986 DEBUG_PRINTF (1, "Expected type '%s', got object '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
5987 return ERR_INVALID_ARGUMENT;
5989 memcpy (addr, mono_object_unbox (obj), mono_class_value_size (obj->vtable->klass, NULL));
5991 err = decode_vtype (t, domain, addr, buf, &buf, limit);
5998 if (MONO_TYPE_IS_REFERENCE (t)) {
5999 if (type == MONO_TYPE_OBJECT) {
6000 int objid = decode_objid (buf, &buf, limit);
6004 err = get_object (objid, (MonoObject**)&obj);
6009 if (!obj_is_of_type (obj, t)) {
6010 DEBUG_PRINTF (1, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6011 return ERR_INVALID_ARGUMENT;
6014 if (obj && obj->vtable->domain != domain)
6015 return ERR_INVALID_ARGUMENT;
6017 mono_gc_wbarrier_generic_store (addr, obj);
6018 } else if (type == VALUE_TYPE_ID_NULL) {
6019 *(MonoObject**)addr = NULL;
6020 } else if (type == MONO_TYPE_VALUETYPE) {
6028 /* This can happen when round-tripping boxed vtypes */
6030 * Obtain vtype class.
6031 * Same as the beginning of the handle_vtype case above.
6034 is_enum = decode_byte (buf, &buf, limit);
6036 return ERR_NOT_IMPLEMENTED;
6037 klass = decode_typeid (buf, &buf, limit, &d, &err);
6041 /* Decode the vtype into a temporary buffer, then box it. */
6042 vtype_buf_size = mono_class_value_size (klass, NULL);
6043 vtype_buf = g_malloc0 (vtype_buf_size);
6044 g_assert (vtype_buf);
6047 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
6052 *(MonoObject**)addr = mono_value_box (d, klass, vtype_buf);
6055 char *name = mono_type_full_name (t);
6056 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type);
6058 return ERR_INVALID_ARGUMENT;
6072 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6075 int type = decode_byte (buf, &buf, limit);
6077 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
6078 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
6079 guint8 *nullable_buf;
6082 * First try decoding it as a Nullable`1
6084 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6089 * Then try decoding as a primitive value or null.
6091 if (targ->type == type) {
6092 nullable_buf = g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
6093 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
6095 g_free (nullable_buf);
6098 mono_nullable_init (addr, mono_value_box (domain, mono_class_from_mono_type (targ), nullable_buf), mono_class_from_mono_type (t));
6099 g_free (nullable_buf);
6102 } else if (type == VALUE_TYPE_ID_NULL) {
6103 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
6109 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6113 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
6117 guint8 *addr, *gaddr;
6120 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6121 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6124 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
6125 reg_val = mono_arch_context_get_int_reg (ctx, reg);
6127 buffer_add_value_full (buf, t, ®_val, domain, as_vtype, NULL);
6129 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6130 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6131 addr += (gint32)var->offset;
6133 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6135 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6137 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6140 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6141 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
6142 /* Same as regoffset, but with an indirection */
6143 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6144 addr += (gint32)var->offset;
6146 gaddr = *(gpointer*)addr;
6148 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL);
6150 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
6151 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
6152 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
6153 MonoGSharedVtMethodRuntimeInfo *info;
6159 g_assert (info_var);
6160 g_assert (locals_var);
6162 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6163 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6164 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6165 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6166 addr += (gint32)info_var->offset;
6167 info = *(gpointer*)addr;
6168 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6169 info = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6171 g_assert_not_reached ();
6175 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6176 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6177 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6178 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6179 addr += (gint32)locals_var->offset;
6180 locals = *(gpointer*)addr;
6181 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6182 locals = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6184 g_assert_not_reached ();
6188 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6190 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6195 g_assert_not_reached ();
6200 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
6204 guint8 *addr, *gaddr;
6206 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6207 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6209 if (MONO_TYPE_IS_REFERENCE (t))
6210 size = sizeof (gpointer);
6212 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6215 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6216 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6218 gboolean is_signed = FALSE;
6221 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6224 // FIXME: Write barriers
6225 mono_gc_memmove_atomic (addr, val, size);
6230 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6235 v = is_signed ? *(gint8*)val : *(guint8*)val;
6238 v = is_signed ? *(gint16*)val : *(guint16*)val;
6241 v = is_signed ? *(gint32*)val : *(guint32*)val;
6244 v = is_signed ? *(gint64*)val : *(guint64*)val;
6247 g_assert_not_reached ();
6250 /* Set value on the stack or in the return ctx */
6251 if (reg_locations [reg]) {
6252 /* Saved on the stack */
6253 DEBUG_PRINTF (1, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v);
6254 *(reg_locations [reg]) = v;
6257 DEBUG_PRINTF (1, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v);
6258 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6261 // FIXME: Move these to mono-context.h/c.
6262 mono_arch_context_set_int_reg (ctx, reg, v);
6264 // FIXME: Can't set registers, so we disable linears
6269 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6270 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6271 addr += (gint32)var->offset;
6273 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6276 addr = *(guint8**)addr;
6282 // FIXME: Write barriers
6283 mono_gc_memmove_atomic (addr, val, size);
6285 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6286 /* Same as regoffset, but with an indirection */
6287 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6288 addr += (gint32)var->offset;
6290 gaddr = *(gpointer*)addr;
6292 // FIXME: Write barriers
6293 mono_gc_memmove_atomic (gaddr, val, size);
6295 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6299 g_assert_not_reached ();
6304 clear_event_request (int req_id, int etype)
6308 mono_loader_lock ();
6309 for (i = 0; i < event_requests->len; ++i) {
6310 EventRequest *req = g_ptr_array_index (event_requests, i);
6312 if (req->id == req_id && req->event_kind == etype) {
6313 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6314 clear_breakpoint (req->info);
6315 if (req->event_kind == EVENT_KIND_STEP)
6316 ss_destroy (req->info);
6317 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6318 clear_breakpoint (req->info);
6319 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6320 clear_breakpoint (req->info);
6321 g_ptr_array_remove_index_fast (event_requests, i);
6326 mono_loader_unlock ();
6330 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
6334 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6335 m->kind = MOD_KIND_NONE;
6336 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6337 int count = 0, match_count = 0, pos;
6338 MonoAssembly **newassemblies;
6340 for (i = 0; m->data.assemblies [i]; ++i) {
6342 if (m->data.assemblies [i] == assembly)
6347 newassemblies = g_new0 (MonoAssembly*, count - match_count);
6350 for (i = 0; i < count; ++i)
6351 if (m->data.assemblies [i] != assembly)
6352 newassemblies [pos ++] = m->data.assemblies [i];
6353 g_assert (pos == count - match_count);
6354 g_free (m->data.assemblies);
6355 m->data.assemblies = newassemblies;
6361 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
6365 for (i = 0; i < req->nmodifiers; ++i) {
6366 Modifier *m = &req->modifiers [i];
6368 clear_assembly_from_modifier (req, m, assembly);
6373 * clear_event_requests_for_assembly:
6375 * Clear all events requests which reference ASSEMBLY.
6378 clear_event_requests_for_assembly (MonoAssembly *assembly)
6383 mono_loader_lock ();
6387 for (i = 0; i < event_requests->len; ++i) {
6388 EventRequest *req = g_ptr_array_index (event_requests, i);
6390 clear_assembly_from_modifiers (req, assembly);
6392 if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly (req->info, assembly)) {
6393 clear_event_request (req->id, req->event_kind);
6398 if (req->event_kind == EVENT_KIND_STEP)
6399 ss_clear_for_assembly (req->info, assembly);
6402 mono_loader_unlock ();
6406 * type_comes_from_assembly:
6408 * GHRFunc that returns TRUE if klass comes from assembly
6411 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6413 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6417 * clear_types_for_assembly:
6419 * Clears types from loaded_classes for a given assembly
6422 clear_types_for_assembly (MonoAssembly *assembly)
6424 MonoDomain *domain = mono_domain_get ();
6425 AgentDomainInfo *info = NULL;
6427 if (!domain || !domain_jit_info (domain))
6428 /* Can happen during shutdown */
6431 info = get_agent_domain_info (domain);
6433 mono_loader_lock ();
6434 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6435 mono_loader_unlock ();
6439 add_thread (gpointer key, gpointer value, gpointer user_data)
6441 MonoInternalThread *thread = value;
6442 Buffer *buf = user_data;
6444 buffer_add_objid (buf, (MonoObject*)thread);
6448 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6450 guint8 *end = invoke->endp;
6453 MonoMethodSignature *sig;
6456 MonoObject *this_arg, *res, *exc;
6459 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6462 MonoStopwatch watch;
6464 if (invoke->method) {
6466 * Invoke this method directly, currently only Environment.Exit () is supported.
6469 DEBUG_PRINTF (1, "[%p] Invoking method '%s' on receiver '%s'.\n", (gpointer)GetCurrentThreadId (), mono_method_full_name (invoke->method, TRUE), this_arg ? this_arg->vtable->klass->name : "<null>");
6470 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
6471 g_assert_not_reached ();
6474 m = decode_methodid (p, &p, end, &domain, &err);
6477 sig = mono_method_signature (m);
6479 if (m->klass->valuetype)
6480 this_buf = g_alloca (mono_class_instance_size (m->klass));
6482 this_buf = g_alloca (sizeof (MonoObject*));
6483 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6484 /* Should be null */
6485 int type = decode_byte (p, &p, end);
6486 if (type != VALUE_TYPE_ID_NULL) {
6487 DEBUG_PRINTF (1, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer)GetCurrentThreadId ());
6488 return ERR_INVALID_ARGUMENT;
6490 memset (this_buf, 0, mono_class_instance_size (m->klass));
6491 } else if (m->klass->valuetype && !strcmp (m->name, ".ctor")) {
6495 int type = decode_byte (p, &tmp_p, end);
6496 if (type == VALUE_TYPE_ID_NULL) {
6497 memset (this_buf, 0, mono_class_instance_size (m->klass));
6500 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6505 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6510 if (!m->klass->valuetype)
6511 this_arg = *(MonoObject**)this_buf;
6515 if (MONO_CLASS_IS_INTERFACE (m->klass)) {
6517 DEBUG_PRINTF (1, "[%p] Error: Interface method invoked without this argument.\n", (gpointer)GetCurrentThreadId ());
6518 return ERR_INVALID_ARGUMENT;
6520 m = mono_object_get_virtual_method (this_arg, m);
6521 /* Transform this to the format the rest of the code expects it to be */
6522 if (m->klass->valuetype) {
6523 this_buf = g_alloca (mono_class_instance_size (m->klass));
6524 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
6526 } else if ((m->flags & METHOD_ATTRIBUTE_VIRTUAL) && !m->klass->valuetype && invoke->flags & INVOKE_FLAG_VIRTUAL) {
6528 DEBUG_PRINTF (1, "[%p] Error: invoke with INVOKE_FLAG_VIRTUAL flag set without this argument.\n", (gpointer)GetCurrentThreadId ());
6529 return ERR_INVALID_ARGUMENT;
6531 m = mono_object_get_virtual_method (this_arg, m);
6532 if (m->klass->valuetype) {
6533 this_buf = g_alloca (mono_class_instance_size (m->klass));
6534 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
6538 DEBUG_PRINTF (1, "[%p] Invoking method '%s' on receiver '%s'.\n", (gpointer)GetCurrentThreadId (), mono_method_full_name (m, TRUE), this_arg ? this_arg->vtable->klass->name : "<null>");
6540 if (this_arg && this_arg->vtable->domain != domain)
6543 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this_arg) {
6544 if (!strcmp (m->name, ".ctor")) {
6545 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
6546 return ERR_INVALID_ARGUMENT;
6548 this_arg = mono_object_new (domain, m->klass);
6550 return ERR_INVALID_ARGUMENT;
6554 if (this_arg && !obj_is_of_type (this_arg, &m->klass->byval_arg))
6555 return ERR_INVALID_ARGUMENT;
6557 nargs = decode_int (p, &p, end);
6558 if (nargs != sig->param_count)
6559 return ERR_INVALID_ARGUMENT;
6560 /* Use alloca to get gc tracking */
6561 arg_buf = g_alloca (nargs * sizeof (gpointer));
6562 memset (arg_buf, 0, nargs * sizeof (gpointer));
6563 args = g_alloca (nargs * sizeof (gpointer));
6564 for (i = 0; i < nargs; ++i) {
6565 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6566 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6569 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6572 if (sig->params [i]->byref) {
6573 arg_buf [i] = g_alloca (sizeof (mgreg_t));
6574 *(gpointer*)arg_buf [i] = args [i];
6575 args [i] = arg_buf [i];
6578 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6579 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6582 args [i] = arg_buf [i];
6589 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6590 tls->disable_breakpoints = TRUE;
6592 tls->disable_breakpoints = FALSE;
6595 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6597 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6598 if (invoke->has_ctx) {
6601 lmf_addr = mono_get_lmf_addr ();
6604 memset (&ext, 0, sizeof (ext));
6605 mono_arch_init_lmf_ext (&ext, *lmf_addr);
6607 ext.debugger_invoke = TRUE;
6608 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6610 mono_set_lmf ((MonoLMF*)&ext);
6614 mono_stopwatch_start (&watch);
6615 if (m->klass->valuetype)
6616 res = mono_runtime_invoke (m, this_buf, args, &exc);
6618 res = mono_runtime_invoke (m, this_arg, args, &exc);
6619 mono_stopwatch_stop (&watch);
6620 DEBUG_PRINTF (1, "[%p] Invoke result: %p, exc: %s, time: %ld ms.\n", (gpointer)GetCurrentThreadId (), res, exc ? exc->vtable->klass->name : NULL, (long)mono_stopwatch_elapsed_ms (&watch));
6622 buffer_add_byte (buf, 0);
6623 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6625 gboolean out_this = FALSE;
6626 gboolean out_args = FALSE;
6628 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_THIS) && CHECK_PROTOCOL_VERSION (2, 35))
6630 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_ARGS) && CHECK_PROTOCOL_VERSION (2, 35))
6632 buffer_add_byte (buf, 1 + (out_this ? 2 : 0) + (out_args ? 4 : 0));
6633 if (sig->ret->type == MONO_TYPE_VOID) {
6634 if (!strcmp (m->name, ".ctor")) {
6635 if (!m->klass->valuetype)
6636 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this_arg, domain);
6638 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
6640 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6642 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6643 buffer_add_value (buf, sig->ret, &res, domain);
6644 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6645 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6646 MonoClass *k = mono_class_from_mono_type (sig->ret);
6647 guint8 *nullable_buf = g_alloca (mono_class_value_size (k, NULL));
6649 g_assert (nullable_buf);
6650 mono_nullable_init (nullable_buf, res, k);
6651 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6654 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6660 /* Return the new value of the receiver after the call */
6661 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
6663 buffer_add_int (buf, nargs);
6664 for (i = 0; i < nargs; ++i) {
6665 if (MONO_TYPE_IS_REFERENCE (sig->params [i]))
6666 buffer_add_value (buf, sig->params [i], &args [i], domain);
6667 else if (sig->params [i]->byref)
6668 /* add_value () does an indirection */
6669 buffer_add_value (buf, sig->params [i], &arg_buf [i], domain);
6671 buffer_add_value (buf, sig->params [i], arg_buf [i], domain);
6676 tls->disable_breakpoints = FALSE;
6678 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6679 if (invoke->has_ctx)
6680 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
6684 // FIXME: byref arguments
6692 * Invoke the method given by tls->pending_invoke in the current thread.
6695 invoke_method (void)
6697 DebuggerTlsData *tls;
6702 MonoContext restore_ctx;
6705 tls = mono_native_tls_get_value (debugger_tls_id);
6709 * Store the `InvokeData *' in `tls->invoke' until we're done with
6710 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6713 mono_loader_lock ();
6715 invoke = tls->pending_invoke;
6717 tls->pending_invoke = NULL;
6719 invoke->last_invoke = tls->invoke;
6720 tls->invoke = invoke;
6722 mono_loader_unlock ();
6724 tls->frames_up_to_date = FALSE;
6730 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6731 buffer_init (&buf, 128);
6734 /* Fail the other invokes as well */
6736 err = do_invoke_method (tls, &buf, invoke, p, &p);
6739 if (tls->abort_requested) {
6740 if (CHECK_PROTOCOL_VERSION (2, 42))
6741 err = ERR_INVOKE_ABORTED;
6744 /* Start suspending before sending the reply */
6745 if (mindex == invoke->nmethods - 1) {
6746 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6747 for (i = 0; i < invoke->suspend_count; ++i)
6752 send_reply_packet (id, err, &buf);
6757 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6759 if (invoke->has_ctx)
6760 save_thread_context (&restore_ctx);
6762 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6763 g_assert (tls->resume_count);
6764 tls->resume_count -= invoke->suspend_count;
6767 DEBUG_PRINTF (1, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer)GetCurrentThreadId (), err, tls->resume_count);
6770 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6772 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
6773 * after the mono_runtime_invoke() already returned, but it doesn't matter
6774 * because we reset the abort here.
6777 mono_loader_lock ();
6779 if (tls->abort_requested)
6780 mono_thread_internal_reset_abort (tls->thread);
6782 tls->invoke = tls->invoke->last_invoke;
6783 tls->abort_requested = FALSE;
6785 mono_loader_unlock ();
6794 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6796 MonoThread *thread = value;
6797 DebuggerTlsData *tls;
6800 mono_loader_lock ();
6801 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6803 res = tls->really_suspended;
6804 mono_loader_unlock ();
6810 get_source_files_for_type (MonoClass *klass)
6812 gpointer iter = NULL;
6814 MonoDebugSourceInfo *sinfo;
6818 files = g_ptr_array_new ();
6820 while ((method = mono_class_get_methods (klass, &iter))) {
6821 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6822 GPtrArray *source_file_list;
6825 mono_debug_get_seq_points (minfo, NULL, &source_file_list, NULL, NULL, NULL);
6826 for (j = 0; j < source_file_list->len; ++j) {
6827 sinfo = g_ptr_array_index (source_file_list, j);
6828 for (i = 0; i < files->len; ++i)
6829 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6831 if (i == files->len)
6832 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6834 g_ptr_array_free (source_file_list, TRUE);
6842 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6845 case CMD_VM_VERSION: {
6846 char *build_info, *version;
6848 build_info = mono_get_runtime_build_info ();
6849 version = g_strdup_printf ("mono %s", build_info);
6851 buffer_add_string (buf, version); /* vm version */
6852 buffer_add_int (buf, MAJOR_VERSION);
6853 buffer_add_int (buf, MINOR_VERSION);
6854 g_free (build_info);
6858 case CMD_VM_SET_PROTOCOL_VERSION: {
6859 major_version = decode_int (p, &p, end);
6860 minor_version = decode_int (p, &p, end);
6861 protocol_version_set = TRUE;
6862 DEBUG_PRINTF (1, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version);
6865 case CMD_VM_ALL_THREADS: {
6867 mono_loader_lock ();
6868 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6869 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6870 mono_loader_unlock ();
6873 case CMD_VM_SUSPEND:
6875 wait_for_suspend ();
6878 if (suspend_count == 0)
6879 return ERR_NOT_SUSPENDED;
6881 clear_suspended_objs ();
6883 case CMD_VM_DISPOSE:
6884 /* Clear all event requests */
6885 mono_loader_lock ();
6886 while (event_requests->len > 0) {
6887 EventRequest *req = g_ptr_array_index (event_requests, 0);
6889 clear_event_request (req->id, req->event_kind);
6891 mono_loader_unlock ();
6893 while (suspend_count > 0)
6895 disconnected = TRUE;
6896 vm_start_event_sent = FALSE;
6899 MonoInternalThread *thread;
6900 DebuggerTlsData *tls;
6901 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6902 MonoClass *env_class;
6904 MonoMethod *exit_method = NULL;
6908 exit_code = decode_int (p, &p, end);
6910 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6912 /* Have to send a reply before exiting */
6913 send_reply_packet (id, 0, buf);
6915 /* Clear all event requests */
6916 mono_loader_lock ();
6917 while (event_requests->len > 0) {
6918 EventRequest *req = g_ptr_array_index (event_requests, 0);
6920 clear_event_request (req->id, req->event_kind);
6922 mono_loader_unlock ();
6925 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6926 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6927 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6928 * better than doing the shutdown ourselves, since it avoids various races.
6932 wait_for_suspend ();
6934 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6935 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
6937 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6940 mono_loader_lock ();
6941 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6942 mono_loader_unlock ();
6944 if (thread && exit_method) {
6945 mono_loader_lock ();
6946 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6947 mono_loader_unlock ();
6949 args = g_new0 (gpointer, 1);
6950 args [0] = g_malloc (sizeof (int));
6951 *(int*)(args [0]) = exit_code;
6953 tls->pending_invoke = g_new0 (InvokeData, 1);
6954 tls->pending_invoke->method = exit_method;
6955 tls->pending_invoke->args = args;
6956 tls->pending_invoke->nmethods = 1;
6958 while (suspend_count > 0)
6962 * No thread found, do it ourselves.
6963 * FIXME: This can race with normal shutdown etc.
6965 while (suspend_count > 0)
6968 if (!mono_runtime_try_shutdown ())
6971 mono_environment_exitcode_set (exit_code);
6973 /* Suspend all managed threads since the runtime is going away */
6974 DEBUG_PRINTF (1, "Suspending all threads...\n");
6975 mono_thread_suspend_all_other_threads ();
6976 DEBUG_PRINTF (1, "Shutting down the runtime...\n");
6977 mono_runtime_quit ();
6978 transport_close2 ();
6979 DEBUG_PRINTF (1, "Exiting...\n");
6985 case CMD_VM_INVOKE_METHOD:
6986 case CMD_VM_INVOKE_METHODS: {
6987 int objid = decode_objid (p, &p, end);
6989 DebuggerTlsData *tls;
6990 int i, count, err, flags, nmethods;
6992 err = get_object (objid, (MonoObject**)&thread);
6996 flags = decode_int (p, &p, end);
6998 if (command == CMD_VM_INVOKE_METHODS)
6999 nmethods = decode_int (p, &p, end);
7003 // Wait for suspending if it already started
7005 wait_for_suspend ();
7006 if (!is_suspended ())
7007 return ERR_NOT_SUSPENDED;
7009 mono_loader_lock ();
7010 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7011 mono_loader_unlock ();
7014 if (!tls->really_suspended)
7015 /* The thread is still running native code, can't do invokes */
7016 return ERR_NOT_SUSPENDED;
7019 * Store the invoke data into tls, the thread will execute it after it is
7022 if (tls->pending_invoke)
7023 return ERR_NOT_SUSPENDED;
7024 tls->pending_invoke = g_new0 (InvokeData, 1);
7025 tls->pending_invoke->id = id;
7026 tls->pending_invoke->flags = flags;
7027 tls->pending_invoke->p = g_malloc (end - p);
7028 memcpy (tls->pending_invoke->p, p, end - p);
7029 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
7030 tls->pending_invoke->suspend_count = suspend_count;
7031 tls->pending_invoke->nmethods = nmethods;
7033 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
7034 resume_thread (THREAD_TO_INTERNAL (thread));
7037 count = suspend_count;
7038 for (i = 0; i < count; ++i)
7043 case CMD_VM_ABORT_INVOKE: {
7044 int objid = decode_objid (p, &p, end);
7046 DebuggerTlsData *tls;
7049 err = get_object (objid, (MonoObject**)&thread);
7053 invoke_id = decode_int (p, &p, end);
7055 mono_loader_lock ();
7056 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7059 if (tls->abort_requested) {
7060 DEBUG_PRINTF (1, "Abort already requested.\n");
7061 mono_loader_unlock ();
7066 * Check whether we're still inside the mono_runtime_invoke() and that it's
7067 * actually the correct invocation.
7069 * Careful, we do not stop the thread that's doing the invocation, so we can't
7070 * inspect its stack. However, invoke_method() also acquires the loader lock
7071 * when it's done, so we're safe here.
7075 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
7076 mono_loader_unlock ();
7077 return ERR_NO_INVOCATION;
7080 tls->abort_requested = TRUE;
7082 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
7083 mono_loader_unlock ();
7087 case CMD_VM_SET_KEEPALIVE: {
7088 int timeout = decode_int (p, &p, end);
7089 agent_config.keepalive = timeout;
7091 #ifndef DISABLE_SOCKET_TRANSPORT
7098 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
7099 GHashTableIter iter, kiter;
7104 char *fname, *basename;
7105 gboolean ignore_case;
7106 GSList *class_list, *l;
7107 GPtrArray *res_classes, *res_domains;
7109 fname = decode_string (p, &p, end);
7110 ignore_case = decode_byte (p, &p, end);
7112 basename = dbg_path_get_basename (fname);
7114 res_classes = g_ptr_array_new ();
7115 res_domains = g_ptr_array_new ();
7117 mono_loader_lock ();
7118 g_hash_table_iter_init (&iter, domains);
7119 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7120 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
7122 /* Update 'source_file_to_class' cache */
7123 g_hash_table_iter_init (&kiter, info->loaded_classes);
7124 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
7125 if (!g_hash_table_lookup (info->source_files, klass)) {
7126 files = get_source_files_for_type (klass);
7127 g_hash_table_insert (info->source_files, klass, files);
7129 for (i = 0; i < files->len; ++i) {
7130 char *s = g_ptr_array_index (files, i);
7131 char *s2 = dbg_path_get_basename (s);
7134 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
7136 class_list = g_slist_prepend (class_list, klass);
7137 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
7139 class_list = g_slist_prepend (class_list, klass);
7140 g_hash_table_insert (info->source_file_to_class, s2, class_list);
7143 /* The _ignorecase hash contains the lowercase path */
7144 s3 = strdup_tolower (s2);
7145 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
7147 class_list = g_slist_prepend (class_list, klass);
7148 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
7150 class_list = g_slist_prepend (class_list, klass);
7151 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
7163 s = strdup_tolower (basename);
7164 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
7167 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
7170 for (l = class_list; l; l = l->next) {
7173 g_ptr_array_add (res_classes, klass);
7174 g_ptr_array_add (res_domains, domain);
7177 mono_loader_unlock ();
7182 buffer_add_int (buf, res_classes->len);
7183 for (i = 0; i < res_classes->len; ++i)
7184 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
7185 g_ptr_array_free (res_classes, TRUE);
7186 g_ptr_array_free (res_domains, TRUE);
7189 case CMD_VM_GET_TYPES: {
7190 GHashTableIter iter;
7194 gboolean ignore_case;
7195 GPtrArray *res_classes, *res_domains;
7196 MonoTypeNameParse info;
7198 name = decode_string (p, &p, end);
7199 ignore_case = decode_byte (p, &p, end);
7201 if (!mono_reflection_parse_type (name, &info)) {
7203 mono_reflection_free_type_info (&info);
7204 return ERR_INVALID_ARGUMENT;
7207 res_classes = g_ptr_array_new ();
7208 res_domains = g_ptr_array_new ();
7210 mono_loader_lock ();
7211 g_hash_table_iter_init (&iter, domains);
7212 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7214 gboolean type_resolve;
7218 mono_domain_assemblies_lock (domain);
7219 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7223 type_resolve = TRUE;
7224 t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
7226 g_ptr_array_add (res_classes, mono_type_get_class (t));
7227 g_ptr_array_add (res_domains, domain);
7231 mono_domain_assemblies_unlock (domain);
7233 mono_loader_unlock ();
7236 mono_reflection_free_type_info (&info);
7238 buffer_add_int (buf, res_classes->len);
7239 for (i = 0; i < res_classes->len; ++i)
7240 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
7241 g_ptr_array_free (res_classes, TRUE);
7242 g_ptr_array_free (res_domains, TRUE);
7245 case CMD_VM_START_BUFFERING:
7246 case CMD_VM_STOP_BUFFERING:
7247 /* Handled in the main loop */
7250 return ERR_NOT_IMPLEMENTED;
7257 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7263 case CMD_EVENT_REQUEST_SET: {
7265 int i, event_kind, suspend_policy, nmodifiers, mod;
7268 MonoThread *step_thread;
7269 int size = 0, depth = 0, filter = 0, step_thread_id = 0;
7273 event_kind = decode_byte (p, &p, end);
7274 suspend_policy = decode_byte (p, &p, end);
7275 nmodifiers = decode_byte (p, &p, end);
7277 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7278 req->id = InterlockedIncrement (&event_request_id);
7279 req->event_kind = event_kind;
7280 req->suspend_policy = suspend_policy;
7281 req->nmodifiers = nmodifiers;
7284 for (i = 0; i < nmodifiers; ++i) {
7285 mod = decode_byte (p, &p, end);
7287 req->modifiers [i].kind = mod;
7288 if (mod == MOD_KIND_COUNT) {
7289 req->modifiers [i].data.count = decode_int (p, &p, end);
7290 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7291 method = decode_methodid (p, &p, end, &domain, &err);
7294 location = decode_long (p, &p, end);
7295 } else if (mod == MOD_KIND_STEP) {
7296 step_thread_id = decode_id (p, &p, end);
7297 size = decode_int (p, &p, end);
7298 depth = decode_int (p, &p, end);
7299 if (CHECK_PROTOCOL_VERSION (2, 16))
7300 filter = decode_int (p, &p, end);
7301 req->modifiers [i].data.filter = filter;
7302 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7303 /* Treat STEP_THOUGH the same as HIDDEN */
7304 req->modifiers [i].data.filter |= STEP_FILTER_DEBUGGER_STEP_THROUGH;
7305 } else if (mod == MOD_KIND_THREAD_ONLY) {
7306 int id = decode_id (p, &p, end);
7308 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7313 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7314 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7318 req->modifiers [i].caught = decode_byte (p, &p, end);
7319 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7320 if (CHECK_PROTOCOL_VERSION (2, 25))
7321 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7323 req->modifiers [i].subclasses = TRUE;
7324 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" : "");
7326 req->modifiers [i].data.exc_class = exc_class;
7328 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
7330 return ERR_INVALID_ARGUMENT;
7333 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7334 int n = decode_int (p, &p, end);
7337 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
7338 for (j = 0; j < n; ++j) {
7339 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7341 g_free (req->modifiers [i].data.assemblies);
7345 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7346 int n = decode_int (p, &p, end);
7349 modifier = &req->modifiers [i];
7350 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7351 for (j = 0; j < n; ++j) {
7352 char *s = decode_string (p, &p, end);
7356 s2 = strdup_tolower (s);
7357 g_hash_table_insert (modifier->data.source_files, s2, s2);
7361 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7362 int n = decode_int (p, &p, end);
7365 modifier = &req->modifiers [i];
7366 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7367 for (j = 0; j < n; ++j) {
7368 char *s = decode_string (p, &p, end);
7371 g_hash_table_insert (modifier->data.type_names, s, s);
7375 return ERR_NOT_IMPLEMENTED;
7379 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7382 req->info = set_breakpoint (method, location, req, &error);
7383 if (!mono_error_ok (&error)) {
7385 DEBUG_PRINTF (1, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error));
7386 mono_error_cleanup (&error);
7387 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7389 } else if (req->event_kind == EVENT_KIND_STEP) {
7390 g_assert (step_thread_id);
7392 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7398 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, filter, req);
7403 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7404 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7405 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7406 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7407 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7408 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7410 if (req->nmodifiers) {
7412 return ERR_NOT_IMPLEMENTED;
7416 mono_loader_lock ();
7417 g_ptr_array_add (event_requests, req);
7419 if (agent_config.defer) {
7420 /* Transmit cached data to the client on receipt of the event request */
7421 switch (req->event_kind) {
7422 case EVENT_KIND_APPDOMAIN_CREATE:
7423 /* Emit load events for currently loaded domains */
7424 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7426 case EVENT_KIND_ASSEMBLY_LOAD:
7427 /* Emit load events for currently loaded assemblies */
7428 mono_assembly_foreach (emit_assembly_load, NULL);
7430 case EVENT_KIND_THREAD_START:
7431 /* Emit start events for currently started threads */
7432 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7434 case EVENT_KIND_TYPE_LOAD:
7435 /* Emit type load events for currently loaded types */
7436 mono_domain_foreach (send_types_for_domain, NULL);
7442 mono_loader_unlock ();
7444 buffer_add_int (buf, req->id);
7447 case CMD_EVENT_REQUEST_CLEAR: {
7448 int etype = decode_byte (p, &p, end);
7449 int req_id = decode_int (p, &p, end);
7451 // FIXME: Make a faster mapping from req_id to request
7452 mono_loader_lock ();
7453 clear_event_request (req_id, etype);
7454 mono_loader_unlock ();
7457 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7460 mono_loader_lock ();
7462 while (i < event_requests->len) {
7463 EventRequest *req = g_ptr_array_index (event_requests, i);
7465 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7466 clear_breakpoint (req->info);
7468 g_ptr_array_remove_index_fast (event_requests, i);
7474 mono_loader_unlock ();
7478 return ERR_NOT_IMPLEMENTED;
7485 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7491 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7492 buffer_add_domainid (buf, mono_get_root_domain ());
7495 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7496 domain = decode_domainid (p, &p, end, NULL, &err);
7499 buffer_add_string (buf, domain->friendly_name);
7502 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7507 domain = decode_domainid (p, &p, end, NULL, &err);
7510 mono_loader_lock ();
7512 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7515 buffer_add_int (buf, count);
7516 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7518 buffer_add_assemblyid (buf, domain, ass);
7520 mono_loader_unlock ();
7523 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7524 domain = decode_domainid (p, &p, end, NULL, &err);
7528 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7531 case CMD_APPDOMAIN_GET_CORLIB: {
7532 domain = decode_domainid (p, &p, end, NULL, &err);
7536 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7539 case CMD_APPDOMAIN_CREATE_STRING: {
7543 domain = decode_domainid (p, &p, end, NULL, &err);
7546 s = decode_string (p, &p, end);
7548 o = mono_string_new (domain, s);
7549 buffer_add_objid (buf, (MonoObject*)o);
7552 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7554 MonoDomain *domain2;
7557 domain = decode_domainid (p, &p, end, NULL, &err);
7560 klass = decode_typeid (p, &p, end, &domain2, &err);
7565 g_assert (domain == domain2);
7567 o = mono_object_new (domain, klass);
7569 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
7573 buffer_add_objid (buf, o);
7577 return ERR_NOT_IMPLEMENTED;
7584 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7590 ass = decode_assemblyid (p, &p, end, &domain, &err);
7595 case CMD_ASSEMBLY_GET_LOCATION: {
7596 buffer_add_string (buf, mono_image_get_filename (ass->image));
7599 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7603 if (ass->image->dynamic) {
7604 buffer_add_id (buf, 0);
7606 token = mono_image_get_entry_point (ass->image);
7608 buffer_add_id (buf, 0);
7610 m = mono_get_method (ass->image, token, NULL);
7611 buffer_add_methodid (buf, domain, m);
7616 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7617 buffer_add_moduleid (buf, domain, ass->image);
7620 case CMD_ASSEMBLY_GET_OBJECT: {
7621 MonoObject *o = (MonoObject*)mono_assembly_get_object (domain, ass);
7622 buffer_add_objid (buf, o);
7625 case CMD_ASSEMBLY_GET_TYPE: {
7626 char *s = decode_string (p, &p, end);
7627 gboolean ignorecase = decode_byte (p, &p, end);
7628 MonoTypeNameParse info;
7630 gboolean type_resolve, res;
7631 MonoDomain *d = mono_domain_get ();
7633 /* This is needed to be able to find referenced assemblies */
7634 res = mono_domain_set (domain, FALSE);
7637 if (!mono_reflection_parse_type (s, &info)) {
7640 if (info.assembly.name)
7642 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
7644 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
7645 mono_reflection_free_type_info (&info);
7648 mono_domain_set (d, TRUE);
7652 case CMD_ASSEMBLY_GET_NAME: {
7654 MonoAssembly *mass = ass;
7656 name = g_strdup_printf (
7657 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7659 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7660 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7661 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7662 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7664 buffer_add_string (buf, name);
7669 return ERR_NOT_IMPLEMENTED;
7676 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7682 case CMD_MODULE_GET_INFO: {
7683 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7686 basename = g_path_get_basename (image->name);
7687 buffer_add_string (buf, basename); // name
7688 buffer_add_string (buf, image->module_name); // scopename
7689 buffer_add_string (buf, image->name); // fqname
7690 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7691 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7696 return ERR_NOT_IMPLEMENTED;
7703 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7709 case CMD_FIELD_GET_INFO: {
7710 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
7712 buffer_add_string (buf, f->name);
7713 buffer_add_typeid (buf, domain, f->parent);
7714 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7715 buffer_add_int (buf, f->type->attrs);
7719 return ERR_NOT_IMPLEMENTED;
7726 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7728 if (val && val->vtable->klass == mono_defaults.monotype_class) {
7729 /* Special case these so the client doesn't have to handle Type objects */
7731 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7732 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7733 } else if (MONO_TYPE_IS_REFERENCE (t))
7734 buffer_add_value (buf, t, &val, domain);
7736 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7740 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7746 buffer_add_int (buf, 0);
7750 for (i = 0; i < cinfo->num_attrs; ++i) {
7751 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7754 buffer_add_int (buf, nattrs);
7756 for (i = 0; i < cinfo->num_attrs; ++i) {
7757 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7758 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7759 MonoArray *typed_args, *named_args;
7761 CattrNamedArg *arginfo = NULL;
7764 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
7765 if (!mono_error_ok (&error)) {
7766 DEBUG_PRINTF (2, "[dbg] mono_reflection_create_custom_attr_data_args () failed with: '%s'\n", mono_error_get_message (&error));
7767 mono_error_cleanup (&error);
7768 return ERR_LOADER_ERROR;
7771 buffer_add_methodid (buf, domain, attr->ctor);
7775 buffer_add_int (buf, mono_array_length (typed_args));
7776 for (j = 0; j < mono_array_length (typed_args); ++j) {
7777 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7779 t = mono_method_signature (attr->ctor)->params [j];
7781 buffer_add_cattr_arg (buf, t, domain, val);
7784 buffer_add_int (buf, 0);
7789 buffer_add_int (buf, mono_array_length (named_args));
7791 for (j = 0; j < mono_array_length (named_args); ++j) {
7792 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7794 if (arginfo [j].prop) {
7795 buffer_add_byte (buf, 0x54);
7796 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7797 } else if (arginfo [j].field) {
7798 buffer_add_byte (buf, 0x53);
7799 buffer_add_fieldid (buf, domain, arginfo [j].field);
7801 g_assert_not_reached ();
7804 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7807 buffer_add_int (buf, 0);
7816 /* FIXME: Code duplication with icall.c */
7818 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7823 mono_class_setup_interfaces (klass, error);
7824 if (!mono_error_ok (error))
7827 for (i = 0; i < klass->interface_count; i++) {
7828 ic = klass->interfaces [i];
7829 g_hash_table_insert (ifaces, ic, ic);
7831 collect_interfaces (ic, ifaces, error);
7832 if (!mono_error_ok (error))
7838 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7848 case CMD_TYPE_GET_INFO: {
7849 buffer_add_string (buf, klass->name_space);
7850 buffer_add_string (buf, klass->name);
7852 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7853 buffer_add_string (buf, name);
7855 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7856 buffer_add_moduleid (buf, domain, klass->image);
7857 buffer_add_typeid (buf, domain, klass->parent);
7858 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7859 buffer_add_typeid (buf, domain, klass->element_class);
7861 buffer_add_id (buf, 0);
7862 buffer_add_int (buf, klass->type_token);
7863 buffer_add_byte (buf, klass->rank);
7864 buffer_add_int (buf, klass->flags);
7866 type = &klass->byval_arg;
7867 // FIXME: Can't decide whenever a class represents a byref type
7870 if (type->type == MONO_TYPE_PTR)
7872 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7874 if (type->type == MONO_TYPE_VALUETYPE)
7876 if (klass->enumtype)
7878 if (klass->generic_container)
7880 if (klass->generic_container || klass->generic_class)
7882 buffer_add_byte (buf, b);
7885 while ((nested = mono_class_get_nested_types (klass, &iter)))
7887 buffer_add_int (buf, nnested);
7889 while ((nested = mono_class_get_nested_types (klass, &iter)))
7890 buffer_add_typeid (buf, domain, nested);
7891 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7892 if (klass->generic_container)
7893 buffer_add_typeid (buf, domain, klass);
7894 else if (klass->generic_class)
7895 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7897 buffer_add_id (buf, 0);
7899 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7902 if (klass->generic_class) {
7903 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7905 count = inst->type_argc;
7906 buffer_add_int (buf, count);
7907 for (i = 0; i < count; i++)
7908 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7909 } else if (klass->generic_container) {
7910 MonoGenericContainer *container = klass->generic_container;
7913 count = container->type_argc;
7914 buffer_add_int (buf, count);
7915 for (i = 0; i < count; i++) {
7916 pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
7917 buffer_add_typeid (buf, domain, pklass);
7920 buffer_add_int (buf, 0);
7925 case CMD_TYPE_GET_METHODS: {
7928 gpointer iter = NULL;
7931 mono_class_setup_methods (klass);
7933 nmethods = mono_class_num_methods (klass);
7935 buffer_add_int (buf, nmethods);
7937 while ((m = mono_class_get_methods (klass, &iter))) {
7938 buffer_add_methodid (buf, domain, m);
7941 g_assert (i == nmethods);
7944 case CMD_TYPE_GET_FIELDS: {
7947 gpointer iter = NULL;
7950 nfields = mono_class_num_fields (klass);
7952 buffer_add_int (buf, nfields);
7954 while ((f = mono_class_get_fields (klass, &iter))) {
7955 buffer_add_fieldid (buf, domain, f);
7956 buffer_add_string (buf, f->name);
7957 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7958 buffer_add_int (buf, f->type->attrs);
7961 g_assert (i == nfields);
7964 case CMD_TYPE_GET_PROPERTIES: {
7967 gpointer iter = NULL;
7970 nprops = mono_class_num_properties (klass);
7972 buffer_add_int (buf, nprops);
7974 while ((p = mono_class_get_properties (klass, &iter))) {
7975 buffer_add_propertyid (buf, domain, p);
7976 buffer_add_string (buf, p->name);
7977 buffer_add_methodid (buf, domain, p->get);
7978 buffer_add_methodid (buf, domain, p->set);
7979 buffer_add_int (buf, p->attrs);
7982 g_assert (i == nprops);
7985 case CMD_TYPE_GET_CATTRS: {
7986 MonoClass *attr_klass;
7987 MonoCustomAttrInfo *cinfo;
7989 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7990 /* attr_klass can be NULL */
7994 cinfo = mono_custom_attrs_from_class (klass);
7996 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8001 case CMD_TYPE_GET_FIELD_CATTRS: {
8002 MonoClass *attr_klass;
8003 MonoCustomAttrInfo *cinfo;
8004 MonoClassField *field;
8006 field = decode_fieldid (p, &p, end, NULL, &err);
8009 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8013 cinfo = mono_custom_attrs_from_field (klass, field);
8015 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8020 case CMD_TYPE_GET_PROPERTY_CATTRS: {
8021 MonoClass *attr_klass;
8022 MonoCustomAttrInfo *cinfo;
8025 prop = decode_propertyid (p, &p, end, NULL, &err);
8028 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8032 cinfo = mono_custom_attrs_from_property (klass, prop);
8034 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8039 case CMD_TYPE_GET_VALUES:
8040 case CMD_TYPE_GET_VALUES_2: {
8047 MonoThread *thread_obj;
8048 MonoInternalThread *thread = NULL;
8049 guint32 special_static_type;
8051 if (command == CMD_TYPE_GET_VALUES_2) {
8052 int objid = decode_objid (p, &p, end);
8055 err = get_object (objid, (MonoObject**)&thread_obj);
8059 thread = THREAD_TO_INTERNAL (thread_obj);
8062 len = decode_int (p, &p, end);
8063 for (i = 0; i < len; ++i) {
8064 f = decode_fieldid (p, &p, end, NULL, &err);
8068 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8069 return ERR_INVALID_FIELDID;
8070 special_static_type = mono_class_field_get_special_static_type (f);
8071 if (special_static_type != SPECIAL_STATIC_NONE) {
8072 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
8073 return ERR_INVALID_FIELDID;
8076 /* Check that the field belongs to the object */
8078 for (k = klass; k; k = k->parent) {
8079 if (k == f->parent) {
8085 return ERR_INVALID_FIELDID;
8087 vtable = mono_class_vtable (domain, f->parent);
8088 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8089 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
8090 buffer_add_value (buf, f->type, val, domain);
8095 case CMD_TYPE_SET_VALUES: {
8103 len = decode_int (p, &p, end);
8104 for (i = 0; i < len; ++i) {
8105 f = decode_fieldid (p, &p, end, NULL, &err);
8109 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8110 return ERR_INVALID_FIELDID;
8111 if (mono_class_field_is_special_static (f))
8112 return ERR_INVALID_FIELDID;
8114 /* Check that the field belongs to the object */
8116 for (k = klass; k; k = k->parent) {
8117 if (k == f->parent) {
8123 return ERR_INVALID_FIELDID;
8125 // FIXME: Check for literal/const
8127 vtable = mono_class_vtable (domain, f->parent);
8128 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8129 err = decode_value (f->type, domain, val, p, &p, end);
8134 if (MONO_TYPE_IS_REFERENCE (f->type))
8135 mono_field_static_set_value (vtable, f, *(gpointer*)val);
8137 mono_field_static_set_value (vtable, f, val);
8142 case CMD_TYPE_GET_OBJECT: {
8143 MonoObject *o = (MonoObject*)mono_type_get_object (domain, &klass->byval_arg);
8144 buffer_add_objid (buf, o);
8147 case CMD_TYPE_GET_SOURCE_FILES:
8148 case CMD_TYPE_GET_SOURCE_FILES_2: {
8149 char *source_file, *base;
8153 files = get_source_files_for_type (klass);
8155 buffer_add_int (buf, files->len);
8156 for (i = 0; i < files->len; ++i) {
8157 source_file = g_ptr_array_index (files, i);
8158 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8159 buffer_add_string (buf, source_file);
8161 base = dbg_path_get_basename (source_file);
8162 buffer_add_string (buf, base);
8165 g_free (source_file);
8167 g_ptr_array_free (files, TRUE);
8170 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8171 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8175 if (mono_class_is_assignable_from (klass, oklass))
8176 buffer_add_byte (buf, 1);
8178 buffer_add_byte (buf, 0);
8181 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8182 char *name = decode_string (p, &p, end);
8183 int i, flags = decode_int (p, &p, end);
8184 MonoException *ex = NULL;
8185 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
8188 return ERR_LOADER_ERROR;
8189 buffer_add_int (buf, array->len);
8190 for (i = 0; i < array->len; ++i) {
8191 MonoMethod *method = g_ptr_array_index (array, i);
8192 buffer_add_methodid (buf, domain, method);
8195 g_ptr_array_free (array, TRUE);
8199 case CMD_TYPE_GET_INTERFACES: {
8201 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8203 MonoClass *tclass, *iface;
8204 GHashTableIter iter;
8208 for (parent = tclass; parent; parent = parent->parent) {
8209 mono_class_setup_interfaces (parent, &error);
8210 if (!mono_error_ok (&error))
8211 return ERR_LOADER_ERROR;
8212 collect_interfaces (parent, iface_hash, &error);
8213 if (!mono_error_ok (&error))
8214 return ERR_LOADER_ERROR;
8217 buffer_add_int (buf, g_hash_table_size (iface_hash));
8219 g_hash_table_iter_init (&iter, iface_hash);
8220 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8221 buffer_add_typeid (buf, domain, iface);
8222 g_hash_table_destroy (iface_hash);
8225 case CMD_TYPE_GET_INTERFACE_MAP: {
8226 int tindex, ioffset;
8227 gboolean variance_used;
8229 int len, nmethods, i;
8233 len = decode_int (p, &p, end);
8234 mono_class_setup_vtable (klass);
8236 for (tindex = 0; tindex < len; ++tindex) {
8237 iclass = decode_typeid (p, &p, end, NULL, &err);
8241 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8243 return ERR_INVALID_ARGUMENT;
8245 nmethods = mono_class_num_methods (iclass);
8246 buffer_add_int (buf, nmethods);
8249 while ((method = mono_class_get_methods (iclass, &iter))) {
8250 buffer_add_methodid (buf, domain, method);
8252 for (i = 0; i < nmethods; ++i)
8253 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
8257 case CMD_TYPE_IS_INITIALIZED: {
8258 MonoVTable *vtable = mono_class_vtable (domain, klass);
8261 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8263 buffer_add_int (buf, 0);
8266 case CMD_TYPE_CREATE_INSTANCE: {
8269 obj = mono_object_new (domain, klass);
8270 buffer_add_objid (buf, obj);
8274 return ERR_NOT_IMPLEMENTED;
8281 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8284 MonoDomain *old_domain;
8288 klass = decode_typeid (p, &p, end, &domain, &err);
8292 old_domain = mono_domain_get ();
8294 mono_domain_set (domain, TRUE);
8296 err = type_commands_internal (command, klass, domain, p, end, buf);
8298 mono_domain_set (old_domain, TRUE);
8304 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8306 MonoMethodHeader *header;
8310 case CMD_METHOD_GET_NAME: {
8311 buffer_add_string (buf, method->name);
8314 case CMD_METHOD_GET_DECLARING_TYPE: {
8315 buffer_add_typeid (buf, domain, method->klass);
8318 case CMD_METHOD_GET_DEBUG_INFO: {
8319 MonoDebugMethodInfo *minfo;
8321 int i, j, n_il_offsets;
8323 GPtrArray *source_file_list;
8324 MonoSymSeqPoint *sym_seq_points;
8326 header = mono_method_get_header (method);
8328 buffer_add_int (buf, 0);
8329 buffer_add_string (buf, "");
8330 buffer_add_int (buf, 0);
8334 minfo = mono_debug_lookup_method (method);
8336 buffer_add_int (buf, header->code_size);
8337 buffer_add_string (buf, "");
8338 buffer_add_int (buf, 0);
8339 mono_metadata_free_mh (header);
8343 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, &source_files, &sym_seq_points, &n_il_offsets);
8344 buffer_add_int (buf, header->code_size);
8345 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8346 buffer_add_int (buf, source_file_list->len);
8347 for (i = 0; i < source_file_list->len; ++i) {
8348 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
8349 buffer_add_string (buf, sinfo->source_file);
8350 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8351 for (j = 0; j < 16; ++j)
8352 buffer_add_byte (buf, sinfo->hash [j]);
8356 buffer_add_string (buf, source_file);
8358 buffer_add_int (buf, n_il_offsets);
8359 DEBUG_PRINTF (10, "Line number table for method %s:\n", mono_method_full_name (method, TRUE));
8360 for (i = 0; i < n_il_offsets; ++i) {
8361 MonoSymSeqPoint *sp = &sym_seq_points [i];
8362 const char *srcfile = "";
8364 if (source_files [i] != -1) {
8365 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
8366 srcfile = sinfo->source_file;
8368 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);
8369 buffer_add_int (buf, sp->il_offset);
8370 buffer_add_int (buf, sp->line);
8371 if (CHECK_PROTOCOL_VERSION (2, 13))
8372 buffer_add_int (buf, source_files [i]);
8373 if (CHECK_PROTOCOL_VERSION (2, 19))
8374 buffer_add_int (buf, sp->column);
8375 if (CHECK_PROTOCOL_VERSION (2, 32)) {
8376 buffer_add_int (buf, sp->end_line);
8377 buffer_add_int (buf, sp->end_column);
8380 g_free (source_file);
8381 g_free (source_files);
8382 g_free (sym_seq_points);
8383 g_ptr_array_free (source_file_list, TRUE);
8384 mono_metadata_free_mh (header);
8387 case CMD_METHOD_GET_PARAM_INFO: {
8388 MonoMethodSignature *sig = mono_method_signature (method);
8392 /* FIXME: mono_class_from_mono_type () and byrefs */
8394 /* FIXME: Use a smaller encoding */
8395 buffer_add_int (buf, sig->call_convention);
8396 buffer_add_int (buf, sig->param_count);
8397 buffer_add_int (buf, sig->generic_param_count);
8398 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
8399 for (i = 0; i < sig->param_count; ++i) {
8401 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
8404 /* Emit parameter names */
8405 names = g_new (char *, sig->param_count);
8406 mono_method_get_param_names (method, (const char **) names);
8407 for (i = 0; i < sig->param_count; ++i)
8408 buffer_add_string (buf, names [i]);
8413 case CMD_METHOD_GET_LOCALS_INFO: {
8415 MonoDebugLocalsInfo *locals;
8416 int *locals_map = NULL;
8418 header = mono_method_get_header (method);
8420 return ERR_INVALID_ARGUMENT;
8422 locals = mono_debug_lookup_locals (method);
8424 buffer_add_int (buf, header->num_locals);
8426 for (i = 0; i < header->num_locals; ++i) {
8427 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
8430 for (i = 0; i < header->num_locals; ++i) {
8432 sprintf (lname, "V_%d", i);
8433 buffer_add_string (buf, lname);
8436 for (i = 0; i < header->num_locals; ++i) {
8437 buffer_add_int (buf, 0);
8438 buffer_add_int (buf, header->code_size);
8441 num_locals = locals->num_locals;
8442 buffer_add_int (buf, num_locals);
8445 for (i = 0; i < num_locals; ++i) {
8446 g_assert (locals->locals [i].index < header->num_locals);
8447 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [locals->locals [i].index]));
8450 for (i = 0; i < num_locals; ++i)
8451 buffer_add_string (buf, locals->locals [i].name);
8453 for (i = 0; i < num_locals; ++i) {
8454 if (locals->locals [i].block) {
8455 buffer_add_int (buf, locals->locals [i].block->start_offset);
8456 buffer_add_int (buf, locals->locals [i].block->end_offset);
8458 buffer_add_int (buf, 0);
8459 buffer_add_int (buf, header->code_size);
8463 mono_metadata_free_mh (header);
8466 mono_debug_free_locals (locals);
8467 g_free (locals_map);
8471 case CMD_METHOD_GET_INFO:
8472 buffer_add_int (buf, method->flags);
8473 buffer_add_int (buf, method->iflags);
8474 buffer_add_int (buf, method->token);
8475 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8477 if (method->is_generic)
8479 if (mono_method_signature (method)->generic_param_count)
8481 buffer_add_byte (buf, attrs);
8482 if (method->is_generic || method->is_inflated) {
8485 if (method->is_generic) {
8488 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8490 result = imethod->declaring;
8491 if (imethod->context.class_inst) {
8492 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8493 /*Generic methods gets the context of the GTD.*/
8494 if (mono_class_get_context (klass)) {
8496 result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), &error);
8497 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8502 buffer_add_methodid (buf, domain, result);
8504 buffer_add_id (buf, 0);
8506 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8507 if (mono_method_signature (method)->generic_param_count) {
8510 if (method->is_inflated) {
8511 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
8513 count = inst->type_argc;
8514 buffer_add_int (buf, count);
8516 for (i = 0; i < count; i++)
8517 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8519 buffer_add_int (buf, 0);
8521 } else if (method->is_generic) {
8522 MonoGenericContainer *container = mono_method_get_generic_container (method);
8524 count = mono_method_signature (method)->generic_param_count;
8525 buffer_add_int (buf, count);
8526 for (i = 0; i < count; i++) {
8527 MonoGenericParam *param = mono_generic_container_get_param (container, i);
8528 MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
8529 buffer_add_typeid (buf, domain, pklass);
8532 buffer_add_int (buf, 0);
8535 buffer_add_int (buf, 0);
8540 case CMD_METHOD_GET_BODY: {
8543 header = mono_method_get_header (method);
8545 buffer_add_int (buf, 0);
8547 if (CHECK_PROTOCOL_VERSION (2, 18))
8548 buffer_add_int (buf, 0);
8550 buffer_add_int (buf, header->code_size);
8551 for (i = 0; i < header->code_size; ++i)
8552 buffer_add_byte (buf, header->code [i]);
8554 if (CHECK_PROTOCOL_VERSION (2, 18)) {
8555 buffer_add_int (buf, header->num_clauses);
8556 for (i = 0; i < header->num_clauses; ++i) {
8557 MonoExceptionClause *clause = &header->clauses [i];
8559 buffer_add_int (buf, clause->flags);
8560 buffer_add_int (buf, clause->try_offset);
8561 buffer_add_int (buf, clause->try_len);
8562 buffer_add_int (buf, clause->handler_offset);
8563 buffer_add_int (buf, clause->handler_len);
8564 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
8565 buffer_add_typeid (buf, domain, clause->data.catch_class);
8566 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8567 buffer_add_int (buf, clause->data.filter_offset);
8571 mono_metadata_free_mh (header);
8576 case CMD_METHOD_RESOLVE_TOKEN: {
8577 guint32 token = decode_int (p, &p, end);
8580 switch (mono_metadata_token_code (token)) {
8581 case MONO_TOKEN_STRING: {
8585 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
8588 s2 = mono_string_to_utf8 (s);
8590 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8591 buffer_add_string (buf, s2);
8597 MonoClass *handle_class;
8599 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8600 val = mono_method_get_wrapper_data (method, token);
8601 handle_class = mono_method_get_wrapper_data (method, token + 1);
8603 if (handle_class == NULL) {
8604 // Can't figure out the token type
8605 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8610 val = mono_ldtoken_checked (method->klass->image, token, &handle_class, NULL, &error);
8612 g_error ("Could not load token due to %s", mono_error_get_message (&error));
8615 if (handle_class == mono_defaults.typehandle_class) {
8616 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8617 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8618 buffer_add_typeid (buf, domain, (MonoClass *) val);
8620 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
8621 } else if (handle_class == mono_defaults.fieldhandle_class) {
8622 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8623 buffer_add_fieldid (buf, domain, val);
8624 } else if (handle_class == mono_defaults.methodhandle_class) {
8625 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8626 buffer_add_methodid (buf, domain, val);
8627 } else if (handle_class == mono_defaults.string_class) {
8630 s = mono_string_to_utf8 (val);
8631 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8632 buffer_add_string (buf, s);
8635 g_assert_not_reached ();
8642 case CMD_METHOD_GET_CATTRS: {
8643 MonoClass *attr_klass;
8644 MonoCustomAttrInfo *cinfo;
8646 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8647 /* attr_klass can be NULL */
8651 cinfo = mono_custom_attrs_from_method (method);
8653 err = buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
8658 case CMD_METHOD_MAKE_GENERIC_METHOD: {
8660 MonoType **type_argv;
8664 MonoGenericInst *ginst;
8665 MonoGenericContext tmp_context;
8666 MonoMethod *inflated;
8668 type_argc = decode_int (p, &p, end);
8669 type_argv = g_new0 (MonoType*, type_argc);
8670 for (i = 0; i < type_argc; ++i) {
8671 klass = decode_typeid (p, &p, end, &d, &err);
8678 return ERR_INVALID_ARGUMENT;
8680 type_argv [i] = &klass->byval_arg;
8682 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
8684 tmp_context.class_inst = method->klass->generic_class ? method->klass->generic_class->context.class_inst : NULL;
8685 tmp_context.method_inst = ginst;
8687 inflated = mono_class_inflate_generic_method_checked (method, &tmp_context, &error);
8688 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8689 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
8690 return ERR_INVALID_ARGUMENT;
8691 buffer_add_methodid (buf, domain, inflated);
8695 return ERR_NOT_IMPLEMENTED;
8702 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8705 MonoDomain *old_domain;
8709 method = decode_methodid (p, &p, end, &domain, &err);
8713 old_domain = mono_domain_get ();
8715 mono_domain_set (domain, TRUE);
8717 err = method_commands_internal (command, method, domain, p, end, buf);
8719 mono_domain_set (old_domain, TRUE);
8725 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8727 int objid = decode_objid (p, &p, end);
8729 MonoThread *thread_obj;
8730 MonoInternalThread *thread;
8732 err = get_object (objid, (MonoObject**)&thread_obj);
8736 thread = THREAD_TO_INTERNAL (thread_obj);
8739 case CMD_THREAD_GET_NAME: {
8741 gunichar2 *s = mono_thread_get_name (thread, &name_len);
8744 buffer_add_int (buf, 0);
8749 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
8751 buffer_add_int (buf, len);
8752 buffer_add_data (buf, (guint8*)name, len);
8757 case CMD_THREAD_GET_FRAME_INFO: {
8758 DebuggerTlsData *tls;
8759 int i, start_frame, length;
8761 // Wait for suspending if it already started
8762 // FIXME: Races with suspend_count
8763 while (!is_suspended ()) {
8765 wait_for_suspend ();
8769 wait_for_suspend ();
8770 if (!is_suspended ())
8771 return ERR_NOT_SUSPENDED;
8774 start_frame = decode_int (p, &p, end);
8775 length = decode_int (p, &p, end);
8777 if (start_frame != 0 || length != -1)
8778 return ERR_NOT_IMPLEMENTED;
8780 mono_loader_lock ();
8781 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8782 mono_loader_unlock ();
8785 compute_frame_info (thread, tls);
8787 buffer_add_int (buf, tls->frame_count);
8788 for (i = 0; i < tls->frame_count; ++i) {
8789 buffer_add_int (buf, tls->frames [i]->id);
8790 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
8791 buffer_add_int (buf, tls->frames [i]->il_offset);
8793 * Instead of passing the frame type directly to the client, we associate
8794 * it with the previous frame using a set of flags. This avoids lots of
8795 * conditional code in the client, since a frame whose type isn't
8796 * FRAME_TYPE_MANAGED has no method, location, etc.
8798 buffer_add_byte (buf, tls->frames [i]->flags);
8803 case CMD_THREAD_GET_STATE:
8804 buffer_add_int (buf, thread->state);
8806 case CMD_THREAD_GET_INFO:
8807 buffer_add_byte (buf, thread->threadpool_thread);
8809 case CMD_THREAD_GET_ID:
8810 buffer_add_long (buf, (guint64)(gsize)thread);
8812 case CMD_THREAD_GET_TID:
8813 buffer_add_long (buf, (guint64)thread->tid);
8815 case CMD_THREAD_SET_IP: {
8816 DebuggerTlsData *tls;
8819 MonoSeqPointInfo *seq_points;
8824 method = decode_methodid (p, &p, end, &domain, &err);
8827 il_offset = decode_long (p, &p, end);
8829 while (!is_suspended ()) {
8831 wait_for_suspend ();
8834 mono_loader_lock ();
8835 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8836 mono_loader_unlock ();
8839 compute_frame_info (thread, tls);
8840 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
8841 return ERR_INVALID_ARGUMENT;
8843 found_sp = mono_find_seq_point (domain, method, il_offset, &seq_points, &sp);
8845 g_assert (seq_points);
8848 return ERR_INVALID_ARGUMENT;
8850 // FIXME: Check that the ip change is safe
8852 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);
8853 MONO_CONTEXT_SET_IP (&tls->restore_state.ctx, (guint8*)tls->frames [0]->ji->code_start + sp.native_offset);
8857 return ERR_NOT_IMPLEMENTED;
8864 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8868 MonoThread *thread_obj;
8869 MonoInternalThread *thread;
8870 int pos, i, len, frame_idx;
8871 DebuggerTlsData *tls;
8873 MonoDebugMethodJitInfo *jit;
8874 MonoMethodSignature *sig;
8876 MonoMethodHeader *header;
8878 objid = decode_objid (p, &p, end);
8879 err = get_object (objid, (MonoObject**)&thread_obj);
8883 thread = THREAD_TO_INTERNAL (thread_obj);
8885 id = decode_id (p, &p, end);
8887 mono_loader_lock ();
8888 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8889 mono_loader_unlock ();
8892 for (i = 0; i < tls->frame_count; ++i) {
8893 if (tls->frames [i]->id == id)
8896 if (i == tls->frame_count)
8897 return ERR_INVALID_FRAMEID;
8900 frame = tls->frames [frame_idx];
8902 /* This is supported for frames without has_ctx etc. set */
8903 if (command == CMD_STACK_FRAME_GET_DOMAIN) {
8904 if (CHECK_PROTOCOL_VERSION (2, 38))
8905 buffer_add_domainid (buf, frame->domain);
8909 if (!frame->has_ctx)
8910 return ERR_ABSENT_INFORMATION;
8913 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
8914 if (!frame->jit && frame->api_method->is_inflated)
8915 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
8919 /* This could happen for aot images with no jit debug info */
8920 s = mono_method_full_name (frame->api_method, TRUE);
8921 DEBUG_PRINTF (1, "[dbg] No debug information found for '%s'.\n", s);
8923 return ERR_ABSENT_INFORMATION;
8928 sig = mono_method_signature (frame->actual_method);
8930 if (!mono_get_seq_points (frame->domain, frame->actual_method))
8932 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
8934 return ERR_ABSENT_INFORMATION;
8937 case CMD_STACK_FRAME_GET_VALUES: {
8938 len = decode_int (p, &p, end);
8939 header = mono_method_get_header (frame->actual_method);
8941 for (i = 0; i < len; ++i) {
8942 pos = decode_int (p, &p, end);
8947 DEBUG_PRINTF (4, "[dbg] send arg %d.\n", pos);
8949 g_assert (pos >= 0 && pos < jit->num_params);
8951 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
8953 MonoDebugLocalsInfo *locals;
8955 locals = mono_debug_lookup_locals (frame->method);
8957 g_assert (pos < locals->num_locals);
8958 pos = locals->locals [pos].index;
8959 mono_debug_free_locals (locals);
8961 g_assert (pos >= 0 && pos < jit->num_locals);
8963 DEBUG_PRINTF (4, "[dbg] send local %d.\n", pos);
8965 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
8968 mono_metadata_free_mh (header);
8971 case CMD_STACK_FRAME_GET_THIS: {
8972 if (frame->api_method->klass->valuetype) {
8973 if (!sig->hasthis) {
8974 MonoObject *p = NULL;
8975 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
8977 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8980 if (!sig->hasthis) {
8981 MonoObject *p = NULL;
8982 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
8984 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8989 case CMD_STACK_FRAME_SET_VALUES: {
8992 MonoDebugVarInfo *var;
8994 len = decode_int (p, &p, end);
8995 header = mono_method_get_header (frame->actual_method);
8997 for (i = 0; i < len; ++i) {
8998 pos = decode_int (p, &p, end);
9003 g_assert (pos >= 0 && pos < jit->num_params);
9005 t = sig->params [pos];
9006 var = &jit->params [pos];
9008 MonoDebugLocalsInfo *locals;
9010 locals = mono_debug_lookup_locals (frame->method);
9012 g_assert (pos < locals->num_locals);
9013 pos = locals->locals [pos].index;
9014 mono_debug_free_locals (locals);
9016 g_assert (pos >= 0 && pos < jit->num_locals);
9018 t = header->locals [pos];
9019 var = &jit->locals [pos];
9022 if (MONO_TYPE_IS_REFERENCE (t))
9023 val_buf = g_alloca (sizeof (MonoObject*));
9025 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9026 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9030 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9032 mono_metadata_free_mh (header);
9035 case CMD_STACK_FRAME_GET_DOMAIN: {
9036 if (CHECK_PROTOCOL_VERSION (2, 38))
9037 buffer_add_domainid (buf, frame->domain);
9041 return ERR_NOT_IMPLEMENTED;
9048 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9051 int objid, err, index, len, i, esize;
9054 objid = decode_objid (p, &p, end);
9055 err = get_object (objid, (MonoObject**)&arr);
9060 case CMD_ARRAY_REF_GET_LENGTH:
9061 buffer_add_int (buf, arr->obj.vtable->klass->rank);
9063 buffer_add_int (buf, arr->max_length);
9064 buffer_add_int (buf, 0);
9066 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
9067 buffer_add_int (buf, arr->bounds [i].length);
9068 buffer_add_int (buf, arr->bounds [i].lower_bound);
9072 case CMD_ARRAY_REF_GET_VALUES:
9073 index = decode_int (p, &p, end);
9074 len = decode_int (p, &p, end);
9076 g_assert (index >= 0 && len >= 0);
9077 // Reordered to avoid integer overflow
9078 g_assert (!(index > arr->max_length - len));
9080 esize = mono_array_element_size (arr->obj.vtable->klass);
9081 for (i = index; i < index + len; ++i) {
9082 elem = (gpointer*)((char*)arr->vector + (i * esize));
9083 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
9086 case CMD_ARRAY_REF_SET_VALUES:
9087 index = decode_int (p, &p, end);
9088 len = decode_int (p, &p, end);
9090 g_assert (index >= 0 && len >= 0);
9091 // Reordered to avoid integer overflow
9092 g_assert (!(index > arr->max_length - len));
9094 esize = mono_array_element_size (arr->obj.vtable->klass);
9095 for (i = index; i < index + len; ++i) {
9096 elem = (gpointer*)((char*)arr->vector + (i * esize));
9098 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
9102 return ERR_NOT_IMPLEMENTED;
9109 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9114 int i, index, length;
9116 gboolean use_utf16 = FALSE;
9118 objid = decode_objid (p, &p, end);
9119 err = get_object (objid, (MonoObject**)&str);
9124 case CMD_STRING_REF_GET_VALUE:
9125 if (CHECK_PROTOCOL_VERSION (2, 41)) {
9126 for (i = 0; i < mono_string_length (str); ++i)
9127 if (mono_string_chars (str)[i] == 0)
9129 buffer_add_byte (buf, use_utf16 ? 1 : 0);
9132 buffer_add_int (buf, mono_string_length (str) * 2);
9133 buffer_add_data (buf, (guint8*)mono_string_chars (str), mono_string_length (str) * 2);
9135 s = mono_string_to_utf8 (str);
9136 buffer_add_string (buf, s);
9140 case CMD_STRING_REF_GET_LENGTH:
9141 buffer_add_long (buf, mono_string_length (str));
9143 case CMD_STRING_REF_GET_CHARS:
9144 index = decode_long (p, &p, end);
9145 length = decode_long (p, &p, end);
9146 if (index > mono_string_length (str) - length)
9147 return ERR_INVALID_ARGUMENT;
9148 c = mono_string_chars (str) + index;
9149 for (i = 0; i < length; ++i)
9150 buffer_add_short (buf, c [i]);
9153 return ERR_NOT_IMPLEMENTED;
9160 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9169 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9170 objid = decode_objid (p, &p, end);
9171 err = get_object (objid, &obj);
9173 buffer_add_int (buf, 1);
9175 buffer_add_int (buf, 0);
9179 objid = decode_objid (p, &p, end);
9180 err = get_object (objid, &obj);
9184 MonoClass *obj_type;
9186 obj_type = obj->vtable->klass;
9187 if (mono_class_is_transparent_proxy (obj_type))
9188 obj_type = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
9190 g_assert (obj_type);
9193 case CMD_OBJECT_REF_GET_TYPE:
9194 /* This handles transparent proxies too */
9195 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9197 case CMD_OBJECT_REF_GET_VALUES:
9198 len = decode_int (p, &p, end);
9200 for (i = 0; i < len; ++i) {
9201 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9205 /* Check that the field belongs to the object */
9207 for (k = obj_type; k; k = k->parent) {
9208 if (k == f->parent) {
9214 return ERR_INVALID_FIELDID;
9216 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9220 if (mono_class_field_is_special_static (f))
9221 return ERR_INVALID_FIELDID;
9223 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9224 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9225 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9226 mono_field_static_get_value (vtable, f, val);
9227 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9230 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
9234 case CMD_OBJECT_REF_SET_VALUES:
9235 len = decode_int (p, &p, end);
9237 for (i = 0; i < len; ++i) {
9238 f = decode_fieldid (p, &p, end, NULL, &err);
9242 /* Check that the field belongs to the object */
9244 for (k = obj_type; k; k = k->parent) {
9245 if (k == f->parent) {
9251 return ERR_INVALID_FIELDID;
9253 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9257 if (mono_class_field_is_special_static (f))
9258 return ERR_INVALID_FIELDID;
9260 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9261 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9263 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9264 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
9269 mono_field_static_set_value (vtable, f, val);
9272 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
9278 case CMD_OBJECT_REF_GET_ADDRESS:
9279 buffer_add_long (buf, (gssize)obj);
9281 case CMD_OBJECT_REF_GET_DOMAIN:
9282 buffer_add_domainid (buf, obj->vtable->domain);
9284 case CMD_OBJECT_REF_GET_INFO:
9285 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9286 buffer_add_domainid (buf, obj->vtable->domain);
9289 return ERR_NOT_IMPLEMENTED;
9296 command_set_to_string (CommandSet command_set)
9298 switch (command_set) {
9301 case CMD_SET_OBJECT_REF:
9302 return "OBJECT_REF";
9303 case CMD_SET_STRING_REF:
9304 return "STRING_REF";
9305 case CMD_SET_THREAD:
9307 case CMD_SET_ARRAY_REF:
9309 case CMD_SET_EVENT_REQUEST:
9310 return "EVENT_REQUEST";
9311 case CMD_SET_STACK_FRAME:
9312 return "STACK_FRAME";
9313 case CMD_SET_APPDOMAIN:
9315 case CMD_SET_ASSEMBLY:
9317 case CMD_SET_METHOD:
9321 case CMD_SET_MODULE:
9332 static const char* vm_cmds_str [] = {
9340 "SET_PROTOCOL_VERSION",
9343 "GET_TYPES_FOR_SOURCE_FILE",
9348 static const char* thread_cmds_str[] = {
9358 static const char* event_cmds_str[] = {
9361 "REQUEST_CLEAR_ALL_BREAKPOINTS"
9364 static const char* appdomain_cmds_str[] = {
9366 "GET_FRIENDLY_NAME",
9368 "GET_ENTRY_ASSEMBLY",
9371 "CREATE_BOXED_VALUE"
9374 static const char* assembly_cmds_str[] = {
9377 "GET_MANIFEST_MODULE",
9383 static const char* module_cmds_str[] = {
9387 static const char* field_cmds_str[] = {
9391 static const char* method_cmds_str[] = {
9393 "GET_DECLARING_TYPE",
9401 "MAKE_GENERIC_METHOD"
9404 static const char* type_cmds_str[] = {
9412 "IS_ASSIGNABLE_FROM",
9416 "GET_PROPERTY_CATTRS",
9417 "GET_SOURCE_FILES_2",
9419 "GET_METHODS_BY_NAME_FLAGS",
9421 "GET_INTERFACE_MAP",
9425 static const char* stack_frame_cmds_str[] = {
9432 static const char* array_cmds_str[] = {
9438 static const char* string_cmds_str[] = {
9444 static const char* object_cmds_str[] = {
9455 cmd_to_string (CommandSet set, int command)
9463 cmds_len = G_N_ELEMENTS (vm_cmds_str);
9465 case CMD_SET_OBJECT_REF:
9466 cmds = object_cmds_str;
9467 cmds_len = G_N_ELEMENTS (object_cmds_str);
9469 case CMD_SET_STRING_REF:
9470 cmds = string_cmds_str;
9471 cmds_len = G_N_ELEMENTS (string_cmds_str);
9473 case CMD_SET_THREAD:
9474 cmds = thread_cmds_str;
9475 cmds_len = G_N_ELEMENTS (thread_cmds_str);
9477 case CMD_SET_ARRAY_REF:
9478 cmds = array_cmds_str;
9479 cmds_len = G_N_ELEMENTS (array_cmds_str);
9481 case CMD_SET_EVENT_REQUEST:
9482 cmds = event_cmds_str;
9483 cmds_len = G_N_ELEMENTS (event_cmds_str);
9485 case CMD_SET_STACK_FRAME:
9486 cmds = stack_frame_cmds_str;
9487 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
9489 case CMD_SET_APPDOMAIN:
9490 cmds = appdomain_cmds_str;
9491 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
9493 case CMD_SET_ASSEMBLY:
9494 cmds = assembly_cmds_str;
9495 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
9497 case CMD_SET_METHOD:
9498 cmds = method_cmds_str;
9499 cmds_len = G_N_ELEMENTS (method_cmds_str);
9502 cmds = type_cmds_str;
9503 cmds_len = G_N_ELEMENTS (type_cmds_str);
9505 case CMD_SET_MODULE:
9506 cmds = module_cmds_str;
9507 cmds_len = G_N_ELEMENTS (module_cmds_str);
9510 cmds = field_cmds_str;
9511 cmds_len = G_N_ELEMENTS (field_cmds_str);
9514 cmds = event_cmds_str;
9515 cmds_len = G_N_ELEMENTS (event_cmds_str);
9520 if (command > 0 && command <= cmds_len)
9521 return cmds [command - 1];
9527 wait_for_attach (void)
9529 #ifndef DISABLE_SOCKET_TRANSPORT
9530 if (listen_fd == -1) {
9531 DEBUG_PRINTF (1, "[dbg] Invalid listening socket\n");
9535 /* Block and wait for client connection */
9536 MONO_PREPARE_BLOCKING;
9537 conn_fd = socket_transport_accept (listen_fd);
9538 MONO_FINISH_BLOCKING;
9540 DEBUG_PRINTF (1, "Accepted connection on %d\n", conn_fd);
9541 if (conn_fd == -1) {
9542 DEBUG_PRINTF (1, "[dbg] Bad client connection\n");
9546 g_assert_not_reached ();
9550 disconnected = !transport_handshake ();
9552 DEBUG_PRINTF (1, "Transport handshake failed!\n");
9562 * This thread handles communication with the debugger client using a JDWP
9565 static guint32 WINAPI
9566 debugger_thread (void *arg)
9568 int res, len, id, flags, command_set = 0, command = 0;
9569 guint8 header [HEADER_LENGTH];
9570 guint8 *data, *p, *end;
9574 gboolean attach_failed = FALSE;
9576 DEBUG_PRINTF (1, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ());
9578 debugger_thread_id = GetCurrentThreadId ();
9580 mono_jit_thread_attach (mono_get_root_domain ());
9582 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
9584 mono_set_is_debugger_attached (TRUE);
9586 if (agent_config.defer) {
9587 if (!wait_for_attach ()) {
9588 DEBUG_PRINTF (1, "[dbg] Can't attach, aborting debugger thread.\n");
9589 attach_failed = TRUE; // Don't abort process when we can't listen
9591 /* Send start event to client */
9592 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
9596 while (!attach_failed) {
9597 MONO_PREPARE_BLOCKING;
9598 res = transport_recv (header, HEADER_LENGTH);
9599 MONO_FINISH_BLOCKING;
9601 /* This will break if the socket is closed during shutdown too */
9602 if (res != HEADER_LENGTH) {
9603 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH);
9608 end = header + HEADER_LENGTH;
9610 len = decode_int (p, &p, end);
9611 id = decode_int (p, &p, end);
9612 flags = decode_byte (p, &p, end);
9613 command_set = decode_byte (p, &p, end);
9614 command = decode_byte (p, &p, end);
9616 g_assert (flags == 0);
9619 const char *cmd_str;
9622 cmd_str = cmd_to_string (command_set, command);
9624 sprintf (cmd_num, "%d", command);
9628 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);
9631 data = g_malloc (len - HEADER_LENGTH);
9632 if (len - HEADER_LENGTH > 0)
9634 MONO_PREPARE_BLOCKING;
9635 res = transport_recv (data, len - HEADER_LENGTH);
9636 MONO_FINISH_BLOCKING;
9637 if (res != len - HEADER_LENGTH) {
9638 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH);
9644 end = data + (len - HEADER_LENGTH);
9646 buffer_init (&buf, 128);
9651 /* Process the request */
9652 switch (command_set) {
9654 err = vm_commands (command, id, p, end, &buf);
9655 if (!err && command == CMD_VM_INVOKE_METHOD)
9656 /* Sent after the invoke is complete */
9659 case CMD_SET_EVENT_REQUEST:
9660 err = event_commands (command, p, end, &buf);
9662 case CMD_SET_APPDOMAIN:
9663 err = domain_commands (command, p, end, &buf);
9665 case CMD_SET_ASSEMBLY:
9666 err = assembly_commands (command, p, end, &buf);
9668 case CMD_SET_MODULE:
9669 err = module_commands (command, p, end, &buf);
9672 err = field_commands (command, p, end, &buf);
9675 err = type_commands (command, p, end, &buf);
9677 case CMD_SET_METHOD:
9678 err = method_commands (command, p, end, &buf);
9680 case CMD_SET_THREAD:
9681 err = thread_commands (command, p, end, &buf);
9683 case CMD_SET_STACK_FRAME:
9684 err = frame_commands (command, p, end, &buf);
9686 case CMD_SET_ARRAY_REF:
9687 err = array_commands (command, p, end, &buf);
9689 case CMD_SET_STRING_REF:
9690 err = string_commands (command, p, end, &buf);
9692 case CMD_SET_OBJECT_REF:
9693 err = object_commands (command, p, end, &buf);
9696 err = ERR_NOT_IMPLEMENTED;
9699 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
9700 buffer_replies = TRUE;
9704 if (buffer_replies) {
9705 buffer_reply_packet (id, err, &buf);
9707 send_reply_packet (id, err, &buf);
9708 //DEBUG_PRINTF (1, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000);
9712 if (!err && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
9713 send_buffered_reply_packets ();
9714 buffer_replies = FALSE;
9720 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
9724 mono_set_is_debugger_attached (FALSE);
9727 mono_mutex_lock (&debugger_thread_exited_mutex);
9728 debugger_thread_exited = TRUE;
9729 mono_cond_signal (&debugger_thread_exited_cond);
9730 mono_mutex_unlock (&debugger_thread_exited_mutex);
9731 MONO_FINISH_TRY_BLOCKING;
9733 DEBUG_PRINTF (1, "[dbg] Debugger thread exited.\n");
9735 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
9736 DEBUG_PRINTF (2, "[dbg] Detached - restarting clean debugger thread.\n");
9737 start_debugger_thread ();
9743 #else /* DISABLE_DEBUGGER_AGENT */
9746 mono_debugger_agent_parse_options (char *options)
9748 g_error ("This runtime is configured with the debugger agent disabled.");
9752 mono_debugger_agent_init (void)
9757 mono_debugger_agent_breakpoint_hit (void *sigctx)
9762 mono_debugger_agent_single_step_event (void *sigctx)
9767 mono_debugger_agent_free_domain_info (MonoDomain *domain)
9772 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
9773 MonoContext *catch_ctx)
9778 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9783 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9788 mono_debugger_agent_user_break (void)
9794 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
9799 mono_debugger_agent_debug_log_is_enabled (void)
9805 mono_debugger_agent_unhandled_exception (MonoException *exc)
9807 g_assert_not_reached ();
9811 debugger_agent_single_step_from_context (MonoContext *ctx)
9813 g_assert_not_reached ();
9817 debugger_agent_breakpoint_from_context (MonoContext *ctx)
9819 g_assert_not_reached ();