2 * debugger-agent.c: Soft Debugger back-end module
5 * Zoltan Varga (vargaz@gmail.com)
7 * Copyright 2009-2010 Novell, Inc.
8 * Copyright 2011 Xamarin Inc.
15 #ifdef HAVE_SYS_TYPES_H
16 #include <sys/types.h>
18 #ifdef HAVE_SYS_SELECT_H
19 #include <sys/select.h>
21 #ifdef HAVE_SYS_SOCKET_H
22 #include <sys/socket.h>
24 #ifdef HAVE_NETINET_TCP_H
25 #include <netinet/tcp.h>
27 #ifdef HAVE_NETINET_IN_H
28 #include <netinet/in.h>
48 #ifdef PLATFORM_ANDROID
50 #include <linux/tcp.h>
51 #include <sys/endian.h>
54 #include <mono/metadata/mono-debug.h>
55 #include <mono/metadata/mono-debug-debugger.h>
56 #include <mono/metadata/debug-mono-symfile.h>
57 #include <mono/metadata/gc-internal.h>
58 #include <mono/metadata/environment.h>
59 #include <mono/metadata/threads-types.h>
60 #include <mono/metadata/socket-io.h>
61 #include <mono/metadata/assembly.h>
62 #include <mono/metadata/runtime.h>
63 #include <mono/metadata/threadpool.h>
64 #include <mono/metadata/verify-internals.h>
65 #include <mono/utils/mono-semaphore.h>
66 #include <mono/utils/mono-error-internals.h>
67 #include <mono/utils/mono-stack-unwinding.h>
68 #include <mono/utils/mono-time.h>
69 #include <mono/utils/mono-threads.h>
70 #include <mono/utils/networking.h>
71 #include "debugger-agent.h"
73 #include "seq-points.h"
76 * On iOS we can't use System.Environment.Exit () as it will do the wrong
79 #if !defined (TARGET_IOS)
80 #define TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
84 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
85 #define DISABLE_DEBUGGER_AGENT 1
88 #ifdef DISABLE_SOFT_DEBUG
89 #define DISABLE_DEBUGGER_AGENT 1
92 #ifndef DISABLE_DEBUGGER_AGENT
94 #include <mono/utils/mono-mutex.h>
96 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
119 guint32 il_offset, native_offset;
123 * If method is gshared, this is the actual instance, otherwise this is equal to
126 MonoMethod *actual_method;
128 * This is the method which is visible to debugger clients. Same as method,
129 * except for native-to-managed wrappers.
131 MonoMethod *api_method;
133 MonoDebugMethodJitInfo *jit;
136 mgreg_t *reg_locations [MONO_MAX_IREGS];
138 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
139 * the frame can become invalid.
144 typedef struct _InvokeData InvokeData;
152 /* This is the context which needs to be restored after the invoke */
156 * If this is set, invoke this method with the arguments given by ARGS.
160 guint32 suspend_count;
163 InvokeData *last_invoke;
167 MonoThreadUnwindState context;
169 /* This is computed on demand when it is requested using the wire protocol */
170 /* It is freed up when the thread is resumed */
174 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
177 gboolean frames_up_to_date;
179 * Points to data about a pending invoke which needs to be executed after the thread
182 InvokeData *pending_invoke;
184 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
189 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
190 * within a finite amount of time.
194 * Set to TRUE if this thread is suspended in suspend_current ().
196 gboolean really_suspended;
197 /* Used to pass the context to the breakpoint/single step handler */
198 MonoContext handler_ctx;
199 /* Whenever thread_stop () was called for this thread */
202 /* Whenever to disable breakpoints (used during invokes) */
203 gboolean disable_breakpoints;
206 * Number of times this thread has been resumed using resume_thread ().
208 guint32 resume_count;
210 MonoInternalThread *thread;
213 * Information about the frame which transitioned to native code for running
216 StackFrameInfo async_last_frame;
219 * The context where the stack walk can be started for running threads.
221 MonoThreadUnwindState async_state;
224 * The context used for filter clauses
226 MonoThreadUnwindState filter_state;
229 * The callee address of the last mono_runtime_invoke call
231 gpointer invoke_addr;
233 gboolean abort_requested;
236 * The current mono_runtime_invoke invocation.
241 * The context where single stepping should resume while the thread is suspended because
242 * of an EXCEPTION event.
244 MonoThreadUnwindState catch_state;
247 * The context which needs to be restored after handling a single step/breakpoint
248 * event. This is the same as the ctx at step/breakpoint site, but includes changes
249 * to caller saved registers done by set_var ().
251 MonoThreadUnwindState restore_state;
252 /* Frames computed from restore_state */
253 int restore_frame_count;
254 StackFrame **restore_frames;
256 /* The currently unloading appdomain */
257 MonoDomain *domain_unloading;
262 void (*connect) (const char *address);
263 void (*close1) (void);
264 void (*close2) (void);
265 gboolean (*send) (void *buf, int len);
266 int (*recv) (void *buf, int len);
270 * Wire Protocol definitions
273 #define HEADER_LENGTH 11
275 #define MAJOR_VERSION 2
276 #define MINOR_VERSION 40
280 CMD_SET_OBJECT_REF = 9,
281 CMD_SET_STRING_REF = 10,
283 CMD_SET_ARRAY_REF = 13,
284 CMD_SET_EVENT_REQUEST = 15,
285 CMD_SET_STACK_FRAME = 16,
286 CMD_SET_APPDOMAIN = 20,
287 CMD_SET_ASSEMBLY = 21,
296 EVENT_KIND_VM_START = 0,
297 EVENT_KIND_VM_DEATH = 1,
298 EVENT_KIND_THREAD_START = 2,
299 EVENT_KIND_THREAD_DEATH = 3,
300 EVENT_KIND_APPDOMAIN_CREATE = 4,
301 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
302 EVENT_KIND_METHOD_ENTRY = 6,
303 EVENT_KIND_METHOD_EXIT = 7,
304 EVENT_KIND_ASSEMBLY_LOAD = 8,
305 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
306 EVENT_KIND_BREAKPOINT = 10,
307 EVENT_KIND_STEP = 11,
308 EVENT_KIND_TYPE_LOAD = 12,
309 EVENT_KIND_EXCEPTION = 13,
310 EVENT_KIND_KEEPALIVE = 14,
311 EVENT_KIND_USER_BREAK = 15,
312 EVENT_KIND_USER_LOG = 16
316 SUSPEND_POLICY_NONE = 0,
317 SUSPEND_POLICY_EVENT_THREAD = 1,
318 SUSPEND_POLICY_ALL = 2
323 ERR_INVALID_OBJECT = 20,
324 ERR_INVALID_FIELDID = 25,
325 ERR_INVALID_FRAMEID = 30,
326 ERR_NOT_IMPLEMENTED = 100,
327 ERR_NOT_SUSPENDED = 101,
328 ERR_INVALID_ARGUMENT = 102,
330 ERR_NO_INVOCATION = 104,
331 ERR_ABSENT_INFORMATION = 105,
332 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
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,
506 CMD_ARRAY_REF_GET_LENGTH = 1,
507 CMD_ARRAY_REF_GET_VALUES = 2,
508 CMD_ARRAY_REF_SET_VALUES = 3,
512 CMD_STRING_REF_GET_VALUE = 1,
513 CMD_STRING_REF_GET_LENGTH = 2,
514 CMD_STRING_REF_GET_CHARS = 3
518 CMD_OBJECT_REF_GET_TYPE = 1,
519 CMD_OBJECT_REF_GET_VALUES = 2,
520 CMD_OBJECT_REF_IS_COLLECTED = 3,
521 CMD_OBJECT_REF_GET_ADDRESS = 4,
522 CMD_OBJECT_REF_GET_DOMAIN = 5,
523 CMD_OBJECT_REF_SET_VALUES = 6,
524 CMD_OBJECT_REF_GET_INFO = 7,
530 int count; /* For kind == MOD_KIND_COUNT */
531 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
532 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
533 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
534 GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
535 GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
536 StepFilter filter; /* For kind == MOD_KIND_STEP */
538 gboolean caught, uncaught, subclasses; /* For kind == MOD_KIND_EXCEPTION_ONLY */
547 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
551 * Describes a single step request.
555 MonoInternalThread *thread;
561 MonoMethod *start_method;
562 MonoMethod *last_method;
564 /* Whenever single stepping is performed using start/stop_single_stepping () */
566 /* The list of breakpoints used to implement step-over */
568 /* The number of frames at the start of a step-over */
573 * Contains additional information for an event
576 /* For EVENT_KIND_EXCEPTION */
578 MonoContext catch_ctx;
580 /* For EVENT_KIND_USER_LOG */
582 char *category, *message;
583 /* For EVENT_KIND_TYPE_LOAD */
587 /* Dummy structure used for the profiler callbacks */
593 guint8 *buf, *p, *end;
596 typedef struct ReplyPacket {
602 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
604 #ifdef PLATFORM_ANDROID
605 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { g_print (__VA_ARGS__); } } while (0)
607 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { fprintf (log_file, __VA_ARGS__); fflush (log_file); } } while (0)
611 #define get_last_sock_error() WSAGetLastError()
612 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
613 #define MONO_EINTR WSAEINTR
615 #define get_last_sock_error() errno
616 #define MONO_EWOULDBLOCK EWOULDBLOCK
617 #define MONO_EINTR EINTR
620 #define CHECK_PROTOCOL_VERSION(major,minor) \
621 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
627 static AgentConfig agent_config;
630 * Whenever the agent is fully initialized.
631 * When using the onuncaught or onthrow options, only some parts of the agent are
632 * initialized on startup, and the full initialization which includes connection
633 * establishment and the startup of the agent thread is only done in response to
636 static gint32 inited;
638 #ifndef DISABLE_SOCKET_TRANSPORT
640 static int listen_fd;
643 static int packet_id = 0;
645 static int objref_id = 0;
647 static int event_request_id = 0;
649 static int frame_id = 0;
651 static GPtrArray *event_requests;
653 static MonoNativeTlsKey debugger_tls_id;
655 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
657 /* Maps MonoInternalThread -> DebuggerTlsData */
658 static MonoGHashTable *thread_to_tls;
660 /* Maps tid -> MonoInternalThread */
661 static MonoGHashTable *tid_to_thread;
663 /* Maps tid -> MonoThread (not MonoInternalThread) */
664 static MonoGHashTable *tid_to_thread_obj;
666 static gsize debugger_thread_id;
668 static HANDLE debugger_thread_handle;
670 static int log_level;
672 static gboolean embedding;
674 static FILE *log_file;
676 /* Assemblies whose assembly load event has no been sent yet */
677 /* Protected by the dbg lock */
678 static GPtrArray *pending_assembly_loads;
680 /* Whenever the debugger thread has exited */
681 static gboolean debugger_thread_exited;
683 /* Cond variable used to wait for debugger_thread_exited becoming true */
684 static mono_cond_t debugger_thread_exited_cond;
686 /* Mutex for the cond var above */
687 static mono_mutex_t debugger_thread_exited_mutex;
689 static DebuggerProfiler debugger_profiler;
691 /* The single step request instance */
692 static SingleStepReq *ss_req;
693 static gpointer ss_invoke_addr;
695 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
696 /* Number of single stepping operations in progress */
700 /* The protocol version of the client */
701 static int major_version, minor_version;
703 /* Whenever the variables above are set by the client */
704 static gboolean protocol_version_set;
706 /* A hash table containing all active domains */
707 static GHashTable *domains;
709 /* The number of times the runtime is suspended */
710 static gint32 suspend_count;
712 /* Whenever to buffer reply messages and send them together */
713 static gboolean buffer_replies;
715 /* Buffered reply packets */
716 static ReplyPacket reply_packets [128];
719 #define dbg_lock() do { \
721 mono_mutex_lock (&debug_mutex); \
722 MONO_FINISH_TRY_BLOCKING \
725 #define dbg_unlock() mono_mutex_unlock (&debug_mutex)
726 static mono_mutex_t debug_mutex;
728 static void transport_init (void);
729 static void transport_connect (const char *address);
730 static gboolean transport_handshake (void);
731 static void register_transport (DebuggerTransport *trans);
733 static guint32 WINAPI debugger_thread (void *arg);
735 static void runtime_initialized (MonoProfiler *prof);
737 static void runtime_shutdown (MonoProfiler *prof);
739 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
741 static void thread_end (MonoProfiler *prof, uintptr_t tid);
743 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
745 static void appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain);
747 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
749 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
751 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
753 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
755 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
757 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
759 static void emit_assembly_load (gpointer assembly, gpointer user_data);
761 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
763 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
765 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
767 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
769 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
771 static void start_single_stepping (void);
773 static void stop_single_stepping (void);
775 static void suspend_current (void);
777 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
779 static void clear_types_for_assembly (MonoAssembly *assembly);
781 static void clear_breakpoints_for_domain (MonoDomain *domain);
783 static void process_profiler_event (EventKind event, gpointer arg);
785 /* Submodule init/cleanup */
786 static void breakpoints_init (void);
787 static void breakpoints_cleanup (void);
789 static void objrefs_init (void);
790 static void objrefs_cleanup (void);
792 static void ids_init (void);
793 static void ids_cleanup (void);
795 static void suspend_init (void);
797 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch,
798 StackFrame **frames, int nframes);
799 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req);
800 static void ss_destroy (SingleStepReq *req);
802 static void start_debugger_thread (void);
803 static void stop_debugger_thread (void);
805 static void finish_agent_init (gboolean on_startup);
807 static void process_profiler_event (EventKind event, gpointer arg);
809 static void invalidate_frames (DebuggerTlsData *tls);
811 #ifndef DISABLE_SOCKET_TRANSPORT
813 register_socket_transport (void);
816 static inline gboolean
817 is_debugger_thread (void)
819 return GetCurrentThreadId () == debugger_thread_id;
823 parse_address (char *address, char **host, int *port)
825 char *pos = strchr (address, ':');
827 if (pos == NULL || pos == address)
830 *host = g_malloc (pos - address + 1);
831 strncpy (*host, address, pos - address);
832 (*host) [pos - address] = '\0';
834 *port = atoi (pos + 1);
842 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
843 fprintf (stderr, "Available options:\n");
844 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
845 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
846 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
847 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
848 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
849 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
850 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
851 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
852 fprintf (stderr, " setpgid=y/n\t\t\tWhether to call setpid(0, 0) after startup.\n");
853 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
857 parse_flag (const char *option, char *flag)
859 if (!strcmp (flag, "y"))
861 else if (!strcmp (flag, "n"))
864 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
871 mono_debugger_agent_parse_options (char *options)
878 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
879 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
883 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
885 options = g_strdup_printf ("%s,%s", options, extra);
887 agent_config.enabled = TRUE;
888 agent_config.suspend = TRUE;
889 agent_config.server = FALSE;
890 agent_config.defer = FALSE;
891 agent_config.address = NULL;
893 //agent_config.log_level = 10;
895 args = g_strsplit (options, ",", -1);
896 for (ptr = args; ptr && *ptr; ptr ++) {
899 if (strncmp (arg, "transport=", 10) == 0) {
900 agent_config.transport = g_strdup (arg + 10);
901 } else if (strncmp (arg, "address=", 8) == 0) {
902 agent_config.address = g_strdup (arg + 8);
903 } else if (strncmp (arg, "loglevel=", 9) == 0) {
904 agent_config.log_level = atoi (arg + 9);
905 } else if (strncmp (arg, "logfile=", 8) == 0) {
906 agent_config.log_file = g_strdup (arg + 8);
907 } else if (strncmp (arg, "suspend=", 8) == 0) {
908 agent_config.suspend = parse_flag ("suspend", arg + 8);
909 } else if (strncmp (arg, "server=", 7) == 0) {
910 agent_config.server = parse_flag ("server", arg + 7);
911 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
912 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
913 } else if (strncmp (arg, "onthrow=", 8) == 0) {
914 /* We support multiple onthrow= options */
915 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
916 } else if (strncmp (arg, "onthrow", 7) == 0) {
917 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
918 } else if (strncmp (arg, "help", 4) == 0) {
921 } else if (strncmp (arg, "timeout=", 8) == 0) {
922 agent_config.timeout = atoi (arg + 8);
923 } else if (strncmp (arg, "launch=", 7) == 0) {
924 agent_config.launch = g_strdup (arg + 7);
925 } else if (strncmp (arg, "embedding=", 10) == 0) {
926 agent_config.embedding = atoi (arg + 10) == 1;
927 } else if (strncmp (arg, "keepalive=", 10) == 0) {
928 agent_config.keepalive = atoi (arg + 10);
929 } else if (strncmp (arg, "setpgid=", 8) == 0) {
930 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
937 if (agent_config.server && !agent_config.suspend) {
938 /* Waiting for deferred attachment */
939 agent_config.defer = TRUE;
940 if (agent_config.address == NULL) {
941 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (getpid () % 1000));
945 //agent_config.log_level = 0;
947 if (agent_config.transport == NULL) {
948 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
952 if (agent_config.address == NULL && !agent_config.server) {
953 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
958 if (!strcmp (agent_config.transport, "dt_socket")) {
959 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
960 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
967 mono_debugger_agent_init (void)
969 mono_mutex_init_recursive (&debug_mutex);
971 if (!agent_config.enabled)
976 /* Need to know whenever a thread has acquired the loader mutex */
977 mono_loader_lock_track_ownership (TRUE);
979 event_requests = g_ptr_array_new ();
981 mono_mutex_init (&debugger_thread_exited_mutex);
982 mono_cond_init (&debugger_thread_exited_cond, NULL);
984 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
985 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
986 mono_profiler_install_runtime_initialized (runtime_initialized);
987 mono_profiler_install_appdomain (NULL, appdomain_load, appdomain_start_unload, appdomain_unload);
988 mono_profiler_install_thread (thread_startup, thread_end);
989 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
990 mono_profiler_install_jit_end (jit_end);
991 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
993 mono_native_tls_alloc (&debugger_tls_id, NULL);
995 /* Needed by the hash_table_new_type () call below */
996 mono_gc_base_init ();
998 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
999 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls);
1001 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
1002 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread);
1004 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
1005 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj);
1007 pending_assembly_loads = g_ptr_array_new ();
1008 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
1010 log_level = agent_config.log_level;
1012 embedding = agent_config.embedding;
1013 disconnected = TRUE;
1015 if (agent_config.log_file) {
1016 log_file = fopen (agent_config.log_file, "w+");
1018 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
1027 breakpoints_init ();
1030 mini_get_debug_options ()->gen_sdb_seq_points = TRUE;
1032 * This is needed because currently we don't handle liveness info.
1034 mini_get_debug_options ()->mdb_optimizations = TRUE;
1036 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
1037 /* This is needed because we can't set local variables in registers yet */
1038 mono_disable_optimizations (MONO_OPT_LINEARS);
1042 * The stack walk done from thread_interrupt () needs to be signal safe, but it
1043 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
1044 * safe (#3411). So load AOT info eagerly when the debugger is running as a
1047 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
1050 if (agent_config.setpgid)
1054 if (!agent_config.onuncaught && !agent_config.onthrow)
1055 finish_agent_init (TRUE);
1059 * finish_agent_init:
1061 * Finish the initialization of the agent. This involves connecting the transport
1062 * and starting the agent thread. This is either done at startup, or
1063 * in response to some event like an unhandled exception.
1066 finish_agent_init (gboolean on_startup)
1070 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
1073 if (agent_config.launch) {
1076 // FIXME: Generated address
1077 // FIXME: Races with transport_connect ()
1079 argv [0] = agent_config.launch;
1080 argv [1] = agent_config.transport;
1081 argv [2] = agent_config.address;
1084 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1086 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1091 MONO_PREPARE_BLOCKING
1092 transport_connect (agent_config.address);
1093 MONO_FINISH_BLOCKING
1096 /* Do some which is usually done after sending the VMStart () event */
1097 vm_start_event_sent = TRUE;
1098 start_debugger_thread ();
1103 mono_debugger_agent_cleanup (void)
1108 stop_debugger_thread ();
1110 breakpoints_cleanup ();
1114 mono_mutex_destroy (&debugger_thread_exited_mutex);
1115 mono_cond_destroy (&debugger_thread_exited_cond);
1122 #ifndef DISABLE_SOCKET_TRANSPORT
1127 * recv() + handle incomplete reads and EINTR
1130 socket_transport_recv (void *buf, int len)
1136 static gint32 last_keepalive;
1141 res = recv (fd, (char *) buf + total, len - total, flags);
1144 if (agent_config.keepalive) {
1145 gboolean need_keepalive = FALSE;
1146 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1147 need_keepalive = TRUE;
1148 } else if (res == -1) {
1149 /* This could happen if recv () is interrupted repeatedly */
1150 msecs = mono_msec_ticks ();
1151 if (msecs - last_keepalive >= agent_config.keepalive) {
1152 need_keepalive = TRUE;
1153 last_keepalive = msecs;
1156 if (need_keepalive) {
1157 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1161 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1166 set_keepalive (void)
1171 if (!agent_config.keepalive || !conn_fd)
1174 tv.tv_sec = agent_config.keepalive / 1000;
1175 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1177 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1178 g_assert (result >= 0);
1182 socket_transport_accept (int socket_fd)
1184 conn_fd = accept (socket_fd, NULL, NULL);
1185 if (conn_fd == -1) {
1186 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1188 DEBUG_PRINTF (1, "Accepted connection from client, connection fd=%d.\n", conn_fd);
1195 socket_transport_send (void *data, int len)
1200 res = send (conn_fd, data, len, 0);
1201 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1209 * socket_transport_connect:
1211 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1214 socket_transport_connect (const char *address)
1216 MonoAddressInfo *result;
1217 MonoAddressEntry *rp;
1218 int sfd = -1, s, res;
1222 if (agent_config.address) {
1223 res = parse_address (agent_config.address, &host, &port);
1224 g_assert (res == 0);
1235 mono_network_init ();
1237 /* Obtain address(es) matching host/port */
1238 s = mono_get_address_info (host, port, MONO_HINT_UNSPECIFIED, &result);
1240 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, s); // FIXME add portable error conversion functions
1245 if (agent_config.server) {
1246 /* Wait for a connection */
1248 struct sockaddr_in addr;
1251 /* No address, generate one */
1252 sfd = socket (AF_INET, SOCK_STREAM, 0);
1255 /* This will bind the socket to a random port */
1256 res = listen (sfd, 16);
1258 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1263 addrlen = sizeof (addr);
1264 memset (&addr, 0, sizeof (addr));
1265 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1266 g_assert (res == 0);
1268 host = (char*)"127.0.0.1";
1269 port = ntohs (addr.sin_port);
1271 /* Emit the address to stdout */
1272 /* FIXME: Should print another interface, not localhost */
1273 printf ("%s:%d\n", host, port);
1275 /* Listen on the provided address */
1276 for (rp = result->entries; rp != NULL; rp = rp->next) {
1277 MonoSocketAddress sockaddr;
1281 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1283 sfd = socket (rp->family, rp->socktype,
1288 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1291 res = bind (sfd, &sockaddr.addr, sock_len);
1295 res = listen (sfd, 16);
1302 mono_free_address_info (result);
1305 if (agent_config.defer)
1308 DEBUG_PRINTF (1, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout);
1310 if (agent_config.timeout) {
1315 tv.tv_usec = agent_config.timeout * 1000;
1317 FD_SET (sfd, &readfds);
1318 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1320 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1325 MONO_PREPARE_BLOCKING
1326 conn_fd = socket_transport_accept (sfd);
1327 MONO_FINISH_BLOCKING
1331 DEBUG_PRINTF (1, "Accepted connection from client, socket fd=%d.\n", conn_fd);
1333 /* Connect to the specified address */
1334 /* FIXME: Respect the timeout */
1335 for (rp = result->entries; rp != NULL; rp = rp->next) {
1336 MonoSocketAddress sockaddr;
1339 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1341 sfd = socket (rp->family, rp->socktype,
1346 if (connect (sfd, &sockaddr.addr, sock_len) != -1)
1347 break; /* Success */
1353 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1359 mono_free_address_info (result);
1362 if (!transport_handshake ())
1367 socket_transport_close1 (void)
1369 /* This will interrupt the agent thread */
1370 /* Close the read part only so it can still send back replies */
1371 /* Also shut down the connection listener so that we can exit normally */
1373 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1374 shutdown (conn_fd, SD_BOTH);
1375 shutdown (listen_fd, SD_BOTH);
1376 closesocket (listen_fd);
1378 shutdown (conn_fd, SHUT_RD);
1379 shutdown (listen_fd, SHUT_RDWR);
1385 socket_transport_close2 (void)
1388 shutdown (conn_fd, SD_BOTH);
1390 shutdown (conn_fd, SHUT_RDWR);
1395 register_socket_transport (void)
1397 DebuggerTransport trans;
1399 trans.name = "dt_socket";
1400 trans.connect = socket_transport_connect;
1401 trans.close1 = socket_transport_close1;
1402 trans.close2 = socket_transport_close2;
1403 trans.send = socket_transport_send;
1404 trans.recv = socket_transport_recv;
1406 register_transport (&trans);
1410 * socket_fd_transport_connect:
1414 socket_fd_transport_connect (const char *address)
1418 res = sscanf (address, "%d", &conn_fd);
1420 fprintf (stderr, "debugger-agent: socket-fd transport address is invalid: '%s'\n", address);
1424 if (!transport_handshake ())
1429 register_socket_fd_transport (void)
1431 DebuggerTransport trans;
1433 /* This is the same as the 'dt_socket' transport, but receives an already connected socket fd */
1434 trans.name = "socket-fd";
1435 trans.connect = socket_fd_transport_connect;
1436 trans.close1 = socket_transport_close1;
1437 trans.close2 = socket_transport_close2;
1438 trans.send = socket_transport_send;
1439 trans.recv = socket_transport_recv;
1441 register_transport (&trans);
1444 #endif /* DISABLE_SOCKET_TRANSPORT */
1450 #define MAX_TRANSPORTS 16
1452 static DebuggerTransport *transport;
1454 static DebuggerTransport transports [MAX_TRANSPORTS];
1455 static int ntransports;
1458 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1461 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1463 register_transport (trans);
1467 register_transport (DebuggerTransport *trans)
1469 g_assert (ntransports < MAX_TRANSPORTS);
1471 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1476 transport_init (void)
1480 #ifndef DISABLE_SOCKET_TRANSPORT
1481 register_socket_transport ();
1482 register_socket_fd_transport ();
1485 for (i = 0; i < ntransports; ++i) {
1486 if (!strcmp (agent_config.transport, transports [i].name))
1489 if (i == ntransports) {
1490 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1491 for (i = 0; i < ntransports; ++i)
1492 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1493 fprintf (stderr, "\n");
1496 transport = &transports [i];
1500 transport_connect (const char *address)
1502 transport->connect (address);
1506 transport_close1 (void)
1508 transport->close1 ();
1512 transport_close2 (void)
1514 transport->close2 ();
1518 transport_send (void *buf, int len)
1520 return transport->send (buf, len);
1524 transport_recv (void *buf, int len)
1526 return transport->recv (buf, len);
1530 mono_debugger_agent_transport_handshake (void)
1532 return transport_handshake ();
1536 transport_handshake (void)
1538 char handshake_msg [128];
1542 disconnected = TRUE;
1544 /* Write handshake message */
1545 sprintf (handshake_msg, "DWP-Handshake");
1546 /* Must use try blocking as this can nest into code that runs blocking */
1549 res = transport_send (handshake_msg, strlen (handshake_msg));
1550 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1551 MONO_FINISH_TRY_BLOCKING
1553 g_assert (res != -1);
1557 res = transport_recv (buf, strlen (handshake_msg));
1558 MONO_FINISH_TRY_BLOCKING
1559 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg)) != 0)) {
1560 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1565 * To support older clients, the client sends its protocol version after connecting
1566 * using a command. Until that is received, default to our protocol version.
1568 major_version = MAJOR_VERSION;
1569 minor_version = MINOR_VERSION;
1570 protocol_version_set = FALSE;
1572 #ifndef DISABLE_SOCKET_TRANSPORT
1573 // FIXME: Move this somewhere else
1575 * Set TCP_NODELAY on the socket so the client receives events/command
1576 * results immediately.
1580 int result = setsockopt (conn_fd,
1585 g_assert (result >= 0);
1591 disconnected = FALSE;
1596 stop_debugger_thread (void)
1601 MONO_PREPARE_BLOCKING
1602 transport_close1 ();
1603 MONO_FINISH_BLOCKING
1606 * Wait for the thread to exit.
1608 * If we continue with the shutdown without waiting for it, then the client might
1609 * not receive an answer to its last command like a resume.
1611 if (GetCurrentThreadId () != debugger_thread_id) {
1614 mono_mutex_lock (&debugger_thread_exited_mutex);
1615 if (!debugger_thread_exited)
1616 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1617 mono_mutex_unlock (&debugger_thread_exited_mutex);
1618 MONO_FINISH_TRY_BLOCKING
1619 } while (!debugger_thread_exited);
1622 MONO_PREPARE_BLOCKING
1623 transport_close2 ();
1624 MONO_FINISH_BLOCKING
1628 start_debugger_thread (void)
1630 debugger_thread_handle = mono_threads_create_thread (debugger_thread, NULL, 0, 0, NULL);
1631 g_assert (debugger_thread_handle);
1635 * Functions to decode protocol data
1639 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1642 g_assert (*endbuf <= limit);
1647 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1650 g_assert (*endbuf <= limit);
1652 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1655 static inline gint64
1656 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1658 guint32 high = decode_int (buf, &buf, limit);
1659 guint32 low = decode_int (buf, &buf, limit);
1663 return ((((guint64)high) << 32) | ((guint64)low));
1667 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1669 return decode_int (buf, endbuf, limit);
1673 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1675 int len = decode_int (buf, &buf, limit);
1683 s = g_malloc (len + 1);
1686 memcpy (s, buf, len);
1695 * Functions to encode protocol data
1699 buffer_init (Buffer *buf, int size)
1701 buf->buf = g_malloc (size);
1703 buf->end = buf->buf + size;
1707 buffer_len (Buffer *buf)
1709 return buf->p - buf->buf;
1713 buffer_make_room (Buffer *buf, int size)
1715 if (buf->end - buf->p < size) {
1716 int new_size = buf->end - buf->buf + size + 32;
1717 guint8 *p = g_realloc (buf->buf, new_size);
1718 size = buf->p - buf->buf;
1721 buf->end = buf->buf + new_size;
1726 buffer_add_byte (Buffer *buf, guint8 val)
1728 buffer_make_room (buf, 1);
1734 buffer_add_short (Buffer *buf, guint32 val)
1736 buffer_make_room (buf, 2);
1737 buf->p [0] = (val >> 8) & 0xff;
1738 buf->p [1] = (val >> 0) & 0xff;
1743 buffer_add_int (Buffer *buf, guint32 val)
1745 buffer_make_room (buf, 4);
1746 buf->p [0] = (val >> 24) & 0xff;
1747 buf->p [1] = (val >> 16) & 0xff;
1748 buf->p [2] = (val >> 8) & 0xff;
1749 buf->p [3] = (val >> 0) & 0xff;
1754 buffer_add_long (Buffer *buf, guint64 l)
1756 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1757 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1761 buffer_add_id (Buffer *buf, int id)
1763 buffer_add_int (buf, (guint64)id);
1767 buffer_add_data (Buffer *buf, guint8 *data, int len)
1769 buffer_make_room (buf, len);
1770 memcpy (buf->p, data, len);
1775 buffer_add_string (Buffer *buf, const char *str)
1780 buffer_add_int (buf, 0);
1783 buffer_add_int (buf, len);
1784 buffer_add_data (buf, (guint8*)str, len);
1789 buffer_add_buffer (Buffer *buf, Buffer *data)
1791 buffer_add_data (buf, data->buf, buffer_len (data));
1795 buffer_free (Buffer *buf)
1801 send_packet (int command_set, int command, Buffer *data)
1807 id = InterlockedIncrement (&packet_id);
1809 len = data->p - data->buf + 11;
1810 buffer_init (&buf, len);
1811 buffer_add_int (&buf, len);
1812 buffer_add_int (&buf, id);
1813 buffer_add_byte (&buf, 0); /* flags */
1814 buffer_add_byte (&buf, command_set);
1815 buffer_add_byte (&buf, command);
1816 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1818 MONO_PREPARE_BLOCKING
1819 res = transport_send (buf.buf, len);
1820 MONO_FINISH_BLOCKING
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 MONO_PREPARE_BLOCKING
1848 res = transport_send (buf.buf, len);
1849 MONO_FINISH_BLOCKING
1857 send_reply_packet (int id, int error, Buffer *data)
1861 memset (&packet, 0, sizeof (ReplyPacket));
1863 packet.error = error;
1866 return send_reply_packets (1, &packet);
1870 send_buffered_reply_packets (void)
1874 send_reply_packets (nreply_packets, reply_packets);
1875 for (i = 0; i < nreply_packets; ++i)
1876 buffer_free (reply_packets [i].data);
1877 DEBUG_PRINTF (1, "[dbg] Sent %d buffered reply packets [at=%lx].\n", nreply_packets, (long)mono_100ns_ticks () / 10000);
1882 buffer_reply_packet (int id, int error, Buffer *data)
1886 if (nreply_packets == 128)
1887 send_buffered_reply_packets ();
1889 p = &reply_packets [nreply_packets];
1892 p->data = g_new0 (Buffer, 1);
1893 buffer_init (p->data, buffer_len (data));
1894 buffer_add_buffer (p->data, data);
1903 * Represents an object accessible by the debugger client.
1906 /* Unique id used in the wire protocol to refer to objects */
1909 * A weakref gc handle pointing to the object. The gc handle is used to
1910 * detect if the object was garbage collected.
1915 /* Maps objid -> ObjRef */
1916 static GHashTable *objrefs;
1917 static GHashTable *obj_to_objref;
1918 /* Protected by the dbg lock */
1919 static MonoGHashTable *suspended_objs;
1922 free_objref (gpointer 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);
1937 MONO_GC_REGISTER_ROOT_FIXED (suspended_objs);
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 = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1981 for (l = reflist; l; l = l->next) {
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 = 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)
2033 return get_objref (obj)->id;
2037 * Set OBJ to the object identified by OBJID.
2038 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
2042 get_object_allow_null (int objid, MonoObject **obj)
2052 return ERR_INVALID_OBJECT;
2054 mono_loader_lock ();
2056 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
2059 *obj = mono_gchandle_get_target (ref->handle);
2060 mono_loader_unlock ();
2062 return ERR_INVALID_OBJECT;
2065 mono_loader_unlock ();
2066 return ERR_INVALID_OBJECT;
2071 get_object (int objid, MonoObject **obj)
2073 int err = get_object_allow_null (objid, obj);
2078 return ERR_INVALID_OBJECT;
2083 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
2085 return decode_id (buf, endbuf, limit);
2089 buffer_add_objid (Buffer *buf, MonoObject *o)
2091 buffer_add_id (buf, get_objid (o));
2110 * Represents a runtime structure accessible to the debugger client
2113 /* Unique id used in the wire protocol */
2115 /* Domain of the runtime structure, NULL if the domain was unloaded */
2122 MonoAssembly *assembly;
2123 MonoClassField *field;
2125 MonoProperty *property;
2130 /* Maps runtime structure -> Id */
2131 GHashTable *val_to_id [ID_NUM];
2132 /* Classes whose class load event has been sent */
2133 GHashTable *loaded_classes;
2134 /* Maps MonoClass->GPtrArray of file names */
2135 GHashTable *source_files;
2136 /* Maps source file basename -> GSList of classes */
2137 GHashTable *source_file_to_class;
2138 /* Same with ignore-case */
2139 GHashTable *source_file_to_class_ignorecase;
2143 /* Protected by the dbg lock */
2144 static GPtrArray *ids [ID_NUM];
2151 for (i = 0; i < ID_NUM; ++i)
2152 ids [i] = g_ptr_array_new ();
2160 for (i = 0; i < ID_NUM; ++i) {
2162 for (j = 0; j < ids [i]->len; ++j)
2163 g_free (g_ptr_array_index (ids [i], j));
2164 g_ptr_array_free (ids [i], TRUE);
2171 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2173 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
2175 GHashTableIter iter;
2176 GPtrArray *file_names;
2181 for (i = 0; i < ID_NUM; ++i)
2182 if (info->val_to_id [i])
2183 g_hash_table_destroy (info->val_to_id [i]);
2184 g_hash_table_destroy (info->loaded_classes);
2186 g_hash_table_iter_init (&iter, info->source_files);
2187 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2188 for (i = 0; i < file_names->len; ++i)
2189 g_free (g_ptr_array_index (file_names, i));
2190 g_ptr_array_free (file_names, TRUE);
2193 g_hash_table_iter_init (&iter, info->source_file_to_class);
2194 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2199 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2200 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2208 domain_jit_info (domain)->agent_info = NULL;
2210 /* Clear ids referencing structures in the domain */
2212 for (i = 0; i < ID_NUM; ++i) {
2214 for (j = 0; j < ids [i]->len; ++j) {
2215 Id *id = g_ptr_array_index (ids [i], j);
2216 if (id->domain == domain)
2223 mono_loader_lock ();
2224 g_hash_table_remove (domains, domain);
2225 mono_loader_unlock ();
2228 static AgentDomainInfo*
2229 get_agent_domain_info (MonoDomain *domain)
2231 AgentDomainInfo *info = NULL;
2233 mono_domain_lock (domain);
2235 info = domain_jit_info (domain)->agent_info;
2237 info = domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
2238 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2239 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2240 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2241 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2244 mono_domain_unlock (domain);
2250 get_id (MonoDomain *domain, IdType type, gpointer val)
2253 AgentDomainInfo *info;
2258 mono_loader_lock ();
2260 mono_domain_lock (domain);
2262 info = get_agent_domain_info (domain);
2264 if (info->val_to_id [type] == NULL)
2265 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2267 id = g_hash_table_lookup (info->val_to_id [type], val);
2269 mono_domain_unlock (domain);
2270 mono_loader_unlock ();
2276 id = g_new0 (Id, 1);
2278 id->id = ids [type]->len + 1;
2279 id->domain = domain;
2282 g_hash_table_insert (info->val_to_id [type], val, id);
2283 g_ptr_array_add (ids [type], id);
2287 mono_domain_unlock (domain);
2289 mono_loader_unlock ();
2294 static inline gpointer
2295 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
2299 int id = decode_id (buf, endbuf, limit);
2308 // FIXME: error handling
2310 g_assert (id > 0 && id <= ids [type]->len);
2312 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2315 if (res->domain == NULL) {
2316 DEBUG_PRINTF (1, "ERR_UNLOADED, id=%d, type=%d.\n", id, type);
2317 *err = ERR_UNLOADED;
2322 *domain = res->domain;
2324 return res->data.val;
2328 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2330 int id = get_id (domain, type, val);
2332 buffer_add_id (buf, id);
2336 static inline MonoClass*
2337 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2341 klass = decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2342 if (G_UNLIKELY (log_level >= 2) && klass) {
2345 s = mono_type_full_name (&klass->byval_arg);
2346 DEBUG_PRINTF (2, "[dbg] recv class [%s]\n", s);
2352 static inline MonoAssembly*
2353 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2355 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2358 static inline MonoImage*
2359 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2361 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2364 static inline MonoMethod*
2365 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2369 m = decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2370 if (G_UNLIKELY (log_level >= 2) && m) {
2373 s = mono_method_full_name (m, TRUE);
2374 DEBUG_PRINTF (2, "[dbg] recv method [%s]\n", s);
2380 static inline MonoClassField*
2381 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2383 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2386 static inline MonoDomain*
2387 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2389 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2392 static inline MonoProperty*
2393 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2395 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2399 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2401 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2402 if (G_UNLIKELY (log_level >= 2) && klass) {
2405 s = mono_type_full_name (&klass->byval_arg);
2406 if (GetCurrentThreadId () == debugger_thread_id)
2407 DEBUG_PRINTF (2, "[dbg] send class [%s]\n", s);
2409 DEBUG_PRINTF (2, "[%p] send class [%s]\n", (gpointer)GetCurrentThreadId (), s);
2415 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2417 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2418 if (G_UNLIKELY (log_level >= 2) && method) {
2421 s = mono_method_full_name (method, 1);
2422 DEBUG_PRINTF (2, "[dbg] send method [%s]\n", s);
2428 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2432 id = buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2433 if (G_UNLIKELY (log_level >= 2) && assembly)
2434 DEBUG_PRINTF (2, "[dbg] send assembly [%s][%s][%d]\n", assembly->aname.name, domain->friendly_name, id);
2438 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2440 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2444 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2446 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2450 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2452 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2456 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2458 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2461 static void invoke_method (void);
2468 * save_thread_context:
2470 * Set CTX as the current threads context which is used for computing stack traces.
2471 * This function is signal-safe.
2474 save_thread_context (MonoContext *ctx)
2476 DebuggerTlsData *tls;
2478 tls = mono_native_tls_get_value (debugger_tls_id);
2482 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2484 mono_thread_state_init_from_current (&tls->context);
2487 /* Number of threads suspended */
2489 * If this is equal to the size of thread_to_tls, the runtime is considered
2492 static gint32 threads_suspend_count;
2494 static mono_mutex_t suspend_mutex;
2496 /* Cond variable used to wait for suspend_count becoming 0 */
2497 static mono_cond_t suspend_cond;
2499 /* Semaphore used to wait for a thread becoming suspended */
2500 static MonoSemType suspend_sem;
2505 mono_mutex_init (&suspend_mutex);
2506 mono_cond_init (&suspend_cond, NULL);
2507 MONO_SEM_INIT (&suspend_sem, 0);
2512 StackFrameInfo last_frame;
2513 gboolean last_frame_set;
2516 } GetLastFrameUserData;
2519 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2521 GetLastFrameUserData *data = user_data;
2523 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
2526 if (!data->last_frame_set) {
2527 /* Store the last frame */
2528 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2529 data->last_frame_set = TRUE;
2532 /* Store the context/lmf for the frame above the last frame */
2533 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2534 data->lmf = info->lmf;
2542 * Process interruption of a thread. This should be signal safe.
2545 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, MonoJitInfo *ji)
2549 MonoNativeThreadId tid;
2553 ip = MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx);
2554 tid = mono_thread_info_get_tid (info);
2556 // FIXME: Races when the thread leaves managed code before hitting a single step
2560 /* Running managed code, will be suspended by the single step code */
2561 DEBUG_PRINTF (1, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip);
2564 * Running native code, will be suspended when it returns to/enters
2565 * managed code. Treat it as already suspended.
2566 * This might interrupt the code in process_single_step_inner (), we use the
2567 * tls->suspending flag to avoid races when that happens.
2569 if (!tls->suspended && !tls->suspending) {
2571 GetLastFrameUserData data;
2573 // FIXME: printf is not signal safe, but this is only used during
2574 // debugger debugging
2576 DEBUG_PRINTF (1, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip);
2577 //save_thread_context (&ctx);
2580 /* Already terminated */
2584 * We are in a difficult position: we want to be able to provide stack
2585 * traces for this thread, but we can't use the current ctx+lmf, since
2586 * the thread is still running, so it might return to managed code,
2587 * making these invalid.
2588 * So we start a stack walk and save the first frame, along with the
2589 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2590 * suspended when it returns to managed code, so the parent's ctx should
2593 data.last_frame_set = FALSE;
2594 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, mono_thread_info_get_suspend_state (info), MONO_UNWIND_SIGNAL_SAFE, &data);
2595 if (data.last_frame_set) {
2596 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2597 res = mono_thread_state_init_from_monoctx (&tls->async_state, &ctx);
2599 mono_thread_state_init_from_monoctx (&tls->context, &ctx);
2602 memcpy (&tls->async_state.ctx, &data.ctx, sizeof (MonoContext));
2603 tls->async_state.unwind_data [MONO_UNWIND_DATA_LMF] = data.lmf;
2604 tls->async_state.unwind_data [MONO_UNWIND_DATA_JIT_TLS] = ((MonoThreadInfo*)tls->thread->thread_info)->jit_data;
2606 tls->async_state.valid = FALSE;
2609 mono_memory_barrier ();
2611 tls->suspended = TRUE;
2612 MONO_SEM_POST (&suspend_sem);
2618 * reset_native_thread_suspend_state:
2620 * Reset the suspended flag and state on native threads
2623 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2625 DebuggerTlsData *tls = value;
2627 if (!tls->really_suspended && tls->suspended) {
2628 tls->suspended = FALSE;
2630 * The thread might still be running if it was executing native code, so the state won't be invalided by
2631 * suspend_current ().
2633 tls->context.valid = FALSE;
2634 tls->async_state.valid = FALSE;
2635 invalidate_frames (tls);
2640 DebuggerTlsData *tls;
2641 gboolean valid_info;
2644 static SuspendThreadResult
2645 debugger_interrupt_critical (MonoThreadInfo *info, gpointer user_data)
2647 InterruptData *data = user_data;
2650 data->valid_info = TRUE;
2651 ji = mono_jit_info_table_find (mono_thread_info_get_suspend_state (info)->unwind_data [MONO_UNWIND_DATA_DOMAIN], MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx));
2653 /* This is signal safe */
2654 thread_interrupt (data->tls, info, ji);
2655 return MonoResumeThread;
2661 * Notify a thread that it needs to suspend.
2664 notify_thread (gpointer key, gpointer value, gpointer user_data)
2666 MonoInternalThread *thread = key;
2667 DebuggerTlsData *tls = value;
2668 gsize tid = thread->tid;
2670 if (GetCurrentThreadId () == tid || tls->terminated)
2673 DEBUG_PRINTF (1, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid);
2675 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2676 InterruptData interrupt_data = { 0 };
2677 interrupt_data.tls = tls;
2679 mono_thread_info_safe_suspend_and_run ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE, debugger_interrupt_critical, &interrupt_data);
2680 if (!interrupt_data.valid_info) {
2681 DEBUG_PRINTF (1, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid);
2683 * Attached thread which died without detaching.
2685 tls->terminated = TRUE;
2690 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2692 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2696 if (mono_loader_lock_is_owned_by_self ()) {
2698 * Shortcut for the check in suspend_current (). This speeds up processing
2699 * when executing long running code inside the loader lock, i.e. assembly load
2705 if (debugger_thread_id == GetCurrentThreadId ())
2708 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2709 if (suspend_count - tls->resume_count > 0)
2710 tls->suspending = TRUE;
2712 DEBUG_PRINTF (1, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ());
2714 if (suspend_count - tls->resume_count == 0) {
2716 * We are executing a single threaded invoke but the single step for
2717 * suspending is still active.
2718 * FIXME: This slows down single threaded invokes.
2720 DEBUG_PRINTF (1, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ());
2724 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2726 /* Can't suspend in these methods */
2727 method = jinfo_get_method (ji);
2728 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2731 save_thread_context (ctx);
2739 * Increase the suspend count of the VM. While the suspend count is greater
2740 * than 0, runtime threads are suspended at certain points during execution.
2745 mono_loader_lock ();
2748 mono_mutex_lock (&suspend_mutex);
2749 MONO_FINISH_TRY_BLOCKING
2753 DEBUG_PRINTF (1, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ());
2755 if (suspend_count == 1) {
2756 // FIXME: Is it safe to call this inside the lock ?
2757 start_single_stepping ();
2758 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2761 mono_mutex_unlock (&suspend_mutex);
2763 if (suspend_count == 1)
2765 * Suspend creation of new threadpool threads, since they cannot run
2767 mono_thread_pool_suspend ();
2769 mono_loader_unlock ();
2775 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2783 g_assert (debugger_thread_id == GetCurrentThreadId ());
2785 mono_loader_lock ();
2788 mono_mutex_lock (&suspend_mutex);
2789 MONO_FINISH_TRY_BLOCKING
2791 g_assert (suspend_count > 0);
2794 DEBUG_PRINTF (1, "[%p] Resuming vm, suspend count=%d...\n", (gpointer)GetCurrentThreadId (), suspend_count);
2796 if (suspend_count == 0) {
2797 // FIXME: Is it safe to call this inside the lock ?
2798 stop_single_stepping ();
2799 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2802 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2803 err = mono_cond_broadcast (&suspend_cond);
2804 g_assert (err == 0);
2806 mono_mutex_unlock (&suspend_mutex);
2807 //g_assert (err == 0);
2809 if (suspend_count == 0)
2810 mono_thread_pool_resume ();
2812 mono_loader_unlock ();
2818 * Resume just one thread.
2821 resume_thread (MonoInternalThread *thread)
2824 DebuggerTlsData *tls;
2826 g_assert (debugger_thread_id == GetCurrentThreadId ());
2828 mono_loader_lock ();
2830 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2834 mono_mutex_lock (&suspend_mutex);
2835 MONO_FINISH_TRY_BLOCKING
2837 g_assert (suspend_count > 0);
2839 DEBUG_PRINTF (1, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid);
2841 tls->resume_count += suspend_count;
2844 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2845 * but only the one whose resume_count field is > 0 will be resumed.
2847 err = mono_cond_broadcast (&suspend_cond);
2848 g_assert (err == 0);
2850 mono_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 = mono_native_tls_get_value (debugger_tls_id);
2876 free_frames (tls->frames, tls->frame_count);
2877 tls->frame_count = 0;
2880 free_frames (tls->restore_frames, tls->restore_frame_count);
2881 tls->restore_frame_count = 0;
2882 tls->restore_frames = NULL;
2888 * Suspend the current thread until the runtime is resumed. If the thread has a
2889 * pending invoke, then the invoke is executed before this function returns.
2892 suspend_current (void)
2894 DebuggerTlsData *tls;
2897 g_assert (debugger_thread_id != GetCurrentThreadId ());
2899 if (mono_loader_lock_is_owned_by_self ()) {
2901 * If we own the loader mutex, can't suspend until we release it, since the
2902 * whole runtime can deadlock otherwise.
2907 tls = mono_native_tls_get_value (debugger_tls_id);
2911 mono_mutex_lock (&suspend_mutex);
2912 MONO_FINISH_TRY_BLOCKING
2914 tls->suspending = FALSE;
2915 tls->really_suspended = TRUE;
2917 if (!tls->suspended) {
2918 tls->suspended = TRUE;
2919 MONO_SEM_POST (&suspend_sem);
2922 DEBUG_PRINTF (1, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ());
2925 while (suspend_count - tls->resume_count > 0) {
2926 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
2927 g_assert (err == 0);
2929 MONO_FINISH_TRY_BLOCKING
2931 tls->suspended = FALSE;
2932 tls->really_suspended = FALSE;
2934 threads_suspend_count --;
2936 mono_mutex_unlock (&suspend_mutex);
2938 DEBUG_PRINTF (1, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ());
2940 if (tls->pending_invoke) {
2941 /* Save the original context */
2942 tls->pending_invoke->has_ctx = TRUE;
2943 tls->pending_invoke->ctx = tls->context.ctx;
2948 /* The frame info becomes invalid after a resume */
2949 tls->context.valid = FALSE;
2950 tls->async_state.valid = FALSE;
2951 invalidate_frames (tls);
2955 count_thread (gpointer key, gpointer value, gpointer user_data)
2957 DebuggerTlsData *tls = value;
2959 if (!tls->suspended && !tls->terminated)
2960 *(int*)user_data = *(int*)user_data + 1;
2964 count_threads_to_wait_for (void)
2968 mono_loader_lock ();
2969 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2970 mono_loader_unlock ();
2978 * Wait until the runtime is completely suspended.
2981 wait_for_suspend (void)
2983 int nthreads, nwait, err;
2984 gboolean waited = FALSE;
2986 // FIXME: Threads starting/stopping ?
2987 mono_loader_lock ();
2988 nthreads = mono_g_hash_table_size (thread_to_tls);
2989 mono_loader_unlock ();
2992 nwait = count_threads_to_wait_for ();
2994 DEBUG_PRINTF (1, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads);
2995 err = MONO_SEM_WAIT (&suspend_sem);
2996 g_assert (err == 0);
3004 DEBUG_PRINTF (1, "%d threads suspended.\n", nthreads);
3010 * Return whenever the runtime is suspended.
3015 return count_threads_to_wait_for () == 0;
3019 no_seq_points_found (MonoMethod *method)
3022 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3024 printf ("Unable to find seq points for method '%s'.\n", mono_method_full_name (method, TRUE));
3028 DebuggerTlsData *tls;
3030 } ComputeFramesUserData;
3033 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3035 ComputeFramesUserData *ud = user_data;
3037 MonoMethod *method, *actual_method, *api_method;
3041 if (info->type != FRAME_TYPE_MANAGED) {
3042 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3043 /* Mark the last frame as an invoke frame */
3045 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3051 method = jinfo_get_method (info->ji);
3053 method = info->method;
3054 actual_method = info->actual_method;
3055 api_method = method;
3060 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3063 if (info->il_offset == -1) {
3064 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3065 if (ud->frames == NULL) {
3066 if (mono_find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL, &sp))
3067 info->il_offset = sp.il_offset;
3069 if (info->il_offset == -1)
3070 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3073 DEBUG_PRINTF (1, "\tFrame: %s:%x(%x) %d\n", mono_method_full_name (method, TRUE), info->il_offset, info->native_offset, info->managed);
3075 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3076 if (!CHECK_PROTOCOL_VERSION (2, 17))
3077 /* Older clients can't handle this flag */
3079 api_method = mono_marshal_method_from_wrapper (method);
3082 actual_method = api_method;
3083 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3086 frame = g_new0 (StackFrame, 1);
3087 frame->method = method;
3088 frame->actual_method = actual_method;
3089 frame->api_method = api_method;
3090 frame->il_offset = info->il_offset;
3091 frame->native_offset = info->native_offset;
3092 frame->flags = flags;
3093 frame->ji = info->ji;
3094 if (info->reg_locations)
3095 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3098 frame->has_ctx = TRUE;
3100 frame->domain = info->domain;
3102 ud->frames = g_slist_append (ud->frames, frame);
3108 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3110 ComputeFramesUserData *ud = user_data;
3113 * 'tls->filter_ctx' is the location of the throw site.
3115 * mono_walk_stack() will never actually hit the throw site, but unwind
3116 * directly from the filter to the call site; we abort stack unwinding here
3117 * once this happens and resume from the throw site.
3120 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3123 return process_frame (info, ctx, user_data);
3127 * Return a malloc-ed list of StackFrame structures.
3130 compute_frame_info_from (MonoInternalThread *thread, DebuggerTlsData *tls, MonoThreadUnwindState *state, int *out_nframes)
3132 ComputeFramesUserData user_data;
3133 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3138 user_data.tls = tls;
3139 user_data.frames = NULL;
3141 mono_walk_stack_with_state (process_frame, state, opts, &user_data);
3143 nframes = g_slist_length (user_data.frames);
3144 res = g_new0 (StackFrame*, nframes);
3145 l = user_data.frames;
3146 for (i = 0; i < nframes; ++i) {
3150 *out_nframes = nframes;
3156 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3158 ComputeFramesUserData user_data;
3160 int i, findex, new_frame_count;
3161 StackFrame **new_frames, *f;
3162 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3164 // FIXME: Locking on tls
3165 if (tls->frames && tls->frames_up_to_date)
3168 DEBUG_PRINTF (1, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid);
3170 user_data.tls = tls;
3171 user_data.frames = NULL;
3172 if (tls->terminated) {
3173 tls->frame_count = 0;
3175 } if (!tls->really_suspended && tls->async_state.valid) {
3176 /* Have to use the state saved by the signal handler */
3177 process_frame (&tls->async_last_frame, NULL, &user_data);
3178 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3179 } else if (tls->filter_state.valid) {
3181 * We are inside an exception filter.
3183 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3185 if (tls->context.valid)
3186 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3188 * After that, we resume unwinding from the location where the exception has been thrown.
3190 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3191 } else if (tls->context.valid) {
3192 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3195 tls->frame_count = 0;
3199 new_frame_count = g_slist_length (user_data.frames);
3200 new_frames = g_new0 (StackFrame*, new_frame_count);
3202 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3206 * Reuse the id for already existing stack frames, so invokes don't invalidate
3207 * the still valid stack frames.
3209 for (i = 0; i < tls->frame_count; ++i) {
3210 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3211 f->id = tls->frames [i]->id;
3216 if (i >= tls->frame_count)
3217 f->id = InterlockedIncrement (&frame_id);
3219 new_frames [findex ++] = f;
3222 g_slist_free (user_data.frames);
3224 invalidate_frames (tls);
3226 tls->frames = new_frames;
3227 tls->frame_count = new_frame_count;
3228 tls->frames_up_to_date = TRUE;
3232 * GHFunc to emit an appdomain creation event
3233 * @param key Don't care
3234 * @param value A loaded appdomain
3235 * @param user_data Don't care
3238 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3240 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3241 g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
3245 * GHFunc to emit a thread start event
3246 * @param key A thread id
3247 * @param value A thread object
3248 * @param user_data Don't care
3251 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3253 if (GPOINTER_TO_INT (key) != debugger_thread_id)
3254 process_profiler_event (EVENT_KIND_THREAD_START, value);
3258 * GFunc to emit an assembly load event
3259 * @param value A loaded assembly
3260 * @param user_data Don't care
3263 emit_assembly_load (gpointer value, gpointer user_data)
3265 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3269 * GFunc to emit a type load event
3270 * @param value A loaded type
3271 * @param user_data Don't care
3274 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3276 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3280 strdup_tolower (char *s)
3285 for (p = s2; *p; ++p)
3291 * Same as g_path_get_basename () but handles windows paths as well,
3292 * which can occur in .mdb files created by pdb2mdb.
3295 dbg_path_get_basename (const char *filename)
3299 if (!filename || strchr (filename, '/') || !strchr (filename, '\\'))
3300 return g_path_get_basename (filename);
3304 /* No separator -> filename */
3305 r = strrchr (filename, '\\');
3307 return g_strdup (filename);
3309 /* Trailing slash, remove component */
3311 char *copy = g_strdup (filename);
3312 copy [r-filename] = 0;
3313 r = strrchr (copy, '\\');
3317 return g_strdup ("/");
3319 r = g_strdup (&r[1]);
3324 return g_strdup (&r[1]);
3328 init_jit_info_dbg_attrs (MonoJitInfo *ji)
3330 static MonoClass *hidden_klass, *step_through_klass, *non_user_klass;
3331 MonoCustomAttrInfo *ainfo;
3333 if (ji->dbg_attrs_inited)
3336 if (!hidden_klass) {
3337 hidden_klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3338 g_assert (hidden_klass);
3340 if (!step_through_klass) {
3341 step_through_klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3342 g_assert (step_through_klass);
3344 if (!non_user_klass) {
3345 non_user_klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute");
3346 g_assert (non_user_klass);
3349 ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji));
3351 if (mono_custom_attrs_has_attr (ainfo, hidden_klass))
3352 ji->dbg_hidden = TRUE;
3353 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3354 ji->dbg_step_through = TRUE;
3355 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3356 ji->dbg_non_user_code = TRUE;
3357 mono_custom_attrs_free (ainfo);
3360 ainfo = mono_custom_attrs_from_class (jinfo_get_method (ji)->klass);
3362 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3363 ji->dbg_step_through = TRUE;
3364 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3365 ji->dbg_non_user_code = TRUE;
3366 mono_custom_attrs_free (ainfo);
3369 mono_memory_barrier ();
3370 ji->dbg_attrs_inited = TRUE;
3378 * create_event_list:
3380 * Return a list of event request ids matching EVENT, starting from REQS, which
3381 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3383 * We return request ids, instead of requests, to simplify threading, since
3384 * requests could be deleted anytime when the loader lock is not held.
3385 * LOCKING: Assumes the loader lock is held.
3388 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3391 GSList *events = NULL;
3393 *suspend_policy = SUSPEND_POLICY_NONE;
3396 reqs = event_requests;
3401 for (i = 0; i < reqs->len; ++i) {
3402 EventRequest *req = g_ptr_array_index (reqs, i);
3403 if (req->event_kind == event) {
3404 gboolean filtered = FALSE;
3407 for (j = 0; j < req->nmodifiers; ++j) {
3408 Modifier *mod = &req->modifiers [j];
3410 if (mod->kind == MOD_KIND_COUNT) {
3412 if (mod->data.count > 0) {
3413 if (mod->data.count > 0) {
3415 if (mod->data.count == 0)
3419 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3420 if (mod->data.thread != mono_thread_internal_current ())
3422 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3423 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3425 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3427 if (ei->caught && !mod->caught)
3429 if (!ei->caught && !mod->uncaught)
3431 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3433 gboolean found = FALSE;
3434 MonoAssembly **assemblies = mod->data.assemblies;
3437 for (k = 0; assemblies [k]; ++k)
3438 if (assemblies [k] == jinfo_get_method (ji)->klass->image->assembly)
3443 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3444 gpointer iter = NULL;
3446 MonoDebugSourceInfo *sinfo;
3447 char *source_file, *s;
3448 gboolean found = FALSE;
3450 GPtrArray *source_file_list;
3452 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3453 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3456 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
3457 for (i = 0; i < source_file_list->len; ++i) {
3458 sinfo = g_ptr_array_index (source_file_list, i);
3460 * Do a case-insesitive match by converting the file name to
3463 s = strdup_tolower (sinfo->source_file);
3464 if (g_hash_table_lookup (mod->data.source_files, s))
3467 char *s2 = dbg_path_get_basename (sinfo->source_file);
3468 char *s3 = strdup_tolower (s2);
3470 if (g_hash_table_lookup (mod->data.source_files, s3))
3477 g_ptr_array_free (source_file_list, TRUE);
3482 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3485 s = mono_type_full_name (&ei->klass->byval_arg);
3486 if (!g_hash_table_lookup (mod->data.type_names, s))
3489 } else if (mod->kind == MOD_KIND_STEP) {
3490 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3491 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3492 !strcmp (jinfo_get_method (ji)->name, ".cctor") &&
3493 (jinfo_get_method (ji) != ((SingleStepReq*)req->info)->start_method))
3495 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3496 init_jit_info_dbg_attrs (ji);
3500 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3501 init_jit_info_dbg_attrs (ji);
3502 if (ji->dbg_step_through)
3505 if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3506 init_jit_info_dbg_attrs (ji);
3507 if (ji->dbg_non_user_code)
3514 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3515 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3520 /* Send a VM START/DEATH event by default */
3521 if (event == EVENT_KIND_VM_START)
3522 events = g_slist_append (events, GINT_TO_POINTER (0));
3523 if (event == EVENT_KIND_VM_DEATH)
3524 events = g_slist_append (events, GINT_TO_POINTER (0));
3529 static G_GNUC_UNUSED const char*
3530 event_to_string (EventKind event)
3533 case EVENT_KIND_VM_START: return "VM_START";
3534 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3535 case EVENT_KIND_THREAD_START: return "THREAD_START";
3536 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3537 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3538 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3539 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3540 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3541 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3542 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3543 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3544 case EVENT_KIND_STEP: return "STEP";
3545 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3546 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3547 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3548 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3549 case EVENT_KIND_USER_LOG: return "USER_LOG";
3551 g_assert_not_reached ();
3559 * Send an event to the client, suspending the vm if needed.
3560 * LOCKING: Since this can suspend the calling thread, no locks should be held
3562 * The EVENTS list is freed by this function.
3565 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3569 MonoDomain *domain = mono_domain_get ();
3570 MonoThread *thread = NULL;
3571 MonoObject *keepalive_obj = NULL;
3572 gboolean send_success = FALSE;
3577 DEBUG_PRINTF (2, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event));
3581 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3582 // FIXME: We miss those events
3583 DEBUG_PRINTF (2, "VM start event not sent yet: dropping %s\n", event_to_string (event));
3587 if (vm_death_event_sent) {
3588 DEBUG_PRINTF (2, "VM death event has been sent: dropping %s\n", event_to_string (event));
3592 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3593 DEBUG_PRINTF (2, "Mono runtime is shutting down: dropping %s\n", event_to_string (event));
3598 DEBUG_PRINTF (2, "Debugger client is not connected: dropping %s\n", event_to_string (event));
3602 if (event == EVENT_KIND_KEEPALIVE)
3603 suspend_policy = SUSPEND_POLICY_NONE;
3608 if (agent_config.defer) {
3609 /* Make sure the thread id is always set when doing deferred debugging */
3610 if (debugger_thread_id == GetCurrentThreadId ()) {
3611 /* Don't suspend on events from the debugger thread */
3612 suspend_policy = SUSPEND_POLICY_NONE;
3613 thread = mono_thread_get_main ();
3615 else thread = mono_thread_current ();
3617 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3618 // FIXME: Send these with a NULL thread, don't suspend the current thread
3623 nevents = g_slist_length (events);
3624 buffer_init (&buf, 128);
3625 buffer_add_byte (&buf, suspend_policy);
3626 buffer_add_int (&buf, nevents);
3628 for (l = events; l; l = l->next) {
3629 buffer_add_byte (&buf, event); // event kind
3630 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3635 thread = mono_thread_current ();
3637 if (event == EVENT_KIND_VM_START && arg != NULL)
3640 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3643 case EVENT_KIND_THREAD_START:
3644 case EVENT_KIND_THREAD_DEATH:
3646 case EVENT_KIND_APPDOMAIN_CREATE:
3647 case EVENT_KIND_APPDOMAIN_UNLOAD:
3648 buffer_add_domainid (&buf, arg);
3650 case EVENT_KIND_METHOD_ENTRY:
3651 case EVENT_KIND_METHOD_EXIT:
3652 buffer_add_methodid (&buf, domain, arg);
3654 case EVENT_KIND_ASSEMBLY_LOAD:
3655 buffer_add_assemblyid (&buf, domain, arg);
3657 case EVENT_KIND_ASSEMBLY_UNLOAD: {
3658 DebuggerTlsData *tls;
3660 /* The domain the assembly belonged to is not equal to the current domain */
3661 tls = mono_native_tls_get_value (debugger_tls_id);
3663 g_assert (tls->domain_unloading);
3665 buffer_add_assemblyid (&buf, tls->domain_unloading, arg);
3668 case EVENT_KIND_TYPE_LOAD:
3669 buffer_add_typeid (&buf, domain, arg);
3671 case EVENT_KIND_BREAKPOINT:
3672 case EVENT_KIND_STEP:
3673 buffer_add_methodid (&buf, domain, arg);
3674 buffer_add_long (&buf, il_offset);
3676 case EVENT_KIND_VM_START:
3677 buffer_add_domainid (&buf, mono_get_root_domain ());
3679 case EVENT_KIND_VM_DEATH:
3680 if (CHECK_PROTOCOL_VERSION (2, 27))
3681 buffer_add_int (&buf, mono_environment_exitcode_get ());
3683 case EVENT_KIND_EXCEPTION: {
3684 EventInfo *ei = arg;
3685 buffer_add_objid (&buf, ei->exc);
3687 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3688 * later after the suspension. (#12494).
3690 keepalive_obj = ei->exc;
3693 case EVENT_KIND_USER_BREAK:
3695 case EVENT_KIND_USER_LOG: {
3696 EventInfo *ei = arg;
3697 buffer_add_int (&buf, ei->level);
3698 buffer_add_string (&buf, ei->category ? ei->category : "");
3699 buffer_add_string (&buf, ei->message ? ei->message : "");
3702 case EVENT_KIND_KEEPALIVE:
3703 suspend_policy = SUSPEND_POLICY_NONE;
3706 g_assert_not_reached ();
3710 if (event == EVENT_KIND_VM_START) {
3711 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3712 if (!agent_config.defer)
3713 start_debugger_thread ();
3716 if (event == EVENT_KIND_VM_DEATH) {
3717 vm_death_event_sent = TRUE;
3718 suspend_policy = SUSPEND_POLICY_NONE;
3721 if (mono_runtime_is_shutting_down ())
3722 suspend_policy = SUSPEND_POLICY_NONE;
3724 if (suspend_policy != SUSPEND_POLICY_NONE) {
3726 * Save the thread context and start suspending before sending the packet,
3727 * since we could be receiving the resume request before send_packet ()
3730 save_thread_context (ctx);
3734 /* This will keep this object alive */
3735 get_objref (keepalive_obj);
3738 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3742 g_slist_free (events);
3745 if (!send_success) {
3746 DEBUG_PRINTF (2, "Sending command %s failed.\n", event_to_string (event));
3750 if (event == EVENT_KIND_VM_START) {
3751 vm_start_event_sent = TRUE;
3754 DEBUG_PRINTF (1, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer)GetCurrentThreadId (), nevents, event_to_string (event), ecount, suspend_policy);
3756 switch (suspend_policy) {
3757 case SUSPEND_POLICY_NONE:
3759 case SUSPEND_POLICY_ALL:
3762 case SUSPEND_POLICY_EVENT_THREAD:
3766 g_assert_not_reached ();
3771 process_profiler_event (EventKind event, gpointer arg)
3775 EventInfo ei, *ei_arg = NULL;
3777 if (event == EVENT_KIND_TYPE_LOAD) {
3782 mono_loader_lock ();
3783 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3784 mono_loader_unlock ();
3786 process_event (event, arg, 0, NULL, events, suspend_policy);
3790 runtime_initialized (MonoProfiler *prof)
3792 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3793 if (agent_config.defer)
3794 start_debugger_thread ();
3798 runtime_shutdown (MonoProfiler *prof)
3800 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3802 mono_debugger_agent_cleanup ();
3806 thread_startup (MonoProfiler *prof, uintptr_t tid)
3808 MonoInternalThread *thread = mono_thread_internal_current ();
3809 MonoInternalThread *old_thread;
3810 DebuggerTlsData *tls;
3812 if (tid == debugger_thread_id)
3815 g_assert (thread->tid == tid);
3817 mono_loader_lock ();
3818 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3819 mono_loader_unlock ();
3821 if (thread == old_thread) {
3823 * For some reason, thread_startup () might be called for the same thread
3824 * multiple times (attach ?).
3826 DEBUG_PRINTF (1, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid);
3830 * thread_end () might not be called for some threads, and the tid could
3833 DEBUG_PRINTF (1, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid);
3834 mono_loader_lock ();
3835 mono_g_hash_table_remove (thread_to_tls, old_thread);
3836 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3837 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3838 mono_loader_unlock ();
3842 tls = mono_native_tls_get_value (debugger_tls_id);
3844 // FIXME: Free this somewhere
3845 tls = g_new0 (DebuggerTlsData, 1);
3846 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3847 tls->thread = thread;
3848 mono_native_tls_set_value (debugger_tls_id, tls);
3850 DEBUG_PRINTF (1, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3852 mono_loader_lock ();
3853 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3854 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3855 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3856 mono_loader_unlock ();
3858 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3861 * suspend_vm () could have missed this thread, so wait for a resume.
3867 thread_end (MonoProfiler *prof, uintptr_t tid)
3869 MonoInternalThread *thread;
3870 DebuggerTlsData *tls = NULL;
3872 mono_loader_lock ();
3873 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3875 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3876 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3878 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3879 tls->terminated = TRUE;
3880 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3881 MONO_GC_UNREGISTER_ROOT (tls->thread);
3885 mono_loader_unlock ();
3887 /* We might be called for threads started before we registered the start callback */
3889 DEBUG_PRINTF (1, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3891 if (GetCurrentThreadId () == tid && !mono_native_tls_get_value (debugger_tls_id)) {
3893 * This can happen on darwin since we deregister threads using pthread dtors.
3894 * process_profiler_event () and the code it calls cannot handle a null TLS value.
3899 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3904 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3906 mono_loader_lock ();
3907 g_hash_table_insert (domains, domain, domain);
3908 mono_loader_unlock ();
3910 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3914 appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain)
3916 DebuggerTlsData *tls;
3918 /* This might be called during shutdown on the debugger thread from the CMD_VM_EXIT code */
3919 if (is_debugger_thread ())
3923 * Remember the currently unloading appdomain as it is needed to generate
3924 * proper ids for unloading assemblies.
3926 tls = mono_native_tls_get_value (debugger_tls_id);
3928 tls->domain_unloading = domain;
3932 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3934 DebuggerTlsData *tls;
3936 if (is_debugger_thread ())
3939 tls = mono_native_tls_get_value (debugger_tls_id);
3941 tls->domain_unloading = NULL;
3943 clear_breakpoints_for_domain (domain);
3945 mono_loader_lock ();
3946 /* Invalidate each thread's frame stack */
3947 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3948 mono_loader_unlock ();
3950 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3954 * invalidate_each_thread:
3956 * A GHFunc to invalidate frames.
3957 * value must be a DebuggerTlsData*
3960 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3962 invalidate_frames (value);
3966 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3968 /* Sent later in jit_end () */
3970 g_ptr_array_add (pending_assembly_loads, assembly);
3975 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3977 if (is_debugger_thread ())
3980 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3982 clear_event_requests_for_assembly (assembly);
3983 clear_types_for_assembly (assembly);
3987 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3989 #if defined(HOST_WIN32) && !defined(__GNUC__)
3990 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3992 gpointer stackptr = __builtin_frame_address (1);
3994 MonoInternalThread *thread = mono_thread_internal_current ();
3995 DebuggerTlsData *tls;
3997 mono_loader_lock ();
3999 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4000 /* Could be the debugger thread with assembly/type load hooks */
4002 tls->invoke_addr = stackptr;
4004 mono_loader_unlock ();
4008 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
4011 #if defined(HOST_WIN32) && !defined(__GNUC__)
4012 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
4014 gpointer stackptr = __builtin_frame_address (1);
4017 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
4021 * We need to stop single stepping when exiting a runtime invoke, since if it is
4022 * a step out, it may return to native code, and thus never end.
4024 mono_loader_lock ();
4025 ss_invoke_addr = NULL;
4027 for (i = 0; i < event_requests->len; ++i) {
4028 EventRequest *req = g_ptr_array_index (event_requests, i);
4030 if (req->event_kind == EVENT_KIND_STEP) {
4031 ss_destroy (req->info);
4032 g_ptr_array_remove_index_fast (event_requests, i);
4037 mono_loader_unlock ();
4041 send_type_load (MonoClass *klass)
4043 gboolean type_load = FALSE;
4044 MonoDomain *domain = mono_domain_get ();
4045 AgentDomainInfo *info = NULL;
4047 mono_loader_lock ();
4048 mono_domain_lock (domain);
4050 info = get_agent_domain_info (domain);
4052 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
4054 g_hash_table_insert (info->loaded_classes, klass, klass);
4057 mono_domain_unlock (domain);
4058 mono_loader_unlock ();
4060 emit_type_load (klass, klass, NULL);
4064 * Emit load events for all types currently loaded in the domain.
4065 * Takes the loader and domain locks.
4066 * user_data is unused.
4069 send_types_for_domain (MonoDomain *domain, void *user_data)
4071 AgentDomainInfo *info = NULL;
4073 mono_loader_lock ();
4074 mono_domain_lock (domain);
4075 info = get_agent_domain_info (domain);
4077 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4078 mono_domain_unlock (domain);
4079 mono_loader_unlock ();
4083 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
4086 * We emit type load events when the first method of the type is JITted,
4087 * since the class load profiler callbacks might be called with the
4088 * loader lock held. They could also occur in the debugger thread.
4089 * Same for assembly load events.
4092 MonoAssembly *assembly = NULL;
4094 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4096 if (pending_assembly_loads->len > 0) {
4097 assembly = g_ptr_array_index (pending_assembly_loads, 0);
4098 g_ptr_array_remove_index (pending_assembly_loads, 0);
4103 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4109 send_type_load (method->klass);
4112 add_pending_breakpoints (method, jinfo);
4116 * BREAKPOINTS/SINGLE STEPPING
4120 * Contains information about an inserted breakpoint.
4123 long il_offset, native_offset;
4127 } BreakpointInstance;
4130 * Contains generic information about a breakpoint.
4134 * The method where the breakpoint is placed. Can be NULL in which case it
4135 * is inserted into every method. This is used to implement method entry/
4136 * exit events. Can be a generic method definition, in which case the
4137 * breakpoint is inserted into every instance.
4143 * A list of BreakpointInstance structures describing where the breakpoint
4144 * was inserted. There could be more than one because of
4145 * generics/appdomains/method entry/exit.
4147 GPtrArray *children;
4150 /* List of breakpoints */
4151 static GPtrArray *breakpoints;
4152 /* Maps breakpoint locations to the number of breakpoints at that location */
4153 static GHashTable *bp_locs;
4156 breakpoints_init (void)
4158 breakpoints = g_ptr_array_new ();
4159 bp_locs = g_hash_table_new (NULL, NULL);
4163 * insert_breakpoint:
4165 * Insert the breakpoint described by BP into the method described by
4169 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4172 BreakpointInstance *inst;
4173 SeqPointIterator it;
4174 gboolean it_has_sp = FALSE;
4177 mono_error_init (error);
4179 mono_seq_point_iterator_init (&it, seq_points);
4180 while (mono_seq_point_iterator_next (&it)) {
4181 if (it.seq_point.il_offset == bp->il_offset) {
4189 * The set of IL offsets with seq points doesn't completely match the
4190 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4192 mono_seq_point_iterator_init (&it, seq_points);
4193 while (mono_seq_point_iterator_next (&it)) {
4194 if (it.seq_point.il_offset != METHOD_ENTRY_IL_OFFSET &&
4195 it.seq_point.il_offset != METHOD_EXIT_IL_OFFSET &&
4196 it.seq_point.il_offset + 1 == bp->il_offset) {
4204 char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d", mono_method_full_name (jinfo_get_method (ji), TRUE), bp->il_offset);
4206 mono_seq_point_iterator_init (&it, seq_points);
4207 while (mono_seq_point_iterator_next (&it))
4208 DEBUG_PRINTF (1, "%d\n", it.seq_point.il_offset);
4211 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4212 g_warning ("%s", s);
4216 g_warning ("%s", s);
4222 inst = g_new0 (BreakpointInstance, 1);
4223 inst->il_offset = it.seq_point.il_offset;
4224 inst->native_offset = it.seq_point.native_offset;
4225 inst->ip = (guint8*)ji->code_start + it.seq_point.native_offset;
4227 inst->domain = domain;
4229 mono_loader_lock ();
4231 g_ptr_array_add (bp->children, inst);
4233 mono_loader_unlock ();
4236 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4237 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4240 if (it.seq_point.native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4241 DEBUG_PRINTF (1, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset);
4242 } else if (count == 0) {
4243 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4244 mono_arch_set_breakpoint (ji, inst->ip);
4250 DEBUG_PRINTF (1, "[dbg] Inserted breakpoint at %s:0x%x [%p](%d).\n", mono_method_full_name (jinfo_get_method (ji), TRUE), (int)it.seq_point.il_offset, inst->ip, count);
4254 remove_breakpoint (BreakpointInstance *inst)
4256 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4258 MonoJitInfo *ji = inst->ji;
4259 guint8 *ip = inst->ip;
4262 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4263 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4266 g_assert (count > 0);
4268 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4269 mono_arch_clear_breakpoint (ji, ip);
4270 DEBUG_PRINTF (1, "[dbg] Clear breakpoint at %s [%p].\n", mono_method_full_name (jinfo_get_method (ji), TRUE), ip);
4277 static inline gboolean
4278 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4284 if (method == bp->method)
4286 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4289 if (bp->method->is_inflated && method->is_inflated) {
4290 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4291 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4293 /* Open generic methods should match closed generic methods of the same class */
4294 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4295 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4296 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4298 /* FIXME: Handle !mvar */
4299 if (t1->type != MONO_TYPE_MVAR)
4310 * add_pending_breakpoints:
4312 * Insert pending breakpoints into the newly JITted method METHOD.
4315 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4318 MonoSeqPointInfo *seq_points;
4320 MonoMethod *jmethod;
4325 domain = mono_domain_get ();
4327 mono_loader_lock ();
4329 for (i = 0; i < breakpoints->len; ++i) {
4330 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4331 gboolean found = FALSE;
4333 if (!bp_matches_method (bp, method))
4336 for (j = 0; j < bp->children->len; ++j) {
4337 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4344 jmethod = jinfo_get_method (ji);
4345 mono_domain_lock (domain);
4346 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, jmethod);
4347 if (!seq_points && jmethod->is_inflated)
4348 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (jmethod));
4349 mono_domain_unlock (domain);
4351 /* Could be AOT code */
4353 g_assert (seq_points);
4355 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4359 mono_loader_unlock ();
4363 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4369 mono_error_init (error);
4371 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4373 /* Might be AOTed code */
4374 code = mono_aot_get_method (domain, method);
4376 ji = mono_jit_info_table_find (domain, code);
4381 insert_breakpoint (seq_points, domain, ji, bp, error);
4385 clear_breakpoint (MonoBreakpoint *bp);
4390 * Set a breakpoint at IL_OFFSET in METHOD.
4391 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4392 * METHOD can also be a generic method definition, in which case a breakpoint
4393 * is placed in all instances of the method.
4394 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4397 static MonoBreakpoint*
4398 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4401 GHashTableIter iter, iter2;
4404 MonoSeqPointInfo *seq_points;
4407 mono_error_init (error);
4410 // - suspend/resume the vm to prevent code patching problems
4411 // - multiple breakpoints on the same location
4412 // - dynamic methods
4415 bp = g_new0 (MonoBreakpoint, 1);
4416 bp->method = method;
4417 bp->il_offset = il_offset;
4419 bp->children = g_ptr_array_new ();
4421 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);
4423 mono_loader_lock ();
4425 g_hash_table_iter_init (&iter, domains);
4426 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4427 mono_domain_lock (domain);
4429 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4430 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4431 if (bp_matches_method (bp, m))
4432 set_bp_in_method (domain, m, seq_points, bp, error);
4435 mono_domain_unlock (domain);
4438 mono_loader_unlock ();
4440 mono_loader_lock ();
4441 g_ptr_array_add (breakpoints, bp);
4442 mono_loader_unlock ();
4444 if (error && !mono_error_ok (error)) {
4445 clear_breakpoint (bp);
4453 clear_breakpoint (MonoBreakpoint *bp)
4457 // FIXME: locking, races
4458 for (i = 0; i < bp->children->len; ++i) {
4459 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4461 remove_breakpoint (inst);
4466 mono_loader_lock ();
4467 g_ptr_array_remove (breakpoints, bp);
4468 mono_loader_unlock ();
4470 g_ptr_array_free (bp->children, TRUE);
4475 breakpoints_cleanup (void)
4479 mono_loader_lock ();
4481 while (i < event_requests->len) {
4482 EventRequest *req = g_ptr_array_index (event_requests, i);
4484 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4485 clear_breakpoint (req->info);
4486 g_ptr_array_remove_index_fast (event_requests, i);
4493 for (i = 0; i < breakpoints->len; ++i)
4494 g_free (g_ptr_array_index (breakpoints, i));
4496 g_ptr_array_free (breakpoints, TRUE);
4497 g_hash_table_destroy (bp_locs);
4502 mono_loader_unlock ();
4506 * clear_breakpoints_for_domain:
4508 * Clear breakpoint instances which reference DOMAIN.
4511 clear_breakpoints_for_domain (MonoDomain *domain)
4515 /* This could be called after shutdown */
4519 mono_loader_lock ();
4520 for (i = 0; i < breakpoints->len; ++i) {
4521 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4524 while (j < bp->children->len) {
4525 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4527 if (inst->domain == domain) {
4528 remove_breakpoint (inst);
4532 g_ptr_array_remove_index_fast (bp->children, j);
4538 mono_loader_unlock ();
4544 * Return FALSE if single stepping needs to continue.
4547 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp, DebuggerTlsData *tls, MonoContext *ctx)
4549 MonoDebugMethodInfo *minfo;
4550 MonoDebugSourceLocation *loc = NULL;
4551 gboolean hit = TRUE;
4554 if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK)) {
4556 * These seq points are inserted by the JIT after calls, step over needs to skip them.
4558 DEBUG_PRINTF (1, "[%p] Seq point at nonempty stack %x while stepping over, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset);
4562 if (req->depth == STEP_DEPTH_OVER && hit) {
4563 if (!tls->context.valid)
4564 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4565 compute_frame_info (tls->thread, tls);
4566 if (req->nframes && tls->frame_count && tls->frame_count > req->nframes) {
4567 /* Hit the breakpoint in a recursive call */
4568 DEBUG_PRINTF (1, "[%p] Breakpoint at lower frame while stepping over, continuing single stepping.\n", (gpointer)GetCurrentThreadId ());
4573 if (req->depth == STEP_DEPTH_INTO && req->size == STEP_SIZE_MIN && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) && ss_req->start_method){
4574 method = jinfo_get_method (ji);
4575 if (!tls->context.valid)
4576 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4577 compute_frame_info (tls->thread, tls);
4578 if (ss_req->start_method == method && req->nframes && tls->frame_count == req->nframes) {//Check also frame count(could be recursion)
4579 DEBUG_PRINTF (1, "[%p] Seq point at nonempty stack %x while stepping in, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset);
4584 if (req->size != STEP_SIZE_LINE)
4587 /* Have to check whenever a different source line was reached */
4588 method = jinfo_get_method (ji);
4589 minfo = mono_debug_lookup_method (method);
4592 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4595 DEBUG_PRINTF (1, "[%p] No line number info for il offset %x, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset);
4596 ss_req->last_method = method;
4598 } else if (loc && method == ss_req->last_method && loc->row == ss_req->last_line) {
4599 DEBUG_PRINTF (1, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer)GetCurrentThreadId (), loc->row);
4604 ss_req->last_method = method;
4605 ss_req->last_line = loc->row;
4606 mono_debug_free_source_location (loc);
4613 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4615 return bp->method && bp->method->klass->image->assembly == assembly;
4619 process_breakpoint_inner (DebuggerTlsData *tls, gboolean from_signal)
4623 int i, j, suspend_policy;
4624 guint32 native_offset;
4626 BreakpointInstance *inst;
4627 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4628 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4629 EventKind kind = EVENT_KIND_BREAKPOINT;
4630 MonoContext *ctx = &tls->restore_state.ctx;
4632 MonoSeqPointInfo *info;
4636 // FIXME: Speed this up
4638 ip = MONO_CONTEXT_GET_IP (ctx);
4639 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4641 method = jinfo_get_method (ji);
4643 /* Compute the native offset of the breakpoint from the ip */
4644 native_offset = ip - (guint8*)ji->code_start;
4647 * Skip the instruction causing the breakpoint signal.
4650 mono_arch_skip_breakpoint (ctx, ji);
4652 if (method->wrapper_type || tls->disable_breakpoints)
4655 bp_reqs = g_ptr_array_new ();
4656 ss_reqs = g_ptr_array_new ();
4657 ss_reqs_orig = g_ptr_array_new ();
4659 mono_loader_lock ();
4662 * The ip points to the instruction causing the breakpoint event, which is after
4663 * the offset recorded in the seq point map, so find the prev seq point before ip.
4665 found_sp = mono_find_prev_seq_point_for_native_offset (mono_domain_get (), method, native_offset, &info, &sp);
4668 no_seq_points_found (method);
4670 g_assert (found_sp);
4672 DEBUG_PRINTF (1, "[%p] Breakpoint hit, method=%s, ip=%p, offset=0x%x, sp il offset=0x%x.\n", (gpointer)GetCurrentThreadId (), method->name, ip, native_offset, sp.il_offset);
4675 for (i = 0; i < breakpoints->len; ++i) {
4676 bp = g_ptr_array_index (breakpoints, i);
4681 for (j = 0; j < bp->children->len; ++j) {
4682 inst = g_ptr_array_index (bp->children, j);
4683 if (inst->ji == ji && inst->il_offset == sp.il_offset && inst->native_offset == sp.native_offset) {
4684 if (bp->req->event_kind == EVENT_KIND_STEP) {
4685 g_ptr_array_add (ss_reqs_orig, bp->req);
4687 g_ptr_array_add (bp_reqs, bp->req);
4692 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4693 /* Maybe a method entry/exit event */
4694 if (sp.il_offset == METHOD_ENTRY_IL_OFFSET)
4695 kind = EVENT_KIND_METHOD_ENTRY;
4696 else if (sp.il_offset == METHOD_EXIT_IL_OFFSET)
4697 kind = EVENT_KIND_METHOD_EXIT;
4700 /* Process single step requests */
4701 for (i = 0; i < ss_reqs_orig->len; ++i) {
4702 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4703 SingleStepReq *ss_req = req->info;
4706 if (mono_thread_internal_current () != ss_req->thread)
4709 hit = ss_update (ss_req, ji, &sp, tls, ctx);
4711 g_ptr_array_add (ss_reqs, req);
4713 /* Start single stepping again from the current sequence point */
4714 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
4717 if (ss_reqs->len > 0)
4718 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4719 if (bp_reqs->len > 0)
4720 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4721 if (kind != EVENT_KIND_BREAKPOINT)
4722 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4724 mono_loader_unlock ();
4726 g_ptr_array_free (bp_reqs, TRUE);
4727 g_ptr_array_free (ss_reqs, TRUE);
4730 * FIXME: The first event will suspend, so the second will only be sent after the
4734 process_event (EVENT_KIND_STEP, method, 0, ctx, ss_events, suspend_policy);
4736 process_event (kind, method, 0, ctx, bp_events, suspend_policy);
4737 if (enter_leave_events)
4738 process_event (kind, method, 0, ctx, enter_leave_events, suspend_policy);
4741 /* Process a breakpoint/single step event after resuming from a signal handler */
4743 process_signal_event (void (*func) (DebuggerTlsData*, gboolean))
4745 DebuggerTlsData *tls;
4746 MonoThreadUnwindState orig_restore_state;
4749 tls = mono_native_tls_get_value (debugger_tls_id);
4750 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4751 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4752 mono_thread_state_init_from_monoctx (&tls->restore_state, &tls->handler_ctx);
4756 /* This is called when resuming from a signal handler, so it shouldn't return */
4757 memcpy (&ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4758 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4759 mono_restore_context (&ctx);
4760 g_assert_not_reached ();
4764 process_breakpoint (void)
4766 process_signal_event (process_breakpoint_inner);
4770 resume_from_signal_handler (void *sigctx, void *func)
4772 DebuggerTlsData *tls;
4775 /* Save the original context in TLS */
4776 // FIXME: This might not work on an altstack ?
4777 tls = mono_native_tls_get_value (debugger_tls_id);
4779 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer)GetCurrentThreadId ());
4782 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4783 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4784 // clob:c could be added to op_seq_point.
4786 mono_sigctx_to_monoctx (sigctx, &ctx);
4787 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4788 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4789 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4791 MONO_CONTEXT_SET_IP (&ctx, func);
4793 mono_monoctx_to_sigctx (&ctx, sigctx);
4795 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4796 mono_ppc_set_func_into_sigctx (sigctx, func);
4801 mono_debugger_agent_breakpoint_hit (void *sigctx)
4804 * We are called from a signal handler, and running code there causes all kinds of
4805 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4806 * So set up the signal context to return to the real breakpoint handler function.
4808 resume_from_signal_handler (sigctx, process_breakpoint);
4812 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4814 if (frame->managed) {
4815 *(MonoContext*)data = *ctx;
4824 * Called by System.Diagnostics.Debugger:Break ().
4827 mono_debugger_agent_user_break (void)
4829 if (agent_config.enabled) {
4834 /* Obtain a context */
4835 MONO_CONTEXT_SET_IP (&ctx, NULL);
4836 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4837 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4839 mono_loader_lock ();
4840 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4841 mono_loader_unlock ();
4843 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4850 ss_depth_to_string (StepDepth depth)
4853 case STEP_DEPTH_OVER:
4855 case STEP_DEPTH_OUT:
4857 case STEP_DEPTH_INTO:
4860 g_assert_not_reached ();
4866 process_single_step_inner (DebuggerTlsData *tls, gboolean from_signal)
4871 int il_offset, suspend_policy;
4874 MonoContext *ctx = &tls->restore_state.ctx;
4877 MonoSeqPointInfo *info;
4879 ip = MONO_CONTEXT_GET_IP (ctx);
4881 /* Skip the instruction causing the single step */
4883 mono_arch_skip_single_step (ctx);
4885 if (suspend_count > 0) {
4886 process_suspend (tls, ctx);
4891 // FIXME: A suspend race
4894 if (mono_thread_internal_current () != ss_req->thread)
4897 if (log_level > 0) {
4898 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4900 DEBUG_PRINTF (1, "[%p] Single step event (depth=%s) at %s (%p)[0x%x], sp %p, last sp %p\n", (gpointer)GetCurrentThreadId (), ss_depth_to_string (ss_req->depth), mono_method_full_name (jinfo_get_method (ji), TRUE), MONO_CONTEXT_GET_IP (ctx), (int)((guint8*)MONO_CONTEXT_GET_IP (ctx) - (guint8*)ji->code_start), MONO_CONTEXT_GET_SP (ctx), ss_req->last_sp);
4903 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4905 method = jinfo_get_method (ji);
4908 if (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4913 * Stopping in memset makes half-initialized vtypes visible.
4914 * Stopping in memcpy makes half-copied vtypes visible.
4916 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
4920 * The ip points to the instruction causing the single step event, which is before
4921 * the offset recorded in the seq point map, so find the next seq point after ip.
4923 if (!mono_find_next_seq_point_for_native_offset (domain, method, (guint8*)ip - (guint8*)ji->code_start, &info, &sp))
4926 il_offset = sp.il_offset;
4928 if (!ss_update (ss_req, ji, &sp, tls, ctx))
4931 /* Start single stepping again from the current sequence point */
4932 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
4934 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
4935 (method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4936 !strcmp (method->name, ".cctor"))
4939 // FIXME: Has to lock earlier
4941 reqs = g_ptr_array_new ();
4943 mono_loader_lock ();
4945 g_ptr_array_add (reqs, ss_req->req);
4947 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4949 g_ptr_array_free (reqs, TRUE);
4951 mono_loader_unlock ();
4953 process_event (EVENT_KIND_STEP, jinfo_get_method (ji), il_offset, ctx, events, suspend_policy);
4957 process_single_step (void)
4959 process_signal_event (process_single_step_inner);
4963 * mono_debugger_agent_single_step_event:
4965 * Called from a signal handler to handle a single step event.
4968 mono_debugger_agent_single_step_event (void *sigctx)
4970 /* Resume to process_single_step through the signal context */
4972 // FIXME: Since step out/over is implemented using step in, the step in case should
4973 // be as fast as possible. Move the relevant code from process_single_step_inner ()
4976 if (GetCurrentThreadId () == debugger_thread_id) {
4978 * This could happen despite our best effors when the runtime calls
4979 * assembly/type resolve hooks.
4980 * FIXME: Breakpoints too.
4984 mono_sigctx_to_monoctx (sigctx, &ctx);
4985 mono_arch_skip_single_step (&ctx);
4986 mono_monoctx_to_sigctx (&ctx, sigctx);
4990 resume_from_signal_handler (sigctx, process_single_step);
4994 debugger_agent_single_step_from_context (MonoContext *ctx)
4996 DebuggerTlsData *tls;
4997 MonoThreadUnwindState orig_restore_state;
4999 if (GetCurrentThreadId () == debugger_thread_id)
5002 tls = mono_native_tls_get_value (debugger_tls_id);
5005 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
5006 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5007 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5008 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5010 process_single_step_inner (tls, FALSE);
5012 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5013 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5017 debugger_agent_breakpoint_from_context (MonoContext *ctx)
5019 DebuggerTlsData *tls;
5020 MonoThreadUnwindState orig_restore_state;
5023 if (GetCurrentThreadId () == debugger_thread_id)
5026 orig_ip = MONO_CONTEXT_GET_IP (ctx);
5027 MONO_CONTEXT_SET_IP (ctx, orig_ip - 1);
5029 tls = mono_native_tls_get_value (debugger_tls_id);
5031 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5032 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5033 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5035 process_breakpoint_inner (tls, FALSE);
5037 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5038 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5039 if (MONO_CONTEXT_GET_IP (ctx) == orig_ip - 1)
5040 MONO_CONTEXT_SET_IP (ctx, orig_ip);
5044 * start_single_stepping:
5046 * Turn on single stepping. Can be called multiple times, for example,
5047 * by a single step event request + a suspend.
5050 start_single_stepping (void)
5052 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5053 int val = InterlockedIncrement (&ss_count);
5056 mono_arch_start_single_stepping ();
5058 if (ss_req != NULL && ss_invoke_addr == NULL) {
5059 DebuggerTlsData *tls;
5061 mono_loader_lock ();
5063 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
5064 ss_invoke_addr = tls->invoke_addr;
5066 mono_loader_unlock ();
5069 g_assert_not_reached ();
5074 stop_single_stepping (void)
5076 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5077 int val = InterlockedDecrement (&ss_count);
5080 mono_arch_stop_single_stepping ();
5082 ss_invoke_addr = NULL;
5084 g_assert_not_reached ();
5091 * Stop the single stepping operation given by SS_REQ.
5094 ss_stop (SingleStepReq *ss_req)
5099 for (l = ss_req->bps; l; l = l->next) {
5100 clear_breakpoint (l->data);
5102 g_slist_free (ss_req->bps);
5106 if (ss_req->global) {
5107 stop_single_stepping ();
5108 ss_req->global = FALSE;
5115 * Start the single stepping operation given by SS_REQ from the sequence point SP.
5116 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
5117 * belong to the same thread as CTX.
5118 * If FRAMES is not-null, use that instead of tls->frames for placing breakpoints etc.
5121 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint* sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls,
5122 gboolean step_to_catch, StackFrame **frames, int nframes)
5124 int i, j, frame_index;
5125 SeqPoint *next_sp, *parent_sp = NULL;
5126 SeqPoint local_sp, local_parent_sp;
5129 MonoSeqPointInfo *parent_info;
5130 MonoMethod *parent_sp_method = NULL;
5131 gboolean enable_global = FALSE;
5133 /* Stop the previous operation */
5137 * Implement single stepping using breakpoints if possible.
5139 if (step_to_catch) {
5140 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
5141 ss_req->bps = g_slist_append (ss_req->bps, bp);
5145 if (ctx && !frames) {
5146 /* Need parent frames */
5147 if (!tls->context.valid)
5148 mono_thread_state_init_from_monoctx (&tls->context, ctx);
5149 compute_frame_info (tls->thread, tls);
5150 frames = tls->frames;
5151 nframes = tls->frame_count;
5155 * Find the first sequence point in the current or in a previous frame which
5156 * is not the last in its method.
5158 if (ss_req->depth == STEP_DEPTH_OUT) {
5159 /* Ignore seq points in current method */
5160 while (frame_index < nframes) {
5161 StackFrame *frame = frames [frame_index];
5163 method = frame->method;
5164 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5165 sp = (found_sp)? &local_sp : NULL;
5167 if (sp && sp->next_len != 0)
5170 // There could be method calls before the next seq point in the caller when using nested calls
5171 //enable_global = TRUE;
5173 if (sp && sp->next_len == 0) {
5175 while (frame_index < nframes) {
5176 StackFrame *frame = frames [frame_index];
5178 method = frame->method;
5179 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5180 sp = (found_sp)? &local_sp : NULL;
5181 if (sp && sp->next_len != 0)
5187 /* Have to put a breakpoint into a parent frame since the seq points might not cover all control flow out of the method */
5188 while (frame_index < nframes) {
5189 StackFrame *frame = frames [frame_index];
5191 parent_sp_method = frame->method;
5192 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &parent_info, &local_parent_sp);
5193 parent_sp = found_sp ? &local_parent_sp : NULL;
5194 if (found_sp && parent_sp->next_len != 0)
5202 if (sp && sp->next_len > 0) {
5203 SeqPoint* next = g_new(SeqPoint, sp->next_len);
5205 mono_seq_point_init_next (info, *sp, next);
5206 for (i = 0; i < sp->next_len; i++) {
5209 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
5210 ss_req->bps = g_slist_append (ss_req->bps, bp);
5216 SeqPoint* next = g_new(SeqPoint, parent_sp->next_len);
5218 mono_seq_point_init_next (parent_info, *parent_sp, next);
5219 for (i = 0; i < parent_sp->next_len; i++) {
5222 bp = set_breakpoint (parent_sp_method, next_sp->il_offset, ss_req->req, NULL);
5223 ss_req->bps = g_slist_append (ss_req->bps, bp);
5228 if (ss_req->nframes == 0)
5229 ss_req->nframes = nframes;
5231 if ((ss_req->depth == STEP_DEPTH_OVER) && (!sp && !parent_sp)) {
5232 DEBUG_PRINTF (1, "[dbg] No parent frame for step over, transition to step into.\n");
5234 * This is needed since if we leave managed code, and later return to it, step over
5235 * is not going to stop.
5236 * This approach is a bit ugly, since we change the step depth, but it only affects
5237 * clients who reuse the same step request, and only in this special case.
5239 ss_req->depth = STEP_DEPTH_INTO;
5242 if (ss_req->depth == STEP_DEPTH_OVER) {
5243 /* Need to stop in catch clauses as well */
5244 for (i = 0; i < nframes; ++i) {
5245 StackFrame *frame = frames [i];
5248 MonoJitInfo *jinfo = frame->ji;
5249 for (j = 0; j < jinfo->num_clauses; ++j) {
5250 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5252 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);
5253 sp = (found_sp)? &local_sp : NULL;
5255 bp = set_breakpoint (frame->method, sp->il_offset, ss_req->req, NULL);
5256 ss_req->bps = g_slist_append (ss_req->bps, bp);
5263 if (ss_req->depth == STEP_DEPTH_INTO) {
5264 /* Enable global stepping so we stop at method entry too */
5265 enable_global = TRUE;
5269 * The ctx/frame info computed above will become invalid when we continue.
5271 tls->context.valid = FALSE;
5272 tls->async_state.valid = FALSE;
5273 invalidate_frames (tls);
5276 if (enable_global) {
5277 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5278 ss_req->global = TRUE;
5279 start_single_stepping ();
5280 } else if (!ss_req->bps) {
5281 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5282 ss_req->global = TRUE;
5283 start_single_stepping ();
5285 ss_req->global = FALSE;
5290 * Start single stepping of thread THREAD
5293 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req)
5295 DebuggerTlsData *tls;
5296 MonoSeqPointInfo *info = NULL;
5297 SeqPoint *sp = NULL;
5300 MonoMethod *method = NULL;
5301 MonoDebugMethodInfo *minfo;
5302 gboolean step_to_catch = FALSE;
5303 gboolean set_ip = FALSE;
5304 StackFrame **frames = NULL;
5307 if (suspend_count == 0)
5308 return ERR_NOT_SUSPENDED;
5310 wait_for_suspend ();
5312 // FIXME: Multiple requests
5314 DEBUG_PRINTF (0, "Received a single step request while the previous one was still active.\n");
5315 return ERR_NOT_IMPLEMENTED;
5318 DEBUG_PRINTF (1, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth));
5320 ss_req = g_new0 (SingleStepReq, 1);
5322 ss_req->thread = thread;
5323 ss_req->size = size;
5324 ss_req->depth = depth;
5325 ss_req->filter = filter;
5328 mono_loader_lock ();
5329 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5330 mono_loader_unlock ();
5332 g_assert (tls->context.valid);
5334 if (tls->restore_state.valid && MONO_CONTEXT_GET_IP (&tls->context.ctx) != MONO_CONTEXT_GET_IP (&tls->restore_state.ctx)) {
5336 * Need to start single stepping from restore_state and not from the current state
5339 frames = compute_frame_info_from (thread, tls, &tls->restore_state, &nframes);
5342 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5344 if (tls->catch_state.valid) {
5346 StackFrameInfo frame;
5347 MonoContext new_ctx;
5348 MonoLMF *lmf = NULL;
5351 * We are stopped at a throw site. Stepping should go to the catch site.
5354 /* Find the the jit info for the catch context */
5355 res = mono_find_jit_info_ext (tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], ((MonoThreadInfo*)thread->thread_info)->jit_data, NULL, &tls->catch_state.ctx, &new_ctx, NULL, &lmf, NULL, &frame);
5357 g_assert (frame.type == FRAME_TYPE_MANAGED);
5360 * Find the seq point corresponding to the landing site ip, which is the first seq
5363 found_sp = mono_find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info, &local_sp);
5364 sp = (found_sp)? &local_sp : NULL;
5366 no_seq_points_found (frame.method);
5369 method = frame.method;
5371 step_to_catch = TRUE;
5372 /* This make sure the seq point is not skipped by process_single_step () */
5373 ss_req->last_sp = NULL;
5376 if (!step_to_catch) {
5377 StackFrame *frame = NULL;
5380 if (frames && nframes)
5383 compute_frame_info (thread, tls);
5385 if (tls->frame_count)
5386 frame = tls->frames [0];
5389 if (ss_req->size == STEP_SIZE_LINE) {
5391 ss_req->last_method = frame->method;
5392 ss_req->last_line = -1;
5394 minfo = mono_debug_lookup_method (frame->method);
5395 if (minfo && frame->il_offset != -1) {
5396 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
5399 ss_req->last_line = loc->row;
5407 if (!method && frame->il_offset != -1) {
5408 /* FIXME: Sort the table and use a binary search */
5409 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5410 sp = (found_sp)? &local_sp : NULL;
5412 no_seq_points_found (frame->method);
5414 method = frame->method;
5419 ss_req->start_method = method;
5421 ss_start (ss_req, method, sp, info, set_ip ? &tls->restore_state.ctx : &tls->context.ctx, tls, step_to_catch, frames, nframes);
5424 free_frames (frames, nframes);
5430 ss_destroy (SingleStepReq *req)
5433 g_assert (ss_req == req);
5442 ss_clear_for_assembly (SingleStepReq *req, MonoAssembly *assembly)
5445 gboolean found = TRUE;
5449 for (l = ss_req->bps; l; l = l->next) {
5450 if (breakpoint_matches_assembly (l->data, assembly)) {
5451 clear_breakpoint (l->data);
5452 ss_req->bps = g_slist_delete_link (ss_req->bps, l);
5461 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5464 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5470 if (!agent_config.enabled)
5473 mono_loader_lock ();
5474 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5475 mono_loader_unlock ();
5478 ei.category = category ? mono_string_to_utf8 (category) : NULL;
5479 ei.message = message ? mono_string_to_utf8 (message) : NULL;
5481 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5483 g_free (ei.category);
5484 g_free (ei.message);
5488 mono_debugger_agent_debug_log_is_enabled (void)
5490 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5491 return agent_config.enabled;
5494 #if defined(PLATFORM_ANDROID) || defined(TARGET_ANDROID)
5496 mono_debugger_agent_unhandled_exception (MonoException *exc)
5505 memset (&ei, 0, sizeof (EventInfo));
5506 ei.exc = (MonoObject*)exc;
5508 mono_loader_lock ();
5509 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5510 mono_loader_unlock ();
5512 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5517 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5518 MonoContext *catch_ctx)
5520 int i, j, suspend_policy;
5522 MonoJitInfo *ji, *catch_ji;
5524 DebuggerTlsData *tls = NULL;
5526 if (thread_to_tls != NULL) {
5527 MonoInternalThread *thread = mono_thread_internal_current ();
5529 mono_loader_lock ();
5530 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5531 mono_loader_unlock ();
5533 if (tls && tls->abort_requested)
5535 if (tls && tls->disable_breakpoints)
5539 memset (&ei, 0, sizeof (EventInfo));
5541 /* Just-In-Time debugging */
5543 if (agent_config.onuncaught && !inited) {
5544 finish_agent_init (FALSE);
5547 * Send an unsolicited EXCEPTION event with a dummy request id.
5549 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5550 ei.exc = (MonoObject*)exc;
5551 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5554 } else if (agent_config.onthrow && !inited) {
5556 gboolean found = FALSE;
5558 for (l = agent_config.onthrow; l; l = l->next) {
5559 char *ex_type = l->data;
5560 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5562 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5569 finish_agent_init (FALSE);
5572 * Send an unsolicited EXCEPTION event with a dummy request id.
5574 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5575 ei.exc = (MonoObject*)exc;
5576 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5584 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5586 catch_ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5590 ei.exc = (MonoObject*)exc;
5591 ei.caught = catch_ctx != NULL;
5593 mono_loader_lock ();
5595 /* Treat exceptions which are caught in non-user code as unhandled */
5596 for (i = 0; i < event_requests->len; ++i) {
5597 EventRequest *req = g_ptr_array_index (event_requests, i);
5598 if (req->event_kind != EVENT_KIND_EXCEPTION)
5601 for (j = 0; j < req->nmodifiers; ++j) {
5602 Modifier *mod = &req->modifiers [j];
5604 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5606 gboolean found = FALSE;
5607 MonoAssembly **assemblies = mod->data.assemblies;
5610 for (k = 0; assemblies [k]; ++k)
5611 if (assemblies [k] == jinfo_get_method (catch_ji)->klass->image->assembly)
5620 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5621 mono_loader_unlock ();
5623 if (tls && ei.caught && catch_ctx) {
5624 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5625 tls->catch_state.ctx = *catch_ctx;
5626 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5627 tls->catch_state.valid = TRUE;
5630 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5633 tls->catch_state.valid = FALSE;
5637 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5639 DebuggerTlsData *tls;
5644 tls = mono_native_tls_get_value (debugger_tls_id);
5649 * We're about to invoke an exception filter during the first pass of exception handling.
5651 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5652 * 'orig_ctx' is the context where the exception has been thrown.
5655 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5657 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5658 * the call site (line 37) and then continue to Main(), but it would never
5659 * include the throw site (line 32).
5661 * Since exception filters are invoked during the first pass of exception handling,
5662 * the stack frames of the throw site are still intact, so we should include them
5665 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5667 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5668 * but report the location of the 'throw' to the user.
5672 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5676 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5678 DebuggerTlsData *tls;
5683 tls = mono_native_tls_get_value (debugger_tls_id);
5687 tls->filter_state.valid = FALSE;
5691 * buffer_add_value_full:
5693 * Add the encoding of the value at ADDR described by T to the buffer.
5694 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5698 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5699 gboolean as_vtype, GHashTable *parent_vtypes)
5702 gboolean boxed_vtype = FALSE;
5705 if (!(*(void**)addr)) {
5706 /* This can happen with compiler generated locals */
5707 //printf ("%s\n", mono_type_full_name (t));
5708 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5711 g_assert (*(void**)addr);
5712 addr = *(void**)addr;
5717 case MONO_TYPE_BOOLEAN:
5720 case MONO_TYPE_CHAR:
5740 case MONO_TYPE_VOID:
5741 buffer_add_byte (buf, t->type);
5743 case MONO_TYPE_BOOLEAN:
5746 buffer_add_byte (buf, t->type);
5747 buffer_add_int (buf, *(gint8*)addr);
5749 case MONO_TYPE_CHAR:
5752 buffer_add_byte (buf, t->type);
5753 buffer_add_int (buf, *(gint16*)addr);
5758 buffer_add_byte (buf, t->type);
5759 buffer_add_int (buf, *(gint32*)addr);
5764 buffer_add_byte (buf, t->type);
5765 buffer_add_long (buf, *(gint64*)addr);
5769 /* Treat it as a vtype */
5771 case MONO_TYPE_PTR: {
5772 gssize val = *(gssize*)addr;
5774 buffer_add_byte (buf, t->type);
5775 buffer_add_long (buf, val);
5779 case MONO_TYPE_STRING:
5780 case MONO_TYPE_SZARRAY:
5781 case MONO_TYPE_OBJECT:
5782 case MONO_TYPE_CLASS:
5783 case MONO_TYPE_ARRAY:
5784 obj = *(MonoObject**)addr;
5787 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5789 if (obj->vtable->klass->valuetype) {
5790 t = &obj->vtable->klass->byval_arg;
5791 addr = mono_object_unbox (obj);
5794 } else if (obj->vtable->klass->rank) {
5795 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5796 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5797 buffer_add_byte (buf, MONO_TYPE_CLASS);
5799 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5801 buffer_add_objid (buf, obj);
5805 case MONO_TYPE_VALUETYPE:
5806 case MONO_TYPE_TYPEDBYREF: {
5810 MonoClass *klass = mono_class_from_mono_type (t);
5815 * Handle boxed vtypes recursively referencing themselves using fields.
5818 parent_vtypes = g_hash_table_new (NULL, NULL);
5819 vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
5821 if (CHECK_PROTOCOL_VERSION (2, 33)) {
5822 buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
5823 buffer_add_int (buf, vtype_index - 1);
5825 /* The client can't handle PARENT_VTYPE */
5826 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5830 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
5834 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5835 buffer_add_byte (buf, klass->enumtype);
5836 buffer_add_typeid (buf, domain, klass);
5840 while ((f = mono_class_get_fields (klass, &iter))) {
5841 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5843 if (mono_field_is_deleted (f))
5847 buffer_add_int (buf, nfields);
5850 while ((f = mono_class_get_fields (klass, &iter))) {
5851 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5853 if (mono_field_is_deleted (f))
5855 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE, parent_vtypes);
5859 g_hash_table_remove (parent_vtypes, addr);
5860 if (g_hash_table_size (parent_vtypes) == 0) {
5861 g_hash_table_destroy (parent_vtypes);
5862 parent_vtypes = NULL;
5867 case MONO_TYPE_GENERICINST:
5868 if (mono_type_generic_inst_is_valuetype (t)) {
5880 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5882 buffer_add_value_full (buf, t, addr, domain, FALSE, NULL);
5886 obj_is_of_type (MonoObject *obj, MonoType *t)
5888 MonoClass *klass = obj->vtable->klass;
5889 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5890 if (mono_class_is_transparent_proxy (klass)) {
5891 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5892 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5902 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5905 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5911 gpointer iter = NULL;
5915 is_enum = decode_byte (buf, &buf, limit);
5916 /* Enums are sent as a normal vtype */
5918 return ERR_NOT_IMPLEMENTED;
5919 klass = decode_typeid (buf, &buf, limit, &d, &err);
5923 if (t && klass != mono_class_from_mono_type (t)) {
5924 char *name = mono_type_full_name (t);
5925 char *name2 = mono_type_full_name (&klass->byval_arg);
5926 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got %s.\n", (gpointer)GetCurrentThreadId (), name, name2);
5929 return ERR_INVALID_ARGUMENT;
5932 nfields = decode_int (buf, &buf, limit);
5933 while ((f = mono_class_get_fields (klass, &iter))) {
5934 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5936 if (mono_field_is_deleted (f))
5938 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5943 g_assert (nfields == 0);
5951 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5955 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5956 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5957 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5958 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5959 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
5960 char *name = mono_type_full_name (t);
5961 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type);
5963 return ERR_INVALID_ARGUMENT;
5967 case MONO_TYPE_BOOLEAN:
5968 *(guint8*)addr = decode_int (buf, &buf, limit);
5970 case MONO_TYPE_CHAR:
5971 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5974 *(gint8*)addr = decode_int (buf, &buf, limit);
5977 *(guint8*)addr = decode_int (buf, &buf, limit);
5980 *(gint16*)addr = decode_int (buf, &buf, limit);
5983 *(guint16*)addr = decode_int (buf, &buf, limit);
5986 *(gint32*)addr = decode_int (buf, &buf, limit);
5989 *(guint32*)addr = decode_int (buf, &buf, limit);
5992 *(gint64*)addr = decode_long (buf, &buf, limit);
5995 *(guint64*)addr = decode_long (buf, &buf, limit);
5998 *(guint32*)addr = decode_int (buf, &buf, limit);
6001 *(guint64*)addr = decode_long (buf, &buf, limit);
6004 /* We send these as I8, so we get them back as such */
6005 g_assert (type == MONO_TYPE_I8);
6006 *(gssize*)addr = decode_long (buf, &buf, limit);
6008 case MONO_TYPE_GENERICINST:
6009 if (MONO_TYPE_ISSTRUCT (t)) {
6010 /* The client sends these as a valuetype */
6018 /* We send these as vtypes, so we get them back as such */
6019 g_assert (type == MONO_TYPE_VALUETYPE);
6022 case MONO_TYPE_VALUETYPE:
6023 err = decode_vtype (t, domain, addr,buf, &buf, limit);
6029 if (MONO_TYPE_IS_REFERENCE (t)) {
6030 if (type == MONO_TYPE_OBJECT) {
6031 int objid = decode_objid (buf, &buf, limit);
6035 err = get_object (objid, (MonoObject**)&obj);
6040 if (!obj_is_of_type (obj, t)) {
6041 DEBUG_PRINTF (1, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6042 return ERR_INVALID_ARGUMENT;
6045 if (obj && obj->vtable->domain != domain)
6046 return ERR_INVALID_ARGUMENT;
6048 mono_gc_wbarrier_generic_store (addr, obj);
6049 } else if (type == VALUE_TYPE_ID_NULL) {
6050 *(MonoObject**)addr = NULL;
6051 } else if (type == MONO_TYPE_VALUETYPE) {
6059 /* This can happen when round-tripping boxed vtypes */
6061 * Obtain vtype class.
6062 * Same as the beginning of the handle_vtype case above.
6065 is_enum = decode_byte (buf, &buf, limit);
6067 return ERR_NOT_IMPLEMENTED;
6068 klass = decode_typeid (buf, &buf, limit, &d, &err);
6072 /* Decode the vtype into a temporary buffer, then box it. */
6073 vtype_buf_size = mono_class_value_size (klass, NULL);
6074 vtype_buf = g_malloc0 (vtype_buf_size);
6075 g_assert (vtype_buf);
6078 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
6083 *(MonoObject**)addr = mono_value_box (d, klass, vtype_buf);
6086 char *name = mono_type_full_name (t);
6087 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type);
6089 return ERR_INVALID_ARGUMENT;
6103 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6106 int type = decode_byte (buf, &buf, limit);
6108 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
6109 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
6110 guint8 *nullable_buf;
6113 * First try decoding it as a Nullable`1
6115 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6120 * Then try decoding as a primitive value or null.
6122 if (targ->type == type) {
6123 nullable_buf = g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
6124 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
6126 g_free (nullable_buf);
6129 mono_nullable_init (addr, mono_value_box (domain, mono_class_from_mono_type (targ), nullable_buf), mono_class_from_mono_type (t));
6130 g_free (nullable_buf);
6133 } else if (type == VALUE_TYPE_ID_NULL) {
6134 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
6140 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6144 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
6148 guint8 *addr, *gaddr;
6151 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6152 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6155 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
6156 reg_val = mono_arch_context_get_int_reg (ctx, reg);
6158 buffer_add_value_full (buf, t, ®_val, domain, as_vtype, NULL);
6160 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6161 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6162 addr += (gint32)var->offset;
6164 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6166 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6168 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6171 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6172 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
6173 /* Same as regoffset, but with an indirection */
6174 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6175 addr += (gint32)var->offset;
6177 gaddr = *(gpointer*)addr;
6179 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL);
6181 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
6182 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
6183 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
6184 MonoGSharedVtMethodRuntimeInfo *info;
6190 g_assert (info_var);
6191 g_assert (locals_var);
6193 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6194 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6195 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6196 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6197 addr += (gint32)info_var->offset;
6198 info = *(gpointer*)addr;
6199 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6200 info = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6202 g_assert_not_reached ();
6206 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6207 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6208 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6209 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6210 addr += (gint32)locals_var->offset;
6211 locals = *(gpointer*)addr;
6212 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6213 locals = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6215 g_assert_not_reached ();
6219 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6221 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6226 g_assert_not_reached ();
6231 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
6235 guint8 *addr, *gaddr;
6237 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6238 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6240 if (MONO_TYPE_IS_REFERENCE (t))
6241 size = sizeof (gpointer);
6243 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6246 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6247 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6249 gboolean is_signed = FALSE;
6252 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6255 // FIXME: Write barriers
6256 mono_gc_memmove_atomic (addr, val, size);
6261 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6266 v = is_signed ? *(gint8*)val : *(guint8*)val;
6269 v = is_signed ? *(gint16*)val : *(guint16*)val;
6272 v = is_signed ? *(gint32*)val : *(guint32*)val;
6275 v = is_signed ? *(gint64*)val : *(guint64*)val;
6278 g_assert_not_reached ();
6281 /* Set value on the stack or in the return ctx */
6282 if (reg_locations [reg]) {
6283 /* Saved on the stack */
6284 DEBUG_PRINTF (1, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v);
6285 *(reg_locations [reg]) = v;
6288 DEBUG_PRINTF (1, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v);
6289 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6292 // FIXME: Move these to mono-context.h/c.
6293 mono_arch_context_set_int_reg (ctx, reg, v);
6295 // FIXME: Can't set registers, so we disable linears
6300 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6301 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6302 addr += (gint32)var->offset;
6304 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6307 addr = *(guint8**)addr;
6313 // FIXME: Write barriers
6314 mono_gc_memmove_atomic (addr, val, size);
6316 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6317 /* Same as regoffset, but with an indirection */
6318 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6319 addr += (gint32)var->offset;
6321 gaddr = *(gpointer*)addr;
6323 // FIXME: Write barriers
6324 mono_gc_memmove_atomic (gaddr, val, size);
6326 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6330 g_assert_not_reached ();
6335 clear_event_request (int req_id, int etype)
6339 mono_loader_lock ();
6340 for (i = 0; i < event_requests->len; ++i) {
6341 EventRequest *req = g_ptr_array_index (event_requests, i);
6343 if (req->id == req_id && req->event_kind == etype) {
6344 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6345 clear_breakpoint (req->info);
6346 if (req->event_kind == EVENT_KIND_STEP)
6347 ss_destroy (req->info);
6348 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6349 clear_breakpoint (req->info);
6350 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6351 clear_breakpoint (req->info);
6352 g_ptr_array_remove_index_fast (event_requests, i);
6357 mono_loader_unlock ();
6361 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
6365 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6366 m->kind = MOD_KIND_NONE;
6367 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6368 int count = 0, match_count = 0, pos;
6369 MonoAssembly **newassemblies;
6371 for (i = 0; m->data.assemblies [i]; ++i) {
6373 if (m->data.assemblies [i] == assembly)
6378 newassemblies = g_new0 (MonoAssembly*, count - match_count);
6381 for (i = 0; i < count; ++i)
6382 if (m->data.assemblies [i] != assembly)
6383 newassemblies [pos ++] = m->data.assemblies [i];
6384 g_assert (pos == count - match_count);
6385 g_free (m->data.assemblies);
6386 m->data.assemblies = newassemblies;
6392 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
6396 for (i = 0; i < req->nmodifiers; ++i) {
6397 Modifier *m = &req->modifiers [i];
6399 clear_assembly_from_modifier (req, m, assembly);
6404 * clear_event_requests_for_assembly:
6406 * Clear all events requests which reference ASSEMBLY.
6409 clear_event_requests_for_assembly (MonoAssembly *assembly)
6414 mono_loader_lock ();
6418 for (i = 0; i < event_requests->len; ++i) {
6419 EventRequest *req = g_ptr_array_index (event_requests, i);
6421 clear_assembly_from_modifiers (req, assembly);
6423 if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly (req->info, assembly)) {
6424 clear_event_request (req->id, req->event_kind);
6429 if (req->event_kind == EVENT_KIND_STEP)
6430 ss_clear_for_assembly (req->info, assembly);
6433 mono_loader_unlock ();
6437 * type_comes_from_assembly:
6439 * GHRFunc that returns TRUE if klass comes from assembly
6442 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6444 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6448 * clear_types_for_assembly:
6450 * Clears types from loaded_classes for a given assembly
6453 clear_types_for_assembly (MonoAssembly *assembly)
6455 MonoDomain *domain = mono_domain_get ();
6456 AgentDomainInfo *info = NULL;
6458 if (!domain || !domain_jit_info (domain))
6459 /* Can happen during shutdown */
6462 mono_loader_lock ();
6463 info = get_agent_domain_info (domain);
6464 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6465 mono_loader_unlock ();
6469 add_thread (gpointer key, gpointer value, gpointer user_data)
6471 MonoInternalThread *thread = value;
6472 Buffer *buf = user_data;
6474 buffer_add_objid (buf, (MonoObject*)thread);
6478 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6480 guint8 *end = invoke->endp;
6483 MonoMethodSignature *sig;
6486 MonoObject *this, *res, *exc;
6489 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6492 MonoStopwatch watch;
6494 if (invoke->method) {
6496 * Invoke this method directly, currently only Environment.Exit () is supported.
6499 DEBUG_PRINTF (1, "[%p] Invoking method '%s' on receiver '%s'.\n", (gpointer)GetCurrentThreadId (), mono_method_full_name (invoke->method, TRUE), this ? this->vtable->klass->name : "<null>");
6500 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
6501 g_assert_not_reached ();
6504 m = decode_methodid (p, &p, end, &domain, &err);
6507 sig = mono_method_signature (m);
6509 if (m->klass->valuetype)
6510 this_buf = g_alloca (mono_class_instance_size (m->klass));
6512 this_buf = g_alloca (sizeof (MonoObject*));
6513 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6514 /* Should be null */
6515 int type = decode_byte (p, &p, end);
6516 if (type != VALUE_TYPE_ID_NULL) {
6517 DEBUG_PRINTF (1, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer)GetCurrentThreadId ());
6518 return ERR_INVALID_ARGUMENT;
6520 memset (this_buf, 0, mono_class_instance_size (m->klass));
6522 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6527 if (!m->klass->valuetype)
6528 this = *(MonoObject**)this_buf;
6532 if (MONO_CLASS_IS_INTERFACE (m->klass)) {
6534 DEBUG_PRINTF (1, "[%p] Error: Interface method invoked without this argument.\n", (gpointer)GetCurrentThreadId ());
6535 return ERR_INVALID_ARGUMENT;
6537 m = mono_object_get_virtual_method (this, m);
6538 } else if ((m->flags & METHOD_ATTRIBUTE_VIRTUAL) && !m->klass->valuetype && invoke->flags & INVOKE_FLAG_VIRTUAL) {
6540 DEBUG_PRINTF (1, "[%p] Error: invoke with INVOKE_FLAG_VIRTUAL flag set without this argument.\n", (gpointer)GetCurrentThreadId ());
6541 return ERR_INVALID_ARGUMENT;
6543 m = mono_object_get_virtual_method (this, m);
6546 DEBUG_PRINTF (1, "[%p] Invoking method '%s' on receiver '%s'.\n", (gpointer)GetCurrentThreadId (), mono_method_full_name (m, TRUE), this ? this->vtable->klass->name : "<null>");
6548 if (this && this->vtable->domain != domain)
6551 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
6552 if (!strcmp (m->name, ".ctor")) {
6553 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
6554 return ERR_INVALID_ARGUMENT;
6556 this = mono_object_new (domain, m->klass);
6558 return ERR_INVALID_ARGUMENT;
6562 if (this && !obj_is_of_type (this, &m->klass->byval_arg))
6563 return ERR_INVALID_ARGUMENT;
6565 nargs = decode_int (p, &p, end);
6566 if (nargs != sig->param_count)
6567 return ERR_INVALID_ARGUMENT;
6568 /* Use alloca to get gc tracking */
6569 arg_buf = g_alloca (nargs * sizeof (gpointer));
6570 memset (arg_buf, 0, nargs * sizeof (gpointer));
6571 args = g_alloca (nargs * sizeof (gpointer));
6572 for (i = 0; i < nargs; ++i) {
6573 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6574 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6577 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6580 if (sig->params [i]->byref) {
6581 arg_buf [i] = g_alloca (sizeof (mgreg_t));
6582 *(gpointer*)arg_buf [i] = args [i];
6583 args [i] = arg_buf [i];
6586 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6587 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6590 args [i] = arg_buf [i];
6597 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6598 tls->disable_breakpoints = TRUE;
6600 tls->disable_breakpoints = FALSE;
6603 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6605 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6606 if (invoke->has_ctx) {
6609 lmf_addr = mono_get_lmf_addr ();
6612 memset (&ext, 0, sizeof (ext));
6613 mono_arch_init_lmf_ext (&ext, *lmf_addr);
6615 ext.debugger_invoke = TRUE;
6616 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6618 mono_set_lmf ((MonoLMF*)&ext);
6622 mono_stopwatch_start (&watch);
6623 if (m->klass->valuetype)
6624 res = mono_runtime_invoke (m, this_buf, args, &exc);
6626 res = mono_runtime_invoke (m, this, args, &exc);
6627 mono_stopwatch_stop (&watch);
6628 DEBUG_PRINTF (1, "[%p] Invoke result: %p, exc: %s, time: %ld ms.\n", (gpointer)GetCurrentThreadId (), res, exc ? exc->vtable->klass->name : NULL, (long)mono_stopwatch_elapsed_ms (&watch));
6630 buffer_add_byte (buf, 0);
6631 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6633 gboolean out_this = FALSE;
6634 gboolean out_args = FALSE;
6636 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_THIS) && CHECK_PROTOCOL_VERSION (2, 35))
6638 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_ARGS) && CHECK_PROTOCOL_VERSION (2, 35))
6640 buffer_add_byte (buf, 1 + (out_this ? 2 : 0) + (out_args ? 4 : 0));
6641 if (sig->ret->type == MONO_TYPE_VOID) {
6642 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
6643 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
6646 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6647 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6648 buffer_add_value (buf, sig->ret, &res, domain);
6649 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6650 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6651 MonoClass *k = mono_class_from_mono_type (sig->ret);
6652 guint8 *nullable_buf = g_alloca (mono_class_value_size (k, NULL));
6654 g_assert (nullable_buf);
6655 mono_nullable_init (nullable_buf, res, k);
6656 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6659 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6665 /* Return the new value of the receiver after the call */
6666 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
6668 buffer_add_int (buf, nargs);
6669 for (i = 0; i < nargs; ++i) {
6670 if (MONO_TYPE_IS_REFERENCE (sig->params [i]))
6671 buffer_add_value (buf, sig->params [i], &args [i], domain);
6672 else if (sig->params [i]->byref)
6673 /* add_value () does an indirection */
6674 buffer_add_value (buf, sig->params [i], &arg_buf [i], domain);
6676 buffer_add_value (buf, sig->params [i], arg_buf [i], domain);
6681 tls->disable_breakpoints = FALSE;
6683 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6684 if (invoke->has_ctx)
6685 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
6689 // FIXME: byref arguments
6697 * Invoke the method given by tls->pending_invoke in the current thread.
6700 invoke_method (void)
6702 DebuggerTlsData *tls;
6707 MonoContext restore_ctx;
6710 tls = mono_native_tls_get_value (debugger_tls_id);
6714 * Store the `InvokeData *' in `tls->invoke' until we're done with
6715 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6718 mono_loader_lock ();
6720 invoke = tls->pending_invoke;
6722 tls->pending_invoke = NULL;
6724 invoke->last_invoke = tls->invoke;
6725 tls->invoke = invoke;
6727 mono_loader_unlock ();
6729 tls->frames_up_to_date = FALSE;
6735 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6736 buffer_init (&buf, 128);
6739 /* Fail the other invokes as well */
6741 err = do_invoke_method (tls, &buf, invoke, p, &p);
6744 /* Start suspending before sending the reply */
6745 if (mindex == invoke->nmethods - 1) {
6746 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6747 for (i = 0; i < invoke->suspend_count; ++i)
6752 send_reply_packet (id, err, &buf);
6757 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6759 if (invoke->has_ctx)
6760 save_thread_context (&restore_ctx);
6762 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6763 g_assert (tls->resume_count);
6764 tls->resume_count -= invoke->suspend_count;
6767 DEBUG_PRINTF (1, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer)GetCurrentThreadId (), err, tls->resume_count);
6770 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6772 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
6773 * after the mono_runtime_invoke() already returned, but it doesn't matter
6774 * because we reset the abort here.
6777 mono_loader_lock ();
6779 if (tls->abort_requested)
6780 mono_thread_internal_reset_abort (tls->thread);
6782 tls->invoke = tls->invoke->last_invoke;
6783 tls->abort_requested = FALSE;
6785 mono_loader_unlock ();
6794 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6796 MonoThread *thread = value;
6797 DebuggerTlsData *tls;
6800 mono_loader_lock ();
6801 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6803 res = tls->really_suspended;
6804 mono_loader_unlock ();
6810 get_source_files_for_type (MonoClass *klass)
6812 gpointer iter = NULL;
6814 MonoDebugSourceInfo *sinfo;
6818 files = g_ptr_array_new ();
6820 while ((method = mono_class_get_methods (klass, &iter))) {
6821 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6822 GPtrArray *source_file_list;
6825 mono_debug_symfile_get_line_numbers_full (minfo, NULL, &source_file_list, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
6826 for (j = 0; j < source_file_list->len; ++j) {
6827 sinfo = g_ptr_array_index (source_file_list, j);
6828 for (i = 0; i < files->len; ++i)
6829 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6831 if (i == files->len)
6832 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6834 g_ptr_array_free (source_file_list, TRUE);
6842 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6845 case CMD_VM_VERSION: {
6846 char *build_info, *version;
6848 build_info = mono_get_runtime_build_info ();
6849 version = g_strdup_printf ("mono %s", build_info);
6851 buffer_add_string (buf, version); /* vm version */
6852 buffer_add_int (buf, MAJOR_VERSION);
6853 buffer_add_int (buf, MINOR_VERSION);
6854 g_free (build_info);
6858 case CMD_VM_SET_PROTOCOL_VERSION: {
6859 major_version = decode_int (p, &p, end);
6860 minor_version = decode_int (p, &p, end);
6861 protocol_version_set = TRUE;
6862 DEBUG_PRINTF (1, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version);
6865 case CMD_VM_ALL_THREADS: {
6867 mono_loader_lock ();
6868 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6869 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6870 mono_loader_unlock ();
6873 case CMD_VM_SUSPEND:
6875 wait_for_suspend ();
6878 if (suspend_count == 0)
6879 return ERR_NOT_SUSPENDED;
6881 clear_suspended_objs ();
6883 case CMD_VM_DISPOSE:
6884 /* Clear all event requests */
6885 mono_loader_lock ();
6886 while (event_requests->len > 0) {
6887 EventRequest *req = g_ptr_array_index (event_requests, 0);
6889 clear_event_request (req->id, req->event_kind);
6891 mono_loader_unlock ();
6893 while (suspend_count > 0)
6895 disconnected = TRUE;
6896 vm_start_event_sent = FALSE;
6899 MonoInternalThread *thread;
6900 DebuggerTlsData *tls;
6901 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6902 MonoClass *env_class;
6904 MonoMethod *exit_method = NULL;
6908 exit_code = decode_int (p, &p, end);
6910 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6912 /* Have to send a reply before exiting */
6913 send_reply_packet (id, 0, buf);
6915 /* Clear all event requests */
6916 mono_loader_lock ();
6917 while (event_requests->len > 0) {
6918 EventRequest *req = g_ptr_array_index (event_requests, 0);
6920 clear_event_request (req->id, req->event_kind);
6922 mono_loader_unlock ();
6925 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6926 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6927 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6928 * better than doing the shutdown ourselves, since it avoids various races.
6932 wait_for_suspend ();
6934 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6935 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
6937 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6940 mono_loader_lock ();
6941 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6942 mono_loader_unlock ();
6944 if (thread && exit_method) {
6945 mono_loader_lock ();
6946 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6947 mono_loader_unlock ();
6949 args = g_new0 (gpointer, 1);
6950 args [0] = g_malloc (sizeof (int));
6951 *(int*)(args [0]) = exit_code;
6953 tls->pending_invoke = g_new0 (InvokeData, 1);
6954 tls->pending_invoke->method = exit_method;
6955 tls->pending_invoke->args = args;
6956 tls->pending_invoke->nmethods = 1;
6958 while (suspend_count > 0)
6962 * No thread found, do it ourselves.
6963 * FIXME: This can race with normal shutdown etc.
6965 while (suspend_count > 0)
6968 if (!mono_runtime_try_shutdown ())
6971 mono_environment_exitcode_set (exit_code);
6973 /* Suspend all managed threads since the runtime is going away */
6974 DEBUG_PRINTF (1, "Suspending all threads...\n");
6975 mono_thread_suspend_all_other_threads ();
6976 DEBUG_PRINTF (1, "Shutting down the runtime...\n");
6977 mono_runtime_quit ();
6978 transport_close2 ();
6979 DEBUG_PRINTF (1, "Exiting...\n");
6985 case CMD_VM_INVOKE_METHOD:
6986 case CMD_VM_INVOKE_METHODS: {
6987 int objid = decode_objid (p, &p, end);
6989 DebuggerTlsData *tls;
6990 int i, count, err, flags, nmethods;
6992 err = get_object (objid, (MonoObject**)&thread);
6996 flags = decode_int (p, &p, end);
6998 if (command == CMD_VM_INVOKE_METHODS)
6999 nmethods = decode_int (p, &p, end);
7003 // Wait for suspending if it already started
7005 wait_for_suspend ();
7006 if (!is_suspended ())
7007 return ERR_NOT_SUSPENDED;
7009 mono_loader_lock ();
7010 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7011 mono_loader_unlock ();
7014 if (!tls->really_suspended)
7015 /* The thread is still running native code, can't do invokes */
7016 return ERR_NOT_SUSPENDED;
7019 * Store the invoke data into tls, the thread will execute it after it is
7022 if (tls->pending_invoke)
7023 return ERR_NOT_SUSPENDED;
7024 tls->pending_invoke = g_new0 (InvokeData, 1);
7025 tls->pending_invoke->id = id;
7026 tls->pending_invoke->flags = flags;
7027 tls->pending_invoke->p = g_malloc (end - p);
7028 memcpy (tls->pending_invoke->p, p, end - p);
7029 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
7030 tls->pending_invoke->suspend_count = suspend_count;
7031 tls->pending_invoke->nmethods = nmethods;
7033 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
7034 resume_thread (THREAD_TO_INTERNAL (thread));
7037 count = suspend_count;
7038 for (i = 0; i < count; ++i)
7043 case CMD_VM_ABORT_INVOKE: {
7044 int objid = decode_objid (p, &p, end);
7046 DebuggerTlsData *tls;
7049 err = get_object (objid, (MonoObject**)&thread);
7053 invoke_id = decode_int (p, &p, end);
7055 mono_loader_lock ();
7056 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7059 if (tls->abort_requested) {
7060 mono_loader_unlock ();
7065 * Check whether we're still inside the mono_runtime_invoke() and that it's
7066 * actually the correct invocation.
7068 * Careful, we do not stop the thread that's doing the invocation, so we can't
7069 * inspect its stack. However, invoke_method() also acquires the loader lock
7070 * when it's done, so we're safe here.
7074 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
7075 mono_loader_unlock ();
7076 return ERR_NO_INVOCATION;
7079 tls->abort_requested = TRUE;
7081 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
7082 mono_loader_unlock ();
7086 case CMD_VM_SET_KEEPALIVE: {
7087 int timeout = decode_int (p, &p, end);
7088 agent_config.keepalive = timeout;
7090 #ifndef DISABLE_SOCKET_TRANSPORT
7097 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
7098 GHashTableIter iter, kiter;
7103 char *fname, *basename;
7104 gboolean ignore_case;
7105 GSList *class_list, *l;
7106 GPtrArray *res_classes, *res_domains;
7108 fname = decode_string (p, &p, end);
7109 ignore_case = decode_byte (p, &p, end);
7111 basename = dbg_path_get_basename (fname);
7113 res_classes = g_ptr_array_new ();
7114 res_domains = g_ptr_array_new ();
7116 mono_loader_lock ();
7117 g_hash_table_iter_init (&iter, domains);
7118 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7119 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
7121 /* Update 'source_file_to_class' cache */
7122 g_hash_table_iter_init (&kiter, info->loaded_classes);
7123 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
7124 if (!g_hash_table_lookup (info->source_files, klass)) {
7125 files = get_source_files_for_type (klass);
7126 g_hash_table_insert (info->source_files, klass, files);
7128 for (i = 0; i < files->len; ++i) {
7129 char *s = g_ptr_array_index (files, i);
7130 char *s2 = dbg_path_get_basename (s);
7133 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
7135 class_list = g_slist_prepend (class_list, klass);
7136 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
7138 class_list = g_slist_prepend (class_list, klass);
7139 g_hash_table_insert (info->source_file_to_class, s2, class_list);
7142 /* The _ignorecase hash contains the lowercase path */
7143 s3 = strdup_tolower (s2);
7144 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
7146 class_list = g_slist_prepend (class_list, klass);
7147 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
7149 class_list = g_slist_prepend (class_list, klass);
7150 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
7162 s = strdup_tolower (basename);
7163 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
7166 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
7169 for (l = class_list; l; l = l->next) {
7172 g_ptr_array_add (res_classes, klass);
7173 g_ptr_array_add (res_domains, domain);
7176 mono_loader_unlock ();
7181 buffer_add_int (buf, res_classes->len);
7182 for (i = 0; i < res_classes->len; ++i)
7183 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
7184 g_ptr_array_free (res_classes, TRUE);
7185 g_ptr_array_free (res_domains, TRUE);
7188 case CMD_VM_GET_TYPES: {
7189 GHashTableIter iter;
7193 gboolean ignore_case;
7194 GPtrArray *res_classes, *res_domains;
7195 MonoTypeNameParse info;
7197 name = decode_string (p, &p, end);
7198 ignore_case = decode_byte (p, &p, end);
7200 if (!mono_reflection_parse_type (name, &info)) {
7202 mono_reflection_free_type_info (&info);
7203 return ERR_INVALID_ARGUMENT;
7206 res_classes = g_ptr_array_new ();
7207 res_domains = g_ptr_array_new ();
7209 mono_loader_lock ();
7210 g_hash_table_iter_init (&iter, domains);
7211 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7213 gboolean type_resolve;
7217 mono_domain_assemblies_lock (domain);
7218 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7222 type_resolve = TRUE;
7223 t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
7225 g_ptr_array_add (res_classes, mono_type_get_class (t));
7226 g_ptr_array_add (res_domains, domain);
7230 mono_domain_assemblies_unlock (domain);
7232 mono_loader_unlock ();
7235 mono_reflection_free_type_info (&info);
7237 buffer_add_int (buf, res_classes->len);
7238 for (i = 0; i < res_classes->len; ++i)
7239 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
7240 g_ptr_array_free (res_classes, TRUE);
7241 g_ptr_array_free (res_domains, TRUE);
7244 case CMD_VM_START_BUFFERING:
7245 case CMD_VM_STOP_BUFFERING:
7246 /* Handled in the main loop */
7249 return ERR_NOT_IMPLEMENTED;
7256 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7262 case CMD_EVENT_REQUEST_SET: {
7264 int i, event_kind, suspend_policy, nmodifiers, mod;
7267 MonoThread *step_thread;
7268 int size = 0, depth = 0, filter = 0, step_thread_id = 0;
7272 event_kind = decode_byte (p, &p, end);
7273 suspend_policy = decode_byte (p, &p, end);
7274 nmodifiers = decode_byte (p, &p, end);
7276 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7277 req->id = InterlockedIncrement (&event_request_id);
7278 req->event_kind = event_kind;
7279 req->suspend_policy = suspend_policy;
7280 req->nmodifiers = nmodifiers;
7283 for (i = 0; i < nmodifiers; ++i) {
7284 mod = decode_byte (p, &p, end);
7286 req->modifiers [i].kind = mod;
7287 if (mod == MOD_KIND_COUNT) {
7288 req->modifiers [i].data.count = decode_int (p, &p, end);
7289 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7290 method = decode_methodid (p, &p, end, &domain, &err);
7293 location = decode_long (p, &p, end);
7294 } else if (mod == MOD_KIND_STEP) {
7295 step_thread_id = decode_id (p, &p, end);
7296 size = decode_int (p, &p, end);
7297 depth = decode_int (p, &p, end);
7298 if (CHECK_PROTOCOL_VERSION (2, 16))
7299 filter = decode_int (p, &p, end);
7300 req->modifiers [i].data.filter = filter;
7301 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7302 /* Treat STEP_THOUGH the same as HIDDEN */
7303 req->modifiers [i].data.filter |= STEP_FILTER_DEBUGGER_STEP_THROUGH;
7304 } else if (mod == MOD_KIND_THREAD_ONLY) {
7305 int id = decode_id (p, &p, end);
7307 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7312 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7313 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7317 req->modifiers [i].caught = decode_byte (p, &p, end);
7318 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7319 if (CHECK_PROTOCOL_VERSION (2, 25))
7320 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7322 req->modifiers [i].subclasses = TRUE;
7323 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" : "");
7325 req->modifiers [i].data.exc_class = exc_class;
7327 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
7329 return ERR_INVALID_ARGUMENT;
7332 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7333 int n = decode_int (p, &p, end);
7336 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
7337 for (j = 0; j < n; ++j) {
7338 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7340 g_free (req->modifiers [i].data.assemblies);
7344 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7345 int n = decode_int (p, &p, end);
7348 modifier = &req->modifiers [i];
7349 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7350 for (j = 0; j < n; ++j) {
7351 char *s = decode_string (p, &p, end);
7355 s2 = strdup_tolower (s);
7356 g_hash_table_insert (modifier->data.source_files, s2, s2);
7360 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7361 int n = decode_int (p, &p, end);
7364 modifier = &req->modifiers [i];
7365 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7366 for (j = 0; j < n; ++j) {
7367 char *s = decode_string (p, &p, end);
7370 g_hash_table_insert (modifier->data.type_names, s, s);
7374 return ERR_NOT_IMPLEMENTED;
7378 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7381 req->info = set_breakpoint (method, location, req, &error);
7382 if (!mono_error_ok (&error)) {
7384 DEBUG_PRINTF (1, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error));
7385 mono_error_cleanup (&error);
7386 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7388 } else if (req->event_kind == EVENT_KIND_STEP) {
7389 g_assert (step_thread_id);
7391 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7397 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, filter, req);
7402 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7403 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7404 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7405 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7406 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7407 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7409 if (req->nmodifiers) {
7411 return ERR_NOT_IMPLEMENTED;
7415 mono_loader_lock ();
7416 g_ptr_array_add (event_requests, req);
7418 if (agent_config.defer) {
7419 /* Transmit cached data to the client on receipt of the event request */
7420 switch (req->event_kind) {
7421 case EVENT_KIND_APPDOMAIN_CREATE:
7422 /* Emit load events for currently loaded domains */
7423 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7425 case EVENT_KIND_ASSEMBLY_LOAD:
7426 /* Emit load events for currently loaded assemblies */
7427 mono_assembly_foreach (emit_assembly_load, NULL);
7429 case EVENT_KIND_THREAD_START:
7430 /* Emit start events for currently started threads */
7431 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7433 case EVENT_KIND_TYPE_LOAD:
7434 /* Emit type load events for currently loaded types */
7435 mono_domain_foreach (send_types_for_domain, NULL);
7441 mono_loader_unlock ();
7443 buffer_add_int (buf, req->id);
7446 case CMD_EVENT_REQUEST_CLEAR: {
7447 int etype = decode_byte (p, &p, end);
7448 int req_id = decode_int (p, &p, end);
7450 // FIXME: Make a faster mapping from req_id to request
7451 mono_loader_lock ();
7452 clear_event_request (req_id, etype);
7453 mono_loader_unlock ();
7456 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7459 mono_loader_lock ();
7461 while (i < event_requests->len) {
7462 EventRequest *req = g_ptr_array_index (event_requests, i);
7464 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7465 clear_breakpoint (req->info);
7467 g_ptr_array_remove_index_fast (event_requests, i);
7473 mono_loader_unlock ();
7477 return ERR_NOT_IMPLEMENTED;
7484 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7490 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7491 buffer_add_domainid (buf, mono_get_root_domain ());
7494 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7495 domain = decode_domainid (p, &p, end, NULL, &err);
7498 buffer_add_string (buf, domain->friendly_name);
7501 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7506 domain = decode_domainid (p, &p, end, NULL, &err);
7509 mono_loader_lock ();
7511 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7514 buffer_add_int (buf, count);
7515 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7517 buffer_add_assemblyid (buf, domain, ass);
7519 mono_loader_unlock ();
7522 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7523 domain = decode_domainid (p, &p, end, NULL, &err);
7527 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7530 case CMD_APPDOMAIN_GET_CORLIB: {
7531 domain = decode_domainid (p, &p, end, NULL, &err);
7535 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7538 case CMD_APPDOMAIN_CREATE_STRING: {
7542 domain = decode_domainid (p, &p, end, NULL, &err);
7545 s = decode_string (p, &p, end);
7547 o = mono_string_new (domain, s);
7548 buffer_add_objid (buf, (MonoObject*)o);
7551 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7553 MonoDomain *domain2;
7556 domain = decode_domainid (p, &p, end, NULL, &err);
7559 klass = decode_typeid (p, &p, end, &domain2, &err);
7564 g_assert (domain == domain2);
7566 o = mono_object_new (domain, klass);
7568 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
7572 buffer_add_objid (buf, o);
7576 return ERR_NOT_IMPLEMENTED;
7583 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7589 ass = decode_assemblyid (p, &p, end, &domain, &err);
7594 case CMD_ASSEMBLY_GET_LOCATION: {
7595 buffer_add_string (buf, mono_image_get_filename (ass->image));
7598 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7602 if (ass->image->dynamic) {
7603 buffer_add_id (buf, 0);
7605 token = mono_image_get_entry_point (ass->image);
7607 buffer_add_id (buf, 0);
7609 m = mono_get_method (ass->image, token, NULL);
7610 buffer_add_methodid (buf, domain, m);
7615 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7616 buffer_add_moduleid (buf, domain, ass->image);
7619 case CMD_ASSEMBLY_GET_OBJECT: {
7620 MonoObject *o = (MonoObject*)mono_assembly_get_object (domain, ass);
7621 buffer_add_objid (buf, o);
7624 case CMD_ASSEMBLY_GET_TYPE: {
7625 char *s = decode_string (p, &p, end);
7626 gboolean ignorecase = decode_byte (p, &p, end);
7627 MonoTypeNameParse info;
7629 gboolean type_resolve, res;
7630 MonoDomain *d = mono_domain_get ();
7632 /* This is needed to be able to find referenced assemblies */
7633 res = mono_domain_set (domain, FALSE);
7636 if (!mono_reflection_parse_type (s, &info)) {
7639 if (info.assembly.name)
7641 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
7643 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
7644 mono_reflection_free_type_info (&info);
7647 mono_domain_set (d, TRUE);
7651 case CMD_ASSEMBLY_GET_NAME: {
7653 MonoAssembly *mass = ass;
7655 name = g_strdup_printf (
7656 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7658 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7659 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7660 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7661 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7663 buffer_add_string (buf, name);
7668 return ERR_NOT_IMPLEMENTED;
7675 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7681 case CMD_MODULE_GET_INFO: {
7682 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7685 basename = g_path_get_basename (image->name);
7686 buffer_add_string (buf, basename); // name
7687 buffer_add_string (buf, image->module_name); // scopename
7688 buffer_add_string (buf, image->name); // fqname
7689 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7690 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7695 return ERR_NOT_IMPLEMENTED;
7702 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7708 case CMD_FIELD_GET_INFO: {
7709 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
7711 buffer_add_string (buf, f->name);
7712 buffer_add_typeid (buf, domain, f->parent);
7713 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7714 buffer_add_int (buf, f->type->attrs);
7718 return ERR_NOT_IMPLEMENTED;
7725 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7727 if (val && val->vtable->klass == mono_defaults.monotype_class) {
7728 /* Special case these so the client doesn't have to handle Type objects */
7730 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7731 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7732 } else if (MONO_TYPE_IS_REFERENCE (t))
7733 buffer_add_value (buf, t, &val, domain);
7735 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7739 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7745 buffer_add_int (buf, 0);
7749 for (i = 0; i < cinfo->num_attrs; ++i) {
7750 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7753 buffer_add_int (buf, nattrs);
7755 for (i = 0; i < cinfo->num_attrs; ++i) {
7756 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7757 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7758 MonoArray *typed_args, *named_args;
7760 CattrNamedArg *arginfo = NULL;
7763 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
7764 if (!mono_error_ok (&error)) {
7765 DEBUG_PRINTF (2, "[dbg] mono_reflection_create_custom_attr_data_args () failed with: '%s'\n", mono_error_get_message (&error));
7766 mono_error_cleanup (&error);
7767 return ERR_LOADER_ERROR;
7770 buffer_add_methodid (buf, domain, attr->ctor);
7774 buffer_add_int (buf, mono_array_length (typed_args));
7775 for (j = 0; j < mono_array_length (typed_args); ++j) {
7776 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7778 t = mono_method_signature (attr->ctor)->params [j];
7780 buffer_add_cattr_arg (buf, t, domain, val);
7783 buffer_add_int (buf, 0);
7788 buffer_add_int (buf, mono_array_length (named_args));
7790 for (j = 0; j < mono_array_length (named_args); ++j) {
7791 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7793 if (arginfo [j].prop) {
7794 buffer_add_byte (buf, 0x54);
7795 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7796 } else if (arginfo [j].field) {
7797 buffer_add_byte (buf, 0x53);
7798 buffer_add_fieldid (buf, domain, arginfo [j].field);
7800 g_assert_not_reached ();
7803 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7806 buffer_add_int (buf, 0);
7815 /* FIXME: Code duplication with icall.c */
7817 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7822 mono_class_setup_interfaces (klass, error);
7823 if (!mono_error_ok (error))
7826 for (i = 0; i < klass->interface_count; i++) {
7827 ic = klass->interfaces [i];
7828 g_hash_table_insert (ifaces, ic, ic);
7830 collect_interfaces (ic, ifaces, error);
7831 if (!mono_error_ok (error))
7837 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7847 case CMD_TYPE_GET_INFO: {
7848 buffer_add_string (buf, klass->name_space);
7849 buffer_add_string (buf, klass->name);
7851 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7852 buffer_add_string (buf, name);
7854 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7855 buffer_add_moduleid (buf, domain, klass->image);
7856 buffer_add_typeid (buf, domain, klass->parent);
7857 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7858 buffer_add_typeid (buf, domain, klass->element_class);
7860 buffer_add_id (buf, 0);
7861 buffer_add_int (buf, klass->type_token);
7862 buffer_add_byte (buf, klass->rank);
7863 buffer_add_int (buf, klass->flags);
7865 type = &klass->byval_arg;
7866 // FIXME: Can't decide whenever a class represents a byref type
7869 if (type->type == MONO_TYPE_PTR)
7871 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7873 if (type->type == MONO_TYPE_VALUETYPE)
7875 if (klass->enumtype)
7877 if (klass->generic_container)
7879 if (klass->generic_container || klass->generic_class)
7881 buffer_add_byte (buf, b);
7884 while ((nested = mono_class_get_nested_types (klass, &iter)))
7886 buffer_add_int (buf, nnested);
7888 while ((nested = mono_class_get_nested_types (klass, &iter)))
7889 buffer_add_typeid (buf, domain, nested);
7890 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7891 if (klass->generic_container)
7892 buffer_add_typeid (buf, domain, klass);
7893 else if (klass->generic_class)
7894 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7896 buffer_add_id (buf, 0);
7898 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7901 if (klass->generic_class) {
7902 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7904 count = inst->type_argc;
7905 buffer_add_int (buf, count);
7906 for (i = 0; i < count; i++)
7907 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7908 } else if (klass->generic_container) {
7909 MonoGenericContainer *container = klass->generic_container;
7912 count = container->type_argc;
7913 buffer_add_int (buf, count);
7914 for (i = 0; i < count; i++) {
7915 pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
7916 buffer_add_typeid (buf, domain, pklass);
7919 buffer_add_int (buf, 0);
7924 case CMD_TYPE_GET_METHODS: {
7927 gpointer iter = NULL;
7930 mono_class_setup_methods (klass);
7932 nmethods = mono_class_num_methods (klass);
7934 buffer_add_int (buf, nmethods);
7936 while ((m = mono_class_get_methods (klass, &iter))) {
7937 buffer_add_methodid (buf, domain, m);
7940 g_assert (i == nmethods);
7943 case CMD_TYPE_GET_FIELDS: {
7946 gpointer iter = NULL;
7949 nfields = mono_class_num_fields (klass);
7951 buffer_add_int (buf, nfields);
7953 while ((f = mono_class_get_fields (klass, &iter))) {
7954 buffer_add_fieldid (buf, domain, f);
7955 buffer_add_string (buf, f->name);
7956 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7957 buffer_add_int (buf, f->type->attrs);
7960 g_assert (i == nfields);
7963 case CMD_TYPE_GET_PROPERTIES: {
7966 gpointer iter = NULL;
7969 nprops = mono_class_num_properties (klass);
7971 buffer_add_int (buf, nprops);
7973 while ((p = mono_class_get_properties (klass, &iter))) {
7974 buffer_add_propertyid (buf, domain, p);
7975 buffer_add_string (buf, p->name);
7976 buffer_add_methodid (buf, domain, p->get);
7977 buffer_add_methodid (buf, domain, p->set);
7978 buffer_add_int (buf, p->attrs);
7981 g_assert (i == nprops);
7984 case CMD_TYPE_GET_CATTRS: {
7985 MonoClass *attr_klass;
7986 MonoCustomAttrInfo *cinfo;
7988 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7989 /* attr_klass can be NULL */
7993 cinfo = mono_custom_attrs_from_class (klass);
7995 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8000 case CMD_TYPE_GET_FIELD_CATTRS: {
8001 MonoClass *attr_klass;
8002 MonoCustomAttrInfo *cinfo;
8003 MonoClassField *field;
8005 field = decode_fieldid (p, &p, end, NULL, &err);
8008 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8012 cinfo = mono_custom_attrs_from_field (klass, field);
8014 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8019 case CMD_TYPE_GET_PROPERTY_CATTRS: {
8020 MonoClass *attr_klass;
8021 MonoCustomAttrInfo *cinfo;
8024 prop = decode_propertyid (p, &p, end, NULL, &err);
8027 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8031 cinfo = mono_custom_attrs_from_property (klass, prop);
8033 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8038 case CMD_TYPE_GET_VALUES:
8039 case CMD_TYPE_GET_VALUES_2: {
8046 MonoThread *thread_obj;
8047 MonoInternalThread *thread = NULL;
8048 guint32 special_static_type;
8050 if (command == CMD_TYPE_GET_VALUES_2) {
8051 int objid = decode_objid (p, &p, end);
8054 err = get_object (objid, (MonoObject**)&thread_obj);
8058 thread = THREAD_TO_INTERNAL (thread_obj);
8061 len = decode_int (p, &p, end);
8062 for (i = 0; i < len; ++i) {
8063 f = decode_fieldid (p, &p, end, NULL, &err);
8067 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8068 return ERR_INVALID_FIELDID;
8069 special_static_type = mono_class_field_get_special_static_type (f);
8070 if (special_static_type != SPECIAL_STATIC_NONE) {
8071 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
8072 return ERR_INVALID_FIELDID;
8075 /* Check that the field belongs to the object */
8077 for (k = klass; k; k = k->parent) {
8078 if (k == f->parent) {
8084 return ERR_INVALID_FIELDID;
8086 vtable = mono_class_vtable (domain, f->parent);
8087 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8088 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
8089 buffer_add_value (buf, f->type, val, domain);
8094 case CMD_TYPE_SET_VALUES: {
8102 len = decode_int (p, &p, end);
8103 for (i = 0; i < len; ++i) {
8104 f = decode_fieldid (p, &p, end, NULL, &err);
8108 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8109 return ERR_INVALID_FIELDID;
8110 if (mono_class_field_is_special_static (f))
8111 return ERR_INVALID_FIELDID;
8113 /* Check that the field belongs to the object */
8115 for (k = klass; k; k = k->parent) {
8116 if (k == f->parent) {
8122 return ERR_INVALID_FIELDID;
8124 // FIXME: Check for literal/const
8126 vtable = mono_class_vtable (domain, f->parent);
8127 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8128 err = decode_value (f->type, domain, val, p, &p, end);
8133 if (MONO_TYPE_IS_REFERENCE (f->type))
8134 mono_field_static_set_value (vtable, f, *(gpointer*)val);
8136 mono_field_static_set_value (vtable, f, val);
8141 case CMD_TYPE_GET_OBJECT: {
8142 MonoObject *o = (MonoObject*)mono_type_get_object (domain, &klass->byval_arg);
8143 buffer_add_objid (buf, o);
8146 case CMD_TYPE_GET_SOURCE_FILES:
8147 case CMD_TYPE_GET_SOURCE_FILES_2: {
8148 char *source_file, *base;
8152 files = get_source_files_for_type (klass);
8154 buffer_add_int (buf, files->len);
8155 for (i = 0; i < files->len; ++i) {
8156 source_file = g_ptr_array_index (files, i);
8157 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8158 buffer_add_string (buf, source_file);
8160 base = dbg_path_get_basename (source_file);
8161 buffer_add_string (buf, base);
8164 g_free (source_file);
8166 g_ptr_array_free (files, TRUE);
8169 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8170 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8174 if (mono_class_is_assignable_from (klass, oklass))
8175 buffer_add_byte (buf, 1);
8177 buffer_add_byte (buf, 0);
8180 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8181 char *name = decode_string (p, &p, end);
8182 int i, flags = decode_int (p, &p, end);
8183 MonoException *ex = NULL;
8184 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
8187 return ERR_LOADER_ERROR;
8188 buffer_add_int (buf, array->len);
8189 for (i = 0; i < array->len; ++i) {
8190 MonoMethod *method = g_ptr_array_index (array, i);
8191 buffer_add_methodid (buf, domain, method);
8194 g_ptr_array_free (array, TRUE);
8198 case CMD_TYPE_GET_INTERFACES: {
8200 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8202 MonoClass *tclass, *iface;
8203 GHashTableIter iter;
8207 for (parent = tclass; parent; parent = parent->parent) {
8208 mono_class_setup_interfaces (parent, &error);
8209 if (!mono_error_ok (&error))
8210 return ERR_LOADER_ERROR;
8211 collect_interfaces (parent, iface_hash, &error);
8212 if (!mono_error_ok (&error))
8213 return ERR_LOADER_ERROR;
8216 buffer_add_int (buf, g_hash_table_size (iface_hash));
8218 g_hash_table_iter_init (&iter, iface_hash);
8219 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8220 buffer_add_typeid (buf, domain, iface);
8221 g_hash_table_destroy (iface_hash);
8224 case CMD_TYPE_GET_INTERFACE_MAP: {
8225 int tindex, ioffset;
8226 gboolean variance_used;
8228 int len, nmethods, i;
8232 len = decode_int (p, &p, end);
8233 mono_class_setup_vtable (klass);
8235 for (tindex = 0; tindex < len; ++tindex) {
8236 iclass = decode_typeid (p, &p, end, NULL, &err);
8240 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8242 return ERR_INVALID_ARGUMENT;
8244 nmethods = mono_class_num_methods (iclass);
8245 buffer_add_int (buf, nmethods);
8248 while ((method = mono_class_get_methods (iclass, &iter))) {
8249 buffer_add_methodid (buf, domain, method);
8251 for (i = 0; i < nmethods; ++i)
8252 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
8256 case CMD_TYPE_IS_INITIALIZED: {
8257 MonoVTable *vtable = mono_class_vtable (domain, klass);
8260 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8262 buffer_add_int (buf, 0);
8265 case CMD_TYPE_CREATE_INSTANCE: {
8268 obj = mono_object_new (domain, klass);
8269 buffer_add_objid (buf, obj);
8273 return ERR_NOT_IMPLEMENTED;
8280 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8283 MonoDomain *old_domain;
8287 klass = decode_typeid (p, &p, end, &domain, &err);
8291 old_domain = mono_domain_get ();
8293 mono_domain_set (domain, TRUE);
8295 err = type_commands_internal (command, klass, domain, p, end, buf);
8297 mono_domain_set (old_domain, TRUE);
8303 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8305 MonoMethodHeader *header;
8309 case CMD_METHOD_GET_NAME: {
8310 buffer_add_string (buf, method->name);
8313 case CMD_METHOD_GET_DECLARING_TYPE: {
8314 buffer_add_typeid (buf, domain, method->klass);
8317 case CMD_METHOD_GET_DEBUG_INFO: {
8318 MonoDebugMethodInfo *minfo;
8320 int i, j, n_il_offsets;
8323 int *column_numbers;
8324 int *end_line_numbers;
8325 int *end_column_numbers;
8327 GPtrArray *source_file_list;
8329 header = mono_method_get_header (method);
8331 buffer_add_int (buf, 0);
8332 buffer_add_string (buf, "");
8333 buffer_add_int (buf, 0);
8337 minfo = mono_debug_lookup_method (method);
8339 buffer_add_int (buf, header->code_size);
8340 buffer_add_string (buf, "");
8341 buffer_add_int (buf, 0);
8342 mono_metadata_free_mh (header);
8346 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, &n_il_offsets, &il_offsets, &line_numbers, &column_numbers, &source_files, &end_line_numbers, &end_column_numbers);
8347 buffer_add_int (buf, header->code_size);
8348 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8349 buffer_add_int (buf, source_file_list->len);
8350 for (i = 0; i < source_file_list->len; ++i) {
8351 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
8352 buffer_add_string (buf, sinfo->source_file);
8353 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8354 for (j = 0; j < 16; ++j)
8355 buffer_add_byte (buf, sinfo->hash [j]);
8359 buffer_add_string (buf, source_file);
8361 buffer_add_int (buf, n_il_offsets);
8362 DEBUG_PRINTF (10, "Line number table for method %s:\n", mono_method_full_name (method, TRUE));
8363 for (i = 0; i < n_il_offsets; ++i) {
8364 const char *srcfile = "";
8366 if (source_files [i] != -1) {
8367 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
8368 srcfile = sinfo->source_file;
8370 DEBUG_PRINTF (10, "IL%x -> %s:%d %d %d %d\n", il_offsets [i], srcfile, line_numbers [i], column_numbers ? column_numbers [i] : -1, end_line_numbers ? end_line_numbers [i] : -1, end_column_numbers ? end_column_numbers [i] : -1);
8371 buffer_add_int (buf, il_offsets [i]);
8372 buffer_add_int (buf, line_numbers [i]);
8373 if (CHECK_PROTOCOL_VERSION (2, 13))
8374 buffer_add_int (buf, source_files [i]);
8375 if (CHECK_PROTOCOL_VERSION (2, 19))
8376 buffer_add_int (buf, column_numbers ? column_numbers [i] : -1);
8377 if (CHECK_PROTOCOL_VERSION (2, 32)) {
8378 buffer_add_int (buf, end_line_numbers ? end_line_numbers [i] : -1);
8379 buffer_add_int (buf, end_column_numbers ? end_column_numbers [i] : -1);
8382 g_free (source_file);
8383 g_free (il_offsets);
8384 g_free (line_numbers);
8385 g_free (column_numbers);
8386 g_free (end_line_numbers);
8387 g_free (end_column_numbers);
8388 g_free (source_files);
8389 g_ptr_array_free (source_file_list, TRUE);
8390 mono_metadata_free_mh (header);
8393 case CMD_METHOD_GET_PARAM_INFO: {
8394 MonoMethodSignature *sig = mono_method_signature (method);
8398 /* FIXME: mono_class_from_mono_type () and byrefs */
8400 /* FIXME: Use a smaller encoding */
8401 buffer_add_int (buf, sig->call_convention);
8402 buffer_add_int (buf, sig->param_count);
8403 buffer_add_int (buf, sig->generic_param_count);
8404 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
8405 for (i = 0; i < sig->param_count; ++i) {
8407 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
8410 /* Emit parameter names */
8411 names = g_new (char *, sig->param_count);
8412 mono_method_get_param_names (method, (const char **) names);
8413 for (i = 0; i < sig->param_count; ++i)
8414 buffer_add_string (buf, names [i]);
8419 case CMD_METHOD_GET_LOCALS_INFO: {
8420 int i, j, num_locals;
8421 MonoDebugLocalsInfo *locals;
8423 header = mono_method_get_header (method);
8425 return ERR_INVALID_ARGUMENT;
8427 buffer_add_int (buf, header->num_locals);
8430 for (i = 0; i < header->num_locals; ++i)
8431 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
8434 locals = mono_debug_lookup_locals (method);
8436 num_locals = locals->num_locals;
8439 for (i = 0; i < header->num_locals; ++i) {
8440 for (j = 0; j < num_locals; ++j)
8441 if (locals->locals [j].index == i)
8444 buffer_add_string (buf, locals->locals [j].name);
8446 buffer_add_string (buf, "");
8450 for (i = 0; i < header->num_locals; ++i) {
8451 for (j = 0; j < num_locals; ++j)
8452 if (locals->locals [j].index == i)
8454 if (j < num_locals && locals->locals [j].block) {
8455 buffer_add_int (buf, locals->locals [j].block->start_offset);
8456 buffer_add_int (buf, locals->locals [j].block->end_offset);
8458 buffer_add_int (buf, 0);
8459 buffer_add_int (buf, header->code_size);
8462 mono_metadata_free_mh (header);
8465 mono_debug_symfile_free_locals (locals);
8469 case CMD_METHOD_GET_INFO:
8470 buffer_add_int (buf, method->flags);
8471 buffer_add_int (buf, method->iflags);
8472 buffer_add_int (buf, method->token);
8473 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8475 if (method->is_generic)
8477 if (mono_method_signature (method)->generic_param_count)
8479 buffer_add_byte (buf, attrs);
8480 if (method->is_generic || method->is_inflated) {
8483 if (method->is_generic) {
8486 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8488 result = imethod->declaring;
8489 if (imethod->context.class_inst) {
8490 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8491 /*Generic methods gets the context of the GTD.*/
8492 if (mono_class_get_context (klass)) {
8494 result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), &error);
8495 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8500 buffer_add_methodid (buf, domain, result);
8502 buffer_add_id (buf, 0);
8504 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8505 if (mono_method_signature (method)->generic_param_count) {
8508 if (method->is_inflated) {
8509 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
8511 count = inst->type_argc;
8512 buffer_add_int (buf, count);
8514 for (i = 0; i < count; i++)
8515 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8517 buffer_add_int (buf, 0);
8519 } else if (method->is_generic) {
8520 MonoGenericContainer *container = mono_method_get_generic_container (method);
8522 count = mono_method_signature (method)->generic_param_count;
8523 buffer_add_int (buf, count);
8524 for (i = 0; i < count; i++) {
8525 MonoGenericParam *param = mono_generic_container_get_param (container, i);
8526 MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
8527 buffer_add_typeid (buf, domain, pklass);
8530 buffer_add_int (buf, 0);
8533 buffer_add_int (buf, 0);
8538 case CMD_METHOD_GET_BODY: {
8541 header = mono_method_get_header (method);
8543 buffer_add_int (buf, 0);
8545 if (CHECK_PROTOCOL_VERSION (2, 18))
8546 buffer_add_int (buf, 0);
8548 buffer_add_int (buf, header->code_size);
8549 for (i = 0; i < header->code_size; ++i)
8550 buffer_add_byte (buf, header->code [i]);
8552 if (CHECK_PROTOCOL_VERSION (2, 18)) {
8553 buffer_add_int (buf, header->num_clauses);
8554 for (i = 0; i < header->num_clauses; ++i) {
8555 MonoExceptionClause *clause = &header->clauses [i];
8557 buffer_add_int (buf, clause->flags);
8558 buffer_add_int (buf, clause->try_offset);
8559 buffer_add_int (buf, clause->try_len);
8560 buffer_add_int (buf, clause->handler_offset);
8561 buffer_add_int (buf, clause->handler_len);
8562 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
8563 buffer_add_typeid (buf, domain, clause->data.catch_class);
8564 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8565 buffer_add_int (buf, clause->data.filter_offset);
8569 mono_metadata_free_mh (header);
8574 case CMD_METHOD_RESOLVE_TOKEN: {
8575 guint32 token = decode_int (p, &p, end);
8578 switch (mono_metadata_token_code (token)) {
8579 case MONO_TOKEN_STRING: {
8583 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
8586 s2 = mono_string_to_utf8 (s);
8588 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8589 buffer_add_string (buf, s2);
8595 MonoClass *handle_class;
8597 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8598 val = mono_method_get_wrapper_data (method, token);
8599 handle_class = mono_method_get_wrapper_data (method, token + 1);
8601 if (handle_class == NULL) {
8602 // Can't figure out the token type
8603 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8608 val = mono_ldtoken_checked (method->klass->image, token, &handle_class, NULL, &error);
8610 g_error ("Could not load token due to %s", mono_error_get_message (&error));
8613 if (handle_class == mono_defaults.typehandle_class) {
8614 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8615 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8616 buffer_add_typeid (buf, domain, (MonoClass *) val);
8618 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
8619 } else if (handle_class == mono_defaults.fieldhandle_class) {
8620 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8621 buffer_add_fieldid (buf, domain, val);
8622 } else if (handle_class == mono_defaults.methodhandle_class) {
8623 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8624 buffer_add_methodid (buf, domain, val);
8625 } else if (handle_class == mono_defaults.string_class) {
8628 s = mono_string_to_utf8 (val);
8629 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8630 buffer_add_string (buf, s);
8633 g_assert_not_reached ();
8640 case CMD_METHOD_GET_CATTRS: {
8641 MonoClass *attr_klass;
8642 MonoCustomAttrInfo *cinfo;
8644 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8645 /* attr_klass can be NULL */
8649 cinfo = mono_custom_attrs_from_method (method);
8651 err = buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
8656 case CMD_METHOD_MAKE_GENERIC_METHOD: {
8658 MonoType **type_argv;
8662 MonoGenericInst *ginst;
8663 MonoGenericContext tmp_context;
8664 MonoMethod *inflated;
8666 type_argc = decode_int (p, &p, end);
8667 type_argv = g_new0 (MonoType*, type_argc);
8668 for (i = 0; i < type_argc; ++i) {
8669 klass = decode_typeid (p, &p, end, &d, &err);
8676 return ERR_INVALID_ARGUMENT;
8678 type_argv [i] = &klass->byval_arg;
8680 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
8682 tmp_context.class_inst = method->klass->generic_class ? method->klass->generic_class->context.class_inst : NULL;
8683 tmp_context.method_inst = ginst;
8685 inflated = mono_class_inflate_generic_method_checked (method, &tmp_context, &error);
8686 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8687 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
8688 return ERR_INVALID_ARGUMENT;
8689 buffer_add_methodid (buf, domain, inflated);
8693 return ERR_NOT_IMPLEMENTED;
8700 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8703 MonoDomain *old_domain;
8707 method = decode_methodid (p, &p, end, &domain, &err);
8711 old_domain = mono_domain_get ();
8713 mono_domain_set (domain, TRUE);
8715 err = method_commands_internal (command, method, domain, p, end, buf);
8717 mono_domain_set (old_domain, TRUE);
8723 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8725 int objid = decode_objid (p, &p, end);
8727 MonoThread *thread_obj;
8728 MonoInternalThread *thread;
8730 err = get_object (objid, (MonoObject**)&thread_obj);
8734 thread = THREAD_TO_INTERNAL (thread_obj);
8737 case CMD_THREAD_GET_NAME: {
8739 gunichar2 *s = mono_thread_get_name (thread, &name_len);
8742 buffer_add_int (buf, 0);
8747 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
8749 buffer_add_int (buf, len);
8750 buffer_add_data (buf, (guint8*)name, len);
8755 case CMD_THREAD_GET_FRAME_INFO: {
8756 DebuggerTlsData *tls;
8757 int i, start_frame, length;
8759 // Wait for suspending if it already started
8760 // FIXME: Races with suspend_count
8761 while (!is_suspended ()) {
8763 wait_for_suspend ();
8767 wait_for_suspend ();
8768 if (!is_suspended ())
8769 return ERR_NOT_SUSPENDED;
8772 start_frame = decode_int (p, &p, end);
8773 length = decode_int (p, &p, end);
8775 if (start_frame != 0 || length != -1)
8776 return ERR_NOT_IMPLEMENTED;
8778 mono_loader_lock ();
8779 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8780 mono_loader_unlock ();
8783 compute_frame_info (thread, tls);
8785 buffer_add_int (buf, tls->frame_count);
8786 for (i = 0; i < tls->frame_count; ++i) {
8787 buffer_add_int (buf, tls->frames [i]->id);
8788 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
8789 buffer_add_int (buf, tls->frames [i]->il_offset);
8791 * Instead of passing the frame type directly to the client, we associate
8792 * it with the previous frame using a set of flags. This avoids lots of
8793 * conditional code in the client, since a frame whose type isn't
8794 * FRAME_TYPE_MANAGED has no method, location, etc.
8796 buffer_add_byte (buf, tls->frames [i]->flags);
8801 case CMD_THREAD_GET_STATE:
8802 buffer_add_int (buf, thread->state);
8804 case CMD_THREAD_GET_INFO:
8805 buffer_add_byte (buf, thread->threadpool_thread);
8807 case CMD_THREAD_GET_ID:
8808 buffer_add_long (buf, (guint64)(gsize)thread);
8810 case CMD_THREAD_GET_TID:
8811 buffer_add_long (buf, (guint64)thread->tid);
8813 case CMD_THREAD_SET_IP: {
8814 DebuggerTlsData *tls;
8817 MonoSeqPointInfo *seq_points;
8822 method = decode_methodid (p, &p, end, &domain, &err);
8825 il_offset = decode_long (p, &p, end);
8827 while (!is_suspended ()) {
8829 wait_for_suspend ();
8832 mono_loader_lock ();
8833 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8834 mono_loader_unlock ();
8837 compute_frame_info (thread, tls);
8838 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
8839 return ERR_INVALID_ARGUMENT;
8841 found_sp = mono_find_seq_point (domain, method, il_offset, &seq_points, &sp);
8843 g_assert (seq_points);
8846 return ERR_INVALID_ARGUMENT;
8848 // FIXME: Check that the ip change is safe
8850 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);
8851 MONO_CONTEXT_SET_IP (&tls->restore_state.ctx, (guint8*)tls->frames [0]->ji->code_start + sp.native_offset);
8855 return ERR_NOT_IMPLEMENTED;
8862 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8866 MonoThread *thread_obj;
8867 MonoInternalThread *thread;
8868 int pos, i, len, frame_idx;
8869 DebuggerTlsData *tls;
8871 MonoDebugMethodJitInfo *jit;
8872 MonoMethodSignature *sig;
8874 MonoMethodHeader *header;
8876 objid = decode_objid (p, &p, end);
8877 err = get_object (objid, (MonoObject**)&thread_obj);
8881 thread = THREAD_TO_INTERNAL (thread_obj);
8883 id = decode_id (p, &p, end);
8885 mono_loader_lock ();
8886 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8887 mono_loader_unlock ();
8890 for (i = 0; i < tls->frame_count; ++i) {
8891 if (tls->frames [i]->id == id)
8894 if (i == tls->frame_count)
8895 return ERR_INVALID_FRAMEID;
8898 frame = tls->frames [frame_idx];
8900 /* This is supported for frames without has_ctx etc. set */
8901 if (command == CMD_STACK_FRAME_GET_DOMAIN) {
8902 if (CHECK_PROTOCOL_VERSION (2, 38))
8903 buffer_add_domainid (buf, frame->domain);
8907 if (!frame->has_ctx)
8908 return ERR_ABSENT_INFORMATION;
8911 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
8912 if (!frame->jit && frame->api_method->is_inflated)
8913 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
8917 /* This could happen for aot images with no jit debug info */
8918 s = mono_method_full_name (frame->api_method, TRUE);
8919 DEBUG_PRINTF (1, "[dbg] No debug information found for '%s'.\n", s);
8921 return ERR_ABSENT_INFORMATION;
8926 sig = mono_method_signature (frame->actual_method);
8928 if (!mono_get_seq_points (frame->domain, frame->actual_method))
8930 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
8932 return ERR_ABSENT_INFORMATION;
8935 case CMD_STACK_FRAME_GET_VALUES: {
8936 len = decode_int (p, &p, end);
8937 header = mono_method_get_header (frame->actual_method);
8939 for (i = 0; i < len; ++i) {
8940 pos = decode_int (p, &p, end);
8945 g_assert (pos >= 0 && pos < jit->num_params);
8947 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
8949 g_assert (pos >= 0 && pos < jit->num_locals);
8951 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
8954 mono_metadata_free_mh (header);
8957 case CMD_STACK_FRAME_GET_THIS: {
8958 if (frame->api_method->klass->valuetype) {
8959 if (!sig->hasthis) {
8960 MonoObject *p = NULL;
8961 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
8963 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8966 if (!sig->hasthis) {
8967 MonoObject *p = NULL;
8968 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
8970 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8975 case CMD_STACK_FRAME_SET_VALUES: {
8978 MonoDebugVarInfo *var;
8980 len = decode_int (p, &p, end);
8981 header = mono_method_get_header (frame->actual_method);
8983 for (i = 0; i < len; ++i) {
8984 pos = decode_int (p, &p, end);
8989 g_assert (pos >= 0 && pos < jit->num_params);
8991 t = sig->params [pos];
8992 var = &jit->params [pos];
8994 g_assert (pos >= 0 && pos < jit->num_locals);
8996 t = header->locals [pos];
8997 var = &jit->locals [pos];
9000 if (MONO_TYPE_IS_REFERENCE (t))
9001 val_buf = g_alloca (sizeof (MonoObject*));
9003 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9004 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9008 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9010 mono_metadata_free_mh (header);
9013 case CMD_STACK_FRAME_GET_DOMAIN: {
9014 if (CHECK_PROTOCOL_VERSION (2, 38))
9015 buffer_add_domainid (buf, frame->domain);
9019 return ERR_NOT_IMPLEMENTED;
9026 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9029 int objid, err, index, len, i, esize;
9032 objid = decode_objid (p, &p, end);
9033 err = get_object (objid, (MonoObject**)&arr);
9038 case CMD_ARRAY_REF_GET_LENGTH:
9039 buffer_add_int (buf, arr->obj.vtable->klass->rank);
9041 buffer_add_int (buf, arr->max_length);
9042 buffer_add_int (buf, 0);
9044 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
9045 buffer_add_int (buf, arr->bounds [i].length);
9046 buffer_add_int (buf, arr->bounds [i].lower_bound);
9050 case CMD_ARRAY_REF_GET_VALUES:
9051 index = decode_int (p, &p, end);
9052 len = decode_int (p, &p, end);
9054 g_assert (index >= 0 && len >= 0);
9055 // Reordered to avoid integer overflow
9056 g_assert (!(index > arr->max_length - len));
9058 esize = mono_array_element_size (arr->obj.vtable->klass);
9059 for (i = index; i < index + len; ++i) {
9060 elem = (gpointer*)((char*)arr->vector + (i * esize));
9061 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
9064 case CMD_ARRAY_REF_SET_VALUES:
9065 index = decode_int (p, &p, end);
9066 len = decode_int (p, &p, end);
9068 g_assert (index >= 0 && len >= 0);
9069 // Reordered to avoid integer overflow
9070 g_assert (!(index > arr->max_length - len));
9072 esize = mono_array_element_size (arr->obj.vtable->klass);
9073 for (i = index; i < index + len; ++i) {
9074 elem = (gpointer*)((char*)arr->vector + (i * esize));
9076 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
9080 return ERR_NOT_IMPLEMENTED;
9087 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9092 int i, index, length;
9095 objid = decode_objid (p, &p, end);
9096 err = get_object (objid, (MonoObject**)&str);
9101 case CMD_STRING_REF_GET_VALUE:
9102 s = mono_string_to_utf8 (str);
9103 buffer_add_string (buf, s);
9106 case CMD_STRING_REF_GET_LENGTH:
9107 buffer_add_long (buf, mono_string_length (str));
9109 case CMD_STRING_REF_GET_CHARS:
9110 index = decode_long (p, &p, end);
9111 length = decode_long (p, &p, end);
9112 if (index > mono_string_length (str) - length)
9113 return ERR_INVALID_ARGUMENT;
9114 c = mono_string_chars (str) + index;
9115 for (i = 0; i < length; ++i)
9116 buffer_add_short (buf, c [i]);
9119 return ERR_NOT_IMPLEMENTED;
9126 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9135 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9136 objid = decode_objid (p, &p, end);
9137 err = get_object (objid, &obj);
9139 buffer_add_int (buf, 1);
9141 buffer_add_int (buf, 0);
9145 objid = decode_objid (p, &p, end);
9146 err = get_object (objid, &obj);
9151 case CMD_OBJECT_REF_GET_TYPE:
9152 /* This handles transparent proxies too */
9153 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9155 case CMD_OBJECT_REF_GET_VALUES:
9156 len = decode_int (p, &p, end);
9158 for (i = 0; i < len; ++i) {
9159 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9163 /* Check that the field belongs to the object */
9165 for (k = obj->vtable->klass; k; k = k->parent) {
9166 if (k == f->parent) {
9172 return ERR_INVALID_FIELDID;
9174 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9178 if (mono_class_field_is_special_static (f))
9179 return ERR_INVALID_FIELDID;
9181 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9182 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9183 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9184 mono_field_static_get_value (vtable, f, val);
9185 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9188 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
9192 case CMD_OBJECT_REF_SET_VALUES:
9193 len = decode_int (p, &p, end);
9195 for (i = 0; i < len; ++i) {
9196 f = decode_fieldid (p, &p, end, NULL, &err);
9200 /* Check that the field belongs to the object */
9202 for (k = obj->vtable->klass; k; k = k->parent) {
9203 if (k == f->parent) {
9209 return ERR_INVALID_FIELDID;
9211 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9215 if (mono_class_field_is_special_static (f))
9216 return ERR_INVALID_FIELDID;
9218 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9219 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9221 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9222 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
9227 mono_field_static_set_value (vtable, f, val);
9230 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
9236 case CMD_OBJECT_REF_GET_ADDRESS:
9237 buffer_add_long (buf, (gssize)obj);
9239 case CMD_OBJECT_REF_GET_DOMAIN:
9240 buffer_add_domainid (buf, obj->vtable->domain);
9242 case CMD_OBJECT_REF_GET_INFO:
9243 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9244 buffer_add_domainid (buf, obj->vtable->domain);
9247 return ERR_NOT_IMPLEMENTED;
9254 command_set_to_string (CommandSet command_set)
9256 switch (command_set) {
9259 case CMD_SET_OBJECT_REF:
9260 return "OBJECT_REF";
9261 case CMD_SET_STRING_REF:
9262 return "STRING_REF";
9263 case CMD_SET_THREAD:
9265 case CMD_SET_ARRAY_REF:
9267 case CMD_SET_EVENT_REQUEST:
9268 return "EVENT_REQUEST";
9269 case CMD_SET_STACK_FRAME:
9270 return "STACK_FRAME";
9271 case CMD_SET_APPDOMAIN:
9273 case CMD_SET_ASSEMBLY:
9275 case CMD_SET_METHOD:
9279 case CMD_SET_MODULE:
9290 static const char* vm_cmds_str [] = {
9298 "SET_PROTOCOL_VERSION",
9301 "GET_TYPES_FOR_SOURCE_FILE",
9306 static const char* thread_cmds_str[] = {
9316 static const char* event_cmds_str[] = {
9319 "REQUEST_CLEAR_ALL_BREAKPOINTS"
9322 static const char* appdomain_cmds_str[] = {
9324 "GET_FRIENDLY_NAME",
9326 "GET_ENTRY_ASSEMBLY",
9329 "CREATE_BOXED_VALUE"
9332 static const char* assembly_cmds_str[] = {
9335 "GET_MANIFEST_MODULE",
9341 static const char* module_cmds_str[] = {
9345 static const char* field_cmds_str[] = {
9349 static const char* method_cmds_str[] = {
9351 "GET_DECLARING_TYPE",
9359 "MAKE_GENERIC_METHOD"
9362 static const char* type_cmds_str[] = {
9370 "IS_ASSIGNABLE_FROM",
9374 "GET_PROPERTY_CATTRS",
9375 "GET_SOURCE_FILES_2",
9377 "GET_METHODS_BY_NAME_FLAGS",
9379 "GET_INTERFACE_MAP",
9383 static const char* stack_frame_cmds_str[] = {
9390 static const char* array_cmds_str[] = {
9396 static const char* string_cmds_str[] = {
9402 static const char* object_cmds_str[] = {
9413 cmd_to_string (CommandSet set, int command)
9421 cmds_len = G_N_ELEMENTS (vm_cmds_str);
9423 case CMD_SET_OBJECT_REF:
9424 cmds = object_cmds_str;
9425 cmds_len = G_N_ELEMENTS (object_cmds_str);
9427 case CMD_SET_STRING_REF:
9428 cmds = string_cmds_str;
9429 cmds_len = G_N_ELEMENTS (string_cmds_str);
9431 case CMD_SET_THREAD:
9432 cmds = thread_cmds_str;
9433 cmds_len = G_N_ELEMENTS (thread_cmds_str);
9435 case CMD_SET_ARRAY_REF:
9436 cmds = array_cmds_str;
9437 cmds_len = G_N_ELEMENTS (array_cmds_str);
9439 case CMD_SET_EVENT_REQUEST:
9440 cmds = event_cmds_str;
9441 cmds_len = G_N_ELEMENTS (event_cmds_str);
9443 case CMD_SET_STACK_FRAME:
9444 cmds = stack_frame_cmds_str;
9445 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
9447 case CMD_SET_APPDOMAIN:
9448 cmds = appdomain_cmds_str;
9449 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
9451 case CMD_SET_ASSEMBLY:
9452 cmds = assembly_cmds_str;
9453 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
9455 case CMD_SET_METHOD:
9456 cmds = method_cmds_str;
9457 cmds_len = G_N_ELEMENTS (method_cmds_str);
9460 cmds = type_cmds_str;
9461 cmds_len = G_N_ELEMENTS (type_cmds_str);
9463 case CMD_SET_MODULE:
9464 cmds = module_cmds_str;
9465 cmds_len = G_N_ELEMENTS (module_cmds_str);
9468 cmds = field_cmds_str;
9469 cmds_len = G_N_ELEMENTS (field_cmds_str);
9472 cmds = event_cmds_str;
9473 cmds_len = G_N_ELEMENTS (event_cmds_str);
9478 if (command > 0 && command <= cmds_len)
9479 return cmds [command - 1];
9485 wait_for_attach (void)
9487 #ifndef DISABLE_SOCKET_TRANSPORT
9488 if (listen_fd == -1) {
9489 DEBUG_PRINTF (1, "[dbg] Invalid listening socket\n");
9493 /* Block and wait for client connection */
9494 MONO_PREPARE_BLOCKING
9495 conn_fd = socket_transport_accept (listen_fd);
9496 MONO_FINISH_BLOCKING
9498 DEBUG_PRINTF (1, "Accepted connection on %d\n", conn_fd);
9499 if (conn_fd == -1) {
9500 DEBUG_PRINTF (1, "[dbg] Bad client connection\n");
9504 g_assert_not_reached ();
9508 disconnected = !transport_handshake ();
9510 DEBUG_PRINTF (1, "Transport handshake failed!\n");
9520 * This thread handles communication with the debugger client using a JDWP
9523 static guint32 WINAPI
9524 debugger_thread (void *arg)
9526 int res, len, id, flags, command_set = 0, command = 0;
9527 guint8 header [HEADER_LENGTH];
9528 guint8 *data, *p, *end;
9532 gboolean attach_failed = FALSE;
9534 DEBUG_PRINTF (1, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ());
9536 debugger_thread_id = GetCurrentThreadId ();
9538 mono_jit_thread_attach (mono_get_root_domain ());
9540 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
9542 mono_set_is_debugger_attached (TRUE);
9544 if (agent_config.defer) {
9545 if (!wait_for_attach ()) {
9546 DEBUG_PRINTF (1, "[dbg] Can't attach, aborting debugger thread.\n");
9547 attach_failed = TRUE; // Don't abort process when we can't listen
9549 /* Send start event to client */
9550 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
9554 while (!attach_failed) {
9555 MONO_PREPARE_BLOCKING
9556 res = transport_recv (header, HEADER_LENGTH);
9557 MONO_FINISH_BLOCKING
9559 /* This will break if the socket is closed during shutdown too */
9560 if (res != HEADER_LENGTH) {
9561 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH);
9566 end = header + HEADER_LENGTH;
9568 len = decode_int (p, &p, end);
9569 id = decode_int (p, &p, end);
9570 flags = decode_byte (p, &p, end);
9571 command_set = decode_byte (p, &p, end);
9572 command = decode_byte (p, &p, end);
9574 g_assert (flags == 0);
9577 const char *cmd_str;
9580 cmd_str = cmd_to_string (command_set, command);
9582 sprintf (cmd_num, "%d", command);
9586 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);
9589 data = g_malloc (len - HEADER_LENGTH);
9590 if (len - HEADER_LENGTH > 0)
9592 MONO_PREPARE_BLOCKING
9593 res = transport_recv (data, len - HEADER_LENGTH);
9594 MONO_FINISH_BLOCKING
9595 if (res != len - HEADER_LENGTH) {
9596 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH);
9602 end = data + (len - HEADER_LENGTH);
9604 buffer_init (&buf, 128);
9609 /* Process the request */
9610 switch (command_set) {
9612 err = vm_commands (command, id, p, end, &buf);
9613 if (!err && command == CMD_VM_INVOKE_METHOD)
9614 /* Sent after the invoke is complete */
9617 case CMD_SET_EVENT_REQUEST:
9618 err = event_commands (command, p, end, &buf);
9620 case CMD_SET_APPDOMAIN:
9621 err = domain_commands (command, p, end, &buf);
9623 case CMD_SET_ASSEMBLY:
9624 err = assembly_commands (command, p, end, &buf);
9626 case CMD_SET_MODULE:
9627 err = module_commands (command, p, end, &buf);
9630 err = field_commands (command, p, end, &buf);
9633 err = type_commands (command, p, end, &buf);
9635 case CMD_SET_METHOD:
9636 err = method_commands (command, p, end, &buf);
9638 case CMD_SET_THREAD:
9639 err = thread_commands (command, p, end, &buf);
9641 case CMD_SET_STACK_FRAME:
9642 err = frame_commands (command, p, end, &buf);
9644 case CMD_SET_ARRAY_REF:
9645 err = array_commands (command, p, end, &buf);
9647 case CMD_SET_STRING_REF:
9648 err = string_commands (command, p, end, &buf);
9650 case CMD_SET_OBJECT_REF:
9651 err = object_commands (command, p, end, &buf);
9654 err = ERR_NOT_IMPLEMENTED;
9657 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
9658 buffer_replies = TRUE;
9662 if (buffer_replies) {
9663 buffer_reply_packet (id, err, &buf);
9665 send_reply_packet (id, err, &buf);
9666 //DEBUG_PRINTF (1, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000);
9670 if (!err && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
9671 send_buffered_reply_packets ();
9672 buffer_replies = FALSE;
9678 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
9682 mono_set_is_debugger_attached (FALSE);
9685 mono_mutex_lock (&debugger_thread_exited_mutex);
9686 debugger_thread_exited = TRUE;
9687 mono_cond_signal (&debugger_thread_exited_cond);
9688 mono_mutex_unlock (&debugger_thread_exited_mutex);
9689 MONO_FINISH_TRY_BLOCKING
9691 DEBUG_PRINTF (1, "[dbg] Debugger thread exited.\n");
9693 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
9694 DEBUG_PRINTF (2, "[dbg] Detached - restarting clean debugger thread.\n");
9695 start_debugger_thread ();
9701 #else /* DISABLE_DEBUGGER_AGENT */
9704 mono_debugger_agent_parse_options (char *options)
9706 g_error ("This runtime is configured with the debugger agent disabled.");
9710 mono_debugger_agent_init (void)
9715 mono_debugger_agent_breakpoint_hit (void *sigctx)
9720 mono_debugger_agent_single_step_event (void *sigctx)
9725 mono_debugger_agent_free_domain_info (MonoDomain *domain)
9730 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
9731 MonoContext *catch_ctx)
9736 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9741 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9746 mono_debugger_agent_user_break (void)
9752 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
9757 mono_debugger_agent_debug_log_is_enabled (void)
9763 mono_debugger_agent_unhandled_exception (MonoException *exc)
9765 g_assert_not_reached ();
9769 debugger_agent_single_step_from_context (MonoContext *ctx)
9771 g_assert_not_reached ();
9775 debugger_agent_breakpoint_from_context (MonoContext *ctx)
9777 g_assert_not_reached ();