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 <mono/utils/mono-proclib.h>
75 #include "debugger-agent.h"
77 #include "seq-points.h"
80 * On iOS we can't use System.Environment.Exit () as it will do the wrong
83 #if !defined (TARGET_IOS)
84 #define TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
88 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
89 #define DISABLE_DEBUGGER_AGENT 1
92 #ifdef DISABLE_SOFT_DEBUG
93 #define DISABLE_DEBUGGER_AGENT 1
96 #ifndef DISABLE_DEBUGGER_AGENT
98 #include <mono/utils/mono-os-mutex.h>
100 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
123 guint32 il_offset, native_offset;
127 * If method is gshared, this is the actual instance, otherwise this is equal to
130 MonoMethod *actual_method;
132 * This is the method which is visible to debugger clients. Same as method,
133 * except for native-to-managed wrappers.
135 MonoMethod *api_method;
137 MonoDebugMethodJitInfo *jit;
140 mgreg_t *reg_locations [MONO_MAX_IREGS];
142 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
143 * the frame can become invalid.
148 typedef struct _InvokeData InvokeData;
156 /* This is the context which needs to be restored after the invoke */
160 * If this is set, invoke this method with the arguments given by ARGS.
164 guint32 suspend_count;
167 InvokeData *last_invoke;
171 MonoThreadUnwindState context;
173 /* This is computed on demand when it is requested using the wire protocol */
174 /* It is freed up when the thread is resumed */
178 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
181 gboolean frames_up_to_date;
183 * Points to data about a pending invoke which needs to be executed after the thread
186 InvokeData *pending_invoke;
188 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
193 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
194 * within a finite amount of time.
198 * Set to TRUE if this thread is suspended in suspend_current ().
200 gboolean really_suspended;
201 /* Used to pass the context to the breakpoint/single step handler */
202 MonoContext handler_ctx;
203 /* Whenever thread_stop () was called for this thread */
206 /* Whenever to disable breakpoints (used during invokes) */
207 gboolean disable_breakpoints;
210 * Number of times this thread has been resumed using resume_thread ().
212 guint32 resume_count;
214 MonoInternalThread *thread;
217 * Information about the frame which transitioned to native code for running
220 StackFrameInfo async_last_frame;
223 * The context where the stack walk can be started for running threads.
225 MonoThreadUnwindState async_state;
228 * The context used for filter clauses
230 MonoThreadUnwindState filter_state;
232 gboolean abort_requested;
235 * The current mono_runtime_invoke_checked invocation.
240 * The context where single stepping should resume while the thread is suspended because
241 * of an EXCEPTION event.
243 MonoThreadUnwindState catch_state;
246 * The context which needs to be restored after handling a single step/breakpoint
247 * event. This is the same as the ctx at step/breakpoint site, but includes changes
248 * to caller saved registers done by set_var ().
250 MonoThreadUnwindState restore_state;
251 /* Frames computed from restore_state */
252 int restore_frame_count;
253 StackFrame **restore_frames;
255 /* The currently unloading appdomain */
256 MonoDomain *domain_unloading;
261 void (*connect) (const char *address);
262 void (*close1) (void);
263 void (*close2) (void);
264 gboolean (*send) (void *buf, int len);
265 int (*recv) (void *buf, int len);
269 * Wire Protocol definitions
272 #define HEADER_LENGTH 11
274 #define MAJOR_VERSION 2
275 #define MINOR_VERSION 44
279 CMD_SET_OBJECT_REF = 9,
280 CMD_SET_STRING_REF = 10,
282 CMD_SET_ARRAY_REF = 13,
283 CMD_SET_EVENT_REQUEST = 15,
284 CMD_SET_STACK_FRAME = 16,
285 CMD_SET_APPDOMAIN = 20,
286 CMD_SET_ASSEMBLY = 21,
295 EVENT_KIND_VM_START = 0,
296 EVENT_KIND_VM_DEATH = 1,
297 EVENT_KIND_THREAD_START = 2,
298 EVENT_KIND_THREAD_DEATH = 3,
299 EVENT_KIND_APPDOMAIN_CREATE = 4,
300 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
301 EVENT_KIND_METHOD_ENTRY = 6,
302 EVENT_KIND_METHOD_EXIT = 7,
303 EVENT_KIND_ASSEMBLY_LOAD = 8,
304 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
305 EVENT_KIND_BREAKPOINT = 10,
306 EVENT_KIND_STEP = 11,
307 EVENT_KIND_TYPE_LOAD = 12,
308 EVENT_KIND_EXCEPTION = 13,
309 EVENT_KIND_KEEPALIVE = 14,
310 EVENT_KIND_USER_BREAK = 15,
311 EVENT_KIND_USER_LOG = 16
315 SUSPEND_POLICY_NONE = 0,
316 SUSPEND_POLICY_EVENT_THREAD = 1,
317 SUSPEND_POLICY_ALL = 2
322 ERR_INVALID_OBJECT = 20,
323 ERR_INVALID_FIELDID = 25,
324 ERR_INVALID_FRAMEID = 30,
325 ERR_NOT_IMPLEMENTED = 100,
326 ERR_NOT_SUSPENDED = 101,
327 ERR_INVALID_ARGUMENT = 102,
329 ERR_NO_INVOCATION = 104,
330 ERR_ABSENT_INFORMATION = 105,
331 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
332 ERR_INVOKE_ABORTED = 107,
333 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
338 MOD_KIND_THREAD_ONLY = 3,
339 MOD_KIND_LOCATION_ONLY = 7,
340 MOD_KIND_EXCEPTION_ONLY = 8,
342 MOD_KIND_ASSEMBLY_ONLY = 11,
343 MOD_KIND_SOURCE_FILE_ONLY = 12,
344 MOD_KIND_TYPE_NAME_ONLY = 13,
360 STEP_FILTER_NONE = 0,
361 STEP_FILTER_STATIC_CTOR = 1,
362 STEP_FILTER_DEBUGGER_HIDDEN = 2,
363 STEP_FILTER_DEBUGGER_STEP_THROUGH = 4,
364 STEP_FILTER_DEBUGGER_NON_USER_CODE = 8
368 TOKEN_TYPE_STRING = 0,
370 TOKEN_TYPE_FIELD = 2,
371 TOKEN_TYPE_METHOD = 3,
372 TOKEN_TYPE_UNKNOWN = 4
376 VALUE_TYPE_ID_NULL = 0xf0,
377 VALUE_TYPE_ID_TYPE = 0xf1,
378 VALUE_TYPE_ID_PARENT_VTYPE = 0xf2
382 FRAME_FLAG_DEBUGGER_INVOKE = 1,
383 FRAME_FLAG_NATIVE_TRANSITION = 2
387 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
388 INVOKE_FLAG_SINGLE_THREADED = 2,
389 INVOKE_FLAG_RETURN_OUT_THIS = 4,
390 INVOKE_FLAG_RETURN_OUT_ARGS = 8,
391 INVOKE_FLAG_VIRTUAL = 16
395 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
396 } BindingFlagsExtensions;
400 CMD_VM_ALL_THREADS = 2,
405 CMD_VM_INVOKE_METHOD = 7,
406 CMD_VM_SET_PROTOCOL_VERSION = 8,
407 CMD_VM_ABORT_INVOKE = 9,
408 CMD_VM_SET_KEEPALIVE = 10,
409 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
410 CMD_VM_GET_TYPES = 12,
411 CMD_VM_INVOKE_METHODS = 13,
412 CMD_VM_START_BUFFERING = 14,
413 CMD_VM_STOP_BUFFERING = 15
417 CMD_THREAD_GET_FRAME_INFO = 1,
418 CMD_THREAD_GET_NAME = 2,
419 CMD_THREAD_GET_STATE = 3,
420 CMD_THREAD_GET_INFO = 4,
421 CMD_THREAD_GET_ID = 5,
422 CMD_THREAD_GET_TID = 6,
423 CMD_THREAD_SET_IP = 7
427 CMD_EVENT_REQUEST_SET = 1,
428 CMD_EVENT_REQUEST_CLEAR = 2,
429 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
437 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
438 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
439 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
440 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
441 CMD_APPDOMAIN_CREATE_STRING = 5,
442 CMD_APPDOMAIN_GET_CORLIB = 6,
443 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
447 CMD_ASSEMBLY_GET_LOCATION = 1,
448 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
449 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
450 CMD_ASSEMBLY_GET_OBJECT = 4,
451 CMD_ASSEMBLY_GET_TYPE = 5,
452 CMD_ASSEMBLY_GET_NAME = 6
456 CMD_MODULE_GET_INFO = 1,
460 CMD_FIELD_GET_INFO = 1,
464 CMD_METHOD_GET_NAME = 1,
465 CMD_METHOD_GET_DECLARING_TYPE = 2,
466 CMD_METHOD_GET_DEBUG_INFO = 3,
467 CMD_METHOD_GET_PARAM_INFO = 4,
468 CMD_METHOD_GET_LOCALS_INFO = 5,
469 CMD_METHOD_GET_INFO = 6,
470 CMD_METHOD_GET_BODY = 7,
471 CMD_METHOD_RESOLVE_TOKEN = 8,
472 CMD_METHOD_GET_CATTRS = 9,
473 CMD_METHOD_MAKE_GENERIC_METHOD = 10
477 CMD_TYPE_GET_INFO = 1,
478 CMD_TYPE_GET_METHODS = 2,
479 CMD_TYPE_GET_FIELDS = 3,
480 CMD_TYPE_GET_VALUES = 4,
481 CMD_TYPE_GET_OBJECT = 5,
482 CMD_TYPE_GET_SOURCE_FILES = 6,
483 CMD_TYPE_SET_VALUES = 7,
484 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
485 CMD_TYPE_GET_PROPERTIES = 9,
486 CMD_TYPE_GET_CATTRS = 10,
487 CMD_TYPE_GET_FIELD_CATTRS = 11,
488 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
489 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
490 CMD_TYPE_GET_VALUES_2 = 14,
491 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
492 CMD_TYPE_GET_INTERFACES = 16,
493 CMD_TYPE_GET_INTERFACE_MAP = 17,
494 CMD_TYPE_IS_INITIALIZED = 18,
495 CMD_TYPE_CREATE_INSTANCE = 19
499 CMD_STACK_FRAME_GET_VALUES = 1,
500 CMD_STACK_FRAME_GET_THIS = 2,
501 CMD_STACK_FRAME_SET_VALUES = 3,
502 CMD_STACK_FRAME_GET_DOMAIN = 4,
503 CMD_STACK_FRAME_SET_THIS = 5,
507 CMD_ARRAY_REF_GET_LENGTH = 1,
508 CMD_ARRAY_REF_GET_VALUES = 2,
509 CMD_ARRAY_REF_SET_VALUES = 3,
513 CMD_STRING_REF_GET_VALUE = 1,
514 CMD_STRING_REF_GET_LENGTH = 2,
515 CMD_STRING_REF_GET_CHARS = 3
519 CMD_OBJECT_REF_GET_TYPE = 1,
520 CMD_OBJECT_REF_GET_VALUES = 2,
521 CMD_OBJECT_REF_IS_COLLECTED = 3,
522 CMD_OBJECT_REF_GET_ADDRESS = 4,
523 CMD_OBJECT_REF_GET_DOMAIN = 5,
524 CMD_OBJECT_REF_SET_VALUES = 6,
525 CMD_OBJECT_REF_GET_INFO = 7,
531 int count; /* For kind == MOD_KIND_COUNT */
532 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
533 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
534 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
535 GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
536 GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
537 StepFilter filter; /* For kind == MOD_KIND_STEP */
539 gboolean caught, uncaught, subclasses; /* For kind == MOD_KIND_EXCEPTION_ONLY */
548 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
552 * Describes a single step request.
556 MonoInternalThread *thread;
562 MonoMethod *start_method;
563 MonoMethod *last_method;
565 /* Whenever single stepping is performed using start/stop_single_stepping () */
567 /* The list of breakpoints used to implement step-over */
569 /* The number of frames at the start of a step-over */
574 * Contains additional information for an event
577 /* For EVENT_KIND_EXCEPTION */
579 MonoContext catch_ctx;
581 /* For EVENT_KIND_USER_LOG */
583 char *category, *message;
584 /* For EVENT_KIND_TYPE_LOAD */
588 /* Dummy structure used for the profiler callbacks */
594 guint8 *buf, *p, *end;
597 typedef struct ReplyPacket {
603 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
605 #ifdef PLATFORM_ANDROID
606 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { g_print (__VA_ARGS__); } } while (0)
608 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { fprintf (log_file, __VA_ARGS__); fflush (log_file); } } while (0)
612 #define get_last_sock_error() WSAGetLastError()
613 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
614 #define MONO_EINTR WSAEINTR
616 #define get_last_sock_error() errno
617 #define MONO_EWOULDBLOCK EWOULDBLOCK
618 #define MONO_EINTR EINTR
621 #define CHECK_PROTOCOL_VERSION(major,minor) \
622 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
628 static AgentConfig agent_config;
631 * Whenever the agent is fully initialized.
632 * When using the onuncaught or onthrow options, only some parts of the agent are
633 * initialized on startup, and the full initialization which includes connection
634 * establishment and the startup of the agent thread is only done in response to
637 static gint32 inited;
639 #ifndef DISABLE_SOCKET_TRANSPORT
641 static int listen_fd;
644 static int packet_id = 0;
646 static int objref_id = 0;
648 static int event_request_id = 0;
650 static int frame_id = 0;
652 static GPtrArray *event_requests;
654 static MonoNativeTlsKey debugger_tls_id;
656 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
658 /* Maps MonoInternalThread -> DebuggerTlsData */
659 /* Protected by the loader lock */
660 static MonoGHashTable *thread_to_tls;
662 /* Maps tid -> MonoInternalThread */
663 /* Protected by the loader lock */
664 static MonoGHashTable *tid_to_thread;
666 /* Maps tid -> MonoThread (not MonoInternalThread) */
667 /* Protected by the loader lock */
668 static MonoGHashTable *tid_to_thread_obj;
670 static MonoNativeThreadId debugger_thread_id;
672 static MonoThreadHandle *debugger_thread_handle;
674 static int log_level;
676 static gboolean embedding;
678 static FILE *log_file;
680 /* Assemblies whose assembly load event has no been sent yet */
681 /* Protected by the dbg lock */
682 static GPtrArray *pending_assembly_loads;
684 /* Whenever the debugger thread has exited */
685 static gboolean debugger_thread_exited;
687 /* Cond variable used to wait for debugger_thread_exited becoming true */
688 static MonoCoopCond debugger_thread_exited_cond;
690 /* Mutex for the cond var above */
691 static MonoCoopMutex debugger_thread_exited_mutex;
693 static DebuggerProfiler debugger_profiler;
695 /* The single step request instance */
696 static SingleStepReq *ss_req;
698 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
699 /* Number of single stepping operations in progress */
703 /* The protocol version of the client */
704 static int major_version, minor_version;
706 /* Whenever the variables above are set by the client */
707 static gboolean protocol_version_set;
709 /* A hash table containing all active domains */
710 /* Protected by the loader lock */
711 static GHashTable *domains;
713 /* The number of times the runtime is suspended */
714 static gint32 suspend_count;
716 /* Whenever to buffer reply messages and send them together */
717 static gboolean buffer_replies;
719 /* Buffered reply packets */
720 static ReplyPacket reply_packets [128];
723 #define dbg_lock() mono_coop_mutex_lock (&debug_mutex)
724 #define dbg_unlock() mono_coop_mutex_unlock (&debug_mutex)
725 static MonoCoopMutex debug_mutex;
727 static void transport_init (void);
728 static void transport_connect (const char *address);
729 static gboolean transport_handshake (void);
730 static void register_transport (DebuggerTransport *trans);
732 static gsize WINAPI debugger_thread (void *arg);
734 static void runtime_initialized (MonoProfiler *prof);
736 static void runtime_shutdown (MonoProfiler *prof);
738 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
740 static void thread_end (MonoProfiler *prof, uintptr_t tid);
742 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
744 static void appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain);
746 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
748 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
750 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
752 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
754 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
756 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
758 static void emit_assembly_load (gpointer assembly, gpointer user_data);
760 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
762 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
764 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
766 static void start_single_stepping (void);
768 static void stop_single_stepping (void);
770 static void suspend_current (void);
772 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
774 static void clear_types_for_assembly (MonoAssembly *assembly);
776 static void clear_breakpoints_for_domain (MonoDomain *domain);
778 static void process_profiler_event (EventKind event, gpointer arg);
780 /* Submodule init/cleanup */
781 static void breakpoints_init (void);
782 static void breakpoints_cleanup (void);
784 static void objrefs_init (void);
785 static void objrefs_cleanup (void);
787 static void ids_init (void);
788 static void ids_cleanup (void);
790 static void suspend_init (void);
792 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch,
793 StackFrame **frames, int nframes);
794 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req);
795 static void ss_destroy (SingleStepReq *req);
797 static void start_debugger_thread (void);
798 static void stop_debugger_thread (void);
800 static void finish_agent_init (gboolean on_startup);
802 static void process_profiler_event (EventKind event, gpointer arg);
804 static void invalidate_frames (DebuggerTlsData *tls);
806 #ifndef DISABLE_SOCKET_TRANSPORT
808 register_socket_transport (void);
811 static inline gboolean
812 is_debugger_thread (void)
814 return mono_native_thread_id_equals (mono_native_thread_id_get (), debugger_thread_id);
818 parse_address (char *address, char **host, int *port)
820 char *pos = strchr (address, ':');
822 if (pos == NULL || pos == address)
825 *host = (char *)g_malloc (pos - address + 1);
826 strncpy (*host, address, pos - address);
827 (*host) [pos - address] = '\0';
829 *port = atoi (pos + 1);
837 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
838 fprintf (stderr, "Available options:\n");
839 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
840 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
841 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
842 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
843 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
844 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
845 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
846 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
847 fprintf (stderr, " setpgid=y/n\t\t\tWhether to call setpid(0, 0) after startup.\n");
848 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
852 parse_flag (const char *option, char *flag)
854 if (!strcmp (flag, "y"))
856 else if (!strcmp (flag, "n"))
859 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
866 mono_debugger_agent_parse_options (char *options)
873 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
874 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
878 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
880 options = g_strdup_printf ("%s,%s", options, extra);
882 agent_config.enabled = TRUE;
883 agent_config.suspend = TRUE;
884 agent_config.server = FALSE;
885 agent_config.defer = FALSE;
886 agent_config.address = NULL;
888 //agent_config.log_level = 10;
890 args = g_strsplit (options, ",", -1);
891 for (ptr = args; ptr && *ptr; ptr ++) {
894 if (strncmp (arg, "transport=", 10) == 0) {
895 agent_config.transport = g_strdup (arg + 10);
896 } else if (strncmp (arg, "address=", 8) == 0) {
897 agent_config.address = g_strdup (arg + 8);
898 } else if (strncmp (arg, "loglevel=", 9) == 0) {
899 agent_config.log_level = atoi (arg + 9);
900 } else if (strncmp (arg, "logfile=", 8) == 0) {
901 agent_config.log_file = g_strdup (arg + 8);
902 } else if (strncmp (arg, "suspend=", 8) == 0) {
903 agent_config.suspend = parse_flag ("suspend", arg + 8);
904 } else if (strncmp (arg, "server=", 7) == 0) {
905 agent_config.server = parse_flag ("server", arg + 7);
906 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
907 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
908 } else if (strncmp (arg, "onthrow=", 8) == 0) {
909 /* We support multiple onthrow= options */
910 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
911 } else if (strncmp (arg, "onthrow", 7) == 0) {
912 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
913 } else if (strncmp (arg, "help", 4) == 0) {
916 } else if (strncmp (arg, "timeout=", 8) == 0) {
917 agent_config.timeout = atoi (arg + 8);
918 } else if (strncmp (arg, "launch=", 7) == 0) {
919 agent_config.launch = g_strdup (arg + 7);
920 } else if (strncmp (arg, "embedding=", 10) == 0) {
921 agent_config.embedding = atoi (arg + 10) == 1;
922 } else if (strncmp (arg, "keepalive=", 10) == 0) {
923 agent_config.keepalive = atoi (arg + 10);
924 } else if (strncmp (arg, "setpgid=", 8) == 0) {
925 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
932 if (agent_config.server && !agent_config.suspend) {
933 /* Waiting for deferred attachment */
934 agent_config.defer = TRUE;
935 if (agent_config.address == NULL) {
936 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (mono_process_current_pid () % 1000));
940 //agent_config.log_level = 0;
942 if (agent_config.transport == NULL) {
943 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
947 if (agent_config.address == NULL && !agent_config.server) {
948 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
953 if (!strcmp (agent_config.transport, "dt_socket")) {
954 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
955 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
962 mono_debugger_agent_init (void)
964 mono_coop_mutex_init_recursive (&debug_mutex);
966 if (!agent_config.enabled)
971 /* Need to know whenever a thread has acquired the loader mutex */
972 mono_loader_lock_track_ownership (TRUE);
974 event_requests = g_ptr_array_new ();
976 mono_coop_mutex_init (&debugger_thread_exited_mutex);
977 mono_coop_cond_init (&debugger_thread_exited_cond);
979 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
980 mono_profiler_set_events ((MonoProfileFlags)(MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS));
981 mono_profiler_install_runtime_initialized (runtime_initialized);
982 mono_profiler_install_appdomain (NULL, appdomain_load, appdomain_start_unload, appdomain_unload);
983 mono_profiler_install_thread (thread_startup, thread_end);
984 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
985 mono_profiler_install_jit_end (jit_end);
987 mono_native_tls_alloc (&debugger_tls_id, NULL);
989 /* Needed by the hash_table_new_type () call below */
990 mono_gc_base_init ();
992 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_DEBUGGER, "thread-to-tls table");
993 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls, MONO_ROOT_SOURCE_DEBUGGER, "thread-to-tls table");
995 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread table");
996 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread table");
998 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread object table");
999 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread object table");
1001 pending_assembly_loads = g_ptr_array_new ();
1002 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
1004 log_level = agent_config.log_level;
1006 embedding = agent_config.embedding;
1007 disconnected = TRUE;
1009 if (agent_config.log_file) {
1010 log_file = fopen (agent_config.log_file, "w+");
1012 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
1021 breakpoints_init ();
1024 mini_get_debug_options ()->gen_sdb_seq_points = TRUE;
1026 * This is needed because currently we don't handle liveness info.
1028 mini_get_debug_options ()->mdb_optimizations = TRUE;
1030 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
1031 /* This is needed because we can't set local variables in registers yet */
1032 mono_disable_optimizations (MONO_OPT_LINEARS);
1036 * The stack walk done from thread_interrupt () needs to be signal safe, but it
1037 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
1038 * safe (#3411). So load AOT info eagerly when the debugger is running as a
1041 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
1044 if (agent_config.setpgid)
1048 if (!agent_config.onuncaught && !agent_config.onthrow)
1049 finish_agent_init (TRUE);
1053 * finish_agent_init:
1055 * Finish the initialization of the agent. This involves connecting the transport
1056 * and starting the agent thread. This is either done at startup, or
1057 * in response to some event like an unhandled exception.
1060 finish_agent_init (gboolean on_startup)
1064 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
1067 if (agent_config.launch) {
1070 // FIXME: Generated address
1071 // FIXME: Races with transport_connect ()
1073 argv [0] = agent_config.launch;
1074 argv [1] = agent_config.transport;
1075 argv [2] = agent_config.address;
1078 res = g_spawn_async_with_pipes (NULL, argv, NULL, (GSpawnFlags)0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1080 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1085 transport_connect (agent_config.address);
1088 /* Do some which is usually done after sending the VMStart () event */
1089 vm_start_event_sent = TRUE;
1090 start_debugger_thread ();
1095 mono_debugger_agent_cleanup (void)
1100 stop_debugger_thread ();
1102 breakpoints_cleanup ();
1111 #ifndef DISABLE_SOCKET_TRANSPORT
1116 * recv() + handle incomplete reads and EINTR
1119 socket_transport_recv (void *buf, int len)
1125 static gint64 last_keepalive;
1132 res = recv (fd, (char *) buf + total, len - total, flags);
1135 if (agent_config.keepalive) {
1136 gboolean need_keepalive = FALSE;
1137 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1138 need_keepalive = TRUE;
1139 } else if (res == -1) {
1140 /* This could happen if recv () is interrupted repeatedly */
1141 msecs = mono_msec_ticks ();
1142 if (msecs - last_keepalive >= agent_config.keepalive) {
1143 need_keepalive = TRUE;
1144 last_keepalive = msecs;
1147 if (need_keepalive) {
1148 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1152 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1160 set_keepalive (void)
1165 if (!agent_config.keepalive || !conn_fd)
1168 tv.tv_sec = agent_config.keepalive / 1000;
1169 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1171 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1172 g_assert (result >= 0);
1176 socket_transport_accept (int socket_fd)
1179 conn_fd = accept (socket_fd, NULL, NULL);
1182 if (conn_fd == -1) {
1183 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1185 DEBUG_PRINTF (1, "Accepted connection from client, connection fd=%d.\n", conn_fd);
1192 socket_transport_send (void *data, int len)
1199 res = send (conn_fd, data, len, 0);
1200 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1211 * socket_transport_connect:
1213 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1216 socket_transport_connect (const char *address)
1218 MonoAddressInfo *result;
1219 MonoAddressEntry *rp;
1220 int sfd = -1, s, res;
1224 if (agent_config.address) {
1225 res = parse_address (agent_config.address, &host, &port);
1226 g_assert (res == 0);
1237 mono_network_init ();
1239 /* Obtain address(es) matching host/port */
1240 s = mono_get_address_info (host, port, MONO_HINT_UNSPECIFIED, &result);
1242 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, s); // FIXME add portable error conversion functions
1247 if (agent_config.server) {
1248 /* Wait for a connection */
1250 struct sockaddr_in addr;
1253 /* No address, generate one */
1254 sfd = socket (AF_INET, SOCK_STREAM, 0);
1257 /* This will bind the socket to a random port */
1258 res = listen (sfd, 16);
1260 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1265 addrlen = sizeof (addr);
1266 memset (&addr, 0, sizeof (addr));
1267 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1268 g_assert (res == 0);
1270 host = (char*)"127.0.0.1";
1271 port = ntohs (addr.sin_port);
1273 /* Emit the address to stdout */
1274 /* FIXME: Should print another interface, not localhost */
1275 printf ("%s:%d\n", host, port);
1277 /* Listen on the provided address */
1278 for (rp = result->entries; rp != NULL; rp = rp->next) {
1279 MonoSocketAddress sockaddr;
1283 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1285 sfd = socket (rp->family, rp->socktype,
1290 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1293 res = bind (sfd, &sockaddr.addr, sock_len);
1297 res = listen (sfd, 16);
1304 mono_free_address_info (result);
1307 if (agent_config.defer)
1310 DEBUG_PRINTF (1, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout);
1312 if (agent_config.timeout) {
1317 tv.tv_usec = agent_config.timeout * 1000;
1319 FD_SET (sfd, &readfds);
1322 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1326 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1331 conn_fd = socket_transport_accept (sfd);
1335 DEBUG_PRINTF (1, "Accepted connection from client, socket fd=%d.\n", conn_fd);
1337 /* Connect to the specified address */
1338 /* FIXME: Respect the timeout */
1339 for (rp = result->entries; rp != NULL; rp = rp->next) {
1340 MonoSocketAddress sockaddr;
1343 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1345 sfd = socket (rp->family, rp->socktype,
1351 res = connect (sfd, &sockaddr.addr, sock_len);
1355 break; /* Success */
1363 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1369 mono_free_address_info (result);
1372 if (!transport_handshake ())
1377 socket_transport_close1 (void)
1379 /* This will interrupt the agent thread */
1380 /* Close the read part only so it can still send back replies */
1381 /* Also shut down the connection listener so that we can exit normally */
1383 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1384 shutdown (conn_fd, SD_BOTH);
1385 shutdown (listen_fd, SD_BOTH);
1386 closesocket (listen_fd);
1388 shutdown (conn_fd, SHUT_RD);
1389 shutdown (listen_fd, SHUT_RDWR);
1397 socket_transport_close2 (void)
1400 shutdown (conn_fd, SD_BOTH);
1402 shutdown (conn_fd, SHUT_RDWR);
1407 register_socket_transport (void)
1409 DebuggerTransport trans;
1411 trans.name = "dt_socket";
1412 trans.connect = socket_transport_connect;
1413 trans.close1 = socket_transport_close1;
1414 trans.close2 = socket_transport_close2;
1415 trans.send = socket_transport_send;
1416 trans.recv = socket_transport_recv;
1418 register_transport (&trans);
1422 * socket_fd_transport_connect:
1426 socket_fd_transport_connect (const char *address)
1430 res = sscanf (address, "%d", &conn_fd);
1432 fprintf (stderr, "debugger-agent: socket-fd transport address is invalid: '%s'\n", address);
1436 if (!transport_handshake ())
1441 register_socket_fd_transport (void)
1443 DebuggerTransport trans;
1445 /* This is the same as the 'dt_socket' transport, but receives an already connected socket fd */
1446 trans.name = "socket-fd";
1447 trans.connect = socket_fd_transport_connect;
1448 trans.close1 = socket_transport_close1;
1449 trans.close2 = socket_transport_close2;
1450 trans.send = socket_transport_send;
1451 trans.recv = socket_transport_recv;
1453 register_transport (&trans);
1456 #endif /* DISABLE_SOCKET_TRANSPORT */
1462 #define MAX_TRANSPORTS 16
1464 static DebuggerTransport *transport;
1466 static DebuggerTransport transports [MAX_TRANSPORTS];
1467 static int ntransports;
1470 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1473 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1475 register_transport (trans);
1479 register_transport (DebuggerTransport *trans)
1481 g_assert (ntransports < MAX_TRANSPORTS);
1483 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1488 transport_init (void)
1492 #ifndef DISABLE_SOCKET_TRANSPORT
1493 register_socket_transport ();
1494 register_socket_fd_transport ();
1497 for (i = 0; i < ntransports; ++i) {
1498 if (!strcmp (agent_config.transport, transports [i].name))
1501 if (i == ntransports) {
1502 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1503 for (i = 0; i < ntransports; ++i)
1504 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1505 fprintf (stderr, "\n");
1508 transport = &transports [i];
1512 transport_connect (const char *address)
1514 transport->connect (address);
1518 transport_close1 (void)
1520 transport->close1 ();
1524 transport_close2 (void)
1526 transport->close2 ();
1530 transport_send (void *buf, int len)
1532 return transport->send (buf, len);
1536 transport_recv (void *buf, int len)
1538 return transport->recv (buf, len);
1542 mono_debugger_agent_transport_handshake (void)
1544 return transport_handshake ();
1548 transport_handshake (void)
1550 char handshake_msg [128];
1554 disconnected = TRUE;
1556 /* Write handshake message */
1557 sprintf (handshake_msg, "DWP-Handshake");
1560 res = transport_send (handshake_msg, strlen (handshake_msg));
1561 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1563 g_assert (res != -1);
1566 res = transport_recv (buf, strlen (handshake_msg));
1567 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg)) != 0)) {
1568 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1573 * To support older clients, the client sends its protocol version after connecting
1574 * using a command. Until that is received, default to our protocol version.
1576 major_version = MAJOR_VERSION;
1577 minor_version = MINOR_VERSION;
1578 protocol_version_set = FALSE;
1580 #ifndef DISABLE_SOCKET_TRANSPORT
1581 // FIXME: Move this somewhere else
1583 * Set TCP_NODELAY on the socket so the client receives events/command
1584 * results immediately.
1588 int result = setsockopt (conn_fd,
1593 g_assert (result >= 0);
1599 disconnected = FALSE;
1604 stop_debugger_thread (void)
1609 transport_close1 ();
1612 * Wait for the thread to exit.
1614 * If we continue with the shutdown without waiting for it, then the client might
1615 * not receive an answer to its last command like a resume.
1617 if (!is_debugger_thread ()) {
1619 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
1620 if (!debugger_thread_exited)
1621 mono_coop_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1622 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
1623 } while (!debugger_thread_exited);
1626 transport_close2 ();
1630 start_debugger_thread (void)
1632 debugger_thread_handle = mono_threads_create_thread (debugger_thread, NULL, NULL, NULL);
1633 g_assert (debugger_thread_handle);
1637 * Functions to decode protocol data
1641 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1644 g_assert (*endbuf <= limit);
1649 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1652 g_assert (*endbuf <= limit);
1654 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1657 static inline gint64
1658 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1660 guint32 high = decode_int (buf, &buf, limit);
1661 guint32 low = decode_int (buf, &buf, limit);
1665 return ((((guint64)high) << 32) | ((guint64)low));
1669 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1671 return decode_int (buf, endbuf, limit);
1675 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1677 int len = decode_int (buf, &buf, limit);
1685 s = (char *)g_malloc (len + 1);
1688 memcpy (s, buf, len);
1697 * Functions to encode protocol data
1701 buffer_init (Buffer *buf, int size)
1703 buf->buf = (guint8 *)g_malloc (size);
1705 buf->end = buf->buf + size;
1709 buffer_len (Buffer *buf)
1711 return buf->p - buf->buf;
1715 buffer_make_room (Buffer *buf, int size)
1717 if (buf->end - buf->p < size) {
1718 int new_size = buf->end - buf->buf + size + 32;
1719 guint8 *p = (guint8 *)g_realloc (buf->buf, new_size);
1720 size = buf->p - buf->buf;
1723 buf->end = buf->buf + new_size;
1728 buffer_add_byte (Buffer *buf, guint8 val)
1730 buffer_make_room (buf, 1);
1736 buffer_add_short (Buffer *buf, guint32 val)
1738 buffer_make_room (buf, 2);
1739 buf->p [0] = (val >> 8) & 0xff;
1740 buf->p [1] = (val >> 0) & 0xff;
1745 buffer_add_int (Buffer *buf, guint32 val)
1747 buffer_make_room (buf, 4);
1748 buf->p [0] = (val >> 24) & 0xff;
1749 buf->p [1] = (val >> 16) & 0xff;
1750 buf->p [2] = (val >> 8) & 0xff;
1751 buf->p [3] = (val >> 0) & 0xff;
1756 buffer_add_long (Buffer *buf, guint64 l)
1758 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1759 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1763 buffer_add_id (Buffer *buf, int id)
1765 buffer_add_int (buf, (guint64)id);
1769 buffer_add_data (Buffer *buf, guint8 *data, int len)
1771 buffer_make_room (buf, len);
1772 memcpy (buf->p, data, len);
1777 buffer_add_string (Buffer *buf, const char *str)
1782 buffer_add_int (buf, 0);
1785 buffer_add_int (buf, len);
1786 buffer_add_data (buf, (guint8*)str, len);
1791 buffer_add_buffer (Buffer *buf, Buffer *data)
1793 buffer_add_data (buf, data->buf, buffer_len (data));
1797 buffer_free (Buffer *buf)
1803 send_packet (int command_set, int command, Buffer *data)
1809 id = InterlockedIncrement (&packet_id);
1811 len = data->p - data->buf + 11;
1812 buffer_init (&buf, len);
1813 buffer_add_int (&buf, len);
1814 buffer_add_int (&buf, id);
1815 buffer_add_byte (&buf, 0); /* flags */
1816 buffer_add_byte (&buf, command_set);
1817 buffer_add_byte (&buf, command);
1818 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1820 res = transport_send (buf.buf, len);
1828 send_reply_packets (int npackets, ReplyPacket *packets)
1835 for (i = 0; i < npackets; ++i)
1836 len += buffer_len (packets [i].data) + 11;
1837 buffer_init (&buf, len);
1838 for (i = 0; i < npackets; ++i) {
1839 buffer_add_int (&buf, buffer_len (packets [i].data) + 11);
1840 buffer_add_int (&buf, packets [i].id);
1841 buffer_add_byte (&buf, 0x80); /* flags */
1842 buffer_add_byte (&buf, (packets [i].error >> 8) & 0xff);
1843 buffer_add_byte (&buf, packets [i].error);
1844 buffer_add_buffer (&buf, packets [i].data);
1847 res = transport_send (buf.buf, len);
1855 send_reply_packet (int id, int error, Buffer *data)
1859 memset (&packet, 0, sizeof (ReplyPacket));
1861 packet.error = error;
1864 return send_reply_packets (1, &packet);
1868 send_buffered_reply_packets (void)
1872 send_reply_packets (nreply_packets, reply_packets);
1873 for (i = 0; i < nreply_packets; ++i)
1874 buffer_free (reply_packets [i].data);
1875 DEBUG_PRINTF (1, "[dbg] Sent %d buffered reply packets [at=%lx].\n", nreply_packets, (long)mono_100ns_ticks () / 10000);
1880 buffer_reply_packet (int id, int error, Buffer *data)
1884 if (nreply_packets == 128)
1885 send_buffered_reply_packets ();
1887 p = &reply_packets [nreply_packets];
1890 p->data = g_new0 (Buffer, 1);
1891 buffer_init (p->data, buffer_len (data));
1892 buffer_add_buffer (p->data, data);
1901 * Represents an object accessible by the debugger client.
1904 /* Unique id used in the wire protocol to refer to objects */
1907 * A weakref gc handle pointing to the object. The gc handle is used to
1908 * detect if the object was garbage collected.
1913 /* Maps objid -> ObjRef */
1914 /* Protected by the loader lock */
1915 static GHashTable *objrefs;
1916 /* Protected by the loader lock */
1917 static GHashTable *obj_to_objref;
1918 /* Protected by the dbg lock */
1919 static MonoGHashTable *suspended_objs;
1922 free_objref (gpointer value)
1924 ObjRef *o = (ObjRef *)value;
1926 mono_gchandle_free (o->handle);
1934 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1935 obj_to_objref = g_hash_table_new (NULL, NULL);
1936 suspended_objs = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_DEBUGGER, "suspended objects table");
1937 MONO_GC_REGISTER_ROOT_FIXED (suspended_objs, MONO_ROOT_SOURCE_DEBUGGER, "suspended objects table");
1941 objrefs_cleanup (void)
1943 g_hash_table_destroy (objrefs);
1948 * Return an ObjRef for OBJ.
1951 get_objref (MonoObject *obj)
1954 GSList *reflist = NULL, *l;
1960 if (suspend_count) {
1962 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1965 mono_g_hash_table_insert (suspended_objs, obj, NULL);
1969 mono_loader_lock ();
1971 /* FIXME: The tables can grow indefinitely */
1973 if (mono_gc_is_moving ()) {
1975 * Objects can move, so use a hash table mapping hash codes to lists of
1976 * ObjRef structures.
1978 hash = mono_object_hash (obj);
1980 reflist = (GSList *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1981 for (l = reflist; l; l = l->next) {
1982 ref = (ObjRef *)l->data;
1983 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1984 mono_loader_unlock ();
1989 /* Use a hash table with masked pointers to internalize object references */
1990 ref = (ObjRef *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1991 /* ref might refer to a different object with the same addr which was GCd */
1992 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1993 mono_loader_unlock ();
1998 ref = g_new0 (ObjRef, 1);
1999 ref->id = InterlockedIncrement (&objref_id);
2000 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
2002 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
2004 if (mono_gc_is_moving ()) {
2005 reflist = g_slist_append (reflist, ref);
2006 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
2008 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
2011 mono_loader_unlock ();
2017 true_pred (gpointer key, gpointer value, gpointer user_data)
2023 clear_suspended_objs (void)
2026 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
2031 get_objid (MonoObject *obj)
2036 return get_objref (obj)->id;
2040 * Set OBJ to the object identified by OBJID.
2041 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
2045 get_object_allow_null (int objid, MonoObject **obj)
2055 return ERR_INVALID_OBJECT;
2057 mono_loader_lock ();
2059 ref = (ObjRef *)g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
2062 *obj = mono_gchandle_get_target (ref->handle);
2063 mono_loader_unlock ();
2065 return ERR_INVALID_OBJECT;
2068 mono_loader_unlock ();
2069 return ERR_INVALID_OBJECT;
2074 get_object (int objid, MonoObject **obj)
2076 ErrorCode err = get_object_allow_null (objid, obj);
2078 if (err != ERR_NONE)
2081 return ERR_INVALID_OBJECT;
2086 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
2088 return decode_id (buf, endbuf, limit);
2092 buffer_add_objid (Buffer *buf, MonoObject *o)
2094 buffer_add_id (buf, get_objid (o));
2113 * Represents a runtime structure accessible to the debugger client
2116 /* Unique id used in the wire protocol */
2118 /* Domain of the runtime structure, NULL if the domain was unloaded */
2125 MonoAssembly *assembly;
2126 MonoClassField *field;
2128 MonoProperty *property;
2133 /* Maps runtime structure -> Id */
2134 /* Protected by the dbg lock */
2135 GHashTable *val_to_id [ID_NUM];
2136 /* Classes whose class load event has been sent */
2137 /* Protected by the loader lock */
2138 GHashTable *loaded_classes;
2139 /* Maps MonoClass->GPtrArray of file names */
2140 GHashTable *source_files;
2141 /* Maps source file basename -> GSList of classes */
2142 GHashTable *source_file_to_class;
2143 /* Same with ignore-case */
2144 GHashTable *source_file_to_class_ignorecase;
2148 /* Protected by the dbg lock */
2149 static GPtrArray *ids [ID_NUM];
2156 for (i = 0; i < ID_NUM; ++i)
2157 ids [i] = g_ptr_array_new ();
2165 for (i = 0; i < ID_NUM; ++i) {
2167 for (j = 0; j < ids [i]->len; ++j)
2168 g_free (g_ptr_array_index (ids [i], j));
2169 g_ptr_array_free (ids [i], TRUE);
2176 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2178 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2180 GHashTableIter iter;
2181 GPtrArray *file_names;
2186 for (i = 0; i < ID_NUM; ++i)
2187 if (info->val_to_id [i])
2188 g_hash_table_destroy (info->val_to_id [i]);
2189 g_hash_table_destroy (info->loaded_classes);
2191 g_hash_table_iter_init (&iter, info->source_files);
2192 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2193 for (i = 0; i < file_names->len; ++i)
2194 g_free (g_ptr_array_index (file_names, i));
2195 g_ptr_array_free (file_names, TRUE);
2198 g_hash_table_iter_init (&iter, info->source_file_to_class);
2199 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2204 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2205 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2213 domain_jit_info (domain)->agent_info = NULL;
2215 /* Clear ids referencing structures in the domain */
2217 for (i = 0; i < ID_NUM; ++i) {
2219 for (j = 0; j < ids [i]->len; ++j) {
2220 Id *id = (Id *)g_ptr_array_index (ids [i], j);
2221 if (id->domain == domain)
2228 mono_loader_lock ();
2229 g_hash_table_remove (domains, domain);
2230 mono_loader_unlock ();
2233 static AgentDomainInfo*
2234 get_agent_domain_info (MonoDomain *domain)
2236 AgentDomainInfo *info = NULL;
2238 mono_domain_lock (domain);
2240 info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2242 info = g_new0 (AgentDomainInfo, 1);
2243 domain_jit_info (domain)->agent_info = info;
2244 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2245 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2246 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2247 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2250 mono_domain_unlock (domain);
2256 get_id (MonoDomain *domain, IdType type, gpointer val)
2259 AgentDomainInfo *info;
2264 info = get_agent_domain_info (domain);
2268 if (info->val_to_id [type] == NULL)
2269 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2271 id = (Id *)g_hash_table_lookup (info->val_to_id [type], val);
2277 id = g_new0 (Id, 1);
2279 id->id = ids [type]->len + 1;
2280 id->domain = domain;
2283 g_hash_table_insert (info->val_to_id [type], val, id);
2284 g_ptr_array_add (ids [type], id);
2291 static inline gpointer
2292 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, ErrorCode *err)
2296 int id = decode_id (buf, endbuf, limit);
2305 // FIXME: error handling
2307 g_assert (id > 0 && id <= ids [type]->len);
2309 res = (Id *)g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2312 if (res->domain == NULL) {
2313 DEBUG_PRINTF (1, "ERR_UNLOADED, id=%d, type=%d.\n", id, type);
2314 *err = ERR_UNLOADED;
2319 *domain = res->domain;
2321 return res->data.val;
2325 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2327 int id = get_id (domain, type, val);
2329 buffer_add_id (buf, id);
2333 static inline MonoClass*
2334 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2338 klass = (MonoClass *)decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2339 if (G_UNLIKELY (log_level >= 2) && klass) {
2342 s = mono_type_full_name (&klass->byval_arg);
2343 DEBUG_PRINTF (2, "[dbg] recv class [%s]\n", s);
2349 static inline MonoAssembly*
2350 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2352 return (MonoAssembly *)decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2355 static inline MonoImage*
2356 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2358 return (MonoImage *)decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2361 static inline MonoMethod*
2362 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2366 m = (MonoMethod *)decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2367 if (G_UNLIKELY (log_level >= 2) && m) {
2370 s = mono_method_full_name (m, TRUE);
2371 DEBUG_PRINTF (2, "[dbg] recv method [%s]\n", s);
2377 static inline MonoClassField*
2378 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2380 return (MonoClassField *)decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2383 static inline MonoDomain*
2384 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2386 return (MonoDomain *)decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2389 static inline MonoProperty*
2390 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2392 return (MonoProperty *)decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2396 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2398 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2399 if (G_UNLIKELY (log_level >= 2) && klass) {
2402 s = mono_type_full_name (&klass->byval_arg);
2403 if (is_debugger_thread ())
2404 DEBUG_PRINTF (2, "[dbg] send class [%s]\n", s);
2406 DEBUG_PRINTF (2, "[%p] send class [%s]\n", (gpointer) (gsize) mono_native_thread_id_get (), s);
2412 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2414 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2415 if (G_UNLIKELY (log_level >= 2) && method) {
2418 s = mono_method_full_name (method, 1);
2419 DEBUG_PRINTF (2, "[dbg] send method [%s]\n", s);
2425 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2429 id = buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2430 if (G_UNLIKELY (log_level >= 2) && assembly)
2431 DEBUG_PRINTF (2, "[dbg] send assembly [%s][%s][%d]\n", assembly->aname.name, domain->friendly_name, id);
2435 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2437 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2441 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2443 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2447 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2449 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2453 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2455 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2458 static void invoke_method (void);
2465 * save_thread_context:
2467 * Set CTX as the current threads context which is used for computing stack traces.
2468 * This function is signal-safe.
2471 save_thread_context (MonoContext *ctx)
2473 DebuggerTlsData *tls;
2475 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2479 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2481 mono_thread_state_init_from_current (&tls->context);
2484 /* Number of threads suspended */
2486 * If this is equal to the size of thread_to_tls, the runtime is considered
2489 static gint32 threads_suspend_count;
2491 static MonoCoopMutex suspend_mutex;
2493 /* Cond variable used to wait for suspend_count becoming 0 */
2494 static MonoCoopCond suspend_cond;
2496 /* Semaphore used to wait for a thread becoming suspended */
2497 static MonoCoopSem suspend_sem;
2502 mono_coop_mutex_init (&suspend_mutex);
2503 mono_coop_cond_init (&suspend_cond);
2504 mono_coop_sem_init (&suspend_sem, 0);
2509 StackFrameInfo last_frame;
2510 gboolean last_frame_set;
2514 } GetLastFrameUserData;
2517 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2519 GetLastFrameUserData *data = (GetLastFrameUserData *)user_data;
2521 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE || info->type == FRAME_TYPE_TRAMPOLINE)
2524 if (!data->last_frame_set) {
2525 /* Store the last frame */
2526 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2527 data->last_frame_set = TRUE;
2530 /* Store the context/lmf for the frame above the last frame */
2531 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2532 data->lmf = info->lmf;
2533 data->domain = info->domain;
2539 copy_unwind_state_from_frame_data (MonoThreadUnwindState *to, GetLastFrameUserData *data, gpointer jit_tls)
2541 memcpy (&to->ctx, &data->ctx, sizeof (MonoContext));
2543 to->unwind_data [MONO_UNWIND_DATA_DOMAIN] = data->domain;
2544 to->unwind_data [MONO_UNWIND_DATA_LMF] = data->lmf;
2545 to->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = jit_tls;
2552 * Process interruption of a thread. This should be signal safe.
2554 * This always runs in the debugger thread.
2557 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, MonoJitInfo *ji)
2560 MonoNativeThreadId tid;
2564 ip = MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx);
2565 tid = mono_thread_info_get_tid (info);
2567 // FIXME: Races when the thread leaves managed code before hitting a single step
2570 if (ji && !ji->is_trampoline) {
2571 /* Running managed code, will be suspended by the single step code */
2572 DEBUG_PRINTF (1, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip);
2575 * Running native code, will be suspended when it returns to/enters
2576 * managed code. Treat it as already suspended.
2577 * This might interrupt the code in process_single_step_inner (), we use the
2578 * tls->suspending flag to avoid races when that happens.
2580 if (!tls->suspended && !tls->suspending) {
2581 GetLastFrameUserData data;
2583 // FIXME: printf is not signal safe, but this is only used during
2584 // debugger debugging
2586 DEBUG_PRINTF (1, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip);
2587 //save_thread_context (&ctx);
2590 /* Already terminated */
2594 * We are in a difficult position: we want to be able to provide stack
2595 * traces for this thread, but we can't use the current ctx+lmf, since
2596 * the thread is still running, so it might return to managed code,
2597 * making these invalid.
2598 * So we start a stack walk and save the first frame, along with the
2599 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2600 * suspended when it returns to managed code, so the parent's ctx should
2603 data.last_frame_set = FALSE;
2604 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, mono_thread_info_get_suspend_state (info), MONO_UNWIND_SIGNAL_SAFE, &data);
2605 if (data.last_frame_set) {
2606 gpointer jit_tls = ((MonoThreadInfo*)tls->thread->thread_info)->jit_data;
2608 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2610 copy_unwind_state_from_frame_data (&tls->async_state, &data, jit_tls);
2611 copy_unwind_state_from_frame_data (&tls->context, &data, jit_tls);
2613 tls->async_state.valid = FALSE;
2616 mono_memory_barrier ();
2618 tls->suspended = TRUE;
2619 mono_coop_sem_post (&suspend_sem);
2625 * reset_native_thread_suspend_state:
2627 * Reset the suspended flag and state on native threads
2630 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2632 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2634 if (!tls->really_suspended && tls->suspended) {
2635 tls->suspended = FALSE;
2637 * The thread might still be running if it was executing native code, so the state won't be invalided by
2638 * suspend_current ().
2640 tls->context.valid = FALSE;
2641 tls->async_state.valid = FALSE;
2642 invalidate_frames (tls);
2647 DebuggerTlsData *tls;
2648 gboolean valid_info;
2651 static SuspendThreadResult
2652 debugger_interrupt_critical (MonoThreadInfo *info, gpointer user_data)
2654 InterruptData *data = (InterruptData *)user_data;
2657 data->valid_info = TRUE;
2658 ji = mono_jit_info_table_find_internal (
2659 (MonoDomain *)mono_thread_info_get_suspend_state (info)->unwind_data [MONO_UNWIND_DATA_DOMAIN],
2660 (char *)MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx),
2664 /* This is signal safe */
2665 thread_interrupt (data->tls, info, ji);
2666 return MonoResumeThread;
2672 * Notify a thread that it needs to suspend.
2675 notify_thread (gpointer key, gpointer value, gpointer user_data)
2677 MonoInternalThread *thread = (MonoInternalThread *)key;
2678 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2679 MonoNativeThreadId tid = MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid);
2681 if (mono_native_thread_id_equals (mono_native_thread_id_get (), tid) || tls->terminated)
2684 DEBUG_PRINTF (1, "[%p] Interrupting %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2686 /* This is _not_ equivalent to mono_thread_internal_abort () */
2687 InterruptData interrupt_data = { 0 };
2688 interrupt_data.tls = tls;
2690 mono_thread_info_safe_suspend_and_run ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE, debugger_interrupt_critical, &interrupt_data);
2691 if (!interrupt_data.valid_info) {
2692 DEBUG_PRINTF (1, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2694 * Attached thread which died without detaching.
2696 tls->terminated = TRUE;
2701 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2703 guint8 *ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
2707 if (mono_loader_lock_is_owned_by_self ()) {
2709 * Shortcut for the check in suspend_current (). This speeds up processing
2710 * when executing long running code inside the loader lock, i.e. assembly load
2716 if (is_debugger_thread ())
2719 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2720 if (suspend_count - tls->resume_count > 0)
2721 tls->suspending = TRUE;
2723 DEBUG_PRINTF (1, "[%p] Received single step event for suspending.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2725 if (suspend_count - tls->resume_count == 0) {
2727 * We are executing a single threaded invoke but the single step for
2728 * suspending is still active.
2729 * FIXME: This slows down single threaded invokes.
2731 DEBUG_PRINTF (1, "[%p] Ignored during single threaded invoke.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2735 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2737 /* Can't suspend in these methods */
2738 method = jinfo_get_method (ji);
2739 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2742 save_thread_context (ctx);
2750 * Increase the suspend count of the VM. While the suspend count is greater
2751 * than 0, runtime threads are suspended at certain points during execution.
2756 mono_loader_lock ();
2758 mono_coop_mutex_lock (&suspend_mutex);
2762 DEBUG_PRINTF (1, "[%p] Suspending vm...\n", (gpointer) (gsize) mono_native_thread_id_get ());
2764 if (suspend_count == 1) {
2765 // FIXME: Is it safe to call this inside the lock ?
2766 start_single_stepping ();
2767 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2770 mono_coop_mutex_unlock (&suspend_mutex);
2772 if (suspend_count == 1)
2774 * Suspend creation of new threadpool threads, since they cannot run
2776 mono_threadpool_ms_suspend ();
2778 mono_loader_unlock ();
2784 * 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 mono_coop_cond_broadcast (&suspend_cond);
2810 mono_coop_mutex_unlock (&suspend_mutex);
2811 //g_assert (err == 0);
2813 if (suspend_count == 0)
2814 mono_threadpool_ms_resume ();
2816 mono_loader_unlock ();
2822 * Resume just one thread.
2825 resume_thread (MonoInternalThread *thread)
2827 DebuggerTlsData *tls;
2829 g_assert (is_debugger_thread ());
2831 mono_loader_lock ();
2833 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
2836 mono_coop_mutex_lock (&suspend_mutex);
2838 g_assert (suspend_count > 0);
2840 DEBUG_PRINTF (1, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid);
2842 tls->resume_count += suspend_count;
2845 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2846 * but only the one whose resume_count field is > 0 will be resumed.
2848 mono_coop_cond_broadcast (&suspend_cond);
2850 mono_coop_mutex_unlock (&suspend_mutex);
2851 //g_assert (err == 0);
2853 mono_loader_unlock ();
2857 free_frames (StackFrame **frames, int nframes)
2861 for (i = 0; i < nframes; ++i) {
2862 if (frames [i]->jit)
2863 mono_debug_free_method_jit_info (frames [i]->jit);
2864 g_free (frames [i]);
2870 invalidate_frames (DebuggerTlsData *tls)
2873 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2876 free_frames (tls->frames, tls->frame_count);
2877 tls->frame_count = 0;
2880 free_frames (tls->restore_frames, tls->restore_frame_count);
2881 tls->restore_frame_count = 0;
2882 tls->restore_frames = NULL;
2888 * Suspend the current thread until the runtime is resumed. If the thread has a
2889 * pending invoke, then the invoke is executed before this function returns.
2892 suspend_current (void)
2894 DebuggerTlsData *tls;
2896 g_assert (!is_debugger_thread ());
2898 if (mono_loader_lock_is_owned_by_self ()) {
2900 * If we own the loader mutex, can't suspend until we release it, since the
2901 * whole runtime can deadlock otherwise.
2906 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2909 mono_coop_mutex_lock (&suspend_mutex);
2911 tls->suspending = FALSE;
2912 tls->really_suspended = TRUE;
2914 if (!tls->suspended) {
2915 tls->suspended = TRUE;
2916 mono_coop_sem_post (&suspend_sem);
2919 DEBUG_PRINTF (1, "[%p] Suspended.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2921 while (suspend_count - tls->resume_count > 0) {
2922 mono_coop_cond_wait (&suspend_cond, &suspend_mutex);
2925 tls->suspended = FALSE;
2926 tls->really_suspended = FALSE;
2928 threads_suspend_count --;
2930 mono_coop_mutex_unlock (&suspend_mutex);
2932 DEBUG_PRINTF (1, "[%p] Resumed.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2934 if (tls->pending_invoke) {
2935 /* Save the original context */
2936 tls->pending_invoke->has_ctx = TRUE;
2937 tls->pending_invoke->ctx = tls->context.ctx;
2942 /* The frame info becomes invalid after a resume */
2943 tls->context.valid = FALSE;
2944 tls->async_state.valid = FALSE;
2945 invalidate_frames (tls);
2949 count_thread (gpointer key, gpointer value, gpointer user_data)
2951 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2953 if (!tls->suspended && !tls->terminated)
2954 *(int*)user_data = *(int*)user_data + 1;
2958 count_threads_to_wait_for (void)
2962 mono_loader_lock ();
2963 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2964 mono_loader_unlock ();
2972 * Wait until the runtime is completely suspended.
2975 wait_for_suspend (void)
2977 int nthreads, nwait, err;
2978 gboolean waited = FALSE;
2980 // FIXME: Threads starting/stopping ?
2981 mono_loader_lock ();
2982 nthreads = mono_g_hash_table_size (thread_to_tls);
2983 mono_loader_unlock ();
2986 nwait = count_threads_to_wait_for ();
2988 DEBUG_PRINTF (1, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads);
2989 err = mono_coop_sem_wait (&suspend_sem, MONO_SEM_FLAGS_NONE);
2990 g_assert (err == 0);
2998 DEBUG_PRINTF (1, "%d threads suspended.\n", nthreads);
3004 * Return whenever the runtime is suspended.
3009 return count_threads_to_wait_for () == 0;
3013 no_seq_points_found (MonoMethod *method, int offset)
3016 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3018 printf ("Unable to find seq points for method '%s', offset 0x%x.\n", mono_method_full_name (method, TRUE), offset);
3022 DebuggerTlsData *tls;
3024 } ComputeFramesUserData;
3027 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3029 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3031 MonoMethod *method, *actual_method, *api_method;
3035 if (info->type != FRAME_TYPE_MANAGED) {
3036 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3037 /* Mark the last frame as an invoke frame */
3039 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3045 method = jinfo_get_method (info->ji);
3047 method = info->method;
3048 actual_method = info->actual_method;
3049 api_method = method;
3054 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3057 if (info->il_offset == -1) {
3058 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3059 if (ud->frames == NULL) {
3060 if (mono_find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL, &sp))
3061 info->il_offset = sp.il_offset;
3063 if (info->il_offset == -1)
3064 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3067 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);
3069 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3070 if (!CHECK_PROTOCOL_VERSION (2, 17))
3071 /* Older clients can't handle this flag */
3073 api_method = mono_marshal_method_from_wrapper (method);
3076 actual_method = api_method;
3077 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3080 frame = g_new0 (StackFrame, 1);
3081 frame->method = method;
3082 frame->actual_method = actual_method;
3083 frame->api_method = api_method;
3084 frame->il_offset = info->il_offset;
3085 frame->native_offset = info->native_offset;
3086 frame->flags = flags;
3087 frame->ji = info->ji;
3088 if (info->reg_locations)
3089 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3092 frame->has_ctx = TRUE;
3094 frame->domain = info->domain;
3096 ud->frames = g_slist_append (ud->frames, frame);
3102 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3104 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3107 * 'tls->filter_ctx' is the location of the throw site.
3109 * mono_walk_stack() will never actually hit the throw site, but unwind
3110 * directly from the filter to the call site; we abort stack unwinding here
3111 * once this happens and resume from the throw site.
3114 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3117 return process_frame (info, ctx, user_data);
3121 * Return a malloc-ed list of StackFrame structures.
3124 compute_frame_info_from (MonoInternalThread *thread, DebuggerTlsData *tls, MonoThreadUnwindState *state, int *out_nframes)
3126 ComputeFramesUserData user_data;
3127 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3132 user_data.tls = tls;
3133 user_data.frames = NULL;
3135 mono_walk_stack_with_state (process_frame, state, opts, &user_data);
3137 nframes = g_slist_length (user_data.frames);
3138 res = g_new0 (StackFrame*, nframes);
3139 l = user_data.frames;
3140 for (i = 0; i < nframes; ++i) {
3141 res [i] = (StackFrame *)l->data;
3144 *out_nframes = nframes;
3150 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3152 ComputeFramesUserData user_data;
3154 int i, findex, new_frame_count;
3155 StackFrame **new_frames, *f;
3156 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3158 // FIXME: Locking on tls
3159 if (tls->frames && tls->frames_up_to_date)
3162 DEBUG_PRINTF (1, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid);
3164 user_data.tls = tls;
3165 user_data.frames = NULL;
3166 if (tls->terminated) {
3167 tls->frame_count = 0;
3169 } if (!tls->really_suspended && tls->async_state.valid) {
3170 /* Have to use the state saved by the signal handler */
3171 process_frame (&tls->async_last_frame, NULL, &user_data);
3172 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3173 } else if (tls->filter_state.valid) {
3175 * We are inside an exception filter.
3177 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3179 if (tls->context.valid)
3180 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3182 * After that, we resume unwinding from the location where the exception has been thrown.
3184 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3185 } else if (tls->context.valid) {
3186 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3189 tls->frame_count = 0;
3193 new_frame_count = g_slist_length (user_data.frames);
3194 new_frames = g_new0 (StackFrame*, new_frame_count);
3196 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3197 f = (StackFrame *)tmp->data;
3200 * Reuse the id for already existing stack frames, so invokes don't invalidate
3201 * the still valid stack frames.
3203 for (i = 0; i < tls->frame_count; ++i) {
3204 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3205 f->id = tls->frames [i]->id;
3210 if (i >= tls->frame_count)
3211 f->id = InterlockedIncrement (&frame_id);
3213 new_frames [findex ++] = f;
3216 g_slist_free (user_data.frames);
3218 invalidate_frames (tls);
3220 tls->frames = new_frames;
3221 tls->frame_count = new_frame_count;
3222 tls->frames_up_to_date = TRUE;
3226 * GHFunc to emit an appdomain creation event
3227 * @param key Don't care
3228 * @param value A loaded appdomain
3229 * @param user_data Don't care
3232 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3234 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3235 g_hash_table_foreach (get_agent_domain_info ((MonoDomain *)value)->loaded_classes, emit_type_load, NULL);
3239 * GHFunc to emit a thread start event
3240 * @param key A thread id
3241 * @param value A thread object
3242 * @param user_data Don't care
3245 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3247 if (!mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (GPOINTER_TO_UINT (key)), debugger_thread_id))
3248 process_profiler_event (EVENT_KIND_THREAD_START, value);
3252 * GFunc to emit an assembly load event
3253 * @param value A loaded assembly
3254 * @param user_data Don't care
3257 emit_assembly_load (gpointer value, gpointer user_data)
3259 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3263 * GFunc to emit a type load event
3264 * @param value A loaded type
3265 * @param user_data Don't care
3268 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3270 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3274 strdup_tolower (char *s)
3279 for (p = s2; *p; ++p)
3285 * Same as g_path_get_basename () but handles windows paths as well,
3286 * which can occur in .mdb files created by pdb2mdb.
3289 dbg_path_get_basename (const char *filename)
3293 if (!filename || strchr (filename, '/') || !strchr (filename, '\\'))
3294 return g_path_get_basename (filename);
3298 /* No separator -> filename */
3299 r = strrchr (filename, '\\');
3301 return g_strdup (filename);
3303 /* Trailing slash, remove component */
3305 char *copy = g_strdup (filename);
3306 copy [r-filename] = 0;
3307 r = strrchr (copy, '\\');
3311 return g_strdup ("/");
3313 r = g_strdup (&r[1]);
3318 return g_strdup (&r[1]);
3322 init_jit_info_dbg_attrs (MonoJitInfo *ji)
3324 static MonoClass *hidden_klass, *step_through_klass, *non_user_klass;
3326 MonoCustomAttrInfo *ainfo;
3328 if (ji->dbg_attrs_inited)
3332 hidden_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3334 if (!step_through_klass)
3335 step_through_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3337 if (!non_user_klass)
3338 non_user_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute");
3340 ainfo = mono_custom_attrs_from_method_checked (jinfo_get_method (ji), &error);
3341 mono_error_cleanup (&error); /* FIXME don't swallow the error? */
3343 if (mono_custom_attrs_has_attr (ainfo, hidden_klass))
3344 ji->dbg_hidden = TRUE;
3345 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3346 ji->dbg_step_through = TRUE;
3347 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3348 ji->dbg_non_user_code = TRUE;
3349 mono_custom_attrs_free (ainfo);
3352 ainfo = mono_custom_attrs_from_class_checked (jinfo_get_method (ji)->klass, &error);
3353 mono_error_cleanup (&error); /* FIXME don't swallow the error? */
3355 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3356 ji->dbg_step_through = TRUE;
3357 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3358 ji->dbg_non_user_code = TRUE;
3359 mono_custom_attrs_free (ainfo);
3362 mono_memory_barrier ();
3363 ji->dbg_attrs_inited = TRUE;
3371 * create_event_list:
3373 * Return a list of event request ids matching EVENT, starting from REQS, which
3374 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3376 * We return request ids, instead of requests, to simplify threading, since
3377 * requests could be deleted anytime when the loader lock is not held.
3378 * LOCKING: Assumes the loader lock is held.
3381 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3384 GSList *events = NULL;
3386 *suspend_policy = SUSPEND_POLICY_NONE;
3389 reqs = event_requests;
3394 for (i = 0; i < reqs->len; ++i) {
3395 EventRequest *req = (EventRequest *)g_ptr_array_index (reqs, i);
3396 if (req->event_kind == event) {
3397 gboolean filtered = FALSE;
3400 for (j = 0; j < req->nmodifiers; ++j) {
3401 Modifier *mod = &req->modifiers [j];
3403 if (mod->kind == MOD_KIND_COUNT) {
3405 if (mod->data.count > 0) {
3406 if (mod->data.count > 0) {
3408 if (mod->data.count == 0)
3412 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3413 if (mod->data.thread != mono_thread_internal_current ())
3415 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3416 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3418 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3420 if (ei->caught && !mod->caught)
3422 if (!ei->caught && !mod->uncaught)
3424 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3426 gboolean found = FALSE;
3427 MonoAssembly **assemblies = mod->data.assemblies;
3430 for (k = 0; assemblies [k]; ++k)
3431 if (assemblies [k] == jinfo_get_method (ji)->klass->image->assembly)
3436 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3437 gpointer iter = NULL;
3439 MonoDebugSourceInfo *sinfo;
3440 char *source_file, *s;
3441 gboolean found = FALSE;
3443 GPtrArray *source_file_list;
3445 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3446 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3449 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, NULL, NULL, NULL);
3450 for (i = 0; i < source_file_list->len; ++i) {
3451 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
3453 * Do a case-insesitive match by converting the file name to
3456 s = strdup_tolower (sinfo->source_file);
3457 if (g_hash_table_lookup (mod->data.source_files, s))
3460 char *s2 = dbg_path_get_basename (sinfo->source_file);
3461 char *s3 = strdup_tolower (s2);
3463 if (g_hash_table_lookup (mod->data.source_files, s3))
3470 g_ptr_array_free (source_file_list, TRUE);
3475 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3478 s = mono_type_full_name (&ei->klass->byval_arg);
3479 if (!g_hash_table_lookup (mod->data.type_names, s))
3482 } else if (mod->kind == MOD_KIND_STEP) {
3483 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3484 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3485 !strcmp (jinfo_get_method (ji)->name, ".cctor") &&
3486 (jinfo_get_method (ji) != ((SingleStepReq*)req->info)->start_method))
3488 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3489 init_jit_info_dbg_attrs (ji);
3493 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3494 init_jit_info_dbg_attrs (ji);
3495 if (ji->dbg_step_through)
3498 if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3499 init_jit_info_dbg_attrs (ji);
3500 if (ji->dbg_non_user_code)
3507 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3508 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3513 /* Send a VM START/DEATH event by default */
3514 if (event == EVENT_KIND_VM_START)
3515 events = g_slist_append (events, GINT_TO_POINTER (0));
3516 if (event == EVENT_KIND_VM_DEATH)
3517 events = g_slist_append (events, GINT_TO_POINTER (0));
3522 static G_GNUC_UNUSED const char*
3523 event_to_string (EventKind event)
3526 case EVENT_KIND_VM_START: return "VM_START";
3527 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3528 case EVENT_KIND_THREAD_START: return "THREAD_START";
3529 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3530 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3531 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3532 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3533 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3534 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3535 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3536 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3537 case EVENT_KIND_STEP: return "STEP";
3538 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3539 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3540 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3541 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3542 case EVENT_KIND_USER_LOG: return "USER_LOG";
3544 g_assert_not_reached ();
3552 * Send an event to the client, suspending the vm if needed.
3553 * LOCKING: Since this can suspend the calling thread, no locks should be held
3555 * The EVENTS list is freed by this function.
3558 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3562 MonoDomain *domain = mono_domain_get ();
3563 MonoThread *thread = NULL;
3564 MonoObject *keepalive_obj = NULL;
3565 gboolean send_success = FALSE;
3570 DEBUG_PRINTF (2, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event));
3574 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3575 // FIXME: We miss those events
3576 DEBUG_PRINTF (2, "VM start event not sent yet: dropping %s\n", event_to_string (event));
3580 if (vm_death_event_sent) {
3581 DEBUG_PRINTF (2, "VM death event has been sent: dropping %s\n", event_to_string (event));
3585 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3586 DEBUG_PRINTF (2, "Mono runtime is shutting down: dropping %s\n", event_to_string (event));
3591 DEBUG_PRINTF (2, "Debugger client is not connected: dropping %s\n", event_to_string (event));
3595 if (event == EVENT_KIND_KEEPALIVE)
3596 suspend_policy = SUSPEND_POLICY_NONE;
3601 if (agent_config.defer) {
3602 /* Make sure the thread id is always set when doing deferred debugging */
3603 if (is_debugger_thread ()) {
3604 /* Don't suspend on events from the debugger thread */
3605 suspend_policy = SUSPEND_POLICY_NONE;
3606 thread = mono_thread_get_main ();
3608 else thread = mono_thread_current ();
3610 if (is_debugger_thread () && event != EVENT_KIND_VM_DEATH)
3611 // FIXME: Send these with a NULL thread, don't suspend the current thread
3616 nevents = g_slist_length (events);
3617 buffer_init (&buf, 128);
3618 buffer_add_byte (&buf, suspend_policy);
3619 buffer_add_int (&buf, nevents);
3621 for (l = events; l; l = l->next) {
3622 buffer_add_byte (&buf, event); // event kind
3623 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3627 if (event == EVENT_KIND_VM_DEATH) {
3631 thread = mono_thread_current ();
3633 if (event == EVENT_KIND_VM_START && arg != NULL)
3634 thread = (MonoThread *)arg;
3637 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3640 case EVENT_KIND_THREAD_START:
3641 case EVENT_KIND_THREAD_DEATH:
3643 case EVENT_KIND_APPDOMAIN_CREATE:
3644 case EVENT_KIND_APPDOMAIN_UNLOAD:
3645 buffer_add_domainid (&buf, (MonoDomain *)arg);
3647 case EVENT_KIND_METHOD_ENTRY:
3648 case EVENT_KIND_METHOD_EXIT:
3649 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3651 case EVENT_KIND_ASSEMBLY_LOAD:
3652 buffer_add_assemblyid (&buf, domain, (MonoAssembly *)arg);
3654 case EVENT_KIND_ASSEMBLY_UNLOAD: {
3655 DebuggerTlsData *tls;
3657 /* The domain the assembly belonged to is not equal to the current domain */
3658 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3660 g_assert (tls->domain_unloading);
3662 buffer_add_assemblyid (&buf, tls->domain_unloading, (MonoAssembly *)arg);
3665 case EVENT_KIND_TYPE_LOAD:
3666 buffer_add_typeid (&buf, domain, (MonoClass *)arg);
3668 case EVENT_KIND_BREAKPOINT:
3669 case EVENT_KIND_STEP:
3670 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3671 buffer_add_long (&buf, il_offset);
3673 case EVENT_KIND_VM_START:
3674 buffer_add_domainid (&buf, mono_get_root_domain ());
3676 case EVENT_KIND_VM_DEATH:
3677 if (CHECK_PROTOCOL_VERSION (2, 27))
3678 buffer_add_int (&buf, mono_environment_exitcode_get ());
3680 case EVENT_KIND_EXCEPTION: {
3681 EventInfo *ei = (EventInfo *)arg;
3682 buffer_add_objid (&buf, ei->exc);
3684 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3685 * later after the suspension. (#12494).
3687 keepalive_obj = ei->exc;
3690 case EVENT_KIND_USER_BREAK:
3692 case EVENT_KIND_USER_LOG: {
3693 EventInfo *ei = (EventInfo *)arg;
3694 buffer_add_int (&buf, ei->level);
3695 buffer_add_string (&buf, ei->category ? ei->category : "");
3696 buffer_add_string (&buf, ei->message ? ei->message : "");
3699 case EVENT_KIND_KEEPALIVE:
3700 suspend_policy = SUSPEND_POLICY_NONE;
3703 g_assert_not_reached ();
3707 if (event == EVENT_KIND_VM_START) {
3708 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3709 if (!agent_config.defer)
3710 start_debugger_thread ();
3713 if (event == EVENT_KIND_VM_DEATH) {
3714 vm_death_event_sent = TRUE;
3715 suspend_policy = SUSPEND_POLICY_NONE;
3718 if (mono_runtime_is_shutting_down ())
3719 suspend_policy = SUSPEND_POLICY_NONE;
3721 if (suspend_policy != SUSPEND_POLICY_NONE) {
3723 * Save the thread context and start suspending before sending the packet,
3724 * since we could be receiving the resume request before send_packet ()
3727 save_thread_context (ctx);
3731 /* This will keep this object alive */
3732 get_objref (keepalive_obj);
3735 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3739 g_slist_free (events);
3742 if (!send_success) {
3743 DEBUG_PRINTF (2, "Sending command %s failed.\n", event_to_string (event));
3747 if (event == EVENT_KIND_VM_START) {
3748 vm_start_event_sent = TRUE;
3751 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);
3753 switch (suspend_policy) {
3754 case SUSPEND_POLICY_NONE:
3756 case SUSPEND_POLICY_ALL:
3759 case SUSPEND_POLICY_EVENT_THREAD:
3763 g_assert_not_reached ();
3768 process_profiler_event (EventKind event, gpointer arg)
3772 EventInfo ei, *ei_arg = NULL;
3774 if (event == EVENT_KIND_TYPE_LOAD) {
3775 ei.klass = (MonoClass *)arg;
3779 mono_loader_lock ();
3780 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3781 mono_loader_unlock ();
3783 process_event (event, arg, 0, NULL, events, suspend_policy);
3787 runtime_initialized (MonoProfiler *prof)
3789 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3790 if (agent_config.defer)
3791 start_debugger_thread ();
3795 runtime_shutdown (MonoProfiler *prof)
3797 process_profiler_event (EVENT_KIND_VM_DEATH, NULL);
3799 mono_debugger_agent_cleanup ();
3803 thread_startup (MonoProfiler *prof, uintptr_t tid)
3805 MonoInternalThread *thread = mono_thread_internal_current ();
3806 MonoInternalThread *old_thread;
3807 DebuggerTlsData *tls;
3809 if (mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (tid), debugger_thread_id))
3812 g_assert (mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (tid), MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid)));
3814 mono_loader_lock ();
3815 old_thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3816 mono_loader_unlock ();
3818 if (thread == old_thread) {
3820 * For some reason, thread_startup () might be called for the same thread
3821 * multiple times (attach ?).
3823 DEBUG_PRINTF (1, "[%p] thread_start () called multiple times for %p, ignored.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3827 * thread_end () might not be called for some threads, and the tid could
3830 DEBUG_PRINTF (1, "[%p] Removing stale data for tid %p.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3831 mono_loader_lock ();
3832 mono_g_hash_table_remove (thread_to_tls, old_thread);
3833 mono_g_hash_table_remove (tid_to_thread, GUINT_TO_POINTER (tid));
3834 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3835 mono_loader_unlock ();
3839 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3841 // FIXME: Free this somewhere
3842 tls = g_new0 (DebuggerTlsData, 1);
3843 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread, MONO_ROOT_SOURCE_DEBUGGER, "debugger thread reference");
3844 tls->thread = thread;
3845 mono_native_tls_set_value (debugger_tls_id, tls);
3847 DEBUG_PRINTF (1, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3849 mono_loader_lock ();
3850 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3851 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3852 mono_g_hash_table_insert (tid_to_thread_obj, GUINT_TO_POINTER (tid), mono_thread_current ());
3853 mono_loader_unlock ();
3855 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3858 * suspend_vm () could have missed this thread, so wait for a resume.
3864 thread_end (MonoProfiler *prof, uintptr_t tid)
3866 MonoInternalThread *thread;
3867 DebuggerTlsData *tls = NULL;
3869 mono_loader_lock ();
3870 thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3872 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3873 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
3875 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3876 tls->terminated = TRUE;
3877 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3878 MONO_GC_UNREGISTER_ROOT (tls->thread);
3882 mono_loader_unlock ();
3884 /* We might be called for threads started before we registered the start callback */
3886 DEBUG_PRINTF (1, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3888 if (mono_native_thread_id_equals (mono_native_thread_id_get (), MONO_UINT_TO_NATIVE_THREAD_ID (tid))
3889 && !mono_native_tls_get_value (debugger_tls_id)
3892 * This can happen on darwin since we deregister threads using pthread dtors.
3893 * process_profiler_event () and the code it calls cannot handle a null TLS value.
3898 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3903 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3905 mono_loader_lock ();
3906 g_hash_table_insert (domains, domain, domain);
3907 mono_loader_unlock ();
3909 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3913 appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain)
3915 DebuggerTlsData *tls;
3917 /* This might be called during shutdown on the debugger thread from the CMD_VM_EXIT code */
3918 if (is_debugger_thread ())
3922 * Remember the currently unloading appdomain as it is needed to generate
3923 * proper ids for unloading assemblies.
3925 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3927 tls->domain_unloading = domain;
3931 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3933 DebuggerTlsData *tls;
3935 if (is_debugger_thread ())
3938 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3940 tls->domain_unloading = NULL;
3942 clear_breakpoints_for_domain (domain);
3944 mono_loader_lock ();
3945 /* Invalidate each thread's frame stack */
3946 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3947 mono_loader_unlock ();
3949 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3953 * invalidate_each_thread:
3955 * A GHFunc to invalidate frames.
3956 * value must be a DebuggerTlsData*
3959 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3961 invalidate_frames ((DebuggerTlsData *)value);
3965 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3967 /* Sent later in jit_end () */
3969 g_ptr_array_add (pending_assembly_loads, assembly);
3974 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3976 if (is_debugger_thread ())
3979 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3981 clear_event_requests_for_assembly (assembly);
3982 clear_types_for_assembly (assembly);
3986 send_type_load (MonoClass *klass)
3988 gboolean type_load = FALSE;
3989 MonoDomain *domain = mono_domain_get ();
3990 AgentDomainInfo *info = NULL;
3992 info = get_agent_domain_info (domain);
3994 mono_loader_lock ();
3996 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
3998 g_hash_table_insert (info->loaded_classes, klass, klass);
4001 mono_loader_unlock ();
4004 emit_type_load (klass, klass, NULL);
4008 * Emit load events for all types currently loaded in the domain.
4009 * Takes the loader and domain locks.
4010 * user_data is unused.
4013 send_types_for_domain (MonoDomain *domain, void *user_data)
4015 AgentDomainInfo *info = NULL;
4017 info = get_agent_domain_info (domain);
4020 mono_loader_lock ();
4021 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4022 mono_loader_unlock ();
4026 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
4029 * We emit type load events when the first method of the type is JITted,
4030 * since the class load profiler callbacks might be called with the
4031 * loader lock held. They could also occur in the debugger thread.
4032 * Same for assembly load events.
4035 MonoAssembly *assembly = NULL;
4037 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4039 if (pending_assembly_loads->len > 0) {
4040 assembly = (MonoAssembly *)g_ptr_array_index (pending_assembly_loads, 0);
4041 g_ptr_array_remove_index (pending_assembly_loads, 0);
4046 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4052 send_type_load (method->klass);
4055 add_pending_breakpoints (method, jinfo);
4059 * BREAKPOINTS/SINGLE STEPPING
4063 * Contains information about an inserted breakpoint.
4066 long il_offset, native_offset;
4070 } BreakpointInstance;
4073 * Contains generic information about a breakpoint.
4077 * The method where the breakpoint is placed. Can be NULL in which case it
4078 * is inserted into every method. This is used to implement method entry/
4079 * exit events. Can be a generic method definition, in which case the
4080 * breakpoint is inserted into every instance.
4086 * A list of BreakpointInstance structures describing where the breakpoint
4087 * was inserted. There could be more than one because of
4088 * generics/appdomains/method entry/exit.
4090 GPtrArray *children;
4093 /* List of breakpoints */
4094 /* Protected by the loader lock */
4095 static GPtrArray *breakpoints;
4096 /* Maps breakpoint locations to the number of breakpoints at that location */
4097 static GHashTable *bp_locs;
4100 breakpoints_init (void)
4102 breakpoints = g_ptr_array_new ();
4103 bp_locs = g_hash_table_new (NULL, NULL);
4107 * insert_breakpoint:
4109 * Insert the breakpoint described by BP into the method described by
4113 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4116 BreakpointInstance *inst;
4117 SeqPointIterator it;
4118 gboolean it_has_sp = FALSE;
4121 mono_error_init (error);
4123 mono_seq_point_iterator_init (&it, seq_points);
4124 while (mono_seq_point_iterator_next (&it)) {
4125 if (it.seq_point.il_offset == bp->il_offset) {
4133 * The set of IL offsets with seq points doesn't completely match the
4134 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4136 mono_seq_point_iterator_init (&it, seq_points);
4137 while (mono_seq_point_iterator_next (&it)) {
4138 if (it.seq_point.il_offset != METHOD_ENTRY_IL_OFFSET &&
4139 it.seq_point.il_offset != METHOD_EXIT_IL_OFFSET &&
4140 it.seq_point.il_offset + 1 == bp->il_offset) {
4148 char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d", mono_method_full_name (jinfo_get_method (ji), TRUE), bp->il_offset);
4150 mono_seq_point_iterator_init (&it, seq_points);
4151 while (mono_seq_point_iterator_next (&it))
4152 DEBUG_PRINTF (1, "%d\n", it.seq_point.il_offset);
4155 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4156 g_warning ("%s", s);
4160 g_warning ("%s", s);
4166 inst = g_new0 (BreakpointInstance, 1);
4167 inst->il_offset = it.seq_point.il_offset;
4168 inst->native_offset = it.seq_point.native_offset;
4169 inst->ip = (guint8*)ji->code_start + it.seq_point.native_offset;
4171 inst->domain = domain;
4173 mono_loader_lock ();
4175 g_ptr_array_add (bp->children, inst);
4177 mono_loader_unlock ();
4180 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4181 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4184 if (it.seq_point.native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4185 DEBUG_PRINTF (1, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset);
4186 } else if (count == 0) {
4187 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4188 mono_arch_set_breakpoint (ji, inst->ip);
4194 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);
4198 remove_breakpoint (BreakpointInstance *inst)
4200 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4202 MonoJitInfo *ji = inst->ji;
4203 guint8 *ip = inst->ip;
4206 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4207 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4210 g_assert (count > 0);
4212 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4213 mono_arch_clear_breakpoint (ji, ip);
4214 DEBUG_PRINTF (1, "[dbg] Clear breakpoint at %s [%p].\n", mono_method_full_name (jinfo_get_method (ji), TRUE), ip);
4222 * This doesn't take any locks.
4224 static inline gboolean
4225 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4231 if (method == bp->method)
4233 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4236 if (bp->method->is_inflated && method->is_inflated) {
4237 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4238 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4240 /* Open generic methods should match closed generic methods of the same class */
4241 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4242 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4243 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4245 /* FIXME: Handle !mvar */
4246 if (t1->type != MONO_TYPE_MVAR)
4257 * add_pending_breakpoints:
4259 * Insert pending breakpoints into the newly JITted method METHOD.
4262 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4265 MonoSeqPointInfo *seq_points;
4267 MonoMethod *jmethod;
4272 domain = mono_domain_get ();
4274 mono_loader_lock ();
4276 for (i = 0; i < breakpoints->len; ++i) {
4277 MonoBreakpoint *bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4278 gboolean found = FALSE;
4280 if (!bp_matches_method (bp, method))
4283 for (j = 0; j < bp->children->len; ++j) {
4284 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4291 MonoMethod *declaring = NULL;
4293 jmethod = jinfo_get_method (ji);
4294 if (jmethod->is_inflated)
4295 declaring = mono_method_get_declaring_generic_method (jmethod);
4297 mono_domain_lock (domain);
4298 seq_points = (MonoSeqPointInfo *)g_hash_table_lookup (domain_jit_info (domain)->seq_points, jmethod);
4299 if (!seq_points && declaring)
4300 seq_points = (MonoSeqPointInfo *)g_hash_table_lookup (domain_jit_info (domain)->seq_points, declaring);
4301 mono_domain_unlock (domain);
4303 /* Could be AOT code */
4305 g_assert (seq_points);
4307 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4311 mono_loader_unlock ();
4315 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4321 mono_error_init (error);
4323 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4327 /* Might be AOTed code */
4328 mono_class_init (method->klass);
4329 code = mono_aot_get_method_checked (domain, method, &oerror);
4331 mono_error_assert_ok (&oerror);
4332 ji = mono_jit_info_table_find (domain, (char *)code);
4337 insert_breakpoint (seq_points, domain, ji, bp, error);
4341 clear_breakpoint (MonoBreakpoint *bp);
4346 * Set a breakpoint at IL_OFFSET in METHOD.
4347 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4348 * METHOD can also be a generic method definition, in which case a breakpoint
4349 * is placed in all instances of the method.
4350 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4353 static MonoBreakpoint*
4354 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4357 GHashTableIter iter, iter2;
4360 MonoSeqPointInfo *seq_points;
4362 GPtrArray *method_domains;
4363 GPtrArray *method_seq_points;
4367 mono_error_init (error);
4370 // - suspend/resume the vm to prevent code patching problems
4371 // - multiple breakpoints on the same location
4372 // - dynamic methods
4375 bp = g_new0 (MonoBreakpoint, 1);
4376 bp->method = method;
4377 bp->il_offset = il_offset;
4379 bp->children = g_ptr_array_new ();
4381 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);
4383 methods = g_ptr_array_new ();
4384 method_domains = g_ptr_array_new ();
4385 method_seq_points = g_ptr_array_new ();
4387 mono_loader_lock ();
4388 g_hash_table_iter_init (&iter, domains);
4389 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4390 mono_domain_lock (domain);
4391 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4392 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4393 if (bp_matches_method (bp, m)) {
4394 /* Save the info locally to simplify the code inside the domain lock */
4395 g_ptr_array_add (methods, m);
4396 g_ptr_array_add (method_domains, domain);
4397 g_ptr_array_add (method_seq_points, seq_points);
4400 mono_domain_unlock (domain);
4403 for (i = 0; i < methods->len; ++i) {
4404 m = (MonoMethod *)g_ptr_array_index (methods, i);
4405 domain = (MonoDomain *)g_ptr_array_index (method_domains, i);
4406 seq_points = (MonoSeqPointInfo *)g_ptr_array_index (method_seq_points, i);
4407 set_bp_in_method (domain, m, seq_points, bp, error);
4410 g_ptr_array_add (breakpoints, bp);
4411 mono_loader_unlock ();
4413 g_ptr_array_free (methods, TRUE);
4414 g_ptr_array_free (method_domains, TRUE);
4415 g_ptr_array_free (method_seq_points, TRUE);
4417 if (error && !mono_error_ok (error)) {
4418 clear_breakpoint (bp);
4426 clear_breakpoint (MonoBreakpoint *bp)
4430 // FIXME: locking, races
4431 for (i = 0; i < bp->children->len; ++i) {
4432 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, i);
4434 remove_breakpoint (inst);
4439 mono_loader_lock ();
4440 g_ptr_array_remove (breakpoints, bp);
4441 mono_loader_unlock ();
4443 g_ptr_array_free (bp->children, TRUE);
4448 breakpoints_cleanup (void)
4452 mono_loader_lock ();
4454 while (i < event_requests->len) {
4455 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
4457 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4458 clear_breakpoint ((MonoBreakpoint *)req->info);
4459 g_ptr_array_remove_index_fast (event_requests, i);
4466 for (i = 0; i < breakpoints->len; ++i)
4467 g_free (g_ptr_array_index (breakpoints, i));
4469 g_ptr_array_free (breakpoints, TRUE);
4470 g_hash_table_destroy (bp_locs);
4475 mono_loader_unlock ();
4479 * clear_breakpoints_for_domain:
4481 * Clear breakpoint instances which reference DOMAIN.
4484 clear_breakpoints_for_domain (MonoDomain *domain)
4488 /* This could be called after shutdown */
4492 mono_loader_lock ();
4493 for (i = 0; i < breakpoints->len; ++i) {
4494 MonoBreakpoint *bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4497 while (j < bp->children->len) {
4498 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4500 if (inst->domain == domain) {
4501 remove_breakpoint (inst);
4505 g_ptr_array_remove_index_fast (bp->children, j);
4511 mono_loader_unlock ();
4515 * ss_calculate_framecount:
4517 * Ensure DebuggerTlsData fields are filled out.
4519 static void ss_calculate_framecount (DebuggerTlsData *tls, MonoContext *ctx)
4521 if (!tls->context.valid)
4522 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4523 compute_frame_info (tls->thread, tls);
4529 * Return FALSE if single stepping needs to continue.
4532 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp, DebuggerTlsData *tls, MonoContext *ctx)
4534 MonoDebugMethodInfo *minfo;
4535 MonoDebugSourceLocation *loc = NULL;
4536 gboolean hit = TRUE;
4539 if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK)) {
4541 * These seq points are inserted by the JIT after calls, step over needs to skip them.
4543 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);
4547 if ((req->depth == STEP_DEPTH_OVER || req->depth == STEP_DEPTH_OUT) && hit) {
4548 gboolean is_step_out = req->depth == STEP_DEPTH_OUT;
4550 ss_calculate_framecount (tls, ctx);
4552 // Because functions can call themselves recursively, we need to make sure we're stopping at the right stack depth.
4553 // In case of step out, the target is the frame *enclosing* the one where the request was made.
4554 int target_frames = req->nframes + (is_step_out ? -1 : 0);
4555 if (req->nframes > 0 && tls->frame_count > 0 && tls->frame_count > target_frames) {
4556 /* Hit the breakpoint in a recursive call, don't halt */
4557 DEBUG_PRINTF (1, "[%p] Breakpoint at lower frame while stepping %s, continuing single stepping.\n", (gpointer) (gsize) mono_native_thread_id_get (), is_step_out ? "out" : "over");
4562 if (req->depth == STEP_DEPTH_INTO && req->size == STEP_SIZE_MIN && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) && ss_req->start_method){
4563 method = jinfo_get_method (ji);
4564 ss_calculate_framecount (tls, ctx);
4565 if (ss_req->start_method == method && req->nframes && tls->frame_count == req->nframes) {//Check also frame count(could be recursion)
4566 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);
4571 if (req->size != STEP_SIZE_LINE)
4574 /* Have to check whenever a different source line was reached */
4575 method = jinfo_get_method (ji);
4576 minfo = mono_debug_lookup_method (method);
4579 loc = mono_debug_method_lookup_location (minfo, sp->il_offset);
4582 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);
4583 ss_req->last_method = method;
4585 } else if (loc && method == ss_req->last_method && loc->row == ss_req->last_line) {
4586 ss_calculate_framecount (tls, ctx);
4587 if (tls->frame_count == req->nframes) { // If the frame has changed we're clearly not on the same source line.
4588 DEBUG_PRINTF (1, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer) (gsize) mono_native_thread_id_get (), loc->row);
4594 ss_req->last_method = method;
4595 ss_req->last_line = loc->row;
4596 mono_debug_free_source_location (loc);
4603 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4605 return bp->method && bp->method->klass->image->assembly == assembly;
4609 process_breakpoint_inner (DebuggerTlsData *tls, gboolean from_signal)
4613 int i, j, suspend_policy;
4614 guint32 native_offset;
4616 BreakpointInstance *inst;
4617 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4618 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4619 EventKind kind = EVENT_KIND_BREAKPOINT;
4620 MonoContext *ctx = &tls->restore_state.ctx;
4622 MonoSeqPointInfo *info;
4626 // FIXME: Speed this up
4628 ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
4629 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4630 g_assert (ji && !ji->is_trampoline);
4631 method = jinfo_get_method (ji);
4633 /* Compute the native offset of the breakpoint from the ip */
4634 native_offset = ip - (guint8*)ji->code_start;
4637 * Skip the instruction causing the breakpoint signal.
4640 mono_arch_skip_breakpoint (ctx, ji);
4642 if (method->wrapper_type || tls->disable_breakpoints)
4645 bp_reqs = g_ptr_array_new ();
4646 ss_reqs = g_ptr_array_new ();
4647 ss_reqs_orig = g_ptr_array_new ();
4649 mono_loader_lock ();
4652 * The ip points to the instruction causing the breakpoint event, which is after
4653 * the offset recorded in the seq point map, so find the prev seq point before ip.
4655 found_sp = mono_find_prev_seq_point_for_native_offset (mono_domain_get (), method, native_offset, &info, &sp);
4658 no_seq_points_found (method, native_offset);
4660 g_assert (found_sp);
4662 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);
4665 for (i = 0; i < breakpoints->len; ++i) {
4666 bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4671 for (j = 0; j < bp->children->len; ++j) {
4672 inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4673 if (inst->ji == ji && inst->il_offset == sp.il_offset && inst->native_offset == sp.native_offset) {
4674 if (bp->req->event_kind == EVENT_KIND_STEP) {
4675 g_ptr_array_add (ss_reqs_orig, bp->req);
4677 g_ptr_array_add (bp_reqs, bp->req);
4682 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4683 /* Maybe a method entry/exit event */
4684 if (sp.il_offset == METHOD_ENTRY_IL_OFFSET)
4685 kind = EVENT_KIND_METHOD_ENTRY;
4686 else if (sp.il_offset == METHOD_EXIT_IL_OFFSET)
4687 kind = EVENT_KIND_METHOD_EXIT;
4690 /* Process single step requests */
4691 for (i = 0; i < ss_reqs_orig->len; ++i) {
4692 EventRequest *req = (EventRequest *)g_ptr_array_index (ss_reqs_orig, i);
4693 SingleStepReq *ss_req = (SingleStepReq *)req->info;
4696 if (mono_thread_internal_current () != ss_req->thread)
4699 hit = ss_update (ss_req, ji, &sp, tls, ctx);
4701 g_ptr_array_add (ss_reqs, req);
4703 /* Start single stepping again from the current sequence point */
4704 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
4707 if (ss_reqs->len > 0)
4708 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4709 if (bp_reqs->len > 0)
4710 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4711 if (kind != EVENT_KIND_BREAKPOINT)
4712 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4714 mono_loader_unlock ();
4716 g_ptr_array_free (bp_reqs, TRUE);
4717 g_ptr_array_free (ss_reqs, TRUE);
4720 * FIXME: The first event will suspend, so the second will only be sent after the
4724 process_event (EVENT_KIND_STEP, method, 0, ctx, ss_events, suspend_policy);
4726 process_event (kind, method, 0, ctx, bp_events, suspend_policy);
4727 if (enter_leave_events)
4728 process_event (kind, method, 0, ctx, enter_leave_events, suspend_policy);
4731 /* Process a breakpoint/single step event after resuming from a signal handler */
4733 process_signal_event (void (*func) (DebuggerTlsData*, gboolean))
4735 DebuggerTlsData *tls;
4736 MonoThreadUnwindState orig_restore_state;
4739 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4740 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4741 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4742 mono_thread_state_init_from_monoctx (&tls->restore_state, &tls->handler_ctx);
4746 /* This is called when resuming from a signal handler, so it shouldn't return */
4747 memcpy (&ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4748 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4749 mono_restore_context (&ctx);
4750 g_assert_not_reached ();
4754 process_breakpoint (void)
4756 process_signal_event (process_breakpoint_inner);
4760 resume_from_signal_handler (void *sigctx, void *func)
4762 DebuggerTlsData *tls;
4765 /* Save the original context in TLS */
4766 // FIXME: This might not work on an altstack ?
4767 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4769 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer) (gsize) mono_native_thread_id_get ());
4772 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4773 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4774 // clob:c could be added to op_seq_point.
4776 mono_sigctx_to_monoctx (sigctx, &ctx);
4777 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4778 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4779 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4781 MONO_CONTEXT_SET_IP (&ctx, func);
4783 mono_monoctx_to_sigctx (&ctx, sigctx);
4785 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4786 mono_ppc_set_func_into_sigctx (sigctx, func);
4791 mono_debugger_agent_breakpoint_hit (void *sigctx)
4794 * We are called from a signal handler, and running code there causes all kinds of
4795 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4796 * So set up the signal context to return to the real breakpoint handler function.
4798 resume_from_signal_handler (sigctx, process_breakpoint);
4802 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4804 if (frame->managed) {
4805 *(MonoContext*)data = *ctx;
4814 * Called by System.Diagnostics.Debugger:Break ().
4817 mono_debugger_agent_user_break (void)
4819 if (agent_config.enabled) {
4824 /* Obtain a context */
4825 MONO_CONTEXT_SET_IP (&ctx, NULL);
4826 mono_walk_stack_with_ctx (user_break_cb, NULL, (MonoUnwindOptions)0, &ctx);
4827 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4829 mono_loader_lock ();
4830 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4831 mono_loader_unlock ();
4833 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4834 } else if (debug_options.native_debugger_break) {
4840 ss_depth_to_string (StepDepth depth)
4843 case STEP_DEPTH_OVER:
4845 case STEP_DEPTH_OUT:
4847 case STEP_DEPTH_INTO:
4850 g_assert_not_reached ();
4856 process_single_step_inner (DebuggerTlsData *tls, gboolean from_signal)
4861 int il_offset, suspend_policy;
4864 MonoContext *ctx = &tls->restore_state.ctx;
4867 MonoSeqPointInfo *info;
4869 ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
4871 /* Skip the instruction causing the single step */
4873 mono_arch_skip_single_step (ctx);
4875 if (suspend_count > 0) {
4876 /* Fastpath during invokes, see in process_suspend () */
4877 if (suspend_count - tls->resume_count == 0)
4879 process_suspend (tls, ctx);
4884 // FIXME: A suspend race
4887 if (mono_thread_internal_current () != ss_req->thread)
4890 if (log_level > 0) {
4891 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4893 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);
4896 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4897 g_assert (ji && !ji->is_trampoline);
4898 method = jinfo_get_method (ji);
4901 if (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4906 * Stopping in memset makes half-initialized vtypes visible.
4907 * Stopping in memcpy makes half-copied vtypes visible.
4909 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
4913 * The ip points to the instruction causing the single step event, which is before
4914 * the offset recorded in the seq point map, so find the next seq point after ip.
4916 if (!mono_find_next_seq_point_for_native_offset (domain, method, (guint8*)ip - (guint8*)ji->code_start, &info, &sp))
4919 il_offset = sp.il_offset;
4921 if (!ss_update (ss_req, ji, &sp, tls, ctx))
4924 /* Start single stepping again from the current sequence point */
4925 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
4927 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
4928 (method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4929 !strcmp (method->name, ".cctor"))
4932 // FIXME: Has to lock earlier
4934 reqs = g_ptr_array_new ();
4936 mono_loader_lock ();
4938 g_ptr_array_add (reqs, ss_req->req);
4940 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4942 g_ptr_array_free (reqs, TRUE);
4944 mono_loader_unlock ();
4946 process_event (EVENT_KIND_STEP, jinfo_get_method (ji), il_offset, ctx, events, suspend_policy);
4950 process_single_step (void)
4952 process_signal_event (process_single_step_inner);
4956 * mono_debugger_agent_single_step_event:
4958 * Called from a signal handler to handle a single step event.
4961 mono_debugger_agent_single_step_event (void *sigctx)
4963 /* Resume to process_single_step through the signal context */
4965 // FIXME: Since step out/over is implemented using step in, the step in case should
4966 // be as fast as possible. Move the relevant code from process_single_step_inner ()
4969 if (is_debugger_thread ()) {
4971 * This could happen despite our best effors when the runtime calls
4972 * assembly/type resolve hooks.
4973 * FIXME: Breakpoints too.
4977 mono_sigctx_to_monoctx (sigctx, &ctx);
4978 mono_arch_skip_single_step (&ctx);
4979 mono_monoctx_to_sigctx (&ctx, sigctx);
4983 resume_from_signal_handler (sigctx, process_single_step);
4987 debugger_agent_single_step_from_context (MonoContext *ctx)
4989 DebuggerTlsData *tls;
4990 MonoThreadUnwindState orig_restore_state;
4992 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4993 /* Fastpath during invokes, see in process_suspend () */
4994 if (tls && suspend_count && suspend_count - tls->resume_count == 0)
4997 if (is_debugger_thread ())
5002 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
5003 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5004 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5005 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5007 process_single_step_inner (tls, FALSE);
5009 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5010 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5014 debugger_agent_breakpoint_from_context (MonoContext *ctx)
5016 DebuggerTlsData *tls;
5017 MonoThreadUnwindState orig_restore_state;
5020 if (is_debugger_thread ())
5023 orig_ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
5024 MONO_CONTEXT_SET_IP (ctx, orig_ip - 1);
5026 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5028 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5029 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5030 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5032 process_breakpoint_inner (tls, FALSE);
5034 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5035 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5036 if (MONO_CONTEXT_GET_IP (ctx) == orig_ip - 1)
5037 MONO_CONTEXT_SET_IP (ctx, orig_ip);
5041 * start_single_stepping:
5043 * Turn on single stepping. Can be called multiple times, for example,
5044 * by a single step event request + a suspend.
5047 start_single_stepping (void)
5049 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5050 int val = InterlockedIncrement (&ss_count);
5053 mono_arch_start_single_stepping ();
5055 g_assert_not_reached ();
5060 stop_single_stepping (void)
5062 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5063 int val = InterlockedDecrement (&ss_count);
5066 mono_arch_stop_single_stepping ();
5068 g_assert_not_reached ();
5075 * Stop the single stepping operation given by SS_REQ.
5078 ss_stop (SingleStepReq *ss_req)
5083 for (l = ss_req->bps; l; l = l->next) {
5084 clear_breakpoint ((MonoBreakpoint *)l->data);
5086 g_slist_free (ss_req->bps);
5090 if (ss_req->global) {
5091 stop_single_stepping ();
5092 ss_req->global = FALSE;
5099 * Reject breakpoint if it is a duplicate of one already in list or hash table.
5102 ss_bp_is_unique (GSList *bps, GHashTable *ss_req_bp_cache, MonoMethod *method, guint32 il_offset)
5104 if (ss_req_bp_cache) {
5105 MonoBreakpoint dummy = {method, il_offset, NULL, NULL};
5106 return !g_hash_table_lookup (ss_req_bp_cache, &dummy);
5108 for (GSList *l = bps; l; l = l->next) {
5109 MonoBreakpoint *bp = (MonoBreakpoint *)l->data;
5110 if (bp->method == method && bp->il_offset == il_offset)
5119 * GHashTable equality for a MonoBreakpoint (only care about method and il_offset fields)
5122 ss_bp_eq (gconstpointer ka, gconstpointer kb)
5124 const MonoBreakpoint *s1 = (const MonoBreakpoint *)ka;
5125 const MonoBreakpoint *s2 = (const MonoBreakpoint *)kb;
5126 return (s1->method == s2->method && s1->il_offset == s2->il_offset) ? 1 : 0;
5132 * GHashTable hash for a MonoBreakpoint (only care about method and il_offset fields)
5135 ss_bp_hash (gconstpointer data)
5137 const MonoBreakpoint *s = (const MonoBreakpoint *)data;
5138 guint hash = (guint) (uintptr_t) s->method;
5139 hash ^= ((guint)s->il_offset) << 16; // Assume low bits are more interesting
5140 hash ^= ((guint)s->il_offset) >> 16;
5144 #define MAX_LINEAR_SCAN_BPS 7
5149 * Create a new breakpoint and add it to a step request.
5150 * Will adjust the bp count and cache used by ss_start.
5153 ss_bp_add_one (SingleStepReq *ss_req, int *ss_req_bp_count, GHashTable **ss_req_bp_cache,
5154 MonoMethod *method, guint32 il_offset)
5156 // This list is getting too long, switch to using the hash table
5157 if (!*ss_req_bp_cache && *ss_req_bp_count > MAX_LINEAR_SCAN_BPS) {
5158 *ss_req_bp_cache = g_hash_table_new (ss_bp_hash, ss_bp_eq);
5159 for (GSList *l = ss_req->bps; l; l = l->next)
5160 g_hash_table_insert (*ss_req_bp_cache, l->data, l->data);
5163 if (ss_bp_is_unique (ss_req->bps, *ss_req_bp_cache, method, il_offset)) {
5164 // Create and add breakpoint
5165 MonoBreakpoint *bp = set_breakpoint (method, il_offset, ss_req->req, NULL);
5166 ss_req->bps = g_slist_append (ss_req->bps, bp);
5167 if (*ss_req_bp_cache)
5168 g_hash_table_insert (*ss_req_bp_cache, bp, bp);
5169 (*ss_req_bp_count)++;
5171 DEBUG_PRINTF (1, "[dbg] Candidate breakpoint at %s:[il=0x%x] is a duplicate for this step request, will not add.\n", mono_method_full_name (method, TRUE), (int)il_offset);
5178 * Start the single stepping operation given by SS_REQ from the sequence point SP.
5179 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
5180 * belong to the same thread as CTX.
5181 * If FRAMES is not-null, use that instead of tls->frames for placing breakpoints etc.
5184 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint* sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls,
5185 gboolean step_to_catch, StackFrame **frames, int nframes)
5187 int i, j, frame_index;
5188 SeqPoint *next_sp, *parent_sp = NULL;
5189 SeqPoint local_sp, local_parent_sp;
5191 MonoSeqPointInfo *parent_info;
5192 MonoMethod *parent_sp_method = NULL;
5193 gboolean enable_global = FALSE;
5195 // When 8 or more entries are in bps, we build a hash table to serve as a set of breakpoints.
5196 // Recreating this on each pass is a little wasteful but at least keeps behavior linear.
5197 int ss_req_bp_count = g_slist_length (ss_req->bps);
5198 GHashTable *ss_req_bp_cache = NULL;
5200 /* Stop the previous operation */
5204 * Implement single stepping using breakpoints if possible.
5206 if (step_to_catch) {
5207 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, sp->il_offset);
5211 if (ctx && !frames) {
5212 /* Need parent frames */
5213 if (!tls->context.valid)
5214 mono_thread_state_init_from_monoctx (&tls->context, ctx);
5215 compute_frame_info (tls->thread, tls);
5216 frames = tls->frames;
5217 nframes = tls->frame_count;
5221 * Find the first sequence point in the current or in a previous frame which
5222 * is not the last in its method.
5224 if (ss_req->depth == STEP_DEPTH_OUT) {
5225 /* Ignore seq points in current method */
5226 while (frame_index < nframes) {
5227 StackFrame *frame = frames [frame_index];
5229 method = frame->method;
5230 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5231 sp = (found_sp)? &local_sp : NULL;
5233 if (sp && sp->next_len != 0)
5236 // There could be method calls before the next seq point in the caller when using nested calls
5237 //enable_global = TRUE;
5239 if (sp && sp->next_len == 0) {
5241 while (frame_index < nframes) {
5242 StackFrame *frame = frames [frame_index];
5244 method = frame->method;
5245 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5246 sp = (found_sp)? &local_sp : NULL;
5247 if (sp && sp->next_len != 0)
5253 /* Have to put a breakpoint into a parent frame since the seq points might not cover all control flow out of the method */
5254 while (frame_index < nframes) {
5255 StackFrame *frame = frames [frame_index];
5257 parent_sp_method = frame->method;
5258 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &parent_info, &local_parent_sp);
5259 parent_sp = found_sp ? &local_parent_sp : NULL;
5260 if (found_sp && parent_sp->next_len != 0)
5268 if (sp && sp->next_len > 0) {
5269 SeqPoint* next = g_new(SeqPoint, sp->next_len);
5271 mono_seq_point_init_next (info, *sp, next);
5272 for (i = 0; i < sp->next_len; i++) {
5275 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, next_sp->il_offset);
5281 SeqPoint* next = g_new(SeqPoint, parent_sp->next_len);
5283 mono_seq_point_init_next (parent_info, *parent_sp, next);
5284 for (i = 0; i < parent_sp->next_len; i++) {
5287 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, parent_sp_method, next_sp->il_offset);
5292 if (ss_req->nframes == 0)
5293 ss_req->nframes = nframes;
5295 if ((ss_req->depth == STEP_DEPTH_OVER) && (!sp && !parent_sp)) {
5296 DEBUG_PRINTF (1, "[dbg] No parent frame for step over, transition to step into.\n");
5298 * This is needed since if we leave managed code, and later return to it, step over
5299 * is not going to stop.
5300 * This approach is a bit ugly, since we change the step depth, but it only affects
5301 * clients who reuse the same step request, and only in this special case.
5303 ss_req->depth = STEP_DEPTH_INTO;
5306 if (ss_req->depth == STEP_DEPTH_OVER) {
5307 /* Need to stop in catch clauses as well */
5308 for (i = 0; i < nframes; ++i) {
5309 StackFrame *frame = frames [i];
5312 MonoJitInfo *jinfo = frame->ji;
5313 for (j = 0; j < jinfo->num_clauses; ++j) {
5314 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5316 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);
5317 sp = (found_sp)? &local_sp : NULL;
5320 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, frame->method, sp->il_offset);
5326 if (ss_req->depth == STEP_DEPTH_INTO) {
5327 /* Enable global stepping so we stop at method entry too */
5328 enable_global = TRUE;
5332 * The ctx/frame info computed above will become invalid when we continue.
5334 tls->context.valid = FALSE;
5335 tls->async_state.valid = FALSE;
5336 invalidate_frames (tls);
5339 if (enable_global) {
5340 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5341 ss_req->global = TRUE;
5342 start_single_stepping ();
5343 } else if (!ss_req->bps) {
5344 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5345 ss_req->global = TRUE;
5346 start_single_stepping ();
5348 ss_req->global = FALSE;
5351 if (ss_req_bp_cache)
5352 g_hash_table_destroy (ss_req_bp_cache);
5356 * Start single stepping of thread THREAD
5359 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req)
5361 DebuggerTlsData *tls;
5362 MonoSeqPointInfo *info = NULL;
5363 SeqPoint *sp = NULL;
5366 MonoMethod *method = NULL;
5367 MonoDebugMethodInfo *minfo;
5368 gboolean step_to_catch = FALSE;
5369 gboolean set_ip = FALSE;
5370 StackFrame **frames = NULL;
5373 if (suspend_count == 0)
5374 return ERR_NOT_SUSPENDED;
5376 wait_for_suspend ();
5378 // FIXME: Multiple requests
5380 DEBUG_PRINTF (0, "Received a single step request while the previous one was still active.\n");
5381 return ERR_NOT_IMPLEMENTED;
5384 DEBUG_PRINTF (1, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth));
5386 ss_req = g_new0 (SingleStepReq, 1);
5388 ss_req->thread = thread;
5389 ss_req->size = size;
5390 ss_req->depth = depth;
5391 ss_req->filter = filter;
5394 mono_loader_lock ();
5395 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5396 mono_loader_unlock ();
5398 g_assert (tls->context.valid);
5400 if (tls->restore_state.valid && MONO_CONTEXT_GET_IP (&tls->context.ctx) != MONO_CONTEXT_GET_IP (&tls->restore_state.ctx)) {
5402 * Need to start single stepping from restore_state and not from the current state
5405 frames = compute_frame_info_from (thread, tls, &tls->restore_state, &nframes);
5408 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5410 if (tls->catch_state.valid) {
5412 StackFrameInfo frame;
5413 MonoContext new_ctx;
5414 MonoLMF *lmf = NULL;
5417 * We are stopped at a throw site. Stepping should go to the catch site.
5420 /* Find the the jit info for the catch context */
5421 res = mono_find_jit_info_ext (
5422 (MonoDomain *)tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN],
5423 (MonoJitTlsData *)((MonoThreadInfo*)thread->thread_info)->jit_data,
5424 NULL, &tls->catch_state.ctx, &new_ctx, NULL, &lmf, NULL, &frame);
5426 g_assert (frame.type == FRAME_TYPE_MANAGED);
5429 * Find the seq point corresponding to the landing site ip, which is the first seq
5432 found_sp = mono_find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info, &local_sp);
5433 sp = (found_sp)? &local_sp : NULL;
5435 no_seq_points_found (frame.method, frame.native_offset);
5438 method = frame.method;
5440 step_to_catch = TRUE;
5441 /* This make sure the seq point is not skipped by process_single_step () */
5442 ss_req->last_sp = NULL;
5445 if (!step_to_catch) {
5446 StackFrame *frame = NULL;
5449 if (frames && nframes)
5452 compute_frame_info (thread, tls);
5454 if (tls->frame_count)
5455 frame = tls->frames [0];
5458 if (ss_req->size == STEP_SIZE_LINE) {
5460 ss_req->last_method = frame->method;
5461 ss_req->last_line = -1;
5463 minfo = mono_debug_lookup_method (frame->method);
5464 if (minfo && frame->il_offset != -1) {
5465 MonoDebugSourceLocation *loc = mono_debug_method_lookup_location (minfo, frame->il_offset);
5468 ss_req->last_line = loc->row;
5476 if (!method && frame->il_offset != -1) {
5477 /* FIXME: Sort the table and use a binary search */
5478 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5479 sp = (found_sp)? &local_sp : NULL;
5481 no_seq_points_found (frame->method, frame->native_offset);
5483 method = frame->method;
5488 ss_req->start_method = method;
5490 ss_start (ss_req, method, sp, info, set_ip ? &tls->restore_state.ctx : &tls->context.ctx, tls, step_to_catch, frames, nframes);
5493 free_frames (frames, nframes);
5499 ss_destroy (SingleStepReq *req)
5502 g_assert (ss_req == req);
5511 ss_clear_for_assembly (SingleStepReq *req, MonoAssembly *assembly)
5514 gboolean found = TRUE;
5518 for (l = ss_req->bps; l; l = l->next) {
5519 if (breakpoint_matches_assembly ((MonoBreakpoint *)l->data, assembly)) {
5520 clear_breakpoint ((MonoBreakpoint *)l->data);
5521 ss_req->bps = g_slist_delete_link (ss_req->bps, l);
5530 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5533 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5540 if (!agent_config.enabled)
5543 mono_loader_lock ();
5544 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5545 mono_loader_unlock ();
5550 ei.category = mono_string_to_utf8_checked (category, &error);
5551 mono_error_cleanup (&error);
5555 ei.message = mono_string_to_utf8_checked (message, &error);
5556 mono_error_cleanup (&error);
5559 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5561 g_free (ei.category);
5562 g_free (ei.message);
5566 mono_debugger_agent_debug_log_is_enabled (void)
5568 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5569 return agent_config.enabled;
5572 #if defined(PLATFORM_ANDROID) || defined(TARGET_ANDROID)
5574 mono_debugger_agent_unhandled_exception (MonoException *exc)
5583 memset (&ei, 0, sizeof (EventInfo));
5584 ei.exc = (MonoObject*)exc;
5586 mono_loader_lock ();
5587 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5588 mono_loader_unlock ();
5590 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5595 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5596 MonoContext *catch_ctx)
5598 int i, j, suspend_policy;
5600 MonoJitInfo *ji, *catch_ji;
5602 DebuggerTlsData *tls = NULL;
5604 if (thread_to_tls != NULL) {
5605 MonoInternalThread *thread = mono_thread_internal_current ();
5607 mono_loader_lock ();
5608 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5609 mono_loader_unlock ();
5611 if (tls && tls->abort_requested)
5613 if (tls && tls->disable_breakpoints)
5617 memset (&ei, 0, sizeof (EventInfo));
5619 /* Just-In-Time debugging */
5621 if (agent_config.onuncaught && !inited) {
5622 finish_agent_init (FALSE);
5625 * Send an unsolicited EXCEPTION event with a dummy request id.
5627 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5628 ei.exc = (MonoObject*)exc;
5629 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5632 } else if (agent_config.onthrow && !inited) {
5634 gboolean found = FALSE;
5636 for (l = agent_config.onthrow; l; l = l->next) {
5637 char *ex_type = (char *)l->data;
5638 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5640 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5647 finish_agent_init (FALSE);
5650 * Send an unsolicited EXCEPTION event with a dummy request id.
5652 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5653 ei.exc = (MonoObject*)exc;
5654 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5662 ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5664 catch_ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5668 ei.exc = (MonoObject*)exc;
5669 ei.caught = catch_ctx != NULL;
5671 mono_loader_lock ();
5673 /* Treat exceptions which are caught in non-user code as unhandled */
5674 for (i = 0; i < event_requests->len; ++i) {
5675 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
5676 if (req->event_kind != EVENT_KIND_EXCEPTION)
5679 for (j = 0; j < req->nmodifiers; ++j) {
5680 Modifier *mod = &req->modifiers [j];
5682 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5684 gboolean found = FALSE;
5685 MonoAssembly **assemblies = mod->data.assemblies;
5688 for (k = 0; assemblies [k]; ++k)
5689 if (assemblies [k] == jinfo_get_method (catch_ji)->klass->image->assembly)
5698 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5699 mono_loader_unlock ();
5701 if (tls && ei.caught && catch_ctx) {
5702 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5703 tls->catch_state.ctx = *catch_ctx;
5704 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5705 tls->catch_state.valid = TRUE;
5708 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5711 tls->catch_state.valid = FALSE;
5715 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5717 DebuggerTlsData *tls;
5722 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5727 * We're about to invoke an exception filter during the first pass of exception handling.
5729 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5730 * 'orig_ctx' is the context where the exception has been thrown.
5733 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5735 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5736 * the call site (line 37) and then continue to Main(), but it would never
5737 * include the throw site (line 32).
5739 * Since exception filters are invoked during the first pass of exception handling,
5740 * the stack frames of the throw site are still intact, so we should include them
5743 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5745 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5746 * but report the location of the 'throw' to the user.
5750 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5754 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5756 DebuggerTlsData *tls;
5761 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5765 tls->filter_state.valid = FALSE;
5769 * buffer_add_value_full:
5771 * Add the encoding of the value at ADDR described by T to the buffer.
5772 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5776 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5777 gboolean as_vtype, GHashTable *parent_vtypes)
5780 gboolean boxed_vtype = FALSE;
5783 if (!(*(void**)addr)) {
5784 /* This can happen with compiler generated locals */
5785 //printf ("%s\n", mono_type_full_name (t));
5786 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5789 g_assert (*(void**)addr);
5790 addr = *(void**)addr;
5795 case MONO_TYPE_BOOLEAN:
5798 case MONO_TYPE_CHAR:
5818 case MONO_TYPE_VOID:
5819 buffer_add_byte (buf, t->type);
5821 case MONO_TYPE_BOOLEAN:
5824 buffer_add_byte (buf, t->type);
5825 buffer_add_int (buf, *(gint8*)addr);
5827 case MONO_TYPE_CHAR:
5830 buffer_add_byte (buf, t->type);
5831 buffer_add_int (buf, *(gint16*)addr);
5836 buffer_add_byte (buf, t->type);
5837 buffer_add_int (buf, *(gint32*)addr);
5842 buffer_add_byte (buf, t->type);
5843 buffer_add_long (buf, *(gint64*)addr);
5847 /* Treat it as a vtype */
5849 case MONO_TYPE_PTR: {
5850 gssize val = *(gssize*)addr;
5852 buffer_add_byte (buf, t->type);
5853 buffer_add_long (buf, val);
5857 case MONO_TYPE_STRING:
5858 case MONO_TYPE_SZARRAY:
5859 case MONO_TYPE_OBJECT:
5860 case MONO_TYPE_CLASS:
5861 case MONO_TYPE_ARRAY:
5862 obj = *(MonoObject**)addr;
5865 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5867 if (obj->vtable->klass->valuetype) {
5868 t = &obj->vtable->klass->byval_arg;
5869 addr = mono_object_unbox (obj);
5872 } else if (obj->vtable->klass->rank) {
5873 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5874 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5875 buffer_add_byte (buf, MONO_TYPE_CLASS);
5877 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5879 buffer_add_objid (buf, obj);
5883 case MONO_TYPE_VALUETYPE:
5884 case MONO_TYPE_TYPEDBYREF: {
5888 MonoClass *klass = mono_class_from_mono_type (t);
5893 * Handle boxed vtypes recursively referencing themselves using fields.
5896 parent_vtypes = g_hash_table_new (NULL, NULL);
5897 vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
5899 if (CHECK_PROTOCOL_VERSION (2, 33)) {
5900 buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
5901 buffer_add_int (buf, vtype_index - 1);
5903 /* The client can't handle PARENT_VTYPE */
5904 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5908 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
5912 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5913 buffer_add_byte (buf, klass->enumtype);
5914 buffer_add_typeid (buf, domain, klass);
5918 while ((f = mono_class_get_fields (klass, &iter))) {
5919 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5921 if (mono_field_is_deleted (f))
5925 buffer_add_int (buf, nfields);
5928 while ((f = mono_class_get_fields (klass, &iter))) {
5929 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5931 if (mono_field_is_deleted (f))
5933 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE, parent_vtypes);
5937 g_hash_table_remove (parent_vtypes, addr);
5938 if (g_hash_table_size (parent_vtypes) == 0) {
5939 g_hash_table_destroy (parent_vtypes);
5940 parent_vtypes = NULL;
5945 case MONO_TYPE_GENERICINST:
5946 if (mono_type_generic_inst_is_valuetype (t)) {
5958 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5960 buffer_add_value_full (buf, t, addr, domain, FALSE, NULL);
5964 obj_is_of_type (MonoObject *obj, MonoType *t)
5966 MonoClass *klass = obj->vtable->klass;
5967 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5968 if (mono_class_is_transparent_proxy (klass)) {
5969 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5970 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5980 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5983 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5989 gpointer iter = NULL;
5993 is_enum = decode_byte (buf, &buf, limit);
5994 /* Enums are sent as a normal vtype */
5996 return ERR_NOT_IMPLEMENTED;
5997 klass = decode_typeid (buf, &buf, limit, &d, &err);
5998 if (err != ERR_NONE)
6001 if (t && klass != mono_class_from_mono_type (t)) {
6002 char *name = mono_type_full_name (t);
6003 char *name2 = mono_type_full_name (&klass->byval_arg);
6004 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got %s.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, name2);
6007 return ERR_INVALID_ARGUMENT;
6010 nfields = decode_int (buf, &buf, limit);
6011 while ((f = mono_class_get_fields (klass, &iter))) {
6012 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6014 if (mono_field_is_deleted (f))
6016 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
6017 if (err != ERR_NONE)
6021 g_assert (nfields == 0);
6029 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6033 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
6034 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
6035 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
6036 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
6037 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE) &&
6038 !(t->type == MONO_TYPE_VALUETYPE && type == MONO_TYPE_OBJECT)) {
6039 char *name = mono_type_full_name (t);
6040 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
6042 return ERR_INVALID_ARGUMENT;
6046 case MONO_TYPE_BOOLEAN:
6047 *(guint8*)addr = decode_int (buf, &buf, limit);
6049 case MONO_TYPE_CHAR:
6050 *(gunichar2*)addr = decode_int (buf, &buf, limit);
6053 *(gint8*)addr = decode_int (buf, &buf, limit);
6056 *(guint8*)addr = decode_int (buf, &buf, limit);
6059 *(gint16*)addr = decode_int (buf, &buf, limit);
6062 *(guint16*)addr = decode_int (buf, &buf, limit);
6065 *(gint32*)addr = decode_int (buf, &buf, limit);
6068 *(guint32*)addr = decode_int (buf, &buf, limit);
6071 *(gint64*)addr = decode_long (buf, &buf, limit);
6074 *(guint64*)addr = decode_long (buf, &buf, limit);
6077 *(guint32*)addr = decode_int (buf, &buf, limit);
6080 *(guint64*)addr = decode_long (buf, &buf, limit);
6083 /* We send these as I8, so we get them back as such */
6084 g_assert (type == MONO_TYPE_I8);
6085 *(gssize*)addr = decode_long (buf, &buf, limit);
6087 case MONO_TYPE_GENERICINST:
6088 if (MONO_TYPE_ISSTRUCT (t)) {
6089 /* The client sends these as a valuetype */
6097 /* We send these as vtypes, so we get them back as such */
6098 g_assert (type == MONO_TYPE_VALUETYPE);
6101 case MONO_TYPE_VALUETYPE:
6102 if (type == MONO_TYPE_OBJECT) {
6104 int objid = decode_objid (buf, &buf, limit);
6108 err = get_object (objid, (MonoObject**)&obj);
6109 if (err != ERR_NONE)
6112 return ERR_INVALID_ARGUMENT;
6113 if (obj->vtable->klass != mono_class_from_mono_type (t)) {
6114 DEBUG_PRINTF (1, "Expected type '%s', got object '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6115 return ERR_INVALID_ARGUMENT;
6117 memcpy (addr, mono_object_unbox (obj), mono_class_value_size (obj->vtable->klass, NULL));
6119 err = decode_vtype (t, domain, addr, buf, &buf, limit);
6120 if (err != ERR_NONE)
6126 if (MONO_TYPE_IS_REFERENCE (t)) {
6127 if (type == MONO_TYPE_OBJECT) {
6128 int objid = decode_objid (buf, &buf, limit);
6132 err = get_object (objid, (MonoObject**)&obj);
6133 if (err != ERR_NONE)
6137 if (!obj_is_of_type (obj, t)) {
6138 DEBUG_PRINTF (1, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6139 return ERR_INVALID_ARGUMENT;
6142 if (obj && obj->vtable->domain != domain)
6143 return ERR_INVALID_ARGUMENT;
6145 mono_gc_wbarrier_generic_store (addr, obj);
6146 } else if (type == VALUE_TYPE_ID_NULL) {
6147 *(MonoObject**)addr = NULL;
6148 } else if (type == MONO_TYPE_VALUETYPE) {
6157 /* This can happen when round-tripping boxed vtypes */
6159 * Obtain vtype class.
6160 * Same as the beginning of the handle_vtype case above.
6163 is_enum = decode_byte (buf, &buf, limit);
6165 return ERR_NOT_IMPLEMENTED;
6166 klass = decode_typeid (buf, &buf, limit, &d, &err);
6167 if (err != ERR_NONE)
6170 /* Decode the vtype into a temporary buffer, then box it. */
6171 vtype_buf_size = mono_class_value_size (klass, NULL);
6172 vtype_buf = (guint8 *)g_malloc0 (vtype_buf_size);
6173 g_assert (vtype_buf);
6176 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
6177 if (err != ERR_NONE) {
6181 *(MonoObject**)addr = mono_value_box_checked (d, klass, vtype_buf, &error);
6182 mono_error_cleanup (&error);
6185 char *name = mono_type_full_name (t);
6186 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
6188 return ERR_INVALID_ARGUMENT;
6202 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6206 int type = decode_byte (buf, &buf, limit);
6208 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
6209 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
6210 guint8 *nullable_buf;
6213 * First try decoding it as a Nullable`1
6215 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6216 if (err == ERR_NONE)
6220 * Then try decoding as a primitive value or null.
6222 if (targ->type == type) {
6223 nullable_buf = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
6224 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
6225 if (err != ERR_NONE) {
6226 g_free (nullable_buf);
6229 MonoObject *boxed = mono_value_box_checked (domain, mono_class_from_mono_type (targ), nullable_buf, &error);
6230 if (!is_ok (&error)) {
6231 mono_error_cleanup (&error);
6232 return ERR_INVALID_OBJECT;
6234 mono_nullable_init (addr, boxed, mono_class_from_mono_type (t));
6235 g_free (nullable_buf);
6238 } else if (type == VALUE_TYPE_ID_NULL) {
6239 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
6245 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6249 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
6253 guint8 *addr, *gaddr;
6256 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6257 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6260 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
6261 reg_val = mono_arch_context_get_int_reg (ctx, reg);
6263 buffer_add_value_full (buf, t, ®_val, domain, as_vtype, NULL);
6265 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6266 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6267 addr += (gint32)var->offset;
6269 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6271 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6273 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6276 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6277 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
6278 /* Same as regoffset, but with an indirection */
6279 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6280 addr += (gint32)var->offset;
6282 gaddr = (guint8 *)*(gpointer*)addr;
6284 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL);
6286 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
6287 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
6288 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
6289 MonoGSharedVtMethodRuntimeInfo *info;
6295 g_assert (info_var);
6296 g_assert (locals_var);
6298 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6299 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6300 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6301 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6302 addr += (gint32)info_var->offset;
6303 info = (MonoGSharedVtMethodRuntimeInfo *)*(gpointer*)addr;
6304 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6305 info = (MonoGSharedVtMethodRuntimeInfo *)mono_arch_context_get_int_reg (ctx, reg);
6307 g_assert_not_reached ();
6311 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6312 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6313 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6314 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6315 addr += (gint32)locals_var->offset;
6316 locals = (guint8 *)*(gpointer*)addr;
6317 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6318 locals = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6320 g_assert_not_reached ();
6324 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6326 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6331 g_assert_not_reached ();
6336 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
6340 guint8 *addr, *gaddr;
6342 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6343 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6345 if (MONO_TYPE_IS_REFERENCE (t))
6346 size = sizeof (gpointer);
6348 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6351 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6352 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6354 gboolean is_signed = FALSE;
6357 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6360 // FIXME: Write barriers
6361 mono_gc_memmove_atomic (addr, val, size);
6366 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6371 v = is_signed ? *(gint8*)val : *(guint8*)val;
6374 v = is_signed ? *(gint16*)val : *(guint16*)val;
6377 v = is_signed ? *(gint32*)val : *(guint32*)val;
6380 v = is_signed ? *(gint64*)val : *(guint64*)val;
6383 g_assert_not_reached ();
6386 /* Set value on the stack or in the return ctx */
6387 if (reg_locations [reg]) {
6388 /* Saved on the stack */
6389 DEBUG_PRINTF (1, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v);
6390 *(reg_locations [reg]) = v;
6393 DEBUG_PRINTF (1, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v);
6394 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6397 // FIXME: Move these to mono-context.h/c.
6398 mono_arch_context_set_int_reg (ctx, reg, v);
6400 // FIXME: Can't set registers, so we disable linears
6405 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6406 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6407 addr += (gint32)var->offset;
6409 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6412 addr = *(guint8**)addr;
6418 // FIXME: Write barriers
6419 mono_gc_memmove_atomic (addr, val, size);
6421 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6422 /* Same as regoffset, but with an indirection */
6423 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6424 addr += (gint32)var->offset;
6426 gaddr = (guint8 *)*(gpointer*)addr;
6428 // FIXME: Write barriers
6429 mono_gc_memmove_atomic (gaddr, val, size);
6431 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6435 g_assert_not_reached ();
6440 clear_event_request (int req_id, int etype)
6444 mono_loader_lock ();
6445 for (i = 0; i < event_requests->len; ++i) {
6446 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6448 if (req->id == req_id && req->event_kind == etype) {
6449 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6450 clear_breakpoint ((MonoBreakpoint *)req->info);
6451 if (req->event_kind == EVENT_KIND_STEP)
6452 ss_destroy ((SingleStepReq *)req->info);
6453 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6454 clear_breakpoint ((MonoBreakpoint *)req->info);
6455 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6456 clear_breakpoint ((MonoBreakpoint *)req->info);
6457 g_ptr_array_remove_index_fast (event_requests, i);
6462 mono_loader_unlock ();
6466 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
6470 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6471 m->kind = MOD_KIND_NONE;
6472 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6473 int count = 0, match_count = 0, pos;
6474 MonoAssembly **newassemblies;
6476 for (i = 0; m->data.assemblies [i]; ++i) {
6478 if (m->data.assemblies [i] == assembly)
6483 newassemblies = g_new0 (MonoAssembly*, count - match_count);
6486 for (i = 0; i < count; ++i)
6487 if (m->data.assemblies [i] != assembly)
6488 newassemblies [pos ++] = m->data.assemblies [i];
6489 g_assert (pos == count - match_count);
6490 g_free (m->data.assemblies);
6491 m->data.assemblies = newassemblies;
6497 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
6501 for (i = 0; i < req->nmodifiers; ++i) {
6502 Modifier *m = &req->modifiers [i];
6504 clear_assembly_from_modifier (req, m, assembly);
6509 * clear_event_requests_for_assembly:
6511 * Clear all events requests which reference ASSEMBLY.
6514 clear_event_requests_for_assembly (MonoAssembly *assembly)
6519 mono_loader_lock ();
6523 for (i = 0; i < event_requests->len; ++i) {
6524 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6526 clear_assembly_from_modifiers (req, assembly);
6528 if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly ((MonoBreakpoint *)req->info, assembly)) {
6529 clear_event_request (req->id, req->event_kind);
6534 if (req->event_kind == EVENT_KIND_STEP)
6535 ss_clear_for_assembly ((SingleStepReq *)req->info, assembly);
6538 mono_loader_unlock ();
6542 * type_comes_from_assembly:
6544 * GHRFunc that returns TRUE if klass comes from assembly
6547 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6549 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6553 * clear_types_for_assembly:
6555 * Clears types from loaded_classes for a given assembly
6558 clear_types_for_assembly (MonoAssembly *assembly)
6560 MonoDomain *domain = mono_domain_get ();
6561 AgentDomainInfo *info = NULL;
6563 if (!domain || !domain_jit_info (domain))
6564 /* Can happen during shutdown */
6567 info = get_agent_domain_info (domain);
6569 mono_loader_lock ();
6570 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6571 mono_loader_unlock ();
6575 add_thread (gpointer key, gpointer value, gpointer user_data)
6577 MonoInternalThread *thread = (MonoInternalThread *)value;
6578 Buffer *buf = (Buffer *)user_data;
6580 buffer_add_objid (buf, (MonoObject*)thread);
6584 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6587 guint8 *end = invoke->endp;
6591 MonoMethodSignature *sig;
6594 MonoObject *this_arg, *res, *exc;
6597 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6600 MonoStopwatch watch;
6602 if (invoke->method) {
6604 * Invoke this method directly, currently only Environment.Exit () is supported.
6607 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>");
6609 mono_runtime_try_invoke (invoke->method, NULL, invoke->args, &exc, &error);
6610 mono_error_assert_ok (&error);
6612 g_assert_not_reached ();
6615 m = decode_methodid (p, &p, end, &domain, &err);
6616 if (err != ERR_NONE)
6618 sig = mono_method_signature (m);
6620 if (m->klass->valuetype)
6621 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6623 this_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
6624 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6625 /* Should be null */
6626 int type = decode_byte (p, &p, end);
6627 if (type != VALUE_TYPE_ID_NULL) {
6628 DEBUG_PRINTF (1, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6629 return ERR_INVALID_ARGUMENT;
6631 memset (this_buf, 0, mono_class_instance_size (m->klass));
6632 } else if (m->klass->valuetype && !strcmp (m->name, ".ctor")) {
6636 int type = decode_byte (p, &tmp_p, end);
6637 if (type == VALUE_TYPE_ID_NULL) {
6638 memset (this_buf, 0, mono_class_instance_size (m->klass));
6641 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6642 if (err != ERR_NONE)
6646 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6647 if (err != ERR_NONE)
6651 if (!m->klass->valuetype)
6652 this_arg = *(MonoObject**)this_buf;
6656 if (MONO_CLASS_IS_INTERFACE (m->klass)) {
6658 DEBUG_PRINTF (1, "[%p] Error: Interface method invoked without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6659 return ERR_INVALID_ARGUMENT;
6661 m = mono_object_get_virtual_method (this_arg, m);
6662 /* Transform this to the format the rest of the code expects it to be */
6663 if (m->klass->valuetype) {
6664 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6665 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
6667 } else if ((m->flags & METHOD_ATTRIBUTE_VIRTUAL) && !m->klass->valuetype && invoke->flags & INVOKE_FLAG_VIRTUAL) {
6669 DEBUG_PRINTF (1, "[%p] Error: invoke with INVOKE_FLAG_VIRTUAL flag set without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6670 return ERR_INVALID_ARGUMENT;
6672 m = mono_object_get_virtual_method (this_arg, m);
6673 if (m->klass->valuetype) {
6674 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6675 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
6679 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>");
6681 if (this_arg && this_arg->vtable->domain != domain)
6684 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this_arg) {
6685 if (!strcmp (m->name, ".ctor")) {
6686 if (mono_class_is_abstract (m->klass))
6687 return ERR_INVALID_ARGUMENT;
6690 this_arg = mono_object_new_checked (domain, m->klass, &error);
6691 mono_error_assert_ok (&error);
6694 return ERR_INVALID_ARGUMENT;
6698 if (this_arg && !obj_is_of_type (this_arg, &m->klass->byval_arg))
6699 return ERR_INVALID_ARGUMENT;
6701 nargs = decode_int (p, &p, end);
6702 if (nargs != sig->param_count)
6703 return ERR_INVALID_ARGUMENT;
6704 /* Use alloca to get gc tracking */
6705 arg_buf = (guint8 **)g_alloca (nargs * sizeof (gpointer));
6706 memset (arg_buf, 0, nargs * sizeof (gpointer));
6707 args = (gpointer *)g_alloca (nargs * sizeof (gpointer));
6708 for (i = 0; i < nargs; ++i) {
6709 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6710 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6711 if (err != ERR_NONE)
6713 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6716 if (sig->params [i]->byref) {
6717 arg_buf [i] = (guint8 *)g_alloca (sizeof (mgreg_t));
6718 *(gpointer*)arg_buf [i] = args [i];
6719 args [i] = arg_buf [i];
6722 arg_buf [i] = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6723 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6724 if (err != ERR_NONE)
6726 args [i] = arg_buf [i];
6733 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6734 tls->disable_breakpoints = TRUE;
6736 tls->disable_breakpoints = FALSE;
6739 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6741 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6742 if (invoke->has_ctx) {
6745 lmf_addr = mono_get_lmf_addr ();
6748 memset (&ext, 0, sizeof (ext));
6749 mono_arch_init_lmf_ext (&ext, *lmf_addr);
6751 ext.debugger_invoke = TRUE;
6752 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6754 mono_set_lmf ((MonoLMF*)&ext);
6758 mono_stopwatch_start (&watch);
6759 res = mono_runtime_try_invoke (m, m->klass->valuetype ? (gpointer) this_buf : (gpointer) this_arg, args, &exc, &error);
6760 if (exc == NULL && !mono_error_ok (&error)) {
6761 exc = (MonoObject*) mono_error_convert_to_exception (&error);
6763 mono_error_cleanup (&error); /* FIXME report error */
6765 mono_stopwatch_stop (&watch);
6766 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));
6768 buffer_add_byte (buf, 0);
6769 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6771 gboolean out_this = FALSE;
6772 gboolean out_args = FALSE;
6774 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_THIS) && CHECK_PROTOCOL_VERSION (2, 35))
6776 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_ARGS) && CHECK_PROTOCOL_VERSION (2, 35))
6778 buffer_add_byte (buf, 1 + (out_this ? 2 : 0) + (out_args ? 4 : 0));
6779 if (sig->ret->type == MONO_TYPE_VOID) {
6780 if (!strcmp (m->name, ".ctor")) {
6781 if (!m->klass->valuetype)
6782 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this_arg, domain);
6784 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
6786 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6788 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6789 buffer_add_value (buf, sig->ret, &res, domain);
6790 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6791 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6792 MonoClass *k = mono_class_from_mono_type (sig->ret);
6793 guint8 *nullable_buf = (guint8 *)g_alloca (mono_class_value_size (k, NULL));
6795 g_assert (nullable_buf);
6796 mono_nullable_init (nullable_buf, res, k);
6797 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6800 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6806 /* Return the new value of the receiver after the call */
6807 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
6809 buffer_add_int (buf, nargs);
6810 for (i = 0; i < nargs; ++i) {
6811 if (MONO_TYPE_IS_REFERENCE (sig->params [i]))
6812 buffer_add_value (buf, sig->params [i], &args [i], domain);
6813 else if (sig->params [i]->byref)
6814 /* add_value () does an indirection */
6815 buffer_add_value (buf, sig->params [i], &arg_buf [i], domain);
6817 buffer_add_value (buf, sig->params [i], arg_buf [i], domain);
6822 tls->disable_breakpoints = FALSE;
6824 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6825 if (invoke->has_ctx)
6826 mono_set_lmf ((MonoLMF *)(((gssize)ext.lmf.previous_lmf) & ~3));
6830 // FIXME: byref arguments
6838 * Invoke the method given by tls->pending_invoke in the current thread.
6841 invoke_method (void)
6843 DebuggerTlsData *tls;
6849 MonoContext restore_ctx;
6852 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
6856 * Store the `InvokeData *' in `tls->invoke' until we're done with
6857 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6860 mono_loader_lock ();
6862 invoke = tls->pending_invoke;
6864 tls->pending_invoke = NULL;
6866 invoke->last_invoke = tls->invoke;
6867 tls->invoke = invoke;
6869 mono_loader_unlock ();
6871 tls->frames_up_to_date = FALSE;
6877 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6878 buffer_init (&buf, 128);
6881 /* Fail the other invokes as well */
6883 err = do_invoke_method (tls, &buf, invoke, p, &p);
6886 if (tls->abort_requested) {
6887 if (CHECK_PROTOCOL_VERSION (2, 42))
6888 err = ERR_INVOKE_ABORTED;
6891 /* Start suspending before sending the reply */
6892 if (mindex == invoke->nmethods - 1) {
6893 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6894 for (i = 0; i < invoke->suspend_count; ++i)
6899 send_reply_packet (id, err, &buf);
6904 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6906 if (invoke->has_ctx)
6907 save_thread_context (&restore_ctx);
6909 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6910 g_assert (tls->resume_count);
6911 tls->resume_count -= invoke->suspend_count;
6914 DEBUG_PRINTF (1, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer) (gsize) mono_native_thread_id_get (), err, tls->resume_count);
6917 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6919 * It is possible that mono_thread_internal_abort () was called
6920 * after the mono_runtime_invoke_checked() already returned, but it doesn't matter
6921 * because we reset the abort here.
6924 mono_loader_lock ();
6926 if (tls->abort_requested)
6927 mono_thread_internal_reset_abort (tls->thread);
6929 tls->invoke = tls->invoke->last_invoke;
6930 tls->abort_requested = FALSE;
6932 mono_loader_unlock ();
6941 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6943 MonoThread *thread = (MonoThread *)value;
6944 DebuggerTlsData *tls;
6947 mono_loader_lock ();
6948 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
6950 res = tls->really_suspended;
6951 mono_loader_unlock ();
6957 get_source_files_for_type (MonoClass *klass)
6959 gpointer iter = NULL;
6961 MonoDebugSourceInfo *sinfo;
6965 files = g_ptr_array_new ();
6967 while ((method = mono_class_get_methods (klass, &iter))) {
6968 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6969 GPtrArray *source_file_list;
6972 mono_debug_get_seq_points (minfo, NULL, &source_file_list, NULL, NULL, NULL);
6973 for (j = 0; j < source_file_list->len; ++j) {
6974 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, j);
6975 for (i = 0; i < files->len; ++i)
6976 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6978 if (i == files->len)
6979 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6981 g_ptr_array_free (source_file_list, TRUE);
6989 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6992 case CMD_VM_VERSION: {
6993 char *build_info, *version;
6995 build_info = mono_get_runtime_build_info ();
6996 version = g_strdup_printf ("mono %s", build_info);
6998 buffer_add_string (buf, version); /* vm version */
6999 buffer_add_int (buf, MAJOR_VERSION);
7000 buffer_add_int (buf, MINOR_VERSION);
7001 g_free (build_info);
7005 case CMD_VM_SET_PROTOCOL_VERSION: {
7006 major_version = decode_int (p, &p, end);
7007 minor_version = decode_int (p, &p, end);
7008 protocol_version_set = TRUE;
7009 DEBUG_PRINTF (1, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version);
7012 case CMD_VM_ALL_THREADS: {
7014 mono_loader_lock ();
7015 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
7016 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
7017 mono_loader_unlock ();
7020 case CMD_VM_SUSPEND:
7022 wait_for_suspend ();
7025 if (suspend_count == 0)
7026 return ERR_NOT_SUSPENDED;
7028 clear_suspended_objs ();
7030 case CMD_VM_DISPOSE:
7031 /* Clear all event requests */
7032 mono_loader_lock ();
7033 while (event_requests->len > 0) {
7034 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
7036 clear_event_request (req->id, req->event_kind);
7038 mono_loader_unlock ();
7040 while (suspend_count > 0)
7042 disconnected = TRUE;
7043 vm_start_event_sent = FALSE;
7046 MonoInternalThread *thread;
7047 DebuggerTlsData *tls;
7048 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7049 MonoClass *env_class;
7051 MonoMethod *exit_method = NULL;
7055 exit_code = decode_int (p, &p, end);
7057 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
7059 /* Have to send a reply before exiting */
7060 send_reply_packet (id, 0, buf);
7062 /* Clear all event requests */
7063 mono_loader_lock ();
7064 while (event_requests->len > 0) {
7065 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
7067 clear_event_request (req->id, req->event_kind);
7069 mono_loader_unlock ();
7072 * The JDWP documentation says that the shutdown is not orderly. It doesn't
7073 * specify whenever a VM_DEATH event is sent. We currently do an orderly
7074 * shutdown by hijacking a thread to execute Environment.Exit (). This is
7075 * better than doing the shutdown ourselves, since it avoids various races.
7079 wait_for_suspend ();
7081 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7082 env_class = mono_class_try_load_from_name (mono_defaults.corlib, "System", "Environment");
7084 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
7087 mono_loader_lock ();
7088 thread = (MonoInternalThread *)mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
7089 mono_loader_unlock ();
7091 if (thread && exit_method) {
7092 mono_loader_lock ();
7093 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
7094 mono_loader_unlock ();
7096 args = g_new0 (gpointer, 1);
7097 args [0] = g_malloc (sizeof (int));
7098 *(int*)(args [0]) = exit_code;
7100 tls->pending_invoke = g_new0 (InvokeData, 1);
7101 tls->pending_invoke->method = exit_method;
7102 tls->pending_invoke->args = args;
7103 tls->pending_invoke->nmethods = 1;
7105 while (suspend_count > 0)
7109 * No thread found, do it ourselves.
7110 * FIXME: This can race with normal shutdown etc.
7112 while (suspend_count > 0)
7115 if (!mono_runtime_try_shutdown ())
7118 mono_environment_exitcode_set (exit_code);
7120 /* Suspend all managed threads since the runtime is going away */
7121 DEBUG_PRINTF (1, "Suspending all threads...\n");
7122 mono_thread_suspend_all_other_threads ();
7123 DEBUG_PRINTF (1, "Shutting down the runtime...\n");
7124 mono_runtime_quit ();
7125 transport_close2 ();
7126 DEBUG_PRINTF (1, "Exiting...\n");
7132 case CMD_VM_INVOKE_METHOD:
7133 case CMD_VM_INVOKE_METHODS: {
7134 int objid = decode_objid (p, &p, end);
7136 DebuggerTlsData *tls;
7137 int i, count, flags, nmethods;
7140 err = get_object (objid, (MonoObject**)&thread);
7141 if (err != ERR_NONE)
7144 flags = decode_int (p, &p, end);
7146 if (command == CMD_VM_INVOKE_METHODS)
7147 nmethods = decode_int (p, &p, end);
7151 // Wait for suspending if it already started
7153 wait_for_suspend ();
7154 if (!is_suspended ())
7155 return ERR_NOT_SUSPENDED;
7157 mono_loader_lock ();
7158 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7159 mono_loader_unlock ();
7162 if (!tls->really_suspended)
7163 /* The thread is still running native code, can't do invokes */
7164 return ERR_NOT_SUSPENDED;
7167 * Store the invoke data into tls, the thread will execute it after it is
7170 if (tls->pending_invoke)
7171 return ERR_NOT_SUSPENDED;
7172 tls->pending_invoke = g_new0 (InvokeData, 1);
7173 tls->pending_invoke->id = id;
7174 tls->pending_invoke->flags = flags;
7175 tls->pending_invoke->p = (guint8 *)g_malloc (end - p);
7176 memcpy (tls->pending_invoke->p, p, end - p);
7177 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
7178 tls->pending_invoke->suspend_count = suspend_count;
7179 tls->pending_invoke->nmethods = nmethods;
7181 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
7182 resume_thread (THREAD_TO_INTERNAL (thread));
7185 count = suspend_count;
7186 for (i = 0; i < count; ++i)
7191 case CMD_VM_ABORT_INVOKE: {
7192 int objid = decode_objid (p, &p, end);
7194 DebuggerTlsData *tls;
7198 err = get_object (objid, (MonoObject**)&thread);
7199 if (err != ERR_NONE)
7202 invoke_id = decode_int (p, &p, end);
7204 mono_loader_lock ();
7205 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7208 if (tls->abort_requested) {
7209 DEBUG_PRINTF (1, "Abort already requested.\n");
7210 mono_loader_unlock ();
7215 * Check whether we're still inside the mono_runtime_invoke_checked() and that it's
7216 * actually the correct invocation.
7218 * Careful, we do not stop the thread that's doing the invocation, so we can't
7219 * inspect its stack. However, invoke_method() also acquires the loader lock
7220 * when it's done, so we're safe here.
7224 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
7225 mono_loader_unlock ();
7226 return ERR_NO_INVOCATION;
7229 tls->abort_requested = TRUE;
7231 mono_thread_internal_abort (THREAD_TO_INTERNAL (thread));
7232 mono_loader_unlock ();
7236 case CMD_VM_SET_KEEPALIVE: {
7237 int timeout = decode_int (p, &p, end);
7238 agent_config.keepalive = timeout;
7240 #ifndef DISABLE_SOCKET_TRANSPORT
7247 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
7248 GHashTableIter iter, kiter;
7253 char *fname, *basename;
7254 gboolean ignore_case;
7255 GSList *class_list, *l;
7256 GPtrArray *res_classes, *res_domains;
7258 fname = decode_string (p, &p, end);
7259 ignore_case = decode_byte (p, &p, end);
7261 basename = dbg_path_get_basename (fname);
7263 res_classes = g_ptr_array_new ();
7264 res_domains = g_ptr_array_new ();
7266 mono_loader_lock ();
7267 g_hash_table_iter_init (&iter, domains);
7268 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7269 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
7271 /* Update 'source_file_to_class' cache */
7272 g_hash_table_iter_init (&kiter, info->loaded_classes);
7273 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
7274 if (!g_hash_table_lookup (info->source_files, klass)) {
7275 files = get_source_files_for_type (klass);
7276 g_hash_table_insert (info->source_files, klass, files);
7278 for (i = 0; i < files->len; ++i) {
7279 char *s = (char *)g_ptr_array_index (files, i);
7280 char *s2 = dbg_path_get_basename (s);
7283 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, s2);
7285 class_list = g_slist_prepend (class_list, klass);
7286 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
7288 class_list = g_slist_prepend (class_list, klass);
7289 g_hash_table_insert (info->source_file_to_class, s2, class_list);
7292 /* The _ignorecase hash contains the lowercase path */
7293 s3 = strdup_tolower (s2);
7294 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
7296 class_list = g_slist_prepend (class_list, klass);
7297 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
7299 class_list = g_slist_prepend (class_list, klass);
7300 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
7312 s = strdup_tolower (basename);
7313 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
7316 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, basename);
7319 for (l = class_list; l; l = l->next) {
7320 klass = (MonoClass *)l->data;
7322 g_ptr_array_add (res_classes, klass);
7323 g_ptr_array_add (res_domains, domain);
7326 mono_loader_unlock ();
7331 buffer_add_int (buf, res_classes->len);
7332 for (i = 0; i < res_classes->len; ++i)
7333 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7334 g_ptr_array_free (res_classes, TRUE);
7335 g_ptr_array_free (res_domains, TRUE);
7338 case CMD_VM_GET_TYPES: {
7339 GHashTableIter iter;
7343 gboolean ignore_case;
7344 GPtrArray *res_classes, *res_domains;
7345 MonoTypeNameParse info;
7347 name = decode_string (p, &p, end);
7348 ignore_case = decode_byte (p, &p, end);
7350 if (!mono_reflection_parse_type (name, &info)) {
7352 mono_reflection_free_type_info (&info);
7353 return ERR_INVALID_ARGUMENT;
7356 res_classes = g_ptr_array_new ();
7357 res_domains = g_ptr_array_new ();
7359 mono_loader_lock ();
7360 g_hash_table_iter_init (&iter, domains);
7361 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7363 gboolean type_resolve;
7367 mono_domain_assemblies_lock (domain);
7368 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7369 ass = (MonoAssembly *)tmp->data;
7373 type_resolve = TRUE;
7374 /* FIXME really okay to call while holding locks? */
7375 t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignore_case, &type_resolve, &error);
7376 mono_error_cleanup (&error);
7378 g_ptr_array_add (res_classes, mono_type_get_class (t));
7379 g_ptr_array_add (res_domains, domain);
7383 mono_domain_assemblies_unlock (domain);
7385 mono_loader_unlock ();
7388 mono_reflection_free_type_info (&info);
7390 buffer_add_int (buf, res_classes->len);
7391 for (i = 0; i < res_classes->len; ++i)
7392 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7393 g_ptr_array_free (res_classes, TRUE);
7394 g_ptr_array_free (res_domains, TRUE);
7397 case CMD_VM_START_BUFFERING:
7398 case CMD_VM_STOP_BUFFERING:
7399 /* Handled in the main loop */
7402 return ERR_NOT_IMPLEMENTED;
7409 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7415 case CMD_EVENT_REQUEST_SET: {
7417 int i, event_kind, suspend_policy, nmodifiers;
7421 MonoThread *step_thread;
7422 int step_thread_id = 0;
7423 StepDepth depth = STEP_DEPTH_INTO;
7424 StepSize size = STEP_SIZE_MIN;
7425 StepFilter filter = STEP_FILTER_NONE;
7429 event_kind = decode_byte (p, &p, end);
7430 suspend_policy = decode_byte (p, &p, end);
7431 nmodifiers = decode_byte (p, &p, end);
7433 req = (EventRequest *)g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7434 req->id = InterlockedIncrement (&event_request_id);
7435 req->event_kind = event_kind;
7436 req->suspend_policy = suspend_policy;
7437 req->nmodifiers = nmodifiers;
7440 for (i = 0; i < nmodifiers; ++i) {
7441 mod = (ModifierKind)decode_byte (p, &p, end);
7443 req->modifiers [i].kind = mod;
7444 if (mod == MOD_KIND_COUNT) {
7445 req->modifiers [i].data.count = decode_int (p, &p, end);
7446 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7447 method = decode_methodid (p, &p, end, &domain, &err);
7448 if (err != ERR_NONE)
7450 location = decode_long (p, &p, end);
7451 } else if (mod == MOD_KIND_STEP) {
7452 step_thread_id = decode_id (p, &p, end);
7453 size = (StepSize)decode_int (p, &p, end);
7454 depth = (StepDepth)decode_int (p, &p, end);
7455 if (CHECK_PROTOCOL_VERSION (2, 16))
7456 filter = (StepFilter)decode_int (p, &p, end);
7457 req->modifiers [i].data.filter = filter;
7458 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7459 /* Treat STEP_THOUGH the same as HIDDEN */
7460 req->modifiers [i].data.filter = (StepFilter)(req->modifiers [i].data.filter | STEP_FILTER_DEBUGGER_STEP_THROUGH);
7461 } else if (mod == MOD_KIND_THREAD_ONLY) {
7462 int id = decode_id (p, &p, end);
7464 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7465 if (err != ERR_NONE) {
7469 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7470 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7472 if (err != ERR_NONE)
7474 req->modifiers [i].caught = decode_byte (p, &p, end);
7475 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7476 if (CHECK_PROTOCOL_VERSION (2, 25))
7477 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7479 req->modifiers [i].subclasses = TRUE;
7480 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" : "");
7482 req->modifiers [i].data.exc_class = exc_class;
7484 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
7486 return ERR_INVALID_ARGUMENT;
7489 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7490 int n = decode_int (p, &p, end);
7493 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
7494 for (j = 0; j < n; ++j) {
7495 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7496 if (err != ERR_NONE) {
7497 g_free (req->modifiers [i].data.assemblies);
7501 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7502 int n = decode_int (p, &p, end);
7505 modifier = &req->modifiers [i];
7506 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7507 for (j = 0; j < n; ++j) {
7508 char *s = decode_string (p, &p, end);
7512 s2 = strdup_tolower (s);
7513 g_hash_table_insert (modifier->data.source_files, s2, s2);
7517 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7518 int n = decode_int (p, &p, end);
7521 modifier = &req->modifiers [i];
7522 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7523 for (j = 0; j < n; ++j) {
7524 char *s = decode_string (p, &p, end);
7527 g_hash_table_insert (modifier->data.type_names, s, s);
7531 return ERR_NOT_IMPLEMENTED;
7535 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7538 req->info = set_breakpoint (method, location, req, &error);
7539 if (!mono_error_ok (&error)) {
7541 DEBUG_PRINTF (1, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error));
7542 mono_error_cleanup (&error);
7543 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7545 } else if (req->event_kind == EVENT_KIND_STEP) {
7546 g_assert (step_thread_id);
7548 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7549 if (err != ERR_NONE) {
7554 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, filter, req);
7555 if (err != ERR_NONE) {
7559 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7560 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7561 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7562 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7563 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7564 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7566 if (req->nmodifiers) {
7568 return ERR_NOT_IMPLEMENTED;
7572 mono_loader_lock ();
7573 g_ptr_array_add (event_requests, req);
7575 if (agent_config.defer) {
7576 /* Transmit cached data to the client on receipt of the event request */
7577 switch (req->event_kind) {
7578 case EVENT_KIND_APPDOMAIN_CREATE:
7579 /* Emit load events for currently loaded domains */
7580 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7582 case EVENT_KIND_ASSEMBLY_LOAD:
7583 /* Emit load events for currently loaded assemblies */
7584 mono_assembly_foreach (emit_assembly_load, NULL);
7586 case EVENT_KIND_THREAD_START:
7587 /* Emit start events for currently started threads */
7588 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7590 case EVENT_KIND_TYPE_LOAD:
7591 /* Emit type load events for currently loaded types */
7592 mono_domain_foreach (send_types_for_domain, NULL);
7598 mono_loader_unlock ();
7600 buffer_add_int (buf, req->id);
7603 case CMD_EVENT_REQUEST_CLEAR: {
7604 int etype = decode_byte (p, &p, end);
7605 int req_id = decode_int (p, &p, end);
7607 // FIXME: Make a faster mapping from req_id to request
7608 mono_loader_lock ();
7609 clear_event_request (req_id, etype);
7610 mono_loader_unlock ();
7613 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7616 mono_loader_lock ();
7618 while (i < event_requests->len) {
7619 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
7621 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7622 clear_breakpoint ((MonoBreakpoint *)req->info);
7624 g_ptr_array_remove_index_fast (event_requests, i);
7630 mono_loader_unlock ();
7634 return ERR_NOT_IMPLEMENTED;
7641 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7647 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7648 buffer_add_domainid (buf, mono_get_root_domain ());
7651 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7652 domain = decode_domainid (p, &p, end, NULL, &err);
7653 if (err != ERR_NONE)
7655 buffer_add_string (buf, domain->friendly_name);
7658 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7663 domain = decode_domainid (p, &p, end, NULL, &err);
7664 if (err != ERR_NONE)
7666 mono_loader_lock ();
7668 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7671 buffer_add_int (buf, count);
7672 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7673 ass = (MonoAssembly *)tmp->data;
7674 buffer_add_assemblyid (buf, domain, ass);
7676 mono_loader_unlock ();
7679 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7680 domain = decode_domainid (p, &p, end, NULL, &err);
7681 if (err != ERR_NONE)
7684 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7687 case CMD_APPDOMAIN_GET_CORLIB: {
7688 domain = decode_domainid (p, &p, end, NULL, &err);
7689 if (err != ERR_NONE)
7692 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7695 case CMD_APPDOMAIN_CREATE_STRING: {
7699 domain = decode_domainid (p, &p, end, NULL, &err);
7700 if (err != ERR_NONE)
7702 s = decode_string (p, &p, end);
7704 o = mono_string_new (domain, s);
7705 buffer_add_objid (buf, (MonoObject*)o);
7708 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7711 MonoDomain *domain2;
7714 domain = decode_domainid (p, &p, end, NULL, &err);
7715 if (err != ERR_NONE)
7717 klass = decode_typeid (p, &p, end, &domain2, &err);
7718 if (err != ERR_NONE)
7722 g_assert (domain == domain2);
7724 o = mono_object_new_checked (domain, klass, &error);
7725 mono_error_assert_ok (&error);
7727 err = decode_value (&klass->byval_arg, domain, (guint8 *)mono_object_unbox (o), p, &p, end);
7728 if (err != ERR_NONE)
7731 buffer_add_objid (buf, o);
7735 return ERR_NOT_IMPLEMENTED;
7742 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7748 ass = decode_assemblyid (p, &p, end, &domain, &err);
7749 if (err != ERR_NONE)
7753 case CMD_ASSEMBLY_GET_LOCATION: {
7754 buffer_add_string (buf, mono_image_get_filename (ass->image));
7757 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7761 if (ass->image->dynamic) {
7762 buffer_add_id (buf, 0);
7764 token = mono_image_get_entry_point (ass->image);
7766 buffer_add_id (buf, 0);
7769 m = mono_get_method_checked (ass->image, token, NULL, NULL, &error);
7771 mono_error_cleanup (&error); /* FIXME don't swallow the error */
7772 buffer_add_methodid (buf, domain, m);
7777 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7778 buffer_add_moduleid (buf, domain, ass->image);
7781 case CMD_ASSEMBLY_GET_OBJECT: {
7783 MonoObject *o = (MonoObject*)mono_assembly_get_object_checked (domain, ass, &error);
7785 mono_error_cleanup (&error); /* FIXME don't swallow the error */
7786 return ERR_INVALID_OBJECT;
7788 buffer_add_objid (buf, o);
7791 case CMD_ASSEMBLY_GET_TYPE: {
7793 char *s = decode_string (p, &p, end);
7794 gboolean ignorecase = decode_byte (p, &p, end);
7795 MonoTypeNameParse info;
7797 gboolean type_resolve, res;
7798 MonoDomain *d = mono_domain_get ();
7800 /* This is needed to be able to find referenced assemblies */
7801 res = mono_domain_set (domain, FALSE);
7804 if (!mono_reflection_parse_type (s, &info)) {
7807 if (info.assembly.name)
7809 t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignorecase, &type_resolve, &error);
7810 if (!is_ok (&error)) {
7811 mono_error_cleanup (&error); /* FIXME don't swallow the error */
7812 mono_reflection_free_type_info (&info);
7814 return ERR_INVALID_ARGUMENT;
7817 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
7818 mono_reflection_free_type_info (&info);
7821 mono_domain_set (d, TRUE);
7825 case CMD_ASSEMBLY_GET_NAME: {
7827 MonoAssembly *mass = ass;
7829 name = g_strdup_printf (
7830 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7832 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7833 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7834 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7835 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7837 buffer_add_string (buf, name);
7842 return ERR_NOT_IMPLEMENTED;
7849 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7855 case CMD_MODULE_GET_INFO: {
7856 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7859 basename = g_path_get_basename (image->name);
7860 buffer_add_string (buf, basename); // name
7861 buffer_add_string (buf, image->module_name); // scopename
7862 buffer_add_string (buf, image->name); // fqname
7863 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7864 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7869 return ERR_NOT_IMPLEMENTED;
7876 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7882 case CMD_FIELD_GET_INFO: {
7883 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
7885 buffer_add_string (buf, f->name);
7886 buffer_add_typeid (buf, domain, f->parent);
7887 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7888 buffer_add_int (buf, f->type->attrs);
7892 return ERR_NOT_IMPLEMENTED;
7899 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7901 if (val && val->vtable->klass == mono_defaults.runtimetype_class) {
7902 /* Special case these so the client doesn't have to handle Type objects */
7904 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7905 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7906 } else if (MONO_TYPE_IS_REFERENCE (t))
7907 buffer_add_value (buf, t, &val, domain);
7909 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7913 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7919 buffer_add_int (buf, 0);
7923 for (i = 0; i < cinfo->num_attrs; ++i) {
7924 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7927 buffer_add_int (buf, nattrs);
7929 for (i = 0; i < cinfo->num_attrs; ++i) {
7930 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7931 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7932 MonoArray *typed_args, *named_args;
7934 CattrNamedArg *arginfo = NULL;
7937 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
7938 if (!mono_error_ok (&error)) {
7939 DEBUG_PRINTF (2, "[dbg] mono_reflection_create_custom_attr_data_args () failed with: '%s'\n", mono_error_get_message (&error));
7940 mono_error_cleanup (&error);
7941 return ERR_LOADER_ERROR;
7944 buffer_add_methodid (buf, domain, attr->ctor);
7948 buffer_add_int (buf, mono_array_length (typed_args));
7949 for (j = 0; j < mono_array_length (typed_args); ++j) {
7950 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7952 t = mono_method_signature (attr->ctor)->params [j];
7954 buffer_add_cattr_arg (buf, t, domain, val);
7957 buffer_add_int (buf, 0);
7962 buffer_add_int (buf, mono_array_length (named_args));
7964 for (j = 0; j < mono_array_length (named_args); ++j) {
7965 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7967 if (arginfo [j].prop) {
7968 buffer_add_byte (buf, 0x54);
7969 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7970 } else if (arginfo [j].field) {
7971 buffer_add_byte (buf, 0x53);
7972 buffer_add_fieldid (buf, domain, arginfo [j].field);
7974 g_assert_not_reached ();
7977 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7980 buffer_add_int (buf, 0);
7989 /* FIXME: Code duplication with icall.c */
7991 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7996 mono_class_setup_interfaces (klass, error);
7997 if (!mono_error_ok (error))
8000 for (i = 0; i < klass->interface_count; i++) {
8001 ic = klass->interfaces [i];
8002 g_hash_table_insert (ifaces, ic, ic);
8004 collect_interfaces (ic, ifaces, error);
8005 if (!mono_error_ok (error))
8011 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8023 case CMD_TYPE_GET_INFO: {
8024 buffer_add_string (buf, klass->name_space);
8025 buffer_add_string (buf, klass->name);
8027 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
8028 buffer_add_string (buf, name);
8030 buffer_add_assemblyid (buf, domain, klass->image->assembly);
8031 buffer_add_moduleid (buf, domain, klass->image);
8032 buffer_add_typeid (buf, domain, klass->parent);
8033 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
8034 buffer_add_typeid (buf, domain, klass->element_class);
8036 buffer_add_id (buf, 0);
8037 buffer_add_int (buf, klass->type_token);
8038 buffer_add_byte (buf, klass->rank);
8039 buffer_add_int (buf, mono_class_get_flags (klass));
8041 type = &klass->byval_arg;
8042 // FIXME: Can't decide whenever a class represents a byref type
8045 if (type->type == MONO_TYPE_PTR)
8047 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
8049 if (type->type == MONO_TYPE_VALUETYPE)
8051 if (klass->enumtype)
8053 if (mono_class_is_gtd (klass))
8055 if (mono_class_is_gtd (klass) || mono_class_is_ginst (klass))
8057 buffer_add_byte (buf, b);
8060 while ((nested = mono_class_get_nested_types (klass, &iter)))
8062 buffer_add_int (buf, nnested);
8064 while ((nested = mono_class_get_nested_types (klass, &iter)))
8065 buffer_add_typeid (buf, domain, nested);
8066 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8067 if (mono_class_is_gtd (klass))
8068 buffer_add_typeid (buf, domain, klass);
8069 else if (mono_class_is_ginst (klass))
8070 buffer_add_typeid (buf, domain, mono_class_get_generic_class (klass)->container_class);
8072 buffer_add_id (buf, 0);
8074 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8077 if (mono_class_is_ginst (klass)) {
8078 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
8080 count = inst->type_argc;
8081 buffer_add_int (buf, count);
8082 for (i = 0; i < count; i++)
8083 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8084 } else if (mono_class_is_gtd (klass)) {
8085 MonoGenericContainer *container = mono_class_get_generic_container (klass);
8088 count = container->type_argc;
8089 buffer_add_int (buf, count);
8090 for (i = 0; i < count; i++) {
8091 pklass = mono_class_from_generic_parameter_internal (mono_generic_container_get_param (container, i));
8092 buffer_add_typeid (buf, domain, pklass);
8095 buffer_add_int (buf, 0);
8100 case CMD_TYPE_GET_METHODS: {
8103 gpointer iter = NULL;
8106 mono_class_setup_methods (klass);
8108 nmethods = mono_class_num_methods (klass);
8110 buffer_add_int (buf, nmethods);
8112 while ((m = mono_class_get_methods (klass, &iter))) {
8113 buffer_add_methodid (buf, domain, m);
8116 g_assert (i == nmethods);
8119 case CMD_TYPE_GET_FIELDS: {
8122 gpointer iter = NULL;
8125 nfields = mono_class_num_fields (klass);
8127 buffer_add_int (buf, nfields);
8129 while ((f = mono_class_get_fields (klass, &iter))) {
8130 buffer_add_fieldid (buf, domain, f);
8131 buffer_add_string (buf, f->name);
8132 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
8133 buffer_add_int (buf, f->type->attrs);
8136 g_assert (i == nfields);
8139 case CMD_TYPE_GET_PROPERTIES: {
8142 gpointer iter = NULL;
8145 nprops = mono_class_num_properties (klass);
8147 buffer_add_int (buf, nprops);
8149 while ((p = mono_class_get_properties (klass, &iter))) {
8150 buffer_add_propertyid (buf, domain, p);
8151 buffer_add_string (buf, p->name);
8152 buffer_add_methodid (buf, domain, p->get);
8153 buffer_add_methodid (buf, domain, p->set);
8154 buffer_add_int (buf, p->attrs);
8157 g_assert (i == nprops);
8160 case CMD_TYPE_GET_CATTRS: {
8161 MonoClass *attr_klass;
8162 MonoCustomAttrInfo *cinfo;
8164 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8165 /* attr_klass can be NULL */
8166 if (err != ERR_NONE)
8169 cinfo = mono_custom_attrs_from_class_checked (klass, &error);
8170 if (!is_ok (&error)) {
8171 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8172 return ERR_LOADER_ERROR;
8175 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8176 if (err != ERR_NONE)
8180 case CMD_TYPE_GET_FIELD_CATTRS: {
8181 MonoClass *attr_klass;
8182 MonoCustomAttrInfo *cinfo;
8183 MonoClassField *field;
8185 field = decode_fieldid (p, &p, end, NULL, &err);
8186 if (err != ERR_NONE)
8188 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8189 if (err != ERR_NONE)
8192 cinfo = mono_custom_attrs_from_field_checked (klass, field, &error);
8193 if (!is_ok (&error)) {
8194 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8195 return ERR_LOADER_ERROR;
8198 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8199 if (err != ERR_NONE)
8203 case CMD_TYPE_GET_PROPERTY_CATTRS: {
8204 MonoClass *attr_klass;
8205 MonoCustomAttrInfo *cinfo;
8208 prop = decode_propertyid (p, &p, end, NULL, &err);
8209 if (err != ERR_NONE)
8211 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8212 if (err != ERR_NONE)
8215 cinfo = mono_custom_attrs_from_property_checked (klass, prop, &error);
8216 if (!is_ok (&error)) {
8217 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8218 return ERR_LOADER_ERROR;
8221 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8222 if (err != ERR_NONE)
8226 case CMD_TYPE_GET_VALUES:
8227 case CMD_TYPE_GET_VALUES_2: {
8234 MonoThread *thread_obj;
8235 MonoInternalThread *thread = NULL;
8236 guint32 special_static_type;
8238 if (command == CMD_TYPE_GET_VALUES_2) {
8239 int objid = decode_objid (p, &p, end);
8242 err = get_object (objid, (MonoObject**)&thread_obj);
8243 if (err != ERR_NONE)
8246 thread = THREAD_TO_INTERNAL (thread_obj);
8249 len = decode_int (p, &p, end);
8250 for (i = 0; i < len; ++i) {
8251 f = decode_fieldid (p, &p, end, NULL, &err);
8252 if (err != ERR_NONE)
8255 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8256 return ERR_INVALID_FIELDID;
8257 special_static_type = mono_class_field_get_special_static_type (f);
8258 if (special_static_type != SPECIAL_STATIC_NONE) {
8259 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
8260 return ERR_INVALID_FIELDID;
8263 /* Check that the field belongs to the object */
8265 for (k = klass; k; k = k->parent) {
8266 if (k == f->parent) {
8272 return ERR_INVALID_FIELDID;
8274 vtable = mono_class_vtable (domain, f->parent);
8275 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8276 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val, &error);
8277 if (!is_ok (&error))
8278 return ERR_INVALID_FIELDID;
8279 buffer_add_value (buf, f->type, val, domain);
8284 case CMD_TYPE_SET_VALUES: {
8292 len = decode_int (p, &p, end);
8293 for (i = 0; i < len; ++i) {
8294 f = decode_fieldid (p, &p, end, NULL, &err);
8295 if (err != ERR_NONE)
8298 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8299 return ERR_INVALID_FIELDID;
8300 if (mono_class_field_is_special_static (f))
8301 return ERR_INVALID_FIELDID;
8303 /* Check that the field belongs to the object */
8305 for (k = klass; k; k = k->parent) {
8306 if (k == f->parent) {
8312 return ERR_INVALID_FIELDID;
8314 // FIXME: Check for literal/const
8316 vtable = mono_class_vtable (domain, f->parent);
8317 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8318 err = decode_value (f->type, domain, val, p, &p, end);
8319 if (err != ERR_NONE) {
8323 if (MONO_TYPE_IS_REFERENCE (f->type))
8324 mono_field_static_set_value (vtable, f, *(gpointer*)val);
8326 mono_field_static_set_value (vtable, f, val);
8331 case CMD_TYPE_GET_OBJECT: {
8332 MonoObject *o = (MonoObject*)mono_type_get_object_checked (domain, &klass->byval_arg, &error);
8333 if (!mono_error_ok (&error)) {
8334 mono_error_cleanup (&error);
8335 return ERR_INVALID_OBJECT;
8337 buffer_add_objid (buf, o);
8340 case CMD_TYPE_GET_SOURCE_FILES:
8341 case CMD_TYPE_GET_SOURCE_FILES_2: {
8342 char *source_file, *base;
8346 files = get_source_files_for_type (klass);
8348 buffer_add_int (buf, files->len);
8349 for (i = 0; i < files->len; ++i) {
8350 source_file = (char *)g_ptr_array_index (files, i);
8351 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8352 buffer_add_string (buf, source_file);
8354 base = dbg_path_get_basename (source_file);
8355 buffer_add_string (buf, base);
8358 g_free (source_file);
8360 g_ptr_array_free (files, TRUE);
8363 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8364 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8366 if (err != ERR_NONE)
8368 if (mono_class_is_assignable_from (klass, oklass))
8369 buffer_add_byte (buf, 1);
8371 buffer_add_byte (buf, 0);
8374 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8375 char *name = decode_string (p, &p, end);
8376 int i, flags = decode_int (p, &p, end);
8380 mono_error_init (&error);
8381 array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &error);
8382 if (!is_ok (&error)) {
8383 mono_error_cleanup (&error);
8384 return ERR_LOADER_ERROR;
8386 buffer_add_int (buf, array->len);
8387 for (i = 0; i < array->len; ++i) {
8388 MonoMethod *method = (MonoMethod *)g_ptr_array_index (array, i);
8389 buffer_add_methodid (buf, domain, method);
8392 g_ptr_array_free (array, TRUE);
8396 case CMD_TYPE_GET_INTERFACES: {
8398 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8399 MonoClass *tclass, *iface;
8400 GHashTableIter iter;
8404 for (parent = tclass; parent; parent = parent->parent) {
8405 mono_class_setup_interfaces (parent, &error);
8406 if (!mono_error_ok (&error))
8407 return ERR_LOADER_ERROR;
8408 collect_interfaces (parent, iface_hash, &error);
8409 if (!mono_error_ok (&error))
8410 return ERR_LOADER_ERROR;
8413 buffer_add_int (buf, g_hash_table_size (iface_hash));
8415 g_hash_table_iter_init (&iter, iface_hash);
8416 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8417 buffer_add_typeid (buf, domain, iface);
8418 g_hash_table_destroy (iface_hash);
8421 case CMD_TYPE_GET_INTERFACE_MAP: {
8422 int tindex, ioffset;
8423 gboolean variance_used;
8425 int len, nmethods, i;
8429 len = decode_int (p, &p, end);
8430 mono_class_setup_vtable (klass);
8432 for (tindex = 0; tindex < len; ++tindex) {
8433 iclass = decode_typeid (p, &p, end, NULL, &err);
8434 if (err != ERR_NONE)
8437 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8439 return ERR_INVALID_ARGUMENT;
8441 nmethods = mono_class_num_methods (iclass);
8442 buffer_add_int (buf, nmethods);
8445 while ((method = mono_class_get_methods (iclass, &iter))) {
8446 buffer_add_methodid (buf, domain, method);
8448 for (i = 0; i < nmethods; ++i)
8449 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
8453 case CMD_TYPE_IS_INITIALIZED: {
8454 MonoVTable *vtable = mono_class_vtable (domain, klass);
8457 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8459 buffer_add_int (buf, 0);
8462 case CMD_TYPE_CREATE_INSTANCE: {
8466 obj = mono_object_new_checked (domain, klass, &error);
8467 mono_error_assert_ok (&error);
8468 buffer_add_objid (buf, obj);
8472 return ERR_NOT_IMPLEMENTED;
8479 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8482 MonoDomain *old_domain;
8486 klass = decode_typeid (p, &p, end, &domain, &err);
8487 if (err != ERR_NONE)
8490 old_domain = mono_domain_get ();
8492 mono_domain_set (domain, TRUE);
8494 err = type_commands_internal (command, klass, domain, p, end, buf);
8496 mono_domain_set (old_domain, TRUE);
8502 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8504 MonoMethodHeader *header;
8508 case CMD_METHOD_GET_NAME: {
8509 buffer_add_string (buf, method->name);
8512 case CMD_METHOD_GET_DECLARING_TYPE: {
8513 buffer_add_typeid (buf, domain, method->klass);
8516 case CMD_METHOD_GET_DEBUG_INFO: {
8518 MonoDebugMethodInfo *minfo;
8520 int i, j, n_il_offsets;
8522 GPtrArray *source_file_list;
8523 MonoSymSeqPoint *sym_seq_points;
8525 header = mono_method_get_header_checked (method, &error);
8527 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8528 buffer_add_int (buf, 0);
8529 buffer_add_string (buf, "");
8530 buffer_add_int (buf, 0);
8534 minfo = mono_debug_lookup_method (method);
8536 buffer_add_int (buf, header->code_size);
8537 buffer_add_string (buf, "");
8538 buffer_add_int (buf, 0);
8539 mono_metadata_free_mh (header);
8543 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, &source_files, &sym_seq_points, &n_il_offsets);
8544 buffer_add_int (buf, header->code_size);
8545 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8546 buffer_add_int (buf, source_file_list->len);
8547 for (i = 0; i < source_file_list->len; ++i) {
8548 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
8549 buffer_add_string (buf, sinfo->source_file);
8550 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8551 for (j = 0; j < 16; ++j)
8552 buffer_add_byte (buf, sinfo->hash [j]);
8556 buffer_add_string (buf, source_file);
8558 buffer_add_int (buf, n_il_offsets);
8559 DEBUG_PRINTF (10, "Line number table for method %s:\n", mono_method_full_name (method, TRUE));
8560 for (i = 0; i < n_il_offsets; ++i) {
8561 MonoSymSeqPoint *sp = &sym_seq_points [i];
8562 const char *srcfile = "";
8564 if (source_files [i] != -1) {
8565 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, source_files [i]);
8566 srcfile = sinfo->source_file;
8568 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);
8569 buffer_add_int (buf, sp->il_offset);
8570 buffer_add_int (buf, sp->line);
8571 if (CHECK_PROTOCOL_VERSION (2, 13))
8572 buffer_add_int (buf, source_files [i]);
8573 if (CHECK_PROTOCOL_VERSION (2, 19))
8574 buffer_add_int (buf, sp->column);
8575 if (CHECK_PROTOCOL_VERSION (2, 32)) {
8576 buffer_add_int (buf, sp->end_line);
8577 buffer_add_int (buf, sp->end_column);
8580 g_free (source_file);
8581 g_free (source_files);
8582 g_free (sym_seq_points);
8583 g_ptr_array_free (source_file_list, TRUE);
8584 mono_metadata_free_mh (header);
8587 case CMD_METHOD_GET_PARAM_INFO: {
8588 MonoMethodSignature *sig = mono_method_signature (method);
8592 /* FIXME: mono_class_from_mono_type () and byrefs */
8594 /* FIXME: Use a smaller encoding */
8595 buffer_add_int (buf, sig->call_convention);
8596 buffer_add_int (buf, sig->param_count);
8597 buffer_add_int (buf, sig->generic_param_count);
8598 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
8599 for (i = 0; i < sig->param_count; ++i) {
8601 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
8604 /* Emit parameter names */
8605 names = g_new (char *, sig->param_count);
8606 mono_method_get_param_names (method, (const char **) names);
8607 for (i = 0; i < sig->param_count; ++i)
8608 buffer_add_string (buf, names [i]);
8613 case CMD_METHOD_GET_LOCALS_INFO: {
8616 MonoDebugLocalsInfo *locals;
8617 int *locals_map = NULL;
8619 header = mono_method_get_header_checked (method, &error);
8621 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8622 return ERR_INVALID_ARGUMENT;
8625 locals = mono_debug_lookup_locals (method);
8627 if (CHECK_PROTOCOL_VERSION (2, 43)) {
8629 buffer_add_int (buf, 1);
8630 buffer_add_int (buf, 0);
8631 buffer_add_int (buf, header->code_size);
8633 buffer_add_int (buf, header->num_locals);
8635 for (i = 0; i < header->num_locals; ++i) {
8636 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
8639 for (i = 0; i < header->num_locals; ++i) {
8641 sprintf (lname, "V_%d", i);
8642 buffer_add_string (buf, lname);
8645 for (i = 0; i < header->num_locals; ++i) {
8646 buffer_add_int (buf, 0);
8647 buffer_add_int (buf, header->code_size);
8650 if (CHECK_PROTOCOL_VERSION (2, 43)) {
8652 buffer_add_int (buf, locals->num_blocks);
8654 for (i = 0; i < locals->num_blocks; ++i) {
8655 buffer_add_int (buf, locals->code_blocks [i].start_offset - last_start);
8656 buffer_add_int (buf, locals->code_blocks [i].end_offset - locals->code_blocks [i].start_offset);
8657 last_start = locals->code_blocks [i].start_offset;
8661 num_locals = locals->num_locals;
8662 buffer_add_int (buf, num_locals);
8665 for (i = 0; i < num_locals; ++i) {
8666 g_assert (locals->locals [i].index < header->num_locals);
8667 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [locals->locals [i].index]));
8670 for (i = 0; i < num_locals; ++i)
8671 buffer_add_string (buf, locals->locals [i].name);
8673 for (i = 0; i < num_locals; ++i) {
8674 if (locals->locals [i].block) {
8675 buffer_add_int (buf, locals->locals [i].block->start_offset);
8676 buffer_add_int (buf, locals->locals [i].block->end_offset);
8678 buffer_add_int (buf, 0);
8679 buffer_add_int (buf, header->code_size);
8683 mono_metadata_free_mh (header);
8686 mono_debug_free_locals (locals);
8687 g_free (locals_map);
8691 case CMD_METHOD_GET_INFO:
8692 buffer_add_int (buf, method->flags);
8693 buffer_add_int (buf, method->iflags);
8694 buffer_add_int (buf, method->token);
8695 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8697 if (method->is_generic)
8699 if (mono_method_signature (method)->generic_param_count)
8701 buffer_add_byte (buf, attrs);
8702 if (method->is_generic || method->is_inflated) {
8705 if (method->is_generic) {
8708 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8710 result = imethod->declaring;
8711 if (imethod->context.class_inst) {
8712 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8713 /*Generic methods gets the context of the GTD.*/
8714 if (mono_class_get_context (klass)) {
8716 result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), &error);
8717 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8722 buffer_add_methodid (buf, domain, result);
8724 buffer_add_id (buf, 0);
8726 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8727 if (mono_method_signature (method)->generic_param_count) {
8730 if (method->is_inflated) {
8731 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
8733 count = inst->type_argc;
8734 buffer_add_int (buf, count);
8736 for (i = 0; i < count; i++)
8737 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8739 buffer_add_int (buf, 0);
8741 } else if (method->is_generic) {
8742 MonoGenericContainer *container = mono_method_get_generic_container (method);
8744 count = mono_method_signature (method)->generic_param_count;
8745 buffer_add_int (buf, count);
8746 for (i = 0; i < count; i++) {
8747 MonoGenericParam *param = mono_generic_container_get_param (container, i);
8748 MonoClass *pklass = mono_class_from_generic_parameter_internal (param);
8749 buffer_add_typeid (buf, domain, pklass);
8752 buffer_add_int (buf, 0);
8755 buffer_add_int (buf, 0);
8760 case CMD_METHOD_GET_BODY: {
8764 header = mono_method_get_header_checked (method, &error);
8766 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8767 buffer_add_int (buf, 0);
8769 if (CHECK_PROTOCOL_VERSION (2, 18))
8770 buffer_add_int (buf, 0);
8772 buffer_add_int (buf, header->code_size);
8773 for (i = 0; i < header->code_size; ++i)
8774 buffer_add_byte (buf, header->code [i]);
8776 if (CHECK_PROTOCOL_VERSION (2, 18)) {
8777 buffer_add_int (buf, header->num_clauses);
8778 for (i = 0; i < header->num_clauses; ++i) {
8779 MonoExceptionClause *clause = &header->clauses [i];
8781 buffer_add_int (buf, clause->flags);
8782 buffer_add_int (buf, clause->try_offset);
8783 buffer_add_int (buf, clause->try_len);
8784 buffer_add_int (buf, clause->handler_offset);
8785 buffer_add_int (buf, clause->handler_len);
8786 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
8787 buffer_add_typeid (buf, domain, clause->data.catch_class);
8788 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8789 buffer_add_int (buf, clause->data.filter_offset);
8793 mono_metadata_free_mh (header);
8798 case CMD_METHOD_RESOLVE_TOKEN: {
8799 guint32 token = decode_int (p, &p, end);
8802 switch (mono_metadata_token_code (token)) {
8803 case MONO_TOKEN_STRING: {
8808 s = mono_ldstr_checked (domain, method->klass->image, mono_metadata_token_index (token), &error);
8809 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
8811 s2 = mono_string_to_utf8_checked (s, &error);
8812 mono_error_assert_ok (&error);
8814 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8815 buffer_add_string (buf, s2);
8822 MonoClass *handle_class;
8824 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8825 val = mono_method_get_wrapper_data (method, token);
8826 handle_class = (MonoClass *)mono_method_get_wrapper_data (method, token + 1);
8828 if (handle_class == NULL) {
8829 // Can't figure out the token type
8830 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8834 val = mono_ldtoken_checked (method->klass->image, token, &handle_class, NULL, &error);
8836 g_error ("Could not load token due to %s", mono_error_get_message (&error));
8839 if (handle_class == mono_defaults.typehandle_class) {
8840 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8841 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8842 buffer_add_typeid (buf, domain, (MonoClass *) val);
8844 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
8845 } else if (handle_class == mono_defaults.fieldhandle_class) {
8846 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8847 buffer_add_fieldid (buf, domain, (MonoClassField *)val);
8848 } else if (handle_class == mono_defaults.methodhandle_class) {
8849 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8850 buffer_add_methodid (buf, domain, (MonoMethod *)val);
8851 } else if (handle_class == mono_defaults.string_class) {
8854 s = mono_string_to_utf8_checked ((MonoString *)val, &error);
8855 mono_error_assert_ok (&error);
8856 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8857 buffer_add_string (buf, s);
8860 g_assert_not_reached ();
8867 case CMD_METHOD_GET_CATTRS: {
8869 MonoClass *attr_klass;
8870 MonoCustomAttrInfo *cinfo;
8872 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8873 /* attr_klass can be NULL */
8874 if (err != ERR_NONE)
8877 cinfo = mono_custom_attrs_from_method_checked (method, &error);
8878 if (!is_ok (&error)) {
8879 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8880 return ERR_LOADER_ERROR;
8883 err = buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
8884 if (err != ERR_NONE)
8888 case CMD_METHOD_MAKE_GENERIC_METHOD: {
8890 MonoType **type_argv;
8894 MonoGenericInst *ginst;
8895 MonoGenericContext tmp_context;
8896 MonoMethod *inflated;
8898 type_argc = decode_int (p, &p, end);
8899 type_argv = g_new0 (MonoType*, type_argc);
8900 for (i = 0; i < type_argc; ++i) {
8901 klass = decode_typeid (p, &p, end, &d, &err);
8902 if (err != ERR_NONE) {
8908 return ERR_INVALID_ARGUMENT;
8910 type_argv [i] = &klass->byval_arg;
8912 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
8914 tmp_context.class_inst = mono_class_is_ginst (method->klass) ? mono_class_get_generic_class (method->klass)->context.class_inst : NULL;
8915 tmp_context.method_inst = ginst;
8917 inflated = mono_class_inflate_generic_method_checked (method, &tmp_context, &error);
8918 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8919 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
8920 return ERR_INVALID_ARGUMENT;
8921 buffer_add_methodid (buf, domain, inflated);
8925 return ERR_NOT_IMPLEMENTED;
8932 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8935 MonoDomain *old_domain;
8939 method = decode_methodid (p, &p, end, &domain, &err);
8940 if (err != ERR_NONE)
8943 old_domain = mono_domain_get ();
8945 mono_domain_set (domain, TRUE);
8947 err = method_commands_internal (command, method, domain, p, end, buf);
8949 mono_domain_set (old_domain, TRUE);
8955 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8957 int objid = decode_objid (p, &p, end);
8959 MonoThread *thread_obj;
8960 MonoInternalThread *thread;
8962 err = get_object (objid, (MonoObject**)&thread_obj);
8963 if (err != ERR_NONE)
8966 thread = THREAD_TO_INTERNAL (thread_obj);
8969 case CMD_THREAD_GET_NAME: {
8971 gunichar2 *s = mono_thread_get_name (thread, &name_len);
8974 buffer_add_int (buf, 0);
8979 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
8981 buffer_add_int (buf, len);
8982 buffer_add_data (buf, (guint8*)name, len);
8987 case CMD_THREAD_GET_FRAME_INFO: {
8988 DebuggerTlsData *tls;
8989 int i, start_frame, length;
8991 // Wait for suspending if it already started
8992 // FIXME: Races with suspend_count
8993 while (!is_suspended ()) {
8995 wait_for_suspend ();
8999 wait_for_suspend ();
9000 if (!is_suspended ())
9001 return ERR_NOT_SUSPENDED;
9004 start_frame = decode_int (p, &p, end);
9005 length = decode_int (p, &p, end);
9007 if (start_frame != 0 || length != -1)
9008 return ERR_NOT_IMPLEMENTED;
9010 mono_loader_lock ();
9011 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9012 mono_loader_unlock ();
9015 compute_frame_info (thread, tls);
9017 buffer_add_int (buf, tls->frame_count);
9018 for (i = 0; i < tls->frame_count; ++i) {
9019 buffer_add_int (buf, tls->frames [i]->id);
9020 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
9021 buffer_add_int (buf, tls->frames [i]->il_offset);
9023 * Instead of passing the frame type directly to the client, we associate
9024 * it with the previous frame using a set of flags. This avoids lots of
9025 * conditional code in the client, since a frame whose type isn't
9026 * FRAME_TYPE_MANAGED has no method, location, etc.
9028 buffer_add_byte (buf, tls->frames [i]->flags);
9033 case CMD_THREAD_GET_STATE:
9034 buffer_add_int (buf, thread->state);
9036 case CMD_THREAD_GET_INFO:
9037 buffer_add_byte (buf, thread->threadpool_thread);
9039 case CMD_THREAD_GET_ID:
9040 buffer_add_long (buf, (guint64)(gsize)thread);
9042 case CMD_THREAD_GET_TID:
9043 buffer_add_long (buf, (guint64)thread->tid);
9045 case CMD_THREAD_SET_IP: {
9046 DebuggerTlsData *tls;
9049 MonoSeqPointInfo *seq_points;
9054 method = decode_methodid (p, &p, end, &domain, &err);
9055 if (err != ERR_NONE)
9057 il_offset = decode_long (p, &p, end);
9059 while (!is_suspended ()) {
9061 wait_for_suspend ();
9064 mono_loader_lock ();
9065 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9066 mono_loader_unlock ();
9069 compute_frame_info (thread, tls);
9070 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
9071 return ERR_INVALID_ARGUMENT;
9073 found_sp = mono_find_seq_point (domain, method, il_offset, &seq_points, &sp);
9075 g_assert (seq_points);
9078 return ERR_INVALID_ARGUMENT;
9080 // FIXME: Check that the ip change is safe
9082 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);
9083 MONO_CONTEXT_SET_IP (&tls->restore_state.ctx, (guint8*)tls->frames [0]->ji->code_start + sp.native_offset);
9087 return ERR_NOT_IMPLEMENTED;
9094 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9098 MonoThread *thread_obj;
9099 MonoInternalThread *thread;
9100 int pos, i, len, frame_idx;
9101 DebuggerTlsData *tls;
9103 MonoDebugMethodJitInfo *jit;
9104 MonoMethodSignature *sig;
9106 MonoMethodHeader *header;
9108 objid = decode_objid (p, &p, end);
9109 err = get_object (objid, (MonoObject**)&thread_obj);
9110 if (err != ERR_NONE)
9113 thread = THREAD_TO_INTERNAL (thread_obj);
9115 id = decode_id (p, &p, end);
9117 mono_loader_lock ();
9118 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9119 mono_loader_unlock ();
9122 for (i = 0; i < tls->frame_count; ++i) {
9123 if (tls->frames [i]->id == id)
9126 if (i == tls->frame_count)
9127 return ERR_INVALID_FRAMEID;
9130 frame = tls->frames [frame_idx];
9132 /* This is supported for frames without has_ctx etc. set */
9133 if (command == CMD_STACK_FRAME_GET_DOMAIN) {
9134 if (CHECK_PROTOCOL_VERSION (2, 38))
9135 buffer_add_domainid (buf, frame->domain);
9139 if (!frame->has_ctx)
9140 return ERR_ABSENT_INFORMATION;
9143 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
9144 if (!frame->jit && frame->api_method->is_inflated)
9145 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
9149 /* This could happen for aot images with no jit debug info */
9150 s = mono_method_full_name (frame->api_method, TRUE);
9151 DEBUG_PRINTF (1, "[dbg] No debug information found for '%s'.\n", s);
9153 return ERR_ABSENT_INFORMATION;
9158 sig = mono_method_signature (frame->actual_method);
9160 if (!jit->has_var_info || !mono_get_seq_points (frame->domain, frame->actual_method))
9162 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
9164 return ERR_ABSENT_INFORMATION;
9167 case CMD_STACK_FRAME_GET_VALUES: {
9169 len = decode_int (p, &p, end);
9170 header = mono_method_get_header_checked (frame->actual_method, &error);
9171 mono_error_assert_ok (&error); /* FIXME report error */
9173 for (i = 0; i < len; ++i) {
9174 pos = decode_int (p, &p, end);
9179 DEBUG_PRINTF (4, "[dbg] send arg %d.\n", pos);
9181 g_assert (pos >= 0 && pos < jit->num_params);
9183 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
9185 MonoDebugLocalsInfo *locals;
9187 locals = mono_debug_lookup_locals (frame->method);
9189 g_assert (pos < locals->num_locals);
9190 pos = locals->locals [pos].index;
9191 mono_debug_free_locals (locals);
9193 g_assert (pos >= 0 && pos < jit->num_locals);
9195 DEBUG_PRINTF (4, "[dbg] send local %d.\n", pos);
9197 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
9200 mono_metadata_free_mh (header);
9203 case CMD_STACK_FRAME_GET_THIS: {
9204 if (frame->api_method->klass->valuetype) {
9205 if (!sig->hasthis) {
9206 MonoObject *p = NULL;
9207 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
9209 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9212 if (!sig->hasthis) {
9213 MonoObject *p = NULL;
9214 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
9216 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9221 case CMD_STACK_FRAME_SET_VALUES: {
9225 MonoDebugVarInfo *var;
9227 len = decode_int (p, &p, end);
9228 header = mono_method_get_header_checked (frame->actual_method, &error);
9229 mono_error_assert_ok (&error); /* FIXME report error */
9231 for (i = 0; i < len; ++i) {
9232 pos = decode_int (p, &p, end);
9237 g_assert (pos >= 0 && pos < jit->num_params);
9239 t = sig->params [pos];
9240 var = &jit->params [pos];
9242 MonoDebugLocalsInfo *locals;
9244 locals = mono_debug_lookup_locals (frame->method);
9246 g_assert (pos < locals->num_locals);
9247 pos = locals->locals [pos].index;
9248 mono_debug_free_locals (locals);
9250 g_assert (pos >= 0 && pos < jit->num_locals);
9252 t = header->locals [pos];
9253 var = &jit->locals [pos];
9256 if (MONO_TYPE_IS_REFERENCE (t))
9257 val_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
9259 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9260 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9261 if (err != ERR_NONE)
9264 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9266 mono_metadata_free_mh (header);
9269 case CMD_STACK_FRAME_GET_DOMAIN: {
9270 if (CHECK_PROTOCOL_VERSION (2, 38))
9271 buffer_add_domainid (buf, frame->domain);
9274 case CMD_STACK_FRAME_SET_THIS: {
9277 MonoDebugVarInfo *var;
9279 t = &frame->actual_method->klass->byval_arg;
9280 /* Checked by the sender */
9281 g_assert (MONO_TYPE_ISSTRUCT (t));
9282 var = jit->this_var;
9285 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9286 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9287 if (err != ERR_NONE)
9290 set_var (&frame->actual_method->klass->this_arg, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9294 return ERR_NOT_IMPLEMENTED;
9301 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9304 int objid, index, len, i, esize;
9308 objid = decode_objid (p, &p, end);
9309 err = get_object (objid, (MonoObject**)&arr);
9310 if (err != ERR_NONE)
9314 case CMD_ARRAY_REF_GET_LENGTH:
9315 buffer_add_int (buf, arr->obj.vtable->klass->rank);
9317 buffer_add_int (buf, arr->max_length);
9318 buffer_add_int (buf, 0);
9320 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
9321 buffer_add_int (buf, arr->bounds [i].length);
9322 buffer_add_int (buf, arr->bounds [i].lower_bound);
9326 case CMD_ARRAY_REF_GET_VALUES:
9327 index = decode_int (p, &p, end);
9328 len = decode_int (p, &p, end);
9330 g_assert (index >= 0 && len >= 0);
9331 // Reordered to avoid integer overflow
9332 g_assert (!(index > arr->max_length - len));
9334 esize = mono_array_element_size (arr->obj.vtable->klass);
9335 for (i = index; i < index + len; ++i) {
9336 elem = (gpointer*)((char*)arr->vector + (i * esize));
9337 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
9340 case CMD_ARRAY_REF_SET_VALUES:
9341 index = decode_int (p, &p, end);
9342 len = decode_int (p, &p, end);
9344 g_assert (index >= 0 && len >= 0);
9345 // Reordered to avoid integer overflow
9346 g_assert (!(index > arr->max_length - len));
9348 esize = mono_array_element_size (arr->obj.vtable->klass);
9349 for (i = index; i < index + len; ++i) {
9350 elem = (gpointer*)((char*)arr->vector + (i * esize));
9352 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, (guint8 *)elem, p, &p, end);
9356 return ERR_NOT_IMPLEMENTED;
9363 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9369 int i, index, length;
9371 gboolean use_utf16 = FALSE;
9373 objid = decode_objid (p, &p, end);
9374 err = get_object (objid, (MonoObject**)&str);
9375 if (err != ERR_NONE)
9379 case CMD_STRING_REF_GET_VALUE:
9380 if (CHECK_PROTOCOL_VERSION (2, 41)) {
9381 for (i = 0; i < mono_string_length (str); ++i)
9382 if (mono_string_chars (str)[i] == 0)
9384 buffer_add_byte (buf, use_utf16 ? 1 : 0);
9387 buffer_add_int (buf, mono_string_length (str) * 2);
9388 buffer_add_data (buf, (guint8*)mono_string_chars (str), mono_string_length (str) * 2);
9391 s = mono_string_to_utf8_checked (str, &error);
9392 mono_error_assert_ok (&error);
9393 buffer_add_string (buf, s);
9397 case CMD_STRING_REF_GET_LENGTH:
9398 buffer_add_long (buf, mono_string_length (str));
9400 case CMD_STRING_REF_GET_CHARS:
9401 index = decode_long (p, &p, end);
9402 length = decode_long (p, &p, end);
9403 if (index > mono_string_length (str) - length)
9404 return ERR_INVALID_ARGUMENT;
9405 c = mono_string_chars (str) + index;
9406 for (i = 0; i < length; ++i)
9407 buffer_add_short (buf, c [i]);
9410 return ERR_NOT_IMPLEMENTED;
9417 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9428 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9429 objid = decode_objid (p, &p, end);
9430 err = get_object (objid, &obj);
9431 if (err != ERR_NONE)
9432 buffer_add_int (buf, 1);
9434 buffer_add_int (buf, 0);
9438 objid = decode_objid (p, &p, end);
9439 err = get_object (objid, &obj);
9440 if (err != ERR_NONE)
9443 MonoClass *obj_type;
9444 gboolean remote_obj = FALSE;
9446 obj_type = obj->vtable->klass;
9447 if (mono_class_is_transparent_proxy (obj_type)) {
9448 obj_type = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
9452 g_assert (obj_type);
9455 case CMD_OBJECT_REF_GET_TYPE:
9456 /* This handles transparent proxies too */
9457 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9459 case CMD_OBJECT_REF_GET_VALUES:
9460 len = decode_int (p, &p, end);
9462 for (i = 0; i < len; ++i) {
9463 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9464 if (err != ERR_NONE)
9467 /* Check that the field belongs to the object */
9469 for (k = obj_type; k; k = k->parent) {
9470 if (k == f->parent) {
9476 return ERR_INVALID_FIELDID;
9478 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9482 if (mono_class_field_is_special_static (f))
9483 return ERR_INVALID_FIELDID;
9485 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9486 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9487 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9488 mono_field_static_get_value_checked (vtable, f, val, &error);
9489 if (!is_ok (&error)) {
9490 mono_error_cleanup (&error); /* FIXME report the error */
9491 return ERR_INVALID_OBJECT;
9493 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9496 guint8 *field_value = NULL;
9499 #ifndef DISABLE_REMOTING
9500 void *field_storage = NULL;
9501 field_value = mono_load_remote_field_checked(obj, obj_type, f, &field_storage, &error);
9502 if (!is_ok (&error)) {
9503 mono_error_cleanup (&error); /* FIXME report the error */
9504 return ERR_INVALID_OBJECT;
9507 g_assert_not_reached ();
9510 field_value = (guint8*)obj + f->offset;
9512 buffer_add_value (buf, f->type, field_value, obj->vtable->domain);
9516 case CMD_OBJECT_REF_SET_VALUES:
9517 len = decode_int (p, &p, end);
9519 for (i = 0; i < len; ++i) {
9520 f = decode_fieldid (p, &p, end, NULL, &err);
9521 if (err != ERR_NONE)
9524 /* Check that the field belongs to the object */
9526 for (k = obj_type; k; k = k->parent) {
9527 if (k == f->parent) {
9533 return ERR_INVALID_FIELDID;
9535 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9539 if (mono_class_field_is_special_static (f))
9540 return ERR_INVALID_FIELDID;
9542 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9543 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9545 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9546 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
9547 if (err != ERR_NONE) {
9551 mono_field_static_set_value (vtable, f, val);
9554 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
9555 if (err != ERR_NONE)
9560 case CMD_OBJECT_REF_GET_ADDRESS:
9561 buffer_add_long (buf, (gssize)obj);
9563 case CMD_OBJECT_REF_GET_DOMAIN:
9564 buffer_add_domainid (buf, obj->vtable->domain);
9566 case CMD_OBJECT_REF_GET_INFO:
9567 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9568 buffer_add_domainid (buf, obj->vtable->domain);
9571 return ERR_NOT_IMPLEMENTED;
9578 command_set_to_string (CommandSet command_set)
9580 switch (command_set) {
9583 case CMD_SET_OBJECT_REF:
9584 return "OBJECT_REF";
9585 case CMD_SET_STRING_REF:
9586 return "STRING_REF";
9587 case CMD_SET_THREAD:
9589 case CMD_SET_ARRAY_REF:
9591 case CMD_SET_EVENT_REQUEST:
9592 return "EVENT_REQUEST";
9593 case CMD_SET_STACK_FRAME:
9594 return "STACK_FRAME";
9595 case CMD_SET_APPDOMAIN:
9597 case CMD_SET_ASSEMBLY:
9599 case CMD_SET_METHOD:
9603 case CMD_SET_MODULE:
9614 static const char* vm_cmds_str [] = {
9622 "SET_PROTOCOL_VERSION",
9625 "GET_TYPES_FOR_SOURCE_FILE",
9630 static const char* thread_cmds_str[] = {
9640 static const char* event_cmds_str[] = {
9643 "REQUEST_CLEAR_ALL_BREAKPOINTS"
9646 static const char* appdomain_cmds_str[] = {
9648 "GET_FRIENDLY_NAME",
9650 "GET_ENTRY_ASSEMBLY",
9653 "CREATE_BOXED_VALUE"
9656 static const char* assembly_cmds_str[] = {
9659 "GET_MANIFEST_MODULE",
9665 static const char* module_cmds_str[] = {
9669 static const char* field_cmds_str[] = {
9673 static const char* method_cmds_str[] = {
9675 "GET_DECLARING_TYPE",
9683 "MAKE_GENERIC_METHOD"
9686 static const char* type_cmds_str[] = {
9694 "IS_ASSIGNABLE_FROM",
9698 "GET_PROPERTY_CATTRS",
9699 "GET_SOURCE_FILES_2",
9701 "GET_METHODS_BY_NAME_FLAGS",
9703 "GET_INTERFACE_MAP",
9707 static const char* stack_frame_cmds_str[] = {
9715 static const char* array_cmds_str[] = {
9721 static const char* string_cmds_str[] = {
9727 static const char* object_cmds_str[] = {
9738 cmd_to_string (CommandSet set, int command)
9746 cmds_len = G_N_ELEMENTS (vm_cmds_str);
9748 case CMD_SET_OBJECT_REF:
9749 cmds = object_cmds_str;
9750 cmds_len = G_N_ELEMENTS (object_cmds_str);
9752 case CMD_SET_STRING_REF:
9753 cmds = string_cmds_str;
9754 cmds_len = G_N_ELEMENTS (string_cmds_str);
9756 case CMD_SET_THREAD:
9757 cmds = thread_cmds_str;
9758 cmds_len = G_N_ELEMENTS (thread_cmds_str);
9760 case CMD_SET_ARRAY_REF:
9761 cmds = array_cmds_str;
9762 cmds_len = G_N_ELEMENTS (array_cmds_str);
9764 case CMD_SET_EVENT_REQUEST:
9765 cmds = event_cmds_str;
9766 cmds_len = G_N_ELEMENTS (event_cmds_str);
9768 case CMD_SET_STACK_FRAME:
9769 cmds = stack_frame_cmds_str;
9770 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
9772 case CMD_SET_APPDOMAIN:
9773 cmds = appdomain_cmds_str;
9774 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
9776 case CMD_SET_ASSEMBLY:
9777 cmds = assembly_cmds_str;
9778 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
9780 case CMD_SET_METHOD:
9781 cmds = method_cmds_str;
9782 cmds_len = G_N_ELEMENTS (method_cmds_str);
9785 cmds = type_cmds_str;
9786 cmds_len = G_N_ELEMENTS (type_cmds_str);
9788 case CMD_SET_MODULE:
9789 cmds = module_cmds_str;
9790 cmds_len = G_N_ELEMENTS (module_cmds_str);
9793 cmds = field_cmds_str;
9794 cmds_len = G_N_ELEMENTS (field_cmds_str);
9797 cmds = event_cmds_str;
9798 cmds_len = G_N_ELEMENTS (event_cmds_str);
9803 if (command > 0 && command <= cmds_len)
9804 return cmds [command - 1];
9810 wait_for_attach (void)
9812 #ifndef DISABLE_SOCKET_TRANSPORT
9813 if (listen_fd == -1) {
9814 DEBUG_PRINTF (1, "[dbg] Invalid listening socket\n");
9818 /* Block and wait for client connection */
9819 conn_fd = socket_transport_accept (listen_fd);
9821 DEBUG_PRINTF (1, "Accepted connection on %d\n", conn_fd);
9822 if (conn_fd == -1) {
9823 DEBUG_PRINTF (1, "[dbg] Bad client connection\n");
9827 g_assert_not_reached ();
9831 disconnected = !transport_handshake ();
9833 DEBUG_PRINTF (1, "Transport handshake failed!\n");
9843 * This thread handles communication with the debugger client using a JDWP
9847 debugger_thread (void *arg)
9850 int res, len, id, flags, command = 0;
9851 CommandSet command_set = (CommandSet)0;
9852 guint8 header [HEADER_LENGTH];
9853 guint8 *data, *p, *end;
9857 gboolean attach_failed = FALSE;
9859 DEBUG_PRINTF (1, "[dbg] Agent thread started, pid=%p\n", (gpointer) (gsize) mono_native_thread_id_get ());
9861 debugger_thread_id = mono_native_thread_id_get ();
9863 MonoThread *thread = mono_thread_attach (mono_get_root_domain ());
9864 mono_thread_set_name_internal (thread->internal_thread, mono_string_new (mono_get_root_domain (), "Debugger agent"), TRUE, &error);
9865 mono_error_assert_ok (&error);
9867 thread->internal_thread->state |= ThreadState_Background;
9868 thread->internal_thread->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
9870 if (agent_config.defer) {
9871 if (!wait_for_attach ()) {
9872 DEBUG_PRINTF (1, "[dbg] Can't attach, aborting debugger thread.\n");
9873 attach_failed = TRUE; // Don't abort process when we can't listen
9875 mono_set_is_debugger_attached (TRUE);
9876 /* Send start event to client */
9877 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
9880 mono_set_is_debugger_attached (TRUE);
9883 while (!attach_failed) {
9884 res = transport_recv (header, HEADER_LENGTH);
9886 /* This will break if the socket is closed during shutdown too */
9887 if (res != HEADER_LENGTH) {
9888 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH);
9893 end = header + HEADER_LENGTH;
9895 len = decode_int (p, &p, end);
9896 id = decode_int (p, &p, end);
9897 flags = decode_byte (p, &p, end);
9898 command_set = (CommandSet)decode_byte (p, &p, end);
9899 command = decode_byte (p, &p, end);
9901 g_assert (flags == 0);
9904 const char *cmd_str;
9907 cmd_str = cmd_to_string (command_set, command);
9909 sprintf (cmd_num, "%d", command);
9913 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);
9916 data = (guint8 *)g_malloc (len - HEADER_LENGTH);
9917 if (len - HEADER_LENGTH > 0)
9919 res = transport_recv (data, len - HEADER_LENGTH);
9920 if (res != len - HEADER_LENGTH) {
9921 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH);
9927 end = data + (len - HEADER_LENGTH);
9929 buffer_init (&buf, 128);
9934 /* Process the request */
9935 switch (command_set) {
9937 err = vm_commands (command, id, p, end, &buf);
9938 if (err == ERR_NONE && command == CMD_VM_INVOKE_METHOD)
9939 /* Sent after the invoke is complete */
9942 case CMD_SET_EVENT_REQUEST:
9943 err = event_commands (command, p, end, &buf);
9945 case CMD_SET_APPDOMAIN:
9946 err = domain_commands (command, p, end, &buf);
9948 case CMD_SET_ASSEMBLY:
9949 err = assembly_commands (command, p, end, &buf);
9951 case CMD_SET_MODULE:
9952 err = module_commands (command, p, end, &buf);
9955 err = field_commands (command, p, end, &buf);
9958 err = type_commands (command, p, end, &buf);
9960 case CMD_SET_METHOD:
9961 err = method_commands (command, p, end, &buf);
9963 case CMD_SET_THREAD:
9964 err = thread_commands (command, p, end, &buf);
9966 case CMD_SET_STACK_FRAME:
9967 err = frame_commands (command, p, end, &buf);
9969 case CMD_SET_ARRAY_REF:
9970 err = array_commands (command, p, end, &buf);
9972 case CMD_SET_STRING_REF:
9973 err = string_commands (command, p, end, &buf);
9975 case CMD_SET_OBJECT_REF:
9976 err = object_commands (command, p, end, &buf);
9979 err = ERR_NOT_IMPLEMENTED;
9982 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
9983 buffer_replies = TRUE;
9987 if (buffer_replies) {
9988 buffer_reply_packet (id, err, &buf);
9990 send_reply_packet (id, err, &buf);
9991 //DEBUG_PRINTF (1, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000);
9995 if (err == ERR_NONE && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
9996 send_buffered_reply_packets ();
9997 buffer_replies = FALSE;
10001 buffer_free (&buf);
10003 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
10007 mono_set_is_debugger_attached (FALSE);
10009 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
10010 debugger_thread_exited = TRUE;
10011 mono_coop_cond_signal (&debugger_thread_exited_cond);
10012 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
10014 DEBUG_PRINTF (1, "[dbg] Debugger thread exited.\n");
10016 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
10017 DEBUG_PRINTF (2, "[dbg] Detached - restarting clean debugger thread.\n");
10018 start_debugger_thread ();
10024 #else /* DISABLE_DEBUGGER_AGENT */
10027 mono_debugger_agent_parse_options (char *options)
10029 g_error ("This runtime is configured with the debugger agent disabled.");
10033 mono_debugger_agent_init (void)
10038 mono_debugger_agent_breakpoint_hit (void *sigctx)
10043 mono_debugger_agent_single_step_event (void *sigctx)
10048 mono_debugger_agent_free_domain_info (MonoDomain *domain)
10053 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
10054 MonoContext *catch_ctx)
10059 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
10064 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
10069 mono_debugger_agent_user_break (void)
10075 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
10080 mono_debugger_agent_debug_log_is_enabled (void)
10086 mono_debugger_agent_unhandled_exception (MonoException *exc)
10088 g_assert_not_reached ();
10092 debugger_agent_single_step_from_context (MonoContext *ctx)
10094 g_assert_not_reached ();
10098 debugger_agent_breakpoint_from_context (MonoContext *ctx)
10100 g_assert_not_reached ();