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.
1610 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
1613 //WaitForSingleObject (debugger_thread_handle, INFINITE);
1614 if (GetCurrentThreadId () != debugger_thread_id) {
1617 mono_mutex_lock (&debugger_thread_exited_mutex);
1618 if (!debugger_thread_exited) {
1620 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
1621 mono_mutex_unlock (&debugger_thread_exited_mutex);
1623 mono_mutex_lock (&debugger_thread_exited_mutex);
1626 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1629 mono_mutex_unlock (&debugger_thread_exited_mutex);
1630 MONO_FINISH_TRY_BLOCKING
1631 } while (!debugger_thread_exited);
1634 MONO_PREPARE_BLOCKING
1635 transport_close2 ();
1636 MONO_FINISH_BLOCKING
1640 start_debugger_thread (void)
1642 debugger_thread_handle = mono_threads_create_thread (debugger_thread, NULL, 0, 0, NULL);
1643 g_assert (debugger_thread_handle);
1647 * Functions to decode protocol data
1651 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1654 g_assert (*endbuf <= limit);
1659 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1662 g_assert (*endbuf <= limit);
1664 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1667 static inline gint64
1668 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1670 guint32 high = decode_int (buf, &buf, limit);
1671 guint32 low = decode_int (buf, &buf, limit);
1675 return ((((guint64)high) << 32) | ((guint64)low));
1679 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1681 return decode_int (buf, endbuf, limit);
1685 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1687 int len = decode_int (buf, &buf, limit);
1695 s = g_malloc (len + 1);
1698 memcpy (s, buf, len);
1707 * Functions to encode protocol data
1711 buffer_init (Buffer *buf, int size)
1713 buf->buf = g_malloc (size);
1715 buf->end = buf->buf + size;
1719 buffer_len (Buffer *buf)
1721 return buf->p - buf->buf;
1725 buffer_make_room (Buffer *buf, int size)
1727 if (buf->end - buf->p < size) {
1728 int new_size = buf->end - buf->buf + size + 32;
1729 guint8 *p = g_realloc (buf->buf, new_size);
1730 size = buf->p - buf->buf;
1733 buf->end = buf->buf + new_size;
1738 buffer_add_byte (Buffer *buf, guint8 val)
1740 buffer_make_room (buf, 1);
1746 buffer_add_short (Buffer *buf, guint32 val)
1748 buffer_make_room (buf, 2);
1749 buf->p [0] = (val >> 8) & 0xff;
1750 buf->p [1] = (val >> 0) & 0xff;
1755 buffer_add_int (Buffer *buf, guint32 val)
1757 buffer_make_room (buf, 4);
1758 buf->p [0] = (val >> 24) & 0xff;
1759 buf->p [1] = (val >> 16) & 0xff;
1760 buf->p [2] = (val >> 8) & 0xff;
1761 buf->p [3] = (val >> 0) & 0xff;
1766 buffer_add_long (Buffer *buf, guint64 l)
1768 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1769 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1773 buffer_add_id (Buffer *buf, int id)
1775 buffer_add_int (buf, (guint64)id);
1779 buffer_add_data (Buffer *buf, guint8 *data, int len)
1781 buffer_make_room (buf, len);
1782 memcpy (buf->p, data, len);
1787 buffer_add_string (Buffer *buf, const char *str)
1792 buffer_add_int (buf, 0);
1795 buffer_add_int (buf, len);
1796 buffer_add_data (buf, (guint8*)str, len);
1801 buffer_add_buffer (Buffer *buf, Buffer *data)
1803 buffer_add_data (buf, data->buf, buffer_len (data));
1807 buffer_free (Buffer *buf)
1813 send_packet (int command_set, int command, Buffer *data)
1819 id = InterlockedIncrement (&packet_id);
1821 len = data->p - data->buf + 11;
1822 buffer_init (&buf, len);
1823 buffer_add_int (&buf, len);
1824 buffer_add_int (&buf, id);
1825 buffer_add_byte (&buf, 0); /* flags */
1826 buffer_add_byte (&buf, command_set);
1827 buffer_add_byte (&buf, command);
1828 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1830 MONO_PREPARE_BLOCKING
1831 res = transport_send (buf.buf, len);
1832 MONO_FINISH_BLOCKING
1840 send_reply_packets (int npackets, ReplyPacket *packets)
1847 for (i = 0; i < npackets; ++i)
1848 len += buffer_len (packets [i].data) + 11;
1849 buffer_init (&buf, len);
1850 for (i = 0; i < npackets; ++i) {
1851 buffer_add_int (&buf, buffer_len (packets [i].data) + 11);
1852 buffer_add_int (&buf, packets [i].id);
1853 buffer_add_byte (&buf, 0x80); /* flags */
1854 buffer_add_byte (&buf, (packets [i].error >> 8) & 0xff);
1855 buffer_add_byte (&buf, packets [i].error);
1856 buffer_add_buffer (&buf, packets [i].data);
1859 MONO_PREPARE_BLOCKING
1860 res = transport_send (buf.buf, len);
1861 MONO_FINISH_BLOCKING
1869 send_reply_packet (int id, int error, Buffer *data)
1873 memset (&packet, 0, sizeof (ReplyPacket));
1875 packet.error = error;
1878 return send_reply_packets (1, &packet);
1882 send_buffered_reply_packets (void)
1886 send_reply_packets (nreply_packets, reply_packets);
1887 for (i = 0; i < nreply_packets; ++i)
1888 buffer_free (reply_packets [i].data);
1889 DEBUG_PRINTF (1, "[dbg] Sent %d buffered reply packets [at=%lx].\n", nreply_packets, (long)mono_100ns_ticks () / 10000);
1894 buffer_reply_packet (int id, int error, Buffer *data)
1898 if (nreply_packets == 128)
1899 send_buffered_reply_packets ();
1901 p = &reply_packets [nreply_packets];
1904 p->data = g_new0 (Buffer, 1);
1905 buffer_init (p->data, buffer_len (data));
1906 buffer_add_buffer (p->data, data);
1915 * Represents an object accessible by the debugger client.
1918 /* Unique id used in the wire protocol to refer to objects */
1921 * A weakref gc handle pointing to the object. The gc handle is used to
1922 * detect if the object was garbage collected.
1927 /* Maps objid -> ObjRef */
1928 static GHashTable *objrefs;
1929 static GHashTable *obj_to_objref;
1930 /* Protected by the dbg lock */
1931 static MonoGHashTable *suspended_objs;
1934 free_objref (gpointer value)
1938 mono_gchandle_free (o->handle);
1946 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1947 obj_to_objref = g_hash_table_new (NULL, NULL);
1948 suspended_objs = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
1949 MONO_GC_REGISTER_ROOT_FIXED (suspended_objs);
1953 objrefs_cleanup (void)
1955 g_hash_table_destroy (objrefs);
1960 * Return an ObjRef for OBJ.
1963 get_objref (MonoObject *obj)
1966 GSList *reflist = NULL, *l;
1972 if (suspend_count) {
1974 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1977 mono_g_hash_table_insert (suspended_objs, obj, NULL);
1981 mono_loader_lock ();
1983 /* FIXME: The tables can grow indefinitely */
1985 if (mono_gc_is_moving ()) {
1987 * Objects can move, so use a hash table mapping hash codes to lists of
1988 * ObjRef structures.
1990 hash = mono_object_hash (obj);
1992 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1993 for (l = reflist; l; l = l->next) {
1995 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1996 mono_loader_unlock ();
2001 /* Use a hash table with masked pointers to internalize object references */
2002 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
2003 /* ref might refer to a different object with the same addr which was GCd */
2004 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
2005 mono_loader_unlock ();
2010 ref = g_new0 (ObjRef, 1);
2011 ref->id = InterlockedIncrement (&objref_id);
2012 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
2014 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
2016 if (mono_gc_is_moving ()) {
2017 reflist = g_slist_append (reflist, ref);
2018 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
2020 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
2023 mono_loader_unlock ();
2029 true_pred (gpointer key, gpointer value, gpointer user_data)
2035 clear_suspended_objs (void)
2038 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
2043 get_objid (MonoObject *obj)
2045 return get_objref (obj)->id;
2049 * Set OBJ to the object identified by OBJID.
2050 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
2054 get_object_allow_null (int objid, MonoObject **obj)
2064 return ERR_INVALID_OBJECT;
2066 mono_loader_lock ();
2068 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
2071 *obj = mono_gchandle_get_target (ref->handle);
2072 mono_loader_unlock ();
2074 return ERR_INVALID_OBJECT;
2077 mono_loader_unlock ();
2078 return ERR_INVALID_OBJECT;
2083 get_object (int objid, MonoObject **obj)
2085 int err = get_object_allow_null (objid, obj);
2090 return ERR_INVALID_OBJECT;
2095 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
2097 return decode_id (buf, endbuf, limit);
2101 buffer_add_objid (Buffer *buf, MonoObject *o)
2103 buffer_add_id (buf, get_objid (o));
2122 * Represents a runtime structure accessible to the debugger client
2125 /* Unique id used in the wire protocol */
2127 /* Domain of the runtime structure, NULL if the domain was unloaded */
2134 MonoAssembly *assembly;
2135 MonoClassField *field;
2137 MonoProperty *property;
2142 /* Maps runtime structure -> Id */
2143 GHashTable *val_to_id [ID_NUM];
2144 /* Classes whose class load event has been sent */
2145 GHashTable *loaded_classes;
2146 /* Maps MonoClass->GPtrArray of file names */
2147 GHashTable *source_files;
2148 /* Maps source file basename -> GSList of classes */
2149 GHashTable *source_file_to_class;
2150 /* Same with ignore-case */
2151 GHashTable *source_file_to_class_ignorecase;
2155 /* Protected by the dbg lock */
2156 static GPtrArray *ids [ID_NUM];
2163 for (i = 0; i < ID_NUM; ++i)
2164 ids [i] = g_ptr_array_new ();
2172 for (i = 0; i < ID_NUM; ++i) {
2174 for (j = 0; j < ids [i]->len; ++j)
2175 g_free (g_ptr_array_index (ids [i], j));
2176 g_ptr_array_free (ids [i], TRUE);
2183 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2185 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
2187 GHashTableIter iter;
2188 GPtrArray *file_names;
2193 for (i = 0; i < ID_NUM; ++i)
2194 if (info->val_to_id [i])
2195 g_hash_table_destroy (info->val_to_id [i]);
2196 g_hash_table_destroy (info->loaded_classes);
2198 g_hash_table_iter_init (&iter, info->source_files);
2199 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2200 for (i = 0; i < file_names->len; ++i)
2201 g_free (g_ptr_array_index (file_names, i));
2202 g_ptr_array_free (file_names, TRUE);
2205 g_hash_table_iter_init (&iter, info->source_file_to_class);
2206 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2211 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2212 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2220 domain_jit_info (domain)->agent_info = NULL;
2222 /* Clear ids referencing structures in the domain */
2224 for (i = 0; i < ID_NUM; ++i) {
2226 for (j = 0; j < ids [i]->len; ++j) {
2227 Id *id = g_ptr_array_index (ids [i], j);
2228 if (id->domain == domain)
2235 mono_loader_lock ();
2236 g_hash_table_remove (domains, domain);
2237 mono_loader_unlock ();
2240 static AgentDomainInfo*
2241 get_agent_domain_info (MonoDomain *domain)
2243 AgentDomainInfo *info = NULL;
2245 mono_domain_lock (domain);
2247 info = domain_jit_info (domain)->agent_info;
2249 info = domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
2250 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2251 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2252 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2253 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2256 mono_domain_unlock (domain);
2262 get_id (MonoDomain *domain, IdType type, gpointer val)
2265 AgentDomainInfo *info;
2270 mono_loader_lock ();
2272 mono_domain_lock (domain);
2274 info = get_agent_domain_info (domain);
2276 if (info->val_to_id [type] == NULL)
2277 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2279 id = g_hash_table_lookup (info->val_to_id [type], val);
2281 mono_domain_unlock (domain);
2282 mono_loader_unlock ();
2288 id = g_new0 (Id, 1);
2290 id->id = ids [type]->len + 1;
2291 id->domain = domain;
2294 g_hash_table_insert (info->val_to_id [type], val, id);
2295 g_ptr_array_add (ids [type], id);
2299 mono_domain_unlock (domain);
2301 mono_loader_unlock ();
2306 static inline gpointer
2307 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
2311 int id = decode_id (buf, endbuf, limit);
2320 // FIXME: error handling
2322 g_assert (id > 0 && id <= ids [type]->len);
2324 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2327 if (res->domain == NULL) {
2328 DEBUG_PRINTF (1, "ERR_UNLOADED, id=%d, type=%d.\n", id, type);
2329 *err = ERR_UNLOADED;
2334 *domain = res->domain;
2336 return res->data.val;
2340 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2342 int id = get_id (domain, type, val);
2344 buffer_add_id (buf, id);
2348 static inline MonoClass*
2349 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2353 klass = decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2354 if (G_UNLIKELY (log_level >= 2) && klass) {
2357 s = mono_type_full_name (&klass->byval_arg);
2358 DEBUG_PRINTF (2, "[dbg] recv class [%s]\n", s);
2364 static inline MonoAssembly*
2365 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2367 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2370 static inline MonoImage*
2371 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2373 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2376 static inline MonoMethod*
2377 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2381 m = decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2382 if (G_UNLIKELY (log_level >= 2) && m) {
2385 s = mono_method_full_name (m, TRUE);
2386 DEBUG_PRINTF (2, "[dbg] recv method [%s]\n", s);
2392 static inline MonoClassField*
2393 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2395 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2398 static inline MonoDomain*
2399 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2401 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2404 static inline MonoProperty*
2405 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2407 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2411 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2413 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2414 if (G_UNLIKELY (log_level >= 2) && klass) {
2417 s = mono_type_full_name (&klass->byval_arg);
2418 if (GetCurrentThreadId () == debugger_thread_id)
2419 DEBUG_PRINTF (2, "[dbg] send class [%s]\n", s);
2421 DEBUG_PRINTF (2, "[%p] send class [%s]\n", (gpointer)GetCurrentThreadId (), s);
2427 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2429 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2430 if (G_UNLIKELY (log_level >= 2) && method) {
2433 s = mono_method_full_name (method, 1);
2434 DEBUG_PRINTF (2, "[dbg] send method [%s]\n", s);
2440 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2444 id = buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2445 if (G_UNLIKELY (log_level >= 2) && assembly)
2446 DEBUG_PRINTF (2, "[dbg] send assembly [%s][%s][%d]\n", assembly->aname.name, domain->friendly_name, id);
2450 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2452 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2456 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2458 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2462 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2464 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2468 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2470 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2473 static void invoke_method (void);
2480 * save_thread_context:
2482 * Set CTX as the current threads context which is used for computing stack traces.
2483 * This function is signal-safe.
2486 save_thread_context (MonoContext *ctx)
2488 DebuggerTlsData *tls;
2490 tls = mono_native_tls_get_value (debugger_tls_id);
2494 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2496 mono_thread_state_init_from_current (&tls->context);
2499 /* Number of threads suspended */
2501 * If this is equal to the size of thread_to_tls, the runtime is considered
2504 static gint32 threads_suspend_count;
2506 static mono_mutex_t suspend_mutex;
2508 /* Cond variable used to wait for suspend_count becoming 0 */
2509 static mono_cond_t suspend_cond;
2511 /* Semaphore used to wait for a thread becoming suspended */
2512 static MonoSemType suspend_sem;
2517 mono_mutex_init (&suspend_mutex);
2518 mono_cond_init (&suspend_cond, NULL);
2519 MONO_SEM_INIT (&suspend_sem, 0);
2524 StackFrameInfo last_frame;
2525 gboolean last_frame_set;
2528 } GetLastFrameUserData;
2531 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2533 GetLastFrameUserData *data = user_data;
2535 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
2538 if (!data->last_frame_set) {
2539 /* Store the last frame */
2540 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2541 data->last_frame_set = TRUE;
2544 /* Store the context/lmf for the frame above the last frame */
2545 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2546 data->lmf = info->lmf;
2554 * Process interruption of a thread. This should be signal safe.
2557 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, MonoJitInfo *ji)
2561 MonoNativeThreadId tid;
2565 ip = MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx);
2566 tid = mono_thread_info_get_tid (info);
2568 // FIXME: Races when the thread leaves managed code before hitting a single step
2572 /* Running managed code, will be suspended by the single step code */
2573 DEBUG_PRINTF (1, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip);
2576 * Running native code, will be suspended when it returns to/enters
2577 * managed code. Treat it as already suspended.
2578 * This might interrupt the code in process_single_step_inner (), we use the
2579 * tls->suspending flag to avoid races when that happens.
2581 if (!tls->suspended && !tls->suspending) {
2583 GetLastFrameUserData data;
2585 // FIXME: printf is not signal safe, but this is only used during
2586 // debugger debugging
2588 DEBUG_PRINTF (1, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip);
2589 //save_thread_context (&ctx);
2592 /* Already terminated */
2596 * We are in a difficult position: we want to be able to provide stack
2597 * traces for this thread, but we can't use the current ctx+lmf, since
2598 * the thread is still running, so it might return to managed code,
2599 * making these invalid.
2600 * So we start a stack walk and save the first frame, along with the
2601 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2602 * suspended when it returns to managed code, so the parent's ctx should
2605 data.last_frame_set = FALSE;
2606 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, mono_thread_info_get_suspend_state (info), MONO_UNWIND_SIGNAL_SAFE, &data);
2607 if (data.last_frame_set) {
2608 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2609 res = mono_thread_state_init_from_monoctx (&tls->async_state, &ctx);
2611 mono_thread_state_init_from_monoctx (&tls->context, &ctx);
2614 memcpy (&tls->async_state.ctx, &data.ctx, sizeof (MonoContext));
2615 tls->async_state.unwind_data [MONO_UNWIND_DATA_LMF] = data.lmf;
2616 tls->async_state.unwind_data [MONO_UNWIND_DATA_JIT_TLS] = ((MonoThreadInfo*)tls->thread->thread_info)->jit_data;
2618 tls->async_state.valid = FALSE;
2621 mono_memory_barrier ();
2623 tls->suspended = TRUE;
2624 MONO_SEM_POST (&suspend_sem);
2630 * reset_native_thread_suspend_state:
2632 * Reset the suspended flag and state on native threads
2635 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2637 DebuggerTlsData *tls = value;
2639 if (!tls->really_suspended && tls->suspended) {
2640 tls->suspended = FALSE;
2642 * The thread might still be running if it was executing native code, so the state won't be invalided by
2643 * suspend_current ().
2645 tls->context.valid = FALSE;
2646 tls->async_state.valid = FALSE;
2647 invalidate_frames (tls);
2652 DebuggerTlsData *tls;
2653 gboolean valid_info;
2656 static SuspendThreadResult
2657 debugger_interrupt_critical (MonoThreadInfo *info, gpointer user_data)
2659 InterruptData *data = user_data;
2662 data->valid_info = TRUE;
2663 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));
2665 /* This is signal safe */
2666 thread_interrupt (data->tls, info, ji);
2667 return MonoResumeThread;
2673 * Notify a thread that it needs to suspend.
2676 notify_thread (gpointer key, gpointer value, gpointer user_data)
2678 MonoInternalThread *thread = key;
2679 DebuggerTlsData *tls = value;
2680 gsize tid = thread->tid;
2682 if (GetCurrentThreadId () == tid || tls->terminated)
2685 DEBUG_PRINTF (1, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid);
2687 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2688 InterruptData interrupt_data = { 0 };
2689 interrupt_data.tls = tls;
2691 mono_thread_info_safe_suspend_and_run ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE, debugger_interrupt_critical, &interrupt_data);
2692 if (!interrupt_data.valid_info) {
2693 DEBUG_PRINTF (1, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid);
2695 * Attached thread which died without detaching.
2697 tls->terminated = TRUE;
2702 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2704 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2708 if (mono_loader_lock_is_owned_by_self ()) {
2710 * Shortcut for the check in suspend_current (). This speeds up processing
2711 * when executing long running code inside the loader lock, i.e. assembly load
2717 if (debugger_thread_id == GetCurrentThreadId ())
2720 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2721 if (suspend_count - tls->resume_count > 0)
2722 tls->suspending = TRUE;
2724 DEBUG_PRINTF (1, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ());
2726 if (suspend_count - tls->resume_count == 0) {
2728 * We are executing a single threaded invoke but the single step for
2729 * suspending is still active.
2730 * FIXME: This slows down single threaded invokes.
2732 DEBUG_PRINTF (1, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ());
2736 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2738 /* Can't suspend in these methods */
2739 method = jinfo_get_method (ji);
2740 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2743 save_thread_context (ctx);
2751 * Increase the suspend count of the VM. While the suspend count is greater
2752 * than 0, runtime threads are suspended at certain points during execution.
2757 mono_loader_lock ();
2760 mono_mutex_lock (&suspend_mutex);
2761 MONO_FINISH_TRY_BLOCKING
2765 DEBUG_PRINTF (1, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ());
2767 if (suspend_count == 1) {
2768 // FIXME: Is it safe to call this inside the lock ?
2769 start_single_stepping ();
2770 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2773 mono_mutex_unlock (&suspend_mutex);
2775 if (suspend_count == 1)
2777 * Suspend creation of new threadpool threads, since they cannot run
2779 mono_thread_pool_suspend ();
2781 mono_loader_unlock ();
2787 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2795 g_assert (debugger_thread_id == GetCurrentThreadId ());
2797 mono_loader_lock ();
2800 mono_mutex_lock (&suspend_mutex);
2801 MONO_FINISH_TRY_BLOCKING
2803 g_assert (suspend_count > 0);
2806 DEBUG_PRINTF (1, "[%p] Resuming vm, suspend count=%d...\n", (gpointer)GetCurrentThreadId (), suspend_count);
2808 if (suspend_count == 0) {
2809 // FIXME: Is it safe to call this inside the lock ?
2810 stop_single_stepping ();
2811 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2814 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2815 err = mono_cond_broadcast (&suspend_cond);
2816 g_assert (err == 0);
2818 mono_mutex_unlock (&suspend_mutex);
2819 //g_assert (err == 0);
2821 if (suspend_count == 0)
2822 mono_thread_pool_resume ();
2824 mono_loader_unlock ();
2830 * Resume just one thread.
2833 resume_thread (MonoInternalThread *thread)
2836 DebuggerTlsData *tls;
2838 g_assert (debugger_thread_id == GetCurrentThreadId ());
2840 mono_loader_lock ();
2842 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2846 mono_mutex_lock (&suspend_mutex);
2847 MONO_FINISH_TRY_BLOCKING
2849 g_assert (suspend_count > 0);
2851 DEBUG_PRINTF (1, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid);
2853 tls->resume_count += suspend_count;
2856 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2857 * but only the one whose resume_count field is > 0 will be resumed.
2859 err = mono_cond_broadcast (&suspend_cond);
2860 g_assert (err == 0);
2862 mono_mutex_unlock (&suspend_mutex);
2863 //g_assert (err == 0);
2865 mono_loader_unlock ();
2869 free_frames (StackFrame **frames, int nframes)
2873 for (i = 0; i < nframes; ++i) {
2874 if (frames [i]->jit)
2875 mono_debug_free_method_jit_info (frames [i]->jit);
2876 g_free (frames [i]);
2882 invalidate_frames (DebuggerTlsData *tls)
2885 tls = mono_native_tls_get_value (debugger_tls_id);
2888 free_frames (tls->frames, tls->frame_count);
2889 tls->frame_count = 0;
2892 free_frames (tls->restore_frames, tls->restore_frame_count);
2893 tls->restore_frame_count = 0;
2894 tls->restore_frames = NULL;
2900 * Suspend the current thread until the runtime is resumed. If the thread has a
2901 * pending invoke, then the invoke is executed before this function returns.
2904 suspend_current (void)
2909 DebuggerTlsData *tls;
2911 g_assert (debugger_thread_id != GetCurrentThreadId ());
2913 if (mono_loader_lock_is_owned_by_self ()) {
2915 * If we own the loader mutex, can't suspend until we release it, since the
2916 * whole runtime can deadlock otherwise.
2921 tls = mono_native_tls_get_value (debugger_tls_id);
2925 mono_mutex_lock (&suspend_mutex);
2926 MONO_FINISH_TRY_BLOCKING
2928 tls->suspending = FALSE;
2929 tls->really_suspended = TRUE;
2931 if (!tls->suspended) {
2932 tls->suspended = TRUE;
2933 MONO_SEM_POST (&suspend_sem);
2936 DEBUG_PRINTF (1, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ());
2939 while (suspend_count - tls->resume_count > 0) {
2941 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
2943 mono_mutex_unlock (&suspend_mutex);
2945 mono_mutex_lock (&suspend_mutex);
2951 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
2952 g_assert (err == 0);
2955 MONO_FINISH_TRY_BLOCKING
2957 tls->suspended = FALSE;
2958 tls->really_suspended = FALSE;
2960 threads_suspend_count --;
2962 mono_mutex_unlock (&suspend_mutex);
2964 DEBUG_PRINTF (1, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ());
2966 if (tls->pending_invoke) {
2967 /* Save the original context */
2968 tls->pending_invoke->has_ctx = TRUE;
2969 tls->pending_invoke->ctx = tls->context.ctx;
2974 /* The frame info becomes invalid after a resume */
2975 tls->context.valid = FALSE;
2976 tls->async_state.valid = FALSE;
2977 invalidate_frames (tls);
2981 count_thread (gpointer key, gpointer value, gpointer user_data)
2983 DebuggerTlsData *tls = value;
2985 if (!tls->suspended && !tls->terminated)
2986 *(int*)user_data = *(int*)user_data + 1;
2990 count_threads_to_wait_for (void)
2994 mono_loader_lock ();
2995 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2996 mono_loader_unlock ();
3004 * Wait until the runtime is completely suspended.
3007 wait_for_suspend (void)
3009 int nthreads, nwait, err;
3010 gboolean waited = FALSE;
3012 // FIXME: Threads starting/stopping ?
3013 mono_loader_lock ();
3014 nthreads = mono_g_hash_table_size (thread_to_tls);
3015 mono_loader_unlock ();
3018 nwait = count_threads_to_wait_for ();
3020 DEBUG_PRINTF (1, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads);
3021 err = MONO_SEM_WAIT (&suspend_sem);
3022 g_assert (err == 0);
3030 DEBUG_PRINTF (1, "%d threads suspended.\n", nthreads);
3036 * Return whenever the runtime is suspended.
3041 return count_threads_to_wait_for () == 0;
3045 no_seq_points_found (MonoMethod *method)
3048 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3050 printf ("Unable to find seq points for method '%s'.\n", mono_method_full_name (method, TRUE));
3054 DebuggerTlsData *tls;
3056 } ComputeFramesUserData;
3059 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3061 ComputeFramesUserData *ud = user_data;
3063 MonoMethod *method, *actual_method, *api_method;
3067 if (info->type != FRAME_TYPE_MANAGED) {
3068 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3069 /* Mark the last frame as an invoke frame */
3071 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3077 method = jinfo_get_method (info->ji);
3079 method = info->method;
3080 actual_method = info->actual_method;
3081 api_method = method;
3086 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3089 if (info->il_offset == -1) {
3090 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3091 if (ud->frames == NULL) {
3092 if (find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL, &sp))
3093 info->il_offset = sp.il_offset;
3095 if (info->il_offset == -1)
3096 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3099 DEBUG_PRINTF (1, "\tFrame: %s:%x(%x) %d\n", mono_method_full_name (method, TRUE), info->il_offset, info->native_offset, info->managed);
3101 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3102 if (!CHECK_PROTOCOL_VERSION (2, 17))
3103 /* Older clients can't handle this flag */
3105 api_method = mono_marshal_method_from_wrapper (method);
3108 actual_method = api_method;
3109 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3112 frame = g_new0 (StackFrame, 1);
3113 frame->method = method;
3114 frame->actual_method = actual_method;
3115 frame->api_method = api_method;
3116 frame->il_offset = info->il_offset;
3117 frame->native_offset = info->native_offset;
3118 frame->flags = flags;
3119 frame->ji = info->ji;
3120 if (info->reg_locations)
3121 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3124 frame->has_ctx = TRUE;
3126 frame->domain = info->domain;
3128 ud->frames = g_slist_append (ud->frames, frame);
3134 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3136 ComputeFramesUserData *ud = user_data;
3139 * 'tls->filter_ctx' is the location of the throw site.
3141 * mono_walk_stack() will never actually hit the throw site, but unwind
3142 * directly from the filter to the call site; we abort stack unwinding here
3143 * once this happens and resume from the throw site.
3146 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3149 return process_frame (info, ctx, user_data);
3153 * Return a malloc-ed list of StackFrame structures.
3156 compute_frame_info_from (MonoInternalThread *thread, DebuggerTlsData *tls, MonoThreadUnwindState *state, int *out_nframes)
3158 ComputeFramesUserData user_data;
3159 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3164 user_data.tls = tls;
3165 user_data.frames = NULL;
3167 mono_walk_stack_with_state (process_frame, state, opts, &user_data);
3169 nframes = g_slist_length (user_data.frames);
3170 res = g_new0 (StackFrame*, nframes);
3171 l = user_data.frames;
3172 for (i = 0; i < nframes; ++i) {
3176 *out_nframes = nframes;
3182 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3184 ComputeFramesUserData user_data;
3186 int i, findex, new_frame_count;
3187 StackFrame **new_frames, *f;
3188 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3190 // FIXME: Locking on tls
3191 if (tls->frames && tls->frames_up_to_date)
3194 DEBUG_PRINTF (1, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid);
3196 user_data.tls = tls;
3197 user_data.frames = NULL;
3198 if (tls->terminated) {
3199 tls->frame_count = 0;
3201 } if (!tls->really_suspended && tls->async_state.valid) {
3202 /* Have to use the state saved by the signal handler */
3203 process_frame (&tls->async_last_frame, NULL, &user_data);
3204 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3205 } else if (tls->filter_state.valid) {
3207 * We are inside an exception filter.
3209 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3211 if (tls->context.valid)
3212 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3214 * After that, we resume unwinding from the location where the exception has been thrown.
3216 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3217 } else if (tls->context.valid) {
3218 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3221 tls->frame_count = 0;
3225 new_frame_count = g_slist_length (user_data.frames);
3226 new_frames = g_new0 (StackFrame*, new_frame_count);
3228 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3232 * Reuse the id for already existing stack frames, so invokes don't invalidate
3233 * the still valid stack frames.
3235 for (i = 0; i < tls->frame_count; ++i) {
3236 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3237 f->id = tls->frames [i]->id;
3242 if (i >= tls->frame_count)
3243 f->id = InterlockedIncrement (&frame_id);
3245 new_frames [findex ++] = f;
3248 g_slist_free (user_data.frames);
3250 invalidate_frames (tls);
3252 tls->frames = new_frames;
3253 tls->frame_count = new_frame_count;
3254 tls->frames_up_to_date = TRUE;
3258 * GHFunc to emit an appdomain creation event
3259 * @param key Don't care
3260 * @param value A loaded appdomain
3261 * @param user_data Don't care
3264 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3266 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3267 g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
3271 * GHFunc to emit a thread start event
3272 * @param key A thread id
3273 * @param value A thread object
3274 * @param user_data Don't care
3277 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3279 if (GPOINTER_TO_INT (key) != debugger_thread_id)
3280 process_profiler_event (EVENT_KIND_THREAD_START, value);
3284 * GFunc to emit an assembly load event
3285 * @param value A loaded assembly
3286 * @param user_data Don't care
3289 emit_assembly_load (gpointer value, gpointer user_data)
3291 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3295 * GFunc to emit a type load event
3296 * @param value A loaded type
3297 * @param user_data Don't care
3300 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3302 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3306 strdup_tolower (char *s)
3311 for (p = s2; *p; ++p)
3317 * Same as g_path_get_basename () but handles windows paths as well,
3318 * which can occur in .mdb files created by pdb2mdb.
3321 dbg_path_get_basename (const char *filename)
3325 if (!filename || strchr (filename, '/') || !strchr (filename, '\\'))
3326 return g_path_get_basename (filename);
3330 /* No separator -> filename */
3331 r = strrchr (filename, '\\');
3333 return g_strdup (filename);
3335 /* Trailing slash, remove component */
3337 char *copy = g_strdup (filename);
3338 copy [r-filename] = 0;
3339 r = strrchr (copy, '\\');
3343 return g_strdup ("/");
3345 r = g_strdup (&r[1]);
3350 return g_strdup (&r[1]);
3354 init_jit_info_dbg_attrs (MonoJitInfo *ji)
3356 static MonoClass *hidden_klass, *step_through_klass, *non_user_klass;
3357 MonoCustomAttrInfo *ainfo;
3359 if (ji->dbg_attrs_inited)
3362 if (!hidden_klass) {
3363 hidden_klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3364 g_assert (hidden_klass);
3366 if (!step_through_klass) {
3367 step_through_klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3368 g_assert (step_through_klass);
3370 if (!non_user_klass) {
3371 non_user_klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute");
3372 g_assert (non_user_klass);
3375 ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji));
3377 if (mono_custom_attrs_has_attr (ainfo, hidden_klass))
3378 ji->dbg_hidden = TRUE;
3379 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3380 ji->dbg_step_through = TRUE;
3381 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3382 ji->dbg_non_user_code = TRUE;
3383 mono_custom_attrs_free (ainfo);
3386 ainfo = mono_custom_attrs_from_class (jinfo_get_method (ji)->klass);
3388 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3389 ji->dbg_step_through = TRUE;
3390 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3391 ji->dbg_non_user_code = TRUE;
3392 mono_custom_attrs_free (ainfo);
3395 mono_memory_barrier ();
3396 ji->dbg_attrs_inited = TRUE;
3404 * create_event_list:
3406 * Return a list of event request ids matching EVENT, starting from REQS, which
3407 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3409 * We return request ids, instead of requests, to simplify threading, since
3410 * requests could be deleted anytime when the loader lock is not held.
3411 * LOCKING: Assumes the loader lock is held.
3414 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3417 GSList *events = NULL;
3419 *suspend_policy = SUSPEND_POLICY_NONE;
3422 reqs = event_requests;
3427 for (i = 0; i < reqs->len; ++i) {
3428 EventRequest *req = g_ptr_array_index (reqs, i);
3429 if (req->event_kind == event) {
3430 gboolean filtered = FALSE;
3433 for (j = 0; j < req->nmodifiers; ++j) {
3434 Modifier *mod = &req->modifiers [j];
3436 if (mod->kind == MOD_KIND_COUNT) {
3438 if (mod->data.count > 0) {
3439 if (mod->data.count > 0) {
3441 if (mod->data.count == 0)
3445 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3446 if (mod->data.thread != mono_thread_internal_current ())
3448 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3449 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3451 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3453 if (ei->caught && !mod->caught)
3455 if (!ei->caught && !mod->uncaught)
3457 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3459 gboolean found = FALSE;
3460 MonoAssembly **assemblies = mod->data.assemblies;
3463 for (k = 0; assemblies [k]; ++k)
3464 if (assemblies [k] == jinfo_get_method (ji)->klass->image->assembly)
3469 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3470 gpointer iter = NULL;
3472 MonoDebugSourceInfo *sinfo;
3473 char *source_file, *s;
3474 gboolean found = FALSE;
3476 GPtrArray *source_file_list;
3478 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3479 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3482 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
3483 for (i = 0; i < source_file_list->len; ++i) {
3484 sinfo = g_ptr_array_index (source_file_list, i);
3486 * Do a case-insesitive match by converting the file name to
3489 s = strdup_tolower (sinfo->source_file);
3490 if (g_hash_table_lookup (mod->data.source_files, s))
3493 char *s2 = dbg_path_get_basename (sinfo->source_file);
3494 char *s3 = strdup_tolower (s2);
3496 if (g_hash_table_lookup (mod->data.source_files, s3))
3503 g_ptr_array_free (source_file_list, TRUE);
3508 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3511 s = mono_type_full_name (&ei->klass->byval_arg);
3512 if (!g_hash_table_lookup (mod->data.type_names, s))
3515 } else if (mod->kind == MOD_KIND_STEP) {
3516 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3517 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3518 !strcmp (jinfo_get_method (ji)->name, ".cctor") &&
3519 (jinfo_get_method (ji) != ((SingleStepReq*)req->info)->start_method))
3521 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3522 init_jit_info_dbg_attrs (ji);
3526 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3527 init_jit_info_dbg_attrs (ji);
3528 if (ji->dbg_step_through)
3531 if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3532 init_jit_info_dbg_attrs (ji);
3533 if (ji->dbg_non_user_code)
3540 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3541 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3546 /* Send a VM START/DEATH event by default */
3547 if (event == EVENT_KIND_VM_START)
3548 events = g_slist_append (events, GINT_TO_POINTER (0));
3549 if (event == EVENT_KIND_VM_DEATH)
3550 events = g_slist_append (events, GINT_TO_POINTER (0));
3555 static G_GNUC_UNUSED const char*
3556 event_to_string (EventKind event)
3559 case EVENT_KIND_VM_START: return "VM_START";
3560 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3561 case EVENT_KIND_THREAD_START: return "THREAD_START";
3562 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3563 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3564 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3565 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3566 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3567 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3568 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3569 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3570 case EVENT_KIND_STEP: return "STEP";
3571 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3572 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3573 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3574 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3575 case EVENT_KIND_USER_LOG: return "USER_LOG";
3577 g_assert_not_reached ();
3585 * Send an event to the client, suspending the vm if needed.
3586 * LOCKING: Since this can suspend the calling thread, no locks should be held
3588 * The EVENTS list is freed by this function.
3591 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3595 MonoDomain *domain = mono_domain_get ();
3596 MonoThread *thread = NULL;
3597 MonoObject *keepalive_obj = NULL;
3598 gboolean send_success = FALSE;
3603 DEBUG_PRINTF (2, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event));
3607 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3608 // FIXME: We miss those events
3609 DEBUG_PRINTF (2, "VM start event not sent yet: dropping %s\n", event_to_string (event));
3613 if (vm_death_event_sent) {
3614 DEBUG_PRINTF (2, "VM death event has been sent: dropping %s\n", event_to_string (event));
3618 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3619 DEBUG_PRINTF (2, "Mono runtime is shutting down: dropping %s\n", event_to_string (event));
3624 DEBUG_PRINTF (2, "Debugger client is not connected: dropping %s\n", event_to_string (event));
3628 if (event == EVENT_KIND_KEEPALIVE)
3629 suspend_policy = SUSPEND_POLICY_NONE;
3634 if (agent_config.defer) {
3635 /* Make sure the thread id is always set when doing deferred debugging */
3636 if (debugger_thread_id == GetCurrentThreadId ()) {
3637 /* Don't suspend on events from the debugger thread */
3638 suspend_policy = SUSPEND_POLICY_NONE;
3639 thread = mono_thread_get_main ();
3641 else thread = mono_thread_current ();
3643 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3644 // FIXME: Send these with a NULL thread, don't suspend the current thread
3649 nevents = g_slist_length (events);
3650 buffer_init (&buf, 128);
3651 buffer_add_byte (&buf, suspend_policy);
3652 buffer_add_int (&buf, nevents);
3654 for (l = events; l; l = l->next) {
3655 buffer_add_byte (&buf, event); // event kind
3656 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3661 thread = mono_thread_current ();
3663 if (event == EVENT_KIND_VM_START && arg != NULL)
3666 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3669 case EVENT_KIND_THREAD_START:
3670 case EVENT_KIND_THREAD_DEATH:
3672 case EVENT_KIND_APPDOMAIN_CREATE:
3673 case EVENT_KIND_APPDOMAIN_UNLOAD:
3674 buffer_add_domainid (&buf, arg);
3676 case EVENT_KIND_METHOD_ENTRY:
3677 case EVENT_KIND_METHOD_EXIT:
3678 buffer_add_methodid (&buf, domain, arg);
3680 case EVENT_KIND_ASSEMBLY_LOAD:
3681 buffer_add_assemblyid (&buf, domain, arg);
3683 case EVENT_KIND_ASSEMBLY_UNLOAD: {
3684 DebuggerTlsData *tls;
3686 /* The domain the assembly belonged to is not equal to the current domain */
3687 tls = mono_native_tls_get_value (debugger_tls_id);
3689 g_assert (tls->domain_unloading);
3691 buffer_add_assemblyid (&buf, tls->domain_unloading, arg);
3694 case EVENT_KIND_TYPE_LOAD:
3695 buffer_add_typeid (&buf, domain, arg);
3697 case EVENT_KIND_BREAKPOINT:
3698 case EVENT_KIND_STEP:
3699 buffer_add_methodid (&buf, domain, arg);
3700 buffer_add_long (&buf, il_offset);
3702 case EVENT_KIND_VM_START:
3703 buffer_add_domainid (&buf, mono_get_root_domain ());
3705 case EVENT_KIND_VM_DEATH:
3706 if (CHECK_PROTOCOL_VERSION (2, 27))
3707 buffer_add_int (&buf, mono_environment_exitcode_get ());
3709 case EVENT_KIND_EXCEPTION: {
3710 EventInfo *ei = arg;
3711 buffer_add_objid (&buf, ei->exc);
3713 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3714 * later after the suspension. (#12494).
3716 keepalive_obj = ei->exc;
3719 case EVENT_KIND_USER_BREAK:
3721 case EVENT_KIND_USER_LOG: {
3722 EventInfo *ei = arg;
3723 buffer_add_int (&buf, ei->level);
3724 buffer_add_string (&buf, ei->category ? ei->category : "");
3725 buffer_add_string (&buf, ei->message ? ei->message : "");
3728 case EVENT_KIND_KEEPALIVE:
3729 suspend_policy = SUSPEND_POLICY_NONE;
3732 g_assert_not_reached ();
3736 if (event == EVENT_KIND_VM_START) {
3737 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3738 if (!agent_config.defer)
3739 start_debugger_thread ();
3742 if (event == EVENT_KIND_VM_DEATH) {
3743 vm_death_event_sent = TRUE;
3744 suspend_policy = SUSPEND_POLICY_NONE;
3747 if (mono_runtime_is_shutting_down ())
3748 suspend_policy = SUSPEND_POLICY_NONE;
3750 if (suspend_policy != SUSPEND_POLICY_NONE) {
3752 * Save the thread context and start suspending before sending the packet,
3753 * since we could be receiving the resume request before send_packet ()
3756 save_thread_context (ctx);
3760 /* This will keep this object alive */
3761 get_objref (keepalive_obj);
3764 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3768 g_slist_free (events);
3771 if (!send_success) {
3772 DEBUG_PRINTF (2, "Sending command %s failed.\n", event_to_string (event));
3776 if (event == EVENT_KIND_VM_START) {
3777 vm_start_event_sent = TRUE;
3780 DEBUG_PRINTF (1, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer)GetCurrentThreadId (), nevents, event_to_string (event), ecount, suspend_policy);
3782 switch (suspend_policy) {
3783 case SUSPEND_POLICY_NONE:
3785 case SUSPEND_POLICY_ALL:
3788 case SUSPEND_POLICY_EVENT_THREAD:
3792 g_assert_not_reached ();
3797 process_profiler_event (EventKind event, gpointer arg)
3801 EventInfo ei, *ei_arg = NULL;
3803 if (event == EVENT_KIND_TYPE_LOAD) {
3808 mono_loader_lock ();
3809 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3810 mono_loader_unlock ();
3812 process_event (event, arg, 0, NULL, events, suspend_policy);
3816 runtime_initialized (MonoProfiler *prof)
3818 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3819 if (agent_config.defer)
3820 start_debugger_thread ();
3824 runtime_shutdown (MonoProfiler *prof)
3826 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3828 mono_debugger_agent_cleanup ();
3832 thread_startup (MonoProfiler *prof, uintptr_t tid)
3834 MonoInternalThread *thread = mono_thread_internal_current ();
3835 MonoInternalThread *old_thread;
3836 DebuggerTlsData *tls;
3838 if (tid == debugger_thread_id)
3841 g_assert (thread->tid == tid);
3843 mono_loader_lock ();
3844 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3845 mono_loader_unlock ();
3847 if (thread == old_thread) {
3849 * For some reason, thread_startup () might be called for the same thread
3850 * multiple times (attach ?).
3852 DEBUG_PRINTF (1, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid);
3856 * thread_end () might not be called for some threads, and the tid could
3859 DEBUG_PRINTF (1, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid);
3860 mono_loader_lock ();
3861 mono_g_hash_table_remove (thread_to_tls, old_thread);
3862 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3863 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3864 mono_loader_unlock ();
3868 tls = mono_native_tls_get_value (debugger_tls_id);
3870 // FIXME: Free this somewhere
3871 tls = g_new0 (DebuggerTlsData, 1);
3872 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3873 tls->thread = thread;
3874 mono_native_tls_set_value (debugger_tls_id, tls);
3876 DEBUG_PRINTF (1, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3878 mono_loader_lock ();
3879 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3880 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3881 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3882 mono_loader_unlock ();
3884 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3887 * suspend_vm () could have missed this thread, so wait for a resume.
3893 thread_end (MonoProfiler *prof, uintptr_t tid)
3895 MonoInternalThread *thread;
3896 DebuggerTlsData *tls = NULL;
3898 mono_loader_lock ();
3899 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3901 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3902 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3904 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3905 tls->terminated = TRUE;
3906 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3907 MONO_GC_UNREGISTER_ROOT (tls->thread);
3911 mono_loader_unlock ();
3913 /* We might be called for threads started before we registered the start callback */
3915 DEBUG_PRINTF (1, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3917 if (GetCurrentThreadId () == tid && !mono_native_tls_get_value (debugger_tls_id)) {
3919 * This can happen on darwin since we deregister threads using pthread dtors.
3920 * process_profiler_event () and the code it calls cannot handle a null TLS value.
3925 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3930 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3932 mono_loader_lock ();
3933 g_hash_table_insert (domains, domain, domain);
3934 mono_loader_unlock ();
3936 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3940 appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain)
3942 DebuggerTlsData *tls;
3944 /* This might be called during shutdown on the debugger thread from the CMD_VM_EXIT code */
3945 if (is_debugger_thread ())
3949 * Remember the currently unloading appdomain as it is needed to generate
3950 * proper ids for unloading assemblies.
3952 tls = mono_native_tls_get_value (debugger_tls_id);
3954 tls->domain_unloading = domain;
3958 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3960 DebuggerTlsData *tls;
3962 if (is_debugger_thread ())
3965 tls = mono_native_tls_get_value (debugger_tls_id);
3967 tls->domain_unloading = NULL;
3969 clear_breakpoints_for_domain (domain);
3971 mono_loader_lock ();
3972 /* Invalidate each thread's frame stack */
3973 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3974 mono_loader_unlock ();
3976 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3980 * invalidate_each_thread:
3982 * A GHFunc to invalidate frames.
3983 * value must be a DebuggerTlsData*
3986 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3988 invalidate_frames (value);
3992 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3994 /* Sent later in jit_end () */
3996 g_ptr_array_add (pending_assembly_loads, assembly);
4001 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
4003 if (is_debugger_thread ())
4006 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
4008 clear_event_requests_for_assembly (assembly);
4009 clear_types_for_assembly (assembly);
4013 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
4015 #if defined(HOST_WIN32) && !defined(__GNUC__)
4016 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
4018 gpointer stackptr = __builtin_frame_address (1);
4020 MonoInternalThread *thread = mono_thread_internal_current ();
4021 DebuggerTlsData *tls;
4023 mono_loader_lock ();
4025 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4026 /* Could be the debugger thread with assembly/type load hooks */
4028 tls->invoke_addr = stackptr;
4030 mono_loader_unlock ();
4034 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
4037 #if defined(HOST_WIN32) && !defined(__GNUC__)
4038 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
4040 gpointer stackptr = __builtin_frame_address (1);
4043 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
4047 * We need to stop single stepping when exiting a runtime invoke, since if it is
4048 * a step out, it may return to native code, and thus never end.
4050 mono_loader_lock ();
4051 ss_invoke_addr = NULL;
4053 for (i = 0; i < event_requests->len; ++i) {
4054 EventRequest *req = g_ptr_array_index (event_requests, i);
4056 if (req->event_kind == EVENT_KIND_STEP) {
4057 ss_destroy (req->info);
4058 g_ptr_array_remove_index_fast (event_requests, i);
4063 mono_loader_unlock ();
4067 send_type_load (MonoClass *klass)
4069 gboolean type_load = FALSE;
4070 MonoDomain *domain = mono_domain_get ();
4071 AgentDomainInfo *info = NULL;
4073 mono_loader_lock ();
4074 mono_domain_lock (domain);
4076 info = get_agent_domain_info (domain);
4078 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
4080 g_hash_table_insert (info->loaded_classes, klass, klass);
4083 mono_domain_unlock (domain);
4084 mono_loader_unlock ();
4086 emit_type_load (klass, klass, NULL);
4090 * Emit load events for all types currently loaded in the domain.
4091 * Takes the loader and domain locks.
4092 * user_data is unused.
4095 send_types_for_domain (MonoDomain *domain, void *user_data)
4097 AgentDomainInfo *info = NULL;
4099 mono_loader_lock ();
4100 mono_domain_lock (domain);
4101 info = get_agent_domain_info (domain);
4103 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4104 mono_domain_unlock (domain);
4105 mono_loader_unlock ();
4109 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
4112 * We emit type load events when the first method of the type is JITted,
4113 * since the class load profiler callbacks might be called with the
4114 * loader lock held. They could also occur in the debugger thread.
4115 * Same for assembly load events.
4118 MonoAssembly *assembly = NULL;
4120 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4122 if (pending_assembly_loads->len > 0) {
4123 assembly = g_ptr_array_index (pending_assembly_loads, 0);
4124 g_ptr_array_remove_index (pending_assembly_loads, 0);
4129 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4135 send_type_load (method->klass);
4138 add_pending_breakpoints (method, jinfo);
4142 * BREAKPOINTS/SINGLE STEPPING
4146 * Contains information about an inserted breakpoint.
4149 long il_offset, native_offset;
4153 } BreakpointInstance;
4156 * Contains generic information about a breakpoint.
4160 * The method where the breakpoint is placed. Can be NULL in which case it
4161 * is inserted into every method. This is used to implement method entry/
4162 * exit events. Can be a generic method definition, in which case the
4163 * breakpoint is inserted into every instance.
4169 * A list of BreakpointInstance structures describing where the breakpoint
4170 * was inserted. There could be more than one because of
4171 * generics/appdomains/method entry/exit.
4173 GPtrArray *children;
4176 /* List of breakpoints */
4177 static GPtrArray *breakpoints;
4178 /* Maps breakpoint locations to the number of breakpoints at that location */
4179 static GHashTable *bp_locs;
4182 breakpoints_init (void)
4184 breakpoints = g_ptr_array_new ();
4185 bp_locs = g_hash_table_new (NULL, NULL);
4189 * insert_breakpoint:
4191 * Insert the breakpoint described by BP into the method described by
4195 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4198 BreakpointInstance *inst;
4199 SeqPointIterator it;
4200 gboolean it_has_sp = FALSE;
4203 mono_error_init (error);
4205 seq_point_iterator_init (&it, seq_points);
4206 while (seq_point_iterator_next (&it)) {
4207 if (it.seq_point.il_offset == bp->il_offset) {
4215 * The set of IL offsets with seq points doesn't completely match the
4216 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4218 seq_point_iterator_init (&it, seq_points);
4219 while (seq_point_iterator_next (&it)) {
4220 if (it.seq_point.il_offset != METHOD_ENTRY_IL_OFFSET &&
4221 it.seq_point.il_offset != METHOD_EXIT_IL_OFFSET &&
4222 it.seq_point.il_offset + 1 == bp->il_offset) {
4230 char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d", mono_method_full_name (jinfo_get_method (ji), TRUE), bp->il_offset);
4232 seq_point_iterator_init (&it, seq_points);
4233 while (seq_point_iterator_next (&it))
4234 DEBUG_PRINTF (1, "%d\n", it.seq_point.il_offset);
4237 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4238 g_warning ("%s", s);
4242 g_warning ("%s", s);
4248 inst = g_new0 (BreakpointInstance, 1);
4249 inst->il_offset = it.seq_point.il_offset;
4250 inst->native_offset = it.seq_point.native_offset;
4251 inst->ip = (guint8*)ji->code_start + it.seq_point.native_offset;
4253 inst->domain = domain;
4255 mono_loader_lock ();
4257 g_ptr_array_add (bp->children, inst);
4259 mono_loader_unlock ();
4262 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4263 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4266 if (it.seq_point.native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4267 DEBUG_PRINTF (1, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset);
4268 } else if (count == 0) {
4269 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4270 mono_arch_set_breakpoint (ji, inst->ip);
4276 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);
4280 remove_breakpoint (BreakpointInstance *inst)
4282 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4284 MonoJitInfo *ji = inst->ji;
4285 guint8 *ip = inst->ip;
4288 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4289 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4292 g_assert (count > 0);
4294 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4295 mono_arch_clear_breakpoint (ji, ip);
4296 DEBUG_PRINTF (1, "[dbg] Clear breakpoint at %s [%p].\n", mono_method_full_name (jinfo_get_method (ji), TRUE), ip);
4303 static inline gboolean
4304 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4310 if (method == bp->method)
4312 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4315 if (bp->method->is_inflated && method->is_inflated) {
4316 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4317 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4319 /* Open generic methods should match closed generic methods of the same class */
4320 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4321 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4322 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4324 /* FIXME: Handle !mvar */
4325 if (t1->type != MONO_TYPE_MVAR)
4336 * add_pending_breakpoints:
4338 * Insert pending breakpoints into the newly JITted method METHOD.
4341 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4344 MonoSeqPointInfo *seq_points;
4346 MonoMethod *jmethod;
4351 domain = mono_domain_get ();
4353 mono_loader_lock ();
4355 for (i = 0; i < breakpoints->len; ++i) {
4356 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4357 gboolean found = FALSE;
4359 if (!bp_matches_method (bp, method))
4362 for (j = 0; j < bp->children->len; ++j) {
4363 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4370 jmethod = jinfo_get_method (ji);
4371 mono_domain_lock (domain);
4372 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, jmethod);
4373 if (!seq_points && jmethod->is_inflated)
4374 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (jmethod));
4375 mono_domain_unlock (domain);
4377 /* Could be AOT code */
4379 g_assert (seq_points);
4381 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4385 mono_loader_unlock ();
4389 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4395 mono_error_init (error);
4397 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4399 /* Might be AOTed code */
4400 code = mono_aot_get_method (domain, method);
4402 ji = mono_jit_info_table_find (domain, code);
4407 insert_breakpoint (seq_points, domain, ji, bp, error);
4411 clear_breakpoint (MonoBreakpoint *bp);
4416 * Set a breakpoint at IL_OFFSET in METHOD.
4417 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4418 * METHOD can also be a generic method definition, in which case a breakpoint
4419 * is placed in all instances of the method.
4420 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4423 static MonoBreakpoint*
4424 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4427 GHashTableIter iter, iter2;
4430 MonoSeqPointInfo *seq_points;
4433 mono_error_init (error);
4436 // - suspend/resume the vm to prevent code patching problems
4437 // - multiple breakpoints on the same location
4438 // - dynamic methods
4441 bp = g_new0 (MonoBreakpoint, 1);
4442 bp->method = method;
4443 bp->il_offset = il_offset;
4445 bp->children = g_ptr_array_new ();
4447 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);
4449 mono_loader_lock ();
4451 g_hash_table_iter_init (&iter, domains);
4452 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4453 mono_domain_lock (domain);
4455 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4456 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4457 if (bp_matches_method (bp, m))
4458 set_bp_in_method (domain, m, seq_points, bp, error);
4461 mono_domain_unlock (domain);
4464 mono_loader_unlock ();
4466 mono_loader_lock ();
4467 g_ptr_array_add (breakpoints, bp);
4468 mono_loader_unlock ();
4470 if (error && !mono_error_ok (error)) {
4471 clear_breakpoint (bp);
4479 clear_breakpoint (MonoBreakpoint *bp)
4483 // FIXME: locking, races
4484 for (i = 0; i < bp->children->len; ++i) {
4485 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4487 remove_breakpoint (inst);
4492 mono_loader_lock ();
4493 g_ptr_array_remove (breakpoints, bp);
4494 mono_loader_unlock ();
4496 g_ptr_array_free (bp->children, TRUE);
4501 breakpoints_cleanup (void)
4505 mono_loader_lock ();
4507 while (i < event_requests->len) {
4508 EventRequest *req = g_ptr_array_index (event_requests, i);
4510 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4511 clear_breakpoint (req->info);
4512 g_ptr_array_remove_index_fast (event_requests, i);
4519 for (i = 0; i < breakpoints->len; ++i)
4520 g_free (g_ptr_array_index (breakpoints, i));
4522 g_ptr_array_free (breakpoints, TRUE);
4523 g_hash_table_destroy (bp_locs);
4528 mono_loader_unlock ();
4532 * clear_breakpoints_for_domain:
4534 * Clear breakpoint instances which reference DOMAIN.
4537 clear_breakpoints_for_domain (MonoDomain *domain)
4541 /* This could be called after shutdown */
4545 mono_loader_lock ();
4546 for (i = 0; i < breakpoints->len; ++i) {
4547 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4550 while (j < bp->children->len) {
4551 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4553 if (inst->domain == domain) {
4554 remove_breakpoint (inst);
4558 g_ptr_array_remove_index_fast (bp->children, j);
4564 mono_loader_unlock ();
4570 * Return FALSE if single stepping needs to continue.
4573 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp, DebuggerTlsData *tls, MonoContext *ctx)
4575 MonoDebugMethodInfo *minfo;
4576 MonoDebugSourceLocation *loc = NULL;
4577 gboolean hit = TRUE;
4580 if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK)) {
4582 * These seq points are inserted by the JIT after calls, step over needs to skip them.
4584 DEBUG_PRINTF (1, "[%p] Seq point at nonempty stack %x while stepping over, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset);
4588 if (req->depth == STEP_DEPTH_OVER && hit) {
4589 if (!tls->context.valid)
4590 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4591 compute_frame_info (tls->thread, tls);
4592 if (req->nframes && tls->frame_count && tls->frame_count > req->nframes) {
4593 /* Hit the breakpoint in a recursive call */
4594 DEBUG_PRINTF (1, "[%p] Breakpoint at lower frame while stepping over, continuing single stepping.\n", (gpointer)GetCurrentThreadId ());
4599 if (req->depth == STEP_DEPTH_INTO && req->size == STEP_SIZE_MIN && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) && ss_req->start_method){
4600 method = jinfo_get_method (ji);
4601 if (!tls->context.valid)
4602 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4603 compute_frame_info (tls->thread, tls);
4604 if (ss_req->start_method == method && req->nframes && tls->frame_count == req->nframes) {//Check also frame count(could be recursion)
4605 DEBUG_PRINTF (1, "[%p] Seq point at nonempty stack %x while stepping in, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset);
4610 if (req->size != STEP_SIZE_LINE)
4613 /* Have to check whenever a different source line was reached */
4614 method = jinfo_get_method (ji);
4615 minfo = mono_debug_lookup_method (method);
4618 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4621 DEBUG_PRINTF (1, "[%p] No line number info for il offset %x, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset);
4622 ss_req->last_method = method;
4624 } else if (loc && method == ss_req->last_method && loc->row == ss_req->last_line) {
4625 DEBUG_PRINTF (1, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer)GetCurrentThreadId (), loc->row);
4630 ss_req->last_method = method;
4631 ss_req->last_line = loc->row;
4632 mono_debug_free_source_location (loc);
4639 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4641 return bp->method && bp->method->klass->image->assembly == assembly;
4645 process_breakpoint_inner (DebuggerTlsData *tls, gboolean from_signal)
4649 int i, j, suspend_policy;
4650 guint32 native_offset;
4652 BreakpointInstance *inst;
4653 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4654 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4655 EventKind kind = EVENT_KIND_BREAKPOINT;
4656 MonoContext *ctx = &tls->restore_state.ctx;
4658 MonoSeqPointInfo *info;
4662 // FIXME: Speed this up
4664 ip = MONO_CONTEXT_GET_IP (ctx);
4665 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4667 method = jinfo_get_method (ji);
4669 /* Compute the native offset of the breakpoint from the ip */
4670 native_offset = ip - (guint8*)ji->code_start;
4673 * Skip the instruction causing the breakpoint signal.
4676 mono_arch_skip_breakpoint (ctx, ji);
4678 if (method->wrapper_type || tls->disable_breakpoints)
4681 bp_reqs = g_ptr_array_new ();
4682 ss_reqs = g_ptr_array_new ();
4683 ss_reqs_orig = g_ptr_array_new ();
4685 mono_loader_lock ();
4688 * The ip points to the instruction causing the breakpoint event, which is after
4689 * the offset recorded in the seq point map, so find the prev seq point before ip.
4691 found_sp = find_prev_seq_point_for_native_offset (mono_domain_get (), method, native_offset, &info, &sp);
4694 no_seq_points_found (method);
4696 g_assert (found_sp);
4698 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);
4701 for (i = 0; i < breakpoints->len; ++i) {
4702 bp = g_ptr_array_index (breakpoints, i);
4707 for (j = 0; j < bp->children->len; ++j) {
4708 inst = g_ptr_array_index (bp->children, j);
4709 if (inst->ji == ji && inst->il_offset == sp.il_offset && inst->native_offset == sp.native_offset) {
4710 if (bp->req->event_kind == EVENT_KIND_STEP) {
4711 g_ptr_array_add (ss_reqs_orig, bp->req);
4713 g_ptr_array_add (bp_reqs, bp->req);
4718 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4719 /* Maybe a method entry/exit event */
4720 if (sp.il_offset == METHOD_ENTRY_IL_OFFSET)
4721 kind = EVENT_KIND_METHOD_ENTRY;
4722 else if (sp.il_offset == METHOD_EXIT_IL_OFFSET)
4723 kind = EVENT_KIND_METHOD_EXIT;
4726 /* Process single step requests */
4727 for (i = 0; i < ss_reqs_orig->len; ++i) {
4728 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4729 SingleStepReq *ss_req = req->info;
4732 if (mono_thread_internal_current () != ss_req->thread)
4735 hit = ss_update (ss_req, ji, &sp, tls, ctx);
4737 g_ptr_array_add (ss_reqs, req);
4739 /* Start single stepping again from the current sequence point */
4740 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
4743 if (ss_reqs->len > 0)
4744 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4745 if (bp_reqs->len > 0)
4746 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4747 if (kind != EVENT_KIND_BREAKPOINT)
4748 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4750 mono_loader_unlock ();
4752 g_ptr_array_free (bp_reqs, TRUE);
4753 g_ptr_array_free (ss_reqs, TRUE);
4756 * FIXME: The first event will suspend, so the second will only be sent after the
4760 process_event (EVENT_KIND_STEP, method, 0, ctx, ss_events, suspend_policy);
4762 process_event (kind, method, 0, ctx, bp_events, suspend_policy);
4763 if (enter_leave_events)
4764 process_event (kind, method, 0, ctx, enter_leave_events, suspend_policy);
4767 /* Process a breakpoint/single step event after resuming from a signal handler */
4769 process_signal_event (void (*func) (DebuggerTlsData*, gboolean))
4771 DebuggerTlsData *tls;
4772 MonoThreadUnwindState orig_restore_state;
4775 tls = mono_native_tls_get_value (debugger_tls_id);
4776 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4777 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4778 mono_thread_state_init_from_monoctx (&tls->restore_state, &tls->handler_ctx);
4782 /* This is called when resuming from a signal handler, so it shouldn't return */
4783 memcpy (&ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4784 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4785 mono_restore_context (&ctx);
4786 g_assert_not_reached ();
4790 process_breakpoint (void)
4792 process_signal_event (process_breakpoint_inner);
4796 resume_from_signal_handler (void *sigctx, void *func)
4798 DebuggerTlsData *tls;
4801 /* Save the original context in TLS */
4802 // FIXME: This might not work on an altstack ?
4803 tls = mono_native_tls_get_value (debugger_tls_id);
4805 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer)GetCurrentThreadId ());
4808 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4809 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4810 // clob:c could be added to op_seq_point.
4812 mono_sigctx_to_monoctx (sigctx, &ctx);
4813 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4814 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4815 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4817 MONO_CONTEXT_SET_IP (&ctx, func);
4819 mono_monoctx_to_sigctx (&ctx, sigctx);
4821 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4822 mono_ppc_set_func_into_sigctx (sigctx, func);
4827 mono_debugger_agent_breakpoint_hit (void *sigctx)
4830 * We are called from a signal handler, and running code there causes all kinds of
4831 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4832 * So set up the signal context to return to the real breakpoint handler function.
4834 resume_from_signal_handler (sigctx, process_breakpoint);
4838 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4840 if (frame->managed) {
4841 *(MonoContext*)data = *ctx;
4850 * Called by System.Diagnostics.Debugger:Break ().
4853 mono_debugger_agent_user_break (void)
4855 if (agent_config.enabled) {
4860 /* Obtain a context */
4861 MONO_CONTEXT_SET_IP (&ctx, NULL);
4862 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4863 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4865 mono_loader_lock ();
4866 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4867 mono_loader_unlock ();
4869 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4876 ss_depth_to_string (StepDepth depth)
4879 case STEP_DEPTH_OVER:
4881 case STEP_DEPTH_OUT:
4883 case STEP_DEPTH_INTO:
4886 g_assert_not_reached ();
4892 process_single_step_inner (DebuggerTlsData *tls, gboolean from_signal)
4897 int il_offset, suspend_policy;
4900 MonoContext *ctx = &tls->restore_state.ctx;
4903 MonoSeqPointInfo *info;
4905 ip = MONO_CONTEXT_GET_IP (ctx);
4907 /* Skip the instruction causing the single step */
4909 mono_arch_skip_single_step (ctx);
4911 if (suspend_count > 0) {
4912 process_suspend (tls, ctx);
4917 // FIXME: A suspend race
4920 if (mono_thread_internal_current () != ss_req->thread)
4923 if (log_level > 0) {
4924 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4926 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);
4929 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4931 method = jinfo_get_method (ji);
4934 if (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4939 * Stopping in memset makes half-initialized vtypes visible.
4940 * Stopping in memcpy makes half-copied vtypes visible.
4942 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
4946 * The ip points to the instruction causing the single step event, which is before
4947 * the offset recorded in the seq point map, so find the next seq point after ip.
4949 if (!find_next_seq_point_for_native_offset (domain, method, (guint8*)ip - (guint8*)ji->code_start, &info, &sp))
4952 il_offset = sp.il_offset;
4954 if (!ss_update (ss_req, ji, &sp, tls, ctx))
4957 /* Start single stepping again from the current sequence point */
4958 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
4960 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
4961 (method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4962 !strcmp (method->name, ".cctor"))
4965 // FIXME: Has to lock earlier
4967 reqs = g_ptr_array_new ();
4969 mono_loader_lock ();
4971 g_ptr_array_add (reqs, ss_req->req);
4973 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4975 g_ptr_array_free (reqs, TRUE);
4977 mono_loader_unlock ();
4979 process_event (EVENT_KIND_STEP, jinfo_get_method (ji), il_offset, ctx, events, suspend_policy);
4983 process_single_step (void)
4985 process_signal_event (process_single_step_inner);
4989 * mono_debugger_agent_single_step_event:
4991 * Called from a signal handler to handle a single step event.
4994 mono_debugger_agent_single_step_event (void *sigctx)
4996 /* Resume to process_single_step through the signal context */
4998 // FIXME: Since step out/over is implemented using step in, the step in case should
4999 // be as fast as possible. Move the relevant code from process_single_step_inner ()
5002 if (GetCurrentThreadId () == debugger_thread_id) {
5004 * This could happen despite our best effors when the runtime calls
5005 * assembly/type resolve hooks.
5006 * FIXME: Breakpoints too.
5010 mono_sigctx_to_monoctx (sigctx, &ctx);
5011 mono_arch_skip_single_step (&ctx);
5012 mono_monoctx_to_sigctx (&ctx, sigctx);
5016 resume_from_signal_handler (sigctx, process_single_step);
5020 debugger_agent_single_step_from_context (MonoContext *ctx)
5022 DebuggerTlsData *tls;
5023 MonoThreadUnwindState orig_restore_state;
5025 if (GetCurrentThreadId () == debugger_thread_id)
5028 tls = mono_native_tls_get_value (debugger_tls_id);
5031 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
5032 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5033 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5034 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5036 process_single_step_inner (tls, FALSE);
5038 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5039 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5043 debugger_agent_breakpoint_from_context (MonoContext *ctx)
5045 DebuggerTlsData *tls;
5046 MonoThreadUnwindState orig_restore_state;
5048 if (GetCurrentThreadId () == debugger_thread_id)
5051 tls = mono_native_tls_get_value (debugger_tls_id);
5053 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5054 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5055 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5057 process_breakpoint_inner (tls, FALSE);
5059 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5060 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5064 * start_single_stepping:
5066 * Turn on single stepping. Can be called multiple times, for example,
5067 * by a single step event request + a suspend.
5070 start_single_stepping (void)
5072 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5073 int val = InterlockedIncrement (&ss_count);
5076 mono_arch_start_single_stepping ();
5078 if (ss_req != NULL && ss_invoke_addr == NULL) {
5079 DebuggerTlsData *tls;
5081 mono_loader_lock ();
5083 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
5084 ss_invoke_addr = tls->invoke_addr;
5086 mono_loader_unlock ();
5089 g_assert_not_reached ();
5094 stop_single_stepping (void)
5096 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5097 int val = InterlockedDecrement (&ss_count);
5100 mono_arch_stop_single_stepping ();
5102 ss_invoke_addr = NULL;
5104 g_assert_not_reached ();
5111 * Stop the single stepping operation given by SS_REQ.
5114 ss_stop (SingleStepReq *ss_req)
5119 for (l = ss_req->bps; l; l = l->next) {
5120 clear_breakpoint (l->data);
5122 g_slist_free (ss_req->bps);
5126 if (ss_req->global) {
5127 stop_single_stepping ();
5128 ss_req->global = FALSE;
5135 * Start the single stepping operation given by SS_REQ from the sequence point SP.
5136 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
5137 * belong to the same thread as CTX.
5138 * If FRAMES is not-null, use that instead of tls->frames for placing breakpoints etc.
5141 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint* sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls,
5142 gboolean step_to_catch, StackFrame **frames, int nframes)
5144 int i, j, frame_index;
5145 SeqPoint *next_sp, *parent_sp = NULL;
5146 SeqPoint local_sp, local_parent_sp;
5149 MonoSeqPointInfo *parent_info;
5150 MonoMethod *parent_sp_method = NULL;
5151 gboolean enable_global = FALSE;
5153 /* Stop the previous operation */
5157 * Implement single stepping using breakpoints if possible.
5159 if (step_to_catch) {
5160 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
5161 ss_req->bps = g_slist_append (ss_req->bps, bp);
5165 if (ctx && !frames) {
5166 /* Need parent frames */
5167 if (!tls->context.valid)
5168 mono_thread_state_init_from_monoctx (&tls->context, ctx);
5169 compute_frame_info (tls->thread, tls);
5170 frames = tls->frames;
5171 nframes = tls->frame_count;
5175 * Find the first sequence point in the current or in a previous frame which
5176 * is not the last in its method.
5178 if (ss_req->depth == STEP_DEPTH_OUT) {
5179 /* Ignore seq points in current method */
5180 while (frame_index < nframes) {
5181 StackFrame *frame = frames [frame_index];
5183 method = frame->method;
5184 found_sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5185 sp = (found_sp)? &local_sp : NULL;
5187 if (sp && sp->next_len != 0)
5190 // There could be method calls before the next seq point in the caller when using nested calls
5191 //enable_global = TRUE;
5193 if (sp && sp->next_len == 0) {
5195 while (frame_index < nframes) {
5196 StackFrame *frame = frames [frame_index];
5198 method = frame->method;
5199 found_sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5200 sp = (found_sp)? &local_sp : NULL;
5201 if (sp && sp->next_len != 0)
5207 /* Have to put a breakpoint into a parent frame since the seq points might not cover all control flow out of the method */
5208 while (frame_index < nframes) {
5209 StackFrame *frame = frames [frame_index];
5211 parent_sp_method = frame->method;
5212 found_sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &parent_info, &local_parent_sp);
5213 parent_sp = found_sp ? &local_parent_sp : NULL;
5214 if (found_sp && parent_sp->next_len != 0)
5222 if (sp && sp->next_len > 0) {
5223 SeqPoint* next = g_new(SeqPoint, sp->next_len);
5225 seq_point_init_next (info, *sp, next);
5226 for (i = 0; i < sp->next_len; i++) {
5229 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
5230 ss_req->bps = g_slist_append (ss_req->bps, bp);
5236 SeqPoint* next = g_new(SeqPoint, parent_sp->next_len);
5238 seq_point_init_next (parent_info, *parent_sp, next);
5239 for (i = 0; i < parent_sp->next_len; i++) {
5242 bp = set_breakpoint (parent_sp_method, next_sp->il_offset, ss_req->req, NULL);
5243 ss_req->bps = g_slist_append (ss_req->bps, bp);
5248 if (ss_req->nframes == 0)
5249 ss_req->nframes = nframes;
5251 if ((ss_req->depth == STEP_DEPTH_OVER) && (!sp && !parent_sp)) {
5252 DEBUG_PRINTF (1, "[dbg] No parent frame for step over, transition to step into.\n");
5254 * This is needed since if we leave managed code, and later return to it, step over
5255 * is not going to stop.
5256 * This approach is a bit ugly, since we change the step depth, but it only affects
5257 * clients who reuse the same step request, and only in this special case.
5259 ss_req->depth = STEP_DEPTH_INTO;
5262 if (ss_req->depth == STEP_DEPTH_OVER) {
5263 /* Need to stop in catch clauses as well */
5264 for (i = 0; i < nframes; ++i) {
5265 StackFrame *frame = frames [i];
5268 MonoJitInfo *jinfo = frame->ji;
5269 for (j = 0; j < jinfo->num_clauses; ++j) {
5270 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5272 found_sp = find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL, &local_sp);
5273 sp = (found_sp)? &local_sp : NULL;
5275 bp = set_breakpoint (frame->method, sp->il_offset, ss_req->req, NULL);
5276 ss_req->bps = g_slist_append (ss_req->bps, bp);
5283 if (ss_req->depth == STEP_DEPTH_INTO) {
5284 /* Enable global stepping so we stop at method entry too */
5285 enable_global = TRUE;
5289 * The ctx/frame info computed above will become invalid when we continue.
5291 tls->context.valid = FALSE;
5292 tls->async_state.valid = FALSE;
5293 invalidate_frames (tls);
5296 if (enable_global) {
5297 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5298 ss_req->global = TRUE;
5299 start_single_stepping ();
5300 } else if (!ss_req->bps) {
5301 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5302 ss_req->global = TRUE;
5303 start_single_stepping ();
5305 ss_req->global = FALSE;
5310 * Start single stepping of thread THREAD
5313 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req)
5315 DebuggerTlsData *tls;
5316 MonoSeqPointInfo *info = NULL;
5317 SeqPoint *sp = NULL;
5320 MonoMethod *method = NULL;
5321 MonoDebugMethodInfo *minfo;
5322 gboolean step_to_catch = FALSE;
5323 gboolean set_ip = FALSE;
5324 StackFrame **frames = NULL;
5327 if (suspend_count == 0)
5328 return ERR_NOT_SUSPENDED;
5330 wait_for_suspend ();
5332 // FIXME: Multiple requests
5334 DEBUG_PRINTF (0, "Received a single step request while the previous one was still active.\n");
5335 return ERR_NOT_IMPLEMENTED;
5338 DEBUG_PRINTF (1, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth));
5340 ss_req = g_new0 (SingleStepReq, 1);
5342 ss_req->thread = thread;
5343 ss_req->size = size;
5344 ss_req->depth = depth;
5345 ss_req->filter = filter;
5348 mono_loader_lock ();
5349 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5350 mono_loader_unlock ();
5352 g_assert (tls->context.valid);
5354 if (tls->restore_state.valid && MONO_CONTEXT_GET_IP (&tls->context.ctx) != MONO_CONTEXT_GET_IP (&tls->restore_state.ctx)) {
5356 * Need to start single stepping from restore_state and not from the current state
5359 frames = compute_frame_info_from (thread, tls, &tls->restore_state, &nframes);
5362 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5364 if (tls->catch_state.valid) {
5366 StackFrameInfo frame;
5367 MonoContext new_ctx;
5368 MonoLMF *lmf = NULL;
5371 * We are stopped at a throw site. Stepping should go to the catch site.
5374 /* Find the the jit info for the catch context */
5375 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);
5377 g_assert (frame.type == FRAME_TYPE_MANAGED);
5380 * Find the seq point corresponding to the landing site ip, which is the first seq
5383 found_sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info, &local_sp);
5384 sp = (found_sp)? &local_sp : NULL;
5386 no_seq_points_found (frame.method);
5389 method = frame.method;
5391 step_to_catch = TRUE;
5392 /* This make sure the seq point is not skipped by process_single_step () */
5393 ss_req->last_sp = NULL;
5396 if (!step_to_catch) {
5397 StackFrame *frame = NULL;
5400 if (frames && nframes)
5403 compute_frame_info (thread, tls);
5405 if (tls->frame_count)
5406 frame = tls->frames [0];
5409 if (ss_req->size == STEP_SIZE_LINE) {
5411 ss_req->last_method = frame->method;
5412 ss_req->last_line = -1;
5414 minfo = mono_debug_lookup_method (frame->method);
5415 if (minfo && frame->il_offset != -1) {
5416 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
5419 ss_req->last_line = loc->row;
5427 if (!method && frame->il_offset != -1) {
5428 /* FIXME: Sort the table and use a binary search */
5429 found_sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5430 sp = (found_sp)? &local_sp : NULL;
5432 no_seq_points_found (frame->method);
5434 method = frame->method;
5439 ss_req->start_method = method;
5441 ss_start (ss_req, method, sp, info, set_ip ? &tls->restore_state.ctx : &tls->context.ctx, tls, step_to_catch, frames, nframes);
5444 free_frames (frames, nframes);
5450 ss_destroy (SingleStepReq *req)
5453 g_assert (ss_req == req);
5462 ss_clear_for_assembly (SingleStepReq *req, MonoAssembly *assembly)
5465 gboolean found = TRUE;
5469 for (l = ss_req->bps; l; l = l->next) {
5470 if (breakpoint_matches_assembly (l->data, assembly)) {
5471 clear_breakpoint (l->data);
5472 ss_req->bps = g_slist_delete_link (ss_req->bps, l);
5481 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5484 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5490 if (!agent_config.enabled)
5493 mono_loader_lock ();
5494 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5495 mono_loader_unlock ();
5498 ei.category = category ? mono_string_to_utf8 (category) : NULL;
5499 ei.message = message ? mono_string_to_utf8 (message) : NULL;
5501 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5503 g_free (ei.category);
5504 g_free (ei.message);
5508 mono_debugger_agent_debug_log_is_enabled (void)
5510 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5511 return agent_config.enabled;
5514 #if defined(PLATFORM_ANDROID) || defined(TARGET_ANDROID)
5516 mono_debugger_agent_unhandled_exception (MonoException *exc)
5525 memset (&ei, 0, sizeof (EventInfo));
5526 ei.exc = (MonoObject*)exc;
5528 mono_loader_lock ();
5529 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5530 mono_loader_unlock ();
5532 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5537 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5538 MonoContext *catch_ctx)
5540 int i, j, suspend_policy;
5542 MonoJitInfo *ji, *catch_ji;
5544 DebuggerTlsData *tls = NULL;
5546 if (thread_to_tls != NULL) {
5547 MonoInternalThread *thread = mono_thread_internal_current ();
5549 mono_loader_lock ();
5550 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5551 mono_loader_unlock ();
5553 if (tls && tls->abort_requested)
5555 if (tls && tls->disable_breakpoints)
5559 memset (&ei, 0, sizeof (EventInfo));
5561 /* Just-In-Time debugging */
5563 if (agent_config.onuncaught && !inited) {
5564 finish_agent_init (FALSE);
5567 * Send an unsolicited EXCEPTION event with a dummy request id.
5569 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5570 ei.exc = (MonoObject*)exc;
5571 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5574 } else if (agent_config.onthrow && !inited) {
5576 gboolean found = FALSE;
5578 for (l = agent_config.onthrow; l; l = l->next) {
5579 char *ex_type = l->data;
5580 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5582 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5589 finish_agent_init (FALSE);
5592 * Send an unsolicited EXCEPTION event with a dummy request id.
5594 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5595 ei.exc = (MonoObject*)exc;
5596 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5604 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5606 catch_ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5610 ei.exc = (MonoObject*)exc;
5611 ei.caught = catch_ctx != NULL;
5613 mono_loader_lock ();
5615 /* Treat exceptions which are caught in non-user code as unhandled */
5616 for (i = 0; i < event_requests->len; ++i) {
5617 EventRequest *req = g_ptr_array_index (event_requests, i);
5618 if (req->event_kind != EVENT_KIND_EXCEPTION)
5621 for (j = 0; j < req->nmodifiers; ++j) {
5622 Modifier *mod = &req->modifiers [j];
5624 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5626 gboolean found = FALSE;
5627 MonoAssembly **assemblies = mod->data.assemblies;
5630 for (k = 0; assemblies [k]; ++k)
5631 if (assemblies [k] == jinfo_get_method (catch_ji)->klass->image->assembly)
5640 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5641 mono_loader_unlock ();
5643 if (tls && ei.caught && catch_ctx) {
5644 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5645 tls->catch_state.ctx = *catch_ctx;
5646 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5647 tls->catch_state.valid = TRUE;
5650 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5653 tls->catch_state.valid = FALSE;
5657 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5659 DebuggerTlsData *tls;
5664 tls = mono_native_tls_get_value (debugger_tls_id);
5669 * We're about to invoke an exception filter during the first pass of exception handling.
5671 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5672 * 'orig_ctx' is the context where the exception has been thrown.
5675 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5677 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5678 * the call site (line 37) and then continue to Main(), but it would never
5679 * include the throw site (line 32).
5681 * Since exception filters are invoked during the first pass of exception handling,
5682 * the stack frames of the throw site are still intact, so we should include them
5685 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5687 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5688 * but report the location of the 'throw' to the user.
5692 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5696 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5698 DebuggerTlsData *tls;
5703 tls = mono_native_tls_get_value (debugger_tls_id);
5707 tls->filter_state.valid = FALSE;
5711 * buffer_add_value_full:
5713 * Add the encoding of the value at ADDR described by T to the buffer.
5714 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5718 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5719 gboolean as_vtype, GHashTable *parent_vtypes)
5722 gboolean boxed_vtype = FALSE;
5725 if (!(*(void**)addr)) {
5726 /* This can happen with compiler generated locals */
5727 //printf ("%s\n", mono_type_full_name (t));
5728 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5731 g_assert (*(void**)addr);
5732 addr = *(void**)addr;
5737 case MONO_TYPE_BOOLEAN:
5740 case MONO_TYPE_CHAR:
5760 case MONO_TYPE_VOID:
5761 buffer_add_byte (buf, t->type);
5763 case MONO_TYPE_BOOLEAN:
5766 buffer_add_byte (buf, t->type);
5767 buffer_add_int (buf, *(gint8*)addr);
5769 case MONO_TYPE_CHAR:
5772 buffer_add_byte (buf, t->type);
5773 buffer_add_int (buf, *(gint16*)addr);
5778 buffer_add_byte (buf, t->type);
5779 buffer_add_int (buf, *(gint32*)addr);
5784 buffer_add_byte (buf, t->type);
5785 buffer_add_long (buf, *(gint64*)addr);
5789 /* Treat it as a vtype */
5791 case MONO_TYPE_PTR: {
5792 gssize val = *(gssize*)addr;
5794 buffer_add_byte (buf, t->type);
5795 buffer_add_long (buf, val);
5799 case MONO_TYPE_STRING:
5800 case MONO_TYPE_SZARRAY:
5801 case MONO_TYPE_OBJECT:
5802 case MONO_TYPE_CLASS:
5803 case MONO_TYPE_ARRAY:
5804 obj = *(MonoObject**)addr;
5807 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5809 if (obj->vtable->klass->valuetype) {
5810 t = &obj->vtable->klass->byval_arg;
5811 addr = mono_object_unbox (obj);
5814 } else if (obj->vtable->klass->rank) {
5815 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5816 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5817 buffer_add_byte (buf, MONO_TYPE_CLASS);
5819 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5821 buffer_add_objid (buf, obj);
5825 case MONO_TYPE_VALUETYPE:
5826 case MONO_TYPE_TYPEDBYREF: {
5830 MonoClass *klass = mono_class_from_mono_type (t);
5835 * Handle boxed vtypes recursively referencing themselves using fields.
5838 parent_vtypes = g_hash_table_new (NULL, NULL);
5839 vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
5841 if (CHECK_PROTOCOL_VERSION (2, 33)) {
5842 buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
5843 buffer_add_int (buf, vtype_index - 1);
5845 /* The client can't handle PARENT_VTYPE */
5846 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5850 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
5854 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5855 buffer_add_byte (buf, klass->enumtype);
5856 buffer_add_typeid (buf, domain, klass);
5860 while ((f = mono_class_get_fields (klass, &iter))) {
5861 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5863 if (mono_field_is_deleted (f))
5867 buffer_add_int (buf, nfields);
5870 while ((f = mono_class_get_fields (klass, &iter))) {
5871 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5873 if (mono_field_is_deleted (f))
5875 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE, parent_vtypes);
5879 g_hash_table_remove (parent_vtypes, addr);
5880 if (g_hash_table_size (parent_vtypes) == 0) {
5881 g_hash_table_destroy (parent_vtypes);
5882 parent_vtypes = NULL;
5887 case MONO_TYPE_GENERICINST:
5888 if (mono_type_generic_inst_is_valuetype (t)) {
5900 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5902 buffer_add_value_full (buf, t, addr, domain, FALSE, NULL);
5906 obj_is_of_type (MonoObject *obj, MonoType *t)
5908 MonoClass *klass = obj->vtable->klass;
5909 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5910 if (mono_class_is_transparent_proxy (klass)) {
5911 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5912 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5922 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5925 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5931 gpointer iter = NULL;
5935 is_enum = decode_byte (buf, &buf, limit);
5936 /* Enums are sent as a normal vtype */
5938 return ERR_NOT_IMPLEMENTED;
5939 klass = decode_typeid (buf, &buf, limit, &d, &err);
5943 if (t && klass != mono_class_from_mono_type (t)) {
5944 char *name = mono_type_full_name (t);
5945 char *name2 = mono_type_full_name (&klass->byval_arg);
5946 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got %s.\n", (gpointer)GetCurrentThreadId (), name, name2);
5949 return ERR_INVALID_ARGUMENT;
5952 nfields = decode_int (buf, &buf, limit);
5953 while ((f = mono_class_get_fields (klass, &iter))) {
5954 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5956 if (mono_field_is_deleted (f))
5958 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5963 g_assert (nfields == 0);
5971 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5975 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5976 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5977 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5978 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5979 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
5980 char *name = mono_type_full_name (t);
5981 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type);
5983 return ERR_INVALID_ARGUMENT;
5987 case MONO_TYPE_BOOLEAN:
5988 *(guint8*)addr = decode_int (buf, &buf, limit);
5990 case MONO_TYPE_CHAR:
5991 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5994 *(gint8*)addr = decode_int (buf, &buf, limit);
5997 *(guint8*)addr = decode_int (buf, &buf, limit);
6000 *(gint16*)addr = decode_int (buf, &buf, limit);
6003 *(guint16*)addr = decode_int (buf, &buf, limit);
6006 *(gint32*)addr = decode_int (buf, &buf, limit);
6009 *(guint32*)addr = decode_int (buf, &buf, limit);
6012 *(gint64*)addr = decode_long (buf, &buf, limit);
6015 *(guint64*)addr = decode_long (buf, &buf, limit);
6018 *(guint32*)addr = decode_int (buf, &buf, limit);
6021 *(guint64*)addr = decode_long (buf, &buf, limit);
6024 /* We send these as I8, so we get them back as such */
6025 g_assert (type == MONO_TYPE_I8);
6026 *(gssize*)addr = decode_long (buf, &buf, limit);
6028 case MONO_TYPE_GENERICINST:
6029 if (MONO_TYPE_ISSTRUCT (t)) {
6030 /* The client sends these as a valuetype */
6038 /* We send these as vtypes, so we get them back as such */
6039 g_assert (type == MONO_TYPE_VALUETYPE);
6042 case MONO_TYPE_VALUETYPE:
6043 err = decode_vtype (t, domain, addr,buf, &buf, limit);
6049 if (MONO_TYPE_IS_REFERENCE (t)) {
6050 if (type == MONO_TYPE_OBJECT) {
6051 int objid = decode_objid (buf, &buf, limit);
6055 err = get_object (objid, (MonoObject**)&obj);
6060 if (!obj_is_of_type (obj, t)) {
6061 DEBUG_PRINTF (1, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6062 return ERR_INVALID_ARGUMENT;
6065 if (obj && obj->vtable->domain != domain)
6066 return ERR_INVALID_ARGUMENT;
6068 mono_gc_wbarrier_generic_store (addr, obj);
6069 } else if (type == VALUE_TYPE_ID_NULL) {
6070 *(MonoObject**)addr = NULL;
6071 } else if (type == MONO_TYPE_VALUETYPE) {
6079 /* This can happen when round-tripping boxed vtypes */
6081 * Obtain vtype class.
6082 * Same as the beginning of the handle_vtype case above.
6085 is_enum = decode_byte (buf, &buf, limit);
6087 return ERR_NOT_IMPLEMENTED;
6088 klass = decode_typeid (buf, &buf, limit, &d, &err);
6092 /* Decode the vtype into a temporary buffer, then box it. */
6093 vtype_buf_size = mono_class_value_size (klass, NULL);
6094 vtype_buf = g_malloc0 (vtype_buf_size);
6095 g_assert (vtype_buf);
6098 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
6103 *(MonoObject**)addr = mono_value_box (d, klass, vtype_buf);
6106 char *name = mono_type_full_name (t);
6107 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type);
6109 return ERR_INVALID_ARGUMENT;
6123 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6126 int type = decode_byte (buf, &buf, limit);
6128 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
6129 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
6130 guint8 *nullable_buf;
6133 * First try decoding it as a Nullable`1
6135 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6140 * Then try decoding as a primitive value or null.
6142 if (targ->type == type) {
6143 nullable_buf = g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
6144 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
6146 g_free (nullable_buf);
6149 mono_nullable_init (addr, mono_value_box (domain, mono_class_from_mono_type (targ), nullable_buf), mono_class_from_mono_type (t));
6150 g_free (nullable_buf);
6153 } else if (type == VALUE_TYPE_ID_NULL) {
6154 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
6160 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6164 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
6168 guint8 *addr, *gaddr;
6171 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6172 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6175 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
6176 reg_val = mono_arch_context_get_int_reg (ctx, reg);
6178 buffer_add_value_full (buf, t, ®_val, domain, as_vtype, NULL);
6180 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6181 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6182 addr += (gint32)var->offset;
6184 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6186 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6188 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6191 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6192 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
6193 /* Same as regoffset, but with an indirection */
6194 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6195 addr += (gint32)var->offset;
6197 gaddr = *(gpointer*)addr;
6199 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL);
6201 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
6202 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
6203 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
6204 MonoGSharedVtMethodRuntimeInfo *info;
6210 g_assert (info_var);
6211 g_assert (locals_var);
6213 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6214 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6215 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6216 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6217 addr += (gint32)info_var->offset;
6218 info = *(gpointer*)addr;
6219 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6220 info = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6222 g_assert_not_reached ();
6226 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6227 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6228 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6229 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6230 addr += (gint32)locals_var->offset;
6231 locals = *(gpointer*)addr;
6232 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6233 locals = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6235 g_assert_not_reached ();
6239 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6241 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6246 g_assert_not_reached ();
6251 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
6255 guint8 *addr, *gaddr;
6257 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6258 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6260 if (MONO_TYPE_IS_REFERENCE (t))
6261 size = sizeof (gpointer);
6263 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6266 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6267 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6269 gboolean is_signed = FALSE;
6272 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6275 // FIXME: Write barriers
6276 mono_gc_memmove_atomic (addr, val, size);
6281 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6286 v = is_signed ? *(gint8*)val : *(guint8*)val;
6289 v = is_signed ? *(gint16*)val : *(guint16*)val;
6292 v = is_signed ? *(gint32*)val : *(guint32*)val;
6295 v = is_signed ? *(gint64*)val : *(guint64*)val;
6298 g_assert_not_reached ();
6301 /* Set value on the stack or in the return ctx */
6302 if (reg_locations [reg]) {
6303 /* Saved on the stack */
6304 DEBUG_PRINTF (1, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v);
6305 *(reg_locations [reg]) = v;
6308 DEBUG_PRINTF (1, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v);
6309 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6312 // FIXME: Move these to mono-context.h/c.
6313 mono_arch_context_set_int_reg (ctx, reg, v);
6315 // FIXME: Can't set registers, so we disable linears
6320 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6321 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6322 addr += (gint32)var->offset;
6324 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6327 addr = *(guint8**)addr;
6333 // FIXME: Write barriers
6334 mono_gc_memmove_atomic (addr, val, size);
6336 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6337 /* Same as regoffset, but with an indirection */
6338 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6339 addr += (gint32)var->offset;
6341 gaddr = *(gpointer*)addr;
6343 // FIXME: Write barriers
6344 mono_gc_memmove_atomic (gaddr, val, size);
6346 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6350 g_assert_not_reached ();
6355 clear_event_request (int req_id, int etype)
6359 mono_loader_lock ();
6360 for (i = 0; i < event_requests->len; ++i) {
6361 EventRequest *req = g_ptr_array_index (event_requests, i);
6363 if (req->id == req_id && req->event_kind == etype) {
6364 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6365 clear_breakpoint (req->info);
6366 if (req->event_kind == EVENT_KIND_STEP)
6367 ss_destroy (req->info);
6368 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6369 clear_breakpoint (req->info);
6370 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6371 clear_breakpoint (req->info);
6372 g_ptr_array_remove_index_fast (event_requests, i);
6377 mono_loader_unlock ();
6381 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
6385 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6386 m->kind = MOD_KIND_NONE;
6387 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6388 int count = 0, match_count = 0, pos;
6389 MonoAssembly **newassemblies;
6391 for (i = 0; m->data.assemblies [i]; ++i) {
6393 if (m->data.assemblies [i] == assembly)
6398 newassemblies = g_new0 (MonoAssembly*, count - match_count);
6401 for (i = 0; i < count; ++i)
6402 if (m->data.assemblies [i] != assembly)
6403 newassemblies [pos ++] = m->data.assemblies [i];
6404 g_assert (pos == count - match_count);
6405 g_free (m->data.assemblies);
6406 m->data.assemblies = newassemblies;
6412 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
6416 for (i = 0; i < req->nmodifiers; ++i) {
6417 Modifier *m = &req->modifiers [i];
6419 clear_assembly_from_modifier (req, m, assembly);
6424 * clear_event_requests_for_assembly:
6426 * Clear all events requests which reference ASSEMBLY.
6429 clear_event_requests_for_assembly (MonoAssembly *assembly)
6434 mono_loader_lock ();
6438 for (i = 0; i < event_requests->len; ++i) {
6439 EventRequest *req = g_ptr_array_index (event_requests, i);
6441 clear_assembly_from_modifiers (req, assembly);
6443 if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly (req->info, assembly)) {
6444 clear_event_request (req->id, req->event_kind);
6449 if (req->event_kind == EVENT_KIND_STEP)
6450 ss_clear_for_assembly (req->info, assembly);
6453 mono_loader_unlock ();
6457 * type_comes_from_assembly:
6459 * GHRFunc that returns TRUE if klass comes from assembly
6462 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6464 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6468 * clear_types_for_assembly:
6470 * Clears types from loaded_classes for a given assembly
6473 clear_types_for_assembly (MonoAssembly *assembly)
6475 MonoDomain *domain = mono_domain_get ();
6476 AgentDomainInfo *info = NULL;
6478 if (!domain || !domain_jit_info (domain))
6479 /* Can happen during shutdown */
6482 mono_loader_lock ();
6483 info = get_agent_domain_info (domain);
6484 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6485 mono_loader_unlock ();
6489 add_thread (gpointer key, gpointer value, gpointer user_data)
6491 MonoInternalThread *thread = value;
6492 Buffer *buf = user_data;
6494 buffer_add_objid (buf, (MonoObject*)thread);
6498 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6500 guint8 *end = invoke->endp;
6503 MonoMethodSignature *sig;
6506 MonoObject *this, *res, *exc;
6509 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6512 MonoStopwatch watch;
6514 if (invoke->method) {
6516 * Invoke this method directly, currently only Environment.Exit () is supported.
6519 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>");
6520 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
6521 g_assert_not_reached ();
6524 m = decode_methodid (p, &p, end, &domain, &err);
6527 sig = mono_method_signature (m);
6529 if (m->klass->valuetype)
6530 this_buf = g_alloca (mono_class_instance_size (m->klass));
6532 this_buf = g_alloca (sizeof (MonoObject*));
6533 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6534 /* Should be null */
6535 int type = decode_byte (p, &p, end);
6536 if (type != VALUE_TYPE_ID_NULL) {
6537 DEBUG_PRINTF (1, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer)GetCurrentThreadId ());
6538 return ERR_INVALID_ARGUMENT;
6540 memset (this_buf, 0, mono_class_instance_size (m->klass));
6542 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6547 if (!m->klass->valuetype)
6548 this = *(MonoObject**)this_buf;
6552 if (MONO_CLASS_IS_INTERFACE (m->klass)) {
6554 DEBUG_PRINTF (1, "[%p] Error: Interface method invoked without this argument.\n", (gpointer)GetCurrentThreadId ());
6555 return ERR_INVALID_ARGUMENT;
6557 m = mono_object_get_virtual_method (this, m);
6558 } else if ((m->flags & METHOD_ATTRIBUTE_VIRTUAL) && !m->klass->valuetype && invoke->flags & INVOKE_FLAG_VIRTUAL) {
6560 DEBUG_PRINTF (1, "[%p] Error: invoke with INVOKE_FLAG_VIRTUAL flag set without this argument.\n", (gpointer)GetCurrentThreadId ());
6561 return ERR_INVALID_ARGUMENT;
6563 m = mono_object_get_virtual_method (this, m);
6566 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>");
6568 if (this && this->vtable->domain != domain)
6571 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
6572 if (!strcmp (m->name, ".ctor")) {
6573 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
6574 return ERR_INVALID_ARGUMENT;
6576 this = mono_object_new (domain, m->klass);
6578 return ERR_INVALID_ARGUMENT;
6582 if (this && !obj_is_of_type (this, &m->klass->byval_arg))
6583 return ERR_INVALID_ARGUMENT;
6585 nargs = decode_int (p, &p, end);
6586 if (nargs != sig->param_count)
6587 return ERR_INVALID_ARGUMENT;
6588 /* Use alloca to get gc tracking */
6589 arg_buf = g_alloca (nargs * sizeof (gpointer));
6590 memset (arg_buf, 0, nargs * sizeof (gpointer));
6591 args = g_alloca (nargs * sizeof (gpointer));
6592 for (i = 0; i < nargs; ++i) {
6593 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6594 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6597 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6600 if (sig->params [i]->byref) {
6601 arg_buf [i] = g_alloca (sizeof (mgreg_t));
6602 *(gpointer*)arg_buf [i] = args [i];
6603 args [i] = arg_buf [i];
6606 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6607 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6610 args [i] = arg_buf [i];
6617 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6618 tls->disable_breakpoints = TRUE;
6620 tls->disable_breakpoints = FALSE;
6623 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6625 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6626 if (invoke->has_ctx) {
6629 lmf_addr = mono_get_lmf_addr ();
6632 memset (&ext, 0, sizeof (ext));
6633 mono_arch_init_lmf_ext (&ext, *lmf_addr);
6635 ext.debugger_invoke = TRUE;
6636 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6638 mono_set_lmf ((MonoLMF*)&ext);
6642 mono_stopwatch_start (&watch);
6643 if (m->klass->valuetype)
6644 res = mono_runtime_invoke (m, this_buf, args, &exc);
6646 res = mono_runtime_invoke (m, this, args, &exc);
6647 mono_stopwatch_stop (&watch);
6648 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));
6650 buffer_add_byte (buf, 0);
6651 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6653 gboolean out_this = FALSE;
6654 gboolean out_args = FALSE;
6656 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_THIS) && CHECK_PROTOCOL_VERSION (2, 35))
6658 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_ARGS) && CHECK_PROTOCOL_VERSION (2, 35))
6660 buffer_add_byte (buf, 1 + (out_this ? 2 : 0) + (out_args ? 4 : 0));
6661 if (sig->ret->type == MONO_TYPE_VOID) {
6662 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
6663 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
6666 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6667 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6668 buffer_add_value (buf, sig->ret, &res, domain);
6669 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6670 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6671 MonoClass *k = mono_class_from_mono_type (sig->ret);
6672 guint8 *nullable_buf = g_alloca (mono_class_value_size (k, NULL));
6674 g_assert (nullable_buf);
6675 mono_nullable_init (nullable_buf, res, k);
6676 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6679 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6685 /* Return the new value of the receiver after the call */
6686 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
6688 buffer_add_int (buf, nargs);
6689 for (i = 0; i < nargs; ++i) {
6690 if (MONO_TYPE_IS_REFERENCE (sig->params [i]))
6691 buffer_add_value (buf, sig->params [i], &args [i], domain);
6692 else if (sig->params [i]->byref)
6693 /* add_value () does an indirection */
6694 buffer_add_value (buf, sig->params [i], &arg_buf [i], domain);
6696 buffer_add_value (buf, sig->params [i], arg_buf [i], domain);
6701 tls->disable_breakpoints = FALSE;
6703 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6704 if (invoke->has_ctx)
6705 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
6709 // FIXME: byref arguments
6717 * Invoke the method given by tls->pending_invoke in the current thread.
6720 invoke_method (void)
6722 DebuggerTlsData *tls;
6727 MonoContext restore_ctx;
6730 tls = mono_native_tls_get_value (debugger_tls_id);
6734 * Store the `InvokeData *' in `tls->invoke' until we're done with
6735 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6738 mono_loader_lock ();
6740 invoke = tls->pending_invoke;
6742 tls->pending_invoke = NULL;
6744 invoke->last_invoke = tls->invoke;
6745 tls->invoke = invoke;
6747 mono_loader_unlock ();
6749 tls->frames_up_to_date = FALSE;
6755 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6756 buffer_init (&buf, 128);
6759 /* Fail the other invokes as well */
6761 err = do_invoke_method (tls, &buf, invoke, p, &p);
6764 /* Start suspending before sending the reply */
6765 if (mindex == invoke->nmethods - 1) {
6766 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6767 for (i = 0; i < invoke->suspend_count; ++i)
6772 send_reply_packet (id, err, &buf);
6777 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6779 if (invoke->has_ctx)
6780 save_thread_context (&restore_ctx);
6782 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6783 g_assert (tls->resume_count);
6784 tls->resume_count -= invoke->suspend_count;
6787 DEBUG_PRINTF (1, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer)GetCurrentThreadId (), err, tls->resume_count);
6790 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6792 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
6793 * after the mono_runtime_invoke() already returned, but it doesn't matter
6794 * because we reset the abort here.
6797 mono_loader_lock ();
6799 if (tls->abort_requested)
6800 mono_thread_internal_reset_abort (tls->thread);
6802 tls->invoke = tls->invoke->last_invoke;
6803 tls->abort_requested = FALSE;
6805 mono_loader_unlock ();
6814 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6816 MonoThread *thread = value;
6817 DebuggerTlsData *tls;
6820 mono_loader_lock ();
6821 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6823 res = tls->really_suspended;
6824 mono_loader_unlock ();
6830 get_source_files_for_type (MonoClass *klass)
6832 gpointer iter = NULL;
6834 MonoDebugSourceInfo *sinfo;
6838 files = g_ptr_array_new ();
6840 while ((method = mono_class_get_methods (klass, &iter))) {
6841 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6842 GPtrArray *source_file_list;
6845 mono_debug_symfile_get_line_numbers_full (minfo, NULL, &source_file_list, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
6846 for (j = 0; j < source_file_list->len; ++j) {
6847 sinfo = g_ptr_array_index (source_file_list, j);
6848 for (i = 0; i < files->len; ++i)
6849 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6851 if (i == files->len)
6852 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6854 g_ptr_array_free (source_file_list, TRUE);
6862 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6865 case CMD_VM_VERSION: {
6866 char *build_info, *version;
6868 build_info = mono_get_runtime_build_info ();
6869 version = g_strdup_printf ("mono %s", build_info);
6871 buffer_add_string (buf, version); /* vm version */
6872 buffer_add_int (buf, MAJOR_VERSION);
6873 buffer_add_int (buf, MINOR_VERSION);
6874 g_free (build_info);
6878 case CMD_VM_SET_PROTOCOL_VERSION: {
6879 major_version = decode_int (p, &p, end);
6880 minor_version = decode_int (p, &p, end);
6881 protocol_version_set = TRUE;
6882 DEBUG_PRINTF (1, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version);
6885 case CMD_VM_ALL_THREADS: {
6887 mono_loader_lock ();
6888 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6889 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6890 mono_loader_unlock ();
6893 case CMD_VM_SUSPEND:
6895 wait_for_suspend ();
6898 if (suspend_count == 0)
6899 return ERR_NOT_SUSPENDED;
6901 clear_suspended_objs ();
6903 case CMD_VM_DISPOSE:
6904 /* Clear all event requests */
6905 mono_loader_lock ();
6906 while (event_requests->len > 0) {
6907 EventRequest *req = g_ptr_array_index (event_requests, 0);
6909 clear_event_request (req->id, req->event_kind);
6911 mono_loader_unlock ();
6913 while (suspend_count > 0)
6915 disconnected = TRUE;
6916 vm_start_event_sent = FALSE;
6919 MonoInternalThread *thread;
6920 DebuggerTlsData *tls;
6921 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6922 MonoClass *env_class;
6924 MonoMethod *exit_method = NULL;
6928 exit_code = decode_int (p, &p, end);
6930 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6932 /* Have to send a reply before exiting */
6933 send_reply_packet (id, 0, buf);
6935 /* Clear all event requests */
6936 mono_loader_lock ();
6937 while (event_requests->len > 0) {
6938 EventRequest *req = g_ptr_array_index (event_requests, 0);
6940 clear_event_request (req->id, req->event_kind);
6942 mono_loader_unlock ();
6945 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6946 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6947 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6948 * better than doing the shutdown ourselves, since it avoids various races.
6952 wait_for_suspend ();
6954 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6955 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
6957 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6960 mono_loader_lock ();
6961 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6962 mono_loader_unlock ();
6964 if (thread && exit_method) {
6965 mono_loader_lock ();
6966 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6967 mono_loader_unlock ();
6969 args = g_new0 (gpointer, 1);
6970 args [0] = g_malloc (sizeof (int));
6971 *(int*)(args [0]) = exit_code;
6973 tls->pending_invoke = g_new0 (InvokeData, 1);
6974 tls->pending_invoke->method = exit_method;
6975 tls->pending_invoke->args = args;
6976 tls->pending_invoke->nmethods = 1;
6978 while (suspend_count > 0)
6982 * No thread found, do it ourselves.
6983 * FIXME: This can race with normal shutdown etc.
6985 while (suspend_count > 0)
6988 if (!mono_runtime_try_shutdown ())
6991 mono_environment_exitcode_set (exit_code);
6993 /* Suspend all managed threads since the runtime is going away */
6994 DEBUG_PRINTF (1, "Suspending all threads...\n");
6995 mono_thread_suspend_all_other_threads ();
6996 DEBUG_PRINTF (1, "Shutting down the runtime...\n");
6997 mono_runtime_quit ();
6998 transport_close2 ();
6999 DEBUG_PRINTF (1, "Exiting...\n");
7005 case CMD_VM_INVOKE_METHOD:
7006 case CMD_VM_INVOKE_METHODS: {
7007 int objid = decode_objid (p, &p, end);
7009 DebuggerTlsData *tls;
7010 int i, count, err, flags, nmethods;
7012 err = get_object (objid, (MonoObject**)&thread);
7016 flags = decode_int (p, &p, end);
7018 if (command == CMD_VM_INVOKE_METHODS)
7019 nmethods = decode_int (p, &p, end);
7023 // Wait for suspending if it already started
7025 wait_for_suspend ();
7026 if (!is_suspended ())
7027 return ERR_NOT_SUSPENDED;
7029 mono_loader_lock ();
7030 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7031 mono_loader_unlock ();
7034 if (!tls->really_suspended)
7035 /* The thread is still running native code, can't do invokes */
7036 return ERR_NOT_SUSPENDED;
7039 * Store the invoke data into tls, the thread will execute it after it is
7042 if (tls->pending_invoke)
7043 return ERR_NOT_SUSPENDED;
7044 tls->pending_invoke = g_new0 (InvokeData, 1);
7045 tls->pending_invoke->id = id;
7046 tls->pending_invoke->flags = flags;
7047 tls->pending_invoke->p = g_malloc (end - p);
7048 memcpy (tls->pending_invoke->p, p, end - p);
7049 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
7050 tls->pending_invoke->suspend_count = suspend_count;
7051 tls->pending_invoke->nmethods = nmethods;
7053 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
7054 resume_thread (THREAD_TO_INTERNAL (thread));
7057 count = suspend_count;
7058 for (i = 0; i < count; ++i)
7063 case CMD_VM_ABORT_INVOKE: {
7064 int objid = decode_objid (p, &p, end);
7066 DebuggerTlsData *tls;
7069 err = get_object (objid, (MonoObject**)&thread);
7073 invoke_id = decode_int (p, &p, end);
7075 mono_loader_lock ();
7076 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7079 if (tls->abort_requested) {
7080 mono_loader_unlock ();
7085 * Check whether we're still inside the mono_runtime_invoke() and that it's
7086 * actually the correct invocation.
7088 * Careful, we do not stop the thread that's doing the invocation, so we can't
7089 * inspect its stack. However, invoke_method() also acquires the loader lock
7090 * when it's done, so we're safe here.
7094 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
7095 mono_loader_unlock ();
7096 return ERR_NO_INVOCATION;
7099 tls->abort_requested = TRUE;
7101 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
7102 mono_loader_unlock ();
7106 case CMD_VM_SET_KEEPALIVE: {
7107 int timeout = decode_int (p, &p, end);
7108 agent_config.keepalive = timeout;
7110 #ifndef DISABLE_SOCKET_TRANSPORT
7117 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
7118 GHashTableIter iter, kiter;
7123 char *fname, *basename;
7124 gboolean ignore_case;
7125 GSList *class_list, *l;
7126 GPtrArray *res_classes, *res_domains;
7128 fname = decode_string (p, &p, end);
7129 ignore_case = decode_byte (p, &p, end);
7131 basename = dbg_path_get_basename (fname);
7133 res_classes = g_ptr_array_new ();
7134 res_domains = g_ptr_array_new ();
7136 mono_loader_lock ();
7137 g_hash_table_iter_init (&iter, domains);
7138 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7139 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
7141 /* Update 'source_file_to_class' cache */
7142 g_hash_table_iter_init (&kiter, info->loaded_classes);
7143 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
7144 if (!g_hash_table_lookup (info->source_files, klass)) {
7145 files = get_source_files_for_type (klass);
7146 g_hash_table_insert (info->source_files, klass, files);
7148 for (i = 0; i < files->len; ++i) {
7149 char *s = g_ptr_array_index (files, i);
7150 char *s2 = dbg_path_get_basename (s);
7153 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
7155 class_list = g_slist_prepend (class_list, klass);
7156 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
7158 class_list = g_slist_prepend (class_list, klass);
7159 g_hash_table_insert (info->source_file_to_class, s2, class_list);
7162 /* The _ignorecase hash contains the lowercase path */
7163 s3 = strdup_tolower (s2);
7164 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
7166 class_list = g_slist_prepend (class_list, klass);
7167 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
7169 class_list = g_slist_prepend (class_list, klass);
7170 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
7182 s = strdup_tolower (basename);
7183 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
7186 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
7189 for (l = class_list; l; l = l->next) {
7192 g_ptr_array_add (res_classes, klass);
7193 g_ptr_array_add (res_domains, domain);
7196 mono_loader_unlock ();
7201 buffer_add_int (buf, res_classes->len);
7202 for (i = 0; i < res_classes->len; ++i)
7203 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
7204 g_ptr_array_free (res_classes, TRUE);
7205 g_ptr_array_free (res_domains, TRUE);
7208 case CMD_VM_GET_TYPES: {
7209 GHashTableIter iter;
7213 gboolean ignore_case;
7214 GPtrArray *res_classes, *res_domains;
7215 MonoTypeNameParse info;
7217 name = decode_string (p, &p, end);
7218 ignore_case = decode_byte (p, &p, end);
7220 if (!mono_reflection_parse_type (name, &info)) {
7222 mono_reflection_free_type_info (&info);
7223 return ERR_INVALID_ARGUMENT;
7226 res_classes = g_ptr_array_new ();
7227 res_domains = g_ptr_array_new ();
7229 mono_loader_lock ();
7230 g_hash_table_iter_init (&iter, domains);
7231 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7233 gboolean type_resolve;
7237 mono_domain_assemblies_lock (domain);
7238 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7242 type_resolve = TRUE;
7243 t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
7245 g_ptr_array_add (res_classes, mono_type_get_class (t));
7246 g_ptr_array_add (res_domains, domain);
7250 mono_domain_assemblies_unlock (domain);
7252 mono_loader_unlock ();
7255 mono_reflection_free_type_info (&info);
7257 buffer_add_int (buf, res_classes->len);
7258 for (i = 0; i < res_classes->len; ++i)
7259 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
7260 g_ptr_array_free (res_classes, TRUE);
7261 g_ptr_array_free (res_domains, TRUE);
7264 case CMD_VM_START_BUFFERING:
7265 case CMD_VM_STOP_BUFFERING:
7266 /* Handled in the main loop */
7269 return ERR_NOT_IMPLEMENTED;
7276 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7282 case CMD_EVENT_REQUEST_SET: {
7284 int i, event_kind, suspend_policy, nmodifiers, mod;
7287 MonoThread *step_thread;
7288 int size = 0, depth = 0, filter = 0, step_thread_id = 0;
7292 event_kind = decode_byte (p, &p, end);
7293 suspend_policy = decode_byte (p, &p, end);
7294 nmodifiers = decode_byte (p, &p, end);
7296 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7297 req->id = InterlockedIncrement (&event_request_id);
7298 req->event_kind = event_kind;
7299 req->suspend_policy = suspend_policy;
7300 req->nmodifiers = nmodifiers;
7303 for (i = 0; i < nmodifiers; ++i) {
7304 mod = decode_byte (p, &p, end);
7306 req->modifiers [i].kind = mod;
7307 if (mod == MOD_KIND_COUNT) {
7308 req->modifiers [i].data.count = decode_int (p, &p, end);
7309 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7310 method = decode_methodid (p, &p, end, &domain, &err);
7313 location = decode_long (p, &p, end);
7314 } else if (mod == MOD_KIND_STEP) {
7315 step_thread_id = decode_id (p, &p, end);
7316 size = decode_int (p, &p, end);
7317 depth = decode_int (p, &p, end);
7318 if (CHECK_PROTOCOL_VERSION (2, 16))
7319 filter = decode_int (p, &p, end);
7320 req->modifiers [i].data.filter = filter;
7321 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7322 /* Treat STEP_THOUGH the same as HIDDEN */
7323 req->modifiers [i].data.filter |= STEP_FILTER_DEBUGGER_STEP_THROUGH;
7324 } else if (mod == MOD_KIND_THREAD_ONLY) {
7325 int id = decode_id (p, &p, end);
7327 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7332 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7333 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7337 req->modifiers [i].caught = decode_byte (p, &p, end);
7338 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7339 if (CHECK_PROTOCOL_VERSION (2, 25))
7340 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7342 req->modifiers [i].subclasses = TRUE;
7343 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" : "");
7345 req->modifiers [i].data.exc_class = exc_class;
7347 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
7349 return ERR_INVALID_ARGUMENT;
7352 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7353 int n = decode_int (p, &p, end);
7356 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
7357 for (j = 0; j < n; ++j) {
7358 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7360 g_free (req->modifiers [i].data.assemblies);
7364 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7365 int n = decode_int (p, &p, end);
7368 modifier = &req->modifiers [i];
7369 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7370 for (j = 0; j < n; ++j) {
7371 char *s = decode_string (p, &p, end);
7375 s2 = strdup_tolower (s);
7376 g_hash_table_insert (modifier->data.source_files, s2, s2);
7380 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7381 int n = decode_int (p, &p, end);
7384 modifier = &req->modifiers [i];
7385 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7386 for (j = 0; j < n; ++j) {
7387 char *s = decode_string (p, &p, end);
7390 g_hash_table_insert (modifier->data.type_names, s, s);
7394 return ERR_NOT_IMPLEMENTED;
7398 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7401 req->info = set_breakpoint (method, location, req, &error);
7402 if (!mono_error_ok (&error)) {
7404 DEBUG_PRINTF (1, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error));
7405 mono_error_cleanup (&error);
7406 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7408 } else if (req->event_kind == EVENT_KIND_STEP) {
7409 g_assert (step_thread_id);
7411 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7417 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, filter, req);
7422 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7423 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7424 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7425 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7426 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7427 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7429 if (req->nmodifiers) {
7431 return ERR_NOT_IMPLEMENTED;
7435 mono_loader_lock ();
7436 g_ptr_array_add (event_requests, req);
7438 if (agent_config.defer) {
7439 /* Transmit cached data to the client on receipt of the event request */
7440 switch (req->event_kind) {
7441 case EVENT_KIND_APPDOMAIN_CREATE:
7442 /* Emit load events for currently loaded domains */
7443 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7445 case EVENT_KIND_ASSEMBLY_LOAD:
7446 /* Emit load events for currently loaded assemblies */
7447 mono_assembly_foreach (emit_assembly_load, NULL);
7449 case EVENT_KIND_THREAD_START:
7450 /* Emit start events for currently started threads */
7451 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7453 case EVENT_KIND_TYPE_LOAD:
7454 /* Emit type load events for currently loaded types */
7455 mono_domain_foreach (send_types_for_domain, NULL);
7461 mono_loader_unlock ();
7463 buffer_add_int (buf, req->id);
7466 case CMD_EVENT_REQUEST_CLEAR: {
7467 int etype = decode_byte (p, &p, end);
7468 int req_id = decode_int (p, &p, end);
7470 // FIXME: Make a faster mapping from req_id to request
7471 mono_loader_lock ();
7472 clear_event_request (req_id, etype);
7473 mono_loader_unlock ();
7476 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7479 mono_loader_lock ();
7481 while (i < event_requests->len) {
7482 EventRequest *req = g_ptr_array_index (event_requests, i);
7484 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7485 clear_breakpoint (req->info);
7487 g_ptr_array_remove_index_fast (event_requests, i);
7493 mono_loader_unlock ();
7497 return ERR_NOT_IMPLEMENTED;
7504 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7510 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7511 buffer_add_domainid (buf, mono_get_root_domain ());
7514 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7515 domain = decode_domainid (p, &p, end, NULL, &err);
7518 buffer_add_string (buf, domain->friendly_name);
7521 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7526 domain = decode_domainid (p, &p, end, NULL, &err);
7529 mono_loader_lock ();
7531 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7534 buffer_add_int (buf, count);
7535 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7537 buffer_add_assemblyid (buf, domain, ass);
7539 mono_loader_unlock ();
7542 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7543 domain = decode_domainid (p, &p, end, NULL, &err);
7547 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7550 case CMD_APPDOMAIN_GET_CORLIB: {
7551 domain = decode_domainid (p, &p, end, NULL, &err);
7555 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7558 case CMD_APPDOMAIN_CREATE_STRING: {
7562 domain = decode_domainid (p, &p, end, NULL, &err);
7565 s = decode_string (p, &p, end);
7567 o = mono_string_new (domain, s);
7568 buffer_add_objid (buf, (MonoObject*)o);
7571 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7573 MonoDomain *domain2;
7576 domain = decode_domainid (p, &p, end, NULL, &err);
7579 klass = decode_typeid (p, &p, end, &domain2, &err);
7584 g_assert (domain == domain2);
7586 o = mono_object_new (domain, klass);
7588 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
7592 buffer_add_objid (buf, o);
7596 return ERR_NOT_IMPLEMENTED;
7603 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7609 ass = decode_assemblyid (p, &p, end, &domain, &err);
7614 case CMD_ASSEMBLY_GET_LOCATION: {
7615 buffer_add_string (buf, mono_image_get_filename (ass->image));
7618 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7622 if (ass->image->dynamic) {
7623 buffer_add_id (buf, 0);
7625 token = mono_image_get_entry_point (ass->image);
7627 buffer_add_id (buf, 0);
7629 m = mono_get_method (ass->image, token, NULL);
7630 buffer_add_methodid (buf, domain, m);
7635 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7636 buffer_add_moduleid (buf, domain, ass->image);
7639 case CMD_ASSEMBLY_GET_OBJECT: {
7640 MonoObject *o = (MonoObject*)mono_assembly_get_object (domain, ass);
7641 buffer_add_objid (buf, o);
7644 case CMD_ASSEMBLY_GET_TYPE: {
7645 char *s = decode_string (p, &p, end);
7646 gboolean ignorecase = decode_byte (p, &p, end);
7647 MonoTypeNameParse info;
7649 gboolean type_resolve, res;
7650 MonoDomain *d = mono_domain_get ();
7652 /* This is needed to be able to find referenced assemblies */
7653 res = mono_domain_set (domain, FALSE);
7656 if (!mono_reflection_parse_type (s, &info)) {
7659 if (info.assembly.name)
7661 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
7663 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
7664 mono_reflection_free_type_info (&info);
7667 mono_domain_set (d, TRUE);
7671 case CMD_ASSEMBLY_GET_NAME: {
7673 MonoAssembly *mass = ass;
7675 name = g_strdup_printf (
7676 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7678 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7679 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7680 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7681 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7683 buffer_add_string (buf, name);
7688 return ERR_NOT_IMPLEMENTED;
7695 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7701 case CMD_MODULE_GET_INFO: {
7702 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7705 basename = g_path_get_basename (image->name);
7706 buffer_add_string (buf, basename); // name
7707 buffer_add_string (buf, image->module_name); // scopename
7708 buffer_add_string (buf, image->name); // fqname
7709 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7710 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7715 return ERR_NOT_IMPLEMENTED;
7722 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7728 case CMD_FIELD_GET_INFO: {
7729 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
7731 buffer_add_string (buf, f->name);
7732 buffer_add_typeid (buf, domain, f->parent);
7733 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7734 buffer_add_int (buf, f->type->attrs);
7738 return ERR_NOT_IMPLEMENTED;
7745 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7747 if (val && val->vtable->klass == mono_defaults.monotype_class) {
7748 /* Special case these so the client doesn't have to handle Type objects */
7750 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7751 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7752 } else if (MONO_TYPE_IS_REFERENCE (t))
7753 buffer_add_value (buf, t, &val, domain);
7755 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7759 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7765 buffer_add_int (buf, 0);
7769 for (i = 0; i < cinfo->num_attrs; ++i) {
7770 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7773 buffer_add_int (buf, nattrs);
7775 for (i = 0; i < cinfo->num_attrs; ++i) {
7776 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7777 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7778 MonoArray *typed_args, *named_args;
7780 CattrNamedArg *arginfo = NULL;
7783 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
7784 if (!mono_error_ok (&error)) {
7785 DEBUG_PRINTF (2, "[dbg] mono_reflection_create_custom_attr_data_args () failed with: '%s'\n", mono_error_get_message (&error));
7786 mono_error_cleanup (&error);
7787 return ERR_LOADER_ERROR;
7790 buffer_add_methodid (buf, domain, attr->ctor);
7794 buffer_add_int (buf, mono_array_length (typed_args));
7795 for (j = 0; j < mono_array_length (typed_args); ++j) {
7796 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7798 t = mono_method_signature (attr->ctor)->params [j];
7800 buffer_add_cattr_arg (buf, t, domain, val);
7803 buffer_add_int (buf, 0);
7808 buffer_add_int (buf, mono_array_length (named_args));
7810 for (j = 0; j < mono_array_length (named_args); ++j) {
7811 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7813 if (arginfo [j].prop) {
7814 buffer_add_byte (buf, 0x54);
7815 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7816 } else if (arginfo [j].field) {
7817 buffer_add_byte (buf, 0x53);
7818 buffer_add_fieldid (buf, domain, arginfo [j].field);
7820 g_assert_not_reached ();
7823 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7826 buffer_add_int (buf, 0);
7835 /* FIXME: Code duplication with icall.c */
7837 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7842 mono_class_setup_interfaces (klass, error);
7843 if (!mono_error_ok (error))
7846 for (i = 0; i < klass->interface_count; i++) {
7847 ic = klass->interfaces [i];
7848 g_hash_table_insert (ifaces, ic, ic);
7850 collect_interfaces (ic, ifaces, error);
7851 if (!mono_error_ok (error))
7857 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7867 case CMD_TYPE_GET_INFO: {
7868 buffer_add_string (buf, klass->name_space);
7869 buffer_add_string (buf, klass->name);
7871 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7872 buffer_add_string (buf, name);
7874 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7875 buffer_add_moduleid (buf, domain, klass->image);
7876 buffer_add_typeid (buf, domain, klass->parent);
7877 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7878 buffer_add_typeid (buf, domain, klass->element_class);
7880 buffer_add_id (buf, 0);
7881 buffer_add_int (buf, klass->type_token);
7882 buffer_add_byte (buf, klass->rank);
7883 buffer_add_int (buf, klass->flags);
7885 type = &klass->byval_arg;
7886 // FIXME: Can't decide whenever a class represents a byref type
7889 if (type->type == MONO_TYPE_PTR)
7891 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7893 if (type->type == MONO_TYPE_VALUETYPE)
7895 if (klass->enumtype)
7897 if (klass->generic_container)
7899 if (klass->generic_container || klass->generic_class)
7901 buffer_add_byte (buf, b);
7904 while ((nested = mono_class_get_nested_types (klass, &iter)))
7906 buffer_add_int (buf, nnested);
7908 while ((nested = mono_class_get_nested_types (klass, &iter)))
7909 buffer_add_typeid (buf, domain, nested);
7910 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7911 if (klass->generic_container)
7912 buffer_add_typeid (buf, domain, klass);
7913 else if (klass->generic_class)
7914 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7916 buffer_add_id (buf, 0);
7918 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7921 if (klass->generic_class) {
7922 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7924 count = inst->type_argc;
7925 buffer_add_int (buf, count);
7926 for (i = 0; i < count; i++)
7927 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7928 } else if (klass->generic_container) {
7929 MonoGenericContainer *container = klass->generic_container;
7932 count = container->type_argc;
7933 buffer_add_int (buf, count);
7934 for (i = 0; i < count; i++) {
7935 pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
7936 buffer_add_typeid (buf, domain, pklass);
7939 buffer_add_int (buf, 0);
7944 case CMD_TYPE_GET_METHODS: {
7947 gpointer iter = NULL;
7950 mono_class_setup_methods (klass);
7952 nmethods = mono_class_num_methods (klass);
7954 buffer_add_int (buf, nmethods);
7956 while ((m = mono_class_get_methods (klass, &iter))) {
7957 buffer_add_methodid (buf, domain, m);
7960 g_assert (i == nmethods);
7963 case CMD_TYPE_GET_FIELDS: {
7966 gpointer iter = NULL;
7969 nfields = mono_class_num_fields (klass);
7971 buffer_add_int (buf, nfields);
7973 while ((f = mono_class_get_fields (klass, &iter))) {
7974 buffer_add_fieldid (buf, domain, f);
7975 buffer_add_string (buf, f->name);
7976 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7977 buffer_add_int (buf, f->type->attrs);
7980 g_assert (i == nfields);
7983 case CMD_TYPE_GET_PROPERTIES: {
7986 gpointer iter = NULL;
7989 nprops = mono_class_num_properties (klass);
7991 buffer_add_int (buf, nprops);
7993 while ((p = mono_class_get_properties (klass, &iter))) {
7994 buffer_add_propertyid (buf, domain, p);
7995 buffer_add_string (buf, p->name);
7996 buffer_add_methodid (buf, domain, p->get);
7997 buffer_add_methodid (buf, domain, p->set);
7998 buffer_add_int (buf, p->attrs);
8001 g_assert (i == nprops);
8004 case CMD_TYPE_GET_CATTRS: {
8005 MonoClass *attr_klass;
8006 MonoCustomAttrInfo *cinfo;
8008 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8009 /* attr_klass can be NULL */
8013 cinfo = mono_custom_attrs_from_class (klass);
8015 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8020 case CMD_TYPE_GET_FIELD_CATTRS: {
8021 MonoClass *attr_klass;
8022 MonoCustomAttrInfo *cinfo;
8023 MonoClassField *field;
8025 field = decode_fieldid (p, &p, end, NULL, &err);
8028 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8032 cinfo = mono_custom_attrs_from_field (klass, field);
8034 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8039 case CMD_TYPE_GET_PROPERTY_CATTRS: {
8040 MonoClass *attr_klass;
8041 MonoCustomAttrInfo *cinfo;
8044 prop = decode_propertyid (p, &p, end, NULL, &err);
8047 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8051 cinfo = mono_custom_attrs_from_property (klass, prop);
8053 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8058 case CMD_TYPE_GET_VALUES:
8059 case CMD_TYPE_GET_VALUES_2: {
8066 MonoThread *thread_obj;
8067 MonoInternalThread *thread = NULL;
8068 guint32 special_static_type;
8070 if (command == CMD_TYPE_GET_VALUES_2) {
8071 int objid = decode_objid (p, &p, end);
8074 err = get_object (objid, (MonoObject**)&thread_obj);
8078 thread = THREAD_TO_INTERNAL (thread_obj);
8081 len = decode_int (p, &p, end);
8082 for (i = 0; i < len; ++i) {
8083 f = decode_fieldid (p, &p, end, NULL, &err);
8087 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8088 return ERR_INVALID_FIELDID;
8089 special_static_type = mono_class_field_get_special_static_type (f);
8090 if (special_static_type != SPECIAL_STATIC_NONE) {
8091 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
8092 return ERR_INVALID_FIELDID;
8095 /* Check that the field belongs to the object */
8097 for (k = klass; k; k = k->parent) {
8098 if (k == f->parent) {
8104 return ERR_INVALID_FIELDID;
8106 vtable = mono_class_vtable (domain, f->parent);
8107 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8108 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
8109 buffer_add_value (buf, f->type, val, domain);
8114 case CMD_TYPE_SET_VALUES: {
8122 len = decode_int (p, &p, end);
8123 for (i = 0; i < len; ++i) {
8124 f = decode_fieldid (p, &p, end, NULL, &err);
8128 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8129 return ERR_INVALID_FIELDID;
8130 if (mono_class_field_is_special_static (f))
8131 return ERR_INVALID_FIELDID;
8133 /* Check that the field belongs to the object */
8135 for (k = klass; k; k = k->parent) {
8136 if (k == f->parent) {
8142 return ERR_INVALID_FIELDID;
8144 // FIXME: Check for literal/const
8146 vtable = mono_class_vtable (domain, f->parent);
8147 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8148 err = decode_value (f->type, domain, val, p, &p, end);
8153 if (MONO_TYPE_IS_REFERENCE (f->type))
8154 mono_field_static_set_value (vtable, f, *(gpointer*)val);
8156 mono_field_static_set_value (vtable, f, val);
8161 case CMD_TYPE_GET_OBJECT: {
8162 MonoObject *o = (MonoObject*)mono_type_get_object (domain, &klass->byval_arg);
8163 buffer_add_objid (buf, o);
8166 case CMD_TYPE_GET_SOURCE_FILES:
8167 case CMD_TYPE_GET_SOURCE_FILES_2: {
8168 char *source_file, *base;
8172 files = get_source_files_for_type (klass);
8174 buffer_add_int (buf, files->len);
8175 for (i = 0; i < files->len; ++i) {
8176 source_file = g_ptr_array_index (files, i);
8177 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8178 buffer_add_string (buf, source_file);
8180 base = dbg_path_get_basename (source_file);
8181 buffer_add_string (buf, base);
8184 g_free (source_file);
8186 g_ptr_array_free (files, TRUE);
8189 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8190 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8194 if (mono_class_is_assignable_from (klass, oklass))
8195 buffer_add_byte (buf, 1);
8197 buffer_add_byte (buf, 0);
8200 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8201 char *name = decode_string (p, &p, end);
8202 int i, flags = decode_int (p, &p, end);
8203 MonoException *ex = NULL;
8204 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
8207 return ERR_LOADER_ERROR;
8208 buffer_add_int (buf, array->len);
8209 for (i = 0; i < array->len; ++i) {
8210 MonoMethod *method = g_ptr_array_index (array, i);
8211 buffer_add_methodid (buf, domain, method);
8214 g_ptr_array_free (array, TRUE);
8218 case CMD_TYPE_GET_INTERFACES: {
8220 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8222 MonoClass *tclass, *iface;
8223 GHashTableIter iter;
8227 for (parent = tclass; parent; parent = parent->parent) {
8228 mono_class_setup_interfaces (parent, &error);
8229 if (!mono_error_ok (&error))
8230 return ERR_LOADER_ERROR;
8231 collect_interfaces (parent, iface_hash, &error);
8232 if (!mono_error_ok (&error))
8233 return ERR_LOADER_ERROR;
8236 buffer_add_int (buf, g_hash_table_size (iface_hash));
8238 g_hash_table_iter_init (&iter, iface_hash);
8239 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8240 buffer_add_typeid (buf, domain, iface);
8241 g_hash_table_destroy (iface_hash);
8244 case CMD_TYPE_GET_INTERFACE_MAP: {
8245 int tindex, ioffset;
8246 gboolean variance_used;
8248 int len, nmethods, i;
8252 len = decode_int (p, &p, end);
8253 mono_class_setup_vtable (klass);
8255 for (tindex = 0; tindex < len; ++tindex) {
8256 iclass = decode_typeid (p, &p, end, NULL, &err);
8260 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8262 return ERR_INVALID_ARGUMENT;
8264 nmethods = mono_class_num_methods (iclass);
8265 buffer_add_int (buf, nmethods);
8268 while ((method = mono_class_get_methods (iclass, &iter))) {
8269 buffer_add_methodid (buf, domain, method);
8271 for (i = 0; i < nmethods; ++i)
8272 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
8276 case CMD_TYPE_IS_INITIALIZED: {
8277 MonoVTable *vtable = mono_class_vtable (domain, klass);
8280 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8282 buffer_add_int (buf, 0);
8285 case CMD_TYPE_CREATE_INSTANCE: {
8288 obj = mono_object_new (domain, klass);
8289 buffer_add_objid (buf, obj);
8293 return ERR_NOT_IMPLEMENTED;
8300 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8303 MonoDomain *old_domain;
8307 klass = decode_typeid (p, &p, end, &domain, &err);
8311 old_domain = mono_domain_get ();
8313 mono_domain_set (domain, TRUE);
8315 err = type_commands_internal (command, klass, domain, p, end, buf);
8317 mono_domain_set (old_domain, TRUE);
8323 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8325 MonoMethodHeader *header;
8329 case CMD_METHOD_GET_NAME: {
8330 buffer_add_string (buf, method->name);
8333 case CMD_METHOD_GET_DECLARING_TYPE: {
8334 buffer_add_typeid (buf, domain, method->klass);
8337 case CMD_METHOD_GET_DEBUG_INFO: {
8338 MonoDebugMethodInfo *minfo;
8340 int i, j, n_il_offsets;
8343 int *column_numbers;
8344 int *end_line_numbers;
8345 int *end_column_numbers;
8347 GPtrArray *source_file_list;
8349 header = mono_method_get_header (method);
8351 buffer_add_int (buf, 0);
8352 buffer_add_string (buf, "");
8353 buffer_add_int (buf, 0);
8357 minfo = mono_debug_lookup_method (method);
8359 buffer_add_int (buf, header->code_size);
8360 buffer_add_string (buf, "");
8361 buffer_add_int (buf, 0);
8362 mono_metadata_free_mh (header);
8366 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);
8367 buffer_add_int (buf, header->code_size);
8368 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8369 buffer_add_int (buf, source_file_list->len);
8370 for (i = 0; i < source_file_list->len; ++i) {
8371 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
8372 buffer_add_string (buf, sinfo->source_file);
8373 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8374 for (j = 0; j < 16; ++j)
8375 buffer_add_byte (buf, sinfo->hash [j]);
8379 buffer_add_string (buf, source_file);
8381 buffer_add_int (buf, n_il_offsets);
8382 DEBUG_PRINTF (10, "Line number table for method %s:\n", mono_method_full_name (method, TRUE));
8383 for (i = 0; i < n_il_offsets; ++i) {
8384 const char *srcfile = "";
8386 if (source_files [i] != -1) {
8387 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
8388 srcfile = sinfo->source_file;
8390 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);
8391 buffer_add_int (buf, il_offsets [i]);
8392 buffer_add_int (buf, line_numbers [i]);
8393 if (CHECK_PROTOCOL_VERSION (2, 13))
8394 buffer_add_int (buf, source_files [i]);
8395 if (CHECK_PROTOCOL_VERSION (2, 19))
8396 buffer_add_int (buf, column_numbers ? column_numbers [i] : -1);
8397 if (CHECK_PROTOCOL_VERSION (2, 32)) {
8398 buffer_add_int (buf, end_line_numbers ? end_line_numbers [i] : -1);
8399 buffer_add_int (buf, end_column_numbers ? end_column_numbers [i] : -1);
8402 g_free (source_file);
8403 g_free (il_offsets);
8404 g_free (line_numbers);
8405 g_free (column_numbers);
8406 g_free (end_line_numbers);
8407 g_free (end_column_numbers);
8408 g_free (source_files);
8409 g_ptr_array_free (source_file_list, TRUE);
8410 mono_metadata_free_mh (header);
8413 case CMD_METHOD_GET_PARAM_INFO: {
8414 MonoMethodSignature *sig = mono_method_signature (method);
8418 /* FIXME: mono_class_from_mono_type () and byrefs */
8420 /* FIXME: Use a smaller encoding */
8421 buffer_add_int (buf, sig->call_convention);
8422 buffer_add_int (buf, sig->param_count);
8423 buffer_add_int (buf, sig->generic_param_count);
8424 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
8425 for (i = 0; i < sig->param_count; ++i) {
8427 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
8430 /* Emit parameter names */
8431 names = g_new (char *, sig->param_count);
8432 mono_method_get_param_names (method, (const char **) names);
8433 for (i = 0; i < sig->param_count; ++i)
8434 buffer_add_string (buf, names [i]);
8439 case CMD_METHOD_GET_LOCALS_INFO: {
8440 int i, j, num_locals;
8441 MonoDebugLocalsInfo *locals;
8443 header = mono_method_get_header (method);
8445 return ERR_INVALID_ARGUMENT;
8447 buffer_add_int (buf, header->num_locals);
8450 for (i = 0; i < header->num_locals; ++i)
8451 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
8454 locals = mono_debug_lookup_locals (method);
8456 num_locals = locals->num_locals;
8459 for (i = 0; i < header->num_locals; ++i) {
8460 for (j = 0; j < num_locals; ++j)
8461 if (locals->locals [j].index == i)
8464 buffer_add_string (buf, locals->locals [j].name);
8466 buffer_add_string (buf, "");
8470 for (i = 0; i < header->num_locals; ++i) {
8471 for (j = 0; j < num_locals; ++j)
8472 if (locals->locals [j].index == i)
8474 if (j < num_locals && locals->locals [j].block) {
8475 buffer_add_int (buf, locals->locals [j].block->start_offset);
8476 buffer_add_int (buf, locals->locals [j].block->end_offset);
8478 buffer_add_int (buf, 0);
8479 buffer_add_int (buf, header->code_size);
8482 mono_metadata_free_mh (header);
8485 mono_debug_symfile_free_locals (locals);
8489 case CMD_METHOD_GET_INFO:
8490 buffer_add_int (buf, method->flags);
8491 buffer_add_int (buf, method->iflags);
8492 buffer_add_int (buf, method->token);
8493 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8495 if (method->is_generic)
8497 if (mono_method_signature (method)->generic_param_count)
8499 buffer_add_byte (buf, attrs);
8500 if (method->is_generic || method->is_inflated) {
8503 if (method->is_generic) {
8506 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8508 result = imethod->declaring;
8509 if (imethod->context.class_inst) {
8510 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8511 /*Generic methods gets the context of the GTD.*/
8512 if (mono_class_get_context (klass)) {
8514 result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), &error);
8515 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8520 buffer_add_methodid (buf, domain, result);
8522 buffer_add_id (buf, 0);
8524 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8525 if (mono_method_signature (method)->generic_param_count) {
8528 if (method->is_inflated) {
8529 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
8531 count = inst->type_argc;
8532 buffer_add_int (buf, count);
8534 for (i = 0; i < count; i++)
8535 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8537 buffer_add_int (buf, 0);
8539 } else if (method->is_generic) {
8540 MonoGenericContainer *container = mono_method_get_generic_container (method);
8542 count = mono_method_signature (method)->generic_param_count;
8543 buffer_add_int (buf, count);
8544 for (i = 0; i < count; i++) {
8545 MonoGenericParam *param = mono_generic_container_get_param (container, i);
8546 MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
8547 buffer_add_typeid (buf, domain, pklass);
8550 buffer_add_int (buf, 0);
8553 buffer_add_int (buf, 0);
8558 case CMD_METHOD_GET_BODY: {
8561 header = mono_method_get_header (method);
8563 buffer_add_int (buf, 0);
8565 if (CHECK_PROTOCOL_VERSION (2, 18))
8566 buffer_add_int (buf, 0);
8568 buffer_add_int (buf, header->code_size);
8569 for (i = 0; i < header->code_size; ++i)
8570 buffer_add_byte (buf, header->code [i]);
8572 if (CHECK_PROTOCOL_VERSION (2, 18)) {
8573 buffer_add_int (buf, header->num_clauses);
8574 for (i = 0; i < header->num_clauses; ++i) {
8575 MonoExceptionClause *clause = &header->clauses [i];
8577 buffer_add_int (buf, clause->flags);
8578 buffer_add_int (buf, clause->try_offset);
8579 buffer_add_int (buf, clause->try_len);
8580 buffer_add_int (buf, clause->handler_offset);
8581 buffer_add_int (buf, clause->handler_len);
8582 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
8583 buffer_add_typeid (buf, domain, clause->data.catch_class);
8584 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8585 buffer_add_int (buf, clause->data.filter_offset);
8589 mono_metadata_free_mh (header);
8594 case CMD_METHOD_RESOLVE_TOKEN: {
8595 guint32 token = decode_int (p, &p, end);
8598 switch (mono_metadata_token_code (token)) {
8599 case MONO_TOKEN_STRING: {
8603 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
8606 s2 = mono_string_to_utf8 (s);
8608 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8609 buffer_add_string (buf, s2);
8615 MonoClass *handle_class;
8617 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8618 val = mono_method_get_wrapper_data (method, token);
8619 handle_class = mono_method_get_wrapper_data (method, token + 1);
8621 if (handle_class == NULL) {
8622 // Can't figure out the token type
8623 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8628 val = mono_ldtoken_checked (method->klass->image, token, &handle_class, NULL, &error);
8630 g_error ("Could not load token due to %s", mono_error_get_message (&error));
8633 if (handle_class == mono_defaults.typehandle_class) {
8634 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8635 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8636 buffer_add_typeid (buf, domain, (MonoClass *) val);
8638 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
8639 } else if (handle_class == mono_defaults.fieldhandle_class) {
8640 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8641 buffer_add_fieldid (buf, domain, val);
8642 } else if (handle_class == mono_defaults.methodhandle_class) {
8643 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8644 buffer_add_methodid (buf, domain, val);
8645 } else if (handle_class == mono_defaults.string_class) {
8648 s = mono_string_to_utf8 (val);
8649 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8650 buffer_add_string (buf, s);
8653 g_assert_not_reached ();
8660 case CMD_METHOD_GET_CATTRS: {
8661 MonoClass *attr_klass;
8662 MonoCustomAttrInfo *cinfo;
8664 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8665 /* attr_klass can be NULL */
8669 cinfo = mono_custom_attrs_from_method (method);
8671 err = buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
8676 case CMD_METHOD_MAKE_GENERIC_METHOD: {
8678 MonoType **type_argv;
8682 MonoGenericInst *ginst;
8683 MonoGenericContext tmp_context;
8684 MonoMethod *inflated;
8686 type_argc = decode_int (p, &p, end);
8687 type_argv = g_new0 (MonoType*, type_argc);
8688 for (i = 0; i < type_argc; ++i) {
8689 klass = decode_typeid (p, &p, end, &d, &err);
8696 return ERR_INVALID_ARGUMENT;
8698 type_argv [i] = &klass->byval_arg;
8700 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
8702 tmp_context.class_inst = method->klass->generic_class ? method->klass->generic_class->context.class_inst : NULL;
8703 tmp_context.method_inst = ginst;
8705 inflated = mono_class_inflate_generic_method_checked (method, &tmp_context, &error);
8706 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8707 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
8708 return ERR_INVALID_ARGUMENT;
8709 buffer_add_methodid (buf, domain, inflated);
8713 return ERR_NOT_IMPLEMENTED;
8720 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8723 MonoDomain *old_domain;
8727 method = decode_methodid (p, &p, end, &domain, &err);
8731 old_domain = mono_domain_get ();
8733 mono_domain_set (domain, TRUE);
8735 err = method_commands_internal (command, method, domain, p, end, buf);
8737 mono_domain_set (old_domain, TRUE);
8743 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8745 int objid = decode_objid (p, &p, end);
8747 MonoThread *thread_obj;
8748 MonoInternalThread *thread;
8750 err = get_object (objid, (MonoObject**)&thread_obj);
8754 thread = THREAD_TO_INTERNAL (thread_obj);
8757 case CMD_THREAD_GET_NAME: {
8759 gunichar2 *s = mono_thread_get_name (thread, &name_len);
8762 buffer_add_int (buf, 0);
8767 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
8769 buffer_add_int (buf, len);
8770 buffer_add_data (buf, (guint8*)name, len);
8775 case CMD_THREAD_GET_FRAME_INFO: {
8776 DebuggerTlsData *tls;
8777 int i, start_frame, length;
8779 // Wait for suspending if it already started
8780 // FIXME: Races with suspend_count
8781 while (!is_suspended ()) {
8783 wait_for_suspend ();
8787 wait_for_suspend ();
8788 if (!is_suspended ())
8789 return ERR_NOT_SUSPENDED;
8792 start_frame = decode_int (p, &p, end);
8793 length = decode_int (p, &p, end);
8795 if (start_frame != 0 || length != -1)
8796 return ERR_NOT_IMPLEMENTED;
8798 mono_loader_lock ();
8799 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8800 mono_loader_unlock ();
8803 compute_frame_info (thread, tls);
8805 buffer_add_int (buf, tls->frame_count);
8806 for (i = 0; i < tls->frame_count; ++i) {
8807 buffer_add_int (buf, tls->frames [i]->id);
8808 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
8809 buffer_add_int (buf, tls->frames [i]->il_offset);
8811 * Instead of passing the frame type directly to the client, we associate
8812 * it with the previous frame using a set of flags. This avoids lots of
8813 * conditional code in the client, since a frame whose type isn't
8814 * FRAME_TYPE_MANAGED has no method, location, etc.
8816 buffer_add_byte (buf, tls->frames [i]->flags);
8821 case CMD_THREAD_GET_STATE:
8822 buffer_add_int (buf, thread->state);
8824 case CMD_THREAD_GET_INFO:
8825 buffer_add_byte (buf, thread->threadpool_thread);
8827 case CMD_THREAD_GET_ID:
8828 buffer_add_long (buf, (guint64)(gsize)thread);
8830 case CMD_THREAD_GET_TID:
8831 buffer_add_long (buf, (guint64)thread->tid);
8833 case CMD_THREAD_SET_IP: {
8834 DebuggerTlsData *tls;
8837 MonoSeqPointInfo *seq_points;
8842 method = decode_methodid (p, &p, end, &domain, &err);
8845 il_offset = decode_long (p, &p, end);
8847 while (!is_suspended ()) {
8849 wait_for_suspend ();
8852 mono_loader_lock ();
8853 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8854 mono_loader_unlock ();
8857 compute_frame_info (thread, tls);
8858 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
8859 return ERR_INVALID_ARGUMENT;
8861 found_sp = find_seq_point (domain, method, il_offset, &seq_points, &sp);
8863 g_assert (seq_points);
8866 return ERR_INVALID_ARGUMENT;
8868 // FIXME: Check that the ip change is safe
8870 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);
8871 MONO_CONTEXT_SET_IP (&tls->restore_state.ctx, (guint8*)tls->frames [0]->ji->code_start + sp.native_offset);
8875 return ERR_NOT_IMPLEMENTED;
8882 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8886 MonoThread *thread_obj;
8887 MonoInternalThread *thread;
8888 int pos, i, len, frame_idx;
8889 DebuggerTlsData *tls;
8891 MonoDebugMethodJitInfo *jit;
8892 MonoMethodSignature *sig;
8894 MonoMethodHeader *header;
8896 objid = decode_objid (p, &p, end);
8897 err = get_object (objid, (MonoObject**)&thread_obj);
8901 thread = THREAD_TO_INTERNAL (thread_obj);
8903 id = decode_id (p, &p, end);
8905 mono_loader_lock ();
8906 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8907 mono_loader_unlock ();
8910 for (i = 0; i < tls->frame_count; ++i) {
8911 if (tls->frames [i]->id == id)
8914 if (i == tls->frame_count)
8915 return ERR_INVALID_FRAMEID;
8918 frame = tls->frames [frame_idx];
8920 /* This is supported for frames without has_ctx etc. set */
8921 if (command == CMD_STACK_FRAME_GET_DOMAIN) {
8922 if (CHECK_PROTOCOL_VERSION (2, 38))
8923 buffer_add_domainid (buf, frame->domain);
8927 if (!frame->has_ctx)
8928 return ERR_ABSENT_INFORMATION;
8931 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
8932 if (!frame->jit && frame->api_method->is_inflated)
8933 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
8937 /* This could happen for aot images with no jit debug info */
8938 s = mono_method_full_name (frame->api_method, TRUE);
8939 DEBUG_PRINTF (1, "[dbg] No debug information found for '%s'.\n", s);
8941 return ERR_ABSENT_INFORMATION;
8946 sig = mono_method_signature (frame->actual_method);
8948 if (!get_seq_points (frame->domain, frame->actual_method))
8950 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
8952 return ERR_ABSENT_INFORMATION;
8955 case CMD_STACK_FRAME_GET_VALUES: {
8956 len = decode_int (p, &p, end);
8957 header = mono_method_get_header (frame->actual_method);
8959 for (i = 0; i < len; ++i) {
8960 pos = decode_int (p, &p, end);
8965 g_assert (pos >= 0 && pos < jit->num_params);
8967 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
8969 g_assert (pos >= 0 && pos < jit->num_locals);
8971 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
8974 mono_metadata_free_mh (header);
8977 case CMD_STACK_FRAME_GET_THIS: {
8978 if (frame->api_method->klass->valuetype) {
8979 if (!sig->hasthis) {
8980 MonoObject *p = NULL;
8981 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
8983 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8986 if (!sig->hasthis) {
8987 MonoObject *p = NULL;
8988 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
8990 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8995 case CMD_STACK_FRAME_SET_VALUES: {
8998 MonoDebugVarInfo *var;
9000 len = decode_int (p, &p, end);
9001 header = mono_method_get_header (frame->actual_method);
9003 for (i = 0; i < len; ++i) {
9004 pos = decode_int (p, &p, end);
9009 g_assert (pos >= 0 && pos < jit->num_params);
9011 t = sig->params [pos];
9012 var = &jit->params [pos];
9014 g_assert (pos >= 0 && pos < jit->num_locals);
9016 t = header->locals [pos];
9017 var = &jit->locals [pos];
9020 if (MONO_TYPE_IS_REFERENCE (t))
9021 val_buf = g_alloca (sizeof (MonoObject*));
9023 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9024 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9028 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9030 mono_metadata_free_mh (header);
9033 case CMD_STACK_FRAME_GET_DOMAIN: {
9034 if (CHECK_PROTOCOL_VERSION (2, 38))
9035 buffer_add_domainid (buf, frame->domain);
9039 return ERR_NOT_IMPLEMENTED;
9046 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9049 int objid, err, index, len, i, esize;
9052 objid = decode_objid (p, &p, end);
9053 err = get_object (objid, (MonoObject**)&arr);
9058 case CMD_ARRAY_REF_GET_LENGTH:
9059 buffer_add_int (buf, arr->obj.vtable->klass->rank);
9061 buffer_add_int (buf, arr->max_length);
9062 buffer_add_int (buf, 0);
9064 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
9065 buffer_add_int (buf, arr->bounds [i].length);
9066 buffer_add_int (buf, arr->bounds [i].lower_bound);
9070 case CMD_ARRAY_REF_GET_VALUES:
9071 index = decode_int (p, &p, end);
9072 len = decode_int (p, &p, end);
9074 g_assert (index >= 0 && len >= 0);
9075 // Reordered to avoid integer overflow
9076 g_assert (!(index > arr->max_length - len));
9078 esize = mono_array_element_size (arr->obj.vtable->klass);
9079 for (i = index; i < index + len; ++i) {
9080 elem = (gpointer*)((char*)arr->vector + (i * esize));
9081 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
9084 case CMD_ARRAY_REF_SET_VALUES:
9085 index = decode_int (p, &p, end);
9086 len = decode_int (p, &p, end);
9088 g_assert (index >= 0 && len >= 0);
9089 // Reordered to avoid integer overflow
9090 g_assert (!(index > arr->max_length - len));
9092 esize = mono_array_element_size (arr->obj.vtable->klass);
9093 for (i = index; i < index + len; ++i) {
9094 elem = (gpointer*)((char*)arr->vector + (i * esize));
9096 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
9100 return ERR_NOT_IMPLEMENTED;
9107 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9112 int i, index, length;
9115 objid = decode_objid (p, &p, end);
9116 err = get_object (objid, (MonoObject**)&str);
9121 case CMD_STRING_REF_GET_VALUE:
9122 s = mono_string_to_utf8 (str);
9123 buffer_add_string (buf, s);
9126 case CMD_STRING_REF_GET_LENGTH:
9127 buffer_add_long (buf, mono_string_length (str));
9129 case CMD_STRING_REF_GET_CHARS:
9130 index = decode_long (p, &p, end);
9131 length = decode_long (p, &p, end);
9132 if (index > mono_string_length (str) - length)
9133 return ERR_INVALID_ARGUMENT;
9134 c = mono_string_chars (str) + index;
9135 for (i = 0; i < length; ++i)
9136 buffer_add_short (buf, c [i]);
9139 return ERR_NOT_IMPLEMENTED;
9146 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9155 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9156 objid = decode_objid (p, &p, end);
9157 err = get_object (objid, &obj);
9159 buffer_add_int (buf, 1);
9161 buffer_add_int (buf, 0);
9165 objid = decode_objid (p, &p, end);
9166 err = get_object (objid, &obj);
9171 case CMD_OBJECT_REF_GET_TYPE:
9172 /* This handles transparent proxies too */
9173 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9175 case CMD_OBJECT_REF_GET_VALUES:
9176 len = decode_int (p, &p, end);
9178 for (i = 0; i < len; ++i) {
9179 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9183 /* Check that the field belongs to the object */
9185 for (k = obj->vtable->klass; k; k = k->parent) {
9186 if (k == f->parent) {
9192 return ERR_INVALID_FIELDID;
9194 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9198 if (mono_class_field_is_special_static (f))
9199 return ERR_INVALID_FIELDID;
9201 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9202 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9203 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9204 mono_field_static_get_value (vtable, f, val);
9205 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9208 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
9212 case CMD_OBJECT_REF_SET_VALUES:
9213 len = decode_int (p, &p, end);
9215 for (i = 0; i < len; ++i) {
9216 f = decode_fieldid (p, &p, end, NULL, &err);
9220 /* Check that the field belongs to the object */
9222 for (k = obj->vtable->klass; k; k = k->parent) {
9223 if (k == f->parent) {
9229 return ERR_INVALID_FIELDID;
9231 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9235 if (mono_class_field_is_special_static (f))
9236 return ERR_INVALID_FIELDID;
9238 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9239 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9241 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9242 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
9247 mono_field_static_set_value (vtable, f, val);
9250 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
9256 case CMD_OBJECT_REF_GET_ADDRESS:
9257 buffer_add_long (buf, (gssize)obj);
9259 case CMD_OBJECT_REF_GET_DOMAIN:
9260 buffer_add_domainid (buf, obj->vtable->domain);
9262 case CMD_OBJECT_REF_GET_INFO:
9263 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9264 buffer_add_domainid (buf, obj->vtable->domain);
9267 return ERR_NOT_IMPLEMENTED;
9274 command_set_to_string (CommandSet command_set)
9276 switch (command_set) {
9279 case CMD_SET_OBJECT_REF:
9280 return "OBJECT_REF";
9281 case CMD_SET_STRING_REF:
9282 return "STRING_REF";
9283 case CMD_SET_THREAD:
9285 case CMD_SET_ARRAY_REF:
9287 case CMD_SET_EVENT_REQUEST:
9288 return "EVENT_REQUEST";
9289 case CMD_SET_STACK_FRAME:
9290 return "STACK_FRAME";
9291 case CMD_SET_APPDOMAIN:
9293 case CMD_SET_ASSEMBLY:
9295 case CMD_SET_METHOD:
9299 case CMD_SET_MODULE:
9310 static const char* vm_cmds_str [] = {
9318 "SET_PROTOCOL_VERSION",
9321 "GET_TYPES_FOR_SOURCE_FILE",
9326 static const char* thread_cmds_str[] = {
9336 static const char* event_cmds_str[] = {
9339 "REQUEST_CLEAR_ALL_BREAKPOINTS"
9342 static const char* appdomain_cmds_str[] = {
9344 "GET_FRIENDLY_NAME",
9346 "GET_ENTRY_ASSEMBLY",
9349 "CREATE_BOXED_VALUE"
9352 static const char* assembly_cmds_str[] = {
9355 "GET_MANIFEST_MODULE",
9361 static const char* module_cmds_str[] = {
9365 static const char* field_cmds_str[] = {
9369 static const char* method_cmds_str[] = {
9371 "GET_DECLARING_TYPE",
9379 "MAKE_GENERIC_METHOD"
9382 static const char* type_cmds_str[] = {
9390 "IS_ASSIGNABLE_FROM",
9394 "GET_PROPERTY_CATTRS",
9395 "GET_SOURCE_FILES_2",
9397 "GET_METHODS_BY_NAME_FLAGS",
9399 "GET_INTERFACE_MAP",
9403 static const char* stack_frame_cmds_str[] = {
9410 static const char* array_cmds_str[] = {
9416 static const char* string_cmds_str[] = {
9422 static const char* object_cmds_str[] = {
9433 cmd_to_string (CommandSet set, int command)
9441 cmds_len = G_N_ELEMENTS (vm_cmds_str);
9443 case CMD_SET_OBJECT_REF:
9444 cmds = object_cmds_str;
9445 cmds_len = G_N_ELEMENTS (object_cmds_str);
9447 case CMD_SET_STRING_REF:
9448 cmds = string_cmds_str;
9449 cmds_len = G_N_ELEMENTS (string_cmds_str);
9451 case CMD_SET_THREAD:
9452 cmds = thread_cmds_str;
9453 cmds_len = G_N_ELEMENTS (thread_cmds_str);
9455 case CMD_SET_ARRAY_REF:
9456 cmds = array_cmds_str;
9457 cmds_len = G_N_ELEMENTS (array_cmds_str);
9459 case CMD_SET_EVENT_REQUEST:
9460 cmds = event_cmds_str;
9461 cmds_len = G_N_ELEMENTS (event_cmds_str);
9463 case CMD_SET_STACK_FRAME:
9464 cmds = stack_frame_cmds_str;
9465 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
9467 case CMD_SET_APPDOMAIN:
9468 cmds = appdomain_cmds_str;
9469 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
9471 case CMD_SET_ASSEMBLY:
9472 cmds = assembly_cmds_str;
9473 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
9475 case CMD_SET_METHOD:
9476 cmds = method_cmds_str;
9477 cmds_len = G_N_ELEMENTS (method_cmds_str);
9480 cmds = type_cmds_str;
9481 cmds_len = G_N_ELEMENTS (type_cmds_str);
9483 case CMD_SET_MODULE:
9484 cmds = module_cmds_str;
9485 cmds_len = G_N_ELEMENTS (module_cmds_str);
9488 cmds = field_cmds_str;
9489 cmds_len = G_N_ELEMENTS (field_cmds_str);
9492 cmds = event_cmds_str;
9493 cmds_len = G_N_ELEMENTS (event_cmds_str);
9498 if (command > 0 && command <= cmds_len)
9499 return cmds [command - 1];
9505 wait_for_attach (void)
9507 #ifndef DISABLE_SOCKET_TRANSPORT
9508 if (listen_fd == -1) {
9509 DEBUG_PRINTF (1, "[dbg] Invalid listening socket\n");
9513 /* Block and wait for client connection */
9514 MONO_PREPARE_BLOCKING
9515 conn_fd = socket_transport_accept (listen_fd);
9516 MONO_FINISH_BLOCKING
9518 DEBUG_PRINTF (1, "Accepted connection on %d\n", conn_fd);
9519 if (conn_fd == -1) {
9520 DEBUG_PRINTF (1, "[dbg] Bad client connection\n");
9524 g_assert_not_reached ();
9528 disconnected = !transport_handshake ();
9530 DEBUG_PRINTF (1, "Transport handshake failed!\n");
9540 * This thread handles communication with the debugger client using a JDWP
9543 static guint32 WINAPI
9544 debugger_thread (void *arg)
9546 int res, len, id, flags, command_set = 0, command = 0;
9547 guint8 header [HEADER_LENGTH];
9548 guint8 *data, *p, *end;
9552 gboolean attach_failed = FALSE;
9554 DEBUG_PRINTF (1, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ());
9556 debugger_thread_id = GetCurrentThreadId ();
9558 mono_jit_thread_attach (mono_get_root_domain ());
9560 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
9562 mono_set_is_debugger_attached (TRUE);
9564 if (agent_config.defer) {
9565 if (!wait_for_attach ()) {
9566 DEBUG_PRINTF (1, "[dbg] Can't attach, aborting debugger thread.\n");
9567 attach_failed = TRUE; // Don't abort process when we can't listen
9569 /* Send start event to client */
9570 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
9574 while (!attach_failed) {
9575 MONO_PREPARE_BLOCKING
9576 res = transport_recv (header, HEADER_LENGTH);
9577 MONO_FINISH_BLOCKING
9579 /* This will break if the socket is closed during shutdown too */
9580 if (res != HEADER_LENGTH) {
9581 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH);
9586 end = header + HEADER_LENGTH;
9588 len = decode_int (p, &p, end);
9589 id = decode_int (p, &p, end);
9590 flags = decode_byte (p, &p, end);
9591 command_set = decode_byte (p, &p, end);
9592 command = decode_byte (p, &p, end);
9594 g_assert (flags == 0);
9597 const char *cmd_str;
9600 cmd_str = cmd_to_string (command_set, command);
9602 sprintf (cmd_num, "%d", command);
9606 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);
9609 data = g_malloc (len - HEADER_LENGTH);
9610 if (len - HEADER_LENGTH > 0)
9612 MONO_PREPARE_BLOCKING
9613 res = transport_recv (data, len - HEADER_LENGTH);
9614 MONO_FINISH_BLOCKING
9615 if (res != len - HEADER_LENGTH) {
9616 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH);
9622 end = data + (len - HEADER_LENGTH);
9624 buffer_init (&buf, 128);
9629 /* Process the request */
9630 switch (command_set) {
9632 err = vm_commands (command, id, p, end, &buf);
9633 if (!err && command == CMD_VM_INVOKE_METHOD)
9634 /* Sent after the invoke is complete */
9637 case CMD_SET_EVENT_REQUEST:
9638 err = event_commands (command, p, end, &buf);
9640 case CMD_SET_APPDOMAIN:
9641 err = domain_commands (command, p, end, &buf);
9643 case CMD_SET_ASSEMBLY:
9644 err = assembly_commands (command, p, end, &buf);
9646 case CMD_SET_MODULE:
9647 err = module_commands (command, p, end, &buf);
9650 err = field_commands (command, p, end, &buf);
9653 err = type_commands (command, p, end, &buf);
9655 case CMD_SET_METHOD:
9656 err = method_commands (command, p, end, &buf);
9658 case CMD_SET_THREAD:
9659 err = thread_commands (command, p, end, &buf);
9661 case CMD_SET_STACK_FRAME:
9662 err = frame_commands (command, p, end, &buf);
9664 case CMD_SET_ARRAY_REF:
9665 err = array_commands (command, p, end, &buf);
9667 case CMD_SET_STRING_REF:
9668 err = string_commands (command, p, end, &buf);
9670 case CMD_SET_OBJECT_REF:
9671 err = object_commands (command, p, end, &buf);
9674 err = ERR_NOT_IMPLEMENTED;
9677 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
9678 buffer_replies = TRUE;
9682 if (buffer_replies) {
9683 buffer_reply_packet (id, err, &buf);
9685 send_reply_packet (id, err, &buf);
9686 //DEBUG_PRINTF (1, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000);
9690 if (!err && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
9691 send_buffered_reply_packets ();
9692 buffer_replies = FALSE;
9698 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
9702 mono_set_is_debugger_attached (FALSE);
9705 mono_mutex_lock (&debugger_thread_exited_mutex);
9706 debugger_thread_exited = TRUE;
9707 mono_cond_signal (&debugger_thread_exited_cond);
9708 mono_mutex_unlock (&debugger_thread_exited_mutex);
9709 MONO_FINISH_TRY_BLOCKING
9711 DEBUG_PRINTF (1, "[dbg] Debugger thread exited.\n");
9713 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
9714 DEBUG_PRINTF (2, "[dbg] Detached - restarting clean debugger thread.\n");
9715 start_debugger_thread ();
9721 #else /* DISABLE_DEBUGGER_AGENT */
9724 mono_debugger_agent_parse_options (char *options)
9726 g_error ("This runtime is configured with the debugger agent disabled.");
9730 mono_debugger_agent_init (void)
9735 mono_debugger_agent_breakpoint_hit (void *sigctx)
9740 mono_debugger_agent_single_step_event (void *sigctx)
9745 mono_debugger_agent_free_domain_info (MonoDomain *domain)
9750 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
9751 MonoContext *catch_ctx)
9756 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9761 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9766 mono_debugger_agent_user_break (void)
9772 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
9777 mono_debugger_agent_debug_log_is_enabled (void)
9783 mono_debugger_agent_unhandled_exception (MonoException *exc)
9785 g_assert_not_reached ();
9789 debugger_agent_single_step_from_context (MonoContext *ctx)
9791 g_assert_not_reached ();
9795 debugger_agent_breakpoint_from_context (MonoContext *ctx)
9797 g_assert_not_reached ();