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>
40 #ifdef HAVE_UCONTEXT_H
52 #ifdef PLATFORM_ANDROID
54 #include <linux/tcp.h>
55 #include <sys/endian.h>
58 #include <mono/metadata/mono-debug.h>
59 #include <mono/metadata/mono-debug-debugger.h>
60 #include <mono/metadata/debug-mono-symfile.h>
61 #include <mono/metadata/gc-internal.h>
62 #include <mono/metadata/environment.h>
63 #include <mono/metadata/threads-types.h>
64 #include <mono/metadata/socket-io.h>
65 #include <mono/metadata/assembly.h>
66 #include <mono/metadata/runtime.h>
67 #include <mono/metadata/threadpool.h>
68 #include <mono/metadata/verify-internals.h>
69 #include <mono/utils/mono-semaphore.h>
70 #include <mono/utils/mono-error-internals.h>
71 #include <mono/utils/mono-stack-unwinding.h>
72 #include <mono/utils/mono-time.h>
73 #include <mono/utils/mono-threads.h>
74 #include <mono/utils/networking.h>
75 #include "debugger-agent.h"
77 #include "seq-points.h"
80 On iOS we can't use System.Environment.Exit () as it will do the wrong
83 #if !defined (TARGET_IOS)
84 #define TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
88 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
89 #define DISABLE_DEBUGGER_AGENT 1
92 #ifdef DISABLE_SOFT_DEBUG
93 #define DISABLE_DEBUGGER_AGENT 1
96 #ifndef DISABLE_DEBUGGER_AGENT
98 #include <mono/utils/mono-mutex.h>
100 /* Definitions to make backporting to 2.6 easier */
101 //#define MonoInternalThread MonoThread
102 //#define mono_thread_internal_current mono_thread_current
103 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
126 guint32 il_offset, native_offset;
130 * If method is gshared, this is the actual instance, otherwise this is equal to
133 MonoMethod *actual_method;
135 * This is the method which is visible to debugger clients. Same as method,
136 * except for native-to-managed wrappers.
138 MonoMethod *api_method;
140 MonoDebugMethodJitInfo *jit;
143 mgreg_t *reg_locations [MONO_MAX_IREGS];
145 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
146 * the frame can become invalid.
151 typedef struct _InvokeData InvokeData;
159 /* This is the context which needs to be restored after the invoke */
163 * If this is set, invoke this method with the arguments given by ARGS.
167 guint32 suspend_count;
170 InvokeData *last_invoke;
174 MonoThreadUnwindState context;
176 /* This is computed on demand when it is requested using the wire protocol */
177 /* It is freed up when the thread is resumed */
181 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
184 gboolean frames_up_to_date;
186 * Points to data about a pending invoke which needs to be executed after the thread
189 InvokeData *pending_invoke;
191 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
196 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
197 * within a finite amount of time.
201 * Set to TRUE if this thread is suspended in suspend_current ().
203 gboolean really_suspended;
204 /* Used to pass the context to the breakpoint/single step handler */
205 MonoContext handler_ctx;
206 /* Whenever thread_stop () was called for this thread */
209 /* Number of thread interruptions not yet processed */
210 gint32 interrupt_count;
212 /* Whenever to disable breakpoints (used during invokes) */
213 gboolean disable_breakpoints;
216 * Number of times this thread has been resumed using resume_thread ().
218 guint32 resume_count;
220 MonoInternalThread *thread;
223 * Information about the frame which transitioned to native code for running
226 StackFrameInfo async_last_frame;
229 * The context where the stack walk can be started for running threads.
231 MonoThreadUnwindState async_state;
234 * The context used for filter clauses
236 MonoThreadUnwindState filter_state;
239 * The callee address of the last mono_runtime_invoke call
241 gpointer invoke_addr;
243 gboolean abort_requested;
246 * The current mono_runtime_invoke invocation.
251 * The context where single stepping should resume while the thread is suspended because
252 * of an EXCEPTION event.
254 MonoThreadUnwindState catch_state;
257 * The context which needs to be restored after handling a single step/breakpoint
258 * event. This is the same as the ctx at step/breakpoint site, but includes changes
259 * to caller saved registers done by set_var ().
261 MonoThreadUnwindState restore_state;
262 /* Frames computed from restore_state */
263 int restore_frame_count;
264 StackFrame **restore_frames;
266 /* The currently unloading appdomain */
267 MonoDomain *domain_unloading;
272 void (*connect) (const char *address);
273 void (*close1) (void);
274 void (*close2) (void);
275 gboolean (*send) (void *buf, int len);
276 int (*recv) (void *buf, int len);
280 * Wire Protocol definitions
283 #define HEADER_LENGTH 11
285 #define MAJOR_VERSION 2
286 #define MINOR_VERSION 40
290 CMD_SET_OBJECT_REF = 9,
291 CMD_SET_STRING_REF = 10,
293 CMD_SET_ARRAY_REF = 13,
294 CMD_SET_EVENT_REQUEST = 15,
295 CMD_SET_STACK_FRAME = 16,
296 CMD_SET_APPDOMAIN = 20,
297 CMD_SET_ASSEMBLY = 21,
306 EVENT_KIND_VM_START = 0,
307 EVENT_KIND_VM_DEATH = 1,
308 EVENT_KIND_THREAD_START = 2,
309 EVENT_KIND_THREAD_DEATH = 3,
310 EVENT_KIND_APPDOMAIN_CREATE = 4,
311 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
312 EVENT_KIND_METHOD_ENTRY = 6,
313 EVENT_KIND_METHOD_EXIT = 7,
314 EVENT_KIND_ASSEMBLY_LOAD = 8,
315 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
316 EVENT_KIND_BREAKPOINT = 10,
317 EVENT_KIND_STEP = 11,
318 EVENT_KIND_TYPE_LOAD = 12,
319 EVENT_KIND_EXCEPTION = 13,
320 EVENT_KIND_KEEPALIVE = 14,
321 EVENT_KIND_USER_BREAK = 15,
322 EVENT_KIND_USER_LOG = 16
326 SUSPEND_POLICY_NONE = 0,
327 SUSPEND_POLICY_EVENT_THREAD = 1,
328 SUSPEND_POLICY_ALL = 2
333 ERR_INVALID_OBJECT = 20,
334 ERR_INVALID_FIELDID = 25,
335 ERR_INVALID_FRAMEID = 30,
336 ERR_NOT_IMPLEMENTED = 100,
337 ERR_NOT_SUSPENDED = 101,
338 ERR_INVALID_ARGUMENT = 102,
340 ERR_NO_INVOCATION = 104,
341 ERR_ABSENT_INFORMATION = 105,
342 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
343 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
348 MOD_KIND_THREAD_ONLY = 3,
349 MOD_KIND_LOCATION_ONLY = 7,
350 MOD_KIND_EXCEPTION_ONLY = 8,
352 MOD_KIND_ASSEMBLY_ONLY = 11,
353 MOD_KIND_SOURCE_FILE_ONLY = 12,
354 MOD_KIND_TYPE_NAME_ONLY = 13,
370 STEP_FILTER_NONE = 0,
371 STEP_FILTER_STATIC_CTOR = 1,
372 STEP_FILTER_DEBUGGER_HIDDEN = 2,
373 STEP_FILTER_DEBUGGER_STEP_THROUGH = 4,
374 STEP_FILTER_DEBUGGER_NON_USER_CODE = 8
378 TOKEN_TYPE_STRING = 0,
380 TOKEN_TYPE_FIELD = 2,
381 TOKEN_TYPE_METHOD = 3,
382 TOKEN_TYPE_UNKNOWN = 4
386 VALUE_TYPE_ID_NULL = 0xf0,
387 VALUE_TYPE_ID_TYPE = 0xf1,
388 VALUE_TYPE_ID_PARENT_VTYPE = 0xf2
392 FRAME_FLAG_DEBUGGER_INVOKE = 1,
393 FRAME_FLAG_NATIVE_TRANSITION = 2
397 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
398 INVOKE_FLAG_SINGLE_THREADED = 2,
399 INVOKE_FLAG_RETURN_OUT_THIS = 4,
400 INVOKE_FLAG_RETURN_OUT_ARGS = 8,
401 INVOKE_FLAG_VIRTUAL = 16
405 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
406 } BindingFlagsExtensions;
410 CMD_VM_ALL_THREADS = 2,
415 CMD_VM_INVOKE_METHOD = 7,
416 CMD_VM_SET_PROTOCOL_VERSION = 8,
417 CMD_VM_ABORT_INVOKE = 9,
418 CMD_VM_SET_KEEPALIVE = 10,
419 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
420 CMD_VM_GET_TYPES = 12,
421 CMD_VM_INVOKE_METHODS = 13,
422 CMD_VM_START_BUFFERING = 14,
423 CMD_VM_STOP_BUFFERING = 15
427 CMD_THREAD_GET_FRAME_INFO = 1,
428 CMD_THREAD_GET_NAME = 2,
429 CMD_THREAD_GET_STATE = 3,
430 CMD_THREAD_GET_INFO = 4,
431 CMD_THREAD_GET_ID = 5,
432 CMD_THREAD_GET_TID = 6,
433 CMD_THREAD_SET_IP = 7
437 CMD_EVENT_REQUEST_SET = 1,
438 CMD_EVENT_REQUEST_CLEAR = 2,
439 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
447 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
448 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
449 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
450 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
451 CMD_APPDOMAIN_CREATE_STRING = 5,
452 CMD_APPDOMAIN_GET_CORLIB = 6,
453 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
457 CMD_ASSEMBLY_GET_LOCATION = 1,
458 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
459 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
460 CMD_ASSEMBLY_GET_OBJECT = 4,
461 CMD_ASSEMBLY_GET_TYPE = 5,
462 CMD_ASSEMBLY_GET_NAME = 6
466 CMD_MODULE_GET_INFO = 1,
470 CMD_FIELD_GET_INFO = 1,
474 CMD_METHOD_GET_NAME = 1,
475 CMD_METHOD_GET_DECLARING_TYPE = 2,
476 CMD_METHOD_GET_DEBUG_INFO = 3,
477 CMD_METHOD_GET_PARAM_INFO = 4,
478 CMD_METHOD_GET_LOCALS_INFO = 5,
479 CMD_METHOD_GET_INFO = 6,
480 CMD_METHOD_GET_BODY = 7,
481 CMD_METHOD_RESOLVE_TOKEN = 8,
482 CMD_METHOD_GET_CATTRS = 9,
483 CMD_METHOD_MAKE_GENERIC_METHOD = 10
487 CMD_TYPE_GET_INFO = 1,
488 CMD_TYPE_GET_METHODS = 2,
489 CMD_TYPE_GET_FIELDS = 3,
490 CMD_TYPE_GET_VALUES = 4,
491 CMD_TYPE_GET_OBJECT = 5,
492 CMD_TYPE_GET_SOURCE_FILES = 6,
493 CMD_TYPE_SET_VALUES = 7,
494 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
495 CMD_TYPE_GET_PROPERTIES = 9,
496 CMD_TYPE_GET_CATTRS = 10,
497 CMD_TYPE_GET_FIELD_CATTRS = 11,
498 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
499 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
500 CMD_TYPE_GET_VALUES_2 = 14,
501 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
502 CMD_TYPE_GET_INTERFACES = 16,
503 CMD_TYPE_GET_INTERFACE_MAP = 17,
504 CMD_TYPE_IS_INITIALIZED = 18,
505 CMD_TYPE_CREATE_INSTANCE = 19
509 CMD_STACK_FRAME_GET_VALUES = 1,
510 CMD_STACK_FRAME_GET_THIS = 2,
511 CMD_STACK_FRAME_SET_VALUES = 3,
512 CMD_STACK_FRAME_GET_DOMAIN = 4,
516 CMD_ARRAY_REF_GET_LENGTH = 1,
517 CMD_ARRAY_REF_GET_VALUES = 2,
518 CMD_ARRAY_REF_SET_VALUES = 3,
522 CMD_STRING_REF_GET_VALUE = 1,
523 CMD_STRING_REF_GET_LENGTH = 2,
524 CMD_STRING_REF_GET_CHARS = 3
528 CMD_OBJECT_REF_GET_TYPE = 1,
529 CMD_OBJECT_REF_GET_VALUES = 2,
530 CMD_OBJECT_REF_IS_COLLECTED = 3,
531 CMD_OBJECT_REF_GET_ADDRESS = 4,
532 CMD_OBJECT_REF_GET_DOMAIN = 5,
533 CMD_OBJECT_REF_SET_VALUES = 6,
534 CMD_OBJECT_REF_GET_INFO = 7,
540 int count; /* For kind == MOD_KIND_COUNT */
541 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
542 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
543 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
544 GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
545 GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
546 StepFilter filter; /* For kind == MOD_KIND_STEP */
548 gboolean caught, uncaught, subclasses; /* For kind == MOD_KIND_EXCEPTION_ONLY */
557 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
561 * Describes a single step request.
565 MonoInternalThread *thread;
571 MonoMethod *start_method;
572 MonoMethod *last_method;
574 /* Whenever single stepping is performed using start/stop_single_stepping () */
576 /* The list of breakpoints used to implement step-over */
578 /* The number of frames at the start of a step-over */
583 * Contains additional information for an event
586 /* For EVENT_KIND_EXCEPTION */
588 MonoContext catch_ctx;
590 /* For EVENT_KIND_USER_LOG */
592 char *category, *message;
593 /* For EVENT_KIND_TYPE_LOAD */
597 /* Dummy structure used for the profiler callbacks */
603 guint8 *buf, *p, *end;
606 typedef struct ReplyPacket {
612 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
614 #ifdef PLATFORM_ANDROID
615 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { g_print (__VA_ARGS__); } } while (0)
617 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { fprintf (log_file, __VA_ARGS__); fflush (log_file); } } while (0)
621 #define get_last_sock_error() WSAGetLastError()
622 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
623 #define MONO_EINTR WSAEINTR
625 #define get_last_sock_error() errno
626 #define MONO_EWOULDBLOCK EWOULDBLOCK
627 #define MONO_EINTR EINTR
630 #define CHECK_PROTOCOL_VERSION(major,minor) \
631 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
637 static AgentConfig agent_config;
640 * Whenever the agent is fully initialized.
641 * When using the onuncaught or onthrow options, only some parts of the agent are
642 * initialized on startup, and the full initialization which includes connection
643 * establishment and the startup of the agent thread is only done in response to
646 static gint32 inited;
648 #ifndef DISABLE_SOCKET_TRANSPORT
650 static int listen_fd;
653 static int packet_id = 0;
655 static int objref_id = 0;
657 static int event_request_id = 0;
659 static int frame_id = 0;
661 static GPtrArray *event_requests;
663 static MonoNativeTlsKey debugger_tls_id;
665 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
667 /* Maps MonoInternalThread -> DebuggerTlsData */
668 static MonoGHashTable *thread_to_tls;
670 /* Maps tid -> MonoInternalThread */
671 static MonoGHashTable *tid_to_thread;
673 /* Maps tid -> MonoThread (not MonoInternalThread) */
674 static MonoGHashTable *tid_to_thread_obj;
676 static gsize debugger_thread_id;
678 static HANDLE debugger_thread_handle;
680 static int log_level;
682 static gboolean embedding;
684 static FILE *log_file;
686 /* Assemblies whose assembly load event has no been sent yet */
687 /* Protected by the dbg lock */
688 static GPtrArray *pending_assembly_loads;
690 /* Whenever the debugger thread has exited */
691 static gboolean debugger_thread_exited;
693 /* Cond variable used to wait for debugger_thread_exited becoming true */
694 static mono_cond_t debugger_thread_exited_cond;
696 /* Mutex for the cond var above */
697 static mono_mutex_t debugger_thread_exited_mutex;
699 static DebuggerProfiler debugger_profiler;
701 /* The single step request instance */
702 static SingleStepReq *ss_req;
703 static gpointer ss_invoke_addr;
705 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
706 /* Number of single stepping operations in progress */
710 /* The protocol version of the client */
711 static int major_version, minor_version;
713 /* Whenever the variables above are set by the client */
714 static gboolean protocol_version_set;
716 /* A hash table containing all active domains */
717 static GHashTable *domains;
719 /* The number of times the runtime is suspended */
720 static gint32 suspend_count;
722 /* Whenever to buffer reply messages and send them together */
723 static gboolean buffer_replies;
725 /* Buffered reply packets */
726 static ReplyPacket reply_packets [128];
729 #define dbg_lock() do { \
731 mono_mutex_lock (&debug_mutex); \
732 MONO_FINISH_TRY_BLOCKING \
735 #define dbg_unlock() mono_mutex_unlock (&debug_mutex)
736 static mono_mutex_t debug_mutex;
738 static void transport_init (void);
739 static void transport_connect (const char *address);
740 static gboolean transport_handshake (void);
741 static void register_transport (DebuggerTransport *trans);
743 static guint32 WINAPI debugger_thread (void *arg);
745 static void runtime_initialized (MonoProfiler *prof);
747 static void runtime_shutdown (MonoProfiler *prof);
749 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
751 static void thread_end (MonoProfiler *prof, uintptr_t tid);
753 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
755 static void appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain);
757 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
759 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
761 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
763 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
765 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
767 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
769 static void emit_assembly_load (gpointer assembly, gpointer user_data);
771 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
773 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
775 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
777 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
779 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
781 static void start_single_stepping (void);
783 static void stop_single_stepping (void);
785 static void suspend_current (void);
787 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
789 static void clear_types_for_assembly (MonoAssembly *assembly);
791 static void clear_breakpoints_for_domain (MonoDomain *domain);
793 static void process_profiler_event (EventKind event, gpointer arg);
795 /* Submodule init/cleanup */
796 static void breakpoints_init (void);
797 static void breakpoints_cleanup (void);
799 static void objrefs_init (void);
800 static void objrefs_cleanup (void);
802 static void ids_init (void);
803 static void ids_cleanup (void);
805 static void suspend_init (void);
807 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch,
808 StackFrame **frames, int nframes);
809 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req);
810 static void ss_destroy (SingleStepReq *req);
812 static void start_debugger_thread (void);
813 static void stop_debugger_thread (void);
815 static void finish_agent_init (gboolean on_startup);
817 static void process_profiler_event (EventKind event, gpointer arg);
819 static void invalidate_frames (DebuggerTlsData *tls);
821 #ifndef DISABLE_SOCKET_TRANSPORT
823 register_socket_transport (void);
826 static inline gboolean
827 is_debugger_thread (void)
829 return GetCurrentThreadId () == debugger_thread_id;
833 parse_address (char *address, char **host, int *port)
835 char *pos = strchr (address, ':');
837 if (pos == NULL || pos == address)
840 *host = g_malloc (pos - address + 1);
841 strncpy (*host, address, pos - address);
842 (*host) [pos - address] = '\0';
844 *port = atoi (pos + 1);
852 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
853 fprintf (stderr, "Available options:\n");
854 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
855 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
856 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
857 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
858 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
859 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
860 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
861 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
862 fprintf (stderr, " setpgid=y/n\t\t\tWhether to call setpid(0, 0) after startup.\n");
863 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
867 parse_flag (const char *option, char *flag)
869 if (!strcmp (flag, "y"))
871 else if (!strcmp (flag, "n"))
874 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
881 mono_debugger_agent_parse_options (char *options)
888 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
889 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
893 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
895 options = g_strdup_printf ("%s,%s", options, extra);
897 agent_config.enabled = TRUE;
898 agent_config.suspend = TRUE;
899 agent_config.server = FALSE;
900 agent_config.defer = FALSE;
901 agent_config.address = NULL;
903 //agent_config.log_level = 10;
905 args = g_strsplit (options, ",", -1);
906 for (ptr = args; ptr && *ptr; ptr ++) {
909 if (strncmp (arg, "transport=", 10) == 0) {
910 agent_config.transport = g_strdup (arg + 10);
911 } else if (strncmp (arg, "address=", 8) == 0) {
912 agent_config.address = g_strdup (arg + 8);
913 } else if (strncmp (arg, "loglevel=", 9) == 0) {
914 agent_config.log_level = atoi (arg + 9);
915 } else if (strncmp (arg, "logfile=", 8) == 0) {
916 agent_config.log_file = g_strdup (arg + 8);
917 } else if (strncmp (arg, "suspend=", 8) == 0) {
918 agent_config.suspend = parse_flag ("suspend", arg + 8);
919 } else if (strncmp (arg, "server=", 7) == 0) {
920 agent_config.server = parse_flag ("server", arg + 7);
921 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
922 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
923 } else if (strncmp (arg, "onthrow=", 8) == 0) {
924 /* We support multiple onthrow= options */
925 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
926 } else if (strncmp (arg, "onthrow", 7) == 0) {
927 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
928 } else if (strncmp (arg, "help", 4) == 0) {
931 } else if (strncmp (arg, "timeout=", 8) == 0) {
932 agent_config.timeout = atoi (arg + 8);
933 } else if (strncmp (arg, "launch=", 7) == 0) {
934 agent_config.launch = g_strdup (arg + 7);
935 } else if (strncmp (arg, "embedding=", 10) == 0) {
936 agent_config.embedding = atoi (arg + 10) == 1;
937 } else if (strncmp (arg, "keepalive=", 10) == 0) {
938 agent_config.keepalive = atoi (arg + 10);
939 } else if (strncmp (arg, "setpgid=", 8) == 0) {
940 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
947 if (agent_config.server && !agent_config.suspend) {
948 /* Waiting for deferred attachment */
949 agent_config.defer = TRUE;
950 if (agent_config.address == NULL) {
951 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (getpid () % 1000));
955 //agent_config.log_level = 0;
957 if (agent_config.transport == NULL) {
958 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
962 if (agent_config.address == NULL && !agent_config.server) {
963 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
968 if (!strcmp (agent_config.transport, "dt_socket")) {
969 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
970 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
977 mono_debugger_agent_init (void)
979 mono_mutex_init_recursive (&debug_mutex);
981 if (!agent_config.enabled)
986 /* Need to know whenever a thread has acquired the loader mutex */
987 mono_loader_lock_track_ownership (TRUE);
989 event_requests = g_ptr_array_new ();
991 mono_mutex_init (&debugger_thread_exited_mutex);
992 mono_cond_init (&debugger_thread_exited_cond, NULL);
994 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
995 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
996 mono_profiler_install_runtime_initialized (runtime_initialized);
997 mono_profiler_install_appdomain (NULL, appdomain_load, appdomain_start_unload, appdomain_unload);
998 mono_profiler_install_thread (thread_startup, thread_end);
999 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
1000 mono_profiler_install_jit_end (jit_end);
1001 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
1003 mono_native_tls_alloc (&debugger_tls_id, NULL);
1005 /* Needed by the hash_table_new_type () call below */
1006 mono_gc_base_init ();
1008 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
1009 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls);
1011 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
1012 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread);
1014 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
1015 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj);
1017 pending_assembly_loads = g_ptr_array_new ();
1018 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
1020 log_level = agent_config.log_level;
1022 embedding = agent_config.embedding;
1023 disconnected = TRUE;
1025 if (agent_config.log_file) {
1026 log_file = fopen (agent_config.log_file, "w+");
1028 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
1037 breakpoints_init ();
1040 mini_get_debug_options ()->gen_sdb_seq_points = TRUE;
1042 * This is needed because currently we don't handle liveness info.
1044 mini_get_debug_options ()->mdb_optimizations = TRUE;
1046 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
1047 /* This is needed because we can't set local variables in registers yet */
1048 mono_disable_optimizations (MONO_OPT_LINEARS);
1052 * The stack walk done from thread_interrupt () needs to be signal safe, but it
1053 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
1054 * safe (#3411). So load AOT info eagerly when the debugger is running as a
1057 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
1060 if (agent_config.setpgid)
1064 if (!agent_config.onuncaught && !agent_config.onthrow)
1065 finish_agent_init (TRUE);
1069 * finish_agent_init:
1071 * Finish the initialization of the agent. This involves connecting the transport
1072 * and starting the agent thread. This is either done at startup, or
1073 * in response to some event like an unhandled exception.
1076 finish_agent_init (gboolean on_startup)
1080 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
1083 if (agent_config.launch) {
1086 // FIXME: Generated address
1087 // FIXME: Races with transport_connect ()
1089 argv [0] = agent_config.launch;
1090 argv [1] = agent_config.transport;
1091 argv [2] = agent_config.address;
1094 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1096 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1101 MONO_PREPARE_BLOCKING
1102 transport_connect (agent_config.address);
1103 MONO_FINISH_BLOCKING
1106 /* Do some which is usually done after sending the VMStart () event */
1107 vm_start_event_sent = TRUE;
1108 start_debugger_thread ();
1113 mono_debugger_agent_cleanup (void)
1118 stop_debugger_thread ();
1120 breakpoints_cleanup ();
1124 mono_mutex_destroy (&debugger_thread_exited_mutex);
1125 mono_cond_destroy (&debugger_thread_exited_cond);
1132 #ifndef DISABLE_SOCKET_TRANSPORT
1137 * recv() + handle incomplete reads and EINTR
1140 socket_transport_recv (void *buf, int len)
1146 static gint32 last_keepalive;
1151 res = recv (fd, (char *) buf + total, len - total, flags);
1154 if (agent_config.keepalive) {
1155 gboolean need_keepalive = FALSE;
1156 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1157 need_keepalive = TRUE;
1158 } else if (res == -1) {
1159 /* This could happen if recv () is interrupted repeatedly */
1160 msecs = mono_msec_ticks ();
1161 if (msecs - last_keepalive >= agent_config.keepalive) {
1162 need_keepalive = TRUE;
1163 last_keepalive = msecs;
1166 if (need_keepalive) {
1167 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1171 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1176 set_keepalive (void)
1181 if (!agent_config.keepalive || !conn_fd)
1184 tv.tv_sec = agent_config.keepalive / 1000;
1185 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1187 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1188 g_assert (result >= 0);
1192 socket_transport_accept (int socket_fd)
1194 conn_fd = accept (socket_fd, NULL, NULL);
1195 if (conn_fd == -1) {
1196 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1198 DEBUG_PRINTF (1, "Accepted connection from client, connection fd=%d.\n", conn_fd);
1205 socket_transport_send (void *data, int len)
1210 res = send (conn_fd, data, len, 0);
1211 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1219 * socket_transport_connect:
1221 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1224 socket_transport_connect (const char *address)
1226 MonoAddressInfo *result;
1227 MonoAddressEntry *rp;
1228 int sfd = -1, s, res;
1232 if (agent_config.address) {
1233 res = parse_address (agent_config.address, &host, &port);
1234 g_assert (res == 0);
1245 mono_network_init ();
1247 /* Obtain address(es) matching host/port */
1248 s = mono_get_address_info (host, port, MONO_HINT_UNSPECIFIED, &result);
1250 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, s); // FIXME add portable error conversion functions
1255 if (agent_config.server) {
1256 /* Wait for a connection */
1258 struct sockaddr_in addr;
1261 /* No address, generate one */
1262 sfd = socket (AF_INET, SOCK_STREAM, 0);
1265 /* This will bind the socket to a random port */
1266 res = listen (sfd, 16);
1268 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1273 addrlen = sizeof (addr);
1274 memset (&addr, 0, sizeof (addr));
1275 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1276 g_assert (res == 0);
1278 host = (char*)"127.0.0.1";
1279 port = ntohs (addr.sin_port);
1281 /* Emit the address to stdout */
1282 /* FIXME: Should print another interface, not localhost */
1283 printf ("%s:%d\n", host, port);
1285 /* Listen on the provided address */
1286 for (rp = result->entries; rp != NULL; rp = rp->next) {
1287 MonoSocketAddress sockaddr;
1291 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1293 sfd = socket (rp->family, rp->socktype,
1298 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1301 res = bind (sfd, &sockaddr.addr, sock_len);
1305 res = listen (sfd, 16);
1312 mono_free_address_info (result);
1315 if (agent_config.defer)
1318 DEBUG_PRINTF (1, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout);
1320 if (agent_config.timeout) {
1325 tv.tv_usec = agent_config.timeout * 1000;
1327 FD_SET (sfd, &readfds);
1328 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1330 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1335 MONO_PREPARE_BLOCKING
1336 conn_fd = socket_transport_accept (sfd);
1337 MONO_FINISH_BLOCKING
1341 DEBUG_PRINTF (1, "Accepted connection from client, socket fd=%d.\n", conn_fd);
1343 /* Connect to the specified address */
1344 /* FIXME: Respect the timeout */
1345 for (rp = result->entries; rp != NULL; rp = rp->next) {
1346 MonoSocketAddress sockaddr;
1349 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1351 sfd = socket (rp->family, rp->socktype,
1356 if (connect (sfd, &sockaddr.addr, sock_len) != -1)
1357 break; /* Success */
1363 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1369 mono_free_address_info (result);
1372 if (!transport_handshake ())
1377 socket_transport_close1 (void)
1379 /* This will interrupt the agent thread */
1380 /* Close the read part only so it can still send back replies */
1381 /* Also shut down the connection listener so that we can exit normally */
1383 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1384 shutdown (conn_fd, SD_BOTH);
1385 shutdown (listen_fd, SD_BOTH);
1386 closesocket (listen_fd);
1388 shutdown (conn_fd, SHUT_RD);
1389 shutdown (listen_fd, SHUT_RDWR);
1395 socket_transport_close2 (void)
1398 shutdown (conn_fd, SD_BOTH);
1400 shutdown (conn_fd, SHUT_RDWR);
1405 register_socket_transport (void)
1407 DebuggerTransport trans;
1409 trans.name = "dt_socket";
1410 trans.connect = socket_transport_connect;
1411 trans.close1 = socket_transport_close1;
1412 trans.close2 = socket_transport_close2;
1413 trans.send = socket_transport_send;
1414 trans.recv = socket_transport_recv;
1416 register_transport (&trans);
1420 * socket_fd_transport_connect:
1424 socket_fd_transport_connect (const char *address)
1428 res = sscanf (address, "%d", &conn_fd);
1430 fprintf (stderr, "debugger-agent: socket-fd transport address is invalid: '%s'\n", address);
1434 if (!transport_handshake ())
1439 register_socket_fd_transport (void)
1441 DebuggerTransport trans;
1443 /* This is the same as the 'dt_socket' transport, but receives an already connected socket fd */
1444 trans.name = "socket-fd";
1445 trans.connect = socket_fd_transport_connect;
1446 trans.close1 = socket_transport_close1;
1447 trans.close2 = socket_transport_close2;
1448 trans.send = socket_transport_send;
1449 trans.recv = socket_transport_recv;
1451 register_transport (&trans);
1454 #endif /* DISABLE_SOCKET_TRANSPORT */
1460 #define MAX_TRANSPORTS 16
1462 static DebuggerTransport *transport;
1464 static DebuggerTransport transports [MAX_TRANSPORTS];
1465 static int ntransports;
1468 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1471 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1473 register_transport (trans);
1477 register_transport (DebuggerTransport *trans)
1479 g_assert (ntransports < MAX_TRANSPORTS);
1481 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1486 transport_init (void)
1490 #ifndef DISABLE_SOCKET_TRANSPORT
1491 register_socket_transport ();
1492 register_socket_fd_transport ();
1495 for (i = 0; i < ntransports; ++i) {
1496 if (!strcmp (agent_config.transport, transports [i].name))
1499 if (i == ntransports) {
1500 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1501 for (i = 0; i < ntransports; ++i)
1502 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1503 fprintf (stderr, "\n");
1506 transport = &transports [i];
1510 transport_connect (const char *address)
1512 transport->connect (address);
1516 transport_close1 (void)
1518 transport->close1 ();
1522 transport_close2 (void)
1524 transport->close2 ();
1528 transport_send (void *buf, int len)
1530 return transport->send (buf, len);
1534 transport_recv (void *buf, int len)
1536 return transport->recv (buf, len);
1540 mono_debugger_agent_transport_handshake (void)
1542 return transport_handshake ();
1546 transport_handshake (void)
1548 char handshake_msg [128];
1552 disconnected = TRUE;
1554 /* Write handshake message */
1555 sprintf (handshake_msg, "DWP-Handshake");
1556 /* Must use try blocking as this can nest into code that runs blocking */
1559 res = transport_send (handshake_msg, strlen (handshake_msg));
1560 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1561 MONO_FINISH_TRY_BLOCKING
1563 g_assert (res != -1);
1567 res = transport_recv (buf, strlen (handshake_msg));
1568 MONO_FINISH_TRY_BLOCKING
1569 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg)) != 0)) {
1570 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1575 * To support older clients, the client sends its protocol version after connecting
1576 * using a command. Until that is received, default to our protocol version.
1578 major_version = MAJOR_VERSION;
1579 minor_version = MINOR_VERSION;
1580 protocol_version_set = FALSE;
1582 #ifndef DISABLE_SOCKET_TRANSPORT
1583 // FIXME: Move this somewhere else
1585 * Set TCP_NODELAY on the socket so the client receives events/command
1586 * results immediately.
1590 int result = setsockopt (conn_fd,
1595 g_assert (result >= 0);
1601 disconnected = FALSE;
1606 stop_debugger_thread (void)
1611 MONO_PREPARE_BLOCKING
1612 transport_close1 ();
1613 MONO_FINISH_BLOCKING
1616 * Wait for the thread to exit.
1618 * If we continue with the shutdown without waiting for it, then the client might
1619 * not receive an answer to its last command like a resume.
1620 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
1623 //WaitForSingleObject (debugger_thread_handle, INFINITE);
1624 if (GetCurrentThreadId () != debugger_thread_id) {
1627 mono_mutex_lock (&debugger_thread_exited_mutex);
1628 if (!debugger_thread_exited) {
1630 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
1631 mono_mutex_unlock (&debugger_thread_exited_mutex);
1633 mono_mutex_lock (&debugger_thread_exited_mutex);
1636 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1639 mono_mutex_unlock (&debugger_thread_exited_mutex);
1640 MONO_FINISH_TRY_BLOCKING
1641 } while (!debugger_thread_exited);
1644 MONO_PREPARE_BLOCKING
1645 transport_close2 ();
1646 MONO_FINISH_BLOCKING
1650 start_debugger_thread (void)
1652 debugger_thread_handle = mono_threads_create_thread (debugger_thread, NULL, 0, 0, NULL);
1653 g_assert (debugger_thread_handle);
1657 * Functions to decode protocol data
1661 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1664 g_assert (*endbuf <= limit);
1669 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1672 g_assert (*endbuf <= limit);
1674 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1677 static inline gint64
1678 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1680 guint32 high = decode_int (buf, &buf, limit);
1681 guint32 low = decode_int (buf, &buf, limit);
1685 return ((((guint64)high) << 32) | ((guint64)low));
1689 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1691 return decode_int (buf, endbuf, limit);
1695 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1697 int len = decode_int (buf, &buf, limit);
1705 s = g_malloc (len + 1);
1708 memcpy (s, buf, len);
1717 * Functions to encode protocol data
1721 buffer_init (Buffer *buf, int size)
1723 buf->buf = g_malloc (size);
1725 buf->end = buf->buf + size;
1729 buffer_len (Buffer *buf)
1731 return buf->p - buf->buf;
1735 buffer_make_room (Buffer *buf, int size)
1737 if (buf->end - buf->p < size) {
1738 int new_size = buf->end - buf->buf + size + 32;
1739 guint8 *p = g_realloc (buf->buf, new_size);
1740 size = buf->p - buf->buf;
1743 buf->end = buf->buf + new_size;
1748 buffer_add_byte (Buffer *buf, guint8 val)
1750 buffer_make_room (buf, 1);
1756 buffer_add_short (Buffer *buf, guint32 val)
1758 buffer_make_room (buf, 2);
1759 buf->p [0] = (val >> 8) & 0xff;
1760 buf->p [1] = (val >> 0) & 0xff;
1765 buffer_add_int (Buffer *buf, guint32 val)
1767 buffer_make_room (buf, 4);
1768 buf->p [0] = (val >> 24) & 0xff;
1769 buf->p [1] = (val >> 16) & 0xff;
1770 buf->p [2] = (val >> 8) & 0xff;
1771 buf->p [3] = (val >> 0) & 0xff;
1776 buffer_add_long (Buffer *buf, guint64 l)
1778 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1779 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1783 buffer_add_id (Buffer *buf, int id)
1785 buffer_add_int (buf, (guint64)id);
1789 buffer_add_data (Buffer *buf, guint8 *data, int len)
1791 buffer_make_room (buf, len);
1792 memcpy (buf->p, data, len);
1797 buffer_add_string (Buffer *buf, const char *str)
1802 buffer_add_int (buf, 0);
1805 buffer_add_int (buf, len);
1806 buffer_add_data (buf, (guint8*)str, len);
1811 buffer_add_buffer (Buffer *buf, Buffer *data)
1813 buffer_add_data (buf, data->buf, buffer_len (data));
1817 buffer_free (Buffer *buf)
1823 send_packet (int command_set, int command, Buffer *data)
1829 id = InterlockedIncrement (&packet_id);
1831 len = data->p - data->buf + 11;
1832 buffer_init (&buf, len);
1833 buffer_add_int (&buf, len);
1834 buffer_add_int (&buf, id);
1835 buffer_add_byte (&buf, 0); /* flags */
1836 buffer_add_byte (&buf, command_set);
1837 buffer_add_byte (&buf, command);
1838 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1840 MONO_PREPARE_BLOCKING
1841 res = transport_send (buf.buf, len);
1842 MONO_FINISH_BLOCKING
1850 send_reply_packets (int npackets, ReplyPacket *packets)
1857 for (i = 0; i < npackets; ++i)
1858 len += buffer_len (packets [i].data) + 11;
1859 buffer_init (&buf, len);
1860 for (i = 0; i < npackets; ++i) {
1861 buffer_add_int (&buf, buffer_len (packets [i].data) + 11);
1862 buffer_add_int (&buf, packets [i].id);
1863 buffer_add_byte (&buf, 0x80); /* flags */
1864 buffer_add_byte (&buf, (packets [i].error >> 8) & 0xff);
1865 buffer_add_byte (&buf, packets [i].error);
1866 buffer_add_buffer (&buf, packets [i].data);
1869 MONO_PREPARE_BLOCKING
1870 res = transport_send (buf.buf, len);
1871 MONO_FINISH_BLOCKING
1879 send_reply_packet (int id, int error, Buffer *data)
1883 memset (&packet, 0, sizeof (ReplyPacket));
1885 packet.error = error;
1888 return send_reply_packets (1, &packet);
1892 send_buffered_reply_packets (void)
1896 send_reply_packets (nreply_packets, reply_packets);
1897 for (i = 0; i < nreply_packets; ++i)
1898 buffer_free (reply_packets [i].data);
1899 DEBUG_PRINTF (1, "[dbg] Sent %d buffered reply packets [at=%lx].\n", nreply_packets, (long)mono_100ns_ticks () / 10000);
1904 buffer_reply_packet (int id, int error, Buffer *data)
1908 if (nreply_packets == 128)
1909 send_buffered_reply_packets ();
1911 p = &reply_packets [nreply_packets];
1914 p->data = g_new0 (Buffer, 1);
1915 buffer_init (p->data, buffer_len (data));
1916 buffer_add_buffer (p->data, data);
1925 * Represents an object accessible by the debugger client.
1928 /* Unique id used in the wire protocol to refer to objects */
1931 * A weakref gc handle pointing to the object. The gc handle is used to
1932 * detect if the object was garbage collected.
1937 /* Maps objid -> ObjRef */
1938 static GHashTable *objrefs;
1939 static GHashTable *obj_to_objref;
1940 /* Protected by the dbg lock */
1941 static MonoGHashTable *suspended_objs;
1944 free_objref (gpointer value)
1948 mono_gchandle_free (o->handle);
1956 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1957 obj_to_objref = g_hash_table_new (NULL, NULL);
1958 suspended_objs = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
1959 MONO_GC_REGISTER_ROOT_FIXED (suspended_objs);
1963 objrefs_cleanup (void)
1965 g_hash_table_destroy (objrefs);
1970 * Return an ObjRef for OBJ.
1973 get_objref (MonoObject *obj)
1976 GSList *reflist = NULL, *l;
1982 if (suspend_count) {
1984 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1987 mono_g_hash_table_insert (suspended_objs, obj, NULL);
1991 mono_loader_lock ();
1993 /* FIXME: The tables can grow indefinitely */
1995 if (mono_gc_is_moving ()) {
1997 * Objects can move, so use a hash table mapping hash codes to lists of
1998 * ObjRef structures.
2000 hash = mono_object_hash (obj);
2002 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
2003 for (l = reflist; l; l = l->next) {
2005 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
2006 mono_loader_unlock ();
2011 /* Use a hash table with masked pointers to internalize object references */
2012 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
2013 /* ref might refer to a different object with the same addr which was GCd */
2014 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
2015 mono_loader_unlock ();
2020 ref = g_new0 (ObjRef, 1);
2021 ref->id = InterlockedIncrement (&objref_id);
2022 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
2024 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
2026 if (mono_gc_is_moving ()) {
2027 reflist = g_slist_append (reflist, ref);
2028 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
2030 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
2033 mono_loader_unlock ();
2039 true_pred (gpointer key, gpointer value, gpointer user_data)
2045 clear_suspended_objs (void)
2048 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
2053 get_objid (MonoObject *obj)
2055 return get_objref (obj)->id;
2059 * Set OBJ to the object identified by OBJID.
2060 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
2064 get_object_allow_null (int objid, MonoObject **obj)
2074 return ERR_INVALID_OBJECT;
2076 mono_loader_lock ();
2078 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
2081 *obj = mono_gchandle_get_target (ref->handle);
2082 mono_loader_unlock ();
2084 return ERR_INVALID_OBJECT;
2087 mono_loader_unlock ();
2088 return ERR_INVALID_OBJECT;
2093 get_object (int objid, MonoObject **obj)
2095 int err = get_object_allow_null (objid, obj);
2100 return ERR_INVALID_OBJECT;
2105 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
2107 return decode_id (buf, endbuf, limit);
2111 buffer_add_objid (Buffer *buf, MonoObject *o)
2113 buffer_add_id (buf, get_objid (o));
2132 * Represents a runtime structure accessible to the debugger client
2135 /* Unique id used in the wire protocol */
2137 /* Domain of the runtime structure, NULL if the domain was unloaded */
2144 MonoAssembly *assembly;
2145 MonoClassField *field;
2147 MonoProperty *property;
2152 /* Maps runtime structure -> Id */
2153 GHashTable *val_to_id [ID_NUM];
2154 /* Classes whose class load event has been sent */
2155 GHashTable *loaded_classes;
2156 /* Maps MonoClass->GPtrArray of file names */
2157 GHashTable *source_files;
2158 /* Maps source file basename -> GSList of classes */
2159 GHashTable *source_file_to_class;
2160 /* Same with ignore-case */
2161 GHashTable *source_file_to_class_ignorecase;
2165 /* Protected by the dbg lock */
2166 static GPtrArray *ids [ID_NUM];
2173 for (i = 0; i < ID_NUM; ++i)
2174 ids [i] = g_ptr_array_new ();
2182 for (i = 0; i < ID_NUM; ++i) {
2184 for (j = 0; j < ids [i]->len; ++j)
2185 g_free (g_ptr_array_index (ids [i], j));
2186 g_ptr_array_free (ids [i], TRUE);
2193 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2195 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
2197 GHashTableIter iter;
2198 GPtrArray *file_names;
2203 for (i = 0; i < ID_NUM; ++i)
2204 if (info->val_to_id [i])
2205 g_hash_table_destroy (info->val_to_id [i]);
2206 g_hash_table_destroy (info->loaded_classes);
2208 g_hash_table_iter_init (&iter, info->source_files);
2209 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2210 for (i = 0; i < file_names->len; ++i)
2211 g_free (g_ptr_array_index (file_names, i));
2212 g_ptr_array_free (file_names, TRUE);
2215 g_hash_table_iter_init (&iter, info->source_file_to_class);
2216 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2221 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2222 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2230 domain_jit_info (domain)->agent_info = NULL;
2232 /* Clear ids referencing structures in the domain */
2234 for (i = 0; i < ID_NUM; ++i) {
2236 for (j = 0; j < ids [i]->len; ++j) {
2237 Id *id = g_ptr_array_index (ids [i], j);
2238 if (id->domain == domain)
2245 mono_loader_lock ();
2246 g_hash_table_remove (domains, domain);
2247 mono_loader_unlock ();
2250 static AgentDomainInfo*
2251 get_agent_domain_info (MonoDomain *domain)
2253 AgentDomainInfo *info = NULL;
2255 mono_domain_lock (domain);
2257 info = domain_jit_info (domain)->agent_info;
2259 info = domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
2260 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2261 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2262 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2263 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2266 mono_domain_unlock (domain);
2272 get_id (MonoDomain *domain, IdType type, gpointer val)
2275 AgentDomainInfo *info;
2280 mono_loader_lock ();
2282 mono_domain_lock (domain);
2284 info = get_agent_domain_info (domain);
2286 if (info->val_to_id [type] == NULL)
2287 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2289 id = g_hash_table_lookup (info->val_to_id [type], val);
2291 mono_domain_unlock (domain);
2292 mono_loader_unlock ();
2298 id = g_new0 (Id, 1);
2300 id->id = ids [type]->len + 1;
2301 id->domain = domain;
2304 g_hash_table_insert (info->val_to_id [type], val, id);
2305 g_ptr_array_add (ids [type], id);
2309 mono_domain_unlock (domain);
2311 mono_loader_unlock ();
2316 static inline gpointer
2317 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
2321 int id = decode_id (buf, endbuf, limit);
2330 // FIXME: error handling
2332 g_assert (id > 0 && id <= ids [type]->len);
2334 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2337 if (res->domain == NULL) {
2338 DEBUG_PRINTF (1, "ERR_UNLOADED, id=%d, type=%d.\n", id, type);
2339 *err = ERR_UNLOADED;
2344 *domain = res->domain;
2346 return res->data.val;
2350 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2352 int id = get_id (domain, type, val);
2354 buffer_add_id (buf, id);
2358 static inline MonoClass*
2359 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2363 klass = decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2364 if (G_UNLIKELY (log_level >= 2) && klass) {
2367 s = mono_type_full_name (&klass->byval_arg);
2368 DEBUG_PRINTF (2, "[dbg] recv class [%s]\n", s);
2374 static inline MonoAssembly*
2375 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2377 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2380 static inline MonoImage*
2381 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2383 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2386 static inline MonoMethod*
2387 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2391 m = decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2392 if (G_UNLIKELY (log_level >= 2) && m) {
2395 s = mono_method_full_name (m, TRUE);
2396 DEBUG_PRINTF (2, "[dbg] recv method [%s]\n", s);
2402 static inline MonoClassField*
2403 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2405 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2408 static inline MonoDomain*
2409 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2411 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2414 static inline MonoProperty*
2415 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2417 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2421 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2423 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2424 if (G_UNLIKELY (log_level >= 2) && klass) {
2427 s = mono_type_full_name (&klass->byval_arg);
2428 if (GetCurrentThreadId () == debugger_thread_id)
2429 DEBUG_PRINTF (2, "[dbg] send class [%s]\n", s);
2431 DEBUG_PRINTF (2, "[%p] send class [%s]\n", (gpointer)GetCurrentThreadId (), s);
2437 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2439 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2440 if (G_UNLIKELY (log_level >= 2) && method) {
2443 s = mono_method_full_name (method, 1);
2444 DEBUG_PRINTF (2, "[dbg] send method [%s]\n", s);
2450 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2454 id = buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2455 if (G_UNLIKELY (log_level >= 2) && assembly)
2456 DEBUG_PRINTF (2, "[dbg] send assembly [%s][%s][%d]\n", assembly->aname.name, domain->friendly_name, id);
2460 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2462 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2466 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2468 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2472 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2474 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2478 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2480 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2483 static void invoke_method (void);
2490 * save_thread_context:
2492 * Set CTX as the current threads context which is used for computing stack traces.
2493 * This function is signal-safe.
2496 save_thread_context (MonoContext *ctx)
2498 DebuggerTlsData *tls;
2500 tls = mono_native_tls_get_value (debugger_tls_id);
2504 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2506 mono_thread_state_init_from_current (&tls->context);
2509 /* Number of threads suspended */
2511 * If this is equal to the size of thread_to_tls, the runtime is considered
2514 static gint32 threads_suspend_count;
2516 static mono_mutex_t suspend_mutex;
2518 /* Cond variable used to wait for suspend_count becoming 0 */
2519 static mono_cond_t suspend_cond;
2521 /* Semaphore used to wait for a thread becoming suspended */
2522 static MonoSemType suspend_sem;
2527 mono_mutex_init (&suspend_mutex);
2528 mono_cond_init (&suspend_cond, NULL);
2529 MONO_SEM_INIT (&suspend_sem, 0);
2534 StackFrameInfo last_frame;
2535 gboolean last_frame_set;
2538 } GetLastFrameUserData;
2541 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2543 GetLastFrameUserData *data = user_data;
2545 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
2548 if (!data->last_frame_set) {
2549 /* Store the last frame */
2550 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2551 data->last_frame_set = TRUE;
2554 /* Store the context/lmf for the frame above the last frame */
2555 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2556 data->lmf = info->lmf;
2564 * Process interruption of a thread. If SIGCTX is set, process the current thread. If
2565 * INFO is set, process the thread described by INFO.
2566 * This should be signal safe.
2569 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, void *sigctx, MonoJitInfo *ji)
2573 MonoNativeThreadId tid;
2576 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2577 * guarantee the signal handler will be called that many times. Instead of tracking
2578 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2579 * has been requested that hasn't been handled yet, otherwise we can have threads
2580 * refuse to die when VM_EXIT is called
2582 #if defined(__APPLE__)
2583 if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
2587 * We use interrupt_count to determine whenever this interrupt should be processed
2588 * by us or the normal interrupt processing code in the signal handler.
2589 * There is no race here with notify_thread (), since the signal is sent after
2590 * incrementing interrupt_count.
2592 if (tls->interrupt_count == 0)
2595 InterlockedDecrement (&tls->interrupt_count);
2599 ip = mono_arch_ip_from_context (sigctx);
2601 ip = MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx);
2606 tid = mono_thread_info_get_tid (info);
2608 tid = (MonoNativeThreadId)GetCurrentThreadId ();
2610 // FIXME: Races when the thread leaves managed code before hitting a single step
2614 /* Running managed code, will be suspended by the single step code */
2615 DEBUG_PRINTF (1, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip);
2619 * Running native code, will be suspended when it returns to/enters
2620 * managed code. Treat it as already suspended.
2621 * This might interrupt the code in process_single_step_inner (), we use the
2622 * tls->suspending flag to avoid races when that happens.
2624 if (!tls->suspended && !tls->suspending) {
2626 GetLastFrameUserData data;
2628 // FIXME: printf is not signal safe, but this is only used during
2629 // debugger debugging
2631 DEBUG_PRINTF (1, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip);
2632 //save_thread_context (&ctx);
2635 /* Already terminated */
2639 * We are in a difficult position: we want to be able to provide stack
2640 * traces for this thread, but we can't use the current ctx+lmf, since
2641 * the thread is still running, so it might return to managed code,
2642 * making these invalid.
2643 * So we start a stack walk and save the first frame, along with the
2644 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2645 * suspended when it returns to managed code, so the parent's ctx should
2648 data.last_frame_set = FALSE;
2650 mono_sigctx_to_monoctx (sigctx, &ctx);
2652 * Don't pass MONO_UNWIND_ACTUAL_METHOD, its not signal safe, and
2653 * get_last_frame () doesn't need it, the last frame cannot be a ginst
2654 * since we are not in a JITted method.
2656 mono_walk_stack_with_ctx (get_last_frame, &ctx, MONO_UNWIND_NONE, &data);
2658 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, mono_thread_info_get_suspend_state (info), MONO_UNWIND_SIGNAL_SAFE, &data);
2660 if (data.last_frame_set) {
2661 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2662 res = mono_thread_state_init_from_monoctx (&tls->async_state, &ctx);
2664 mono_thread_state_init_from_monoctx (&tls->context, &ctx);
2667 memcpy (&tls->async_state.ctx, &data.ctx, sizeof (MonoContext));
2668 tls->async_state.unwind_data [MONO_UNWIND_DATA_LMF] = data.lmf;
2669 tls->async_state.unwind_data [MONO_UNWIND_DATA_JIT_TLS] = ((MonoThreadInfo*)tls->thread->thread_info)->jit_data;
2671 tls->async_state.valid = FALSE;
2674 mono_memory_barrier ();
2676 tls->suspended = TRUE;
2677 MONO_SEM_POST (&suspend_sem);
2684 * mono_debugger_agent_thread_interrupt:
2686 * Called by the abort signal handler.
2687 * Should be signal safe.
2690 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
2692 DebuggerTlsData *tls;
2697 tls = mono_native_tls_get_value (debugger_tls_id);
2699 DEBUG_PRINTF (1, "[%p] Received interrupt with no TLS, continuing.\n", (gpointer)GetCurrentThreadId ());
2703 return thread_interrupt (tls, NULL, sigctx, ji);
2707 static void CALLBACK notify_thread_apc (ULONG_PTR param)
2710 mono_debugger_agent_thread_interrupt (NULL, NULL);
2712 #endif /* HOST_WIN32 */
2715 * reset_native_thread_suspend_state:
2717 * Reset the suspended flag and state on native threads
2720 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2722 DebuggerTlsData *tls = value;
2724 if (!tls->really_suspended && tls->suspended) {
2725 tls->suspended = FALSE;
2727 * The thread might still be running if it was executing native code, so the state won't be invalided by
2728 * suspend_current ().
2730 tls->context.valid = FALSE;
2731 tls->async_state.valid = FALSE;
2732 invalidate_frames (tls);
2737 DebuggerTlsData *tls;
2738 gboolean valid_info;
2741 static SuspendThreadResult
2742 debugger_interrupt_critical (MonoThreadInfo *info, gpointer user_data)
2744 InterruptData *data = user_data;
2747 data->valid_info = TRUE;
2748 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));
2750 thread_interrupt (data->tls, info, NULL, ji);
2751 return MonoResumeThread;
2757 * Notify a thread that it needs to suspend.
2760 notify_thread (gpointer key, gpointer value, gpointer user_data)
2762 MonoInternalThread *thread = key;
2763 DebuggerTlsData *tls = value;
2764 gsize tid = thread->tid;
2769 if (GetCurrentThreadId () == tid || tls->terminated)
2772 DEBUG_PRINTF (1, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid);
2775 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2776 * guarantee the signal handler will be called that many times. Instead of tracking
2777 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2778 * has been requested that hasn't been handled yet, otherwise we can have threads
2779 * refuse to die when VM_EXIT is called
2781 #if defined(__APPLE__)
2782 if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
2786 * Maybe we could use the normal interrupt infrastructure, but that does a lot
2787 * of things like breaking waits etc. which we don't want.
2789 InterlockedIncrement (&tls->interrupt_count);
2792 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2793 if (mono_thread_info_new_interrupt_enabled ()) {
2794 InterruptData interrupt_data = { 0 };
2795 interrupt_data.tls = tls;
2797 mono_thread_info_safe_suspend_and_run ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE, debugger_interrupt_critical, &interrupt_data);
2798 if (!interrupt_data.valid_info) {
2799 DEBUG_PRINTF (1, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid);
2801 * Attached thread which died without detaching.
2803 tls->terminated = TRUE;
2807 // FIXME: Remove this since new interrupt is used on win32 now
2808 QueueUserAPC (notify_thread_apc, thread->handle, (ULONG_PTR)NULL);
2810 res = mono_thread_kill (thread, mono_thread_get_abort_signal ());
2812 DEBUG_PRINTF (1, "[%p] mono_thread_kill () failed for %p: %d...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid, res);
2814 * Attached thread which died without detaching.
2816 tls->terminated = TRUE;
2823 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2825 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2829 if (mono_loader_lock_is_owned_by_self ()) {
2831 * Shortcut for the check in suspend_current (). This speeds up processing
2832 * when executing long running code inside the loader lock, i.e. assembly load
2838 if (debugger_thread_id == GetCurrentThreadId ())
2841 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2842 if (suspend_count - tls->resume_count > 0)
2843 tls->suspending = TRUE;
2845 DEBUG_PRINTF (1, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ());
2847 if (suspend_count - tls->resume_count == 0) {
2849 * We are executing a single threaded invoke but the single step for
2850 * suspending is still active.
2851 * FIXME: This slows down single threaded invokes.
2853 DEBUG_PRINTF (1, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ());
2857 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2859 /* Can't suspend in these methods */
2860 method = jinfo_get_method (ji);
2861 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2864 save_thread_context (ctx);
2872 * Increase the suspend count of the VM. While the suspend count is greater
2873 * than 0, runtime threads are suspended at certain points during execution.
2878 mono_loader_lock ();
2881 mono_mutex_lock (&suspend_mutex);
2882 MONO_FINISH_TRY_BLOCKING
2886 DEBUG_PRINTF (1, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ());
2888 if (suspend_count == 1) {
2889 // FIXME: Is it safe to call this inside the lock ?
2890 start_single_stepping ();
2891 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2894 mono_mutex_unlock (&suspend_mutex);
2896 if (suspend_count == 1)
2898 * Suspend creation of new threadpool threads, since they cannot run
2900 mono_thread_pool_suspend ();
2902 mono_loader_unlock ();
2908 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2916 g_assert (debugger_thread_id == GetCurrentThreadId ());
2918 mono_loader_lock ();
2921 mono_mutex_lock (&suspend_mutex);
2922 MONO_FINISH_TRY_BLOCKING
2924 g_assert (suspend_count > 0);
2927 DEBUG_PRINTF (1, "[%p] Resuming vm, suspend count=%d...\n", (gpointer)GetCurrentThreadId (), suspend_count);
2929 if (suspend_count == 0) {
2930 // FIXME: Is it safe to call this inside the lock ?
2931 stop_single_stepping ();
2932 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2935 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2936 err = mono_cond_broadcast (&suspend_cond);
2937 g_assert (err == 0);
2939 mono_mutex_unlock (&suspend_mutex);
2940 //g_assert (err == 0);
2942 if (suspend_count == 0)
2943 mono_thread_pool_resume ();
2945 mono_loader_unlock ();
2951 * Resume just one thread.
2954 resume_thread (MonoInternalThread *thread)
2957 DebuggerTlsData *tls;
2959 g_assert (debugger_thread_id == GetCurrentThreadId ());
2961 mono_loader_lock ();
2963 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2967 mono_mutex_lock (&suspend_mutex);
2968 MONO_FINISH_TRY_BLOCKING
2970 g_assert (suspend_count > 0);
2972 DEBUG_PRINTF (1, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid);
2974 tls->resume_count += suspend_count;
2977 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2978 * but only the one whose resume_count field is > 0 will be resumed.
2980 err = mono_cond_broadcast (&suspend_cond);
2981 g_assert (err == 0);
2983 mono_mutex_unlock (&suspend_mutex);
2984 //g_assert (err == 0);
2986 mono_loader_unlock ();
2990 free_frames (StackFrame **frames, int nframes)
2994 for (i = 0; i < nframes; ++i) {
2995 if (frames [i]->jit)
2996 mono_debug_free_method_jit_info (frames [i]->jit);
2997 g_free (frames [i]);
3003 invalidate_frames (DebuggerTlsData *tls)
3006 tls = mono_native_tls_get_value (debugger_tls_id);
3009 free_frames (tls->frames, tls->frame_count);
3010 tls->frame_count = 0;
3013 free_frames (tls->restore_frames, tls->restore_frame_count);
3014 tls->restore_frame_count = 0;
3015 tls->restore_frames = NULL;
3021 * Suspend the current thread until the runtime is resumed. If the thread has a
3022 * pending invoke, then the invoke is executed before this function returns.
3025 suspend_current (void)
3030 DebuggerTlsData *tls;
3032 g_assert (debugger_thread_id != GetCurrentThreadId ());
3034 if (mono_loader_lock_is_owned_by_self ()) {
3036 * If we own the loader mutex, can't suspend until we release it, since the
3037 * whole runtime can deadlock otherwise.
3042 tls = mono_native_tls_get_value (debugger_tls_id);
3046 mono_mutex_lock (&suspend_mutex);
3047 MONO_FINISH_TRY_BLOCKING
3049 tls->suspending = FALSE;
3050 tls->really_suspended = TRUE;
3052 if (!tls->suspended) {
3053 tls->suspended = TRUE;
3054 MONO_SEM_POST (&suspend_sem);
3057 DEBUG_PRINTF (1, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ());
3060 while (suspend_count - tls->resume_count > 0) {
3062 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
3064 mono_mutex_unlock (&suspend_mutex);
3066 mono_mutex_lock (&suspend_mutex);
3072 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
3073 g_assert (err == 0);
3076 MONO_FINISH_TRY_BLOCKING
3078 tls->suspended = FALSE;
3079 tls->really_suspended = FALSE;
3081 threads_suspend_count --;
3083 mono_mutex_unlock (&suspend_mutex);
3085 DEBUG_PRINTF (1, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ());
3087 if (tls->pending_invoke) {
3088 /* Save the original context */
3089 tls->pending_invoke->has_ctx = TRUE;
3090 tls->pending_invoke->ctx = tls->context.ctx;
3095 /* The frame info becomes invalid after a resume */
3096 tls->context.valid = FALSE;
3097 tls->async_state.valid = FALSE;
3098 invalidate_frames (tls);
3102 count_thread (gpointer key, gpointer value, gpointer user_data)
3104 DebuggerTlsData *tls = value;
3106 if (!tls->suspended && !tls->terminated)
3107 *(int*)user_data = *(int*)user_data + 1;
3111 count_threads_to_wait_for (void)
3115 mono_loader_lock ();
3116 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
3117 mono_loader_unlock ();
3125 * Wait until the runtime is completely suspended.
3128 wait_for_suspend (void)
3130 int nthreads, nwait, err;
3131 gboolean waited = FALSE;
3133 // FIXME: Threads starting/stopping ?
3134 mono_loader_lock ();
3135 nthreads = mono_g_hash_table_size (thread_to_tls);
3136 mono_loader_unlock ();
3139 nwait = count_threads_to_wait_for ();
3141 DEBUG_PRINTF (1, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads);
3142 err = MONO_SEM_WAIT (&suspend_sem);
3143 g_assert (err == 0);
3151 DEBUG_PRINTF (1, "%d threads suspended.\n", nthreads);
3157 * Return whenever the runtime is suspended.
3162 return count_threads_to_wait_for () == 0;
3166 no_seq_points_found (MonoMethod *method)
3169 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3171 printf ("Unable to find seq points for method '%s'.\n", mono_method_full_name (method, TRUE));
3175 DebuggerTlsData *tls;
3177 } ComputeFramesUserData;
3180 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3182 ComputeFramesUserData *ud = user_data;
3184 MonoMethod *method, *actual_method, *api_method;
3188 if (info->type != FRAME_TYPE_MANAGED) {
3189 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3190 /* Mark the last frame as an invoke frame */
3192 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3198 method = jinfo_get_method (info->ji);
3200 method = info->method;
3201 actual_method = info->actual_method;
3202 api_method = method;
3207 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3210 if (info->il_offset == -1) {
3211 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3212 if (ud->frames == NULL) {
3213 if (find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL, &sp))
3214 info->il_offset = sp.il_offset;
3216 if (info->il_offset == -1)
3217 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3220 DEBUG_PRINTF (1, "\tFrame: %s:%x(%x) %d\n", mono_method_full_name (method, TRUE), info->il_offset, info->native_offset, info->managed);
3222 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3223 if (!CHECK_PROTOCOL_VERSION (2, 17))
3224 /* Older clients can't handle this flag */
3226 api_method = mono_marshal_method_from_wrapper (method);
3229 actual_method = api_method;
3230 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3233 frame = g_new0 (StackFrame, 1);
3234 frame->method = method;
3235 frame->actual_method = actual_method;
3236 frame->api_method = api_method;
3237 frame->il_offset = info->il_offset;
3238 frame->native_offset = info->native_offset;
3239 frame->flags = flags;
3240 frame->ji = info->ji;
3241 if (info->reg_locations)
3242 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3245 frame->has_ctx = TRUE;
3247 frame->domain = info->domain;
3249 ud->frames = g_slist_append (ud->frames, frame);
3255 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3257 ComputeFramesUserData *ud = user_data;
3260 * 'tls->filter_ctx' is the location of the throw site.
3262 * mono_walk_stack() will never actually hit the throw site, but unwind
3263 * directly from the filter to the call site; we abort stack unwinding here
3264 * once this happens and resume from the throw site.
3267 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3270 return process_frame (info, ctx, user_data);
3274 * Return a malloc-ed list of StackFrame structures.
3277 compute_frame_info_from (MonoInternalThread *thread, DebuggerTlsData *tls, MonoThreadUnwindState *state, int *out_nframes)
3279 ComputeFramesUserData user_data;
3280 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3285 user_data.tls = tls;
3286 user_data.frames = NULL;
3288 mono_walk_stack_with_state (process_frame, state, opts, &user_data);
3290 nframes = g_slist_length (user_data.frames);
3291 res = g_new0 (StackFrame*, nframes);
3292 l = user_data.frames;
3293 for (i = 0; i < nframes; ++i) {
3297 *out_nframes = nframes;
3303 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3305 ComputeFramesUserData user_data;
3307 int i, findex, new_frame_count;
3308 StackFrame **new_frames, *f;
3309 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3311 // FIXME: Locking on tls
3312 if (tls->frames && tls->frames_up_to_date)
3315 DEBUG_PRINTF (1, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid);
3317 user_data.tls = tls;
3318 user_data.frames = NULL;
3319 if (tls->terminated) {
3320 tls->frame_count = 0;
3322 } if (!tls->really_suspended && tls->async_state.valid) {
3323 /* Have to use the state saved by the signal handler */
3324 process_frame (&tls->async_last_frame, NULL, &user_data);
3325 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3326 } else if (tls->filter_state.valid) {
3328 * We are inside an exception filter.
3330 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3332 if (tls->context.valid)
3333 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3335 * After that, we resume unwinding from the location where the exception has been thrown.
3337 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3338 } else if (tls->context.valid) {
3339 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3342 tls->frame_count = 0;
3346 new_frame_count = g_slist_length (user_data.frames);
3347 new_frames = g_new0 (StackFrame*, new_frame_count);
3349 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3353 * Reuse the id for already existing stack frames, so invokes don't invalidate
3354 * the still valid stack frames.
3356 for (i = 0; i < tls->frame_count; ++i) {
3357 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3358 f->id = tls->frames [i]->id;
3363 if (i >= tls->frame_count)
3364 f->id = InterlockedIncrement (&frame_id);
3366 new_frames [findex ++] = f;
3369 g_slist_free (user_data.frames);
3371 invalidate_frames (tls);
3373 tls->frames = new_frames;
3374 tls->frame_count = new_frame_count;
3375 tls->frames_up_to_date = TRUE;
3379 * GHFunc to emit an appdomain creation event
3380 * @param key Don't care
3381 * @param value A loaded appdomain
3382 * @param user_data Don't care
3385 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3387 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3388 g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
3392 * GHFunc to emit a thread start event
3393 * @param key A thread id
3394 * @param value A thread object
3395 * @param user_data Don't care
3398 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3400 if (GPOINTER_TO_INT (key) != debugger_thread_id)
3401 process_profiler_event (EVENT_KIND_THREAD_START, value);
3405 * GFunc to emit an assembly load event
3406 * @param value A loaded assembly
3407 * @param user_data Don't care
3410 emit_assembly_load (gpointer value, gpointer user_data)
3412 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3416 * GFunc to emit a type load event
3417 * @param value A loaded type
3418 * @param user_data Don't care
3421 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3423 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3427 strdup_tolower (char *s)
3432 for (p = s2; *p; ++p)
3438 * Same as g_path_get_basename () but handles windows paths as well,
3439 * which can occur in .mdb files created by pdb2mdb.
3442 dbg_path_get_basename (const char *filename)
3446 if (!filename || strchr (filename, '/') || !strchr (filename, '\\'))
3447 return g_path_get_basename (filename);
3451 /* No separator -> filename */
3452 r = strrchr (filename, '\\');
3454 return g_strdup (filename);
3456 /* Trailing slash, remove component */
3458 char *copy = g_strdup (filename);
3459 copy [r-filename] = 0;
3460 r = strrchr (copy, '\\');
3464 return g_strdup ("/");
3466 r = g_strdup (&r[1]);
3471 return g_strdup (&r[1]);
3475 init_jit_info_dbg_attrs (MonoJitInfo *ji)
3477 static MonoClass *hidden_klass, *step_through_klass, *non_user_klass;
3478 MonoCustomAttrInfo *ainfo;
3480 if (ji->dbg_attrs_inited)
3483 if (!hidden_klass) {
3484 hidden_klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3485 g_assert (hidden_klass);
3487 if (!step_through_klass) {
3488 step_through_klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3489 g_assert (step_through_klass);
3491 if (!non_user_klass) {
3492 non_user_klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute");
3493 g_assert (non_user_klass);
3496 ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji));
3498 if (mono_custom_attrs_has_attr (ainfo, hidden_klass))
3499 ji->dbg_hidden = TRUE;
3500 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3501 ji->dbg_step_through = TRUE;
3502 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3503 ji->dbg_non_user_code = TRUE;
3504 mono_custom_attrs_free (ainfo);
3507 ainfo = mono_custom_attrs_from_class (jinfo_get_method (ji)->klass);
3509 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3510 ji->dbg_step_through = TRUE;
3511 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3512 ji->dbg_non_user_code = TRUE;
3513 mono_custom_attrs_free (ainfo);
3516 mono_memory_barrier ();
3517 ji->dbg_attrs_inited = TRUE;
3525 * create_event_list:
3527 * Return a list of event request ids matching EVENT, starting from REQS, which
3528 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3530 * We return request ids, instead of requests, to simplify threading, since
3531 * requests could be deleted anytime when the loader lock is not held.
3532 * LOCKING: Assumes the loader lock is held.
3535 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3538 GSList *events = NULL;
3540 *suspend_policy = SUSPEND_POLICY_NONE;
3543 reqs = event_requests;
3548 for (i = 0; i < reqs->len; ++i) {
3549 EventRequest *req = g_ptr_array_index (reqs, i);
3550 if (req->event_kind == event) {
3551 gboolean filtered = FALSE;
3554 for (j = 0; j < req->nmodifiers; ++j) {
3555 Modifier *mod = &req->modifiers [j];
3557 if (mod->kind == MOD_KIND_COUNT) {
3559 if (mod->data.count > 0) {
3560 if (mod->data.count > 0) {
3562 if (mod->data.count == 0)
3566 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3567 if (mod->data.thread != mono_thread_internal_current ())
3569 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3570 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3572 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3574 if (ei->caught && !mod->caught)
3576 if (!ei->caught && !mod->uncaught)
3578 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3580 gboolean found = FALSE;
3581 MonoAssembly **assemblies = mod->data.assemblies;
3584 for (k = 0; assemblies [k]; ++k)
3585 if (assemblies [k] == jinfo_get_method (ji)->klass->image->assembly)
3590 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3591 gpointer iter = NULL;
3593 MonoDebugSourceInfo *sinfo;
3594 char *source_file, *s;
3595 gboolean found = FALSE;
3597 GPtrArray *source_file_list;
3599 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3600 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3603 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
3604 for (i = 0; i < source_file_list->len; ++i) {
3605 sinfo = g_ptr_array_index (source_file_list, i);
3607 * Do a case-insesitive match by converting the file name to
3610 s = strdup_tolower (sinfo->source_file);
3611 if (g_hash_table_lookup (mod->data.source_files, s))
3614 char *s2 = dbg_path_get_basename (sinfo->source_file);
3615 char *s3 = strdup_tolower (s2);
3617 if (g_hash_table_lookup (mod->data.source_files, s3))
3624 g_ptr_array_free (source_file_list, TRUE);
3629 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3632 s = mono_type_full_name (&ei->klass->byval_arg);
3633 if (!g_hash_table_lookup (mod->data.type_names, s))
3636 } else if (mod->kind == MOD_KIND_STEP) {
3637 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3638 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3639 !strcmp (jinfo_get_method (ji)->name, ".cctor") &&
3640 (jinfo_get_method (ji) != ((SingleStepReq*)req->info)->start_method))
3642 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3643 init_jit_info_dbg_attrs (ji);
3647 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3648 init_jit_info_dbg_attrs (ji);
3649 if (ji->dbg_step_through)
3652 if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3653 init_jit_info_dbg_attrs (ji);
3654 if (ji->dbg_non_user_code)
3661 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3662 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3667 /* Send a VM START/DEATH event by default */
3668 if (event == EVENT_KIND_VM_START)
3669 events = g_slist_append (events, GINT_TO_POINTER (0));
3670 if (event == EVENT_KIND_VM_DEATH)
3671 events = g_slist_append (events, GINT_TO_POINTER (0));
3676 static G_GNUC_UNUSED const char*
3677 event_to_string (EventKind event)
3680 case EVENT_KIND_VM_START: return "VM_START";
3681 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3682 case EVENT_KIND_THREAD_START: return "THREAD_START";
3683 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3684 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3685 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3686 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3687 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3688 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3689 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3690 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3691 case EVENT_KIND_STEP: return "STEP";
3692 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3693 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3694 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3695 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3696 case EVENT_KIND_USER_LOG: return "USER_LOG";
3698 g_assert_not_reached ();
3706 * Send an event to the client, suspending the vm if needed.
3707 * LOCKING: Since this can suspend the calling thread, no locks should be held
3709 * The EVENTS list is freed by this function.
3712 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3716 MonoDomain *domain = mono_domain_get ();
3717 MonoThread *thread = NULL;
3718 MonoObject *keepalive_obj = NULL;
3719 gboolean send_success = FALSE;
3724 DEBUG_PRINTF (2, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event));
3728 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3729 // FIXME: We miss those events
3730 DEBUG_PRINTF (2, "VM start event not sent yet: dropping %s\n", event_to_string (event));
3734 if (vm_death_event_sent) {
3735 DEBUG_PRINTF (2, "VM death event has been sent: dropping %s\n", event_to_string (event));
3739 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3740 DEBUG_PRINTF (2, "Mono runtime is shutting down: dropping %s\n", event_to_string (event));
3745 DEBUG_PRINTF (2, "Debugger client is not connected: dropping %s\n", event_to_string (event));
3749 if (event == EVENT_KIND_KEEPALIVE)
3750 suspend_policy = SUSPEND_POLICY_NONE;
3755 if (agent_config.defer) {
3756 /* Make sure the thread id is always set when doing deferred debugging */
3757 if (debugger_thread_id == GetCurrentThreadId ()) {
3758 /* Don't suspend on events from the debugger thread */
3759 suspend_policy = SUSPEND_POLICY_NONE;
3760 thread = mono_thread_get_main ();
3762 else thread = mono_thread_current ();
3764 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3765 // FIXME: Send these with a NULL thread, don't suspend the current thread
3770 nevents = g_slist_length (events);
3771 buffer_init (&buf, 128);
3772 buffer_add_byte (&buf, suspend_policy);
3773 buffer_add_int (&buf, nevents);
3775 for (l = events; l; l = l->next) {
3776 buffer_add_byte (&buf, event); // event kind
3777 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3782 thread = mono_thread_current ();
3784 if (event == EVENT_KIND_VM_START && arg != NULL)
3787 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3790 case EVENT_KIND_THREAD_START:
3791 case EVENT_KIND_THREAD_DEATH:
3793 case EVENT_KIND_APPDOMAIN_CREATE:
3794 case EVENT_KIND_APPDOMAIN_UNLOAD:
3795 buffer_add_domainid (&buf, arg);
3797 case EVENT_KIND_METHOD_ENTRY:
3798 case EVENT_KIND_METHOD_EXIT:
3799 buffer_add_methodid (&buf, domain, arg);
3801 case EVENT_KIND_ASSEMBLY_LOAD:
3802 buffer_add_assemblyid (&buf, domain, arg);
3804 case EVENT_KIND_ASSEMBLY_UNLOAD: {
3805 DebuggerTlsData *tls;
3807 /* The domain the assembly belonged to is not equal to the current domain */
3808 tls = mono_native_tls_get_value (debugger_tls_id);
3810 g_assert (tls->domain_unloading);
3812 buffer_add_assemblyid (&buf, tls->domain_unloading, arg);
3815 case EVENT_KIND_TYPE_LOAD:
3816 buffer_add_typeid (&buf, domain, arg);
3818 case EVENT_KIND_BREAKPOINT:
3819 case EVENT_KIND_STEP:
3820 buffer_add_methodid (&buf, domain, arg);
3821 buffer_add_long (&buf, il_offset);
3823 case EVENT_KIND_VM_START:
3824 buffer_add_domainid (&buf, mono_get_root_domain ());
3826 case EVENT_KIND_VM_DEATH:
3827 if (CHECK_PROTOCOL_VERSION (2, 27))
3828 buffer_add_int (&buf, mono_environment_exitcode_get ());
3830 case EVENT_KIND_EXCEPTION: {
3831 EventInfo *ei = arg;
3832 buffer_add_objid (&buf, ei->exc);
3834 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3835 * later after the suspension. (#12494).
3837 keepalive_obj = ei->exc;
3840 case EVENT_KIND_USER_BREAK:
3842 case EVENT_KIND_USER_LOG: {
3843 EventInfo *ei = arg;
3844 buffer_add_int (&buf, ei->level);
3845 buffer_add_string (&buf, ei->category ? ei->category : "");
3846 buffer_add_string (&buf, ei->message ? ei->message : "");
3849 case EVENT_KIND_KEEPALIVE:
3850 suspend_policy = SUSPEND_POLICY_NONE;
3853 g_assert_not_reached ();
3857 if (event == EVENT_KIND_VM_START) {
3858 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3859 if (!agent_config.defer)
3860 start_debugger_thread ();
3863 if (event == EVENT_KIND_VM_DEATH) {
3864 vm_death_event_sent = TRUE;
3865 suspend_policy = SUSPEND_POLICY_NONE;
3868 if (mono_runtime_is_shutting_down ())
3869 suspend_policy = SUSPEND_POLICY_NONE;
3871 if (suspend_policy != SUSPEND_POLICY_NONE) {
3873 * Save the thread context and start suspending before sending the packet,
3874 * since we could be receiving the resume request before send_packet ()
3877 save_thread_context (ctx);
3881 /* This will keep this object alive */
3882 get_objref (keepalive_obj);
3885 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3889 g_slist_free (events);
3892 if (!send_success) {
3893 DEBUG_PRINTF (2, "Sending command %s failed.\n", event_to_string (event));
3897 if (event == EVENT_KIND_VM_START) {
3898 vm_start_event_sent = TRUE;
3901 DEBUG_PRINTF (1, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer)GetCurrentThreadId (), nevents, event_to_string (event), ecount, suspend_policy);
3903 switch (suspend_policy) {
3904 case SUSPEND_POLICY_NONE:
3906 case SUSPEND_POLICY_ALL:
3909 case SUSPEND_POLICY_EVENT_THREAD:
3913 g_assert_not_reached ();
3918 process_profiler_event (EventKind event, gpointer arg)
3922 EventInfo ei, *ei_arg = NULL;
3924 if (event == EVENT_KIND_TYPE_LOAD) {
3929 mono_loader_lock ();
3930 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3931 mono_loader_unlock ();
3933 process_event (event, arg, 0, NULL, events, suspend_policy);
3937 runtime_initialized (MonoProfiler *prof)
3939 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3940 if (agent_config.defer)
3941 start_debugger_thread ();
3945 runtime_shutdown (MonoProfiler *prof)
3947 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3949 mono_debugger_agent_cleanup ();
3953 thread_startup (MonoProfiler *prof, uintptr_t tid)
3955 MonoInternalThread *thread = mono_thread_internal_current ();
3956 MonoInternalThread *old_thread;
3957 DebuggerTlsData *tls;
3959 if (tid == debugger_thread_id)
3962 g_assert (thread->tid == tid);
3964 mono_loader_lock ();
3965 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3966 mono_loader_unlock ();
3968 if (thread == old_thread) {
3970 * For some reason, thread_startup () might be called for the same thread
3971 * multiple times (attach ?).
3973 DEBUG_PRINTF (1, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid);
3977 * thread_end () might not be called for some threads, and the tid could
3980 DEBUG_PRINTF (1, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid);
3981 mono_loader_lock ();
3982 mono_g_hash_table_remove (thread_to_tls, old_thread);
3983 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3984 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3985 mono_loader_unlock ();
3989 tls = mono_native_tls_get_value (debugger_tls_id);
3991 // FIXME: Free this somewhere
3992 tls = g_new0 (DebuggerTlsData, 1);
3993 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3994 tls->thread = thread;
3995 mono_native_tls_set_value (debugger_tls_id, tls);
3997 DEBUG_PRINTF (1, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3999 mono_loader_lock ();
4000 mono_g_hash_table_insert (thread_to_tls, thread, tls);
4001 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
4002 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
4003 mono_loader_unlock ();
4005 process_profiler_event (EVENT_KIND_THREAD_START, thread);
4008 * suspend_vm () could have missed this thread, so wait for a resume.
4014 thread_end (MonoProfiler *prof, uintptr_t tid)
4016 MonoInternalThread *thread;
4017 DebuggerTlsData *tls = NULL;
4019 mono_loader_lock ();
4020 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
4022 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
4023 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4025 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
4026 tls->terminated = TRUE;
4027 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
4028 MONO_GC_UNREGISTER_ROOT (tls->thread);
4032 mono_loader_unlock ();
4034 /* We might be called for threads started before we registered the start callback */
4036 DEBUG_PRINTF (1, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
4038 if (GetCurrentThreadId () == tid && !mono_native_tls_get_value (debugger_tls_id)) {
4040 * This can happen on darwin since we deregister threads using pthread dtors.
4041 * process_profiler_event () and the code it calls cannot handle a null TLS value.
4046 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
4051 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
4053 mono_loader_lock ();
4054 g_hash_table_insert (domains, domain, domain);
4055 mono_loader_unlock ();
4057 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
4061 appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain)
4063 DebuggerTlsData *tls;
4065 /* This might be called during shutdown on the debugger thread from the CMD_VM_EXIT code */
4066 if (is_debugger_thread ())
4070 * Remember the currently unloading appdomain as it is needed to generate
4071 * proper ids for unloading assemblies.
4073 tls = mono_native_tls_get_value (debugger_tls_id);
4075 tls->domain_unloading = domain;
4079 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
4081 DebuggerTlsData *tls;
4083 if (is_debugger_thread ())
4086 tls = mono_native_tls_get_value (debugger_tls_id);
4088 tls->domain_unloading = NULL;
4090 clear_breakpoints_for_domain (domain);
4092 mono_loader_lock ();
4093 /* Invalidate each thread's frame stack */
4094 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
4095 mono_loader_unlock ();
4097 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
4101 * invalidate_each_thread:
4103 * A GHFunc to invalidate frames.
4104 * value must be a DebuggerTlsData*
4107 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
4109 invalidate_frames (value);
4113 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
4115 /* Sent later in jit_end () */
4117 g_ptr_array_add (pending_assembly_loads, assembly);
4122 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
4124 if (is_debugger_thread ())
4127 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
4129 clear_event_requests_for_assembly (assembly);
4130 clear_types_for_assembly (assembly);
4134 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
4136 #if defined(HOST_WIN32) && !defined(__GNUC__)
4137 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
4139 gpointer stackptr = __builtin_frame_address (1);
4141 MonoInternalThread *thread = mono_thread_internal_current ();
4142 DebuggerTlsData *tls;
4144 mono_loader_lock ();
4146 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4147 /* Could be the debugger thread with assembly/type load hooks */
4149 tls->invoke_addr = stackptr;
4151 mono_loader_unlock ();
4155 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
4158 #if defined(HOST_WIN32) && !defined(__GNUC__)
4159 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
4161 gpointer stackptr = __builtin_frame_address (1);
4164 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
4168 * We need to stop single stepping when exiting a runtime invoke, since if it is
4169 * a step out, it may return to native code, and thus never end.
4171 mono_loader_lock ();
4172 ss_invoke_addr = NULL;
4174 for (i = 0; i < event_requests->len; ++i) {
4175 EventRequest *req = g_ptr_array_index (event_requests, i);
4177 if (req->event_kind == EVENT_KIND_STEP) {
4178 ss_destroy (req->info);
4179 g_ptr_array_remove_index_fast (event_requests, i);
4184 mono_loader_unlock ();
4188 send_type_load (MonoClass *klass)
4190 gboolean type_load = FALSE;
4191 MonoDomain *domain = mono_domain_get ();
4192 AgentDomainInfo *info = NULL;
4194 mono_loader_lock ();
4195 mono_domain_lock (domain);
4197 info = get_agent_domain_info (domain);
4199 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
4201 g_hash_table_insert (info->loaded_classes, klass, klass);
4204 mono_domain_unlock (domain);
4205 mono_loader_unlock ();
4207 emit_type_load (klass, klass, NULL);
4211 * Emit load events for all types currently loaded in the domain.
4212 * Takes the loader and domain locks.
4213 * user_data is unused.
4216 send_types_for_domain (MonoDomain *domain, void *user_data)
4218 AgentDomainInfo *info = NULL;
4220 mono_loader_lock ();
4221 mono_domain_lock (domain);
4222 info = get_agent_domain_info (domain);
4224 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4225 mono_domain_unlock (domain);
4226 mono_loader_unlock ();
4230 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
4233 * We emit type load events when the first method of the type is JITted,
4234 * since the class load profiler callbacks might be called with the
4235 * loader lock held. They could also occur in the debugger thread.
4236 * Same for assembly load events.
4239 MonoAssembly *assembly = NULL;
4241 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4243 if (pending_assembly_loads->len > 0) {
4244 assembly = g_ptr_array_index (pending_assembly_loads, 0);
4245 g_ptr_array_remove_index (pending_assembly_loads, 0);
4250 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4256 send_type_load (method->klass);
4259 add_pending_breakpoints (method, jinfo);
4263 * BREAKPOINTS/SINGLE STEPPING
4267 * Contains information about an inserted breakpoint.
4270 long il_offset, native_offset;
4274 } BreakpointInstance;
4277 * Contains generic information about a breakpoint.
4281 * The method where the breakpoint is placed. Can be NULL in which case it
4282 * is inserted into every method. This is used to implement method entry/
4283 * exit events. Can be a generic method definition, in which case the
4284 * breakpoint is inserted into every instance.
4290 * A list of BreakpointInstance structures describing where the breakpoint
4291 * was inserted. There could be more than one because of
4292 * generics/appdomains/method entry/exit.
4294 GPtrArray *children;
4297 /* List of breakpoints */
4298 static GPtrArray *breakpoints;
4299 /* Maps breakpoint locations to the number of breakpoints at that location */
4300 static GHashTable *bp_locs;
4303 breakpoints_init (void)
4305 breakpoints = g_ptr_array_new ();
4306 bp_locs = g_hash_table_new (NULL, NULL);
4310 * insert_breakpoint:
4312 * Insert the breakpoint described by BP into the method described by
4316 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4319 BreakpointInstance *inst;
4320 SeqPointIterator it;
4321 gboolean it_has_sp = FALSE;
4324 mono_error_init (error);
4326 seq_point_iterator_init (&it, seq_points);
4327 while (seq_point_iterator_next (&it)) {
4328 if (it.seq_point.il_offset == bp->il_offset) {
4336 * The set of IL offsets with seq points doesn't completely match the
4337 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4339 seq_point_iterator_init (&it, seq_points);
4340 while (seq_point_iterator_next (&it)) {
4341 if (it.seq_point.il_offset != METHOD_ENTRY_IL_OFFSET &&
4342 it.seq_point.il_offset != METHOD_EXIT_IL_OFFSET &&
4343 it.seq_point.il_offset + 1 == bp->il_offset) {
4351 char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d", mono_method_full_name (jinfo_get_method (ji), TRUE), bp->il_offset);
4353 seq_point_iterator_init (&it, seq_points);
4354 while (seq_point_iterator_next (&it))
4355 DEBUG_PRINTF (1, "%d\n", it.seq_point.il_offset);
4358 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4359 g_warning ("%s", s);
4363 g_warning ("%s", s);
4369 inst = g_new0 (BreakpointInstance, 1);
4370 inst->il_offset = it.seq_point.il_offset;
4371 inst->native_offset = it.seq_point.native_offset;
4372 inst->ip = (guint8*)ji->code_start + it.seq_point.native_offset;
4374 inst->domain = domain;
4376 mono_loader_lock ();
4378 g_ptr_array_add (bp->children, inst);
4380 mono_loader_unlock ();
4383 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4384 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4387 if (it.seq_point.native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4388 DEBUG_PRINTF (1, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset);
4389 } else if (count == 0) {
4390 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4391 mono_arch_set_breakpoint (ji, inst->ip);
4397 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);
4401 remove_breakpoint (BreakpointInstance *inst)
4403 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4405 MonoJitInfo *ji = inst->ji;
4406 guint8 *ip = inst->ip;
4409 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4410 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4413 g_assert (count > 0);
4415 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4416 mono_arch_clear_breakpoint (ji, ip);
4417 DEBUG_PRINTF (1, "[dbg] Clear breakpoint at %s [%p].\n", mono_method_full_name (jinfo_get_method (ji), TRUE), ip);
4424 static inline gboolean
4425 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4431 if (method == bp->method)
4433 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4436 if (bp->method->is_inflated && method->is_inflated) {
4437 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4438 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4440 /* Open generic methods should match closed generic methods of the same class */
4441 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4442 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4443 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4445 /* FIXME: Handle !mvar */
4446 if (t1->type != MONO_TYPE_MVAR)
4457 * add_pending_breakpoints:
4459 * Insert pending breakpoints into the newly JITted method METHOD.
4462 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4465 MonoSeqPointInfo *seq_points;
4467 MonoMethod *jmethod;
4472 domain = mono_domain_get ();
4474 mono_loader_lock ();
4476 for (i = 0; i < breakpoints->len; ++i) {
4477 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4478 gboolean found = FALSE;
4480 if (!bp_matches_method (bp, method))
4483 for (j = 0; j < bp->children->len; ++j) {
4484 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4491 jmethod = jinfo_get_method (ji);
4492 mono_domain_lock (domain);
4493 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, jmethod);
4494 if (!seq_points && jmethod->is_inflated)
4495 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (jmethod));
4496 mono_domain_unlock (domain);
4498 /* Could be AOT code */
4500 g_assert (seq_points);
4502 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4506 mono_loader_unlock ();
4510 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4516 mono_error_init (error);
4518 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4520 /* Might be AOTed code */
4521 code = mono_aot_get_method (domain, method);
4523 ji = mono_jit_info_table_find (domain, code);
4528 insert_breakpoint (seq_points, domain, ji, bp, error);
4532 clear_breakpoint (MonoBreakpoint *bp);
4537 * Set a breakpoint at IL_OFFSET in METHOD.
4538 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4539 * METHOD can also be a generic method definition, in which case a breakpoint
4540 * is placed in all instances of the method.
4541 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4544 static MonoBreakpoint*
4545 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4548 GHashTableIter iter, iter2;
4551 MonoSeqPointInfo *seq_points;
4554 mono_error_init (error);
4557 // - suspend/resume the vm to prevent code patching problems
4558 // - multiple breakpoints on the same location
4559 // - dynamic methods
4562 bp = g_new0 (MonoBreakpoint, 1);
4563 bp->method = method;
4564 bp->il_offset = il_offset;
4566 bp->children = g_ptr_array_new ();
4568 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);
4570 mono_loader_lock ();
4572 g_hash_table_iter_init (&iter, domains);
4573 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4574 mono_domain_lock (domain);
4576 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4577 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4578 if (bp_matches_method (bp, m))
4579 set_bp_in_method (domain, m, seq_points, bp, error);
4582 mono_domain_unlock (domain);
4585 mono_loader_unlock ();
4587 mono_loader_lock ();
4588 g_ptr_array_add (breakpoints, bp);
4589 mono_loader_unlock ();
4591 if (error && !mono_error_ok (error)) {
4592 clear_breakpoint (bp);
4600 clear_breakpoint (MonoBreakpoint *bp)
4604 // FIXME: locking, races
4605 for (i = 0; i < bp->children->len; ++i) {
4606 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4608 remove_breakpoint (inst);
4613 mono_loader_lock ();
4614 g_ptr_array_remove (breakpoints, bp);
4615 mono_loader_unlock ();
4617 g_ptr_array_free (bp->children, TRUE);
4622 breakpoints_cleanup (void)
4626 mono_loader_lock ();
4628 while (i < event_requests->len) {
4629 EventRequest *req = g_ptr_array_index (event_requests, i);
4631 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4632 clear_breakpoint (req->info);
4633 g_ptr_array_remove_index_fast (event_requests, i);
4640 for (i = 0; i < breakpoints->len; ++i)
4641 g_free (g_ptr_array_index (breakpoints, i));
4643 g_ptr_array_free (breakpoints, TRUE);
4644 g_hash_table_destroy (bp_locs);
4649 mono_loader_unlock ();
4653 * clear_breakpoints_for_domain:
4655 * Clear breakpoint instances which reference DOMAIN.
4658 clear_breakpoints_for_domain (MonoDomain *domain)
4662 /* This could be called after shutdown */
4666 mono_loader_lock ();
4667 for (i = 0; i < breakpoints->len; ++i) {
4668 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4671 while (j < bp->children->len) {
4672 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4674 if (inst->domain == domain) {
4675 remove_breakpoint (inst);
4679 g_ptr_array_remove_index_fast (bp->children, j);
4685 mono_loader_unlock ();
4691 * Return FALSE if single stepping needs to continue.
4694 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp, DebuggerTlsData *tls, MonoContext *ctx)
4696 MonoDebugMethodInfo *minfo;
4697 MonoDebugSourceLocation *loc = NULL;
4698 gboolean hit = TRUE;
4701 if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK)) {
4703 * These seq points are inserted by the JIT after calls, step over needs to skip them.
4705 DEBUG_PRINTF (1, "[%p] Seq point at nonempty stack %x while stepping over, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset);
4709 if (req->depth == STEP_DEPTH_OVER && hit) {
4710 if (!tls->context.valid)
4711 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4712 compute_frame_info (tls->thread, tls);
4713 if (req->nframes && tls->frame_count && tls->frame_count > req->nframes) {
4714 /* Hit the breakpoint in a recursive call */
4715 DEBUG_PRINTF (1, "[%p] Breakpoint at lower frame while stepping over, continuing single stepping.\n", (gpointer)GetCurrentThreadId ());
4720 if (req->depth == STEP_DEPTH_INTO && req->size == STEP_SIZE_MIN && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) && ss_req->start_method){
4721 method = jinfo_get_method (ji);
4722 if (!tls->context.valid)
4723 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4724 compute_frame_info (tls->thread, tls);
4725 if (ss_req->start_method == method && req->nframes && tls->frame_count == req->nframes) {//Check also frame count(could be recursion)
4726 DEBUG_PRINTF (1, "[%p] Seq point at nonempty stack %x while stepping in, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset);
4731 if (req->size != STEP_SIZE_LINE)
4734 /* Have to check whenever a different source line was reached */
4735 method = jinfo_get_method (ji);
4736 minfo = mono_debug_lookup_method (method);
4739 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4742 DEBUG_PRINTF (1, "[%p] No line number info for il offset %x, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset);
4743 ss_req->last_method = method;
4745 } else if (loc && method == ss_req->last_method && loc->row == ss_req->last_line) {
4746 DEBUG_PRINTF (1, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer)GetCurrentThreadId (), loc->row);
4751 ss_req->last_method = method;
4752 ss_req->last_line = loc->row;
4753 mono_debug_free_source_location (loc);
4760 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4762 return bp->method && bp->method->klass->image->assembly == assembly;
4766 process_breakpoint_inner (DebuggerTlsData *tls, gboolean from_signal)
4770 int i, j, suspend_policy;
4771 guint32 native_offset;
4773 BreakpointInstance *inst;
4774 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4775 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4776 EventKind kind = EVENT_KIND_BREAKPOINT;
4777 MonoContext *ctx = &tls->restore_state.ctx;
4779 MonoSeqPointInfo *info;
4783 // FIXME: Speed this up
4785 ip = MONO_CONTEXT_GET_IP (ctx);
4786 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4788 method = jinfo_get_method (ji);
4790 /* Compute the native offset of the breakpoint from the ip */
4791 native_offset = ip - (guint8*)ji->code_start;
4794 * Skip the instruction causing the breakpoint signal.
4797 mono_arch_skip_breakpoint (ctx, ji);
4799 if (method->wrapper_type || tls->disable_breakpoints)
4802 bp_reqs = g_ptr_array_new ();
4803 ss_reqs = g_ptr_array_new ();
4804 ss_reqs_orig = g_ptr_array_new ();
4806 mono_loader_lock ();
4809 * The ip points to the instruction causing the breakpoint event, which is after
4810 * the offset recorded in the seq point map, so find the prev seq point before ip.
4812 found_sp = find_prev_seq_point_for_native_offset (mono_domain_get (), method, native_offset, &info, &sp);
4815 no_seq_points_found (method);
4817 g_assert (found_sp);
4819 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);
4822 for (i = 0; i < breakpoints->len; ++i) {
4823 bp = g_ptr_array_index (breakpoints, i);
4828 for (j = 0; j < bp->children->len; ++j) {
4829 inst = g_ptr_array_index (bp->children, j);
4830 if (inst->ji == ji && inst->il_offset == sp.il_offset && inst->native_offset == sp.native_offset) {
4831 if (bp->req->event_kind == EVENT_KIND_STEP) {
4832 g_ptr_array_add (ss_reqs_orig, bp->req);
4834 g_ptr_array_add (bp_reqs, bp->req);
4839 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4840 /* Maybe a method entry/exit event */
4841 if (sp.il_offset == METHOD_ENTRY_IL_OFFSET)
4842 kind = EVENT_KIND_METHOD_ENTRY;
4843 else if (sp.il_offset == METHOD_EXIT_IL_OFFSET)
4844 kind = EVENT_KIND_METHOD_EXIT;
4847 /* Process single step requests */
4848 for (i = 0; i < ss_reqs_orig->len; ++i) {
4849 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4850 SingleStepReq *ss_req = req->info;
4853 if (mono_thread_internal_current () != ss_req->thread)
4856 hit = ss_update (ss_req, ji, &sp, tls, ctx);
4858 g_ptr_array_add (ss_reqs, req);
4860 /* Start single stepping again from the current sequence point */
4861 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
4864 if (ss_reqs->len > 0)
4865 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4866 if (bp_reqs->len > 0)
4867 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4868 if (kind != EVENT_KIND_BREAKPOINT)
4869 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4871 mono_loader_unlock ();
4873 g_ptr_array_free (bp_reqs, TRUE);
4874 g_ptr_array_free (ss_reqs, TRUE);
4877 * FIXME: The first event will suspend, so the second will only be sent after the
4881 process_event (EVENT_KIND_STEP, method, 0, ctx, ss_events, suspend_policy);
4883 process_event (kind, method, 0, ctx, bp_events, suspend_policy);
4884 if (enter_leave_events)
4885 process_event (kind, method, 0, ctx, enter_leave_events, suspend_policy);
4888 /* Process a breakpoint/single step event after resuming from a signal handler */
4890 process_signal_event (void (*func) (DebuggerTlsData*, gboolean))
4892 DebuggerTlsData *tls;
4893 MonoThreadUnwindState orig_restore_state;
4896 tls = mono_native_tls_get_value (debugger_tls_id);
4897 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4898 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4899 mono_thread_state_init_from_monoctx (&tls->restore_state, &tls->handler_ctx);
4903 /* This is called when resuming from a signal handler, so it shouldn't return */
4904 memcpy (&ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4905 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4906 mono_restore_context (&ctx);
4907 g_assert_not_reached ();
4911 process_breakpoint (void)
4913 process_signal_event (process_breakpoint_inner);
4917 resume_from_signal_handler (void *sigctx, void *func)
4919 DebuggerTlsData *tls;
4922 /* Save the original context in TLS */
4923 // FIXME: This might not work on an altstack ?
4924 tls = mono_native_tls_get_value (debugger_tls_id);
4926 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer)GetCurrentThreadId ());
4929 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4930 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4931 // clob:c could be added to op_seq_point.
4933 mono_sigctx_to_monoctx (sigctx, &ctx);
4934 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4935 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4936 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4938 MONO_CONTEXT_SET_IP (&ctx, func);
4940 mono_monoctx_to_sigctx (&ctx, sigctx);
4942 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4943 mono_ppc_set_func_into_sigctx (sigctx, func);
4948 mono_debugger_agent_breakpoint_hit (void *sigctx)
4951 * We are called from a signal handler, and running code there causes all kinds of
4952 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4953 * So set up the signal context to return to the real breakpoint handler function.
4955 resume_from_signal_handler (sigctx, process_breakpoint);
4959 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4961 if (frame->managed) {
4962 *(MonoContext*)data = *ctx;
4971 * Called by System.Diagnostics.Debugger:Break ().
4974 mono_debugger_agent_user_break (void)
4976 if (agent_config.enabled) {
4981 /* Obtain a context */
4982 MONO_CONTEXT_SET_IP (&ctx, NULL);
4983 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4984 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4986 mono_loader_lock ();
4987 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4988 mono_loader_unlock ();
4990 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4997 ss_depth_to_string (StepDepth depth)
5000 case STEP_DEPTH_OVER:
5002 case STEP_DEPTH_OUT:
5004 case STEP_DEPTH_INTO:
5007 g_assert_not_reached ();
5013 process_single_step_inner (DebuggerTlsData *tls, gboolean from_signal)
5018 int il_offset, suspend_policy;
5021 MonoContext *ctx = &tls->restore_state.ctx;
5024 MonoSeqPointInfo *info;
5026 ip = MONO_CONTEXT_GET_IP (ctx);
5028 /* Skip the instruction causing the single step */
5030 mono_arch_skip_single_step (ctx);
5032 if (suspend_count > 0) {
5033 process_suspend (tls, ctx);
5038 // FIXME: A suspend race
5041 if (mono_thread_internal_current () != ss_req->thread)
5044 if (log_level > 0) {
5045 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
5047 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);
5050 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
5052 method = jinfo_get_method (ji);
5055 if (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
5060 * Stopping in memset makes half-initialized vtypes visible.
5061 * Stopping in memcpy makes half-copied vtypes visible.
5063 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
5067 * The ip points to the instruction causing the single step event, which is before
5068 * the offset recorded in the seq point map, so find the next seq point after ip.
5070 if (!find_next_seq_point_for_native_offset (domain, method, (guint8*)ip - (guint8*)ji->code_start, &info, &sp))
5073 il_offset = sp.il_offset;
5075 if (!ss_update (ss_req, ji, &sp, tls, ctx))
5078 /* Start single stepping again from the current sequence point */
5079 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
5081 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
5082 (method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
5083 !strcmp (method->name, ".cctor"))
5086 // FIXME: Has to lock earlier
5088 reqs = g_ptr_array_new ();
5090 mono_loader_lock ();
5092 g_ptr_array_add (reqs, ss_req->req);
5094 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
5096 g_ptr_array_free (reqs, TRUE);
5098 mono_loader_unlock ();
5100 process_event (EVENT_KIND_STEP, jinfo_get_method (ji), il_offset, ctx, events, suspend_policy);
5104 process_single_step (void)
5106 process_signal_event (process_single_step_inner);
5110 * mono_debugger_agent_single_step_event:
5112 * Called from a signal handler to handle a single step event.
5115 mono_debugger_agent_single_step_event (void *sigctx)
5117 /* Resume to process_single_step through the signal context */
5119 // FIXME: Since step out/over is implemented using step in, the step in case should
5120 // be as fast as possible. Move the relevant code from process_single_step_inner ()
5123 if (GetCurrentThreadId () == debugger_thread_id) {
5125 * This could happen despite our best effors when the runtime calls
5126 * assembly/type resolve hooks.
5127 * FIXME: Breakpoints too.
5131 mono_sigctx_to_monoctx (sigctx, &ctx);
5132 mono_arch_skip_single_step (&ctx);
5133 mono_monoctx_to_sigctx (&ctx, sigctx);
5137 resume_from_signal_handler (sigctx, process_single_step);
5141 debugger_agent_single_step_from_context (MonoContext *ctx)
5143 DebuggerTlsData *tls;
5144 MonoThreadUnwindState orig_restore_state;
5146 tls = mono_native_tls_get_value (debugger_tls_id);
5149 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
5150 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5151 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5153 process_single_step_inner (tls, FALSE);
5155 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5156 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5160 debugger_agent_breakpoint_from_context (MonoContext *ctx)
5162 DebuggerTlsData *tls;
5163 MonoThreadUnwindState orig_restore_state;
5165 tls = mono_native_tls_get_value (debugger_tls_id);
5167 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoContext));
5168 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5170 process_breakpoint_inner (tls, FALSE);
5172 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5173 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5177 * start_single_stepping:
5179 * Turn on single stepping. Can be called multiple times, for example,
5180 * by a single step event request + a suspend.
5183 start_single_stepping (void)
5185 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5186 int val = InterlockedIncrement (&ss_count);
5189 mono_arch_start_single_stepping ();
5191 if (ss_req != NULL && ss_invoke_addr == NULL) {
5192 DebuggerTlsData *tls;
5194 mono_loader_lock ();
5196 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
5197 ss_invoke_addr = tls->invoke_addr;
5199 mono_loader_unlock ();
5202 g_assert_not_reached ();
5207 stop_single_stepping (void)
5209 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5210 int val = InterlockedDecrement (&ss_count);
5213 mono_arch_stop_single_stepping ();
5215 ss_invoke_addr = NULL;
5217 g_assert_not_reached ();
5224 * Stop the single stepping operation given by SS_REQ.
5227 ss_stop (SingleStepReq *ss_req)
5232 for (l = ss_req->bps; l; l = l->next) {
5233 clear_breakpoint (l->data);
5235 g_slist_free (ss_req->bps);
5239 if (ss_req->global) {
5240 stop_single_stepping ();
5241 ss_req->global = FALSE;
5248 * Start the single stepping operation given by SS_REQ from the sequence point SP.
5249 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
5250 * belong to the same thread as CTX.
5251 * If FRAMES is not-null, use that instead of tls->frames for placing breakpoints etc.
5254 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint* sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls,
5255 gboolean step_to_catch, StackFrame **frames, int nframes)
5257 int i, j, frame_index;
5258 SeqPoint *next_sp, *parent_sp = NULL;
5259 SeqPoint local_sp, local_parent_sp;
5262 MonoSeqPointInfo *parent_info;
5263 MonoMethod *parent_sp_method = NULL;
5264 gboolean enable_global = FALSE;
5266 /* Stop the previous operation */
5270 * Implement single stepping using breakpoints if possible.
5272 if (step_to_catch) {
5273 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
5274 ss_req->bps = g_slist_append (ss_req->bps, bp);
5278 if (ctx && !frames) {
5279 /* Need parent frames */
5280 if (!tls->context.valid)
5281 mono_thread_state_init_from_monoctx (&tls->context, ctx);
5282 compute_frame_info (tls->thread, tls);
5283 frames = tls->frames;
5284 nframes = tls->frame_count;
5288 * Find the first sequence point in the current or in a previous frame which
5289 * is not the last in its method.
5291 if (ss_req->depth == STEP_DEPTH_OUT) {
5292 /* Ignore seq points in current method */
5293 while (frame_index < nframes) {
5294 StackFrame *frame = frames [frame_index];
5296 method = frame->method;
5297 found_sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5298 sp = (found_sp)? &local_sp : NULL;
5300 if (sp && sp->next_len != 0)
5303 // There could be method calls before the next seq point in the caller when using nested calls
5304 //enable_global = TRUE;
5306 if (sp && sp->next_len == 0) {
5308 while (frame_index < nframes) {
5309 StackFrame *frame = frames [frame_index];
5311 method = frame->method;
5312 found_sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5313 sp = (found_sp)? &local_sp : NULL;
5314 if (sp && sp->next_len != 0)
5320 /* Have to put a breakpoint into a parent frame since the seq points might not cover all control flow out of the method */
5321 while (frame_index < nframes) {
5322 StackFrame *frame = frames [frame_index];
5324 parent_sp_method = frame->method;
5325 found_sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &parent_info, &local_parent_sp);
5326 parent_sp = found_sp ? &local_parent_sp : NULL;
5327 if (found_sp && parent_sp->next_len != 0)
5335 if (sp && sp->next_len > 0) {
5336 SeqPoint* next = g_new(SeqPoint, sp->next_len);
5338 seq_point_init_next (info, *sp, next);
5339 for (i = 0; i < sp->next_len; i++) {
5342 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
5343 ss_req->bps = g_slist_append (ss_req->bps, bp);
5349 SeqPoint* next = g_new(SeqPoint, parent_sp->next_len);
5351 seq_point_init_next (parent_info, *parent_sp, next);
5352 for (i = 0; i < parent_sp->next_len; i++) {
5355 bp = set_breakpoint (parent_sp_method, next_sp->il_offset, ss_req->req, NULL);
5356 ss_req->bps = g_slist_append (ss_req->bps, bp);
5361 if (ss_req->nframes == 0)
5362 ss_req->nframes = nframes;
5364 if ((ss_req->depth == STEP_DEPTH_OVER) && (!sp && !parent_sp)) {
5365 DEBUG_PRINTF (1, "[dbg] No parent frame for step over, transition to step into.\n");
5367 * This is needed since if we leave managed code, and later return to it, step over
5368 * is not going to stop.
5369 * This approach is a bit ugly, since we change the step depth, but it only affects
5370 * clients who reuse the same step request, and only in this special case.
5372 ss_req->depth = STEP_DEPTH_INTO;
5375 if (ss_req->depth == STEP_DEPTH_OVER) {
5376 /* Need to stop in catch clauses as well */
5377 for (i = 0; i < nframes; ++i) {
5378 StackFrame *frame = frames [i];
5381 MonoJitInfo *jinfo = frame->ji;
5382 for (j = 0; j < jinfo->num_clauses; ++j) {
5383 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5385 found_sp = find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL, &local_sp);
5386 sp = (found_sp)? &local_sp : NULL;
5388 bp = set_breakpoint (frame->method, sp->il_offset, ss_req->req, NULL);
5389 ss_req->bps = g_slist_append (ss_req->bps, bp);
5396 if (ss_req->depth == STEP_DEPTH_INTO) {
5397 /* Enable global stepping so we stop at method entry too */
5398 enable_global = TRUE;
5402 * The ctx/frame info computed above will become invalid when we continue.
5404 tls->context.valid = FALSE;
5405 tls->async_state.valid = FALSE;
5406 invalidate_frames (tls);
5409 if (enable_global) {
5410 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5411 ss_req->global = TRUE;
5412 start_single_stepping ();
5413 } else if (!ss_req->bps) {
5414 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5415 ss_req->global = TRUE;
5416 start_single_stepping ();
5418 ss_req->global = FALSE;
5423 * Start single stepping of thread THREAD
5426 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req)
5428 DebuggerTlsData *tls;
5429 MonoSeqPointInfo *info = NULL;
5430 SeqPoint *sp = NULL;
5433 MonoMethod *method = NULL;
5434 MonoDebugMethodInfo *minfo;
5435 gboolean step_to_catch = FALSE;
5436 gboolean set_ip = FALSE;
5437 StackFrame **frames = NULL;
5440 if (suspend_count == 0)
5441 return ERR_NOT_SUSPENDED;
5443 wait_for_suspend ();
5445 // FIXME: Multiple requests
5447 DEBUG_PRINTF (0, "Received a single step request while the previous one was still active.\n");
5448 return ERR_NOT_IMPLEMENTED;
5451 DEBUG_PRINTF (1, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth));
5453 ss_req = g_new0 (SingleStepReq, 1);
5455 ss_req->thread = thread;
5456 ss_req->size = size;
5457 ss_req->depth = depth;
5458 ss_req->filter = filter;
5461 mono_loader_lock ();
5462 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5463 mono_loader_unlock ();
5465 g_assert (tls->context.valid);
5467 if (tls->restore_state.valid && MONO_CONTEXT_GET_IP (&tls->context.ctx) != MONO_CONTEXT_GET_IP (&tls->restore_state.ctx)) {
5469 * Need to start single stepping from restore_state and not from the current state
5472 frames = compute_frame_info_from (thread, tls, &tls->restore_state, &nframes);
5475 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5477 if (tls->catch_state.valid) {
5479 StackFrameInfo frame;
5480 MonoContext new_ctx;
5481 MonoLMF *lmf = NULL;
5484 * We are stopped at a throw site. Stepping should go to the catch site.
5487 /* Find the the jit info for the catch context */
5488 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);
5490 g_assert (frame.type == FRAME_TYPE_MANAGED);
5493 * Find the seq point corresponding to the landing site ip, which is the first seq
5496 found_sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info, &local_sp);
5497 sp = (found_sp)? &local_sp : NULL;
5499 no_seq_points_found (frame.method);
5502 method = frame.method;
5504 step_to_catch = TRUE;
5505 /* This make sure the seq point is not skipped by process_single_step () */
5506 ss_req->last_sp = NULL;
5509 if (!step_to_catch) {
5510 StackFrame *frame = NULL;
5513 if (frames && nframes)
5516 compute_frame_info (thread, tls);
5518 if (tls->frame_count)
5519 frame = tls->frames [0];
5522 if (ss_req->size == STEP_SIZE_LINE) {
5524 ss_req->last_method = frame->method;
5525 ss_req->last_line = -1;
5527 minfo = mono_debug_lookup_method (frame->method);
5528 if (minfo && frame->il_offset != -1) {
5529 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
5532 ss_req->last_line = loc->row;
5540 if (!method && frame->il_offset != -1) {
5541 /* FIXME: Sort the table and use a binary search */
5542 found_sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5543 sp = (found_sp)? &local_sp : NULL;
5545 no_seq_points_found (frame->method);
5547 method = frame->method;
5552 ss_req->start_method = method;
5554 ss_start (ss_req, method, sp, info, set_ip ? &tls->restore_state.ctx : &tls->context.ctx, tls, step_to_catch, frames, nframes);
5557 free_frames (frames, nframes);
5563 ss_destroy (SingleStepReq *req)
5566 g_assert (ss_req == req);
5575 ss_clear_for_assembly (SingleStepReq *req, MonoAssembly *assembly)
5578 gboolean found = TRUE;
5582 for (l = ss_req->bps; l; l = l->next) {
5583 if (breakpoint_matches_assembly (l->data, assembly)) {
5584 clear_breakpoint (l->data);
5585 ss_req->bps = g_slist_delete_link (ss_req->bps, l);
5594 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5597 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5603 if (!agent_config.enabled)
5606 mono_loader_lock ();
5607 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5608 mono_loader_unlock ();
5611 ei.category = category ? mono_string_to_utf8 (category) : NULL;
5612 ei.message = message ? mono_string_to_utf8 (message) : NULL;
5614 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5616 g_free (ei.category);
5617 g_free (ei.message);
5621 mono_debugger_agent_debug_log_is_enabled (void)
5623 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5624 return agent_config.enabled;
5627 #if defined(PLATFORM_ANDROID) || defined(TARGET_ANDROID)
5629 mono_debugger_agent_unhandled_exception (MonoException *exc)
5638 memset (&ei, 0, sizeof (EventInfo));
5639 ei.exc = (MonoObject*)exc;
5641 mono_loader_lock ();
5642 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5643 mono_loader_unlock ();
5645 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5650 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5651 MonoContext *catch_ctx)
5653 int i, j, suspend_policy;
5655 MonoJitInfo *ji, *catch_ji;
5657 DebuggerTlsData *tls = NULL;
5659 if (thread_to_tls != NULL) {
5660 MonoInternalThread *thread = mono_thread_internal_current ();
5662 mono_loader_lock ();
5663 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5664 mono_loader_unlock ();
5666 if (tls && tls->abort_requested)
5668 if (tls && tls->disable_breakpoints)
5672 memset (&ei, 0, sizeof (EventInfo));
5674 /* Just-In-Time debugging */
5676 if (agent_config.onuncaught && !inited) {
5677 finish_agent_init (FALSE);
5680 * Send an unsolicited EXCEPTION event with a dummy request id.
5682 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5683 ei.exc = (MonoObject*)exc;
5684 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5687 } else if (agent_config.onthrow && !inited) {
5689 gboolean found = FALSE;
5691 for (l = agent_config.onthrow; l; l = l->next) {
5692 char *ex_type = l->data;
5693 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5695 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5702 finish_agent_init (FALSE);
5705 * Send an unsolicited EXCEPTION event with a dummy request id.
5707 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5708 ei.exc = (MonoObject*)exc;
5709 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5717 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5719 catch_ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5723 ei.exc = (MonoObject*)exc;
5724 ei.caught = catch_ctx != NULL;
5726 mono_loader_lock ();
5728 /* Treat exceptions which are caught in non-user code as unhandled */
5729 for (i = 0; i < event_requests->len; ++i) {
5730 EventRequest *req = g_ptr_array_index (event_requests, i);
5731 if (req->event_kind != EVENT_KIND_EXCEPTION)
5734 for (j = 0; j < req->nmodifiers; ++j) {
5735 Modifier *mod = &req->modifiers [j];
5737 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5739 gboolean found = FALSE;
5740 MonoAssembly **assemblies = mod->data.assemblies;
5743 for (k = 0; assemblies [k]; ++k)
5744 if (assemblies [k] == jinfo_get_method (catch_ji)->klass->image->assembly)
5753 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5754 mono_loader_unlock ();
5756 if (tls && ei.caught && catch_ctx) {
5757 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5758 tls->catch_state.ctx = *catch_ctx;
5759 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5760 tls->catch_state.valid = TRUE;
5763 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5766 tls->catch_state.valid = FALSE;
5770 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5772 DebuggerTlsData *tls;
5777 tls = mono_native_tls_get_value (debugger_tls_id);
5782 * We're about to invoke an exception filter during the first pass of exception handling.
5784 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5785 * 'orig_ctx' is the context where the exception has been thrown.
5788 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5790 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5791 * the call site (line 37) and then continue to Main(), but it would never
5792 * include the throw site (line 32).
5794 * Since exception filters are invoked during the first pass of exception handling,
5795 * the stack frames of the throw site are still intact, so we should include them
5798 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5800 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5801 * but report the location of the 'throw' to the user.
5805 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5809 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5811 DebuggerTlsData *tls;
5816 tls = mono_native_tls_get_value (debugger_tls_id);
5820 tls->filter_state.valid = FALSE;
5824 * buffer_add_value_full:
5826 * Add the encoding of the value at ADDR described by T to the buffer.
5827 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5831 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5832 gboolean as_vtype, GHashTable *parent_vtypes)
5835 gboolean boxed_vtype = FALSE;
5838 if (!(*(void**)addr)) {
5839 /* This can happen with compiler generated locals */
5840 //printf ("%s\n", mono_type_full_name (t));
5841 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5844 g_assert (*(void**)addr);
5845 addr = *(void**)addr;
5850 case MONO_TYPE_BOOLEAN:
5853 case MONO_TYPE_CHAR:
5873 case MONO_TYPE_VOID:
5874 buffer_add_byte (buf, t->type);
5876 case MONO_TYPE_BOOLEAN:
5879 buffer_add_byte (buf, t->type);
5880 buffer_add_int (buf, *(gint8*)addr);
5882 case MONO_TYPE_CHAR:
5885 buffer_add_byte (buf, t->type);
5886 buffer_add_int (buf, *(gint16*)addr);
5891 buffer_add_byte (buf, t->type);
5892 buffer_add_int (buf, *(gint32*)addr);
5897 buffer_add_byte (buf, t->type);
5898 buffer_add_long (buf, *(gint64*)addr);
5902 /* Treat it as a vtype */
5904 case MONO_TYPE_PTR: {
5905 gssize val = *(gssize*)addr;
5907 buffer_add_byte (buf, t->type);
5908 buffer_add_long (buf, val);
5912 case MONO_TYPE_STRING:
5913 case MONO_TYPE_SZARRAY:
5914 case MONO_TYPE_OBJECT:
5915 case MONO_TYPE_CLASS:
5916 case MONO_TYPE_ARRAY:
5917 obj = *(MonoObject**)addr;
5920 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5922 if (obj->vtable->klass->valuetype) {
5923 t = &obj->vtable->klass->byval_arg;
5924 addr = mono_object_unbox (obj);
5927 } else if (obj->vtable->klass->rank) {
5928 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5929 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5930 buffer_add_byte (buf, MONO_TYPE_CLASS);
5932 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5934 buffer_add_objid (buf, obj);
5938 case MONO_TYPE_VALUETYPE:
5939 case MONO_TYPE_TYPEDBYREF: {
5943 MonoClass *klass = mono_class_from_mono_type (t);
5948 * Handle boxed vtypes recursively referencing themselves using fields.
5951 parent_vtypes = g_hash_table_new (NULL, NULL);
5952 vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
5954 if (CHECK_PROTOCOL_VERSION (2, 33)) {
5955 buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
5956 buffer_add_int (buf, vtype_index - 1);
5958 /* The client can't handle PARENT_VTYPE */
5959 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5963 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
5967 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5968 buffer_add_byte (buf, klass->enumtype);
5969 buffer_add_typeid (buf, domain, klass);
5973 while ((f = mono_class_get_fields (klass, &iter))) {
5974 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5976 if (mono_field_is_deleted (f))
5980 buffer_add_int (buf, nfields);
5983 while ((f = mono_class_get_fields (klass, &iter))) {
5984 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5986 if (mono_field_is_deleted (f))
5988 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE, parent_vtypes);
5992 g_hash_table_remove (parent_vtypes, addr);
5993 if (g_hash_table_size (parent_vtypes) == 0) {
5994 g_hash_table_destroy (parent_vtypes);
5995 parent_vtypes = NULL;
6000 case MONO_TYPE_GENERICINST:
6001 if (mono_type_generic_inst_is_valuetype (t)) {
6013 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
6015 buffer_add_value_full (buf, t, addr, domain, FALSE, NULL);
6019 obj_is_of_type (MonoObject *obj, MonoType *t)
6021 MonoClass *klass = obj->vtable->klass;
6022 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
6023 if (mono_class_is_transparent_proxy (klass)) {
6024 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
6025 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
6035 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
6038 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6044 gpointer iter = NULL;
6048 is_enum = decode_byte (buf, &buf, limit);
6049 /* Enums are sent as a normal vtype */
6051 return ERR_NOT_IMPLEMENTED;
6052 klass = decode_typeid (buf, &buf, limit, &d, &err);
6056 if (t && klass != mono_class_from_mono_type (t)) {
6057 char *name = mono_type_full_name (t);
6058 char *name2 = mono_type_full_name (&klass->byval_arg);
6059 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got %s.\n", (gpointer)GetCurrentThreadId (), name, name2);
6062 return ERR_INVALID_ARGUMENT;
6065 nfields = decode_int (buf, &buf, limit);
6066 while ((f = mono_class_get_fields (klass, &iter))) {
6067 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6069 if (mono_field_is_deleted (f))
6071 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
6076 g_assert (nfields == 0);
6084 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6088 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
6089 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
6090 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
6091 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
6092 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
6093 char *name = mono_type_full_name (t);
6094 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type);
6096 return ERR_INVALID_ARGUMENT;
6100 case MONO_TYPE_BOOLEAN:
6101 *(guint8*)addr = decode_int (buf, &buf, limit);
6103 case MONO_TYPE_CHAR:
6104 *(gunichar2*)addr = decode_int (buf, &buf, limit);
6107 *(gint8*)addr = decode_int (buf, &buf, limit);
6110 *(guint8*)addr = decode_int (buf, &buf, limit);
6113 *(gint16*)addr = decode_int (buf, &buf, limit);
6116 *(guint16*)addr = decode_int (buf, &buf, limit);
6119 *(gint32*)addr = decode_int (buf, &buf, limit);
6122 *(guint32*)addr = decode_int (buf, &buf, limit);
6125 *(gint64*)addr = decode_long (buf, &buf, limit);
6128 *(guint64*)addr = decode_long (buf, &buf, limit);
6131 *(guint32*)addr = decode_int (buf, &buf, limit);
6134 *(guint64*)addr = decode_long (buf, &buf, limit);
6137 /* We send these as I8, so we get them back as such */
6138 g_assert (type == MONO_TYPE_I8);
6139 *(gssize*)addr = decode_long (buf, &buf, limit);
6141 case MONO_TYPE_GENERICINST:
6142 if (MONO_TYPE_ISSTRUCT (t)) {
6143 /* The client sends these as a valuetype */
6151 /* We send these as vtypes, so we get them back as such */
6152 g_assert (type == MONO_TYPE_VALUETYPE);
6155 case MONO_TYPE_VALUETYPE:
6156 err = decode_vtype (t, domain, addr,buf, &buf, limit);
6162 if (MONO_TYPE_IS_REFERENCE (t)) {
6163 if (type == MONO_TYPE_OBJECT) {
6164 int objid = decode_objid (buf, &buf, limit);
6168 err = get_object (objid, (MonoObject**)&obj);
6173 if (!obj_is_of_type (obj, t)) {
6174 DEBUG_PRINTF (1, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6175 return ERR_INVALID_ARGUMENT;
6178 if (obj && obj->vtable->domain != domain)
6179 return ERR_INVALID_ARGUMENT;
6181 mono_gc_wbarrier_generic_store (addr, obj);
6182 } else if (type == VALUE_TYPE_ID_NULL) {
6183 *(MonoObject**)addr = NULL;
6184 } else if (type == MONO_TYPE_VALUETYPE) {
6192 /* This can happen when round-tripping boxed vtypes */
6194 * Obtain vtype class.
6195 * Same as the beginning of the handle_vtype case above.
6198 is_enum = decode_byte (buf, &buf, limit);
6200 return ERR_NOT_IMPLEMENTED;
6201 klass = decode_typeid (buf, &buf, limit, &d, &err);
6205 /* Decode the vtype into a temporary buffer, then box it. */
6206 vtype_buf_size = mono_class_value_size (klass, NULL);
6207 vtype_buf = g_malloc0 (vtype_buf_size);
6208 g_assert (vtype_buf);
6211 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
6216 *(MonoObject**)addr = mono_value_box (d, klass, vtype_buf);
6219 char *name = mono_type_full_name (t);
6220 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type);
6222 return ERR_INVALID_ARGUMENT;
6236 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6239 int type = decode_byte (buf, &buf, limit);
6241 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
6242 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
6243 guint8 *nullable_buf;
6246 * First try decoding it as a Nullable`1
6248 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6253 * Then try decoding as a primitive value or null.
6255 if (targ->type == type) {
6256 nullable_buf = g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
6257 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
6259 g_free (nullable_buf);
6262 mono_nullable_init (addr, mono_value_box (domain, mono_class_from_mono_type (targ), nullable_buf), mono_class_from_mono_type (t));
6263 g_free (nullable_buf);
6266 } else if (type == VALUE_TYPE_ID_NULL) {
6267 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
6273 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6277 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
6281 guint8 *addr, *gaddr;
6284 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6285 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6288 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
6289 reg_val = mono_arch_context_get_int_reg (ctx, reg);
6291 buffer_add_value_full (buf, t, ®_val, domain, as_vtype, NULL);
6293 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6294 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6295 addr += (gint32)var->offset;
6297 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6299 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6301 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6304 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6305 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
6306 /* Same as regoffset, but with an indirection */
6307 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6308 addr += (gint32)var->offset;
6310 gaddr = *(gpointer*)addr;
6312 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL);
6314 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
6315 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
6316 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
6317 MonoGSharedVtMethodRuntimeInfo *info;
6323 g_assert (info_var);
6324 g_assert (locals_var);
6326 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6327 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6328 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6329 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6330 addr += (gint32)info_var->offset;
6331 info = *(gpointer*)addr;
6332 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6333 info = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6335 g_assert_not_reached ();
6339 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6340 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6341 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6342 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6343 addr += (gint32)locals_var->offset;
6344 locals = *(gpointer*)addr;
6345 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6346 locals = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6348 g_assert_not_reached ();
6352 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6354 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6359 g_assert_not_reached ();
6364 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
6368 guint8 *addr, *gaddr;
6370 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6371 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6373 if (MONO_TYPE_IS_REFERENCE (t))
6374 size = sizeof (gpointer);
6376 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6379 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6380 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6382 gboolean is_signed = FALSE;
6385 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6388 // FIXME: Write barriers
6389 mono_gc_memmove_atomic (addr, val, size);
6394 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6399 v = is_signed ? *(gint8*)val : *(guint8*)val;
6402 v = is_signed ? *(gint16*)val : *(guint16*)val;
6405 v = is_signed ? *(gint32*)val : *(guint32*)val;
6408 v = is_signed ? *(gint64*)val : *(guint64*)val;
6411 g_assert_not_reached ();
6414 /* Set value on the stack or in the return ctx */
6415 if (reg_locations [reg]) {
6416 /* Saved on the stack */
6417 DEBUG_PRINTF (1, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v);
6418 *(reg_locations [reg]) = v;
6421 DEBUG_PRINTF (1, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v);
6422 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6425 // FIXME: Move these to mono-context.h/c.
6426 mono_arch_context_set_int_reg (ctx, reg, v);
6428 // FIXME: Can't set registers, so we disable linears
6433 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6434 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6435 addr += (gint32)var->offset;
6437 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6440 addr = *(guint8**)addr;
6446 // FIXME: Write barriers
6447 mono_gc_memmove_atomic (addr, val, size);
6449 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6450 /* Same as regoffset, but with an indirection */
6451 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6452 addr += (gint32)var->offset;
6454 gaddr = *(gpointer*)addr;
6456 // FIXME: Write barriers
6457 mono_gc_memmove_atomic (gaddr, val, size);
6459 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6463 g_assert_not_reached ();
6468 clear_event_request (int req_id, int etype)
6472 mono_loader_lock ();
6473 for (i = 0; i < event_requests->len; ++i) {
6474 EventRequest *req = g_ptr_array_index (event_requests, i);
6476 if (req->id == req_id && req->event_kind == etype) {
6477 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6478 clear_breakpoint (req->info);
6479 if (req->event_kind == EVENT_KIND_STEP)
6480 ss_destroy (req->info);
6481 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6482 clear_breakpoint (req->info);
6483 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6484 clear_breakpoint (req->info);
6485 g_ptr_array_remove_index_fast (event_requests, i);
6490 mono_loader_unlock ();
6494 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
6498 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6499 m->kind = MOD_KIND_NONE;
6500 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6501 int count = 0, match_count = 0, pos;
6502 MonoAssembly **newassemblies;
6504 for (i = 0; m->data.assemblies [i]; ++i) {
6506 if (m->data.assemblies [i] == assembly)
6511 newassemblies = g_new0 (MonoAssembly*, count - match_count);
6514 for (i = 0; i < count; ++i)
6515 if (m->data.assemblies [i] != assembly)
6516 newassemblies [pos ++] = m->data.assemblies [i];
6517 g_assert (pos == count - match_count);
6518 g_free (m->data.assemblies);
6519 m->data.assemblies = newassemblies;
6525 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
6529 for (i = 0; i < req->nmodifiers; ++i) {
6530 Modifier *m = &req->modifiers [i];
6532 clear_assembly_from_modifier (req, m, assembly);
6537 * clear_event_requests_for_assembly:
6539 * Clear all events requests which reference ASSEMBLY.
6542 clear_event_requests_for_assembly (MonoAssembly *assembly)
6547 mono_loader_lock ();
6551 for (i = 0; i < event_requests->len; ++i) {
6552 EventRequest *req = g_ptr_array_index (event_requests, i);
6554 clear_assembly_from_modifiers (req, assembly);
6556 if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly (req->info, assembly)) {
6557 clear_event_request (req->id, req->event_kind);
6562 if (req->event_kind == EVENT_KIND_STEP)
6563 ss_clear_for_assembly (req->info, assembly);
6566 mono_loader_unlock ();
6570 * type_comes_from_assembly:
6572 * GHRFunc that returns TRUE if klass comes from assembly
6575 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6577 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6581 * clear_types_for_assembly:
6583 * Clears types from loaded_classes for a given assembly
6586 clear_types_for_assembly (MonoAssembly *assembly)
6588 MonoDomain *domain = mono_domain_get ();
6589 AgentDomainInfo *info = NULL;
6591 if (!domain || !domain_jit_info (domain))
6592 /* Can happen during shutdown */
6595 mono_loader_lock ();
6596 info = get_agent_domain_info (domain);
6597 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6598 mono_loader_unlock ();
6602 add_thread (gpointer key, gpointer value, gpointer user_data)
6604 MonoInternalThread *thread = value;
6605 Buffer *buf = user_data;
6607 buffer_add_objid (buf, (MonoObject*)thread);
6611 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6613 guint8 *end = invoke->endp;
6616 MonoMethodSignature *sig;
6619 MonoObject *this, *res, *exc;
6622 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6625 MonoStopwatch watch;
6627 if (invoke->method) {
6629 * Invoke this method directly, currently only Environment.Exit () is supported.
6632 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>");
6633 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
6634 g_assert_not_reached ();
6637 m = decode_methodid (p, &p, end, &domain, &err);
6640 sig = mono_method_signature (m);
6642 if (m->klass->valuetype)
6643 this_buf = g_alloca (mono_class_instance_size (m->klass));
6645 this_buf = g_alloca (sizeof (MonoObject*));
6646 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6647 /* Should be null */
6648 int type = decode_byte (p, &p, end);
6649 if (type != VALUE_TYPE_ID_NULL) {
6650 DEBUG_PRINTF (1, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer)GetCurrentThreadId ());
6651 return ERR_INVALID_ARGUMENT;
6653 memset (this_buf, 0, mono_class_instance_size (m->klass));
6655 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6660 if (!m->klass->valuetype)
6661 this = *(MonoObject**)this_buf;
6665 if (MONO_CLASS_IS_INTERFACE (m->klass)) {
6667 DEBUG_PRINTF (1, "[%p] Error: Interface method invoked without this argument.\n", (gpointer)GetCurrentThreadId ());
6668 return ERR_INVALID_ARGUMENT;
6670 m = mono_object_get_virtual_method (this, m);
6671 } else if ((m->flags & METHOD_ATTRIBUTE_VIRTUAL) && !m->klass->valuetype && invoke->flags & INVOKE_FLAG_VIRTUAL) {
6673 DEBUG_PRINTF (1, "[%p] Error: invoke with INVOKE_FLAG_VIRTUAL flag set without this argument.\n", (gpointer)GetCurrentThreadId ());
6674 return ERR_INVALID_ARGUMENT;
6676 m = mono_object_get_virtual_method (this, m);
6679 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>");
6681 if (this && this->vtable->domain != domain)
6684 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
6685 if (!strcmp (m->name, ".ctor")) {
6686 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
6687 return ERR_INVALID_ARGUMENT;
6689 this = mono_object_new (domain, m->klass);
6691 return ERR_INVALID_ARGUMENT;
6695 if (this && !obj_is_of_type (this, &m->klass->byval_arg))
6696 return ERR_INVALID_ARGUMENT;
6698 nargs = decode_int (p, &p, end);
6699 if (nargs != sig->param_count)
6700 return ERR_INVALID_ARGUMENT;
6701 /* Use alloca to get gc tracking */
6702 arg_buf = g_alloca (nargs * sizeof (gpointer));
6703 memset (arg_buf, 0, nargs * sizeof (gpointer));
6704 args = g_alloca (nargs * sizeof (gpointer));
6705 for (i = 0; i < nargs; ++i) {
6706 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6707 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6710 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6713 if (sig->params [i]->byref) {
6714 arg_buf [i] = g_alloca (sizeof (mgreg_t));
6715 *(gpointer*)arg_buf [i] = args [i];
6716 args [i] = arg_buf [i];
6719 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6720 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6723 args [i] = arg_buf [i];
6730 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6731 tls->disable_breakpoints = TRUE;
6733 tls->disable_breakpoints = FALSE;
6736 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6738 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6739 if (invoke->has_ctx) {
6742 lmf_addr = mono_get_lmf_addr ();
6745 memset (&ext, 0, sizeof (ext));
6746 mono_arch_init_lmf_ext (&ext, *lmf_addr);
6748 ext.debugger_invoke = TRUE;
6749 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6751 mono_set_lmf ((MonoLMF*)&ext);
6755 mono_stopwatch_start (&watch);
6756 if (m->klass->valuetype)
6757 res = mono_runtime_invoke (m, this_buf, args, &exc);
6759 res = mono_runtime_invoke (m, this, args, &exc);
6760 mono_stopwatch_stop (&watch);
6761 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));
6763 buffer_add_byte (buf, 0);
6764 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6766 gboolean out_this = FALSE;
6767 gboolean out_args = FALSE;
6769 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_THIS) && CHECK_PROTOCOL_VERSION (2, 35))
6771 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_ARGS) && CHECK_PROTOCOL_VERSION (2, 35))
6773 buffer_add_byte (buf, 1 + (out_this ? 2 : 0) + (out_args ? 4 : 0));
6774 if (sig->ret->type == MONO_TYPE_VOID) {
6775 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
6776 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
6779 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6780 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6781 buffer_add_value (buf, sig->ret, &res, domain);
6782 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6783 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6784 MonoClass *k = mono_class_from_mono_type (sig->ret);
6785 guint8 *nullable_buf = g_alloca (mono_class_value_size (k, NULL));
6787 g_assert (nullable_buf);
6788 mono_nullable_init (nullable_buf, res, k);
6789 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6792 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6798 /* Return the new value of the receiver after the call */
6799 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
6801 buffer_add_int (buf, nargs);
6802 for (i = 0; i < nargs; ++i) {
6803 if (MONO_TYPE_IS_REFERENCE (sig->params [i]))
6804 buffer_add_value (buf, sig->params [i], &args [i], domain);
6805 else if (sig->params [i]->byref)
6806 /* add_value () does an indirection */
6807 buffer_add_value (buf, sig->params [i], &arg_buf [i], domain);
6809 buffer_add_value (buf, sig->params [i], arg_buf [i], domain);
6814 tls->disable_breakpoints = FALSE;
6816 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6817 if (invoke->has_ctx)
6818 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
6822 // FIXME: byref arguments
6830 * Invoke the method given by tls->pending_invoke in the current thread.
6833 invoke_method (void)
6835 DebuggerTlsData *tls;
6840 MonoContext restore_ctx;
6843 tls = mono_native_tls_get_value (debugger_tls_id);
6847 * Store the `InvokeData *' in `tls->invoke' until we're done with
6848 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6851 mono_loader_lock ();
6853 invoke = tls->pending_invoke;
6855 tls->pending_invoke = NULL;
6857 invoke->last_invoke = tls->invoke;
6858 tls->invoke = invoke;
6860 mono_loader_unlock ();
6862 tls->frames_up_to_date = FALSE;
6868 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6869 buffer_init (&buf, 128);
6872 /* Fail the other invokes as well */
6874 err = do_invoke_method (tls, &buf, invoke, p, &p);
6877 /* Start suspending before sending the reply */
6878 if (mindex == invoke->nmethods - 1) {
6879 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6880 for (i = 0; i < invoke->suspend_count; ++i)
6885 send_reply_packet (id, err, &buf);
6890 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6892 if (invoke->has_ctx)
6893 save_thread_context (&restore_ctx);
6895 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6896 g_assert (tls->resume_count);
6897 tls->resume_count -= invoke->suspend_count;
6900 DEBUG_PRINTF (1, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer)GetCurrentThreadId (), err, tls->resume_count);
6903 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6905 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
6906 * after the mono_runtime_invoke() already returned, but it doesn't matter
6907 * because we reset the abort here.
6910 mono_loader_lock ();
6912 if (tls->abort_requested)
6913 mono_thread_internal_reset_abort (tls->thread);
6915 tls->invoke = tls->invoke->last_invoke;
6916 tls->abort_requested = FALSE;
6918 mono_loader_unlock ();
6927 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6929 MonoThread *thread = value;
6930 DebuggerTlsData *tls;
6933 mono_loader_lock ();
6934 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6936 res = tls->really_suspended;
6937 mono_loader_unlock ();
6943 get_source_files_for_type (MonoClass *klass)
6945 gpointer iter = NULL;
6947 MonoDebugSourceInfo *sinfo;
6951 files = g_ptr_array_new ();
6953 while ((method = mono_class_get_methods (klass, &iter))) {
6954 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6955 GPtrArray *source_file_list;
6958 mono_debug_symfile_get_line_numbers_full (minfo, NULL, &source_file_list, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
6959 for (j = 0; j < source_file_list->len; ++j) {
6960 sinfo = g_ptr_array_index (source_file_list, j);
6961 for (i = 0; i < files->len; ++i)
6962 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6964 if (i == files->len)
6965 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6967 g_ptr_array_free (source_file_list, TRUE);
6975 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6978 case CMD_VM_VERSION: {
6979 char *build_info, *version;
6981 build_info = mono_get_runtime_build_info ();
6982 version = g_strdup_printf ("mono %s", build_info);
6984 buffer_add_string (buf, version); /* vm version */
6985 buffer_add_int (buf, MAJOR_VERSION);
6986 buffer_add_int (buf, MINOR_VERSION);
6987 g_free (build_info);
6991 case CMD_VM_SET_PROTOCOL_VERSION: {
6992 major_version = decode_int (p, &p, end);
6993 minor_version = decode_int (p, &p, end);
6994 protocol_version_set = TRUE;
6995 DEBUG_PRINTF (1, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version);
6998 case CMD_VM_ALL_THREADS: {
7000 mono_loader_lock ();
7001 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
7002 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
7003 mono_loader_unlock ();
7006 case CMD_VM_SUSPEND:
7008 wait_for_suspend ();
7011 if (suspend_count == 0)
7012 return ERR_NOT_SUSPENDED;
7014 clear_suspended_objs ();
7016 case CMD_VM_DISPOSE:
7017 /* Clear all event requests */
7018 mono_loader_lock ();
7019 while (event_requests->len > 0) {
7020 EventRequest *req = g_ptr_array_index (event_requests, 0);
7022 clear_event_request (req->id, req->event_kind);
7024 mono_loader_unlock ();
7026 while (suspend_count > 0)
7028 disconnected = TRUE;
7029 vm_start_event_sent = FALSE;
7032 MonoInternalThread *thread;
7033 DebuggerTlsData *tls;
7034 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7035 MonoClass *env_class;
7037 MonoMethod *exit_method = NULL;
7041 exit_code = decode_int (p, &p, end);
7043 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
7045 /* Have to send a reply before exiting */
7046 send_reply_packet (id, 0, buf);
7048 /* Clear all event requests */
7049 mono_loader_lock ();
7050 while (event_requests->len > 0) {
7051 EventRequest *req = g_ptr_array_index (event_requests, 0);
7053 clear_event_request (req->id, req->event_kind);
7055 mono_loader_unlock ();
7058 * The JDWP documentation says that the shutdown is not orderly. It doesn't
7059 * specify whenever a VM_DEATH event is sent. We currently do an orderly
7060 * shutdown by hijacking a thread to execute Environment.Exit (). This is
7061 * better than doing the shutdown ourselves, since it avoids various races.
7065 wait_for_suspend ();
7067 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7068 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
7070 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
7073 mono_loader_lock ();
7074 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
7075 mono_loader_unlock ();
7077 if (thread && exit_method) {
7078 mono_loader_lock ();
7079 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
7080 mono_loader_unlock ();
7082 args = g_new0 (gpointer, 1);
7083 args [0] = g_malloc (sizeof (int));
7084 *(int*)(args [0]) = exit_code;
7086 tls->pending_invoke = g_new0 (InvokeData, 1);
7087 tls->pending_invoke->method = exit_method;
7088 tls->pending_invoke->args = args;
7089 tls->pending_invoke->nmethods = 1;
7091 while (suspend_count > 0)
7095 * No thread found, do it ourselves.
7096 * FIXME: This can race with normal shutdown etc.
7098 while (suspend_count > 0)
7101 if (!mono_runtime_try_shutdown ())
7104 mono_environment_exitcode_set (exit_code);
7106 /* Suspend all managed threads since the runtime is going away */
7107 DEBUG_PRINTF (1, "Suspending all threads...\n");
7108 mono_thread_suspend_all_other_threads ();
7109 DEBUG_PRINTF (1, "Shutting down the runtime...\n");
7110 mono_runtime_quit ();
7111 transport_close2 ();
7112 DEBUG_PRINTF (1, "Exiting...\n");
7118 case CMD_VM_INVOKE_METHOD:
7119 case CMD_VM_INVOKE_METHODS: {
7120 int objid = decode_objid (p, &p, end);
7122 DebuggerTlsData *tls;
7123 int i, count, err, flags, nmethods;
7125 err = get_object (objid, (MonoObject**)&thread);
7129 flags = decode_int (p, &p, end);
7131 if (command == CMD_VM_INVOKE_METHODS)
7132 nmethods = decode_int (p, &p, end);
7136 // Wait for suspending if it already started
7138 wait_for_suspend ();
7139 if (!is_suspended ())
7140 return ERR_NOT_SUSPENDED;
7142 mono_loader_lock ();
7143 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7144 mono_loader_unlock ();
7147 if (!tls->really_suspended)
7148 /* The thread is still running native code, can't do invokes */
7149 return ERR_NOT_SUSPENDED;
7152 * Store the invoke data into tls, the thread will execute it after it is
7155 if (tls->pending_invoke)
7156 return ERR_NOT_SUSPENDED;
7157 tls->pending_invoke = g_new0 (InvokeData, 1);
7158 tls->pending_invoke->id = id;
7159 tls->pending_invoke->flags = flags;
7160 tls->pending_invoke->p = g_malloc (end - p);
7161 memcpy (tls->pending_invoke->p, p, end - p);
7162 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
7163 tls->pending_invoke->suspend_count = suspend_count;
7164 tls->pending_invoke->nmethods = nmethods;
7166 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
7167 resume_thread (THREAD_TO_INTERNAL (thread));
7170 count = suspend_count;
7171 for (i = 0; i < count; ++i)
7176 case CMD_VM_ABORT_INVOKE: {
7177 int objid = decode_objid (p, &p, end);
7179 DebuggerTlsData *tls;
7182 err = get_object (objid, (MonoObject**)&thread);
7186 invoke_id = decode_int (p, &p, end);
7188 mono_loader_lock ();
7189 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7192 if (tls->abort_requested) {
7193 mono_loader_unlock ();
7198 * Check whether we're still inside the mono_runtime_invoke() and that it's
7199 * actually the correct invocation.
7201 * Careful, we do not stop the thread that's doing the invocation, so we can't
7202 * inspect its stack. However, invoke_method() also acquires the loader lock
7203 * when it's done, so we're safe here.
7207 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
7208 mono_loader_unlock ();
7209 return ERR_NO_INVOCATION;
7212 tls->abort_requested = TRUE;
7214 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
7215 mono_loader_unlock ();
7219 case CMD_VM_SET_KEEPALIVE: {
7220 int timeout = decode_int (p, &p, end);
7221 agent_config.keepalive = timeout;
7223 #ifndef DISABLE_SOCKET_TRANSPORT
7230 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
7231 GHashTableIter iter, kiter;
7236 char *fname, *basename;
7237 gboolean ignore_case;
7238 GSList *class_list, *l;
7239 GPtrArray *res_classes, *res_domains;
7241 fname = decode_string (p, &p, end);
7242 ignore_case = decode_byte (p, &p, end);
7244 basename = dbg_path_get_basename (fname);
7246 res_classes = g_ptr_array_new ();
7247 res_domains = g_ptr_array_new ();
7249 mono_loader_lock ();
7250 g_hash_table_iter_init (&iter, domains);
7251 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7252 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
7254 /* Update 'source_file_to_class' cache */
7255 g_hash_table_iter_init (&kiter, info->loaded_classes);
7256 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
7257 if (!g_hash_table_lookup (info->source_files, klass)) {
7258 files = get_source_files_for_type (klass);
7259 g_hash_table_insert (info->source_files, klass, files);
7261 for (i = 0; i < files->len; ++i) {
7262 char *s = g_ptr_array_index (files, i);
7263 char *s2 = dbg_path_get_basename (s);
7266 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
7268 class_list = g_slist_prepend (class_list, klass);
7269 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
7271 class_list = g_slist_prepend (class_list, klass);
7272 g_hash_table_insert (info->source_file_to_class, s2, class_list);
7275 /* The _ignorecase hash contains the lowercase path */
7276 s3 = strdup_tolower (s2);
7277 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
7279 class_list = g_slist_prepend (class_list, klass);
7280 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
7282 class_list = g_slist_prepend (class_list, klass);
7283 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
7295 s = strdup_tolower (basename);
7296 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
7299 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
7302 for (l = class_list; l; l = l->next) {
7305 g_ptr_array_add (res_classes, klass);
7306 g_ptr_array_add (res_domains, domain);
7309 mono_loader_unlock ();
7314 buffer_add_int (buf, res_classes->len);
7315 for (i = 0; i < res_classes->len; ++i)
7316 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
7317 g_ptr_array_free (res_classes, TRUE);
7318 g_ptr_array_free (res_domains, TRUE);
7321 case CMD_VM_GET_TYPES: {
7322 GHashTableIter iter;
7326 gboolean ignore_case;
7327 GPtrArray *res_classes, *res_domains;
7328 MonoTypeNameParse info;
7330 name = decode_string (p, &p, end);
7331 ignore_case = decode_byte (p, &p, end);
7333 if (!mono_reflection_parse_type (name, &info)) {
7335 mono_reflection_free_type_info (&info);
7336 return ERR_INVALID_ARGUMENT;
7339 res_classes = g_ptr_array_new ();
7340 res_domains = g_ptr_array_new ();
7342 mono_loader_lock ();
7343 g_hash_table_iter_init (&iter, domains);
7344 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7346 gboolean type_resolve;
7350 mono_domain_assemblies_lock (domain);
7351 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7355 type_resolve = TRUE;
7356 t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
7358 g_ptr_array_add (res_classes, mono_type_get_class (t));
7359 g_ptr_array_add (res_domains, domain);
7363 mono_domain_assemblies_unlock (domain);
7365 mono_loader_unlock ();
7368 mono_reflection_free_type_info (&info);
7370 buffer_add_int (buf, res_classes->len);
7371 for (i = 0; i < res_classes->len; ++i)
7372 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
7373 g_ptr_array_free (res_classes, TRUE);
7374 g_ptr_array_free (res_domains, TRUE);
7377 case CMD_VM_START_BUFFERING:
7378 case CMD_VM_STOP_BUFFERING:
7379 /* Handled in the main loop */
7382 return ERR_NOT_IMPLEMENTED;
7389 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7395 case CMD_EVENT_REQUEST_SET: {
7397 int i, event_kind, suspend_policy, nmodifiers, mod;
7400 MonoThread *step_thread;
7401 int size = 0, depth = 0, filter = 0, step_thread_id = 0;
7405 event_kind = decode_byte (p, &p, end);
7406 suspend_policy = decode_byte (p, &p, end);
7407 nmodifiers = decode_byte (p, &p, end);
7409 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7410 req->id = InterlockedIncrement (&event_request_id);
7411 req->event_kind = event_kind;
7412 req->suspend_policy = suspend_policy;
7413 req->nmodifiers = nmodifiers;
7416 for (i = 0; i < nmodifiers; ++i) {
7417 mod = decode_byte (p, &p, end);
7419 req->modifiers [i].kind = mod;
7420 if (mod == MOD_KIND_COUNT) {
7421 req->modifiers [i].data.count = decode_int (p, &p, end);
7422 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7423 method = decode_methodid (p, &p, end, &domain, &err);
7426 location = decode_long (p, &p, end);
7427 } else if (mod == MOD_KIND_STEP) {
7428 step_thread_id = decode_id (p, &p, end);
7429 size = decode_int (p, &p, end);
7430 depth = decode_int (p, &p, end);
7431 if (CHECK_PROTOCOL_VERSION (2, 16))
7432 filter = decode_int (p, &p, end);
7433 req->modifiers [i].data.filter = filter;
7434 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7435 /* Treat STEP_THOUGH the same as HIDDEN */
7436 req->modifiers [i].data.filter |= STEP_FILTER_DEBUGGER_STEP_THROUGH;
7437 } else if (mod == MOD_KIND_THREAD_ONLY) {
7438 int id = decode_id (p, &p, end);
7440 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7445 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7446 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7450 req->modifiers [i].caught = decode_byte (p, &p, end);
7451 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7452 if (CHECK_PROTOCOL_VERSION (2, 25))
7453 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7455 req->modifiers [i].subclasses = TRUE;
7456 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" : "");
7458 req->modifiers [i].data.exc_class = exc_class;
7460 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
7462 return ERR_INVALID_ARGUMENT;
7465 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7466 int n = decode_int (p, &p, end);
7469 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
7470 for (j = 0; j < n; ++j) {
7471 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7473 g_free (req->modifiers [i].data.assemblies);
7477 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7478 int n = decode_int (p, &p, end);
7481 modifier = &req->modifiers [i];
7482 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7483 for (j = 0; j < n; ++j) {
7484 char *s = decode_string (p, &p, end);
7488 s2 = strdup_tolower (s);
7489 g_hash_table_insert (modifier->data.source_files, s2, s2);
7493 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7494 int n = decode_int (p, &p, end);
7497 modifier = &req->modifiers [i];
7498 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7499 for (j = 0; j < n; ++j) {
7500 char *s = decode_string (p, &p, end);
7503 g_hash_table_insert (modifier->data.type_names, s, s);
7507 return ERR_NOT_IMPLEMENTED;
7511 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7514 req->info = set_breakpoint (method, location, req, &error);
7515 if (!mono_error_ok (&error)) {
7517 DEBUG_PRINTF (1, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error));
7518 mono_error_cleanup (&error);
7519 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7521 } else if (req->event_kind == EVENT_KIND_STEP) {
7522 g_assert (step_thread_id);
7524 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7530 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, filter, req);
7535 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7536 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7537 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7538 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7539 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7540 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7542 if (req->nmodifiers) {
7544 return ERR_NOT_IMPLEMENTED;
7548 mono_loader_lock ();
7549 g_ptr_array_add (event_requests, req);
7551 if (agent_config.defer) {
7552 /* Transmit cached data to the client on receipt of the event request */
7553 switch (req->event_kind) {
7554 case EVENT_KIND_APPDOMAIN_CREATE:
7555 /* Emit load events for currently loaded domains */
7556 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7558 case EVENT_KIND_ASSEMBLY_LOAD:
7559 /* Emit load events for currently loaded assemblies */
7560 mono_assembly_foreach (emit_assembly_load, NULL);
7562 case EVENT_KIND_THREAD_START:
7563 /* Emit start events for currently started threads */
7564 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7566 case EVENT_KIND_TYPE_LOAD:
7567 /* Emit type load events for currently loaded types */
7568 mono_domain_foreach (send_types_for_domain, NULL);
7574 mono_loader_unlock ();
7576 buffer_add_int (buf, req->id);
7579 case CMD_EVENT_REQUEST_CLEAR: {
7580 int etype = decode_byte (p, &p, end);
7581 int req_id = decode_int (p, &p, end);
7583 // FIXME: Make a faster mapping from req_id to request
7584 mono_loader_lock ();
7585 clear_event_request (req_id, etype);
7586 mono_loader_unlock ();
7589 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7592 mono_loader_lock ();
7594 while (i < event_requests->len) {
7595 EventRequest *req = g_ptr_array_index (event_requests, i);
7597 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7598 clear_breakpoint (req->info);
7600 g_ptr_array_remove_index_fast (event_requests, i);
7606 mono_loader_unlock ();
7610 return ERR_NOT_IMPLEMENTED;
7617 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7623 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7624 buffer_add_domainid (buf, mono_get_root_domain ());
7627 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7628 domain = decode_domainid (p, &p, end, NULL, &err);
7631 buffer_add_string (buf, domain->friendly_name);
7634 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7639 domain = decode_domainid (p, &p, end, NULL, &err);
7642 mono_loader_lock ();
7644 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7647 buffer_add_int (buf, count);
7648 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7650 buffer_add_assemblyid (buf, domain, ass);
7652 mono_loader_unlock ();
7655 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7656 domain = decode_domainid (p, &p, end, NULL, &err);
7660 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7663 case CMD_APPDOMAIN_GET_CORLIB: {
7664 domain = decode_domainid (p, &p, end, NULL, &err);
7668 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7671 case CMD_APPDOMAIN_CREATE_STRING: {
7675 domain = decode_domainid (p, &p, end, NULL, &err);
7678 s = decode_string (p, &p, end);
7680 o = mono_string_new (domain, s);
7681 buffer_add_objid (buf, (MonoObject*)o);
7684 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7686 MonoDomain *domain2;
7689 domain = decode_domainid (p, &p, end, NULL, &err);
7692 klass = decode_typeid (p, &p, end, &domain2, &err);
7697 g_assert (domain == domain2);
7699 o = mono_object_new (domain, klass);
7701 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
7705 buffer_add_objid (buf, o);
7709 return ERR_NOT_IMPLEMENTED;
7716 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7722 ass = decode_assemblyid (p, &p, end, &domain, &err);
7727 case CMD_ASSEMBLY_GET_LOCATION: {
7728 buffer_add_string (buf, mono_image_get_filename (ass->image));
7731 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7735 if (ass->image->dynamic) {
7736 buffer_add_id (buf, 0);
7738 token = mono_image_get_entry_point (ass->image);
7740 buffer_add_id (buf, 0);
7742 m = mono_get_method (ass->image, token, NULL);
7743 buffer_add_methodid (buf, domain, m);
7748 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7749 buffer_add_moduleid (buf, domain, ass->image);
7752 case CMD_ASSEMBLY_GET_OBJECT: {
7753 MonoObject *o = (MonoObject*)mono_assembly_get_object (domain, ass);
7754 buffer_add_objid (buf, o);
7757 case CMD_ASSEMBLY_GET_TYPE: {
7758 char *s = decode_string (p, &p, end);
7759 gboolean ignorecase = decode_byte (p, &p, end);
7760 MonoTypeNameParse info;
7762 gboolean type_resolve, res;
7763 MonoDomain *d = mono_domain_get ();
7765 /* This is needed to be able to find referenced assemblies */
7766 res = mono_domain_set (domain, FALSE);
7769 if (!mono_reflection_parse_type (s, &info)) {
7772 if (info.assembly.name)
7774 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
7776 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
7777 mono_reflection_free_type_info (&info);
7780 mono_domain_set (d, TRUE);
7784 case CMD_ASSEMBLY_GET_NAME: {
7786 MonoAssembly *mass = ass;
7788 name = g_strdup_printf (
7789 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7791 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7792 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7793 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7794 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7796 buffer_add_string (buf, name);
7801 return ERR_NOT_IMPLEMENTED;
7808 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7814 case CMD_MODULE_GET_INFO: {
7815 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7818 basename = g_path_get_basename (image->name);
7819 buffer_add_string (buf, basename); // name
7820 buffer_add_string (buf, image->module_name); // scopename
7821 buffer_add_string (buf, image->name); // fqname
7822 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7823 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7828 return ERR_NOT_IMPLEMENTED;
7835 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7841 case CMD_FIELD_GET_INFO: {
7842 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
7844 buffer_add_string (buf, f->name);
7845 buffer_add_typeid (buf, domain, f->parent);
7846 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7847 buffer_add_int (buf, f->type->attrs);
7851 return ERR_NOT_IMPLEMENTED;
7858 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7860 if (val && val->vtable->klass == mono_defaults.monotype_class) {
7861 /* Special case these so the client doesn't have to handle Type objects */
7863 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7864 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7865 } else if (MONO_TYPE_IS_REFERENCE (t))
7866 buffer_add_value (buf, t, &val, domain);
7868 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7872 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7878 buffer_add_int (buf, 0);
7882 for (i = 0; i < cinfo->num_attrs; ++i) {
7883 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7886 buffer_add_int (buf, nattrs);
7888 for (i = 0; i < cinfo->num_attrs; ++i) {
7889 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7890 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7891 MonoArray *typed_args, *named_args;
7893 CattrNamedArg *arginfo = NULL;
7896 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
7897 if (!mono_error_ok (&error)) {
7898 DEBUG_PRINTF (2, "[dbg] mono_reflection_create_custom_attr_data_args () failed with: '%s'\n", mono_error_get_message (&error));
7899 mono_error_cleanup (&error);
7900 return ERR_LOADER_ERROR;
7903 buffer_add_methodid (buf, domain, attr->ctor);
7907 buffer_add_int (buf, mono_array_length (typed_args));
7908 for (j = 0; j < mono_array_length (typed_args); ++j) {
7909 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7911 t = mono_method_signature (attr->ctor)->params [j];
7913 buffer_add_cattr_arg (buf, t, domain, val);
7916 buffer_add_int (buf, 0);
7921 buffer_add_int (buf, mono_array_length (named_args));
7923 for (j = 0; j < mono_array_length (named_args); ++j) {
7924 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7926 if (arginfo [j].prop) {
7927 buffer_add_byte (buf, 0x54);
7928 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7929 } else if (arginfo [j].field) {
7930 buffer_add_byte (buf, 0x53);
7931 buffer_add_fieldid (buf, domain, arginfo [j].field);
7933 g_assert_not_reached ();
7936 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7939 buffer_add_int (buf, 0);
7948 /* FIXME: Code duplication with icall.c */
7950 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7955 mono_class_setup_interfaces (klass, error);
7956 if (!mono_error_ok (error))
7959 for (i = 0; i < klass->interface_count; i++) {
7960 ic = klass->interfaces [i];
7961 g_hash_table_insert (ifaces, ic, ic);
7963 collect_interfaces (ic, ifaces, error);
7964 if (!mono_error_ok (error))
7970 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7980 case CMD_TYPE_GET_INFO: {
7981 buffer_add_string (buf, klass->name_space);
7982 buffer_add_string (buf, klass->name);
7984 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7985 buffer_add_string (buf, name);
7987 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7988 buffer_add_moduleid (buf, domain, klass->image);
7989 buffer_add_typeid (buf, domain, klass->parent);
7990 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7991 buffer_add_typeid (buf, domain, klass->element_class);
7993 buffer_add_id (buf, 0);
7994 buffer_add_int (buf, klass->type_token);
7995 buffer_add_byte (buf, klass->rank);
7996 buffer_add_int (buf, klass->flags);
7998 type = &klass->byval_arg;
7999 // FIXME: Can't decide whenever a class represents a byref type
8002 if (type->type == MONO_TYPE_PTR)
8004 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
8006 if (type->type == MONO_TYPE_VALUETYPE)
8008 if (klass->enumtype)
8010 if (klass->generic_container)
8012 if (klass->generic_container || klass->generic_class)
8014 buffer_add_byte (buf, b);
8017 while ((nested = mono_class_get_nested_types (klass, &iter)))
8019 buffer_add_int (buf, nnested);
8021 while ((nested = mono_class_get_nested_types (klass, &iter)))
8022 buffer_add_typeid (buf, domain, nested);
8023 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8024 if (klass->generic_container)
8025 buffer_add_typeid (buf, domain, klass);
8026 else if (klass->generic_class)
8027 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
8029 buffer_add_id (buf, 0);
8031 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8034 if (klass->generic_class) {
8035 MonoGenericInst *inst = klass->generic_class->context.class_inst;
8037 count = inst->type_argc;
8038 buffer_add_int (buf, count);
8039 for (i = 0; i < count; i++)
8040 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8041 } else if (klass->generic_container) {
8042 MonoGenericContainer *container = klass->generic_container;
8045 count = container->type_argc;
8046 buffer_add_int (buf, count);
8047 for (i = 0; i < count; i++) {
8048 pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
8049 buffer_add_typeid (buf, domain, pklass);
8052 buffer_add_int (buf, 0);
8057 case CMD_TYPE_GET_METHODS: {
8060 gpointer iter = NULL;
8063 mono_class_setup_methods (klass);
8065 nmethods = mono_class_num_methods (klass);
8067 buffer_add_int (buf, nmethods);
8069 while ((m = mono_class_get_methods (klass, &iter))) {
8070 buffer_add_methodid (buf, domain, m);
8073 g_assert (i == nmethods);
8076 case CMD_TYPE_GET_FIELDS: {
8079 gpointer iter = NULL;
8082 nfields = mono_class_num_fields (klass);
8084 buffer_add_int (buf, nfields);
8086 while ((f = mono_class_get_fields (klass, &iter))) {
8087 buffer_add_fieldid (buf, domain, f);
8088 buffer_add_string (buf, f->name);
8089 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
8090 buffer_add_int (buf, f->type->attrs);
8093 g_assert (i == nfields);
8096 case CMD_TYPE_GET_PROPERTIES: {
8099 gpointer iter = NULL;
8102 nprops = mono_class_num_properties (klass);
8104 buffer_add_int (buf, nprops);
8106 while ((p = mono_class_get_properties (klass, &iter))) {
8107 buffer_add_propertyid (buf, domain, p);
8108 buffer_add_string (buf, p->name);
8109 buffer_add_methodid (buf, domain, p->get);
8110 buffer_add_methodid (buf, domain, p->set);
8111 buffer_add_int (buf, p->attrs);
8114 g_assert (i == nprops);
8117 case CMD_TYPE_GET_CATTRS: {
8118 MonoClass *attr_klass;
8119 MonoCustomAttrInfo *cinfo;
8121 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8122 /* attr_klass can be NULL */
8126 cinfo = mono_custom_attrs_from_class (klass);
8128 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8133 case CMD_TYPE_GET_FIELD_CATTRS: {
8134 MonoClass *attr_klass;
8135 MonoCustomAttrInfo *cinfo;
8136 MonoClassField *field;
8138 field = decode_fieldid (p, &p, end, NULL, &err);
8141 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8145 cinfo = mono_custom_attrs_from_field (klass, field);
8147 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8152 case CMD_TYPE_GET_PROPERTY_CATTRS: {
8153 MonoClass *attr_klass;
8154 MonoCustomAttrInfo *cinfo;
8157 prop = decode_propertyid (p, &p, end, NULL, &err);
8160 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8164 cinfo = mono_custom_attrs_from_property (klass, prop);
8166 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8171 case CMD_TYPE_GET_VALUES:
8172 case CMD_TYPE_GET_VALUES_2: {
8179 MonoThread *thread_obj;
8180 MonoInternalThread *thread = NULL;
8181 guint32 special_static_type;
8183 if (command == CMD_TYPE_GET_VALUES_2) {
8184 int objid = decode_objid (p, &p, end);
8187 err = get_object (objid, (MonoObject**)&thread_obj);
8191 thread = THREAD_TO_INTERNAL (thread_obj);
8194 len = decode_int (p, &p, end);
8195 for (i = 0; i < len; ++i) {
8196 f = decode_fieldid (p, &p, end, NULL, &err);
8200 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8201 return ERR_INVALID_FIELDID;
8202 special_static_type = mono_class_field_get_special_static_type (f);
8203 if (special_static_type != SPECIAL_STATIC_NONE) {
8204 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
8205 return ERR_INVALID_FIELDID;
8208 /* Check that the field belongs to the object */
8210 for (k = klass; k; k = k->parent) {
8211 if (k == f->parent) {
8217 return ERR_INVALID_FIELDID;
8219 vtable = mono_class_vtable (domain, f->parent);
8220 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8221 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
8222 buffer_add_value (buf, f->type, val, domain);
8227 case CMD_TYPE_SET_VALUES: {
8235 len = decode_int (p, &p, end);
8236 for (i = 0; i < len; ++i) {
8237 f = decode_fieldid (p, &p, end, NULL, &err);
8241 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8242 return ERR_INVALID_FIELDID;
8243 if (mono_class_field_is_special_static (f))
8244 return ERR_INVALID_FIELDID;
8246 /* Check that the field belongs to the object */
8248 for (k = klass; k; k = k->parent) {
8249 if (k == f->parent) {
8255 return ERR_INVALID_FIELDID;
8257 // FIXME: Check for literal/const
8259 vtable = mono_class_vtable (domain, f->parent);
8260 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8261 err = decode_value (f->type, domain, val, p, &p, end);
8266 if (MONO_TYPE_IS_REFERENCE (f->type))
8267 mono_field_static_set_value (vtable, f, *(gpointer*)val);
8269 mono_field_static_set_value (vtable, f, val);
8274 case CMD_TYPE_GET_OBJECT: {
8275 MonoObject *o = (MonoObject*)mono_type_get_object (domain, &klass->byval_arg);
8276 buffer_add_objid (buf, o);
8279 case CMD_TYPE_GET_SOURCE_FILES:
8280 case CMD_TYPE_GET_SOURCE_FILES_2: {
8281 char *source_file, *base;
8285 files = get_source_files_for_type (klass);
8287 buffer_add_int (buf, files->len);
8288 for (i = 0; i < files->len; ++i) {
8289 source_file = g_ptr_array_index (files, i);
8290 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8291 buffer_add_string (buf, source_file);
8293 base = dbg_path_get_basename (source_file);
8294 buffer_add_string (buf, base);
8297 g_free (source_file);
8299 g_ptr_array_free (files, TRUE);
8302 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8303 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8307 if (mono_class_is_assignable_from (klass, oklass))
8308 buffer_add_byte (buf, 1);
8310 buffer_add_byte (buf, 0);
8313 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8314 char *name = decode_string (p, &p, end);
8315 int i, flags = decode_int (p, &p, end);
8316 MonoException *ex = NULL;
8317 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
8320 return ERR_LOADER_ERROR;
8321 buffer_add_int (buf, array->len);
8322 for (i = 0; i < array->len; ++i) {
8323 MonoMethod *method = g_ptr_array_index (array, i);
8324 buffer_add_methodid (buf, domain, method);
8327 g_ptr_array_free (array, TRUE);
8331 case CMD_TYPE_GET_INTERFACES: {
8333 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8335 MonoClass *tclass, *iface;
8336 GHashTableIter iter;
8340 for (parent = tclass; parent; parent = parent->parent) {
8341 mono_class_setup_interfaces (parent, &error);
8342 if (!mono_error_ok (&error))
8343 return ERR_LOADER_ERROR;
8344 collect_interfaces (parent, iface_hash, &error);
8345 if (!mono_error_ok (&error))
8346 return ERR_LOADER_ERROR;
8349 buffer_add_int (buf, g_hash_table_size (iface_hash));
8351 g_hash_table_iter_init (&iter, iface_hash);
8352 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8353 buffer_add_typeid (buf, domain, iface);
8354 g_hash_table_destroy (iface_hash);
8357 case CMD_TYPE_GET_INTERFACE_MAP: {
8358 int tindex, ioffset;
8359 gboolean variance_used;
8361 int len, nmethods, i;
8365 len = decode_int (p, &p, end);
8366 mono_class_setup_vtable (klass);
8368 for (tindex = 0; tindex < len; ++tindex) {
8369 iclass = decode_typeid (p, &p, end, NULL, &err);
8373 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8375 return ERR_INVALID_ARGUMENT;
8377 nmethods = mono_class_num_methods (iclass);
8378 buffer_add_int (buf, nmethods);
8381 while ((method = mono_class_get_methods (iclass, &iter))) {
8382 buffer_add_methodid (buf, domain, method);
8384 for (i = 0; i < nmethods; ++i)
8385 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
8389 case CMD_TYPE_IS_INITIALIZED: {
8390 MonoVTable *vtable = mono_class_vtable (domain, klass);
8393 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8395 buffer_add_int (buf, 0);
8398 case CMD_TYPE_CREATE_INSTANCE: {
8401 obj = mono_object_new (domain, klass);
8402 buffer_add_objid (buf, obj);
8406 return ERR_NOT_IMPLEMENTED;
8413 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8416 MonoDomain *old_domain;
8420 klass = decode_typeid (p, &p, end, &domain, &err);
8424 old_domain = mono_domain_get ();
8426 mono_domain_set (domain, TRUE);
8428 err = type_commands_internal (command, klass, domain, p, end, buf);
8430 mono_domain_set (old_domain, TRUE);
8436 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8438 MonoMethodHeader *header;
8442 case CMD_METHOD_GET_NAME: {
8443 buffer_add_string (buf, method->name);
8446 case CMD_METHOD_GET_DECLARING_TYPE: {
8447 buffer_add_typeid (buf, domain, method->klass);
8450 case CMD_METHOD_GET_DEBUG_INFO: {
8451 MonoDebugMethodInfo *minfo;
8453 int i, j, n_il_offsets;
8456 int *column_numbers;
8457 int *end_line_numbers;
8458 int *end_column_numbers;
8460 GPtrArray *source_file_list;
8462 header = mono_method_get_header (method);
8464 buffer_add_int (buf, 0);
8465 buffer_add_string (buf, "");
8466 buffer_add_int (buf, 0);
8470 minfo = mono_debug_lookup_method (method);
8472 buffer_add_int (buf, header->code_size);
8473 buffer_add_string (buf, "");
8474 buffer_add_int (buf, 0);
8475 mono_metadata_free_mh (header);
8479 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);
8480 buffer_add_int (buf, header->code_size);
8481 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8482 buffer_add_int (buf, source_file_list->len);
8483 for (i = 0; i < source_file_list->len; ++i) {
8484 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
8485 buffer_add_string (buf, sinfo->source_file);
8486 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8487 for (j = 0; j < 16; ++j)
8488 buffer_add_byte (buf, sinfo->hash [j]);
8492 buffer_add_string (buf, source_file);
8494 buffer_add_int (buf, n_il_offsets);
8495 DEBUG_PRINTF (10, "Line number table for method %s:\n", mono_method_full_name (method, TRUE));
8496 for (i = 0; i < n_il_offsets; ++i) {
8497 const char *srcfile = "";
8499 if (source_files [i] != -1) {
8500 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
8501 srcfile = sinfo->source_file;
8503 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);
8504 buffer_add_int (buf, il_offsets [i]);
8505 buffer_add_int (buf, line_numbers [i]);
8506 if (CHECK_PROTOCOL_VERSION (2, 13))
8507 buffer_add_int (buf, source_files [i]);
8508 if (CHECK_PROTOCOL_VERSION (2, 19))
8509 buffer_add_int (buf, column_numbers ? column_numbers [i] : -1);
8510 if (CHECK_PROTOCOL_VERSION (2, 32)) {
8511 buffer_add_int (buf, end_line_numbers ? end_line_numbers [i] : -1);
8512 buffer_add_int (buf, end_column_numbers ? end_column_numbers [i] : -1);
8515 g_free (source_file);
8516 g_free (il_offsets);
8517 g_free (line_numbers);
8518 g_free (column_numbers);
8519 g_free (end_line_numbers);
8520 g_free (end_column_numbers);
8521 g_free (source_files);
8522 g_ptr_array_free (source_file_list, TRUE);
8523 mono_metadata_free_mh (header);
8526 case CMD_METHOD_GET_PARAM_INFO: {
8527 MonoMethodSignature *sig = mono_method_signature (method);
8531 /* FIXME: mono_class_from_mono_type () and byrefs */
8533 /* FIXME: Use a smaller encoding */
8534 buffer_add_int (buf, sig->call_convention);
8535 buffer_add_int (buf, sig->param_count);
8536 buffer_add_int (buf, sig->generic_param_count);
8537 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
8538 for (i = 0; i < sig->param_count; ++i) {
8540 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
8543 /* Emit parameter names */
8544 names = g_new (char *, sig->param_count);
8545 mono_method_get_param_names (method, (const char **) names);
8546 for (i = 0; i < sig->param_count; ++i)
8547 buffer_add_string (buf, names [i]);
8552 case CMD_METHOD_GET_LOCALS_INFO: {
8553 int i, j, num_locals;
8554 MonoDebugLocalsInfo *locals;
8556 header = mono_method_get_header (method);
8558 return ERR_INVALID_ARGUMENT;
8560 buffer_add_int (buf, header->num_locals);
8563 for (i = 0; i < header->num_locals; ++i)
8564 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
8567 locals = mono_debug_lookup_locals (method);
8569 num_locals = locals->num_locals;
8572 for (i = 0; i < header->num_locals; ++i) {
8573 for (j = 0; j < num_locals; ++j)
8574 if (locals->locals [j].index == i)
8577 buffer_add_string (buf, locals->locals [j].name);
8579 buffer_add_string (buf, "");
8583 for (i = 0; i < header->num_locals; ++i) {
8584 for (j = 0; j < num_locals; ++j)
8585 if (locals->locals [j].index == i)
8587 if (j < num_locals && locals->locals [j].block) {
8588 buffer_add_int (buf, locals->locals [j].block->start_offset);
8589 buffer_add_int (buf, locals->locals [j].block->end_offset);
8591 buffer_add_int (buf, 0);
8592 buffer_add_int (buf, header->code_size);
8595 mono_metadata_free_mh (header);
8598 mono_debug_symfile_free_locals (locals);
8602 case CMD_METHOD_GET_INFO:
8603 buffer_add_int (buf, method->flags);
8604 buffer_add_int (buf, method->iflags);
8605 buffer_add_int (buf, method->token);
8606 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8608 if (method->is_generic)
8610 if (mono_method_signature (method)->generic_param_count)
8612 buffer_add_byte (buf, attrs);
8613 if (method->is_generic || method->is_inflated) {
8616 if (method->is_generic) {
8619 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8621 result = imethod->declaring;
8622 if (imethod->context.class_inst) {
8623 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8624 /*Generic methods gets the context of the GTD.*/
8625 if (mono_class_get_context (klass)) {
8627 result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), &error);
8628 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8633 buffer_add_methodid (buf, domain, result);
8635 buffer_add_id (buf, 0);
8637 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8638 if (mono_method_signature (method)->generic_param_count) {
8641 if (method->is_inflated) {
8642 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
8644 count = inst->type_argc;
8645 buffer_add_int (buf, count);
8647 for (i = 0; i < count; i++)
8648 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8650 buffer_add_int (buf, 0);
8652 } else if (method->is_generic) {
8653 MonoGenericContainer *container = mono_method_get_generic_container (method);
8655 count = mono_method_signature (method)->generic_param_count;
8656 buffer_add_int (buf, count);
8657 for (i = 0; i < count; i++) {
8658 MonoGenericParam *param = mono_generic_container_get_param (container, i);
8659 MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
8660 buffer_add_typeid (buf, domain, pklass);
8663 buffer_add_int (buf, 0);
8666 buffer_add_int (buf, 0);
8671 case CMD_METHOD_GET_BODY: {
8674 header = mono_method_get_header (method);
8676 buffer_add_int (buf, 0);
8678 if (CHECK_PROTOCOL_VERSION (2, 18))
8679 buffer_add_int (buf, 0);
8681 buffer_add_int (buf, header->code_size);
8682 for (i = 0; i < header->code_size; ++i)
8683 buffer_add_byte (buf, header->code [i]);
8685 if (CHECK_PROTOCOL_VERSION (2, 18)) {
8686 buffer_add_int (buf, header->num_clauses);
8687 for (i = 0; i < header->num_clauses; ++i) {
8688 MonoExceptionClause *clause = &header->clauses [i];
8690 buffer_add_int (buf, clause->flags);
8691 buffer_add_int (buf, clause->try_offset);
8692 buffer_add_int (buf, clause->try_len);
8693 buffer_add_int (buf, clause->handler_offset);
8694 buffer_add_int (buf, clause->handler_len);
8695 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
8696 buffer_add_typeid (buf, domain, clause->data.catch_class);
8697 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8698 buffer_add_int (buf, clause->data.filter_offset);
8702 mono_metadata_free_mh (header);
8707 case CMD_METHOD_RESOLVE_TOKEN: {
8708 guint32 token = decode_int (p, &p, end);
8711 switch (mono_metadata_token_code (token)) {
8712 case MONO_TOKEN_STRING: {
8716 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
8719 s2 = mono_string_to_utf8 (s);
8721 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8722 buffer_add_string (buf, s2);
8728 MonoClass *handle_class;
8730 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8731 val = mono_method_get_wrapper_data (method, token);
8732 handle_class = mono_method_get_wrapper_data (method, token + 1);
8734 if (handle_class == NULL) {
8735 // Can't figure out the token type
8736 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8741 val = mono_ldtoken_checked (method->klass->image, token, &handle_class, NULL, &error);
8743 g_error ("Could not load token due to %s", mono_error_get_message (&error));
8746 if (handle_class == mono_defaults.typehandle_class) {
8747 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8748 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8749 buffer_add_typeid (buf, domain, (MonoClass *) val);
8751 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
8752 } else if (handle_class == mono_defaults.fieldhandle_class) {
8753 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8754 buffer_add_fieldid (buf, domain, val);
8755 } else if (handle_class == mono_defaults.methodhandle_class) {
8756 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8757 buffer_add_methodid (buf, domain, val);
8758 } else if (handle_class == mono_defaults.string_class) {
8761 s = mono_string_to_utf8 (val);
8762 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8763 buffer_add_string (buf, s);
8766 g_assert_not_reached ();
8773 case CMD_METHOD_GET_CATTRS: {
8774 MonoClass *attr_klass;
8775 MonoCustomAttrInfo *cinfo;
8777 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8778 /* attr_klass can be NULL */
8782 cinfo = mono_custom_attrs_from_method (method);
8784 err = buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
8789 case CMD_METHOD_MAKE_GENERIC_METHOD: {
8791 MonoType **type_argv;
8795 MonoGenericInst *ginst;
8796 MonoGenericContext tmp_context;
8797 MonoMethod *inflated;
8799 type_argc = decode_int (p, &p, end);
8800 type_argv = g_new0 (MonoType*, type_argc);
8801 for (i = 0; i < type_argc; ++i) {
8802 klass = decode_typeid (p, &p, end, &d, &err);
8809 return ERR_INVALID_ARGUMENT;
8811 type_argv [i] = &klass->byval_arg;
8813 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
8815 tmp_context.class_inst = method->klass->generic_class ? method->klass->generic_class->context.class_inst : NULL;
8816 tmp_context.method_inst = ginst;
8818 inflated = mono_class_inflate_generic_method_checked (method, &tmp_context, &error);
8819 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8820 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
8821 return ERR_INVALID_ARGUMENT;
8822 buffer_add_methodid (buf, domain, inflated);
8826 return ERR_NOT_IMPLEMENTED;
8833 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8836 MonoDomain *old_domain;
8840 method = decode_methodid (p, &p, end, &domain, &err);
8844 old_domain = mono_domain_get ();
8846 mono_domain_set (domain, TRUE);
8848 err = method_commands_internal (command, method, domain, p, end, buf);
8850 mono_domain_set (old_domain, TRUE);
8856 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8858 int objid = decode_objid (p, &p, end);
8860 MonoThread *thread_obj;
8861 MonoInternalThread *thread;
8863 err = get_object (objid, (MonoObject**)&thread_obj);
8867 thread = THREAD_TO_INTERNAL (thread_obj);
8870 case CMD_THREAD_GET_NAME: {
8872 gunichar2 *s = mono_thread_get_name (thread, &name_len);
8875 buffer_add_int (buf, 0);
8880 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
8882 buffer_add_int (buf, len);
8883 buffer_add_data (buf, (guint8*)name, len);
8888 case CMD_THREAD_GET_FRAME_INFO: {
8889 DebuggerTlsData *tls;
8890 int i, start_frame, length;
8892 // Wait for suspending if it already started
8893 // FIXME: Races with suspend_count
8894 while (!is_suspended ()) {
8896 wait_for_suspend ();
8900 wait_for_suspend ();
8901 if (!is_suspended ())
8902 return ERR_NOT_SUSPENDED;
8905 start_frame = decode_int (p, &p, end);
8906 length = decode_int (p, &p, end);
8908 if (start_frame != 0 || length != -1)
8909 return ERR_NOT_IMPLEMENTED;
8911 mono_loader_lock ();
8912 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8913 mono_loader_unlock ();
8916 compute_frame_info (thread, tls);
8918 buffer_add_int (buf, tls->frame_count);
8919 for (i = 0; i < tls->frame_count; ++i) {
8920 buffer_add_int (buf, tls->frames [i]->id);
8921 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
8922 buffer_add_int (buf, tls->frames [i]->il_offset);
8924 * Instead of passing the frame type directly to the client, we associate
8925 * it with the previous frame using a set of flags. This avoids lots of
8926 * conditional code in the client, since a frame whose type isn't
8927 * FRAME_TYPE_MANAGED has no method, location, etc.
8929 buffer_add_byte (buf, tls->frames [i]->flags);
8934 case CMD_THREAD_GET_STATE:
8935 buffer_add_int (buf, thread->state);
8937 case CMD_THREAD_GET_INFO:
8938 buffer_add_byte (buf, thread->threadpool_thread);
8940 case CMD_THREAD_GET_ID:
8941 buffer_add_long (buf, (guint64)(gsize)thread);
8943 case CMD_THREAD_GET_TID:
8944 buffer_add_long (buf, (guint64)thread->tid);
8946 case CMD_THREAD_SET_IP: {
8947 DebuggerTlsData *tls;
8950 MonoSeqPointInfo *seq_points;
8955 method = decode_methodid (p, &p, end, &domain, &err);
8958 il_offset = decode_long (p, &p, end);
8960 while (!is_suspended ()) {
8962 wait_for_suspend ();
8965 mono_loader_lock ();
8966 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8967 mono_loader_unlock ();
8970 compute_frame_info (thread, tls);
8971 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
8972 return ERR_INVALID_ARGUMENT;
8974 found_sp = find_seq_point (domain, method, il_offset, &seq_points, &sp);
8976 g_assert (seq_points);
8979 return ERR_INVALID_ARGUMENT;
8981 // FIXME: Check that the ip change is safe
8983 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);
8984 MONO_CONTEXT_SET_IP (&tls->restore_state.ctx, (guint8*)tls->frames [0]->ji->code_start + sp.native_offset);
8988 return ERR_NOT_IMPLEMENTED;
8995 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8999 MonoThread *thread_obj;
9000 MonoInternalThread *thread;
9001 int pos, i, len, frame_idx;
9002 DebuggerTlsData *tls;
9004 MonoDebugMethodJitInfo *jit;
9005 MonoMethodSignature *sig;
9007 MonoMethodHeader *header;
9009 objid = decode_objid (p, &p, end);
9010 err = get_object (objid, (MonoObject**)&thread_obj);
9014 thread = THREAD_TO_INTERNAL (thread_obj);
9016 id = decode_id (p, &p, end);
9018 mono_loader_lock ();
9019 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
9020 mono_loader_unlock ();
9023 for (i = 0; i < tls->frame_count; ++i) {
9024 if (tls->frames [i]->id == id)
9027 if (i == tls->frame_count)
9028 return ERR_INVALID_FRAMEID;
9031 frame = tls->frames [frame_idx];
9033 /* This is supported for frames without has_ctx etc. set */
9034 if (command == CMD_STACK_FRAME_GET_DOMAIN) {
9035 if (CHECK_PROTOCOL_VERSION (2, 38))
9036 buffer_add_domainid (buf, frame->domain);
9040 if (!frame->has_ctx)
9041 return ERR_ABSENT_INFORMATION;
9044 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
9045 if (!frame->jit && frame->api_method->is_inflated)
9046 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
9050 /* This could happen for aot images with no jit debug info */
9051 s = mono_method_full_name (frame->api_method, TRUE);
9052 DEBUG_PRINTF (1, "[dbg] No debug information found for '%s'.\n", s);
9054 return ERR_ABSENT_INFORMATION;
9059 sig = mono_method_signature (frame->actual_method);
9061 if (!get_seq_points (frame->domain, frame->actual_method))
9063 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
9065 return ERR_ABSENT_INFORMATION;
9068 case CMD_STACK_FRAME_GET_VALUES: {
9069 len = decode_int (p, &p, end);
9070 header = mono_method_get_header (frame->actual_method);
9072 for (i = 0; i < len; ++i) {
9073 pos = decode_int (p, &p, end);
9078 g_assert (pos >= 0 && pos < jit->num_params);
9080 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
9082 g_assert (pos >= 0 && pos < jit->num_locals);
9084 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
9087 mono_metadata_free_mh (header);
9090 case CMD_STACK_FRAME_GET_THIS: {
9091 if (frame->api_method->klass->valuetype) {
9092 if (!sig->hasthis) {
9093 MonoObject *p = NULL;
9094 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
9096 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9099 if (!sig->hasthis) {
9100 MonoObject *p = NULL;
9101 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
9103 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9108 case CMD_STACK_FRAME_SET_VALUES: {
9111 MonoDebugVarInfo *var;
9113 len = decode_int (p, &p, end);
9114 header = mono_method_get_header (frame->actual_method);
9116 for (i = 0; i < len; ++i) {
9117 pos = decode_int (p, &p, end);
9122 g_assert (pos >= 0 && pos < jit->num_params);
9124 t = sig->params [pos];
9125 var = &jit->params [pos];
9127 g_assert (pos >= 0 && pos < jit->num_locals);
9129 t = header->locals [pos];
9130 var = &jit->locals [pos];
9133 if (MONO_TYPE_IS_REFERENCE (t))
9134 val_buf = g_alloca (sizeof (MonoObject*));
9136 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9137 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9141 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9143 mono_metadata_free_mh (header);
9146 case CMD_STACK_FRAME_GET_DOMAIN: {
9147 if (CHECK_PROTOCOL_VERSION (2, 38))
9148 buffer_add_domainid (buf, frame->domain);
9152 return ERR_NOT_IMPLEMENTED;
9159 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9162 int objid, err, index, len, i, esize;
9165 objid = decode_objid (p, &p, end);
9166 err = get_object (objid, (MonoObject**)&arr);
9171 case CMD_ARRAY_REF_GET_LENGTH:
9172 buffer_add_int (buf, arr->obj.vtable->klass->rank);
9174 buffer_add_int (buf, arr->max_length);
9175 buffer_add_int (buf, 0);
9177 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
9178 buffer_add_int (buf, arr->bounds [i].length);
9179 buffer_add_int (buf, arr->bounds [i].lower_bound);
9183 case CMD_ARRAY_REF_GET_VALUES:
9184 index = decode_int (p, &p, end);
9185 len = decode_int (p, &p, end);
9187 g_assert (index >= 0 && len >= 0);
9188 // Reordered to avoid integer overflow
9189 g_assert (!(index > arr->max_length - len));
9191 esize = mono_array_element_size (arr->obj.vtable->klass);
9192 for (i = index; i < index + len; ++i) {
9193 elem = (gpointer*)((char*)arr->vector + (i * esize));
9194 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
9197 case CMD_ARRAY_REF_SET_VALUES:
9198 index = decode_int (p, &p, end);
9199 len = decode_int (p, &p, end);
9201 g_assert (index >= 0 && len >= 0);
9202 // Reordered to avoid integer overflow
9203 g_assert (!(index > arr->max_length - len));
9205 esize = mono_array_element_size (arr->obj.vtable->klass);
9206 for (i = index; i < index + len; ++i) {
9207 elem = (gpointer*)((char*)arr->vector + (i * esize));
9209 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
9213 return ERR_NOT_IMPLEMENTED;
9220 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9225 int i, index, length;
9228 objid = decode_objid (p, &p, end);
9229 err = get_object (objid, (MonoObject**)&str);
9234 case CMD_STRING_REF_GET_VALUE:
9235 s = mono_string_to_utf8 (str);
9236 buffer_add_string (buf, s);
9239 case CMD_STRING_REF_GET_LENGTH:
9240 buffer_add_long (buf, mono_string_length (str));
9242 case CMD_STRING_REF_GET_CHARS:
9243 index = decode_long (p, &p, end);
9244 length = decode_long (p, &p, end);
9245 if (index > mono_string_length (str) - length)
9246 return ERR_INVALID_ARGUMENT;
9247 c = mono_string_chars (str) + index;
9248 for (i = 0; i < length; ++i)
9249 buffer_add_short (buf, c [i]);
9252 return ERR_NOT_IMPLEMENTED;
9259 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9268 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9269 objid = decode_objid (p, &p, end);
9270 err = get_object (objid, &obj);
9272 buffer_add_int (buf, 1);
9274 buffer_add_int (buf, 0);
9278 objid = decode_objid (p, &p, end);
9279 err = get_object (objid, &obj);
9284 case CMD_OBJECT_REF_GET_TYPE:
9285 /* This handles transparent proxies too */
9286 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9288 case CMD_OBJECT_REF_GET_VALUES:
9289 len = decode_int (p, &p, end);
9291 for (i = 0; i < len; ++i) {
9292 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9296 /* Check that the field belongs to the object */
9298 for (k = obj->vtable->klass; k; k = k->parent) {
9299 if (k == f->parent) {
9305 return ERR_INVALID_FIELDID;
9307 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9311 if (mono_class_field_is_special_static (f))
9312 return ERR_INVALID_FIELDID;
9314 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9315 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9316 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9317 mono_field_static_get_value (vtable, f, val);
9318 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9321 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
9325 case CMD_OBJECT_REF_SET_VALUES:
9326 len = decode_int (p, &p, end);
9328 for (i = 0; i < len; ++i) {
9329 f = decode_fieldid (p, &p, end, NULL, &err);
9333 /* Check that the field belongs to the object */
9335 for (k = obj->vtable->klass; k; k = k->parent) {
9336 if (k == f->parent) {
9342 return ERR_INVALID_FIELDID;
9344 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9348 if (mono_class_field_is_special_static (f))
9349 return ERR_INVALID_FIELDID;
9351 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9352 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9354 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9355 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
9360 mono_field_static_set_value (vtable, f, val);
9363 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
9369 case CMD_OBJECT_REF_GET_ADDRESS:
9370 buffer_add_long (buf, (gssize)obj);
9372 case CMD_OBJECT_REF_GET_DOMAIN:
9373 buffer_add_domainid (buf, obj->vtable->domain);
9375 case CMD_OBJECT_REF_GET_INFO:
9376 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9377 buffer_add_domainid (buf, obj->vtable->domain);
9380 return ERR_NOT_IMPLEMENTED;
9387 command_set_to_string (CommandSet command_set)
9389 switch (command_set) {
9392 case CMD_SET_OBJECT_REF:
9393 return "OBJECT_REF";
9394 case CMD_SET_STRING_REF:
9395 return "STRING_REF";
9396 case CMD_SET_THREAD:
9398 case CMD_SET_ARRAY_REF:
9400 case CMD_SET_EVENT_REQUEST:
9401 return "EVENT_REQUEST";
9402 case CMD_SET_STACK_FRAME:
9403 return "STACK_FRAME";
9404 case CMD_SET_APPDOMAIN:
9406 case CMD_SET_ASSEMBLY:
9408 case CMD_SET_METHOD:
9412 case CMD_SET_MODULE:
9423 static const char* vm_cmds_str [] = {
9431 "SET_PROTOCOL_VERSION",
9434 "GET_TYPES_FOR_SOURCE_FILE",
9439 static const char* thread_cmds_str[] = {
9449 static const char* event_cmds_str[] = {
9452 "REQUEST_CLEAR_ALL_BREAKPOINTS"
9455 static const char* appdomain_cmds_str[] = {
9457 "GET_FRIENDLY_NAME",
9459 "GET_ENTRY_ASSEMBLY",
9462 "CREATE_BOXED_VALUE"
9465 static const char* assembly_cmds_str[] = {
9468 "GET_MANIFEST_MODULE",
9474 static const char* module_cmds_str[] = {
9478 static const char* field_cmds_str[] = {
9482 static const char* method_cmds_str[] = {
9484 "GET_DECLARING_TYPE",
9492 "MAKE_GENERIC_METHOD"
9495 static const char* type_cmds_str[] = {
9503 "IS_ASSIGNABLE_FROM",
9507 "GET_PROPERTY_CATTRS",
9508 "GET_SOURCE_FILES_2",
9510 "GET_METHODS_BY_NAME_FLAGS",
9512 "GET_INTERFACE_MAP",
9516 static const char* stack_frame_cmds_str[] = {
9523 static const char* array_cmds_str[] = {
9529 static const char* string_cmds_str[] = {
9535 static const char* object_cmds_str[] = {
9546 cmd_to_string (CommandSet set, int command)
9554 cmds_len = G_N_ELEMENTS (vm_cmds_str);
9556 case CMD_SET_OBJECT_REF:
9557 cmds = object_cmds_str;
9558 cmds_len = G_N_ELEMENTS (object_cmds_str);
9560 case CMD_SET_STRING_REF:
9561 cmds = string_cmds_str;
9562 cmds_len = G_N_ELEMENTS (string_cmds_str);
9564 case CMD_SET_THREAD:
9565 cmds = thread_cmds_str;
9566 cmds_len = G_N_ELEMENTS (thread_cmds_str);
9568 case CMD_SET_ARRAY_REF:
9569 cmds = array_cmds_str;
9570 cmds_len = G_N_ELEMENTS (array_cmds_str);
9572 case CMD_SET_EVENT_REQUEST:
9573 cmds = event_cmds_str;
9574 cmds_len = G_N_ELEMENTS (event_cmds_str);
9576 case CMD_SET_STACK_FRAME:
9577 cmds = stack_frame_cmds_str;
9578 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
9580 case CMD_SET_APPDOMAIN:
9581 cmds = appdomain_cmds_str;
9582 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
9584 case CMD_SET_ASSEMBLY:
9585 cmds = assembly_cmds_str;
9586 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
9588 case CMD_SET_METHOD:
9589 cmds = method_cmds_str;
9590 cmds_len = G_N_ELEMENTS (method_cmds_str);
9593 cmds = type_cmds_str;
9594 cmds_len = G_N_ELEMENTS (type_cmds_str);
9596 case CMD_SET_MODULE:
9597 cmds = module_cmds_str;
9598 cmds_len = G_N_ELEMENTS (module_cmds_str);
9601 cmds = field_cmds_str;
9602 cmds_len = G_N_ELEMENTS (field_cmds_str);
9605 cmds = event_cmds_str;
9606 cmds_len = G_N_ELEMENTS (event_cmds_str);
9611 if (command > 0 && command <= cmds_len)
9612 return cmds [command - 1];
9618 wait_for_attach (void)
9620 #ifndef DISABLE_SOCKET_TRANSPORT
9621 if (listen_fd == -1) {
9622 DEBUG_PRINTF (1, "[dbg] Invalid listening socket\n");
9626 /* Block and wait for client connection */
9627 MONO_PREPARE_BLOCKING
9628 conn_fd = socket_transport_accept (listen_fd);
9629 MONO_FINISH_BLOCKING
9631 DEBUG_PRINTF (1, "Accepted connection on %d\n", conn_fd);
9632 if (conn_fd == -1) {
9633 DEBUG_PRINTF (1, "[dbg] Bad client connection\n");
9637 g_assert_not_reached ();
9641 disconnected = !transport_handshake ();
9643 DEBUG_PRINTF (1, "Transport handshake failed!\n");
9653 * This thread handles communication with the debugger client using a JDWP
9656 static guint32 WINAPI
9657 debugger_thread (void *arg)
9659 int res, len, id, flags, command_set = 0, command = 0;
9660 guint8 header [HEADER_LENGTH];
9661 guint8 *data, *p, *end;
9665 gboolean attach_failed = FALSE;
9667 DEBUG_PRINTF (1, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ());
9669 debugger_thread_id = GetCurrentThreadId ();
9671 mono_jit_thread_attach (mono_get_root_domain ());
9673 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
9675 mono_set_is_debugger_attached (TRUE);
9677 if (agent_config.defer) {
9678 if (!wait_for_attach ()) {
9679 DEBUG_PRINTF (1, "[dbg] Can't attach, aborting debugger thread.\n");
9680 attach_failed = TRUE; // Don't abort process when we can't listen
9682 /* Send start event to client */
9683 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
9687 while (!attach_failed) {
9688 MONO_PREPARE_BLOCKING
9689 res = transport_recv (header, HEADER_LENGTH);
9690 MONO_FINISH_BLOCKING
9692 /* This will break if the socket is closed during shutdown too */
9693 if (res != HEADER_LENGTH) {
9694 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH);
9699 end = header + HEADER_LENGTH;
9701 len = decode_int (p, &p, end);
9702 id = decode_int (p, &p, end);
9703 flags = decode_byte (p, &p, end);
9704 command_set = decode_byte (p, &p, end);
9705 command = decode_byte (p, &p, end);
9707 g_assert (flags == 0);
9710 const char *cmd_str;
9713 cmd_str = cmd_to_string (command_set, command);
9715 sprintf (cmd_num, "%d", command);
9719 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);
9722 data = g_malloc (len - HEADER_LENGTH);
9723 if (len - HEADER_LENGTH > 0)
9725 MONO_PREPARE_BLOCKING
9726 res = transport_recv (data, len - HEADER_LENGTH);
9727 MONO_FINISH_BLOCKING
9728 if (res != len - HEADER_LENGTH) {
9729 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH);
9735 end = data + (len - HEADER_LENGTH);
9737 buffer_init (&buf, 128);
9742 /* Process the request */
9743 switch (command_set) {
9745 err = vm_commands (command, id, p, end, &buf);
9746 if (!err && command == CMD_VM_INVOKE_METHOD)
9747 /* Sent after the invoke is complete */
9750 case CMD_SET_EVENT_REQUEST:
9751 err = event_commands (command, p, end, &buf);
9753 case CMD_SET_APPDOMAIN:
9754 err = domain_commands (command, p, end, &buf);
9756 case CMD_SET_ASSEMBLY:
9757 err = assembly_commands (command, p, end, &buf);
9759 case CMD_SET_MODULE:
9760 err = module_commands (command, p, end, &buf);
9763 err = field_commands (command, p, end, &buf);
9766 err = type_commands (command, p, end, &buf);
9768 case CMD_SET_METHOD:
9769 err = method_commands (command, p, end, &buf);
9771 case CMD_SET_THREAD:
9772 err = thread_commands (command, p, end, &buf);
9774 case CMD_SET_STACK_FRAME:
9775 err = frame_commands (command, p, end, &buf);
9777 case CMD_SET_ARRAY_REF:
9778 err = array_commands (command, p, end, &buf);
9780 case CMD_SET_STRING_REF:
9781 err = string_commands (command, p, end, &buf);
9783 case CMD_SET_OBJECT_REF:
9784 err = object_commands (command, p, end, &buf);
9787 err = ERR_NOT_IMPLEMENTED;
9790 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
9791 buffer_replies = TRUE;
9795 if (buffer_replies) {
9796 buffer_reply_packet (id, err, &buf);
9798 send_reply_packet (id, err, &buf);
9799 //DEBUG_PRINTF (1, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000);
9803 if (!err && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
9804 send_buffered_reply_packets ();
9805 buffer_replies = FALSE;
9811 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
9815 mono_set_is_debugger_attached (FALSE);
9818 mono_mutex_lock (&debugger_thread_exited_mutex);
9819 debugger_thread_exited = TRUE;
9820 mono_cond_signal (&debugger_thread_exited_cond);
9821 mono_mutex_unlock (&debugger_thread_exited_mutex);
9822 MONO_FINISH_TRY_BLOCKING
9824 DEBUG_PRINTF (1, "[dbg] Debugger thread exited.\n");
9826 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
9827 DEBUG_PRINTF (2, "[dbg] Detached - restarting clean debugger thread.\n");
9828 start_debugger_thread ();
9834 #else /* DISABLE_DEBUGGER_AGENT */
9837 mono_debugger_agent_parse_options (char *options)
9839 g_error ("This runtime is configured with the debugger agent disabled.");
9843 mono_debugger_agent_init (void)
9848 mono_debugger_agent_breakpoint_hit (void *sigctx)
9853 mono_debugger_agent_single_step_event (void *sigctx)
9858 mono_debugger_agent_free_domain_info (MonoDomain *domain)
9863 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
9869 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
9870 MonoContext *catch_ctx)
9875 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9880 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9885 mono_debugger_agent_user_break (void)
9891 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
9896 mono_debugger_agent_debug_log_is_enabled (void)
9902 mono_debugger_agent_unhandled_exception (MonoException *exc)
9904 g_assert_not_reached ();
9908 debugger_agent_single_step_from_context (MonoContext *ctx)
9910 g_assert_not_reached ();
9914 debugger_agent_breakpoint_from_context (MonoContext *ctx)
9916 g_assert_not_reached ();