2 * debugger-agent.c: Soft Debugger back-end module
5 * Zoltan Varga (vargaz@gmail.com)
7 * Copyright 2009-2010 Novell, Inc.
8 * Copyright 2011 Xamarin Inc.
9 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
16 #ifdef HAVE_SYS_TYPES_H
17 #include <sys/types.h>
19 #ifdef HAVE_SYS_SELECT_H
20 #include <sys/select.h>
22 #ifdef HAVE_SYS_SOCKET_H
23 #include <sys/socket.h>
25 #ifdef HAVE_NETINET_TCP_H
26 #include <netinet/tcp.h>
28 #ifdef HAVE_NETINET_IN_H
29 #include <netinet/in.h>
49 #ifdef PLATFORM_ANDROID
51 #include <linux/tcp.h>
52 #include <sys/endian.h>
55 #include <mono/metadata/mono-debug.h>
56 #include <mono/metadata/mono-debug-debugger.h>
57 #include <mono/metadata/debug-mono-symfile.h>
58 #include <mono/metadata/gc-internals.h>
59 #include <mono/metadata/environment.h>
60 #include <mono/metadata/threads-types.h>
61 #include <mono/metadata/threadpool-ms.h>
62 #include <mono/metadata/socket-io.h>
63 #include <mono/metadata/assembly.h>
64 #include <mono/metadata/runtime.h>
65 #include <mono/metadata/verify-internals.h>
66 #include <mono/metadata/reflection-internals.h>
67 #include <mono/utils/mono-coop-mutex.h>
68 #include <mono/utils/mono-coop-semaphore.h>
69 #include <mono/utils/mono-error-internals.h>
70 #include <mono/utils/mono-stack-unwinding.h>
71 #include <mono/utils/mono-time.h>
72 #include <mono/utils/mono-threads.h>
73 #include <mono/utils/networking.h>
74 #include "debugger-agent.h"
76 #include "seq-points.h"
79 * On iOS we can't use System.Environment.Exit () as it will do the wrong
82 #if !defined (TARGET_IOS)
83 #define TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
87 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
88 #define DISABLE_DEBUGGER_AGENT 1
91 #ifdef DISABLE_SOFT_DEBUG
92 #define DISABLE_DEBUGGER_AGENT 1
95 #ifndef DISABLE_DEBUGGER_AGENT
97 #include <mono/utils/mono-os-mutex.h>
99 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
122 guint32 il_offset, native_offset;
126 * If method is gshared, this is the actual instance, otherwise this is equal to
129 MonoMethod *actual_method;
131 * This is the method which is visible to debugger clients. Same as method,
132 * except for native-to-managed wrappers.
134 MonoMethod *api_method;
136 MonoDebugMethodJitInfo *jit;
139 mgreg_t *reg_locations [MONO_MAX_IREGS];
141 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
142 * the frame can become invalid.
147 typedef struct _InvokeData InvokeData;
155 /* This is the context which needs to be restored after the invoke */
159 * If this is set, invoke this method with the arguments given by ARGS.
163 guint32 suspend_count;
166 InvokeData *last_invoke;
170 MonoThreadUnwindState context;
172 /* This is computed on demand when it is requested using the wire protocol */
173 /* It is freed up when the thread is resumed */
177 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
180 gboolean frames_up_to_date;
182 * Points to data about a pending invoke which needs to be executed after the thread
185 InvokeData *pending_invoke;
187 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
192 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
193 * within a finite amount of time.
197 * Set to TRUE if this thread is suspended in suspend_current ().
199 gboolean really_suspended;
200 /* Used to pass the context to the breakpoint/single step handler */
201 MonoContext handler_ctx;
202 /* Whenever thread_stop () was called for this thread */
205 /* Whenever to disable breakpoints (used during invokes) */
206 gboolean disable_breakpoints;
209 * Number of times this thread has been resumed using resume_thread ().
211 guint32 resume_count;
213 MonoInternalThread *thread;
216 * Information about the frame which transitioned to native code for running
219 StackFrameInfo async_last_frame;
222 * The context where the stack walk can be started for running threads.
224 MonoThreadUnwindState async_state;
227 * The context used for filter clauses
229 MonoThreadUnwindState filter_state;
231 gboolean abort_requested;
234 * The current mono_runtime_invoke_checked invocation.
239 * The context where single stepping should resume while the thread is suspended because
240 * of an EXCEPTION event.
242 MonoThreadUnwindState catch_state;
245 * The context which needs to be restored after handling a single step/breakpoint
246 * event. This is the same as the ctx at step/breakpoint site, but includes changes
247 * to caller saved registers done by set_var ().
249 MonoThreadUnwindState restore_state;
250 /* Frames computed from restore_state */
251 int restore_frame_count;
252 StackFrame **restore_frames;
254 /* The currently unloading appdomain */
255 MonoDomain *domain_unloading;
260 void (*connect) (const char *address);
261 void (*close1) (void);
262 void (*close2) (void);
263 gboolean (*send) (void *buf, int len);
264 int (*recv) (void *buf, int len);
268 * Wire Protocol definitions
271 #define HEADER_LENGTH 11
273 #define MAJOR_VERSION 2
274 #define MINOR_VERSION 42
278 CMD_SET_OBJECT_REF = 9,
279 CMD_SET_STRING_REF = 10,
281 CMD_SET_ARRAY_REF = 13,
282 CMD_SET_EVENT_REQUEST = 15,
283 CMD_SET_STACK_FRAME = 16,
284 CMD_SET_APPDOMAIN = 20,
285 CMD_SET_ASSEMBLY = 21,
294 EVENT_KIND_VM_START = 0,
295 EVENT_KIND_VM_DEATH = 1,
296 EVENT_KIND_THREAD_START = 2,
297 EVENT_KIND_THREAD_DEATH = 3,
298 EVENT_KIND_APPDOMAIN_CREATE = 4,
299 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
300 EVENT_KIND_METHOD_ENTRY = 6,
301 EVENT_KIND_METHOD_EXIT = 7,
302 EVENT_KIND_ASSEMBLY_LOAD = 8,
303 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
304 EVENT_KIND_BREAKPOINT = 10,
305 EVENT_KIND_STEP = 11,
306 EVENT_KIND_TYPE_LOAD = 12,
307 EVENT_KIND_EXCEPTION = 13,
308 EVENT_KIND_KEEPALIVE = 14,
309 EVENT_KIND_USER_BREAK = 15,
310 EVENT_KIND_USER_LOG = 16
314 SUSPEND_POLICY_NONE = 0,
315 SUSPEND_POLICY_EVENT_THREAD = 1,
316 SUSPEND_POLICY_ALL = 2
321 ERR_INVALID_OBJECT = 20,
322 ERR_INVALID_FIELDID = 25,
323 ERR_INVALID_FRAMEID = 30,
324 ERR_NOT_IMPLEMENTED = 100,
325 ERR_NOT_SUSPENDED = 101,
326 ERR_INVALID_ARGUMENT = 102,
328 ERR_NO_INVOCATION = 104,
329 ERR_ABSENT_INFORMATION = 105,
330 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
331 ERR_INVOKE_ABORTED = 107,
332 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
337 MOD_KIND_THREAD_ONLY = 3,
338 MOD_KIND_LOCATION_ONLY = 7,
339 MOD_KIND_EXCEPTION_ONLY = 8,
341 MOD_KIND_ASSEMBLY_ONLY = 11,
342 MOD_KIND_SOURCE_FILE_ONLY = 12,
343 MOD_KIND_TYPE_NAME_ONLY = 13,
359 STEP_FILTER_NONE = 0,
360 STEP_FILTER_STATIC_CTOR = 1,
361 STEP_FILTER_DEBUGGER_HIDDEN = 2,
362 STEP_FILTER_DEBUGGER_STEP_THROUGH = 4,
363 STEP_FILTER_DEBUGGER_NON_USER_CODE = 8
367 TOKEN_TYPE_STRING = 0,
369 TOKEN_TYPE_FIELD = 2,
370 TOKEN_TYPE_METHOD = 3,
371 TOKEN_TYPE_UNKNOWN = 4
375 VALUE_TYPE_ID_NULL = 0xf0,
376 VALUE_TYPE_ID_TYPE = 0xf1,
377 VALUE_TYPE_ID_PARENT_VTYPE = 0xf2
381 FRAME_FLAG_DEBUGGER_INVOKE = 1,
382 FRAME_FLAG_NATIVE_TRANSITION = 2
386 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
387 INVOKE_FLAG_SINGLE_THREADED = 2,
388 INVOKE_FLAG_RETURN_OUT_THIS = 4,
389 INVOKE_FLAG_RETURN_OUT_ARGS = 8,
390 INVOKE_FLAG_VIRTUAL = 16
394 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
395 } BindingFlagsExtensions;
399 CMD_VM_ALL_THREADS = 2,
404 CMD_VM_INVOKE_METHOD = 7,
405 CMD_VM_SET_PROTOCOL_VERSION = 8,
406 CMD_VM_ABORT_INVOKE = 9,
407 CMD_VM_SET_KEEPALIVE = 10,
408 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
409 CMD_VM_GET_TYPES = 12,
410 CMD_VM_INVOKE_METHODS = 13,
411 CMD_VM_START_BUFFERING = 14,
412 CMD_VM_STOP_BUFFERING = 15
416 CMD_THREAD_GET_FRAME_INFO = 1,
417 CMD_THREAD_GET_NAME = 2,
418 CMD_THREAD_GET_STATE = 3,
419 CMD_THREAD_GET_INFO = 4,
420 CMD_THREAD_GET_ID = 5,
421 CMD_THREAD_GET_TID = 6,
422 CMD_THREAD_SET_IP = 7
426 CMD_EVENT_REQUEST_SET = 1,
427 CMD_EVENT_REQUEST_CLEAR = 2,
428 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
436 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
437 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
438 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
439 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
440 CMD_APPDOMAIN_CREATE_STRING = 5,
441 CMD_APPDOMAIN_GET_CORLIB = 6,
442 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
446 CMD_ASSEMBLY_GET_LOCATION = 1,
447 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
448 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
449 CMD_ASSEMBLY_GET_OBJECT = 4,
450 CMD_ASSEMBLY_GET_TYPE = 5,
451 CMD_ASSEMBLY_GET_NAME = 6
455 CMD_MODULE_GET_INFO = 1,
459 CMD_FIELD_GET_INFO = 1,
463 CMD_METHOD_GET_NAME = 1,
464 CMD_METHOD_GET_DECLARING_TYPE = 2,
465 CMD_METHOD_GET_DEBUG_INFO = 3,
466 CMD_METHOD_GET_PARAM_INFO = 4,
467 CMD_METHOD_GET_LOCALS_INFO = 5,
468 CMD_METHOD_GET_INFO = 6,
469 CMD_METHOD_GET_BODY = 7,
470 CMD_METHOD_RESOLVE_TOKEN = 8,
471 CMD_METHOD_GET_CATTRS = 9,
472 CMD_METHOD_MAKE_GENERIC_METHOD = 10
476 CMD_TYPE_GET_INFO = 1,
477 CMD_TYPE_GET_METHODS = 2,
478 CMD_TYPE_GET_FIELDS = 3,
479 CMD_TYPE_GET_VALUES = 4,
480 CMD_TYPE_GET_OBJECT = 5,
481 CMD_TYPE_GET_SOURCE_FILES = 6,
482 CMD_TYPE_SET_VALUES = 7,
483 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
484 CMD_TYPE_GET_PROPERTIES = 9,
485 CMD_TYPE_GET_CATTRS = 10,
486 CMD_TYPE_GET_FIELD_CATTRS = 11,
487 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
488 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
489 CMD_TYPE_GET_VALUES_2 = 14,
490 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
491 CMD_TYPE_GET_INTERFACES = 16,
492 CMD_TYPE_GET_INTERFACE_MAP = 17,
493 CMD_TYPE_IS_INITIALIZED = 18,
494 CMD_TYPE_CREATE_INSTANCE = 19
498 CMD_STACK_FRAME_GET_VALUES = 1,
499 CMD_STACK_FRAME_GET_THIS = 2,
500 CMD_STACK_FRAME_SET_VALUES = 3,
501 CMD_STACK_FRAME_GET_DOMAIN = 4,
505 CMD_ARRAY_REF_GET_LENGTH = 1,
506 CMD_ARRAY_REF_GET_VALUES = 2,
507 CMD_ARRAY_REF_SET_VALUES = 3,
511 CMD_STRING_REF_GET_VALUE = 1,
512 CMD_STRING_REF_GET_LENGTH = 2,
513 CMD_STRING_REF_GET_CHARS = 3
517 CMD_OBJECT_REF_GET_TYPE = 1,
518 CMD_OBJECT_REF_GET_VALUES = 2,
519 CMD_OBJECT_REF_IS_COLLECTED = 3,
520 CMD_OBJECT_REF_GET_ADDRESS = 4,
521 CMD_OBJECT_REF_GET_DOMAIN = 5,
522 CMD_OBJECT_REF_SET_VALUES = 6,
523 CMD_OBJECT_REF_GET_INFO = 7,
529 int count; /* For kind == MOD_KIND_COUNT */
530 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
531 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
532 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
533 GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
534 GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
535 StepFilter filter; /* For kind == MOD_KIND_STEP */
537 gboolean caught, uncaught, subclasses; /* For kind == MOD_KIND_EXCEPTION_ONLY */
546 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
550 * Describes a single step request.
554 MonoInternalThread *thread;
560 MonoMethod *start_method;
561 MonoMethod *last_method;
563 /* Whenever single stepping is performed using start/stop_single_stepping () */
565 /* The list of breakpoints used to implement step-over */
567 /* The number of frames at the start of a step-over */
572 * Contains additional information for an event
575 /* For EVENT_KIND_EXCEPTION */
577 MonoContext catch_ctx;
579 /* For EVENT_KIND_USER_LOG */
581 char *category, *message;
582 /* For EVENT_KIND_TYPE_LOAD */
586 /* Dummy structure used for the profiler callbacks */
592 guint8 *buf, *p, *end;
595 typedef struct ReplyPacket {
601 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
603 #ifdef PLATFORM_ANDROID
604 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { g_print (__VA_ARGS__); } } while (0)
606 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { fprintf (log_file, __VA_ARGS__); fflush (log_file); } } while (0)
610 #define get_last_sock_error() WSAGetLastError()
611 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
612 #define MONO_EINTR WSAEINTR
614 #define get_last_sock_error() errno
615 #define MONO_EWOULDBLOCK EWOULDBLOCK
616 #define MONO_EINTR EINTR
619 #define CHECK_PROTOCOL_VERSION(major,minor) \
620 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
626 static AgentConfig agent_config;
629 * Whenever the agent is fully initialized.
630 * When using the onuncaught or onthrow options, only some parts of the agent are
631 * initialized on startup, and the full initialization which includes connection
632 * establishment and the startup of the agent thread is only done in response to
635 static gint32 inited;
637 #ifndef DISABLE_SOCKET_TRANSPORT
639 static int listen_fd;
642 static int packet_id = 0;
644 static int objref_id = 0;
646 static int event_request_id = 0;
648 static int frame_id = 0;
650 static GPtrArray *event_requests;
652 static MonoNativeTlsKey debugger_tls_id;
654 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
656 /* Maps MonoInternalThread -> DebuggerTlsData */
657 /* Protected by the loader lock */
658 static MonoGHashTable *thread_to_tls;
660 /* Maps tid -> MonoInternalThread */
661 /* Protected by the loader lock */
662 static MonoGHashTable *tid_to_thread;
664 /* Maps tid -> MonoThread (not MonoInternalThread) */
665 /* Protected by the loader lock */
666 static MonoGHashTable *tid_to_thread_obj;
668 static MonoNativeThreadId debugger_thread_id;
670 static HANDLE debugger_thread_handle;
672 static int log_level;
674 static gboolean embedding;
676 static FILE *log_file;
678 /* Assemblies whose assembly load event has no been sent yet */
679 /* Protected by the dbg lock */
680 static GPtrArray *pending_assembly_loads;
682 /* Whenever the debugger thread has exited */
683 static gboolean debugger_thread_exited;
685 /* Cond variable used to wait for debugger_thread_exited becoming true */
686 static MonoCoopCond debugger_thread_exited_cond;
688 /* Mutex for the cond var above */
689 static MonoCoopMutex debugger_thread_exited_mutex;
691 static DebuggerProfiler debugger_profiler;
693 /* The single step request instance */
694 static SingleStepReq *ss_req;
696 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
697 /* Number of single stepping operations in progress */
701 /* The protocol version of the client */
702 static int major_version, minor_version;
704 /* Whenever the variables above are set by the client */
705 static gboolean protocol_version_set;
707 /* A hash table containing all active domains */
708 /* Protected by the loader lock */
709 static GHashTable *domains;
711 /* The number of times the runtime is suspended */
712 static gint32 suspend_count;
714 /* Whenever to buffer reply messages and send them together */
715 static gboolean buffer_replies;
717 /* Buffered reply packets */
718 static ReplyPacket reply_packets [128];
721 #define dbg_lock() mono_coop_mutex_lock (&debug_mutex)
722 #define dbg_unlock() mono_coop_mutex_unlock (&debug_mutex)
723 static MonoCoopMutex debug_mutex;
725 static void transport_init (void);
726 static void transport_connect (const char *address);
727 static gboolean transport_handshake (void);
728 static void register_transport (DebuggerTransport *trans);
730 static guint32 WINAPI debugger_thread (void *arg);
732 static void runtime_initialized (MonoProfiler *prof);
734 static void runtime_shutdown (MonoProfiler *prof);
736 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
738 static void thread_end (MonoProfiler *prof, uintptr_t tid);
740 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
742 static void appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain);
744 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
746 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
748 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
750 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
752 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
754 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
756 static void emit_assembly_load (gpointer assembly, gpointer user_data);
758 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
760 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
762 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
764 static void start_single_stepping (void);
766 static void stop_single_stepping (void);
768 static void suspend_current (void);
770 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
772 static void clear_types_for_assembly (MonoAssembly *assembly);
774 static void clear_breakpoints_for_domain (MonoDomain *domain);
776 static void process_profiler_event (EventKind event, gpointer arg);
778 /* Submodule init/cleanup */
779 static void breakpoints_init (void);
780 static void breakpoints_cleanup (void);
782 static void objrefs_init (void);
783 static void objrefs_cleanup (void);
785 static void ids_init (void);
786 static void ids_cleanup (void);
788 static void suspend_init (void);
790 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch,
791 StackFrame **frames, int nframes);
792 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req);
793 static void ss_destroy (SingleStepReq *req);
795 static void start_debugger_thread (void);
796 static void stop_debugger_thread (void);
798 static void finish_agent_init (gboolean on_startup);
800 static void process_profiler_event (EventKind event, gpointer arg);
802 static void invalidate_frames (DebuggerTlsData *tls);
804 #ifndef DISABLE_SOCKET_TRANSPORT
806 register_socket_transport (void);
809 static inline gboolean
810 is_debugger_thread (void)
812 return mono_native_thread_id_equals (mono_native_thread_id_get (), debugger_thread_id);
816 parse_address (char *address, char **host, int *port)
818 char *pos = strchr (address, ':');
820 if (pos == NULL || pos == address)
823 *host = (char *)g_malloc (pos - address + 1);
824 strncpy (*host, address, pos - address);
825 (*host) [pos - address] = '\0';
827 *port = atoi (pos + 1);
835 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
836 fprintf (stderr, "Available options:\n");
837 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
838 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
839 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
840 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
841 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
842 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
843 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
844 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
845 fprintf (stderr, " setpgid=y/n\t\t\tWhether to call setpid(0, 0) after startup.\n");
846 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
850 parse_flag (const char *option, char *flag)
852 if (!strcmp (flag, "y"))
854 else if (!strcmp (flag, "n"))
857 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
864 mono_debugger_agent_parse_options (char *options)
871 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
872 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
876 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
878 options = g_strdup_printf ("%s,%s", options, extra);
880 agent_config.enabled = TRUE;
881 agent_config.suspend = TRUE;
882 agent_config.server = FALSE;
883 agent_config.defer = FALSE;
884 agent_config.address = NULL;
886 //agent_config.log_level = 10;
888 args = g_strsplit (options, ",", -1);
889 for (ptr = args; ptr && *ptr; ptr ++) {
892 if (strncmp (arg, "transport=", 10) == 0) {
893 agent_config.transport = g_strdup (arg + 10);
894 } else if (strncmp (arg, "address=", 8) == 0) {
895 agent_config.address = g_strdup (arg + 8);
896 } else if (strncmp (arg, "loglevel=", 9) == 0) {
897 agent_config.log_level = atoi (arg + 9);
898 } else if (strncmp (arg, "logfile=", 8) == 0) {
899 agent_config.log_file = g_strdup (arg + 8);
900 } else if (strncmp (arg, "suspend=", 8) == 0) {
901 agent_config.suspend = parse_flag ("suspend", arg + 8);
902 } else if (strncmp (arg, "server=", 7) == 0) {
903 agent_config.server = parse_flag ("server", arg + 7);
904 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
905 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
906 } else if (strncmp (arg, "onthrow=", 8) == 0) {
907 /* We support multiple onthrow= options */
908 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
909 } else if (strncmp (arg, "onthrow", 7) == 0) {
910 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
911 } else if (strncmp (arg, "help", 4) == 0) {
914 } else if (strncmp (arg, "timeout=", 8) == 0) {
915 agent_config.timeout = atoi (arg + 8);
916 } else if (strncmp (arg, "launch=", 7) == 0) {
917 agent_config.launch = g_strdup (arg + 7);
918 } else if (strncmp (arg, "embedding=", 10) == 0) {
919 agent_config.embedding = atoi (arg + 10) == 1;
920 } else if (strncmp (arg, "keepalive=", 10) == 0) {
921 agent_config.keepalive = atoi (arg + 10);
922 } else if (strncmp (arg, "setpgid=", 8) == 0) {
923 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
930 if (agent_config.server && !agent_config.suspend) {
931 /* Waiting for deferred attachment */
932 agent_config.defer = TRUE;
933 if (agent_config.address == NULL) {
934 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (getpid () % 1000));
938 //agent_config.log_level = 0;
940 if (agent_config.transport == NULL) {
941 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
945 if (agent_config.address == NULL && !agent_config.server) {
946 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
951 if (!strcmp (agent_config.transport, "dt_socket")) {
952 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
953 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
960 mono_debugger_agent_init (void)
962 mono_coop_mutex_init_recursive (&debug_mutex);
964 if (!agent_config.enabled)
969 /* Need to know whenever a thread has acquired the loader mutex */
970 mono_loader_lock_track_ownership (TRUE);
972 event_requests = g_ptr_array_new ();
974 mono_coop_mutex_init (&debugger_thread_exited_mutex);
975 mono_coop_cond_init (&debugger_thread_exited_cond);
977 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
978 mono_profiler_set_events ((MonoProfileFlags)(MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS));
979 mono_profiler_install_runtime_initialized (runtime_initialized);
980 mono_profiler_install_appdomain (NULL, appdomain_load, appdomain_start_unload, appdomain_unload);
981 mono_profiler_install_thread (thread_startup, thread_end);
982 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
983 mono_profiler_install_jit_end (jit_end);
985 mono_native_tls_alloc (&debugger_tls_id, NULL);
987 /* Needed by the hash_table_new_type () call below */
988 mono_gc_base_init ();
990 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_DEBUGGER, "thread-to-tls table");
991 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls, MONO_ROOT_SOURCE_DEBUGGER, "thread-to-tls table");
993 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread table");
994 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread table");
996 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread object table");
997 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread object table");
999 pending_assembly_loads = g_ptr_array_new ();
1000 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
1002 log_level = agent_config.log_level;
1004 embedding = agent_config.embedding;
1005 disconnected = TRUE;
1007 if (agent_config.log_file) {
1008 log_file = fopen (agent_config.log_file, "w+");
1010 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
1019 breakpoints_init ();
1022 mini_get_debug_options ()->gen_sdb_seq_points = TRUE;
1024 * This is needed because currently we don't handle liveness info.
1026 mini_get_debug_options ()->mdb_optimizations = TRUE;
1028 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
1029 /* This is needed because we can't set local variables in registers yet */
1030 mono_disable_optimizations (MONO_OPT_LINEARS);
1034 * The stack walk done from thread_interrupt () needs to be signal safe, but it
1035 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
1036 * safe (#3411). So load AOT info eagerly when the debugger is running as a
1039 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
1042 if (agent_config.setpgid)
1046 if (!agent_config.onuncaught && !agent_config.onthrow)
1047 finish_agent_init (TRUE);
1051 * finish_agent_init:
1053 * Finish the initialization of the agent. This involves connecting the transport
1054 * and starting the agent thread. This is either done at startup, or
1055 * in response to some event like an unhandled exception.
1058 finish_agent_init (gboolean on_startup)
1062 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
1065 if (agent_config.launch) {
1068 // FIXME: Generated address
1069 // FIXME: Races with transport_connect ()
1071 argv [0] = agent_config.launch;
1072 argv [1] = agent_config.transport;
1073 argv [2] = agent_config.address;
1076 res = g_spawn_async_with_pipes (NULL, argv, NULL, (GSpawnFlags)0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1078 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1083 transport_connect (agent_config.address);
1086 /* Do some which is usually done after sending the VMStart () event */
1087 vm_start_event_sent = TRUE;
1088 start_debugger_thread ();
1093 mono_debugger_agent_cleanup (void)
1098 stop_debugger_thread ();
1100 breakpoints_cleanup ();
1109 #ifndef DISABLE_SOCKET_TRANSPORT
1114 * recv() + handle incomplete reads and EINTR
1117 socket_transport_recv (void *buf, int len)
1123 static gint64 last_keepalive;
1130 res = recv (fd, (char *) buf + total, len - total, flags);
1133 if (agent_config.keepalive) {
1134 gboolean need_keepalive = FALSE;
1135 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1136 need_keepalive = TRUE;
1137 } else if (res == -1) {
1138 /* This could happen if recv () is interrupted repeatedly */
1139 msecs = mono_msec_ticks ();
1140 if (msecs - last_keepalive >= agent_config.keepalive) {
1141 need_keepalive = TRUE;
1142 last_keepalive = msecs;
1145 if (need_keepalive) {
1146 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1150 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1158 set_keepalive (void)
1163 if (!agent_config.keepalive || !conn_fd)
1166 tv.tv_sec = agent_config.keepalive / 1000;
1167 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1169 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1170 g_assert (result >= 0);
1174 socket_transport_accept (int socket_fd)
1177 conn_fd = accept (socket_fd, NULL, NULL);
1180 if (conn_fd == -1) {
1181 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1183 DEBUG_PRINTF (1, "Accepted connection from client, connection fd=%d.\n", conn_fd);
1190 socket_transport_send (void *data, int len)
1197 res = send (conn_fd, data, len, 0);
1198 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1209 * socket_transport_connect:
1211 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1214 socket_transport_connect (const char *address)
1216 MonoAddressInfo *result;
1217 MonoAddressEntry *rp;
1218 int sfd = -1, s, res;
1222 if (agent_config.address) {
1223 res = parse_address (agent_config.address, &host, &port);
1224 g_assert (res == 0);
1235 mono_network_init ();
1237 /* Obtain address(es) matching host/port */
1238 s = mono_get_address_info (host, port, MONO_HINT_UNSPECIFIED, &result);
1240 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, s); // FIXME add portable error conversion functions
1245 if (agent_config.server) {
1246 /* Wait for a connection */
1248 struct sockaddr_in addr;
1251 /* No address, generate one */
1252 sfd = socket (AF_INET, SOCK_STREAM, 0);
1255 /* This will bind the socket to a random port */
1256 res = listen (sfd, 16);
1258 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1263 addrlen = sizeof (addr);
1264 memset (&addr, 0, sizeof (addr));
1265 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1266 g_assert (res == 0);
1268 host = (char*)"127.0.0.1";
1269 port = ntohs (addr.sin_port);
1271 /* Emit the address to stdout */
1272 /* FIXME: Should print another interface, not localhost */
1273 printf ("%s:%d\n", host, port);
1275 /* Listen on the provided address */
1276 for (rp = result->entries; rp != NULL; rp = rp->next) {
1277 MonoSocketAddress sockaddr;
1281 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1283 sfd = socket (rp->family, rp->socktype,
1288 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1291 res = bind (sfd, &sockaddr.addr, sock_len);
1295 res = listen (sfd, 16);
1302 mono_free_address_info (result);
1305 if (agent_config.defer)
1308 DEBUG_PRINTF (1, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout);
1310 if (agent_config.timeout) {
1315 tv.tv_usec = agent_config.timeout * 1000;
1317 FD_SET (sfd, &readfds);
1320 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1324 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1329 conn_fd = socket_transport_accept (sfd);
1333 DEBUG_PRINTF (1, "Accepted connection from client, socket fd=%d.\n", conn_fd);
1335 /* Connect to the specified address */
1336 /* FIXME: Respect the timeout */
1337 for (rp = result->entries; rp != NULL; rp = rp->next) {
1338 MonoSocketAddress sockaddr;
1341 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1343 sfd = socket (rp->family, rp->socktype,
1349 res = connect (sfd, &sockaddr.addr, sock_len);
1353 break; /* Success */
1361 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1367 mono_free_address_info (result);
1370 if (!transport_handshake ())
1375 socket_transport_close1 (void)
1377 /* This will interrupt the agent thread */
1378 /* Close the read part only so it can still send back replies */
1379 /* Also shut down the connection listener so that we can exit normally */
1381 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1382 shutdown (conn_fd, SD_BOTH);
1383 shutdown (listen_fd, SD_BOTH);
1384 closesocket (listen_fd);
1386 shutdown (conn_fd, SHUT_RD);
1387 shutdown (listen_fd, SHUT_RDWR);
1395 socket_transport_close2 (void)
1398 shutdown (conn_fd, SD_BOTH);
1400 shutdown (conn_fd, SHUT_RDWR);
1405 register_socket_transport (void)
1407 DebuggerTransport trans;
1409 trans.name = "dt_socket";
1410 trans.connect = socket_transport_connect;
1411 trans.close1 = socket_transport_close1;
1412 trans.close2 = socket_transport_close2;
1413 trans.send = socket_transport_send;
1414 trans.recv = socket_transport_recv;
1416 register_transport (&trans);
1420 * socket_fd_transport_connect:
1424 socket_fd_transport_connect (const char *address)
1428 res = sscanf (address, "%d", &conn_fd);
1430 fprintf (stderr, "debugger-agent: socket-fd transport address is invalid: '%s'\n", address);
1434 if (!transport_handshake ())
1439 register_socket_fd_transport (void)
1441 DebuggerTransport trans;
1443 /* This is the same as the 'dt_socket' transport, but receives an already connected socket fd */
1444 trans.name = "socket-fd";
1445 trans.connect = socket_fd_transport_connect;
1446 trans.close1 = socket_transport_close1;
1447 trans.close2 = socket_transport_close2;
1448 trans.send = socket_transport_send;
1449 trans.recv = socket_transport_recv;
1451 register_transport (&trans);
1454 #endif /* DISABLE_SOCKET_TRANSPORT */
1460 #define MAX_TRANSPORTS 16
1462 static DebuggerTransport *transport;
1464 static DebuggerTransport transports [MAX_TRANSPORTS];
1465 static int ntransports;
1468 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1471 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1473 register_transport (trans);
1477 register_transport (DebuggerTransport *trans)
1479 g_assert (ntransports < MAX_TRANSPORTS);
1481 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1486 transport_init (void)
1490 #ifndef DISABLE_SOCKET_TRANSPORT
1491 register_socket_transport ();
1492 register_socket_fd_transport ();
1495 for (i = 0; i < ntransports; ++i) {
1496 if (!strcmp (agent_config.transport, transports [i].name))
1499 if (i == ntransports) {
1500 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1501 for (i = 0; i < ntransports; ++i)
1502 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1503 fprintf (stderr, "\n");
1506 transport = &transports [i];
1510 transport_connect (const char *address)
1512 transport->connect (address);
1516 transport_close1 (void)
1518 transport->close1 ();
1522 transport_close2 (void)
1524 transport->close2 ();
1528 transport_send (void *buf, int len)
1530 return transport->send (buf, len);
1534 transport_recv (void *buf, int len)
1536 return transport->recv (buf, len);
1540 mono_debugger_agent_transport_handshake (void)
1542 return transport_handshake ();
1546 transport_handshake (void)
1548 char handshake_msg [128];
1552 disconnected = TRUE;
1554 /* Write handshake message */
1555 sprintf (handshake_msg, "DWP-Handshake");
1558 res = transport_send (handshake_msg, strlen (handshake_msg));
1559 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1561 g_assert (res != -1);
1564 res = transport_recv (buf, strlen (handshake_msg));
1565 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg)) != 0)) {
1566 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1571 * To support older clients, the client sends its protocol version after connecting
1572 * using a command. Until that is received, default to our protocol version.
1574 major_version = MAJOR_VERSION;
1575 minor_version = MINOR_VERSION;
1576 protocol_version_set = FALSE;
1578 #ifndef DISABLE_SOCKET_TRANSPORT
1579 // FIXME: Move this somewhere else
1581 * Set TCP_NODELAY on the socket so the client receives events/command
1582 * results immediately.
1586 int result = setsockopt (conn_fd,
1591 g_assert (result >= 0);
1597 disconnected = FALSE;
1602 stop_debugger_thread (void)
1607 transport_close1 ();
1610 * Wait for the thread to exit.
1612 * If we continue with the shutdown without waiting for it, then the client might
1613 * not receive an answer to its last command like a resume.
1615 if (!is_debugger_thread ()) {
1617 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
1618 if (!debugger_thread_exited)
1619 mono_coop_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1620 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
1621 } while (!debugger_thread_exited);
1624 transport_close2 ();
1628 start_debugger_thread (void)
1630 debugger_thread_handle = mono_threads_create_thread (debugger_thread, NULL, 0, 0, NULL);
1631 g_assert (debugger_thread_handle);
1635 * Functions to decode protocol data
1639 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1642 g_assert (*endbuf <= limit);
1647 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1650 g_assert (*endbuf <= limit);
1652 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1655 static inline gint64
1656 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1658 guint32 high = decode_int (buf, &buf, limit);
1659 guint32 low = decode_int (buf, &buf, limit);
1663 return ((((guint64)high) << 32) | ((guint64)low));
1667 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1669 return decode_int (buf, endbuf, limit);
1673 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1675 int len = decode_int (buf, &buf, limit);
1683 s = (char *)g_malloc (len + 1);
1686 memcpy (s, buf, len);
1695 * Functions to encode protocol data
1699 buffer_init (Buffer *buf, int size)
1701 buf->buf = (guint8 *)g_malloc (size);
1703 buf->end = buf->buf + size;
1707 buffer_len (Buffer *buf)
1709 return buf->p - buf->buf;
1713 buffer_make_room (Buffer *buf, int size)
1715 if (buf->end - buf->p < size) {
1716 int new_size = buf->end - buf->buf + size + 32;
1717 guint8 *p = (guint8 *)g_realloc (buf->buf, new_size);
1718 size = buf->p - buf->buf;
1721 buf->end = buf->buf + new_size;
1726 buffer_add_byte (Buffer *buf, guint8 val)
1728 buffer_make_room (buf, 1);
1734 buffer_add_short (Buffer *buf, guint32 val)
1736 buffer_make_room (buf, 2);
1737 buf->p [0] = (val >> 8) & 0xff;
1738 buf->p [1] = (val >> 0) & 0xff;
1743 buffer_add_int (Buffer *buf, guint32 val)
1745 buffer_make_room (buf, 4);
1746 buf->p [0] = (val >> 24) & 0xff;
1747 buf->p [1] = (val >> 16) & 0xff;
1748 buf->p [2] = (val >> 8) & 0xff;
1749 buf->p [3] = (val >> 0) & 0xff;
1754 buffer_add_long (Buffer *buf, guint64 l)
1756 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1757 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1761 buffer_add_id (Buffer *buf, int id)
1763 buffer_add_int (buf, (guint64)id);
1767 buffer_add_data (Buffer *buf, guint8 *data, int len)
1769 buffer_make_room (buf, len);
1770 memcpy (buf->p, data, len);
1775 buffer_add_string (Buffer *buf, const char *str)
1780 buffer_add_int (buf, 0);
1783 buffer_add_int (buf, len);
1784 buffer_add_data (buf, (guint8*)str, len);
1789 buffer_add_buffer (Buffer *buf, Buffer *data)
1791 buffer_add_data (buf, data->buf, buffer_len (data));
1795 buffer_free (Buffer *buf)
1801 send_packet (int command_set, int command, Buffer *data)
1807 id = InterlockedIncrement (&packet_id);
1809 len = data->p - data->buf + 11;
1810 buffer_init (&buf, len);
1811 buffer_add_int (&buf, len);
1812 buffer_add_int (&buf, id);
1813 buffer_add_byte (&buf, 0); /* flags */
1814 buffer_add_byte (&buf, command_set);
1815 buffer_add_byte (&buf, command);
1816 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1818 res = transport_send (buf.buf, len);
1826 send_reply_packets (int npackets, ReplyPacket *packets)
1833 for (i = 0; i < npackets; ++i)
1834 len += buffer_len (packets [i].data) + 11;
1835 buffer_init (&buf, len);
1836 for (i = 0; i < npackets; ++i) {
1837 buffer_add_int (&buf, buffer_len (packets [i].data) + 11);
1838 buffer_add_int (&buf, packets [i].id);
1839 buffer_add_byte (&buf, 0x80); /* flags */
1840 buffer_add_byte (&buf, (packets [i].error >> 8) & 0xff);
1841 buffer_add_byte (&buf, packets [i].error);
1842 buffer_add_buffer (&buf, packets [i].data);
1845 res = transport_send (buf.buf, len);
1853 send_reply_packet (int id, int error, Buffer *data)
1857 memset (&packet, 0, sizeof (ReplyPacket));
1859 packet.error = error;
1862 return send_reply_packets (1, &packet);
1866 send_buffered_reply_packets (void)
1870 send_reply_packets (nreply_packets, reply_packets);
1871 for (i = 0; i < nreply_packets; ++i)
1872 buffer_free (reply_packets [i].data);
1873 DEBUG_PRINTF (1, "[dbg] Sent %d buffered reply packets [at=%lx].\n", nreply_packets, (long)mono_100ns_ticks () / 10000);
1878 buffer_reply_packet (int id, int error, Buffer *data)
1882 if (nreply_packets == 128)
1883 send_buffered_reply_packets ();
1885 p = &reply_packets [nreply_packets];
1888 p->data = g_new0 (Buffer, 1);
1889 buffer_init (p->data, buffer_len (data));
1890 buffer_add_buffer (p->data, data);
1899 * Represents an object accessible by the debugger client.
1902 /* Unique id used in the wire protocol to refer to objects */
1905 * A weakref gc handle pointing to the object. The gc handle is used to
1906 * detect if the object was garbage collected.
1911 /* Maps objid -> ObjRef */
1912 /* Protected by the loader lock */
1913 static GHashTable *objrefs;
1914 /* Protected by the loader lock */
1915 static GHashTable *obj_to_objref;
1916 /* Protected by the dbg lock */
1917 static MonoGHashTable *suspended_objs;
1920 free_objref (gpointer value)
1922 ObjRef *o = (ObjRef *)value;
1924 mono_gchandle_free (o->handle);
1932 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1933 obj_to_objref = g_hash_table_new (NULL, NULL);
1934 suspended_objs = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_DEBUGGER, "suspended objects table");
1935 MONO_GC_REGISTER_ROOT_FIXED (suspended_objs, MONO_ROOT_SOURCE_DEBUGGER, "suspended objects table");
1939 objrefs_cleanup (void)
1941 g_hash_table_destroy (objrefs);
1946 * Return an ObjRef for OBJ.
1949 get_objref (MonoObject *obj)
1952 GSList *reflist = NULL, *l;
1958 if (suspend_count) {
1960 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1963 mono_g_hash_table_insert (suspended_objs, obj, NULL);
1967 mono_loader_lock ();
1969 /* FIXME: The tables can grow indefinitely */
1971 if (mono_gc_is_moving ()) {
1973 * Objects can move, so use a hash table mapping hash codes to lists of
1974 * ObjRef structures.
1976 hash = mono_object_hash (obj);
1978 reflist = (GSList *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1979 for (l = reflist; l; l = l->next) {
1980 ref = (ObjRef *)l->data;
1981 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1982 mono_loader_unlock ();
1987 /* Use a hash table with masked pointers to internalize object references */
1988 ref = (ObjRef *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1989 /* ref might refer to a different object with the same addr which was GCd */
1990 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1991 mono_loader_unlock ();
1996 ref = g_new0 (ObjRef, 1);
1997 ref->id = InterlockedIncrement (&objref_id);
1998 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
2000 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
2002 if (mono_gc_is_moving ()) {
2003 reflist = g_slist_append (reflist, ref);
2004 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
2006 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
2009 mono_loader_unlock ();
2015 true_pred (gpointer key, gpointer value, gpointer user_data)
2021 clear_suspended_objs (void)
2024 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
2029 get_objid (MonoObject *obj)
2034 return get_objref (obj)->id;
2038 * Set OBJ to the object identified by OBJID.
2039 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
2043 get_object_allow_null (int objid, MonoObject **obj)
2053 return ERR_INVALID_OBJECT;
2055 mono_loader_lock ();
2057 ref = (ObjRef *)g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
2060 *obj = mono_gchandle_get_target (ref->handle);
2061 mono_loader_unlock ();
2063 return ERR_INVALID_OBJECT;
2066 mono_loader_unlock ();
2067 return ERR_INVALID_OBJECT;
2072 get_object (int objid, MonoObject **obj)
2074 ErrorCode err = get_object_allow_null (objid, obj);
2076 if (err != ERR_NONE)
2079 return ERR_INVALID_OBJECT;
2084 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
2086 return decode_id (buf, endbuf, limit);
2090 buffer_add_objid (Buffer *buf, MonoObject *o)
2092 buffer_add_id (buf, get_objid (o));
2111 * Represents a runtime structure accessible to the debugger client
2114 /* Unique id used in the wire protocol */
2116 /* Domain of the runtime structure, NULL if the domain was unloaded */
2123 MonoAssembly *assembly;
2124 MonoClassField *field;
2126 MonoProperty *property;
2131 /* Maps runtime structure -> Id */
2132 /* Protected by the dbg lock */
2133 GHashTable *val_to_id [ID_NUM];
2134 /* Classes whose class load event has been sent */
2135 /* Protected by the loader lock */
2136 GHashTable *loaded_classes;
2137 /* Maps MonoClass->GPtrArray of file names */
2138 GHashTable *source_files;
2139 /* Maps source file basename -> GSList of classes */
2140 GHashTable *source_file_to_class;
2141 /* Same with ignore-case */
2142 GHashTable *source_file_to_class_ignorecase;
2146 /* Protected by the dbg lock */
2147 static GPtrArray *ids [ID_NUM];
2154 for (i = 0; i < ID_NUM; ++i)
2155 ids [i] = g_ptr_array_new ();
2163 for (i = 0; i < ID_NUM; ++i) {
2165 for (j = 0; j < ids [i]->len; ++j)
2166 g_free (g_ptr_array_index (ids [i], j));
2167 g_ptr_array_free (ids [i], TRUE);
2174 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2176 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2178 GHashTableIter iter;
2179 GPtrArray *file_names;
2184 for (i = 0; i < ID_NUM; ++i)
2185 if (info->val_to_id [i])
2186 g_hash_table_destroy (info->val_to_id [i]);
2187 g_hash_table_destroy (info->loaded_classes);
2189 g_hash_table_iter_init (&iter, info->source_files);
2190 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2191 for (i = 0; i < file_names->len; ++i)
2192 g_free (g_ptr_array_index (file_names, i));
2193 g_ptr_array_free (file_names, TRUE);
2196 g_hash_table_iter_init (&iter, info->source_file_to_class);
2197 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2202 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2203 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2211 domain_jit_info (domain)->agent_info = NULL;
2213 /* Clear ids referencing structures in the domain */
2215 for (i = 0; i < ID_NUM; ++i) {
2217 for (j = 0; j < ids [i]->len; ++j) {
2218 Id *id = (Id *)g_ptr_array_index (ids [i], j);
2219 if (id->domain == domain)
2226 mono_loader_lock ();
2227 g_hash_table_remove (domains, domain);
2228 mono_loader_unlock ();
2231 static AgentDomainInfo*
2232 get_agent_domain_info (MonoDomain *domain)
2234 AgentDomainInfo *info = NULL;
2236 mono_domain_lock (domain);
2238 info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2240 info = g_new0 (AgentDomainInfo, 1);
2241 domain_jit_info (domain)->agent_info = info;
2242 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2243 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2244 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2245 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2248 mono_domain_unlock (domain);
2254 get_id (MonoDomain *domain, IdType type, gpointer val)
2257 AgentDomainInfo *info;
2262 info = get_agent_domain_info (domain);
2266 if (info->val_to_id [type] == NULL)
2267 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2269 id = (Id *)g_hash_table_lookup (info->val_to_id [type], val);
2275 id = g_new0 (Id, 1);
2277 id->id = ids [type]->len + 1;
2278 id->domain = domain;
2281 g_hash_table_insert (info->val_to_id [type], val, id);
2282 g_ptr_array_add (ids [type], id);
2289 static inline gpointer
2290 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, ErrorCode *err)
2294 int id = decode_id (buf, endbuf, limit);
2303 // FIXME: error handling
2305 g_assert (id > 0 && id <= ids [type]->len);
2307 res = (Id *)g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2310 if (res->domain == NULL) {
2311 DEBUG_PRINTF (1, "ERR_UNLOADED, id=%d, type=%d.\n", id, type);
2312 *err = ERR_UNLOADED;
2317 *domain = res->domain;
2319 return res->data.val;
2323 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2325 int id = get_id (domain, type, val);
2327 buffer_add_id (buf, id);
2331 static inline MonoClass*
2332 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2336 klass = (MonoClass *)decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2337 if (G_UNLIKELY (log_level >= 2) && klass) {
2340 s = mono_type_full_name (&klass->byval_arg);
2341 DEBUG_PRINTF (2, "[dbg] recv class [%s]\n", s);
2347 static inline MonoAssembly*
2348 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2350 return (MonoAssembly *)decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2353 static inline MonoImage*
2354 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2356 return (MonoImage *)decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2359 static inline MonoMethod*
2360 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2364 m = (MonoMethod *)decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2365 if (G_UNLIKELY (log_level >= 2) && m) {
2368 s = mono_method_full_name (m, TRUE);
2369 DEBUG_PRINTF (2, "[dbg] recv method [%s]\n", s);
2375 static inline MonoClassField*
2376 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2378 return (MonoClassField *)decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2381 static inline MonoDomain*
2382 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2384 return (MonoDomain *)decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2387 static inline MonoProperty*
2388 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2390 return (MonoProperty *)decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2394 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2396 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2397 if (G_UNLIKELY (log_level >= 2) && klass) {
2400 s = mono_type_full_name (&klass->byval_arg);
2401 if (is_debugger_thread ())
2402 DEBUG_PRINTF (2, "[dbg] send class [%s]\n", s);
2404 DEBUG_PRINTF (2, "[%p] send class [%s]\n", (gpointer) (gsize) mono_native_thread_id_get (), s);
2410 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2412 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2413 if (G_UNLIKELY (log_level >= 2) && method) {
2416 s = mono_method_full_name (method, 1);
2417 DEBUG_PRINTF (2, "[dbg] send method [%s]\n", s);
2423 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2427 id = buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2428 if (G_UNLIKELY (log_level >= 2) && assembly)
2429 DEBUG_PRINTF (2, "[dbg] send assembly [%s][%s][%d]\n", assembly->aname.name, domain->friendly_name, id);
2433 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2435 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2439 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2441 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2445 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2447 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2451 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2453 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2456 static void invoke_method (void);
2463 * save_thread_context:
2465 * Set CTX as the current threads context which is used for computing stack traces.
2466 * This function is signal-safe.
2469 save_thread_context (MonoContext *ctx)
2471 DebuggerTlsData *tls;
2473 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2477 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2479 mono_thread_state_init_from_current (&tls->context);
2482 /* Number of threads suspended */
2484 * If this is equal to the size of thread_to_tls, the runtime is considered
2487 static gint32 threads_suspend_count;
2489 static MonoCoopMutex suspend_mutex;
2491 /* Cond variable used to wait for suspend_count becoming 0 */
2492 static MonoCoopCond suspend_cond;
2494 /* Semaphore used to wait for a thread becoming suspended */
2495 static MonoCoopSem suspend_sem;
2500 mono_coop_mutex_init (&suspend_mutex);
2501 mono_coop_cond_init (&suspend_cond);
2502 mono_coop_sem_init (&suspend_sem, 0);
2507 StackFrameInfo last_frame;
2508 gboolean last_frame_set;
2512 } GetLastFrameUserData;
2515 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2517 GetLastFrameUserData *data = (GetLastFrameUserData *)user_data;
2519 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE || info->type == FRAME_TYPE_TRAMPOLINE)
2522 if (!data->last_frame_set) {
2523 /* Store the last frame */
2524 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2525 data->last_frame_set = TRUE;
2528 /* Store the context/lmf for the frame above the last frame */
2529 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2530 data->lmf = info->lmf;
2531 data->domain = info->domain;
2537 copy_unwind_state_from_frame_data (MonoThreadUnwindState *to, GetLastFrameUserData *data, gpointer jit_tls)
2539 memcpy (&to->ctx, &data->ctx, sizeof (MonoContext));
2541 to->unwind_data [MONO_UNWIND_DATA_DOMAIN] = data->domain;
2542 to->unwind_data [MONO_UNWIND_DATA_LMF] = data->lmf;
2543 to->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = jit_tls;
2550 * Process interruption of a thread. This should be signal safe.
2552 * This always runs in the debugger thread.
2555 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, MonoJitInfo *ji)
2558 MonoNativeThreadId tid;
2562 ip = MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx);
2563 tid = mono_thread_info_get_tid (info);
2565 // FIXME: Races when the thread leaves managed code before hitting a single step
2568 if (ji && !ji->is_trampoline) {
2569 /* Running managed code, will be suspended by the single step code */
2570 DEBUG_PRINTF (1, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip);
2573 * Running native code, will be suspended when it returns to/enters
2574 * managed code. Treat it as already suspended.
2575 * This might interrupt the code in process_single_step_inner (), we use the
2576 * tls->suspending flag to avoid races when that happens.
2578 if (!tls->suspended && !tls->suspending) {
2579 GetLastFrameUserData data;
2581 // FIXME: printf is not signal safe, but this is only used during
2582 // debugger debugging
2584 DEBUG_PRINTF (1, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip);
2585 //save_thread_context (&ctx);
2588 /* Already terminated */
2592 * We are in a difficult position: we want to be able to provide stack
2593 * traces for this thread, but we can't use the current ctx+lmf, since
2594 * the thread is still running, so it might return to managed code,
2595 * making these invalid.
2596 * So we start a stack walk and save the first frame, along with the
2597 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2598 * suspended when it returns to managed code, so the parent's ctx should
2601 data.last_frame_set = FALSE;
2602 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, mono_thread_info_get_suspend_state (info), MONO_UNWIND_SIGNAL_SAFE, &data);
2603 if (data.last_frame_set) {
2604 gpointer jit_tls = ((MonoThreadInfo*)tls->thread->thread_info)->jit_data;
2606 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2608 copy_unwind_state_from_frame_data (&tls->async_state, &data, jit_tls);
2609 copy_unwind_state_from_frame_data (&tls->context, &data, jit_tls);
2611 tls->async_state.valid = FALSE;
2614 mono_memory_barrier ();
2616 tls->suspended = TRUE;
2617 mono_coop_sem_post (&suspend_sem);
2623 * reset_native_thread_suspend_state:
2625 * Reset the suspended flag and state on native threads
2628 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2630 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2632 if (!tls->really_suspended && tls->suspended) {
2633 tls->suspended = FALSE;
2635 * The thread might still be running if it was executing native code, so the state won't be invalided by
2636 * suspend_current ().
2638 tls->context.valid = FALSE;
2639 tls->async_state.valid = FALSE;
2640 invalidate_frames (tls);
2645 DebuggerTlsData *tls;
2646 gboolean valid_info;
2649 static SuspendThreadResult
2650 debugger_interrupt_critical (MonoThreadInfo *info, gpointer user_data)
2652 InterruptData *data = (InterruptData *)user_data;
2655 data->valid_info = TRUE;
2656 ji = mono_jit_info_table_find_internal (
2657 (MonoDomain *)mono_thread_info_get_suspend_state (info)->unwind_data [MONO_UNWIND_DATA_DOMAIN],
2658 (char *)MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx),
2662 /* This is signal safe */
2663 thread_interrupt (data->tls, info, ji);
2664 return MonoResumeThread;
2670 * Notify a thread that it needs to suspend.
2673 notify_thread (gpointer key, gpointer value, gpointer user_data)
2675 MonoInternalThread *thread = (MonoInternalThread *)key;
2676 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2677 MonoNativeThreadId tid = MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid);
2679 if (mono_native_thread_id_equals (mono_native_thread_id_get (), tid) || tls->terminated)
2682 DEBUG_PRINTF (1, "[%p] Interrupting %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2684 /* This is _not_ equivalent to mono_thread_internal_abort () */
2685 InterruptData interrupt_data = { 0 };
2686 interrupt_data.tls = tls;
2688 mono_thread_info_safe_suspend_and_run ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE, debugger_interrupt_critical, &interrupt_data);
2689 if (!interrupt_data.valid_info) {
2690 DEBUG_PRINTF (1, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2692 * Attached thread which died without detaching.
2694 tls->terminated = TRUE;
2699 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2701 guint8 *ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
2705 if (mono_loader_lock_is_owned_by_self ()) {
2707 * Shortcut for the check in suspend_current (). This speeds up processing
2708 * when executing long running code inside the loader lock, i.e. assembly load
2714 if (is_debugger_thread ())
2717 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2718 if (suspend_count - tls->resume_count > 0)
2719 tls->suspending = TRUE;
2721 DEBUG_PRINTF (1, "[%p] Received single step event for suspending.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2723 if (suspend_count - tls->resume_count == 0) {
2725 * We are executing a single threaded invoke but the single step for
2726 * suspending is still active.
2727 * FIXME: This slows down single threaded invokes.
2729 DEBUG_PRINTF (1, "[%p] Ignored during single threaded invoke.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2733 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2735 /* Can't suspend in these methods */
2736 method = jinfo_get_method (ji);
2737 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2740 save_thread_context (ctx);
2748 * Increase the suspend count of the VM. While the suspend count is greater
2749 * than 0, runtime threads are suspended at certain points during execution.
2754 mono_loader_lock ();
2756 mono_coop_mutex_lock (&suspend_mutex);
2760 DEBUG_PRINTF (1, "[%p] Suspending vm...\n", (gpointer) (gsize) mono_native_thread_id_get ());
2762 if (suspend_count == 1) {
2763 // FIXME: Is it safe to call this inside the lock ?
2764 start_single_stepping ();
2765 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2768 mono_coop_mutex_unlock (&suspend_mutex);
2770 if (suspend_count == 1)
2772 * Suspend creation of new threadpool threads, since they cannot run
2774 mono_threadpool_ms_suspend ();
2776 mono_loader_unlock ();
2782 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2790 g_assert (is_debugger_thread ());
2792 mono_loader_lock ();
2794 mono_coop_mutex_lock (&suspend_mutex);
2796 g_assert (suspend_count > 0);
2799 DEBUG_PRINTF (1, "[%p] Resuming vm, suspend count=%d...\n", (gpointer) (gsize) mono_native_thread_id_get (), suspend_count);
2801 if (suspend_count == 0) {
2802 // FIXME: Is it safe to call this inside the lock ?
2803 stop_single_stepping ();
2804 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2807 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2808 err = mono_coop_cond_broadcast (&suspend_cond);
2809 g_assert (err == 0);
2811 mono_coop_mutex_unlock (&suspend_mutex);
2812 //g_assert (err == 0);
2814 if (suspend_count == 0)
2815 mono_threadpool_ms_resume ();
2817 mono_loader_unlock ();
2823 * Resume just one thread.
2826 resume_thread (MonoInternalThread *thread)
2829 DebuggerTlsData *tls;
2831 g_assert (is_debugger_thread ());
2833 mono_loader_lock ();
2835 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
2838 mono_coop_mutex_lock (&suspend_mutex);
2840 g_assert (suspend_count > 0);
2842 DEBUG_PRINTF (1, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid);
2844 tls->resume_count += suspend_count;
2847 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2848 * but only the one whose resume_count field is > 0 will be resumed.
2850 err = mono_coop_cond_broadcast (&suspend_cond);
2851 g_assert (err == 0);
2853 mono_coop_mutex_unlock (&suspend_mutex);
2854 //g_assert (err == 0);
2856 mono_loader_unlock ();
2860 free_frames (StackFrame **frames, int nframes)
2864 for (i = 0; i < nframes; ++i) {
2865 if (frames [i]->jit)
2866 mono_debug_free_method_jit_info (frames [i]->jit);
2867 g_free (frames [i]);
2873 invalidate_frames (DebuggerTlsData *tls)
2876 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2879 free_frames (tls->frames, tls->frame_count);
2880 tls->frame_count = 0;
2883 free_frames (tls->restore_frames, tls->restore_frame_count);
2884 tls->restore_frame_count = 0;
2885 tls->restore_frames = NULL;
2891 * Suspend the current thread until the runtime is resumed. If the thread has a
2892 * pending invoke, then the invoke is executed before this function returns.
2895 suspend_current (void)
2897 DebuggerTlsData *tls;
2900 g_assert (!is_debugger_thread ());
2902 if (mono_loader_lock_is_owned_by_self ()) {
2904 * If we own the loader mutex, can't suspend until we release it, since the
2905 * whole runtime can deadlock otherwise.
2910 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2913 mono_coop_mutex_lock (&suspend_mutex);
2915 tls->suspending = FALSE;
2916 tls->really_suspended = TRUE;
2918 if (!tls->suspended) {
2919 tls->suspended = TRUE;
2920 mono_coop_sem_post (&suspend_sem);
2923 DEBUG_PRINTF (1, "[%p] Suspended.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2925 while (suspend_count - tls->resume_count > 0) {
2926 err = mono_coop_cond_wait (&suspend_cond, &suspend_mutex);
2927 g_assert (err == 0);
2930 tls->suspended = FALSE;
2931 tls->really_suspended = FALSE;
2933 threads_suspend_count --;
2935 mono_coop_mutex_unlock (&suspend_mutex);
2937 DEBUG_PRINTF (1, "[%p] Resumed.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2939 if (tls->pending_invoke) {
2940 /* Save the original context */
2941 tls->pending_invoke->has_ctx = TRUE;
2942 tls->pending_invoke->ctx = tls->context.ctx;
2947 /* The frame info becomes invalid after a resume */
2948 tls->context.valid = FALSE;
2949 tls->async_state.valid = FALSE;
2950 invalidate_frames (tls);
2954 count_thread (gpointer key, gpointer value, gpointer user_data)
2956 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2958 if (!tls->suspended && !tls->terminated)
2959 *(int*)user_data = *(int*)user_data + 1;
2963 count_threads_to_wait_for (void)
2967 mono_loader_lock ();
2968 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2969 mono_loader_unlock ();
2977 * Wait until the runtime is completely suspended.
2980 wait_for_suspend (void)
2982 int nthreads, nwait, err;
2983 gboolean waited = FALSE;
2985 // FIXME: Threads starting/stopping ?
2986 mono_loader_lock ();
2987 nthreads = mono_g_hash_table_size (thread_to_tls);
2988 mono_loader_unlock ();
2991 nwait = count_threads_to_wait_for ();
2993 DEBUG_PRINTF (1, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads);
2994 err = mono_coop_sem_wait (&suspend_sem, MONO_SEM_FLAGS_NONE);
2995 g_assert (err == 0);
3003 DEBUG_PRINTF (1, "%d threads suspended.\n", nthreads);
3009 * Return whenever the runtime is suspended.
3014 return count_threads_to_wait_for () == 0;
3018 no_seq_points_found (MonoMethod *method, int offset)
3021 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3023 printf ("Unable to find seq points for method '%s', offset 0x%x.\n", mono_method_full_name (method, TRUE), offset);
3027 DebuggerTlsData *tls;
3029 } ComputeFramesUserData;
3032 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3034 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3036 MonoMethod *method, *actual_method, *api_method;
3040 if (info->type != FRAME_TYPE_MANAGED) {
3041 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3042 /* Mark the last frame as an invoke frame */
3044 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3050 method = jinfo_get_method (info->ji);
3052 method = info->method;
3053 actual_method = info->actual_method;
3054 api_method = method;
3059 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3062 if (info->il_offset == -1) {
3063 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3064 if (ud->frames == NULL) {
3065 if (mono_find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL, &sp))
3066 info->il_offset = sp.il_offset;
3068 if (info->il_offset == -1)
3069 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3072 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);
3074 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3075 if (!CHECK_PROTOCOL_VERSION (2, 17))
3076 /* Older clients can't handle this flag */
3078 api_method = mono_marshal_method_from_wrapper (method);
3081 actual_method = api_method;
3082 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3085 frame = g_new0 (StackFrame, 1);
3086 frame->method = method;
3087 frame->actual_method = actual_method;
3088 frame->api_method = api_method;
3089 frame->il_offset = info->il_offset;
3090 frame->native_offset = info->native_offset;
3091 frame->flags = flags;
3092 frame->ji = info->ji;
3093 if (info->reg_locations)
3094 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3097 frame->has_ctx = TRUE;
3099 frame->domain = info->domain;
3101 ud->frames = g_slist_append (ud->frames, frame);
3107 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3109 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3112 * 'tls->filter_ctx' is the location of the throw site.
3114 * mono_walk_stack() will never actually hit the throw site, but unwind
3115 * directly from the filter to the call site; we abort stack unwinding here
3116 * once this happens and resume from the throw site.
3119 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3122 return process_frame (info, ctx, user_data);
3126 * Return a malloc-ed list of StackFrame structures.
3129 compute_frame_info_from (MonoInternalThread *thread, DebuggerTlsData *tls, MonoThreadUnwindState *state, int *out_nframes)
3131 ComputeFramesUserData user_data;
3132 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3137 user_data.tls = tls;
3138 user_data.frames = NULL;
3140 mono_walk_stack_with_state (process_frame, state, opts, &user_data);
3142 nframes = g_slist_length (user_data.frames);
3143 res = g_new0 (StackFrame*, nframes);
3144 l = user_data.frames;
3145 for (i = 0; i < nframes; ++i) {
3146 res [i] = (StackFrame *)l->data;
3149 *out_nframes = nframes;
3155 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3157 ComputeFramesUserData user_data;
3159 int i, findex, new_frame_count;
3160 StackFrame **new_frames, *f;
3161 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3163 // FIXME: Locking on tls
3164 if (tls->frames && tls->frames_up_to_date)
3167 DEBUG_PRINTF (1, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid);
3169 user_data.tls = tls;
3170 user_data.frames = NULL;
3171 if (tls->terminated) {
3172 tls->frame_count = 0;
3174 } if (!tls->really_suspended && tls->async_state.valid) {
3175 /* Have to use the state saved by the signal handler */
3176 process_frame (&tls->async_last_frame, NULL, &user_data);
3177 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3178 } else if (tls->filter_state.valid) {
3180 * We are inside an exception filter.
3182 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3184 if (tls->context.valid)
3185 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3187 * After that, we resume unwinding from the location where the exception has been thrown.
3189 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3190 } else if (tls->context.valid) {
3191 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3194 tls->frame_count = 0;
3198 new_frame_count = g_slist_length (user_data.frames);
3199 new_frames = g_new0 (StackFrame*, new_frame_count);
3201 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3202 f = (StackFrame *)tmp->data;
3205 * Reuse the id for already existing stack frames, so invokes don't invalidate
3206 * the still valid stack frames.
3208 for (i = 0; i < tls->frame_count; ++i) {
3209 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3210 f->id = tls->frames [i]->id;
3215 if (i >= tls->frame_count)
3216 f->id = InterlockedIncrement (&frame_id);
3218 new_frames [findex ++] = f;
3221 g_slist_free (user_data.frames);
3223 invalidate_frames (tls);
3225 tls->frames = new_frames;
3226 tls->frame_count = new_frame_count;
3227 tls->frames_up_to_date = TRUE;
3231 * GHFunc to emit an appdomain creation event
3232 * @param key Don't care
3233 * @param value A loaded appdomain
3234 * @param user_data Don't care
3237 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3239 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3240 g_hash_table_foreach (get_agent_domain_info ((MonoDomain *)value)->loaded_classes, emit_type_load, NULL);
3244 * GHFunc to emit a thread start event
3245 * @param key A thread id
3246 * @param value A thread object
3247 * @param user_data Don't care
3250 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3252 if (!mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (GPOINTER_TO_UINT (key)), debugger_thread_id))
3253 process_profiler_event (EVENT_KIND_THREAD_START, value);
3257 * GFunc to emit an assembly load event
3258 * @param value A loaded assembly
3259 * @param user_data Don't care
3262 emit_assembly_load (gpointer value, gpointer user_data)
3264 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3268 * GFunc to emit a type load event
3269 * @param value A loaded type
3270 * @param user_data Don't care
3273 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3275 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3279 strdup_tolower (char *s)
3284 for (p = s2; *p; ++p)
3290 * Same as g_path_get_basename () but handles windows paths as well,
3291 * which can occur in .mdb files created by pdb2mdb.
3294 dbg_path_get_basename (const char *filename)
3298 if (!filename || strchr (filename, '/') || !strchr (filename, '\\'))
3299 return g_path_get_basename (filename);
3303 /* No separator -> filename */
3304 r = strrchr (filename, '\\');
3306 return g_strdup (filename);
3308 /* Trailing slash, remove component */
3310 char *copy = g_strdup (filename);
3311 copy [r-filename] = 0;
3312 r = strrchr (copy, '\\');
3316 return g_strdup ("/");
3318 r = g_strdup (&r[1]);
3323 return g_strdup (&r[1]);
3327 init_jit_info_dbg_attrs (MonoJitInfo *ji)
3329 static MonoClass *hidden_klass, *step_through_klass, *non_user_klass;
3331 MonoCustomAttrInfo *ainfo;
3333 if (ji->dbg_attrs_inited)
3337 hidden_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3339 if (!step_through_klass)
3340 step_through_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3342 if (!non_user_klass)
3343 non_user_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute");
3345 ainfo = mono_custom_attrs_from_method_checked (jinfo_get_method (ji), &error);
3346 mono_error_cleanup (&error); /* FIXME don't swallow the error? */
3348 if (mono_custom_attrs_has_attr (ainfo, hidden_klass))
3349 ji->dbg_hidden = TRUE;
3350 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3351 ji->dbg_step_through = TRUE;
3352 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3353 ji->dbg_non_user_code = TRUE;
3354 mono_custom_attrs_free (ainfo);
3357 ainfo = mono_custom_attrs_from_class_checked (jinfo_get_method (ji)->klass, &error);
3358 mono_error_cleanup (&error); /* FIXME don't swallow the error? */
3360 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3361 ji->dbg_step_through = TRUE;
3362 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3363 ji->dbg_non_user_code = TRUE;
3364 mono_custom_attrs_free (ainfo);
3367 mono_memory_barrier ();
3368 ji->dbg_attrs_inited = TRUE;
3376 * create_event_list:
3378 * Return a list of event request ids matching EVENT, starting from REQS, which
3379 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3381 * We return request ids, instead of requests, to simplify threading, since
3382 * requests could be deleted anytime when the loader lock is not held.
3383 * LOCKING: Assumes the loader lock is held.
3386 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3389 GSList *events = NULL;
3391 *suspend_policy = SUSPEND_POLICY_NONE;
3394 reqs = event_requests;
3399 for (i = 0; i < reqs->len; ++i) {
3400 EventRequest *req = (EventRequest *)g_ptr_array_index (reqs, i);
3401 if (req->event_kind == event) {
3402 gboolean filtered = FALSE;
3405 for (j = 0; j < req->nmodifiers; ++j) {
3406 Modifier *mod = &req->modifiers [j];
3408 if (mod->kind == MOD_KIND_COUNT) {
3410 if (mod->data.count > 0) {
3411 if (mod->data.count > 0) {
3413 if (mod->data.count == 0)
3417 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3418 if (mod->data.thread != mono_thread_internal_current ())
3420 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3421 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3423 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3425 if (ei->caught && !mod->caught)
3427 if (!ei->caught && !mod->uncaught)
3429 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3431 gboolean found = FALSE;
3432 MonoAssembly **assemblies = mod->data.assemblies;
3435 for (k = 0; assemblies [k]; ++k)
3436 if (assemblies [k] == jinfo_get_method (ji)->klass->image->assembly)
3441 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3442 gpointer iter = NULL;
3444 MonoDebugSourceInfo *sinfo;
3445 char *source_file, *s;
3446 gboolean found = FALSE;
3448 GPtrArray *source_file_list;
3450 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3451 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3454 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, NULL, NULL, NULL);
3455 for (i = 0; i < source_file_list->len; ++i) {
3456 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
3458 * Do a case-insesitive match by converting the file name to
3461 s = strdup_tolower (sinfo->source_file);
3462 if (g_hash_table_lookup (mod->data.source_files, s))
3465 char *s2 = dbg_path_get_basename (sinfo->source_file);
3466 char *s3 = strdup_tolower (s2);
3468 if (g_hash_table_lookup (mod->data.source_files, s3))
3475 g_ptr_array_free (source_file_list, TRUE);
3480 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3483 s = mono_type_full_name (&ei->klass->byval_arg);
3484 if (!g_hash_table_lookup (mod->data.type_names, s))
3487 } else if (mod->kind == MOD_KIND_STEP) {
3488 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3489 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3490 !strcmp (jinfo_get_method (ji)->name, ".cctor") &&
3491 (jinfo_get_method (ji) != ((SingleStepReq*)req->info)->start_method))
3493 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3494 init_jit_info_dbg_attrs (ji);
3498 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3499 init_jit_info_dbg_attrs (ji);
3500 if (ji->dbg_step_through)
3503 if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3504 init_jit_info_dbg_attrs (ji);
3505 if (ji->dbg_non_user_code)
3512 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3513 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3518 /* Send a VM START/DEATH event by default */
3519 if (event == EVENT_KIND_VM_START)
3520 events = g_slist_append (events, GINT_TO_POINTER (0));
3521 if (event == EVENT_KIND_VM_DEATH)
3522 events = g_slist_append (events, GINT_TO_POINTER (0));
3527 static G_GNUC_UNUSED const char*
3528 event_to_string (EventKind event)
3531 case EVENT_KIND_VM_START: return "VM_START";
3532 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3533 case EVENT_KIND_THREAD_START: return "THREAD_START";
3534 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3535 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3536 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3537 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3538 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3539 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3540 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3541 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3542 case EVENT_KIND_STEP: return "STEP";
3543 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3544 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3545 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3546 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3547 case EVENT_KIND_USER_LOG: return "USER_LOG";
3549 g_assert_not_reached ();
3557 * Send an event to the client, suspending the vm if needed.
3558 * LOCKING: Since this can suspend the calling thread, no locks should be held
3560 * The EVENTS list is freed by this function.
3563 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3567 MonoDomain *domain = mono_domain_get ();
3568 MonoThread *thread = NULL;
3569 MonoObject *keepalive_obj = NULL;
3570 gboolean send_success = FALSE;
3575 DEBUG_PRINTF (2, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event));
3579 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3580 // FIXME: We miss those events
3581 DEBUG_PRINTF (2, "VM start event not sent yet: dropping %s\n", event_to_string (event));
3585 if (vm_death_event_sent) {
3586 DEBUG_PRINTF (2, "VM death event has been sent: dropping %s\n", event_to_string (event));
3590 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3591 DEBUG_PRINTF (2, "Mono runtime is shutting down: dropping %s\n", event_to_string (event));
3596 DEBUG_PRINTF (2, "Debugger client is not connected: dropping %s\n", event_to_string (event));
3600 if (event == EVENT_KIND_KEEPALIVE)
3601 suspend_policy = SUSPEND_POLICY_NONE;
3606 if (agent_config.defer) {
3607 /* Make sure the thread id is always set when doing deferred debugging */
3608 if (is_debugger_thread ()) {
3609 /* Don't suspend on events from the debugger thread */
3610 suspend_policy = SUSPEND_POLICY_NONE;
3611 thread = mono_thread_get_main ();
3613 else thread = mono_thread_current ();
3615 if (is_debugger_thread () && event != EVENT_KIND_VM_DEATH)
3616 // FIXME: Send these with a NULL thread, don't suspend the current thread
3621 nevents = g_slist_length (events);
3622 buffer_init (&buf, 128);
3623 buffer_add_byte (&buf, suspend_policy);
3624 buffer_add_int (&buf, nevents);
3626 for (l = events; l; l = l->next) {
3627 buffer_add_byte (&buf, event); // event kind
3628 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3632 if (event == EVENT_KIND_VM_DEATH) {
3636 thread = mono_thread_current ();
3638 if (event == EVENT_KIND_VM_START && arg != NULL)
3639 thread = (MonoThread *)arg;
3642 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3645 case EVENT_KIND_THREAD_START:
3646 case EVENT_KIND_THREAD_DEATH:
3648 case EVENT_KIND_APPDOMAIN_CREATE:
3649 case EVENT_KIND_APPDOMAIN_UNLOAD:
3650 buffer_add_domainid (&buf, (MonoDomain *)arg);
3652 case EVENT_KIND_METHOD_ENTRY:
3653 case EVENT_KIND_METHOD_EXIT:
3654 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3656 case EVENT_KIND_ASSEMBLY_LOAD:
3657 buffer_add_assemblyid (&buf, domain, (MonoAssembly *)arg);
3659 case EVENT_KIND_ASSEMBLY_UNLOAD: {
3660 DebuggerTlsData *tls;
3662 /* The domain the assembly belonged to is not equal to the current domain */
3663 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3665 g_assert (tls->domain_unloading);
3667 buffer_add_assemblyid (&buf, tls->domain_unloading, (MonoAssembly *)arg);
3670 case EVENT_KIND_TYPE_LOAD:
3671 buffer_add_typeid (&buf, domain, (MonoClass *)arg);
3673 case EVENT_KIND_BREAKPOINT:
3674 case EVENT_KIND_STEP:
3675 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3676 buffer_add_long (&buf, il_offset);
3678 case EVENT_KIND_VM_START:
3679 buffer_add_domainid (&buf, mono_get_root_domain ());
3681 case EVENT_KIND_VM_DEATH:
3682 if (CHECK_PROTOCOL_VERSION (2, 27))
3683 buffer_add_int (&buf, mono_environment_exitcode_get ());
3685 case EVENT_KIND_EXCEPTION: {
3686 EventInfo *ei = (EventInfo *)arg;
3687 buffer_add_objid (&buf, ei->exc);
3689 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3690 * later after the suspension. (#12494).
3692 keepalive_obj = ei->exc;
3695 case EVENT_KIND_USER_BREAK:
3697 case EVENT_KIND_USER_LOG: {
3698 EventInfo *ei = (EventInfo *)arg;
3699 buffer_add_int (&buf, ei->level);
3700 buffer_add_string (&buf, ei->category ? ei->category : "");
3701 buffer_add_string (&buf, ei->message ? ei->message : "");
3704 case EVENT_KIND_KEEPALIVE:
3705 suspend_policy = SUSPEND_POLICY_NONE;
3708 g_assert_not_reached ();
3712 if (event == EVENT_KIND_VM_START) {
3713 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3714 if (!agent_config.defer)
3715 start_debugger_thread ();
3718 if (event == EVENT_KIND_VM_DEATH) {
3719 vm_death_event_sent = TRUE;
3720 suspend_policy = SUSPEND_POLICY_NONE;
3723 if (mono_runtime_is_shutting_down ())
3724 suspend_policy = SUSPEND_POLICY_NONE;
3726 if (suspend_policy != SUSPEND_POLICY_NONE) {
3728 * Save the thread context and start suspending before sending the packet,
3729 * since we could be receiving the resume request before send_packet ()
3732 save_thread_context (ctx);
3736 /* This will keep this object alive */
3737 get_objref (keepalive_obj);
3740 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3744 g_slist_free (events);
3747 if (!send_success) {
3748 DEBUG_PRINTF (2, "Sending command %s failed.\n", event_to_string (event));
3752 if (event == EVENT_KIND_VM_START) {
3753 vm_start_event_sent = TRUE;
3756 DEBUG_PRINTF (1, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer) (gsize) mono_native_thread_id_get (), nevents, event_to_string (event), ecount, suspend_policy);
3758 switch (suspend_policy) {
3759 case SUSPEND_POLICY_NONE:
3761 case SUSPEND_POLICY_ALL:
3764 case SUSPEND_POLICY_EVENT_THREAD:
3768 g_assert_not_reached ();
3773 process_profiler_event (EventKind event, gpointer arg)
3777 EventInfo ei, *ei_arg = NULL;
3779 if (event == EVENT_KIND_TYPE_LOAD) {
3780 ei.klass = (MonoClass *)arg;
3784 mono_loader_lock ();
3785 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3786 mono_loader_unlock ();
3788 process_event (event, arg, 0, NULL, events, suspend_policy);
3792 runtime_initialized (MonoProfiler *prof)
3794 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3795 if (agent_config.defer)
3796 start_debugger_thread ();
3800 runtime_shutdown (MonoProfiler *prof)
3802 process_profiler_event (EVENT_KIND_VM_DEATH, NULL);
3804 mono_debugger_agent_cleanup ();
3808 thread_startup (MonoProfiler *prof, uintptr_t tid)
3810 MonoInternalThread *thread = mono_thread_internal_current ();
3811 MonoInternalThread *old_thread;
3812 DebuggerTlsData *tls;
3814 if (mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (tid), debugger_thread_id))
3817 g_assert (mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (tid), MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid)));
3819 mono_loader_lock ();
3820 old_thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3821 mono_loader_unlock ();
3823 if (thread == old_thread) {
3825 * For some reason, thread_startup () might be called for the same thread
3826 * multiple times (attach ?).
3828 DEBUG_PRINTF (1, "[%p] thread_start () called multiple times for %p, ignored.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3832 * thread_end () might not be called for some threads, and the tid could
3835 DEBUG_PRINTF (1, "[%p] Removing stale data for tid %p.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3836 mono_loader_lock ();
3837 mono_g_hash_table_remove (thread_to_tls, old_thread);
3838 mono_g_hash_table_remove (tid_to_thread, GUINT_TO_POINTER (tid));
3839 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3840 mono_loader_unlock ();
3844 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3846 // FIXME: Free this somewhere
3847 tls = g_new0 (DebuggerTlsData, 1);
3848 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread, MONO_ROOT_SOURCE_DEBUGGER, "debugger thread reference");
3849 tls->thread = thread;
3850 mono_native_tls_set_value (debugger_tls_id, tls);
3852 DEBUG_PRINTF (1, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3854 mono_loader_lock ();
3855 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3856 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3857 mono_g_hash_table_insert (tid_to_thread_obj, GUINT_TO_POINTER (tid), mono_thread_current ());
3858 mono_loader_unlock ();
3860 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3863 * suspend_vm () could have missed this thread, so wait for a resume.
3869 thread_end (MonoProfiler *prof, uintptr_t tid)
3871 MonoInternalThread *thread;
3872 DebuggerTlsData *tls = NULL;
3874 mono_loader_lock ();
3875 thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3877 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3878 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
3880 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3881 tls->terminated = TRUE;
3882 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3883 MONO_GC_UNREGISTER_ROOT (tls->thread);
3887 mono_loader_unlock ();
3889 /* We might be called for threads started before we registered the start callback */
3891 DEBUG_PRINTF (1, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3893 if (mono_native_thread_id_equals (mono_native_thread_id_get (), MONO_UINT_TO_NATIVE_THREAD_ID (tid))
3894 && !mono_native_tls_get_value (debugger_tls_id)
3897 * This can happen on darwin since we deregister threads using pthread dtors.
3898 * process_profiler_event () and the code it calls cannot handle a null TLS value.
3903 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3908 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3910 mono_loader_lock ();
3911 g_hash_table_insert (domains, domain, domain);
3912 mono_loader_unlock ();
3914 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3918 appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain)
3920 DebuggerTlsData *tls;
3922 /* This might be called during shutdown on the debugger thread from the CMD_VM_EXIT code */
3923 if (is_debugger_thread ())
3927 * Remember the currently unloading appdomain as it is needed to generate
3928 * proper ids for unloading assemblies.
3930 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3932 tls->domain_unloading = domain;
3936 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3938 DebuggerTlsData *tls;
3940 if (is_debugger_thread ())
3943 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3945 tls->domain_unloading = NULL;
3947 clear_breakpoints_for_domain (domain);
3949 mono_loader_lock ();
3950 /* Invalidate each thread's frame stack */
3951 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3952 mono_loader_unlock ();
3954 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3958 * invalidate_each_thread:
3960 * A GHFunc to invalidate frames.
3961 * value must be a DebuggerTlsData*
3964 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3966 invalidate_frames ((DebuggerTlsData *)value);
3970 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3972 /* Sent later in jit_end () */
3974 g_ptr_array_add (pending_assembly_loads, assembly);
3979 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3981 if (is_debugger_thread ())
3984 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3986 clear_event_requests_for_assembly (assembly);
3987 clear_types_for_assembly (assembly);
3991 send_type_load (MonoClass *klass)
3993 gboolean type_load = FALSE;
3994 MonoDomain *domain = mono_domain_get ();
3995 AgentDomainInfo *info = NULL;
3997 info = get_agent_domain_info (domain);
3999 mono_loader_lock ();
4001 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
4003 g_hash_table_insert (info->loaded_classes, klass, klass);
4006 mono_loader_unlock ();
4009 emit_type_load (klass, klass, NULL);
4013 * Emit load events for all types currently loaded in the domain.
4014 * Takes the loader and domain locks.
4015 * user_data is unused.
4018 send_types_for_domain (MonoDomain *domain, void *user_data)
4020 AgentDomainInfo *info = NULL;
4022 info = get_agent_domain_info (domain);
4025 mono_loader_lock ();
4026 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4027 mono_loader_unlock ();
4031 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
4034 * We emit type load events when the first method of the type is JITted,
4035 * since the class load profiler callbacks might be called with the
4036 * loader lock held. They could also occur in the debugger thread.
4037 * Same for assembly load events.
4040 MonoAssembly *assembly = NULL;
4042 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4044 if (pending_assembly_loads->len > 0) {
4045 assembly = (MonoAssembly *)g_ptr_array_index (pending_assembly_loads, 0);
4046 g_ptr_array_remove_index (pending_assembly_loads, 0);
4051 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4057 send_type_load (method->klass);
4060 add_pending_breakpoints (method, jinfo);
4064 * BREAKPOINTS/SINGLE STEPPING
4068 * Contains information about an inserted breakpoint.
4071 long il_offset, native_offset;
4075 } BreakpointInstance;
4078 * Contains generic information about a breakpoint.
4082 * The method where the breakpoint is placed. Can be NULL in which case it
4083 * is inserted into every method. This is used to implement method entry/
4084 * exit events. Can be a generic method definition, in which case the
4085 * breakpoint is inserted into every instance.
4091 * A list of BreakpointInstance structures describing where the breakpoint
4092 * was inserted. There could be more than one because of
4093 * generics/appdomains/method entry/exit.
4095 GPtrArray *children;
4098 /* List of breakpoints */
4099 /* Protected by the loader lock */
4100 static GPtrArray *breakpoints;
4101 /* Maps breakpoint locations to the number of breakpoints at that location */
4102 static GHashTable *bp_locs;
4105 breakpoints_init (void)
4107 breakpoints = g_ptr_array_new ();
4108 bp_locs = g_hash_table_new (NULL, NULL);
4112 * insert_breakpoint:
4114 * Insert the breakpoint described by BP into the method described by
4118 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4121 BreakpointInstance *inst;
4122 SeqPointIterator it;
4123 gboolean it_has_sp = FALSE;
4126 mono_error_init (error);
4128 mono_seq_point_iterator_init (&it, seq_points);
4129 while (mono_seq_point_iterator_next (&it)) {
4130 if (it.seq_point.il_offset == bp->il_offset) {
4138 * The set of IL offsets with seq points doesn't completely match the
4139 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4141 mono_seq_point_iterator_init (&it, seq_points);
4142 while (mono_seq_point_iterator_next (&it)) {
4143 if (it.seq_point.il_offset != METHOD_ENTRY_IL_OFFSET &&
4144 it.seq_point.il_offset != METHOD_EXIT_IL_OFFSET &&
4145 it.seq_point.il_offset + 1 == bp->il_offset) {
4153 char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d", mono_method_full_name (jinfo_get_method (ji), TRUE), bp->il_offset);
4155 mono_seq_point_iterator_init (&it, seq_points);
4156 while (mono_seq_point_iterator_next (&it))
4157 DEBUG_PRINTF (1, "%d\n", it.seq_point.il_offset);
4160 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4161 g_warning ("%s", s);
4165 g_warning ("%s", s);
4171 inst = g_new0 (BreakpointInstance, 1);
4172 inst->il_offset = it.seq_point.il_offset;
4173 inst->native_offset = it.seq_point.native_offset;
4174 inst->ip = (guint8*)ji->code_start + it.seq_point.native_offset;
4176 inst->domain = domain;
4178 mono_loader_lock ();
4180 g_ptr_array_add (bp->children, inst);
4182 mono_loader_unlock ();
4185 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4186 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4189 if (it.seq_point.native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4190 DEBUG_PRINTF (1, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset);
4191 } else if (count == 0) {
4192 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4193 mono_arch_set_breakpoint (ji, inst->ip);
4199 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);
4203 remove_breakpoint (BreakpointInstance *inst)
4205 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4207 MonoJitInfo *ji = inst->ji;
4208 guint8 *ip = inst->ip;
4211 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4212 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4215 g_assert (count > 0);
4217 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4218 mono_arch_clear_breakpoint (ji, ip);
4219 DEBUG_PRINTF (1, "[dbg] Clear breakpoint at %s [%p].\n", mono_method_full_name (jinfo_get_method (ji), TRUE), ip);
4227 * This doesn't take any locks.
4229 static inline gboolean
4230 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4236 if (method == bp->method)
4238 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4241 if (bp->method->is_inflated && method->is_inflated) {
4242 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4243 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4245 /* Open generic methods should match closed generic methods of the same class */
4246 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4247 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4248 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4250 /* FIXME: Handle !mvar */
4251 if (t1->type != MONO_TYPE_MVAR)
4262 * add_pending_breakpoints:
4264 * Insert pending breakpoints into the newly JITted method METHOD.
4267 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4270 MonoSeqPointInfo *seq_points;
4272 MonoMethod *jmethod;
4277 domain = mono_domain_get ();
4279 mono_loader_lock ();
4281 for (i = 0; i < breakpoints->len; ++i) {
4282 MonoBreakpoint *bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4283 gboolean found = FALSE;
4285 if (!bp_matches_method (bp, method))
4288 for (j = 0; j < bp->children->len; ++j) {
4289 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4296 MonoMethod *declaring = NULL;
4298 jmethod = jinfo_get_method (ji);
4299 if (jmethod->is_inflated)
4300 declaring = mono_method_get_declaring_generic_method (jmethod);
4302 mono_domain_lock (domain);
4303 seq_points = (MonoSeqPointInfo *)g_hash_table_lookup (domain_jit_info (domain)->seq_points, jmethod);
4304 if (!seq_points && declaring)
4305 seq_points = (MonoSeqPointInfo *)g_hash_table_lookup (domain_jit_info (domain)->seq_points, declaring);
4306 mono_domain_unlock (domain);
4308 /* Could be AOT code */
4310 g_assert (seq_points);
4312 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4316 mono_loader_unlock ();
4320 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4326 mono_error_init (error);
4328 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4332 /* Might be AOTed code */
4333 code = mono_aot_get_method_checked (domain, method, &oerror);
4335 mono_error_assert_ok (&oerror);
4336 ji = mono_jit_info_table_find (domain, (char *)code);
4341 insert_breakpoint (seq_points, domain, ji, bp, error);
4345 clear_breakpoint (MonoBreakpoint *bp);
4350 * Set a breakpoint at IL_OFFSET in METHOD.
4351 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4352 * METHOD can also be a generic method definition, in which case a breakpoint
4353 * is placed in all instances of the method.
4354 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4357 static MonoBreakpoint*
4358 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4361 GHashTableIter iter, iter2;
4364 MonoSeqPointInfo *seq_points;
4366 GPtrArray *method_domains;
4367 GPtrArray *method_seq_points;
4371 mono_error_init (error);
4374 // - suspend/resume the vm to prevent code patching problems
4375 // - multiple breakpoints on the same location
4376 // - dynamic methods
4379 bp = g_new0 (MonoBreakpoint, 1);
4380 bp->method = method;
4381 bp->il_offset = il_offset;
4383 bp->children = g_ptr_array_new ();
4385 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);
4387 methods = g_ptr_array_new ();
4388 method_domains = g_ptr_array_new ();
4389 method_seq_points = g_ptr_array_new ();
4391 mono_loader_lock ();
4392 g_hash_table_iter_init (&iter, domains);
4393 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4394 mono_domain_lock (domain);
4395 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4396 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4397 if (bp_matches_method (bp, m)) {
4398 /* Save the info locally to simplify the code inside the domain lock */
4399 g_ptr_array_add (methods, m);
4400 g_ptr_array_add (method_domains, domain);
4401 g_ptr_array_add (method_seq_points, seq_points);
4404 mono_domain_unlock (domain);
4407 for (i = 0; i < methods->len; ++i) {
4408 m = (MonoMethod *)g_ptr_array_index (methods, i);
4409 domain = (MonoDomain *)g_ptr_array_index (method_domains, i);
4410 seq_points = (MonoSeqPointInfo *)g_ptr_array_index (method_seq_points, i);
4411 set_bp_in_method (domain, m, seq_points, bp, error);
4414 g_ptr_array_add (breakpoints, bp);
4415 mono_loader_unlock ();
4417 g_ptr_array_free (methods, TRUE);
4418 g_ptr_array_free (method_domains, TRUE);
4419 g_ptr_array_free (method_seq_points, TRUE);
4421 if (error && !mono_error_ok (error)) {
4422 clear_breakpoint (bp);
4430 clear_breakpoint (MonoBreakpoint *bp)
4434 // FIXME: locking, races
4435 for (i = 0; i < bp->children->len; ++i) {
4436 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, i);
4438 remove_breakpoint (inst);
4443 mono_loader_lock ();
4444 g_ptr_array_remove (breakpoints, bp);
4445 mono_loader_unlock ();
4447 g_ptr_array_free (bp->children, TRUE);
4452 breakpoints_cleanup (void)
4456 mono_loader_lock ();
4458 while (i < event_requests->len) {
4459 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
4461 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4462 clear_breakpoint ((MonoBreakpoint *)req->info);
4463 g_ptr_array_remove_index_fast (event_requests, i);
4470 for (i = 0; i < breakpoints->len; ++i)
4471 g_free (g_ptr_array_index (breakpoints, i));
4473 g_ptr_array_free (breakpoints, TRUE);
4474 g_hash_table_destroy (bp_locs);
4479 mono_loader_unlock ();
4483 * clear_breakpoints_for_domain:
4485 * Clear breakpoint instances which reference DOMAIN.
4488 clear_breakpoints_for_domain (MonoDomain *domain)
4492 /* This could be called after shutdown */
4496 mono_loader_lock ();
4497 for (i = 0; i < breakpoints->len; ++i) {
4498 MonoBreakpoint *bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4501 while (j < bp->children->len) {
4502 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4504 if (inst->domain == domain) {
4505 remove_breakpoint (inst);
4509 g_ptr_array_remove_index_fast (bp->children, j);
4515 mono_loader_unlock ();
4521 * Return FALSE if single stepping needs to continue.
4524 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp, DebuggerTlsData *tls, MonoContext *ctx)
4526 MonoDebugMethodInfo *minfo;
4527 MonoDebugSourceLocation *loc = NULL;
4528 gboolean hit = TRUE;
4531 if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK)) {
4533 * These seq points are inserted by the JIT after calls, step over needs to skip them.
4535 DEBUG_PRINTF (1, "[%p] Seq point at nonempty stack %x while stepping over, continuing single stepping.\n", (gpointer) (gsize) mono_native_thread_id_get (), sp->il_offset);
4539 if (req->depth == STEP_DEPTH_OVER && hit) {
4540 if (!tls->context.valid)
4541 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4542 compute_frame_info (tls->thread, tls);
4543 if (req->nframes && tls->frame_count && tls->frame_count > req->nframes) {
4544 /* Hit the breakpoint in a recursive call */
4545 DEBUG_PRINTF (1, "[%p] Breakpoint at lower frame while stepping over, continuing single stepping.\n", (gpointer) (gsize) mono_native_thread_id_get ());
4550 if (req->depth == STEP_DEPTH_INTO && req->size == STEP_SIZE_MIN && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) && ss_req->start_method){
4551 method = jinfo_get_method (ji);
4552 if (!tls->context.valid)
4553 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4554 compute_frame_info (tls->thread, tls);
4555 if (ss_req->start_method == method && req->nframes && tls->frame_count == req->nframes) {//Check also frame count(could be recursion)
4556 DEBUG_PRINTF (1, "[%p] Seq point at nonempty stack %x while stepping in, continuing single stepping.\n", (gpointer) (gsize) mono_native_thread_id_get (), sp->il_offset);
4561 if (req->size != STEP_SIZE_LINE)
4564 /* Have to check whenever a different source line was reached */
4565 method = jinfo_get_method (ji);
4566 minfo = mono_debug_lookup_method (method);
4569 loc = mono_debug_method_lookup_location (minfo, sp->il_offset);
4572 DEBUG_PRINTF (1, "[%p] No line number info for il offset %x, continuing single stepping.\n", (gpointer) (gsize) mono_native_thread_id_get (), sp->il_offset);
4573 ss_req->last_method = method;
4575 } else if (loc && method == ss_req->last_method && loc->row == ss_req->last_line) {
4576 DEBUG_PRINTF (1, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer) (gsize) mono_native_thread_id_get (), loc->row);
4581 ss_req->last_method = method;
4582 ss_req->last_line = loc->row;
4583 mono_debug_free_source_location (loc);
4590 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4592 return bp->method && bp->method->klass->image->assembly == assembly;
4596 process_breakpoint_inner (DebuggerTlsData *tls, gboolean from_signal)
4600 int i, j, suspend_policy;
4601 guint32 native_offset;
4603 BreakpointInstance *inst;
4604 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4605 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4606 EventKind kind = EVENT_KIND_BREAKPOINT;
4607 MonoContext *ctx = &tls->restore_state.ctx;
4609 MonoSeqPointInfo *info;
4613 // FIXME: Speed this up
4615 ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
4616 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4617 g_assert (ji && !ji->is_trampoline);
4618 method = jinfo_get_method (ji);
4620 /* Compute the native offset of the breakpoint from the ip */
4621 native_offset = ip - (guint8*)ji->code_start;
4624 * Skip the instruction causing the breakpoint signal.
4627 mono_arch_skip_breakpoint (ctx, ji);
4629 if (method->wrapper_type || tls->disable_breakpoints)
4632 bp_reqs = g_ptr_array_new ();
4633 ss_reqs = g_ptr_array_new ();
4634 ss_reqs_orig = g_ptr_array_new ();
4636 mono_loader_lock ();
4639 * The ip points to the instruction causing the breakpoint event, which is after
4640 * the offset recorded in the seq point map, so find the prev seq point before ip.
4642 found_sp = mono_find_prev_seq_point_for_native_offset (mono_domain_get (), method, native_offset, &info, &sp);
4645 no_seq_points_found (method, native_offset);
4647 g_assert (found_sp);
4649 DEBUG_PRINTF (1, "[%p] Breakpoint hit, method=%s, ip=%p, [il=0x%x,native=0x%x].\n", (gpointer) (gsize) mono_native_thread_id_get (), method->name, ip, sp.il_offset, native_offset);
4652 for (i = 0; i < breakpoints->len; ++i) {
4653 bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4658 for (j = 0; j < bp->children->len; ++j) {
4659 inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4660 if (inst->ji == ji && inst->il_offset == sp.il_offset && inst->native_offset == sp.native_offset) {
4661 if (bp->req->event_kind == EVENT_KIND_STEP) {
4662 g_ptr_array_add (ss_reqs_orig, bp->req);
4664 g_ptr_array_add (bp_reqs, bp->req);
4669 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4670 /* Maybe a method entry/exit event */
4671 if (sp.il_offset == METHOD_ENTRY_IL_OFFSET)
4672 kind = EVENT_KIND_METHOD_ENTRY;
4673 else if (sp.il_offset == METHOD_EXIT_IL_OFFSET)
4674 kind = EVENT_KIND_METHOD_EXIT;
4677 /* Process single step requests */
4678 for (i = 0; i < ss_reqs_orig->len; ++i) {
4679 EventRequest *req = (EventRequest *)g_ptr_array_index (ss_reqs_orig, i);
4680 SingleStepReq *ss_req = (SingleStepReq *)req->info;
4683 if (mono_thread_internal_current () != ss_req->thread)
4686 hit = ss_update (ss_req, ji, &sp, tls, ctx);
4688 g_ptr_array_add (ss_reqs, req);
4690 /* Start single stepping again from the current sequence point */
4691 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
4694 if (ss_reqs->len > 0)
4695 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4696 if (bp_reqs->len > 0)
4697 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4698 if (kind != EVENT_KIND_BREAKPOINT)
4699 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4701 mono_loader_unlock ();
4703 g_ptr_array_free (bp_reqs, TRUE);
4704 g_ptr_array_free (ss_reqs, TRUE);
4707 * FIXME: The first event will suspend, so the second will only be sent after the
4711 process_event (EVENT_KIND_STEP, method, 0, ctx, ss_events, suspend_policy);
4713 process_event (kind, method, 0, ctx, bp_events, suspend_policy);
4714 if (enter_leave_events)
4715 process_event (kind, method, 0, ctx, enter_leave_events, suspend_policy);
4718 /* Process a breakpoint/single step event after resuming from a signal handler */
4720 process_signal_event (void (*func) (DebuggerTlsData*, gboolean))
4722 DebuggerTlsData *tls;
4723 MonoThreadUnwindState orig_restore_state;
4726 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4727 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4728 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4729 mono_thread_state_init_from_monoctx (&tls->restore_state, &tls->handler_ctx);
4733 /* This is called when resuming from a signal handler, so it shouldn't return */
4734 memcpy (&ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4735 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4736 mono_restore_context (&ctx);
4737 g_assert_not_reached ();
4741 process_breakpoint (void)
4743 process_signal_event (process_breakpoint_inner);
4747 resume_from_signal_handler (void *sigctx, void *func)
4749 DebuggerTlsData *tls;
4752 /* Save the original context in TLS */
4753 // FIXME: This might not work on an altstack ?
4754 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4756 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer) (gsize) mono_native_thread_id_get ());
4759 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4760 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4761 // clob:c could be added to op_seq_point.
4763 mono_sigctx_to_monoctx (sigctx, &ctx);
4764 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4765 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4766 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4768 MONO_CONTEXT_SET_IP (&ctx, func);
4770 mono_monoctx_to_sigctx (&ctx, sigctx);
4772 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4773 mono_ppc_set_func_into_sigctx (sigctx, func);
4778 mono_debugger_agent_breakpoint_hit (void *sigctx)
4781 * We are called from a signal handler, and running code there causes all kinds of
4782 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4783 * So set up the signal context to return to the real breakpoint handler function.
4785 resume_from_signal_handler (sigctx, process_breakpoint);
4789 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4791 if (frame->managed) {
4792 *(MonoContext*)data = *ctx;
4801 * Called by System.Diagnostics.Debugger:Break ().
4804 mono_debugger_agent_user_break (void)
4806 if (agent_config.enabled) {
4811 /* Obtain a context */
4812 MONO_CONTEXT_SET_IP (&ctx, NULL);
4813 mono_walk_stack_with_ctx (user_break_cb, NULL, (MonoUnwindOptions)0, &ctx);
4814 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4816 mono_loader_lock ();
4817 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4818 mono_loader_unlock ();
4820 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4821 } else if (debug_options.native_debugger_break) {
4827 ss_depth_to_string (StepDepth depth)
4830 case STEP_DEPTH_OVER:
4832 case STEP_DEPTH_OUT:
4834 case STEP_DEPTH_INTO:
4837 g_assert_not_reached ();
4843 process_single_step_inner (DebuggerTlsData *tls, gboolean from_signal)
4848 int il_offset, suspend_policy;
4851 MonoContext *ctx = &tls->restore_state.ctx;
4854 MonoSeqPointInfo *info;
4856 ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
4858 /* Skip the instruction causing the single step */
4860 mono_arch_skip_single_step (ctx);
4862 if (suspend_count > 0) {
4863 /* Fastpath during invokes, see in process_suspend () */
4864 if (suspend_count - tls->resume_count == 0)
4866 process_suspend (tls, ctx);
4871 // FIXME: A suspend race
4874 if (mono_thread_internal_current () != ss_req->thread)
4877 if (log_level > 0) {
4878 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4880 DEBUG_PRINTF (1, "[%p] Single step event (depth=%s) at %s (%p)[0x%x], sp %p, last sp %p\n", (gpointer) (gsize) mono_native_thread_id_get (), ss_depth_to_string (ss_req->depth), mono_method_full_name (jinfo_get_method (ji), TRUE), MONO_CONTEXT_GET_IP (ctx), (int)((guint8*)MONO_CONTEXT_GET_IP (ctx) - (guint8*)ji->code_start), MONO_CONTEXT_GET_SP (ctx), ss_req->last_sp);
4883 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4884 g_assert (ji && !ji->is_trampoline);
4885 method = jinfo_get_method (ji);
4888 if (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4893 * Stopping in memset makes half-initialized vtypes visible.
4894 * Stopping in memcpy makes half-copied vtypes visible.
4896 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
4900 * The ip points to the instruction causing the single step event, which is before
4901 * the offset recorded in the seq point map, so find the next seq point after ip.
4903 if (!mono_find_next_seq_point_for_native_offset (domain, method, (guint8*)ip - (guint8*)ji->code_start, &info, &sp))
4906 il_offset = sp.il_offset;
4908 if (!ss_update (ss_req, ji, &sp, tls, ctx))
4911 /* Start single stepping again from the current sequence point */
4912 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
4914 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
4915 (method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4916 !strcmp (method->name, ".cctor"))
4919 // FIXME: Has to lock earlier
4921 reqs = g_ptr_array_new ();
4923 mono_loader_lock ();
4925 g_ptr_array_add (reqs, ss_req->req);
4927 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4929 g_ptr_array_free (reqs, TRUE);
4931 mono_loader_unlock ();
4933 process_event (EVENT_KIND_STEP, jinfo_get_method (ji), il_offset, ctx, events, suspend_policy);
4937 process_single_step (void)
4939 process_signal_event (process_single_step_inner);
4943 * mono_debugger_agent_single_step_event:
4945 * Called from a signal handler to handle a single step event.
4948 mono_debugger_agent_single_step_event (void *sigctx)
4950 /* Resume to process_single_step through the signal context */
4952 // FIXME: Since step out/over is implemented using step in, the step in case should
4953 // be as fast as possible. Move the relevant code from process_single_step_inner ()
4956 if (is_debugger_thread ()) {
4958 * This could happen despite our best effors when the runtime calls
4959 * assembly/type resolve hooks.
4960 * FIXME: Breakpoints too.
4964 mono_sigctx_to_monoctx (sigctx, &ctx);
4965 mono_arch_skip_single_step (&ctx);
4966 mono_monoctx_to_sigctx (&ctx, sigctx);
4970 resume_from_signal_handler (sigctx, process_single_step);
4974 debugger_agent_single_step_from_context (MonoContext *ctx)
4976 DebuggerTlsData *tls;
4977 MonoThreadUnwindState orig_restore_state;
4979 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4980 /* Fastpath during invokes, see in process_suspend () */
4981 if (tls && suspend_count && suspend_count - tls->resume_count == 0)
4984 if (is_debugger_thread ())
4989 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4990 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4991 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
4992 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
4994 process_single_step_inner (tls, FALSE);
4996 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4997 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5001 debugger_agent_breakpoint_from_context (MonoContext *ctx)
5003 DebuggerTlsData *tls;
5004 MonoThreadUnwindState orig_restore_state;
5007 if (is_debugger_thread ())
5010 orig_ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
5011 MONO_CONTEXT_SET_IP (ctx, orig_ip - 1);
5013 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5015 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5016 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5017 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5019 process_breakpoint_inner (tls, FALSE);
5021 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5022 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5023 if (MONO_CONTEXT_GET_IP (ctx) == orig_ip - 1)
5024 MONO_CONTEXT_SET_IP (ctx, orig_ip);
5028 * start_single_stepping:
5030 * Turn on single stepping. Can be called multiple times, for example,
5031 * by a single step event request + a suspend.
5034 start_single_stepping (void)
5036 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5037 int val = InterlockedIncrement (&ss_count);
5040 mono_arch_start_single_stepping ();
5042 g_assert_not_reached ();
5047 stop_single_stepping (void)
5049 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5050 int val = InterlockedDecrement (&ss_count);
5053 mono_arch_stop_single_stepping ();
5055 g_assert_not_reached ();
5062 * Stop the single stepping operation given by SS_REQ.
5065 ss_stop (SingleStepReq *ss_req)
5070 for (l = ss_req->bps; l; l = l->next) {
5071 clear_breakpoint ((MonoBreakpoint *)l->data);
5073 g_slist_free (ss_req->bps);
5077 if (ss_req->global) {
5078 stop_single_stepping ();
5079 ss_req->global = FALSE;
5086 * Start the single stepping operation given by SS_REQ from the sequence point SP.
5087 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
5088 * belong to the same thread as CTX.
5089 * If FRAMES is not-null, use that instead of tls->frames for placing breakpoints etc.
5092 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint* sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls,
5093 gboolean step_to_catch, StackFrame **frames, int nframes)
5095 int i, j, frame_index;
5096 SeqPoint *next_sp, *parent_sp = NULL;
5097 SeqPoint local_sp, local_parent_sp;
5100 MonoSeqPointInfo *parent_info;
5101 MonoMethod *parent_sp_method = NULL;
5102 gboolean enable_global = FALSE;
5104 /* Stop the previous operation */
5108 * Implement single stepping using breakpoints if possible.
5110 if (step_to_catch) {
5111 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
5112 ss_req->bps = g_slist_append (ss_req->bps, bp);
5116 if (ctx && !frames) {
5117 /* Need parent frames */
5118 if (!tls->context.valid)
5119 mono_thread_state_init_from_monoctx (&tls->context, ctx);
5120 compute_frame_info (tls->thread, tls);
5121 frames = tls->frames;
5122 nframes = tls->frame_count;
5126 * Find the first sequence point in the current or in a previous frame which
5127 * is not the last in its method.
5129 if (ss_req->depth == STEP_DEPTH_OUT) {
5130 /* Ignore seq points in current method */
5131 while (frame_index < nframes) {
5132 StackFrame *frame = frames [frame_index];
5134 method = frame->method;
5135 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5136 sp = (found_sp)? &local_sp : NULL;
5138 if (sp && sp->next_len != 0)
5141 // There could be method calls before the next seq point in the caller when using nested calls
5142 //enable_global = TRUE;
5144 if (sp && sp->next_len == 0) {
5146 while (frame_index < nframes) {
5147 StackFrame *frame = frames [frame_index];
5149 method = frame->method;
5150 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5151 sp = (found_sp)? &local_sp : NULL;
5152 if (sp && sp->next_len != 0)
5158 /* Have to put a breakpoint into a parent frame since the seq points might not cover all control flow out of the method */
5159 while (frame_index < nframes) {
5160 StackFrame *frame = frames [frame_index];
5162 parent_sp_method = frame->method;
5163 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &parent_info, &local_parent_sp);
5164 parent_sp = found_sp ? &local_parent_sp : NULL;
5165 if (found_sp && parent_sp->next_len != 0)
5173 if (sp && sp->next_len > 0) {
5174 SeqPoint* next = g_new(SeqPoint, sp->next_len);
5176 mono_seq_point_init_next (info, *sp, next);
5177 for (i = 0; i < sp->next_len; i++) {
5180 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
5181 ss_req->bps = g_slist_append (ss_req->bps, bp);
5187 SeqPoint* next = g_new(SeqPoint, parent_sp->next_len);
5189 mono_seq_point_init_next (parent_info, *parent_sp, next);
5190 for (i = 0; i < parent_sp->next_len; i++) {
5193 bp = set_breakpoint (parent_sp_method, next_sp->il_offset, ss_req->req, NULL);
5194 ss_req->bps = g_slist_append (ss_req->bps, bp);
5199 if (ss_req->nframes == 0)
5200 ss_req->nframes = nframes;
5202 if ((ss_req->depth == STEP_DEPTH_OVER) && (!sp && !parent_sp)) {
5203 DEBUG_PRINTF (1, "[dbg] No parent frame for step over, transition to step into.\n");
5205 * This is needed since if we leave managed code, and later return to it, step over
5206 * is not going to stop.
5207 * This approach is a bit ugly, since we change the step depth, but it only affects
5208 * clients who reuse the same step request, and only in this special case.
5210 ss_req->depth = STEP_DEPTH_INTO;
5213 if (ss_req->depth == STEP_DEPTH_OVER) {
5214 /* Need to stop in catch clauses as well */
5215 for (i = 0; i < nframes; ++i) {
5216 StackFrame *frame = frames [i];
5219 MonoJitInfo *jinfo = frame->ji;
5220 for (j = 0; j < jinfo->num_clauses; ++j) {
5221 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5223 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);
5224 sp = (found_sp)? &local_sp : NULL;
5226 bp = set_breakpoint (frame->method, sp->il_offset, ss_req->req, NULL);
5227 ss_req->bps = g_slist_append (ss_req->bps, bp);
5234 if (ss_req->depth == STEP_DEPTH_INTO) {
5235 /* Enable global stepping so we stop at method entry too */
5236 enable_global = TRUE;
5240 * The ctx/frame info computed above will become invalid when we continue.
5242 tls->context.valid = FALSE;
5243 tls->async_state.valid = FALSE;
5244 invalidate_frames (tls);
5247 if (enable_global) {
5248 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5249 ss_req->global = TRUE;
5250 start_single_stepping ();
5251 } else if (!ss_req->bps) {
5252 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5253 ss_req->global = TRUE;
5254 start_single_stepping ();
5256 ss_req->global = FALSE;
5261 * Start single stepping of thread THREAD
5264 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req)
5266 DebuggerTlsData *tls;
5267 MonoSeqPointInfo *info = NULL;
5268 SeqPoint *sp = NULL;
5271 MonoMethod *method = NULL;
5272 MonoDebugMethodInfo *minfo;
5273 gboolean step_to_catch = FALSE;
5274 gboolean set_ip = FALSE;
5275 StackFrame **frames = NULL;
5278 if (suspend_count == 0)
5279 return ERR_NOT_SUSPENDED;
5281 wait_for_suspend ();
5283 // FIXME: Multiple requests
5285 DEBUG_PRINTF (0, "Received a single step request while the previous one was still active.\n");
5286 return ERR_NOT_IMPLEMENTED;
5289 DEBUG_PRINTF (1, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth));
5291 ss_req = g_new0 (SingleStepReq, 1);
5293 ss_req->thread = thread;
5294 ss_req->size = size;
5295 ss_req->depth = depth;
5296 ss_req->filter = filter;
5299 mono_loader_lock ();
5300 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5301 mono_loader_unlock ();
5303 g_assert (tls->context.valid);
5305 if (tls->restore_state.valid && MONO_CONTEXT_GET_IP (&tls->context.ctx) != MONO_CONTEXT_GET_IP (&tls->restore_state.ctx)) {
5307 * Need to start single stepping from restore_state and not from the current state
5310 frames = compute_frame_info_from (thread, tls, &tls->restore_state, &nframes);
5313 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5315 if (tls->catch_state.valid) {
5317 StackFrameInfo frame;
5318 MonoContext new_ctx;
5319 MonoLMF *lmf = NULL;
5322 * We are stopped at a throw site. Stepping should go to the catch site.
5325 /* Find the the jit info for the catch context */
5326 res = mono_find_jit_info_ext (
5327 (MonoDomain *)tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN],
5328 (MonoJitTlsData *)((MonoThreadInfo*)thread->thread_info)->jit_data,
5329 NULL, &tls->catch_state.ctx, &new_ctx, NULL, &lmf, NULL, &frame);
5331 g_assert (frame.type == FRAME_TYPE_MANAGED);
5334 * Find the seq point corresponding to the landing site ip, which is the first seq
5337 found_sp = mono_find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info, &local_sp);
5338 sp = (found_sp)? &local_sp : NULL;
5340 no_seq_points_found (frame.method, frame.native_offset);
5343 method = frame.method;
5345 step_to_catch = TRUE;
5346 /* This make sure the seq point is not skipped by process_single_step () */
5347 ss_req->last_sp = NULL;
5350 if (!step_to_catch) {
5351 StackFrame *frame = NULL;
5354 if (frames && nframes)
5357 compute_frame_info (thread, tls);
5359 if (tls->frame_count)
5360 frame = tls->frames [0];
5363 if (ss_req->size == STEP_SIZE_LINE) {
5365 ss_req->last_method = frame->method;
5366 ss_req->last_line = -1;
5368 minfo = mono_debug_lookup_method (frame->method);
5369 if (minfo && frame->il_offset != -1) {
5370 MonoDebugSourceLocation *loc = mono_debug_method_lookup_location (minfo, frame->il_offset);
5373 ss_req->last_line = loc->row;
5381 if (!method && frame->il_offset != -1) {
5382 /* FIXME: Sort the table and use a binary search */
5383 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5384 sp = (found_sp)? &local_sp : NULL;
5386 no_seq_points_found (frame->method, frame->native_offset);
5388 method = frame->method;
5393 ss_req->start_method = method;
5395 ss_start (ss_req, method, sp, info, set_ip ? &tls->restore_state.ctx : &tls->context.ctx, tls, step_to_catch, frames, nframes);
5398 free_frames (frames, nframes);
5404 ss_destroy (SingleStepReq *req)
5407 g_assert (ss_req == req);
5416 ss_clear_for_assembly (SingleStepReq *req, MonoAssembly *assembly)
5419 gboolean found = TRUE;
5423 for (l = ss_req->bps; l; l = l->next) {
5424 if (breakpoint_matches_assembly ((MonoBreakpoint *)l->data, assembly)) {
5425 clear_breakpoint ((MonoBreakpoint *)l->data);
5426 ss_req->bps = g_slist_delete_link (ss_req->bps, l);
5435 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5438 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5444 if (!agent_config.enabled)
5447 mono_loader_lock ();
5448 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5449 mono_loader_unlock ();
5452 ei.category = category ? mono_string_to_utf8 (category) : NULL;
5453 ei.message = message ? mono_string_to_utf8 (message) : NULL;
5455 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5457 g_free (ei.category);
5458 g_free (ei.message);
5462 mono_debugger_agent_debug_log_is_enabled (void)
5464 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5465 return agent_config.enabled;
5468 #if defined(PLATFORM_ANDROID) || defined(TARGET_ANDROID)
5470 mono_debugger_agent_unhandled_exception (MonoException *exc)
5479 memset (&ei, 0, sizeof (EventInfo));
5480 ei.exc = (MonoObject*)exc;
5482 mono_loader_lock ();
5483 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5484 mono_loader_unlock ();
5486 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5491 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5492 MonoContext *catch_ctx)
5494 int i, j, suspend_policy;
5496 MonoJitInfo *ji, *catch_ji;
5498 DebuggerTlsData *tls = NULL;
5500 if (thread_to_tls != NULL) {
5501 MonoInternalThread *thread = mono_thread_internal_current ();
5503 mono_loader_lock ();
5504 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5505 mono_loader_unlock ();
5507 if (tls && tls->abort_requested)
5509 if (tls && tls->disable_breakpoints)
5513 memset (&ei, 0, sizeof (EventInfo));
5515 /* Just-In-Time debugging */
5517 if (agent_config.onuncaught && !inited) {
5518 finish_agent_init (FALSE);
5521 * Send an unsolicited EXCEPTION event with a dummy request id.
5523 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5524 ei.exc = (MonoObject*)exc;
5525 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5528 } else if (agent_config.onthrow && !inited) {
5530 gboolean found = FALSE;
5532 for (l = agent_config.onthrow; l; l = l->next) {
5533 char *ex_type = (char *)l->data;
5534 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5536 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5543 finish_agent_init (FALSE);
5546 * Send an unsolicited EXCEPTION event with a dummy request id.
5548 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5549 ei.exc = (MonoObject*)exc;
5550 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5558 ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5560 catch_ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5564 ei.exc = (MonoObject*)exc;
5565 ei.caught = catch_ctx != NULL;
5567 mono_loader_lock ();
5569 /* Treat exceptions which are caught in non-user code as unhandled */
5570 for (i = 0; i < event_requests->len; ++i) {
5571 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
5572 if (req->event_kind != EVENT_KIND_EXCEPTION)
5575 for (j = 0; j < req->nmodifiers; ++j) {
5576 Modifier *mod = &req->modifiers [j];
5578 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5580 gboolean found = FALSE;
5581 MonoAssembly **assemblies = mod->data.assemblies;
5584 for (k = 0; assemblies [k]; ++k)
5585 if (assemblies [k] == jinfo_get_method (catch_ji)->klass->image->assembly)
5594 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5595 mono_loader_unlock ();
5597 if (tls && ei.caught && catch_ctx) {
5598 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5599 tls->catch_state.ctx = *catch_ctx;
5600 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5601 tls->catch_state.valid = TRUE;
5604 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5607 tls->catch_state.valid = FALSE;
5611 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5613 DebuggerTlsData *tls;
5618 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5623 * We're about to invoke an exception filter during the first pass of exception handling.
5625 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5626 * 'orig_ctx' is the context where the exception has been thrown.
5629 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5631 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5632 * the call site (line 37) and then continue to Main(), but it would never
5633 * include the throw site (line 32).
5635 * Since exception filters are invoked during the first pass of exception handling,
5636 * the stack frames of the throw site are still intact, so we should include them
5639 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5641 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5642 * but report the location of the 'throw' to the user.
5646 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5650 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5652 DebuggerTlsData *tls;
5657 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5661 tls->filter_state.valid = FALSE;
5665 * buffer_add_value_full:
5667 * Add the encoding of the value at ADDR described by T to the buffer.
5668 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5672 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5673 gboolean as_vtype, GHashTable *parent_vtypes)
5676 gboolean boxed_vtype = FALSE;
5679 if (!(*(void**)addr)) {
5680 /* This can happen with compiler generated locals */
5681 //printf ("%s\n", mono_type_full_name (t));
5682 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5685 g_assert (*(void**)addr);
5686 addr = *(void**)addr;
5691 case MONO_TYPE_BOOLEAN:
5694 case MONO_TYPE_CHAR:
5714 case MONO_TYPE_VOID:
5715 buffer_add_byte (buf, t->type);
5717 case MONO_TYPE_BOOLEAN:
5720 buffer_add_byte (buf, t->type);
5721 buffer_add_int (buf, *(gint8*)addr);
5723 case MONO_TYPE_CHAR:
5726 buffer_add_byte (buf, t->type);
5727 buffer_add_int (buf, *(gint16*)addr);
5732 buffer_add_byte (buf, t->type);
5733 buffer_add_int (buf, *(gint32*)addr);
5738 buffer_add_byte (buf, t->type);
5739 buffer_add_long (buf, *(gint64*)addr);
5743 /* Treat it as a vtype */
5745 case MONO_TYPE_PTR: {
5746 gssize val = *(gssize*)addr;
5748 buffer_add_byte (buf, t->type);
5749 buffer_add_long (buf, val);
5753 case MONO_TYPE_STRING:
5754 case MONO_TYPE_SZARRAY:
5755 case MONO_TYPE_OBJECT:
5756 case MONO_TYPE_CLASS:
5757 case MONO_TYPE_ARRAY:
5758 obj = *(MonoObject**)addr;
5761 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5763 if (obj->vtable->klass->valuetype) {
5764 t = &obj->vtable->klass->byval_arg;
5765 addr = mono_object_unbox (obj);
5768 } else if (obj->vtable->klass->rank) {
5769 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5770 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5771 buffer_add_byte (buf, MONO_TYPE_CLASS);
5773 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5775 buffer_add_objid (buf, obj);
5779 case MONO_TYPE_VALUETYPE:
5780 case MONO_TYPE_TYPEDBYREF: {
5784 MonoClass *klass = mono_class_from_mono_type (t);
5789 * Handle boxed vtypes recursively referencing themselves using fields.
5792 parent_vtypes = g_hash_table_new (NULL, NULL);
5793 vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
5795 if (CHECK_PROTOCOL_VERSION (2, 33)) {
5796 buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
5797 buffer_add_int (buf, vtype_index - 1);
5799 /* The client can't handle PARENT_VTYPE */
5800 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5804 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
5808 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5809 buffer_add_byte (buf, klass->enumtype);
5810 buffer_add_typeid (buf, domain, klass);
5814 while ((f = mono_class_get_fields (klass, &iter))) {
5815 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5817 if (mono_field_is_deleted (f))
5821 buffer_add_int (buf, nfields);
5824 while ((f = mono_class_get_fields (klass, &iter))) {
5825 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5827 if (mono_field_is_deleted (f))
5829 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE, parent_vtypes);
5833 g_hash_table_remove (parent_vtypes, addr);
5834 if (g_hash_table_size (parent_vtypes) == 0) {
5835 g_hash_table_destroy (parent_vtypes);
5836 parent_vtypes = NULL;
5841 case MONO_TYPE_GENERICINST:
5842 if (mono_type_generic_inst_is_valuetype (t)) {
5854 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5856 buffer_add_value_full (buf, t, addr, domain, FALSE, NULL);
5860 obj_is_of_type (MonoObject *obj, MonoType *t)
5862 MonoClass *klass = obj->vtable->klass;
5863 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5864 if (mono_class_is_transparent_proxy (klass)) {
5865 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5866 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5876 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5879 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5885 gpointer iter = NULL;
5889 is_enum = decode_byte (buf, &buf, limit);
5890 /* Enums are sent as a normal vtype */
5892 return ERR_NOT_IMPLEMENTED;
5893 klass = decode_typeid (buf, &buf, limit, &d, &err);
5894 if (err != ERR_NONE)
5897 if (t && klass != mono_class_from_mono_type (t)) {
5898 char *name = mono_type_full_name (t);
5899 char *name2 = mono_type_full_name (&klass->byval_arg);
5900 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got %s.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, name2);
5903 return ERR_INVALID_ARGUMENT;
5906 nfields = decode_int (buf, &buf, limit);
5907 while ((f = mono_class_get_fields (klass, &iter))) {
5908 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5910 if (mono_field_is_deleted (f))
5912 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5913 if (err != ERR_NONE)
5917 g_assert (nfields == 0);
5925 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5929 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5930 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5931 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5932 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5933 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE) &&
5934 !(t->type == MONO_TYPE_VALUETYPE && type == MONO_TYPE_OBJECT)) {
5935 char *name = mono_type_full_name (t);
5936 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
5938 return ERR_INVALID_ARGUMENT;
5942 case MONO_TYPE_BOOLEAN:
5943 *(guint8*)addr = decode_int (buf, &buf, limit);
5945 case MONO_TYPE_CHAR:
5946 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5949 *(gint8*)addr = decode_int (buf, &buf, limit);
5952 *(guint8*)addr = decode_int (buf, &buf, limit);
5955 *(gint16*)addr = decode_int (buf, &buf, limit);
5958 *(guint16*)addr = decode_int (buf, &buf, limit);
5961 *(gint32*)addr = decode_int (buf, &buf, limit);
5964 *(guint32*)addr = decode_int (buf, &buf, limit);
5967 *(gint64*)addr = decode_long (buf, &buf, limit);
5970 *(guint64*)addr = decode_long (buf, &buf, limit);
5973 *(guint32*)addr = decode_int (buf, &buf, limit);
5976 *(guint64*)addr = decode_long (buf, &buf, limit);
5979 /* We send these as I8, so we get them back as such */
5980 g_assert (type == MONO_TYPE_I8);
5981 *(gssize*)addr = decode_long (buf, &buf, limit);
5983 case MONO_TYPE_GENERICINST:
5984 if (MONO_TYPE_ISSTRUCT (t)) {
5985 /* The client sends these as a valuetype */
5993 /* We send these as vtypes, so we get them back as such */
5994 g_assert (type == MONO_TYPE_VALUETYPE);
5997 case MONO_TYPE_VALUETYPE:
5998 if (type == MONO_TYPE_OBJECT) {
6000 int objid = decode_objid (buf, &buf, limit);
6004 err = get_object (objid, (MonoObject**)&obj);
6005 if (err != ERR_NONE)
6008 return ERR_INVALID_ARGUMENT;
6009 if (obj->vtable->klass != mono_class_from_mono_type (t)) {
6010 DEBUG_PRINTF (1, "Expected type '%s', got object '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6011 return ERR_INVALID_ARGUMENT;
6013 memcpy (addr, mono_object_unbox (obj), mono_class_value_size (obj->vtable->klass, NULL));
6015 err = decode_vtype (t, domain, addr, buf, &buf, limit);
6016 if (err != ERR_NONE)
6022 if (MONO_TYPE_IS_REFERENCE (t)) {
6023 if (type == MONO_TYPE_OBJECT) {
6024 int objid = decode_objid (buf, &buf, limit);
6028 err = get_object (objid, (MonoObject**)&obj);
6029 if (err != ERR_NONE)
6033 if (!obj_is_of_type (obj, t)) {
6034 DEBUG_PRINTF (1, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6035 return ERR_INVALID_ARGUMENT;
6038 if (obj && obj->vtable->domain != domain)
6039 return ERR_INVALID_ARGUMENT;
6041 mono_gc_wbarrier_generic_store (addr, obj);
6042 } else if (type == VALUE_TYPE_ID_NULL) {
6043 *(MonoObject**)addr = NULL;
6044 } else if (type == MONO_TYPE_VALUETYPE) {
6053 /* This can happen when round-tripping boxed vtypes */
6055 * Obtain vtype class.
6056 * Same as the beginning of the handle_vtype case above.
6059 is_enum = decode_byte (buf, &buf, limit);
6061 return ERR_NOT_IMPLEMENTED;
6062 klass = decode_typeid (buf, &buf, limit, &d, &err);
6063 if (err != ERR_NONE)
6066 /* Decode the vtype into a temporary buffer, then box it. */
6067 vtype_buf_size = mono_class_value_size (klass, NULL);
6068 vtype_buf = (guint8 *)g_malloc0 (vtype_buf_size);
6069 g_assert (vtype_buf);
6072 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
6073 if (err != ERR_NONE) {
6077 *(MonoObject**)addr = mono_value_box_checked (d, klass, vtype_buf, &error);
6078 mono_error_cleanup (&error);
6081 char *name = mono_type_full_name (t);
6082 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
6084 return ERR_INVALID_ARGUMENT;
6098 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6102 int type = decode_byte (buf, &buf, limit);
6104 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
6105 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
6106 guint8 *nullable_buf;
6109 * First try decoding it as a Nullable`1
6111 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6112 if (err == ERR_NONE)
6116 * Then try decoding as a primitive value or null.
6118 if (targ->type == type) {
6119 nullable_buf = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
6120 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
6121 if (err != ERR_NONE) {
6122 g_free (nullable_buf);
6125 MonoObject *boxed = mono_value_box_checked (domain, mono_class_from_mono_type (targ), nullable_buf, &error);
6126 if (!is_ok (&error)) {
6127 mono_error_cleanup (&error);
6128 return ERR_INVALID_OBJECT;
6130 mono_nullable_init (addr, boxed, mono_class_from_mono_type (t));
6131 g_free (nullable_buf);
6134 } else if (type == VALUE_TYPE_ID_NULL) {
6135 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
6141 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6145 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
6149 guint8 *addr, *gaddr;
6152 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6153 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6156 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
6157 reg_val = mono_arch_context_get_int_reg (ctx, reg);
6159 buffer_add_value_full (buf, t, ®_val, domain, as_vtype, NULL);
6161 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6162 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6163 addr += (gint32)var->offset;
6165 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6167 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6169 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6172 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6173 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
6174 /* Same as regoffset, but with an indirection */
6175 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6176 addr += (gint32)var->offset;
6178 gaddr = (guint8 *)*(gpointer*)addr;
6180 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL);
6182 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
6183 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
6184 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
6185 MonoGSharedVtMethodRuntimeInfo *info;
6191 g_assert (info_var);
6192 g_assert (locals_var);
6194 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6195 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6196 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6197 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6198 addr += (gint32)info_var->offset;
6199 info = (MonoGSharedVtMethodRuntimeInfo *)*(gpointer*)addr;
6200 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6201 info = (MonoGSharedVtMethodRuntimeInfo *)mono_arch_context_get_int_reg (ctx, reg);
6203 g_assert_not_reached ();
6207 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6208 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6209 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6210 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6211 addr += (gint32)locals_var->offset;
6212 locals = (guint8 *)*(gpointer*)addr;
6213 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6214 locals = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6216 g_assert_not_reached ();
6220 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6222 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6227 g_assert_not_reached ();
6232 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
6236 guint8 *addr, *gaddr;
6238 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6239 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6241 if (MONO_TYPE_IS_REFERENCE (t))
6242 size = sizeof (gpointer);
6244 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6247 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6248 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6250 gboolean is_signed = FALSE;
6253 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6256 // FIXME: Write barriers
6257 mono_gc_memmove_atomic (addr, val, size);
6262 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6267 v = is_signed ? *(gint8*)val : *(guint8*)val;
6270 v = is_signed ? *(gint16*)val : *(guint16*)val;
6273 v = is_signed ? *(gint32*)val : *(guint32*)val;
6276 v = is_signed ? *(gint64*)val : *(guint64*)val;
6279 g_assert_not_reached ();
6282 /* Set value on the stack or in the return ctx */
6283 if (reg_locations [reg]) {
6284 /* Saved on the stack */
6285 DEBUG_PRINTF (1, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v);
6286 *(reg_locations [reg]) = v;
6289 DEBUG_PRINTF (1, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v);
6290 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6293 // FIXME: Move these to mono-context.h/c.
6294 mono_arch_context_set_int_reg (ctx, reg, v);
6296 // FIXME: Can't set registers, so we disable linears
6301 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6302 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6303 addr += (gint32)var->offset;
6305 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6308 addr = *(guint8**)addr;
6314 // FIXME: Write barriers
6315 mono_gc_memmove_atomic (addr, val, size);
6317 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6318 /* Same as regoffset, but with an indirection */
6319 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6320 addr += (gint32)var->offset;
6322 gaddr = (guint8 *)*(gpointer*)addr;
6324 // FIXME: Write barriers
6325 mono_gc_memmove_atomic (gaddr, val, size);
6327 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6331 g_assert_not_reached ();
6336 clear_event_request (int req_id, int etype)
6340 mono_loader_lock ();
6341 for (i = 0; i < event_requests->len; ++i) {
6342 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6344 if (req->id == req_id && req->event_kind == etype) {
6345 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6346 clear_breakpoint ((MonoBreakpoint *)req->info);
6347 if (req->event_kind == EVENT_KIND_STEP)
6348 ss_destroy ((SingleStepReq *)req->info);
6349 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6350 clear_breakpoint ((MonoBreakpoint *)req->info);
6351 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6352 clear_breakpoint ((MonoBreakpoint *)req->info);
6353 g_ptr_array_remove_index_fast (event_requests, i);
6358 mono_loader_unlock ();
6362 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
6366 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6367 m->kind = MOD_KIND_NONE;
6368 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6369 int count = 0, match_count = 0, pos;
6370 MonoAssembly **newassemblies;
6372 for (i = 0; m->data.assemblies [i]; ++i) {
6374 if (m->data.assemblies [i] == assembly)
6379 newassemblies = g_new0 (MonoAssembly*, count - match_count);
6382 for (i = 0; i < count; ++i)
6383 if (m->data.assemblies [i] != assembly)
6384 newassemblies [pos ++] = m->data.assemblies [i];
6385 g_assert (pos == count - match_count);
6386 g_free (m->data.assemblies);
6387 m->data.assemblies = newassemblies;
6393 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
6397 for (i = 0; i < req->nmodifiers; ++i) {
6398 Modifier *m = &req->modifiers [i];
6400 clear_assembly_from_modifier (req, m, assembly);
6405 * clear_event_requests_for_assembly:
6407 * Clear all events requests which reference ASSEMBLY.
6410 clear_event_requests_for_assembly (MonoAssembly *assembly)
6415 mono_loader_lock ();
6419 for (i = 0; i < event_requests->len; ++i) {
6420 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6422 clear_assembly_from_modifiers (req, assembly);
6424 if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly ((MonoBreakpoint *)req->info, assembly)) {
6425 clear_event_request (req->id, req->event_kind);
6430 if (req->event_kind == EVENT_KIND_STEP)
6431 ss_clear_for_assembly ((SingleStepReq *)req->info, assembly);
6434 mono_loader_unlock ();
6438 * type_comes_from_assembly:
6440 * GHRFunc that returns TRUE if klass comes from assembly
6443 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6445 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6449 * clear_types_for_assembly:
6451 * Clears types from loaded_classes for a given assembly
6454 clear_types_for_assembly (MonoAssembly *assembly)
6456 MonoDomain *domain = mono_domain_get ();
6457 AgentDomainInfo *info = NULL;
6459 if (!domain || !domain_jit_info (domain))
6460 /* Can happen during shutdown */
6463 info = get_agent_domain_info (domain);
6465 mono_loader_lock ();
6466 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6467 mono_loader_unlock ();
6471 add_thread (gpointer key, gpointer value, gpointer user_data)
6473 MonoInternalThread *thread = (MonoInternalThread *)value;
6474 Buffer *buf = (Buffer *)user_data;
6476 buffer_add_objid (buf, (MonoObject*)thread);
6480 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6483 guint8 *end = invoke->endp;
6487 MonoMethodSignature *sig;
6490 MonoObject *this_arg, *res, *exc;
6493 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6496 MonoStopwatch watch;
6498 if (invoke->method) {
6500 * Invoke this method directly, currently only Environment.Exit () is supported.
6503 DEBUG_PRINTF (1, "[%p] Invoking method '%s' on receiver '%s'.\n", (gpointer) (gsize) mono_native_thread_id_get (), mono_method_full_name (invoke->method, TRUE), this_arg ? this_arg->vtable->klass->name : "<null>");
6505 mono_runtime_try_invoke (invoke->method, NULL, invoke->args, &exc, &error);
6506 mono_error_assert_ok (&error);
6508 g_assert_not_reached ();
6511 m = decode_methodid (p, &p, end, &domain, &err);
6512 if (err != ERR_NONE)
6514 sig = mono_method_signature (m);
6516 if (m->klass->valuetype)
6517 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6519 this_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
6520 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6521 /* Should be null */
6522 int type = decode_byte (p, &p, end);
6523 if (type != VALUE_TYPE_ID_NULL) {
6524 DEBUG_PRINTF (1, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6525 return ERR_INVALID_ARGUMENT;
6527 memset (this_buf, 0, mono_class_instance_size (m->klass));
6528 } else if (m->klass->valuetype && !strcmp (m->name, ".ctor")) {
6532 int type = decode_byte (p, &tmp_p, end);
6533 if (type == VALUE_TYPE_ID_NULL) {
6534 memset (this_buf, 0, mono_class_instance_size (m->klass));
6537 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6538 if (err != ERR_NONE)
6542 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6543 if (err != ERR_NONE)
6547 if (!m->klass->valuetype)
6548 this_arg = *(MonoObject**)this_buf;
6552 if (MONO_CLASS_IS_INTERFACE (m->klass)) {
6554 DEBUG_PRINTF (1, "[%p] Error: Interface method invoked without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6555 return ERR_INVALID_ARGUMENT;
6557 m = mono_object_get_virtual_method (this_arg, m);
6558 /* Transform this to the format the rest of the code expects it to be */
6559 if (m->klass->valuetype) {
6560 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6561 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
6563 } else if ((m->flags & METHOD_ATTRIBUTE_VIRTUAL) && !m->klass->valuetype && invoke->flags & INVOKE_FLAG_VIRTUAL) {
6565 DEBUG_PRINTF (1, "[%p] Error: invoke with INVOKE_FLAG_VIRTUAL flag set without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6566 return ERR_INVALID_ARGUMENT;
6568 m = mono_object_get_virtual_method (this_arg, m);
6569 if (m->klass->valuetype) {
6570 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6571 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
6575 DEBUG_PRINTF (1, "[%p] Invoking method '%s' on receiver '%s'.\n", (gpointer) (gsize) mono_native_thread_id_get (), mono_method_full_name (m, TRUE), this_arg ? this_arg->vtable->klass->name : "<null>");
6577 if (this_arg && this_arg->vtable->domain != domain)
6580 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this_arg) {
6581 if (!strcmp (m->name, ".ctor")) {
6582 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
6583 return ERR_INVALID_ARGUMENT;
6586 this_arg = mono_object_new_checked (domain, m->klass, &error);
6587 mono_error_assert_ok (&error);
6590 return ERR_INVALID_ARGUMENT;
6594 if (this_arg && !obj_is_of_type (this_arg, &m->klass->byval_arg))
6595 return ERR_INVALID_ARGUMENT;
6597 nargs = decode_int (p, &p, end);
6598 if (nargs != sig->param_count)
6599 return ERR_INVALID_ARGUMENT;
6600 /* Use alloca to get gc tracking */
6601 arg_buf = (guint8 **)g_alloca (nargs * sizeof (gpointer));
6602 memset (arg_buf, 0, nargs * sizeof (gpointer));
6603 args = (gpointer *)g_alloca (nargs * sizeof (gpointer));
6604 for (i = 0; i < nargs; ++i) {
6605 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6606 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6607 if (err != ERR_NONE)
6609 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6612 if (sig->params [i]->byref) {
6613 arg_buf [i] = (guint8 *)g_alloca (sizeof (mgreg_t));
6614 *(gpointer*)arg_buf [i] = args [i];
6615 args [i] = arg_buf [i];
6618 arg_buf [i] = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6619 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6620 if (err != ERR_NONE)
6622 args [i] = arg_buf [i];
6629 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6630 tls->disable_breakpoints = TRUE;
6632 tls->disable_breakpoints = FALSE;
6635 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6637 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6638 if (invoke->has_ctx) {
6641 lmf_addr = mono_get_lmf_addr ();
6644 memset (&ext, 0, sizeof (ext));
6645 mono_arch_init_lmf_ext (&ext, *lmf_addr);
6647 ext.debugger_invoke = TRUE;
6648 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6650 mono_set_lmf ((MonoLMF*)&ext);
6654 mono_stopwatch_start (&watch);
6655 res = mono_runtime_try_invoke (m, m->klass->valuetype ? (gpointer) this_buf : (gpointer) this_arg, args, &exc, &error);
6656 if (exc == NULL && !mono_error_ok (&error)) {
6657 exc = (MonoObject*) mono_error_convert_to_exception (&error);
6659 mono_error_cleanup (&error); /* FIXME report error */
6661 mono_stopwatch_stop (&watch);
6662 DEBUG_PRINTF (1, "[%p] Invoke result: %p, exc: %s, time: %ld ms.\n", (gpointer) (gsize) mono_native_thread_id_get (), res, exc ? exc->vtable->klass->name : NULL, (long)mono_stopwatch_elapsed_ms (&watch));
6664 buffer_add_byte (buf, 0);
6665 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6667 gboolean out_this = FALSE;
6668 gboolean out_args = FALSE;
6670 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_THIS) && CHECK_PROTOCOL_VERSION (2, 35))
6672 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_ARGS) && CHECK_PROTOCOL_VERSION (2, 35))
6674 buffer_add_byte (buf, 1 + (out_this ? 2 : 0) + (out_args ? 4 : 0));
6675 if (sig->ret->type == MONO_TYPE_VOID) {
6676 if (!strcmp (m->name, ".ctor")) {
6677 if (!m->klass->valuetype)
6678 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this_arg, domain);
6680 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
6682 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6684 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6685 buffer_add_value (buf, sig->ret, &res, domain);
6686 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6687 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6688 MonoClass *k = mono_class_from_mono_type (sig->ret);
6689 guint8 *nullable_buf = (guint8 *)g_alloca (mono_class_value_size (k, NULL));
6691 g_assert (nullable_buf);
6692 mono_nullable_init (nullable_buf, res, k);
6693 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6696 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6702 /* Return the new value of the receiver after the call */
6703 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
6705 buffer_add_int (buf, nargs);
6706 for (i = 0; i < nargs; ++i) {
6707 if (MONO_TYPE_IS_REFERENCE (sig->params [i]))
6708 buffer_add_value (buf, sig->params [i], &args [i], domain);
6709 else if (sig->params [i]->byref)
6710 /* add_value () does an indirection */
6711 buffer_add_value (buf, sig->params [i], &arg_buf [i], domain);
6713 buffer_add_value (buf, sig->params [i], arg_buf [i], domain);
6718 tls->disable_breakpoints = FALSE;
6720 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6721 if (invoke->has_ctx)
6722 mono_set_lmf ((MonoLMF *)(((gssize)ext.lmf.previous_lmf) & ~3));
6726 // FIXME: byref arguments
6734 * Invoke the method given by tls->pending_invoke in the current thread.
6737 invoke_method (void)
6739 DebuggerTlsData *tls;
6745 MonoContext restore_ctx;
6748 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
6752 * Store the `InvokeData *' in `tls->invoke' until we're done with
6753 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6756 mono_loader_lock ();
6758 invoke = tls->pending_invoke;
6760 tls->pending_invoke = NULL;
6762 invoke->last_invoke = tls->invoke;
6763 tls->invoke = invoke;
6765 mono_loader_unlock ();
6767 tls->frames_up_to_date = FALSE;
6773 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6774 buffer_init (&buf, 128);
6777 /* Fail the other invokes as well */
6779 err = do_invoke_method (tls, &buf, invoke, p, &p);
6782 if (tls->abort_requested) {
6783 if (CHECK_PROTOCOL_VERSION (2, 42))
6784 err = ERR_INVOKE_ABORTED;
6787 /* Start suspending before sending the reply */
6788 if (mindex == invoke->nmethods - 1) {
6789 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6790 for (i = 0; i < invoke->suspend_count; ++i)
6795 send_reply_packet (id, err, &buf);
6800 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6802 if (invoke->has_ctx)
6803 save_thread_context (&restore_ctx);
6805 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6806 g_assert (tls->resume_count);
6807 tls->resume_count -= invoke->suspend_count;
6810 DEBUG_PRINTF (1, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer) (gsize) mono_native_thread_id_get (), err, tls->resume_count);
6813 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6815 * It is possible that mono_thread_internal_abort () was called
6816 * after the mono_runtime_invoke_checked() already returned, but it doesn't matter
6817 * because we reset the abort here.
6820 mono_loader_lock ();
6822 if (tls->abort_requested)
6823 mono_thread_internal_reset_abort (tls->thread);
6825 tls->invoke = tls->invoke->last_invoke;
6826 tls->abort_requested = FALSE;
6828 mono_loader_unlock ();
6837 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6839 MonoThread *thread = (MonoThread *)value;
6840 DebuggerTlsData *tls;
6843 mono_loader_lock ();
6844 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
6846 res = tls->really_suspended;
6847 mono_loader_unlock ();
6853 get_source_files_for_type (MonoClass *klass)
6855 gpointer iter = NULL;
6857 MonoDebugSourceInfo *sinfo;
6861 files = g_ptr_array_new ();
6863 while ((method = mono_class_get_methods (klass, &iter))) {
6864 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6865 GPtrArray *source_file_list;
6868 mono_debug_get_seq_points (minfo, NULL, &source_file_list, NULL, NULL, NULL);
6869 for (j = 0; j < source_file_list->len; ++j) {
6870 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, j);
6871 for (i = 0; i < files->len; ++i)
6872 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6874 if (i == files->len)
6875 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6877 g_ptr_array_free (source_file_list, TRUE);
6885 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6888 case CMD_VM_VERSION: {
6889 char *build_info, *version;
6891 build_info = mono_get_runtime_build_info ();
6892 version = g_strdup_printf ("mono %s", build_info);
6894 buffer_add_string (buf, version); /* vm version */
6895 buffer_add_int (buf, MAJOR_VERSION);
6896 buffer_add_int (buf, MINOR_VERSION);
6897 g_free (build_info);
6901 case CMD_VM_SET_PROTOCOL_VERSION: {
6902 major_version = decode_int (p, &p, end);
6903 minor_version = decode_int (p, &p, end);
6904 protocol_version_set = TRUE;
6905 DEBUG_PRINTF (1, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version);
6908 case CMD_VM_ALL_THREADS: {
6910 mono_loader_lock ();
6911 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6912 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6913 mono_loader_unlock ();
6916 case CMD_VM_SUSPEND:
6918 wait_for_suspend ();
6921 if (suspend_count == 0)
6922 return ERR_NOT_SUSPENDED;
6924 clear_suspended_objs ();
6926 case CMD_VM_DISPOSE:
6927 /* Clear all event requests */
6928 mono_loader_lock ();
6929 while (event_requests->len > 0) {
6930 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
6932 clear_event_request (req->id, req->event_kind);
6934 mono_loader_unlock ();
6936 while (suspend_count > 0)
6938 disconnected = TRUE;
6939 vm_start_event_sent = FALSE;
6942 MonoInternalThread *thread;
6943 DebuggerTlsData *tls;
6944 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6945 MonoClass *env_class;
6947 MonoMethod *exit_method = NULL;
6951 exit_code = decode_int (p, &p, end);
6953 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6955 /* Have to send a reply before exiting */
6956 send_reply_packet (id, 0, buf);
6958 /* Clear all event requests */
6959 mono_loader_lock ();
6960 while (event_requests->len > 0) {
6961 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
6963 clear_event_request (req->id, req->event_kind);
6965 mono_loader_unlock ();
6968 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6969 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6970 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6971 * better than doing the shutdown ourselves, since it avoids various races.
6975 wait_for_suspend ();
6977 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6978 env_class = mono_class_try_load_from_name (mono_defaults.corlib, "System", "Environment");
6980 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6983 mono_loader_lock ();
6984 thread = (MonoInternalThread *)mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6985 mono_loader_unlock ();
6987 if (thread && exit_method) {
6988 mono_loader_lock ();
6989 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
6990 mono_loader_unlock ();
6992 args = g_new0 (gpointer, 1);
6993 args [0] = g_malloc (sizeof (int));
6994 *(int*)(args [0]) = exit_code;
6996 tls->pending_invoke = g_new0 (InvokeData, 1);
6997 tls->pending_invoke->method = exit_method;
6998 tls->pending_invoke->args = args;
6999 tls->pending_invoke->nmethods = 1;
7001 while (suspend_count > 0)
7005 * No thread found, do it ourselves.
7006 * FIXME: This can race with normal shutdown etc.
7008 while (suspend_count > 0)
7011 if (!mono_runtime_try_shutdown ())
7014 mono_environment_exitcode_set (exit_code);
7016 /* Suspend all managed threads since the runtime is going away */
7017 DEBUG_PRINTF (1, "Suspending all threads...\n");
7018 mono_thread_suspend_all_other_threads ();
7019 DEBUG_PRINTF (1, "Shutting down the runtime...\n");
7020 mono_runtime_quit ();
7021 transport_close2 ();
7022 DEBUG_PRINTF (1, "Exiting...\n");
7028 case CMD_VM_INVOKE_METHOD:
7029 case CMD_VM_INVOKE_METHODS: {
7030 int objid = decode_objid (p, &p, end);
7032 DebuggerTlsData *tls;
7033 int i, count, flags, nmethods;
7036 err = get_object (objid, (MonoObject**)&thread);
7037 if (err != ERR_NONE)
7040 flags = decode_int (p, &p, end);
7042 if (command == CMD_VM_INVOKE_METHODS)
7043 nmethods = decode_int (p, &p, end);
7047 // Wait for suspending if it already started
7049 wait_for_suspend ();
7050 if (!is_suspended ())
7051 return ERR_NOT_SUSPENDED;
7053 mono_loader_lock ();
7054 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7055 mono_loader_unlock ();
7058 if (!tls->really_suspended)
7059 /* The thread is still running native code, can't do invokes */
7060 return ERR_NOT_SUSPENDED;
7063 * Store the invoke data into tls, the thread will execute it after it is
7066 if (tls->pending_invoke)
7067 return ERR_NOT_SUSPENDED;
7068 tls->pending_invoke = g_new0 (InvokeData, 1);
7069 tls->pending_invoke->id = id;
7070 tls->pending_invoke->flags = flags;
7071 tls->pending_invoke->p = (guint8 *)g_malloc (end - p);
7072 memcpy (tls->pending_invoke->p, p, end - p);
7073 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
7074 tls->pending_invoke->suspend_count = suspend_count;
7075 tls->pending_invoke->nmethods = nmethods;
7077 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
7078 resume_thread (THREAD_TO_INTERNAL (thread));
7081 count = suspend_count;
7082 for (i = 0; i < count; ++i)
7087 case CMD_VM_ABORT_INVOKE: {
7088 int objid = decode_objid (p, &p, end);
7090 DebuggerTlsData *tls;
7094 err = get_object (objid, (MonoObject**)&thread);
7095 if (err != ERR_NONE)
7098 invoke_id = decode_int (p, &p, end);
7100 mono_loader_lock ();
7101 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7104 if (tls->abort_requested) {
7105 DEBUG_PRINTF (1, "Abort already requested.\n");
7106 mono_loader_unlock ();
7111 * Check whether we're still inside the mono_runtime_invoke_checked() and that it's
7112 * actually the correct invocation.
7114 * Careful, we do not stop the thread that's doing the invocation, so we can't
7115 * inspect its stack. However, invoke_method() also acquires the loader lock
7116 * when it's done, so we're safe here.
7120 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
7121 mono_loader_unlock ();
7122 return ERR_NO_INVOCATION;
7125 tls->abort_requested = TRUE;
7127 mono_thread_internal_abort (THREAD_TO_INTERNAL (thread));
7128 mono_loader_unlock ();
7132 case CMD_VM_SET_KEEPALIVE: {
7133 int timeout = decode_int (p, &p, end);
7134 agent_config.keepalive = timeout;
7136 #ifndef DISABLE_SOCKET_TRANSPORT
7143 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
7144 GHashTableIter iter, kiter;
7149 char *fname, *basename;
7150 gboolean ignore_case;
7151 GSList *class_list, *l;
7152 GPtrArray *res_classes, *res_domains;
7154 fname = decode_string (p, &p, end);
7155 ignore_case = decode_byte (p, &p, end);
7157 basename = dbg_path_get_basename (fname);
7159 res_classes = g_ptr_array_new ();
7160 res_domains = g_ptr_array_new ();
7162 mono_loader_lock ();
7163 g_hash_table_iter_init (&iter, domains);
7164 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7165 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
7167 /* Update 'source_file_to_class' cache */
7168 g_hash_table_iter_init (&kiter, info->loaded_classes);
7169 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
7170 if (!g_hash_table_lookup (info->source_files, klass)) {
7171 files = get_source_files_for_type (klass);
7172 g_hash_table_insert (info->source_files, klass, files);
7174 for (i = 0; i < files->len; ++i) {
7175 char *s = (char *)g_ptr_array_index (files, i);
7176 char *s2 = dbg_path_get_basename (s);
7179 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, s2);
7181 class_list = g_slist_prepend (class_list, klass);
7182 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
7184 class_list = g_slist_prepend (class_list, klass);
7185 g_hash_table_insert (info->source_file_to_class, s2, class_list);
7188 /* The _ignorecase hash contains the lowercase path */
7189 s3 = strdup_tolower (s2);
7190 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
7192 class_list = g_slist_prepend (class_list, klass);
7193 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
7195 class_list = g_slist_prepend (class_list, klass);
7196 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
7208 s = strdup_tolower (basename);
7209 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
7212 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, basename);
7215 for (l = class_list; l; l = l->next) {
7216 klass = (MonoClass *)l->data;
7218 g_ptr_array_add (res_classes, klass);
7219 g_ptr_array_add (res_domains, domain);
7222 mono_loader_unlock ();
7227 buffer_add_int (buf, res_classes->len);
7228 for (i = 0; i < res_classes->len; ++i)
7229 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7230 g_ptr_array_free (res_classes, TRUE);
7231 g_ptr_array_free (res_domains, TRUE);
7234 case CMD_VM_GET_TYPES: {
7235 GHashTableIter iter;
7239 gboolean ignore_case;
7240 GPtrArray *res_classes, *res_domains;
7241 MonoTypeNameParse info;
7243 name = decode_string (p, &p, end);
7244 ignore_case = decode_byte (p, &p, end);
7246 if (!mono_reflection_parse_type (name, &info)) {
7248 mono_reflection_free_type_info (&info);
7249 return ERR_INVALID_ARGUMENT;
7252 res_classes = g_ptr_array_new ();
7253 res_domains = g_ptr_array_new ();
7255 mono_loader_lock ();
7256 g_hash_table_iter_init (&iter, domains);
7257 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7259 gboolean type_resolve;
7263 mono_domain_assemblies_lock (domain);
7264 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7265 ass = (MonoAssembly *)tmp->data;
7269 type_resolve = TRUE;
7270 /* FIXME really okay to call while holding locks? */
7271 t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignore_case, &type_resolve, &error);
7272 mono_error_cleanup (&error);
7274 g_ptr_array_add (res_classes, mono_type_get_class (t));
7275 g_ptr_array_add (res_domains, domain);
7279 mono_domain_assemblies_unlock (domain);
7281 mono_loader_unlock ();
7284 mono_reflection_free_type_info (&info);
7286 buffer_add_int (buf, res_classes->len);
7287 for (i = 0; i < res_classes->len; ++i)
7288 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7289 g_ptr_array_free (res_classes, TRUE);
7290 g_ptr_array_free (res_domains, TRUE);
7293 case CMD_VM_START_BUFFERING:
7294 case CMD_VM_STOP_BUFFERING:
7295 /* Handled in the main loop */
7298 return ERR_NOT_IMPLEMENTED;
7305 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7311 case CMD_EVENT_REQUEST_SET: {
7313 int i, event_kind, suspend_policy, nmodifiers;
7317 MonoThread *step_thread;
7318 int step_thread_id = 0;
7319 StepDepth depth = STEP_DEPTH_INTO;
7320 StepSize size = STEP_SIZE_MIN;
7321 StepFilter filter = STEP_FILTER_NONE;
7325 event_kind = decode_byte (p, &p, end);
7326 suspend_policy = decode_byte (p, &p, end);
7327 nmodifiers = decode_byte (p, &p, end);
7329 req = (EventRequest *)g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7330 req->id = InterlockedIncrement (&event_request_id);
7331 req->event_kind = event_kind;
7332 req->suspend_policy = suspend_policy;
7333 req->nmodifiers = nmodifiers;
7336 for (i = 0; i < nmodifiers; ++i) {
7337 mod = (ModifierKind)decode_byte (p, &p, end);
7339 req->modifiers [i].kind = mod;
7340 if (mod == MOD_KIND_COUNT) {
7341 req->modifiers [i].data.count = decode_int (p, &p, end);
7342 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7343 method = decode_methodid (p, &p, end, &domain, &err);
7344 if (err != ERR_NONE)
7346 location = decode_long (p, &p, end);
7347 } else if (mod == MOD_KIND_STEP) {
7348 step_thread_id = decode_id (p, &p, end);
7349 size = (StepSize)decode_int (p, &p, end);
7350 depth = (StepDepth)decode_int (p, &p, end);
7351 if (CHECK_PROTOCOL_VERSION (2, 16))
7352 filter = (StepFilter)decode_int (p, &p, end);
7353 req->modifiers [i].data.filter = filter;
7354 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7355 /* Treat STEP_THOUGH the same as HIDDEN */
7356 req->modifiers [i].data.filter = (StepFilter)(req->modifiers [i].data.filter | STEP_FILTER_DEBUGGER_STEP_THROUGH);
7357 } else if (mod == MOD_KIND_THREAD_ONLY) {
7358 int id = decode_id (p, &p, end);
7360 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7361 if (err != ERR_NONE) {
7365 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7366 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7368 if (err != ERR_NONE)
7370 req->modifiers [i].caught = decode_byte (p, &p, end);
7371 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7372 if (CHECK_PROTOCOL_VERSION (2, 25))
7373 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7375 req->modifiers [i].subclasses = TRUE;
7376 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" : "");
7378 req->modifiers [i].data.exc_class = exc_class;
7380 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
7382 return ERR_INVALID_ARGUMENT;
7385 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7386 int n = decode_int (p, &p, end);
7389 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
7390 for (j = 0; j < n; ++j) {
7391 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7392 if (err != ERR_NONE) {
7393 g_free (req->modifiers [i].data.assemblies);
7397 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7398 int n = decode_int (p, &p, end);
7401 modifier = &req->modifiers [i];
7402 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7403 for (j = 0; j < n; ++j) {
7404 char *s = decode_string (p, &p, end);
7408 s2 = strdup_tolower (s);
7409 g_hash_table_insert (modifier->data.source_files, s2, s2);
7413 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7414 int n = decode_int (p, &p, end);
7417 modifier = &req->modifiers [i];
7418 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7419 for (j = 0; j < n; ++j) {
7420 char *s = decode_string (p, &p, end);
7423 g_hash_table_insert (modifier->data.type_names, s, s);
7427 return ERR_NOT_IMPLEMENTED;
7431 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7434 req->info = set_breakpoint (method, location, req, &error);
7435 if (!mono_error_ok (&error)) {
7437 DEBUG_PRINTF (1, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error));
7438 mono_error_cleanup (&error);
7439 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7441 } else if (req->event_kind == EVENT_KIND_STEP) {
7442 g_assert (step_thread_id);
7444 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7445 if (err != ERR_NONE) {
7450 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, filter, req);
7451 if (err != ERR_NONE) {
7455 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7456 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7457 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7458 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7459 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7460 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7462 if (req->nmodifiers) {
7464 return ERR_NOT_IMPLEMENTED;
7468 mono_loader_lock ();
7469 g_ptr_array_add (event_requests, req);
7471 if (agent_config.defer) {
7472 /* Transmit cached data to the client on receipt of the event request */
7473 switch (req->event_kind) {
7474 case EVENT_KIND_APPDOMAIN_CREATE:
7475 /* Emit load events for currently loaded domains */
7476 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7478 case EVENT_KIND_ASSEMBLY_LOAD:
7479 /* Emit load events for currently loaded assemblies */
7480 mono_assembly_foreach (emit_assembly_load, NULL);
7482 case EVENT_KIND_THREAD_START:
7483 /* Emit start events for currently started threads */
7484 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7486 case EVENT_KIND_TYPE_LOAD:
7487 /* Emit type load events for currently loaded types */
7488 mono_domain_foreach (send_types_for_domain, NULL);
7494 mono_loader_unlock ();
7496 buffer_add_int (buf, req->id);
7499 case CMD_EVENT_REQUEST_CLEAR: {
7500 int etype = decode_byte (p, &p, end);
7501 int req_id = decode_int (p, &p, end);
7503 // FIXME: Make a faster mapping from req_id to request
7504 mono_loader_lock ();
7505 clear_event_request (req_id, etype);
7506 mono_loader_unlock ();
7509 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7512 mono_loader_lock ();
7514 while (i < event_requests->len) {
7515 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
7517 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7518 clear_breakpoint ((MonoBreakpoint *)req->info);
7520 g_ptr_array_remove_index_fast (event_requests, i);
7526 mono_loader_unlock ();
7530 return ERR_NOT_IMPLEMENTED;
7537 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7543 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7544 buffer_add_domainid (buf, mono_get_root_domain ());
7547 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7548 domain = decode_domainid (p, &p, end, NULL, &err);
7549 if (err != ERR_NONE)
7551 buffer_add_string (buf, domain->friendly_name);
7554 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7559 domain = decode_domainid (p, &p, end, NULL, &err);
7560 if (err != ERR_NONE)
7562 mono_loader_lock ();
7564 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7567 buffer_add_int (buf, count);
7568 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7569 ass = (MonoAssembly *)tmp->data;
7570 buffer_add_assemblyid (buf, domain, ass);
7572 mono_loader_unlock ();
7575 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7576 domain = decode_domainid (p, &p, end, NULL, &err);
7577 if (err != ERR_NONE)
7580 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7583 case CMD_APPDOMAIN_GET_CORLIB: {
7584 domain = decode_domainid (p, &p, end, NULL, &err);
7585 if (err != ERR_NONE)
7588 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7591 case CMD_APPDOMAIN_CREATE_STRING: {
7595 domain = decode_domainid (p, &p, end, NULL, &err);
7596 if (err != ERR_NONE)
7598 s = decode_string (p, &p, end);
7600 o = mono_string_new (domain, s);
7601 buffer_add_objid (buf, (MonoObject*)o);
7604 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7607 MonoDomain *domain2;
7610 domain = decode_domainid (p, &p, end, NULL, &err);
7611 if (err != ERR_NONE)
7613 klass = decode_typeid (p, &p, end, &domain2, &err);
7614 if (err != ERR_NONE)
7618 g_assert (domain == domain2);
7620 o = mono_object_new_checked (domain, klass, &error);
7621 mono_error_assert_ok (&error);
7623 err = decode_value (&klass->byval_arg, domain, (guint8 *)mono_object_unbox (o), p, &p, end);
7624 if (err != ERR_NONE)
7627 buffer_add_objid (buf, o);
7631 return ERR_NOT_IMPLEMENTED;
7638 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7644 ass = decode_assemblyid (p, &p, end, &domain, &err);
7645 if (err != ERR_NONE)
7649 case CMD_ASSEMBLY_GET_LOCATION: {
7650 buffer_add_string (buf, mono_image_get_filename (ass->image));
7653 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7657 if (ass->image->dynamic) {
7658 buffer_add_id (buf, 0);
7660 token = mono_image_get_entry_point (ass->image);
7662 buffer_add_id (buf, 0);
7665 m = mono_get_method_checked (ass->image, token, NULL, NULL, &error);
7667 mono_error_cleanup (&error); /* FIXME don't swallow the error */
7668 buffer_add_methodid (buf, domain, m);
7673 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7674 buffer_add_moduleid (buf, domain, ass->image);
7677 case CMD_ASSEMBLY_GET_OBJECT: {
7679 MonoObject *o = (MonoObject*)mono_assembly_get_object_checked (domain, ass, &error);
7681 mono_error_cleanup (&error); /* FIXME don't swallow the error */
7682 return ERR_INVALID_OBJECT;
7684 buffer_add_objid (buf, o);
7687 case CMD_ASSEMBLY_GET_TYPE: {
7689 char *s = decode_string (p, &p, end);
7690 gboolean ignorecase = decode_byte (p, &p, end);
7691 MonoTypeNameParse info;
7693 gboolean type_resolve, res;
7694 MonoDomain *d = mono_domain_get ();
7696 /* This is needed to be able to find referenced assemblies */
7697 res = mono_domain_set (domain, FALSE);
7700 if (!mono_reflection_parse_type (s, &info)) {
7703 if (info.assembly.name)
7705 t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignorecase, &type_resolve, &error);
7706 if (!is_ok (&error)) {
7707 mono_error_cleanup (&error); /* FIXME don't swallow the error */
7708 mono_reflection_free_type_info (&info);
7710 return ERR_INVALID_ARGUMENT;
7713 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
7714 mono_reflection_free_type_info (&info);
7717 mono_domain_set (d, TRUE);
7721 case CMD_ASSEMBLY_GET_NAME: {
7723 MonoAssembly *mass = ass;
7725 name = g_strdup_printf (
7726 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7728 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7729 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7730 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7731 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7733 buffer_add_string (buf, name);
7738 return ERR_NOT_IMPLEMENTED;
7745 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7751 case CMD_MODULE_GET_INFO: {
7752 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7755 basename = g_path_get_basename (image->name);
7756 buffer_add_string (buf, basename); // name
7757 buffer_add_string (buf, image->module_name); // scopename
7758 buffer_add_string (buf, image->name); // fqname
7759 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7760 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7765 return ERR_NOT_IMPLEMENTED;
7772 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7778 case CMD_FIELD_GET_INFO: {
7779 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
7781 buffer_add_string (buf, f->name);
7782 buffer_add_typeid (buf, domain, f->parent);
7783 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7784 buffer_add_int (buf, f->type->attrs);
7788 return ERR_NOT_IMPLEMENTED;
7795 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7797 if (val && val->vtable->klass == mono_defaults.runtimetype_class) {
7798 /* Special case these so the client doesn't have to handle Type objects */
7800 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7801 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7802 } else if (MONO_TYPE_IS_REFERENCE (t))
7803 buffer_add_value (buf, t, &val, domain);
7805 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7809 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7815 buffer_add_int (buf, 0);
7819 for (i = 0; i < cinfo->num_attrs; ++i) {
7820 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7823 buffer_add_int (buf, nattrs);
7825 for (i = 0; i < cinfo->num_attrs; ++i) {
7826 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7827 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7828 MonoArray *typed_args, *named_args;
7830 CattrNamedArg *arginfo = NULL;
7833 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
7834 if (!mono_error_ok (&error)) {
7835 DEBUG_PRINTF (2, "[dbg] mono_reflection_create_custom_attr_data_args () failed with: '%s'\n", mono_error_get_message (&error));
7836 mono_error_cleanup (&error);
7837 return ERR_LOADER_ERROR;
7840 buffer_add_methodid (buf, domain, attr->ctor);
7844 buffer_add_int (buf, mono_array_length (typed_args));
7845 for (j = 0; j < mono_array_length (typed_args); ++j) {
7846 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7848 t = mono_method_signature (attr->ctor)->params [j];
7850 buffer_add_cattr_arg (buf, t, domain, val);
7853 buffer_add_int (buf, 0);
7858 buffer_add_int (buf, mono_array_length (named_args));
7860 for (j = 0; j < mono_array_length (named_args); ++j) {
7861 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7863 if (arginfo [j].prop) {
7864 buffer_add_byte (buf, 0x54);
7865 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7866 } else if (arginfo [j].field) {
7867 buffer_add_byte (buf, 0x53);
7868 buffer_add_fieldid (buf, domain, arginfo [j].field);
7870 g_assert_not_reached ();
7873 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7876 buffer_add_int (buf, 0);
7885 /* FIXME: Code duplication with icall.c */
7887 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7892 mono_class_setup_interfaces (klass, error);
7893 if (!mono_error_ok (error))
7896 for (i = 0; i < klass->interface_count; i++) {
7897 ic = klass->interfaces [i];
7898 g_hash_table_insert (ifaces, ic, ic);
7900 collect_interfaces (ic, ifaces, error);
7901 if (!mono_error_ok (error))
7907 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7919 case CMD_TYPE_GET_INFO: {
7920 buffer_add_string (buf, klass->name_space);
7921 buffer_add_string (buf, klass->name);
7923 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7924 buffer_add_string (buf, name);
7926 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7927 buffer_add_moduleid (buf, domain, klass->image);
7928 buffer_add_typeid (buf, domain, klass->parent);
7929 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7930 buffer_add_typeid (buf, domain, klass->element_class);
7932 buffer_add_id (buf, 0);
7933 buffer_add_int (buf, klass->type_token);
7934 buffer_add_byte (buf, klass->rank);
7935 buffer_add_int (buf, klass->flags);
7937 type = &klass->byval_arg;
7938 // FIXME: Can't decide whenever a class represents a byref type
7941 if (type->type == MONO_TYPE_PTR)
7943 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7945 if (type->type == MONO_TYPE_VALUETYPE)
7947 if (klass->enumtype)
7949 if (klass->generic_container)
7951 if (klass->generic_container || klass->generic_class)
7953 buffer_add_byte (buf, b);
7956 while ((nested = mono_class_get_nested_types (klass, &iter)))
7958 buffer_add_int (buf, nnested);
7960 while ((nested = mono_class_get_nested_types (klass, &iter)))
7961 buffer_add_typeid (buf, domain, nested);
7962 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7963 if (klass->generic_container)
7964 buffer_add_typeid (buf, domain, klass);
7965 else if (klass->generic_class)
7966 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7968 buffer_add_id (buf, 0);
7970 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7973 if (klass->generic_class) {
7974 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7976 count = inst->type_argc;
7977 buffer_add_int (buf, count);
7978 for (i = 0; i < count; i++)
7979 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7980 } else if (klass->generic_container) {
7981 MonoGenericContainer *container = klass->generic_container;
7984 count = container->type_argc;
7985 buffer_add_int (buf, count);
7986 for (i = 0; i < count; i++) {
7987 pklass = mono_class_from_generic_parameter_internal (mono_generic_container_get_param (container, i));
7988 buffer_add_typeid (buf, domain, pklass);
7991 buffer_add_int (buf, 0);
7996 case CMD_TYPE_GET_METHODS: {
7999 gpointer iter = NULL;
8002 mono_class_setup_methods (klass);
8004 nmethods = mono_class_num_methods (klass);
8006 buffer_add_int (buf, nmethods);
8008 while ((m = mono_class_get_methods (klass, &iter))) {
8009 buffer_add_methodid (buf, domain, m);
8012 g_assert (i == nmethods);
8015 case CMD_TYPE_GET_FIELDS: {
8018 gpointer iter = NULL;
8021 nfields = mono_class_num_fields (klass);
8023 buffer_add_int (buf, nfields);
8025 while ((f = mono_class_get_fields (klass, &iter))) {
8026 buffer_add_fieldid (buf, domain, f);
8027 buffer_add_string (buf, f->name);
8028 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
8029 buffer_add_int (buf, f->type->attrs);
8032 g_assert (i == nfields);
8035 case CMD_TYPE_GET_PROPERTIES: {
8038 gpointer iter = NULL;
8041 nprops = mono_class_num_properties (klass);
8043 buffer_add_int (buf, nprops);
8045 while ((p = mono_class_get_properties (klass, &iter))) {
8046 buffer_add_propertyid (buf, domain, p);
8047 buffer_add_string (buf, p->name);
8048 buffer_add_methodid (buf, domain, p->get);
8049 buffer_add_methodid (buf, domain, p->set);
8050 buffer_add_int (buf, p->attrs);
8053 g_assert (i == nprops);
8056 case CMD_TYPE_GET_CATTRS: {
8057 MonoClass *attr_klass;
8058 MonoCustomAttrInfo *cinfo;
8060 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8061 /* attr_klass can be NULL */
8062 if (err != ERR_NONE)
8065 cinfo = mono_custom_attrs_from_class_checked (klass, &error);
8066 if (!is_ok (&error)) {
8067 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8068 return ERR_LOADER_ERROR;
8071 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8072 if (err != ERR_NONE)
8076 case CMD_TYPE_GET_FIELD_CATTRS: {
8077 MonoClass *attr_klass;
8078 MonoCustomAttrInfo *cinfo;
8079 MonoClassField *field;
8081 field = decode_fieldid (p, &p, end, NULL, &err);
8082 if (err != ERR_NONE)
8084 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8085 if (err != ERR_NONE)
8088 cinfo = mono_custom_attrs_from_field_checked (klass, field, &error);
8089 if (!is_ok (&error)) {
8090 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8091 return ERR_LOADER_ERROR;
8094 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8095 if (err != ERR_NONE)
8099 case CMD_TYPE_GET_PROPERTY_CATTRS: {
8100 MonoClass *attr_klass;
8101 MonoCustomAttrInfo *cinfo;
8104 prop = decode_propertyid (p, &p, end, NULL, &err);
8105 if (err != ERR_NONE)
8107 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8108 if (err != ERR_NONE)
8111 cinfo = mono_custom_attrs_from_property_checked (klass, prop, &error);
8112 if (!is_ok (&error)) {
8113 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8114 return ERR_LOADER_ERROR;
8117 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8118 if (err != ERR_NONE)
8122 case CMD_TYPE_GET_VALUES:
8123 case CMD_TYPE_GET_VALUES_2: {
8130 MonoThread *thread_obj;
8131 MonoInternalThread *thread = NULL;
8132 guint32 special_static_type;
8134 if (command == CMD_TYPE_GET_VALUES_2) {
8135 int objid = decode_objid (p, &p, end);
8138 err = get_object (objid, (MonoObject**)&thread_obj);
8139 if (err != ERR_NONE)
8142 thread = THREAD_TO_INTERNAL (thread_obj);
8145 len = decode_int (p, &p, end);
8146 for (i = 0; i < len; ++i) {
8147 f = decode_fieldid (p, &p, end, NULL, &err);
8148 if (err != ERR_NONE)
8151 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8152 return ERR_INVALID_FIELDID;
8153 special_static_type = mono_class_field_get_special_static_type (f);
8154 if (special_static_type != SPECIAL_STATIC_NONE) {
8155 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
8156 return ERR_INVALID_FIELDID;
8159 /* Check that the field belongs to the object */
8161 for (k = klass; k; k = k->parent) {
8162 if (k == f->parent) {
8168 return ERR_INVALID_FIELDID;
8170 vtable = mono_class_vtable (domain, f->parent);
8171 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8172 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val, &error);
8173 if (!is_ok (&error))
8174 return ERR_INVALID_FIELDID;
8175 buffer_add_value (buf, f->type, val, domain);
8180 case CMD_TYPE_SET_VALUES: {
8188 len = decode_int (p, &p, end);
8189 for (i = 0; i < len; ++i) {
8190 f = decode_fieldid (p, &p, end, NULL, &err);
8191 if (err != ERR_NONE)
8194 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8195 return ERR_INVALID_FIELDID;
8196 if (mono_class_field_is_special_static (f))
8197 return ERR_INVALID_FIELDID;
8199 /* Check that the field belongs to the object */
8201 for (k = klass; k; k = k->parent) {
8202 if (k == f->parent) {
8208 return ERR_INVALID_FIELDID;
8210 // FIXME: Check for literal/const
8212 vtable = mono_class_vtable (domain, f->parent);
8213 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8214 err = decode_value (f->type, domain, val, p, &p, end);
8215 if (err != ERR_NONE) {
8219 if (MONO_TYPE_IS_REFERENCE (f->type))
8220 mono_field_static_set_value (vtable, f, *(gpointer*)val);
8222 mono_field_static_set_value (vtable, f, val);
8227 case CMD_TYPE_GET_OBJECT: {
8228 MonoObject *o = (MonoObject*)mono_type_get_object_checked (domain, &klass->byval_arg, &error);
8229 if (!mono_error_ok (&error)) {
8230 mono_error_cleanup (&error);
8231 return ERR_INVALID_OBJECT;
8233 buffer_add_objid (buf, o);
8236 case CMD_TYPE_GET_SOURCE_FILES:
8237 case CMD_TYPE_GET_SOURCE_FILES_2: {
8238 char *source_file, *base;
8242 files = get_source_files_for_type (klass);
8244 buffer_add_int (buf, files->len);
8245 for (i = 0; i < files->len; ++i) {
8246 source_file = (char *)g_ptr_array_index (files, i);
8247 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8248 buffer_add_string (buf, source_file);
8250 base = dbg_path_get_basename (source_file);
8251 buffer_add_string (buf, base);
8254 g_free (source_file);
8256 g_ptr_array_free (files, TRUE);
8259 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8260 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8262 if (err != ERR_NONE)
8264 if (mono_class_is_assignable_from (klass, oklass))
8265 buffer_add_byte (buf, 1);
8267 buffer_add_byte (buf, 0);
8270 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8271 char *name = decode_string (p, &p, end);
8272 int i, flags = decode_int (p, &p, end);
8273 MonoException *ex = NULL;
8274 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
8277 return ERR_LOADER_ERROR;
8278 buffer_add_int (buf, array->len);
8279 for (i = 0; i < array->len; ++i) {
8280 MonoMethod *method = (MonoMethod *)g_ptr_array_index (array, i);
8281 buffer_add_methodid (buf, domain, method);
8284 g_ptr_array_free (array, TRUE);
8288 case CMD_TYPE_GET_INTERFACES: {
8290 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8291 MonoClass *tclass, *iface;
8292 GHashTableIter iter;
8296 for (parent = tclass; parent; parent = parent->parent) {
8297 mono_class_setup_interfaces (parent, &error);
8298 if (!mono_error_ok (&error))
8299 return ERR_LOADER_ERROR;
8300 collect_interfaces (parent, iface_hash, &error);
8301 if (!mono_error_ok (&error))
8302 return ERR_LOADER_ERROR;
8305 buffer_add_int (buf, g_hash_table_size (iface_hash));
8307 g_hash_table_iter_init (&iter, iface_hash);
8308 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8309 buffer_add_typeid (buf, domain, iface);
8310 g_hash_table_destroy (iface_hash);
8313 case CMD_TYPE_GET_INTERFACE_MAP: {
8314 int tindex, ioffset;
8315 gboolean variance_used;
8317 int len, nmethods, i;
8321 len = decode_int (p, &p, end);
8322 mono_class_setup_vtable (klass);
8324 for (tindex = 0; tindex < len; ++tindex) {
8325 iclass = decode_typeid (p, &p, end, NULL, &err);
8326 if (err != ERR_NONE)
8329 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8331 return ERR_INVALID_ARGUMENT;
8333 nmethods = mono_class_num_methods (iclass);
8334 buffer_add_int (buf, nmethods);
8337 while ((method = mono_class_get_methods (iclass, &iter))) {
8338 buffer_add_methodid (buf, domain, method);
8340 for (i = 0; i < nmethods; ++i)
8341 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
8345 case CMD_TYPE_IS_INITIALIZED: {
8346 MonoVTable *vtable = mono_class_vtable (domain, klass);
8349 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8351 buffer_add_int (buf, 0);
8354 case CMD_TYPE_CREATE_INSTANCE: {
8358 obj = mono_object_new_checked (domain, klass, &error);
8359 mono_error_assert_ok (&error);
8360 buffer_add_objid (buf, obj);
8364 return ERR_NOT_IMPLEMENTED;
8371 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8374 MonoDomain *old_domain;
8378 klass = decode_typeid (p, &p, end, &domain, &err);
8379 if (err != ERR_NONE)
8382 old_domain = mono_domain_get ();
8384 mono_domain_set (domain, TRUE);
8386 err = type_commands_internal (command, klass, domain, p, end, buf);
8388 mono_domain_set (old_domain, TRUE);
8394 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8396 MonoMethodHeader *header;
8400 case CMD_METHOD_GET_NAME: {
8401 buffer_add_string (buf, method->name);
8404 case CMD_METHOD_GET_DECLARING_TYPE: {
8405 buffer_add_typeid (buf, domain, method->klass);
8408 case CMD_METHOD_GET_DEBUG_INFO: {
8410 MonoDebugMethodInfo *minfo;
8412 int i, j, n_il_offsets;
8414 GPtrArray *source_file_list;
8415 MonoSymSeqPoint *sym_seq_points;
8417 header = mono_method_get_header_checked (method, &error);
8419 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8420 buffer_add_int (buf, 0);
8421 buffer_add_string (buf, "");
8422 buffer_add_int (buf, 0);
8426 minfo = mono_debug_lookup_method (method);
8428 buffer_add_int (buf, header->code_size);
8429 buffer_add_string (buf, "");
8430 buffer_add_int (buf, 0);
8431 mono_metadata_free_mh (header);
8435 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, &source_files, &sym_seq_points, &n_il_offsets);
8436 buffer_add_int (buf, header->code_size);
8437 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8438 buffer_add_int (buf, source_file_list->len);
8439 for (i = 0; i < source_file_list->len; ++i) {
8440 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
8441 buffer_add_string (buf, sinfo->source_file);
8442 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8443 for (j = 0; j < 16; ++j)
8444 buffer_add_byte (buf, sinfo->hash [j]);
8448 buffer_add_string (buf, source_file);
8450 buffer_add_int (buf, n_il_offsets);
8451 DEBUG_PRINTF (10, "Line number table for method %s:\n", mono_method_full_name (method, TRUE));
8452 for (i = 0; i < n_il_offsets; ++i) {
8453 MonoSymSeqPoint *sp = &sym_seq_points [i];
8454 const char *srcfile = "";
8456 if (source_files [i] != -1) {
8457 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, source_files [i]);
8458 srcfile = sinfo->source_file;
8460 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);
8461 buffer_add_int (buf, sp->il_offset);
8462 buffer_add_int (buf, sp->line);
8463 if (CHECK_PROTOCOL_VERSION (2, 13))
8464 buffer_add_int (buf, source_files [i]);
8465 if (CHECK_PROTOCOL_VERSION (2, 19))
8466 buffer_add_int (buf, sp->column);
8467 if (CHECK_PROTOCOL_VERSION (2, 32)) {
8468 buffer_add_int (buf, sp->end_line);
8469 buffer_add_int (buf, sp->end_column);
8472 g_free (source_file);
8473 g_free (source_files);
8474 g_free (sym_seq_points);
8475 g_ptr_array_free (source_file_list, TRUE);
8476 mono_metadata_free_mh (header);
8479 case CMD_METHOD_GET_PARAM_INFO: {
8480 MonoMethodSignature *sig = mono_method_signature (method);
8484 /* FIXME: mono_class_from_mono_type () and byrefs */
8486 /* FIXME: Use a smaller encoding */
8487 buffer_add_int (buf, sig->call_convention);
8488 buffer_add_int (buf, sig->param_count);
8489 buffer_add_int (buf, sig->generic_param_count);
8490 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
8491 for (i = 0; i < sig->param_count; ++i) {
8493 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
8496 /* Emit parameter names */
8497 names = g_new (char *, sig->param_count);
8498 mono_method_get_param_names (method, (const char **) names);
8499 for (i = 0; i < sig->param_count; ++i)
8500 buffer_add_string (buf, names [i]);
8505 case CMD_METHOD_GET_LOCALS_INFO: {
8508 MonoDebugLocalsInfo *locals;
8509 int *locals_map = NULL;
8511 header = mono_method_get_header_checked (method, &error);
8513 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8514 return ERR_INVALID_ARGUMENT;
8517 locals = mono_debug_lookup_locals (method);
8519 buffer_add_int (buf, header->num_locals);
8521 for (i = 0; i < header->num_locals; ++i) {
8522 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
8525 for (i = 0; i < header->num_locals; ++i) {
8527 sprintf (lname, "V_%d", i);
8528 buffer_add_string (buf, lname);
8531 for (i = 0; i < header->num_locals; ++i) {
8532 buffer_add_int (buf, 0);
8533 buffer_add_int (buf, header->code_size);
8536 num_locals = locals->num_locals;
8537 buffer_add_int (buf, num_locals);
8540 for (i = 0; i < num_locals; ++i) {
8541 g_assert (locals->locals [i].index < header->num_locals);
8542 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [locals->locals [i].index]));
8545 for (i = 0; i < num_locals; ++i)
8546 buffer_add_string (buf, locals->locals [i].name);
8548 for (i = 0; i < num_locals; ++i) {
8549 if (locals->locals [i].block) {
8550 buffer_add_int (buf, locals->locals [i].block->start_offset);
8551 buffer_add_int (buf, locals->locals [i].block->end_offset);
8553 buffer_add_int (buf, 0);
8554 buffer_add_int (buf, header->code_size);
8558 mono_metadata_free_mh (header);
8561 mono_debug_free_locals (locals);
8562 g_free (locals_map);
8566 case CMD_METHOD_GET_INFO:
8567 buffer_add_int (buf, method->flags);
8568 buffer_add_int (buf, method->iflags);
8569 buffer_add_int (buf, method->token);
8570 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8572 if (method->is_generic)
8574 if (mono_method_signature (method)->generic_param_count)
8576 buffer_add_byte (buf, attrs);
8577 if (method->is_generic || method->is_inflated) {
8580 if (method->is_generic) {
8583 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8585 result = imethod->declaring;
8586 if (imethod->context.class_inst) {
8587 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8588 /*Generic methods gets the context of the GTD.*/
8589 if (mono_class_get_context (klass)) {
8591 result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), &error);
8592 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8597 buffer_add_methodid (buf, domain, result);
8599 buffer_add_id (buf, 0);
8601 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8602 if (mono_method_signature (method)->generic_param_count) {
8605 if (method->is_inflated) {
8606 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
8608 count = inst->type_argc;
8609 buffer_add_int (buf, count);
8611 for (i = 0; i < count; i++)
8612 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8614 buffer_add_int (buf, 0);
8616 } else if (method->is_generic) {
8617 MonoGenericContainer *container = mono_method_get_generic_container (method);
8619 count = mono_method_signature (method)->generic_param_count;
8620 buffer_add_int (buf, count);
8621 for (i = 0; i < count; i++) {
8622 MonoGenericParam *param = mono_generic_container_get_param (container, i);
8623 MonoClass *pklass = mono_class_from_generic_parameter_internal (param);
8624 buffer_add_typeid (buf, domain, pklass);
8627 buffer_add_int (buf, 0);
8630 buffer_add_int (buf, 0);
8635 case CMD_METHOD_GET_BODY: {
8639 header = mono_method_get_header_checked (method, &error);
8641 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8642 buffer_add_int (buf, 0);
8644 if (CHECK_PROTOCOL_VERSION (2, 18))
8645 buffer_add_int (buf, 0);
8647 buffer_add_int (buf, header->code_size);
8648 for (i = 0; i < header->code_size; ++i)
8649 buffer_add_byte (buf, header->code [i]);
8651 if (CHECK_PROTOCOL_VERSION (2, 18)) {
8652 buffer_add_int (buf, header->num_clauses);
8653 for (i = 0; i < header->num_clauses; ++i) {
8654 MonoExceptionClause *clause = &header->clauses [i];
8656 buffer_add_int (buf, clause->flags);
8657 buffer_add_int (buf, clause->try_offset);
8658 buffer_add_int (buf, clause->try_len);
8659 buffer_add_int (buf, clause->handler_offset);
8660 buffer_add_int (buf, clause->handler_len);
8661 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
8662 buffer_add_typeid (buf, domain, clause->data.catch_class);
8663 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8664 buffer_add_int (buf, clause->data.filter_offset);
8668 mono_metadata_free_mh (header);
8673 case CMD_METHOD_RESOLVE_TOKEN: {
8674 guint32 token = decode_int (p, &p, end);
8677 switch (mono_metadata_token_code (token)) {
8678 case MONO_TOKEN_STRING: {
8683 s = mono_ldstr_checked (domain, method->klass->image, mono_metadata_token_index (token), &error);
8684 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
8686 s2 = mono_string_to_utf8 (s);
8688 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8689 buffer_add_string (buf, s2);
8695 MonoClass *handle_class;
8697 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8698 val = mono_method_get_wrapper_data (method, token);
8699 handle_class = (MonoClass *)mono_method_get_wrapper_data (method, token + 1);
8701 if (handle_class == NULL) {
8702 // Can't figure out the token type
8703 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8708 val = mono_ldtoken_checked (method->klass->image, token, &handle_class, NULL, &error);
8710 g_error ("Could not load token due to %s", mono_error_get_message (&error));
8713 if (handle_class == mono_defaults.typehandle_class) {
8714 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8715 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8716 buffer_add_typeid (buf, domain, (MonoClass *) val);
8718 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
8719 } else if (handle_class == mono_defaults.fieldhandle_class) {
8720 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8721 buffer_add_fieldid (buf, domain, (MonoClassField *)val);
8722 } else if (handle_class == mono_defaults.methodhandle_class) {
8723 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8724 buffer_add_methodid (buf, domain, (MonoMethod *)val);
8725 } else if (handle_class == mono_defaults.string_class) {
8728 s = mono_string_to_utf8 ((MonoString *)val);
8729 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8730 buffer_add_string (buf, s);
8733 g_assert_not_reached ();
8740 case CMD_METHOD_GET_CATTRS: {
8742 MonoClass *attr_klass;
8743 MonoCustomAttrInfo *cinfo;
8745 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8746 /* attr_klass can be NULL */
8747 if (err != ERR_NONE)
8750 cinfo = mono_custom_attrs_from_method_checked (method, &error);
8751 if (!is_ok (&error)) {
8752 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8753 return ERR_LOADER_ERROR;
8756 err = buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
8757 if (err != ERR_NONE)
8761 case CMD_METHOD_MAKE_GENERIC_METHOD: {
8763 MonoType **type_argv;
8767 MonoGenericInst *ginst;
8768 MonoGenericContext tmp_context;
8769 MonoMethod *inflated;
8771 type_argc = decode_int (p, &p, end);
8772 type_argv = g_new0 (MonoType*, type_argc);
8773 for (i = 0; i < type_argc; ++i) {
8774 klass = decode_typeid (p, &p, end, &d, &err);
8775 if (err != ERR_NONE) {
8781 return ERR_INVALID_ARGUMENT;
8783 type_argv [i] = &klass->byval_arg;
8785 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
8787 tmp_context.class_inst = method->klass->generic_class ? method->klass->generic_class->context.class_inst : NULL;
8788 tmp_context.method_inst = ginst;
8790 inflated = mono_class_inflate_generic_method_checked (method, &tmp_context, &error);
8791 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8792 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
8793 return ERR_INVALID_ARGUMENT;
8794 buffer_add_methodid (buf, domain, inflated);
8798 return ERR_NOT_IMPLEMENTED;
8805 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8808 MonoDomain *old_domain;
8812 method = decode_methodid (p, &p, end, &domain, &err);
8813 if (err != ERR_NONE)
8816 old_domain = mono_domain_get ();
8818 mono_domain_set (domain, TRUE);
8820 err = method_commands_internal (command, method, domain, p, end, buf);
8822 mono_domain_set (old_domain, TRUE);
8828 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8830 int objid = decode_objid (p, &p, end);
8832 MonoThread *thread_obj;
8833 MonoInternalThread *thread;
8835 err = get_object (objid, (MonoObject**)&thread_obj);
8836 if (err != ERR_NONE)
8839 thread = THREAD_TO_INTERNAL (thread_obj);
8842 case CMD_THREAD_GET_NAME: {
8844 gunichar2 *s = mono_thread_get_name (thread, &name_len);
8847 buffer_add_int (buf, 0);
8852 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
8854 buffer_add_int (buf, len);
8855 buffer_add_data (buf, (guint8*)name, len);
8860 case CMD_THREAD_GET_FRAME_INFO: {
8861 DebuggerTlsData *tls;
8862 int i, start_frame, length;
8864 // Wait for suspending if it already started
8865 // FIXME: Races with suspend_count
8866 while (!is_suspended ()) {
8868 wait_for_suspend ();
8872 wait_for_suspend ();
8873 if (!is_suspended ())
8874 return ERR_NOT_SUSPENDED;
8877 start_frame = decode_int (p, &p, end);
8878 length = decode_int (p, &p, end);
8880 if (start_frame != 0 || length != -1)
8881 return ERR_NOT_IMPLEMENTED;
8883 mono_loader_lock ();
8884 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
8885 mono_loader_unlock ();
8888 compute_frame_info (thread, tls);
8890 buffer_add_int (buf, tls->frame_count);
8891 for (i = 0; i < tls->frame_count; ++i) {
8892 buffer_add_int (buf, tls->frames [i]->id);
8893 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
8894 buffer_add_int (buf, tls->frames [i]->il_offset);
8896 * Instead of passing the frame type directly to the client, we associate
8897 * it with the previous frame using a set of flags. This avoids lots of
8898 * conditional code in the client, since a frame whose type isn't
8899 * FRAME_TYPE_MANAGED has no method, location, etc.
8901 buffer_add_byte (buf, tls->frames [i]->flags);
8906 case CMD_THREAD_GET_STATE:
8907 buffer_add_int (buf, thread->state);
8909 case CMD_THREAD_GET_INFO:
8910 buffer_add_byte (buf, thread->threadpool_thread);
8912 case CMD_THREAD_GET_ID:
8913 buffer_add_long (buf, (guint64)(gsize)thread);
8915 case CMD_THREAD_GET_TID:
8916 buffer_add_long (buf, (guint64)thread->tid);
8918 case CMD_THREAD_SET_IP: {
8919 DebuggerTlsData *tls;
8922 MonoSeqPointInfo *seq_points;
8927 method = decode_methodid (p, &p, end, &domain, &err);
8928 if (err != ERR_NONE)
8930 il_offset = decode_long (p, &p, end);
8932 while (!is_suspended ()) {
8934 wait_for_suspend ();
8937 mono_loader_lock ();
8938 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
8939 mono_loader_unlock ();
8942 compute_frame_info (thread, tls);
8943 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
8944 return ERR_INVALID_ARGUMENT;
8946 found_sp = mono_find_seq_point (domain, method, il_offset, &seq_points, &sp);
8948 g_assert (seq_points);
8951 return ERR_INVALID_ARGUMENT;
8953 // FIXME: Check that the ip change is safe
8955 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);
8956 MONO_CONTEXT_SET_IP (&tls->restore_state.ctx, (guint8*)tls->frames [0]->ji->code_start + sp.native_offset);
8960 return ERR_NOT_IMPLEMENTED;
8967 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8971 MonoThread *thread_obj;
8972 MonoInternalThread *thread;
8973 int pos, i, len, frame_idx;
8974 DebuggerTlsData *tls;
8976 MonoDebugMethodJitInfo *jit;
8977 MonoMethodSignature *sig;
8979 MonoMethodHeader *header;
8981 objid = decode_objid (p, &p, end);
8982 err = get_object (objid, (MonoObject**)&thread_obj);
8983 if (err != ERR_NONE)
8986 thread = THREAD_TO_INTERNAL (thread_obj);
8988 id = decode_id (p, &p, end);
8990 mono_loader_lock ();
8991 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
8992 mono_loader_unlock ();
8995 for (i = 0; i < tls->frame_count; ++i) {
8996 if (tls->frames [i]->id == id)
8999 if (i == tls->frame_count)
9000 return ERR_INVALID_FRAMEID;
9003 frame = tls->frames [frame_idx];
9005 /* This is supported for frames without has_ctx etc. set */
9006 if (command == CMD_STACK_FRAME_GET_DOMAIN) {
9007 if (CHECK_PROTOCOL_VERSION (2, 38))
9008 buffer_add_domainid (buf, frame->domain);
9012 if (!frame->has_ctx)
9013 return ERR_ABSENT_INFORMATION;
9016 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
9017 if (!frame->jit && frame->api_method->is_inflated)
9018 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
9022 /* This could happen for aot images with no jit debug info */
9023 s = mono_method_full_name (frame->api_method, TRUE);
9024 DEBUG_PRINTF (1, "[dbg] No debug information found for '%s'.\n", s);
9026 return ERR_ABSENT_INFORMATION;
9031 sig = mono_method_signature (frame->actual_method);
9033 if (!mono_get_seq_points (frame->domain, frame->actual_method))
9035 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
9037 return ERR_ABSENT_INFORMATION;
9040 case CMD_STACK_FRAME_GET_VALUES: {
9042 len = decode_int (p, &p, end);
9043 header = mono_method_get_header_checked (frame->actual_method, &error);
9044 mono_error_assert_ok (&error); /* FIXME report error */
9046 for (i = 0; i < len; ++i) {
9047 pos = decode_int (p, &p, end);
9052 DEBUG_PRINTF (4, "[dbg] send arg %d.\n", pos);
9054 g_assert (pos >= 0 && pos < jit->num_params);
9056 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
9058 MonoDebugLocalsInfo *locals;
9060 locals = mono_debug_lookup_locals (frame->method);
9062 g_assert (pos < locals->num_locals);
9063 pos = locals->locals [pos].index;
9064 mono_debug_free_locals (locals);
9066 g_assert (pos >= 0 && pos < jit->num_locals);
9068 DEBUG_PRINTF (4, "[dbg] send local %d.\n", pos);
9070 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
9073 mono_metadata_free_mh (header);
9076 case CMD_STACK_FRAME_GET_THIS: {
9077 if (frame->api_method->klass->valuetype) {
9078 if (!sig->hasthis) {
9079 MonoObject *p = NULL;
9080 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
9082 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9085 if (!sig->hasthis) {
9086 MonoObject *p = NULL;
9087 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
9089 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9094 case CMD_STACK_FRAME_SET_VALUES: {
9098 MonoDebugVarInfo *var;
9100 len = decode_int (p, &p, end);
9101 header = mono_method_get_header_checked (frame->actual_method, &error);
9102 mono_error_assert_ok (&error); /* FIXME report error */
9104 for (i = 0; i < len; ++i) {
9105 pos = decode_int (p, &p, end);
9110 g_assert (pos >= 0 && pos < jit->num_params);
9112 t = sig->params [pos];
9113 var = &jit->params [pos];
9115 MonoDebugLocalsInfo *locals;
9117 locals = mono_debug_lookup_locals (frame->method);
9119 g_assert (pos < locals->num_locals);
9120 pos = locals->locals [pos].index;
9121 mono_debug_free_locals (locals);
9123 g_assert (pos >= 0 && pos < jit->num_locals);
9125 t = header->locals [pos];
9126 var = &jit->locals [pos];
9129 if (MONO_TYPE_IS_REFERENCE (t))
9130 val_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
9132 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9133 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9134 if (err != ERR_NONE)
9137 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9139 mono_metadata_free_mh (header);
9142 case CMD_STACK_FRAME_GET_DOMAIN: {
9143 if (CHECK_PROTOCOL_VERSION (2, 38))
9144 buffer_add_domainid (buf, frame->domain);
9148 return ERR_NOT_IMPLEMENTED;
9155 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9158 int objid, index, len, i, esize;
9162 objid = decode_objid (p, &p, end);
9163 err = get_object (objid, (MonoObject**)&arr);
9164 if (err != ERR_NONE)
9168 case CMD_ARRAY_REF_GET_LENGTH:
9169 buffer_add_int (buf, arr->obj.vtable->klass->rank);
9171 buffer_add_int (buf, arr->max_length);
9172 buffer_add_int (buf, 0);
9174 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
9175 buffer_add_int (buf, arr->bounds [i].length);
9176 buffer_add_int (buf, arr->bounds [i].lower_bound);
9180 case CMD_ARRAY_REF_GET_VALUES:
9181 index = decode_int (p, &p, end);
9182 len = decode_int (p, &p, end);
9184 g_assert (index >= 0 && len >= 0);
9185 // Reordered to avoid integer overflow
9186 g_assert (!(index > arr->max_length - len));
9188 esize = mono_array_element_size (arr->obj.vtable->klass);
9189 for (i = index; i < index + len; ++i) {
9190 elem = (gpointer*)((char*)arr->vector + (i * esize));
9191 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
9194 case CMD_ARRAY_REF_SET_VALUES:
9195 index = decode_int (p, &p, end);
9196 len = decode_int (p, &p, end);
9198 g_assert (index >= 0 && len >= 0);
9199 // Reordered to avoid integer overflow
9200 g_assert (!(index > arr->max_length - len));
9202 esize = mono_array_element_size (arr->obj.vtable->klass);
9203 for (i = index; i < index + len; ++i) {
9204 elem = (gpointer*)((char*)arr->vector + (i * esize));
9206 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, (guint8 *)elem, p, &p, end);
9210 return ERR_NOT_IMPLEMENTED;
9217 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9223 int i, index, length;
9225 gboolean use_utf16 = FALSE;
9227 objid = decode_objid (p, &p, end);
9228 err = get_object (objid, (MonoObject**)&str);
9229 if (err != ERR_NONE)
9233 case CMD_STRING_REF_GET_VALUE:
9234 if (CHECK_PROTOCOL_VERSION (2, 41)) {
9235 for (i = 0; i < mono_string_length (str); ++i)
9236 if (mono_string_chars (str)[i] == 0)
9238 buffer_add_byte (buf, use_utf16 ? 1 : 0);
9241 buffer_add_int (buf, mono_string_length (str) * 2);
9242 buffer_add_data (buf, (guint8*)mono_string_chars (str), mono_string_length (str) * 2);
9244 s = mono_string_to_utf8 (str);
9245 buffer_add_string (buf, s);
9249 case CMD_STRING_REF_GET_LENGTH:
9250 buffer_add_long (buf, mono_string_length (str));
9252 case CMD_STRING_REF_GET_CHARS:
9253 index = decode_long (p, &p, end);
9254 length = decode_long (p, &p, end);
9255 if (index > mono_string_length (str) - length)
9256 return ERR_INVALID_ARGUMENT;
9257 c = mono_string_chars (str) + index;
9258 for (i = 0; i < length; ++i)
9259 buffer_add_short (buf, c [i]);
9262 return ERR_NOT_IMPLEMENTED;
9269 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9280 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9281 objid = decode_objid (p, &p, end);
9282 err = get_object (objid, &obj);
9283 if (err != ERR_NONE)
9284 buffer_add_int (buf, 1);
9286 buffer_add_int (buf, 0);
9290 objid = decode_objid (p, &p, end);
9291 err = get_object (objid, &obj);
9292 if (err != ERR_NONE)
9295 MonoClass *obj_type;
9296 gboolean remote_obj = FALSE;
9298 obj_type = obj->vtable->klass;
9299 if (mono_class_is_transparent_proxy (obj_type)) {
9300 obj_type = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
9304 g_assert (obj_type);
9307 case CMD_OBJECT_REF_GET_TYPE:
9308 /* This handles transparent proxies too */
9309 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9311 case CMD_OBJECT_REF_GET_VALUES:
9312 len = decode_int (p, &p, end);
9314 for (i = 0; i < len; ++i) {
9315 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9316 if (err != ERR_NONE)
9319 /* Check that the field belongs to the object */
9321 for (k = obj_type; k; k = k->parent) {
9322 if (k == f->parent) {
9328 return ERR_INVALID_FIELDID;
9330 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9334 if (mono_class_field_is_special_static (f))
9335 return ERR_INVALID_FIELDID;
9337 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9338 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9339 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9340 mono_field_static_get_value_checked (vtable, f, val, &error);
9341 if (!is_ok (&error)) {
9342 mono_error_cleanup (&error); /* FIXME report the error */
9343 return ERR_INVALID_OBJECT;
9345 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9348 guint8 *field_value = NULL;
9349 void *field_storage = NULL;
9352 #ifndef DISABLE_REMOTING
9353 field_value = mono_load_remote_field_checked(obj, obj_type, f, &field_storage, &error);
9354 if (!is_ok (&error)) {
9355 mono_error_cleanup (&error); /* FIXME report the error */
9356 return ERR_INVALID_OBJECT;
9359 g_assert_not_reached ();
9362 field_value = (guint8*)obj + f->offset;
9364 buffer_add_value (buf, f->type, field_value, obj->vtable->domain);
9368 case CMD_OBJECT_REF_SET_VALUES:
9369 len = decode_int (p, &p, end);
9371 for (i = 0; i < len; ++i) {
9372 f = decode_fieldid (p, &p, end, NULL, &err);
9373 if (err != ERR_NONE)
9376 /* Check that the field belongs to the object */
9378 for (k = obj_type; k; k = k->parent) {
9379 if (k == f->parent) {
9385 return ERR_INVALID_FIELDID;
9387 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9391 if (mono_class_field_is_special_static (f))
9392 return ERR_INVALID_FIELDID;
9394 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9395 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9397 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9398 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
9399 if (err != ERR_NONE) {
9403 mono_field_static_set_value (vtable, f, val);
9406 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
9407 if (err != ERR_NONE)
9412 case CMD_OBJECT_REF_GET_ADDRESS:
9413 buffer_add_long (buf, (gssize)obj);
9415 case CMD_OBJECT_REF_GET_DOMAIN:
9416 buffer_add_domainid (buf, obj->vtable->domain);
9418 case CMD_OBJECT_REF_GET_INFO:
9419 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9420 buffer_add_domainid (buf, obj->vtable->domain);
9423 return ERR_NOT_IMPLEMENTED;
9430 command_set_to_string (CommandSet command_set)
9432 switch (command_set) {
9435 case CMD_SET_OBJECT_REF:
9436 return "OBJECT_REF";
9437 case CMD_SET_STRING_REF:
9438 return "STRING_REF";
9439 case CMD_SET_THREAD:
9441 case CMD_SET_ARRAY_REF:
9443 case CMD_SET_EVENT_REQUEST:
9444 return "EVENT_REQUEST";
9445 case CMD_SET_STACK_FRAME:
9446 return "STACK_FRAME";
9447 case CMD_SET_APPDOMAIN:
9449 case CMD_SET_ASSEMBLY:
9451 case CMD_SET_METHOD:
9455 case CMD_SET_MODULE:
9466 static const char* vm_cmds_str [] = {
9474 "SET_PROTOCOL_VERSION",
9477 "GET_TYPES_FOR_SOURCE_FILE",
9482 static const char* thread_cmds_str[] = {
9492 static const char* event_cmds_str[] = {
9495 "REQUEST_CLEAR_ALL_BREAKPOINTS"
9498 static const char* appdomain_cmds_str[] = {
9500 "GET_FRIENDLY_NAME",
9502 "GET_ENTRY_ASSEMBLY",
9505 "CREATE_BOXED_VALUE"
9508 static const char* assembly_cmds_str[] = {
9511 "GET_MANIFEST_MODULE",
9517 static const char* module_cmds_str[] = {
9521 static const char* field_cmds_str[] = {
9525 static const char* method_cmds_str[] = {
9527 "GET_DECLARING_TYPE",
9535 "MAKE_GENERIC_METHOD"
9538 static const char* type_cmds_str[] = {
9546 "IS_ASSIGNABLE_FROM",
9550 "GET_PROPERTY_CATTRS",
9551 "GET_SOURCE_FILES_2",
9553 "GET_METHODS_BY_NAME_FLAGS",
9555 "GET_INTERFACE_MAP",
9559 static const char* stack_frame_cmds_str[] = {
9566 static const char* array_cmds_str[] = {
9572 static const char* string_cmds_str[] = {
9578 static const char* object_cmds_str[] = {
9589 cmd_to_string (CommandSet set, int command)
9597 cmds_len = G_N_ELEMENTS (vm_cmds_str);
9599 case CMD_SET_OBJECT_REF:
9600 cmds = object_cmds_str;
9601 cmds_len = G_N_ELEMENTS (object_cmds_str);
9603 case CMD_SET_STRING_REF:
9604 cmds = string_cmds_str;
9605 cmds_len = G_N_ELEMENTS (string_cmds_str);
9607 case CMD_SET_THREAD:
9608 cmds = thread_cmds_str;
9609 cmds_len = G_N_ELEMENTS (thread_cmds_str);
9611 case CMD_SET_ARRAY_REF:
9612 cmds = array_cmds_str;
9613 cmds_len = G_N_ELEMENTS (array_cmds_str);
9615 case CMD_SET_EVENT_REQUEST:
9616 cmds = event_cmds_str;
9617 cmds_len = G_N_ELEMENTS (event_cmds_str);
9619 case CMD_SET_STACK_FRAME:
9620 cmds = stack_frame_cmds_str;
9621 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
9623 case CMD_SET_APPDOMAIN:
9624 cmds = appdomain_cmds_str;
9625 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
9627 case CMD_SET_ASSEMBLY:
9628 cmds = assembly_cmds_str;
9629 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
9631 case CMD_SET_METHOD:
9632 cmds = method_cmds_str;
9633 cmds_len = G_N_ELEMENTS (method_cmds_str);
9636 cmds = type_cmds_str;
9637 cmds_len = G_N_ELEMENTS (type_cmds_str);
9639 case CMD_SET_MODULE:
9640 cmds = module_cmds_str;
9641 cmds_len = G_N_ELEMENTS (module_cmds_str);
9644 cmds = field_cmds_str;
9645 cmds_len = G_N_ELEMENTS (field_cmds_str);
9648 cmds = event_cmds_str;
9649 cmds_len = G_N_ELEMENTS (event_cmds_str);
9654 if (command > 0 && command <= cmds_len)
9655 return cmds [command - 1];
9661 wait_for_attach (void)
9663 #ifndef DISABLE_SOCKET_TRANSPORT
9664 if (listen_fd == -1) {
9665 DEBUG_PRINTF (1, "[dbg] Invalid listening socket\n");
9669 /* Block and wait for client connection */
9670 conn_fd = socket_transport_accept (listen_fd);
9672 DEBUG_PRINTF (1, "Accepted connection on %d\n", conn_fd);
9673 if (conn_fd == -1) {
9674 DEBUG_PRINTF (1, "[dbg] Bad client connection\n");
9678 g_assert_not_reached ();
9682 disconnected = !transport_handshake ();
9684 DEBUG_PRINTF (1, "Transport handshake failed!\n");
9694 * This thread handles communication with the debugger client using a JDWP
9697 static guint32 WINAPI
9698 debugger_thread (void *arg)
9701 int res, len, id, flags, command = 0;
9702 CommandSet command_set = (CommandSet)0;
9703 guint8 header [HEADER_LENGTH];
9704 guint8 *data, *p, *end;
9708 gboolean attach_failed = FALSE;
9710 DEBUG_PRINTF (1, "[dbg] Agent thread started, pid=%p\n", (gpointer) (gsize) mono_native_thread_id_get ());
9712 debugger_thread_id = mono_native_thread_id_get ();
9714 MonoThread *thread = mono_thread_attach (mono_get_root_domain ());
9715 mono_thread_set_name_internal (thread->internal_thread, mono_string_new (mono_get_root_domain (), "Debugger agent"), TRUE, &error);
9716 mono_error_assert_ok (&error);
9718 thread->internal_thread->state |= ThreadState_Background;
9719 thread->internal_thread->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
9721 mono_set_is_debugger_attached (TRUE);
9723 if (agent_config.defer) {
9724 if (!wait_for_attach ()) {
9725 DEBUG_PRINTF (1, "[dbg] Can't attach, aborting debugger thread.\n");
9726 attach_failed = TRUE; // Don't abort process when we can't listen
9728 /* Send start event to client */
9729 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
9733 while (!attach_failed) {
9734 res = transport_recv (header, HEADER_LENGTH);
9736 /* This will break if the socket is closed during shutdown too */
9737 if (res != HEADER_LENGTH) {
9738 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH);
9743 end = header + HEADER_LENGTH;
9745 len = decode_int (p, &p, end);
9746 id = decode_int (p, &p, end);
9747 flags = decode_byte (p, &p, end);
9748 command_set = (CommandSet)decode_byte (p, &p, end);
9749 command = decode_byte (p, &p, end);
9751 g_assert (flags == 0);
9754 const char *cmd_str;
9757 cmd_str = cmd_to_string (command_set, command);
9759 sprintf (cmd_num, "%d", command);
9763 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);
9766 data = (guint8 *)g_malloc (len - HEADER_LENGTH);
9767 if (len - HEADER_LENGTH > 0)
9769 res = transport_recv (data, len - HEADER_LENGTH);
9770 if (res != len - HEADER_LENGTH) {
9771 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH);
9777 end = data + (len - HEADER_LENGTH);
9779 buffer_init (&buf, 128);
9784 /* Process the request */
9785 switch (command_set) {
9787 err = vm_commands (command, id, p, end, &buf);
9788 if (err == ERR_NONE && command == CMD_VM_INVOKE_METHOD)
9789 /* Sent after the invoke is complete */
9792 case CMD_SET_EVENT_REQUEST:
9793 err = event_commands (command, p, end, &buf);
9795 case CMD_SET_APPDOMAIN:
9796 err = domain_commands (command, p, end, &buf);
9798 case CMD_SET_ASSEMBLY:
9799 err = assembly_commands (command, p, end, &buf);
9801 case CMD_SET_MODULE:
9802 err = module_commands (command, p, end, &buf);
9805 err = field_commands (command, p, end, &buf);
9808 err = type_commands (command, p, end, &buf);
9810 case CMD_SET_METHOD:
9811 err = method_commands (command, p, end, &buf);
9813 case CMD_SET_THREAD:
9814 err = thread_commands (command, p, end, &buf);
9816 case CMD_SET_STACK_FRAME:
9817 err = frame_commands (command, p, end, &buf);
9819 case CMD_SET_ARRAY_REF:
9820 err = array_commands (command, p, end, &buf);
9822 case CMD_SET_STRING_REF:
9823 err = string_commands (command, p, end, &buf);
9825 case CMD_SET_OBJECT_REF:
9826 err = object_commands (command, p, end, &buf);
9829 err = ERR_NOT_IMPLEMENTED;
9832 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
9833 buffer_replies = TRUE;
9837 if (buffer_replies) {
9838 buffer_reply_packet (id, err, &buf);
9840 send_reply_packet (id, err, &buf);
9841 //DEBUG_PRINTF (1, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000);
9845 if (err == ERR_NONE && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
9846 send_buffered_reply_packets ();
9847 buffer_replies = FALSE;
9853 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
9857 mono_set_is_debugger_attached (FALSE);
9859 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
9860 debugger_thread_exited = TRUE;
9861 mono_coop_cond_signal (&debugger_thread_exited_cond);
9862 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
9864 DEBUG_PRINTF (1, "[dbg] Debugger thread exited.\n");
9866 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
9867 DEBUG_PRINTF (2, "[dbg] Detached - restarting clean debugger thread.\n");
9868 start_debugger_thread ();
9874 #else /* DISABLE_DEBUGGER_AGENT */
9877 mono_debugger_agent_parse_options (char *options)
9879 g_error ("This runtime is configured with the debugger agent disabled.");
9883 mono_debugger_agent_init (void)
9888 mono_debugger_agent_breakpoint_hit (void *sigctx)
9893 mono_debugger_agent_single_step_event (void *sigctx)
9898 mono_debugger_agent_free_domain_info (MonoDomain *domain)
9903 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
9904 MonoContext *catch_ctx)
9909 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9914 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9919 mono_debugger_agent_user_break (void)
9925 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
9930 mono_debugger_agent_debug_log_is_enabled (void)
9936 mono_debugger_agent_unhandled_exception (MonoException *exc)
9938 g_assert_not_reached ();
9942 debugger_agent_single_step_from_context (MonoContext *ctx)
9944 g_assert_not_reached ();
9948 debugger_agent_breakpoint_from_context (MonoContext *ctx)
9950 g_assert_not_reached ();