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() mono_mutex_lock (&debug_mutex)
730 #define dbg_unlock() mono_mutex_unlock (&debug_mutex)
731 static mono_mutex_t debug_mutex;
733 static void transport_init (void);
734 static void transport_connect (const char *address);
735 static gboolean transport_handshake (void);
736 static void register_transport (DebuggerTransport *trans);
738 static guint32 WINAPI debugger_thread (void *arg);
740 static void runtime_initialized (MonoProfiler *prof);
742 static void runtime_shutdown (MonoProfiler *prof);
744 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
746 static void thread_end (MonoProfiler *prof, uintptr_t tid);
748 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
750 static void appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain);
752 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
754 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
756 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
758 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
760 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
762 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
764 static void emit_assembly_load (gpointer assembly, gpointer user_data);
766 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
768 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
770 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
772 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
774 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
776 static void start_single_stepping (void);
778 static void stop_single_stepping (void);
780 static void suspend_current (void);
782 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
784 static void clear_types_for_assembly (MonoAssembly *assembly);
786 static void clear_breakpoints_for_domain (MonoDomain *domain);
788 static void process_profiler_event (EventKind event, gpointer arg);
790 /* Submodule init/cleanup */
791 static void breakpoints_init (void);
792 static void breakpoints_cleanup (void);
794 static void objrefs_init (void);
795 static void objrefs_cleanup (void);
797 static void ids_init (void);
798 static void ids_cleanup (void);
800 static void suspend_init (void);
802 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch,
803 StackFrame **frames, int nframes);
804 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req);
805 static void ss_destroy (SingleStepReq *req);
807 static void start_debugger_thread (void);
808 static void stop_debugger_thread (void);
810 static void finish_agent_init (gboolean on_startup);
812 static void process_profiler_event (EventKind event, gpointer arg);
814 static void invalidate_frames (DebuggerTlsData *tls);
816 #ifndef DISABLE_SOCKET_TRANSPORT
818 register_socket_transport (void);
821 static inline gboolean
822 is_debugger_thread (void)
824 return GetCurrentThreadId () == debugger_thread_id;
828 parse_address (char *address, char **host, int *port)
830 char *pos = strchr (address, ':');
832 if (pos == NULL || pos == address)
835 *host = g_malloc (pos - address + 1);
836 strncpy (*host, address, pos - address);
837 (*host) [pos - address] = '\0';
839 *port = atoi (pos + 1);
847 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
848 fprintf (stderr, "Available options:\n");
849 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
850 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
851 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
852 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
853 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
854 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
855 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
856 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
857 fprintf (stderr, " setpgid=y/n\t\t\tWhether to call setpid(0, 0) after startup.\n");
858 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
862 parse_flag (const char *option, char *flag)
864 if (!strcmp (flag, "y"))
866 else if (!strcmp (flag, "n"))
869 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
876 mono_debugger_agent_parse_options (char *options)
883 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
884 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
888 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
890 options = g_strdup_printf ("%s,%s", options, extra);
892 agent_config.enabled = TRUE;
893 agent_config.suspend = TRUE;
894 agent_config.server = FALSE;
895 agent_config.defer = FALSE;
896 agent_config.address = NULL;
898 //agent_config.log_level = 10;
900 args = g_strsplit (options, ",", -1);
901 for (ptr = args; ptr && *ptr; ptr ++) {
904 if (strncmp (arg, "transport=", 10) == 0) {
905 agent_config.transport = g_strdup (arg + 10);
906 } else if (strncmp (arg, "address=", 8) == 0) {
907 agent_config.address = g_strdup (arg + 8);
908 } else if (strncmp (arg, "loglevel=", 9) == 0) {
909 agent_config.log_level = atoi (arg + 9);
910 } else if (strncmp (arg, "logfile=", 8) == 0) {
911 agent_config.log_file = g_strdup (arg + 8);
912 } else if (strncmp (arg, "suspend=", 8) == 0) {
913 agent_config.suspend = parse_flag ("suspend", arg + 8);
914 } else if (strncmp (arg, "server=", 7) == 0) {
915 agent_config.server = parse_flag ("server", arg + 7);
916 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
917 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
918 } else if (strncmp (arg, "onthrow=", 8) == 0) {
919 /* We support multiple onthrow= options */
920 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
921 } else if (strncmp (arg, "onthrow", 7) == 0) {
922 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
923 } else if (strncmp (arg, "help", 4) == 0) {
926 } else if (strncmp (arg, "timeout=", 8) == 0) {
927 agent_config.timeout = atoi (arg + 8);
928 } else if (strncmp (arg, "launch=", 7) == 0) {
929 agent_config.launch = g_strdup (arg + 7);
930 } else if (strncmp (arg, "embedding=", 10) == 0) {
931 agent_config.embedding = atoi (arg + 10) == 1;
932 } else if (strncmp (arg, "keepalive=", 10) == 0) {
933 agent_config.keepalive = atoi (arg + 10);
934 } else if (strncmp (arg, "setpgid=", 8) == 0) {
935 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
942 if (agent_config.server && !agent_config.suspend) {
943 /* Waiting for deferred attachment */
944 agent_config.defer = TRUE;
945 if (agent_config.address == NULL) {
946 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (getpid () % 1000));
950 //agent_config.log_level = 0;
952 if (agent_config.transport == NULL) {
953 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
957 if (agent_config.address == NULL && !agent_config.server) {
958 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
963 if (!strcmp (agent_config.transport, "dt_socket")) {
964 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
965 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
972 mono_debugger_agent_init (void)
974 mono_mutex_init_recursive (&debug_mutex);
976 if (!agent_config.enabled)
981 /* Need to know whenever a thread has acquired the loader mutex */
982 mono_loader_lock_track_ownership (TRUE);
984 event_requests = g_ptr_array_new ();
986 mono_mutex_init (&debugger_thread_exited_mutex);
987 mono_cond_init (&debugger_thread_exited_cond, NULL);
989 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
990 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
991 mono_profiler_install_runtime_initialized (runtime_initialized);
992 mono_profiler_install_appdomain (NULL, appdomain_load, appdomain_start_unload, appdomain_unload);
993 mono_profiler_install_thread (thread_startup, thread_end);
994 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
995 mono_profiler_install_jit_end (jit_end);
996 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
998 mono_native_tls_alloc (&debugger_tls_id, NULL);
1000 /* Needed by the hash_table_new_type () call below */
1001 mono_gc_base_init ();
1003 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
1004 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls);
1006 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
1007 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread);
1009 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
1010 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj);
1012 pending_assembly_loads = g_ptr_array_new ();
1013 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
1015 log_level = agent_config.log_level;
1017 embedding = agent_config.embedding;
1018 disconnected = TRUE;
1020 if (agent_config.log_file) {
1021 log_file = fopen (agent_config.log_file, "w+");
1023 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
1032 breakpoints_init ();
1035 mini_get_debug_options ()->gen_sdb_seq_points = TRUE;
1037 * This is needed because currently we don't handle liveness info.
1039 mini_get_debug_options ()->mdb_optimizations = TRUE;
1041 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
1042 /* This is needed because we can't set local variables in registers yet */
1043 mono_disable_optimizations (MONO_OPT_LINEARS);
1047 * The stack walk done from thread_interrupt () needs to be signal safe, but it
1048 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
1049 * safe (#3411). So load AOT info eagerly when the debugger is running as a
1052 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
1055 if (agent_config.setpgid)
1059 if (!agent_config.onuncaught && !agent_config.onthrow)
1060 finish_agent_init (TRUE);
1064 * finish_agent_init:
1066 * Finish the initialization of the agent. This involves connecting the transport
1067 * and starting the agent thread. This is either done at startup, or
1068 * in response to some event like an unhandled exception.
1071 finish_agent_init (gboolean on_startup)
1075 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
1078 if (agent_config.launch) {
1081 // FIXME: Generated address
1082 // FIXME: Races with transport_connect ()
1084 argv [0] = agent_config.launch;
1085 argv [1] = agent_config.transport;
1086 argv [2] = agent_config.address;
1089 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1091 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1096 transport_connect (agent_config.address);
1099 /* Do some which is usually done after sending the VMStart () event */
1100 vm_start_event_sent = TRUE;
1101 start_debugger_thread ();
1106 mono_debugger_agent_cleanup (void)
1111 stop_debugger_thread ();
1113 breakpoints_cleanup ();
1117 mono_mutex_destroy (&debugger_thread_exited_mutex);
1118 mono_cond_destroy (&debugger_thread_exited_cond);
1125 #ifndef DISABLE_SOCKET_TRANSPORT
1130 * recv() + handle incomplete reads and EINTR
1133 socket_transport_recv (void *buf, int len)
1139 static gint32 last_keepalive;
1144 res = recv (fd, (char *) buf + total, len - total, flags);
1147 if (agent_config.keepalive) {
1148 gboolean need_keepalive = FALSE;
1149 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1150 need_keepalive = TRUE;
1151 } else if (res == -1) {
1152 /* This could happen if recv () is interrupted repeatedly */
1153 msecs = mono_msec_ticks ();
1154 if (msecs - last_keepalive >= agent_config.keepalive) {
1155 need_keepalive = TRUE;
1156 last_keepalive = msecs;
1159 if (need_keepalive) {
1160 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1164 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1169 set_keepalive (void)
1174 if (!agent_config.keepalive || !conn_fd)
1177 tv.tv_sec = agent_config.keepalive / 1000;
1178 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1180 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1181 g_assert (result >= 0);
1185 socket_transport_accept (int socket_fd)
1187 conn_fd = accept (socket_fd, NULL, NULL);
1188 if (conn_fd == -1) {
1189 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1191 DEBUG_PRINTF (1, "Accepted connection from client, connection fd=%d.\n", conn_fd);
1198 socket_transport_send (void *data, int len)
1203 res = send (conn_fd, data, len, 0);
1204 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1212 * socket_transport_connect:
1214 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1217 socket_transport_connect (const char *address)
1219 MonoAddressInfo *result;
1220 MonoAddressEntry *rp;
1221 int sfd = -1, s, res;
1225 if (agent_config.address) {
1226 res = parse_address (agent_config.address, &host, &port);
1227 g_assert (res == 0);
1238 mono_network_init ();
1240 /* Obtain address(es) matching host/port */
1241 s = mono_get_address_info (host, port, MONO_HINT_UNSPECIFIED, &result);
1243 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, s); // FIXME add portable error conversion functions
1248 if (agent_config.server) {
1249 /* Wait for a connection */
1251 struct sockaddr_in addr;
1254 /* No address, generate one */
1255 sfd = socket (AF_INET, SOCK_STREAM, 0);
1258 /* This will bind the socket to a random port */
1259 res = listen (sfd, 16);
1261 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1266 addrlen = sizeof (addr);
1267 memset (&addr, 0, sizeof (addr));
1268 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1269 g_assert (res == 0);
1271 host = (char*)"127.0.0.1";
1272 port = ntohs (addr.sin_port);
1274 /* Emit the address to stdout */
1275 /* FIXME: Should print another interface, not localhost */
1276 printf ("%s:%d\n", host, port);
1278 /* Listen on the provided address */
1279 for (rp = result->entries; rp != NULL; rp = rp->next) {
1280 MonoSocketAddress sockaddr;
1284 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1286 sfd = socket (rp->family, rp->socktype,
1291 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1294 res = bind (sfd, &sockaddr.addr, sock_len);
1298 res = listen (sfd, 16);
1305 mono_free_address_info (result);
1308 if (agent_config.defer)
1311 DEBUG_PRINTF (1, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout);
1313 if (agent_config.timeout) {
1318 tv.tv_usec = agent_config.timeout * 1000;
1320 FD_SET (sfd, &readfds);
1321 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1323 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1328 conn_fd = socket_transport_accept (sfd);
1332 DEBUG_PRINTF (1, "Accepted connection from client, socket fd=%d.\n", conn_fd);
1334 /* Connect to the specified address */
1335 /* FIXME: Respect the timeout */
1336 for (rp = result->entries; rp != NULL; rp = rp->next) {
1337 MonoSocketAddress sockaddr;
1340 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1342 sfd = socket (rp->family, rp->socktype,
1347 if (connect (sfd, &sockaddr.addr, sock_len) != -1)
1348 break; /* Success */
1354 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1360 mono_free_address_info (result);
1363 if (!transport_handshake ())
1368 socket_transport_close1 (void)
1370 /* This will interrupt the agent thread */
1371 /* Close the read part only so it can still send back replies */
1372 /* Also shut down the connection listener so that we can exit normally */
1374 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1375 shutdown (conn_fd, SD_BOTH);
1376 shutdown (listen_fd, SD_BOTH);
1377 closesocket (listen_fd);
1379 shutdown (conn_fd, SHUT_RD);
1380 shutdown (listen_fd, SHUT_RDWR);
1386 socket_transport_close2 (void)
1389 shutdown (conn_fd, SD_BOTH);
1391 shutdown (conn_fd, SHUT_RDWR);
1396 register_socket_transport (void)
1398 DebuggerTransport trans;
1400 trans.name = "dt_socket";
1401 trans.connect = socket_transport_connect;
1402 trans.close1 = socket_transport_close1;
1403 trans.close2 = socket_transport_close2;
1404 trans.send = socket_transport_send;
1405 trans.recv = socket_transport_recv;
1407 register_transport (&trans);
1411 * socket_fd_transport_connect:
1415 socket_fd_transport_connect (const char *address)
1419 res = sscanf (address, "%d", &conn_fd);
1421 fprintf (stderr, "debugger-agent: socket-fd transport address is invalid: '%s'\n", address);
1425 if (!transport_handshake ())
1430 register_socket_fd_transport (void)
1432 DebuggerTransport trans;
1434 /* This is the same as the 'dt_socket' transport, but receives an already connected socket fd */
1435 trans.name = "socket-fd";
1436 trans.connect = socket_fd_transport_connect;
1437 trans.close1 = socket_transport_close1;
1438 trans.close2 = socket_transport_close2;
1439 trans.send = socket_transport_send;
1440 trans.recv = socket_transport_recv;
1442 register_transport (&trans);
1445 #endif /* DISABLE_SOCKET_TRANSPORT */
1451 #define MAX_TRANSPORTS 16
1453 static DebuggerTransport *transport;
1455 static DebuggerTransport transports [MAX_TRANSPORTS];
1456 static int ntransports;
1459 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1462 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1464 register_transport (trans);
1468 register_transport (DebuggerTransport *trans)
1470 g_assert (ntransports < MAX_TRANSPORTS);
1472 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1477 transport_init (void)
1481 #ifndef DISABLE_SOCKET_TRANSPORT
1482 register_socket_transport ();
1483 register_socket_fd_transport ();
1486 for (i = 0; i < ntransports; ++i) {
1487 if (!strcmp (agent_config.transport, transports [i].name))
1490 if (i == ntransports) {
1491 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1492 for (i = 0; i < ntransports; ++i)
1493 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1494 fprintf (stderr, "\n");
1497 transport = &transports [i];
1501 transport_connect (const char *address)
1503 transport->connect (address);
1507 transport_close1 (void)
1509 transport->close1 ();
1513 transport_close2 (void)
1515 transport->close2 ();
1519 transport_send (void *buf, int len)
1521 return transport->send (buf, len);
1525 transport_recv (void *buf, int len)
1527 return transport->recv (buf, len);
1531 mono_debugger_agent_transport_handshake (void)
1533 return transport_handshake ();
1537 transport_handshake (void)
1539 char handshake_msg [128];
1543 disconnected = TRUE;
1545 /* Write handshake message */
1546 sprintf (handshake_msg, "DWP-Handshake");
1548 res = transport_send (handshake_msg, strlen (handshake_msg));
1549 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1550 g_assert (res != -1);
1553 res = transport_recv (buf, strlen (handshake_msg));
1554 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg)) != 0)) {
1555 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1560 * To support older clients, the client sends its protocol version after connecting
1561 * using a command. Until that is received, default to our protocol version.
1563 major_version = MAJOR_VERSION;
1564 minor_version = MINOR_VERSION;
1565 protocol_version_set = FALSE;
1567 #ifndef DISABLE_SOCKET_TRANSPORT
1568 // FIXME: Move this somewhere else
1570 * Set TCP_NODELAY on the socket so the client receives events/command
1571 * results immediately.
1575 int result = setsockopt (conn_fd,
1580 g_assert (result >= 0);
1586 disconnected = FALSE;
1591 stop_debugger_thread (void)
1596 transport_close1 ();
1599 * Wait for the thread to exit.
1601 * If we continue with the shutdown without waiting for it, then the client might
1602 * not receive an answer to its last command like a resume.
1603 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
1606 //WaitForSingleObject (debugger_thread_handle, INFINITE);
1607 if (GetCurrentThreadId () != debugger_thread_id) {
1609 mono_mutex_lock (&debugger_thread_exited_mutex);
1610 if (!debugger_thread_exited) {
1612 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
1613 mono_mutex_unlock (&debugger_thread_exited_mutex);
1615 mono_mutex_lock (&debugger_thread_exited_mutex);
1618 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1621 mono_mutex_unlock (&debugger_thread_exited_mutex);
1622 } while (!debugger_thread_exited);
1625 transport_close2 ();
1629 start_debugger_thread (void)
1631 debugger_thread_handle = mono_threads_create_thread (debugger_thread, NULL, 0, 0, NULL);
1632 g_assert (debugger_thread_handle);
1636 * Functions to decode protocol data
1640 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1643 g_assert (*endbuf <= limit);
1648 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1651 g_assert (*endbuf <= limit);
1653 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1656 static inline gint64
1657 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1659 guint32 high = decode_int (buf, &buf, limit);
1660 guint32 low = decode_int (buf, &buf, limit);
1664 return ((((guint64)high) << 32) | ((guint64)low));
1668 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1670 return decode_int (buf, endbuf, limit);
1674 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1676 int len = decode_int (buf, &buf, limit);
1684 s = g_malloc (len + 1);
1687 memcpy (s, buf, len);
1696 * Functions to encode protocol data
1700 buffer_init (Buffer *buf, int size)
1702 buf->buf = g_malloc (size);
1704 buf->end = buf->buf + size;
1708 buffer_len (Buffer *buf)
1710 return buf->p - buf->buf;
1714 buffer_make_room (Buffer *buf, int size)
1716 if (buf->end - buf->p < size) {
1717 int new_size = buf->end - buf->buf + size + 32;
1718 guint8 *p = g_realloc (buf->buf, new_size);
1719 size = buf->p - buf->buf;
1722 buf->end = buf->buf + new_size;
1727 buffer_add_byte (Buffer *buf, guint8 val)
1729 buffer_make_room (buf, 1);
1735 buffer_add_short (Buffer *buf, guint32 val)
1737 buffer_make_room (buf, 2);
1738 buf->p [0] = (val >> 8) & 0xff;
1739 buf->p [1] = (val >> 0) & 0xff;
1744 buffer_add_int (Buffer *buf, guint32 val)
1746 buffer_make_room (buf, 4);
1747 buf->p [0] = (val >> 24) & 0xff;
1748 buf->p [1] = (val >> 16) & 0xff;
1749 buf->p [2] = (val >> 8) & 0xff;
1750 buf->p [3] = (val >> 0) & 0xff;
1755 buffer_add_long (Buffer *buf, guint64 l)
1757 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1758 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1762 buffer_add_id (Buffer *buf, int id)
1764 buffer_add_int (buf, (guint64)id);
1768 buffer_add_data (Buffer *buf, guint8 *data, int len)
1770 buffer_make_room (buf, len);
1771 memcpy (buf->p, data, len);
1776 buffer_add_string (Buffer *buf, const char *str)
1781 buffer_add_int (buf, 0);
1784 buffer_add_int (buf, len);
1785 buffer_add_data (buf, (guint8*)str, len);
1790 buffer_add_buffer (Buffer *buf, Buffer *data)
1792 buffer_add_data (buf, data->buf, buffer_len (data));
1796 buffer_free (Buffer *buf)
1802 send_packet (int command_set, int command, Buffer *data)
1808 id = InterlockedIncrement (&packet_id);
1810 len = data->p - data->buf + 11;
1811 buffer_init (&buf, len);
1812 buffer_add_int (&buf, len);
1813 buffer_add_int (&buf, id);
1814 buffer_add_byte (&buf, 0); /* flags */
1815 buffer_add_byte (&buf, command_set);
1816 buffer_add_byte (&buf, command);
1817 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1819 res = transport_send (buf.buf, len);
1827 send_reply_packets (int npackets, ReplyPacket *packets)
1834 for (i = 0; i < npackets; ++i)
1835 len += buffer_len (packets [i].data) + 11;
1836 buffer_init (&buf, len);
1837 for (i = 0; i < npackets; ++i) {
1838 buffer_add_int (&buf, buffer_len (packets [i].data) + 11);
1839 buffer_add_int (&buf, packets [i].id);
1840 buffer_add_byte (&buf, 0x80); /* flags */
1841 buffer_add_byte (&buf, (packets [i].error >> 8) & 0xff);
1842 buffer_add_byte (&buf, packets [i].error);
1843 buffer_add_buffer (&buf, packets [i].data);
1845 res = transport_send (buf.buf, len);
1853 send_reply_packet (int id, int error, Buffer *data)
1857 memset (&packet, 0, sizeof (ReplyPacket));
1859 packet.error = error;
1862 return send_reply_packets (1, &packet);
1866 send_buffered_reply_packets (void)
1870 send_reply_packets (nreply_packets, reply_packets);
1871 for (i = 0; i < nreply_packets; ++i)
1872 buffer_free (reply_packets [i].data);
1873 DEBUG_PRINTF (1, "[dbg] Sent %d buffered reply packets [at=%lx].\n", nreply_packets, (long)mono_100ns_ticks () / 10000);
1878 buffer_reply_packet (int id, int error, Buffer *data)
1882 if (nreply_packets == 128)
1883 send_buffered_reply_packets ();
1885 p = &reply_packets [nreply_packets];
1888 p->data = g_new0 (Buffer, 1);
1889 buffer_init (p->data, buffer_len (data));
1890 buffer_add_buffer (p->data, data);
1899 * Represents an object accessible by the debugger client.
1902 /* Unique id used in the wire protocol to refer to objects */
1905 * A weakref gc handle pointing to the object. The gc handle is used to
1906 * detect if the object was garbage collected.
1911 /* Maps objid -> ObjRef */
1912 static GHashTable *objrefs;
1913 static GHashTable *obj_to_objref;
1914 /* Protected by the dbg lock */
1915 static MonoGHashTable *suspended_objs;
1918 free_objref (gpointer value)
1922 mono_gchandle_free (o->handle);
1930 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1931 obj_to_objref = g_hash_table_new (NULL, NULL);
1932 suspended_objs = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
1933 MONO_GC_REGISTER_ROOT_FIXED (suspended_objs);
1937 objrefs_cleanup (void)
1939 g_hash_table_destroy (objrefs);
1944 * Return an ObjRef for OBJ.
1947 get_objref (MonoObject *obj)
1950 GSList *reflist = NULL, *l;
1956 if (suspend_count) {
1958 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1961 mono_g_hash_table_insert (suspended_objs, obj, NULL);
1965 mono_loader_lock ();
1967 /* FIXME: The tables can grow indefinitely */
1969 if (mono_gc_is_moving ()) {
1971 * Objects can move, so use a hash table mapping hash codes to lists of
1972 * ObjRef structures.
1974 hash = mono_object_hash (obj);
1976 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1977 for (l = reflist; l; l = l->next) {
1979 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1980 mono_loader_unlock ();
1985 /* Use a hash table with masked pointers to internalize object references */
1986 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1987 /* ref might refer to a different object with the same addr which was GCd */
1988 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1989 mono_loader_unlock ();
1994 ref = g_new0 (ObjRef, 1);
1995 ref->id = InterlockedIncrement (&objref_id);
1996 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1998 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
2000 if (mono_gc_is_moving ()) {
2001 reflist = g_slist_append (reflist, ref);
2002 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
2004 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
2007 mono_loader_unlock ();
2013 true_pred (gpointer key, gpointer value, gpointer user_data)
2019 clear_suspended_objs (void)
2022 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
2027 get_objid (MonoObject *obj)
2029 return get_objref (obj)->id;
2033 * Set OBJ to the object identified by OBJID.
2034 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
2038 get_object_allow_null (int objid, MonoObject **obj)
2048 return ERR_INVALID_OBJECT;
2050 mono_loader_lock ();
2052 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
2055 *obj = mono_gchandle_get_target (ref->handle);
2056 mono_loader_unlock ();
2058 return ERR_INVALID_OBJECT;
2061 mono_loader_unlock ();
2062 return ERR_INVALID_OBJECT;
2067 get_object (int objid, MonoObject **obj)
2069 int err = get_object_allow_null (objid, obj);
2074 return ERR_INVALID_OBJECT;
2079 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
2081 return decode_id (buf, endbuf, limit);
2085 buffer_add_objid (Buffer *buf, MonoObject *o)
2087 buffer_add_id (buf, get_objid (o));
2106 * Represents a runtime structure accessible to the debugger client
2109 /* Unique id used in the wire protocol */
2111 /* Domain of the runtime structure, NULL if the domain was unloaded */
2118 MonoAssembly *assembly;
2119 MonoClassField *field;
2121 MonoProperty *property;
2126 /* Maps runtime structure -> Id */
2127 GHashTable *val_to_id [ID_NUM];
2128 /* Classes whose class load event has been sent */
2129 GHashTable *loaded_classes;
2130 /* Maps MonoClass->GPtrArray of file names */
2131 GHashTable *source_files;
2132 /* Maps source file basename -> GSList of classes */
2133 GHashTable *source_file_to_class;
2134 /* Same with ignore-case */
2135 GHashTable *source_file_to_class_ignorecase;
2139 /* Protected by the dbg lock */
2140 static GPtrArray *ids [ID_NUM];
2147 for (i = 0; i < ID_NUM; ++i)
2148 ids [i] = g_ptr_array_new ();
2156 for (i = 0; i < ID_NUM; ++i) {
2158 for (j = 0; j < ids [i]->len; ++j)
2159 g_free (g_ptr_array_index (ids [i], j));
2160 g_ptr_array_free (ids [i], TRUE);
2167 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2169 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
2171 GHashTableIter iter;
2172 GPtrArray *file_names;
2177 for (i = 0; i < ID_NUM; ++i)
2178 if (info->val_to_id [i])
2179 g_hash_table_destroy (info->val_to_id [i]);
2180 g_hash_table_destroy (info->loaded_classes);
2182 g_hash_table_iter_init (&iter, info->source_files);
2183 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2184 for (i = 0; i < file_names->len; ++i)
2185 g_free (g_ptr_array_index (file_names, i));
2186 g_ptr_array_free (file_names, TRUE);
2189 g_hash_table_iter_init (&iter, info->source_file_to_class);
2190 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2195 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2196 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2204 domain_jit_info (domain)->agent_info = NULL;
2206 /* Clear ids referencing structures in the domain */
2208 for (i = 0; i < ID_NUM; ++i) {
2210 for (j = 0; j < ids [i]->len; ++j) {
2211 Id *id = g_ptr_array_index (ids [i], j);
2212 if (id->domain == domain)
2219 mono_loader_lock ();
2220 g_hash_table_remove (domains, domain);
2221 mono_loader_unlock ();
2224 static AgentDomainInfo*
2225 get_agent_domain_info (MonoDomain *domain)
2227 AgentDomainInfo *info = NULL;
2229 mono_domain_lock (domain);
2231 info = domain_jit_info (domain)->agent_info;
2233 info = domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
2234 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2235 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2236 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2237 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2240 mono_domain_unlock (domain);
2246 get_id (MonoDomain *domain, IdType type, gpointer val)
2249 AgentDomainInfo *info;
2254 mono_loader_lock ();
2256 mono_domain_lock (domain);
2258 info = get_agent_domain_info (domain);
2260 if (info->val_to_id [type] == NULL)
2261 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2263 id = g_hash_table_lookup (info->val_to_id [type], val);
2265 mono_domain_unlock (domain);
2266 mono_loader_unlock ();
2272 id = g_new0 (Id, 1);
2274 id->id = ids [type]->len + 1;
2275 id->domain = domain;
2278 g_hash_table_insert (info->val_to_id [type], val, id);
2279 g_ptr_array_add (ids [type], id);
2283 mono_domain_unlock (domain);
2285 mono_loader_unlock ();
2290 static inline gpointer
2291 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
2295 int id = decode_id (buf, endbuf, limit);
2304 // FIXME: error handling
2306 g_assert (id > 0 && id <= ids [type]->len);
2308 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2311 if (res->domain == NULL) {
2312 DEBUG_PRINTF (1, "ERR_UNLOADED, id=%d, type=%d.\n", id, type);
2313 *err = ERR_UNLOADED;
2318 *domain = res->domain;
2320 return res->data.val;
2324 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2326 int id = get_id (domain, type, val);
2328 buffer_add_id (buf, id);
2332 static inline MonoClass*
2333 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2337 klass = decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2338 if (G_UNLIKELY (log_level >= 2) && klass) {
2341 s = mono_type_full_name (&klass->byval_arg);
2342 DEBUG_PRINTF (2, "[dbg] recv class [%s]\n", s);
2348 static inline MonoAssembly*
2349 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2351 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2354 static inline MonoImage*
2355 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2357 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2360 static inline MonoMethod*
2361 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2365 m = decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2366 if (G_UNLIKELY (log_level >= 2) && m) {
2369 s = mono_method_full_name (m, TRUE);
2370 DEBUG_PRINTF (2, "[dbg] recv method [%s]\n", s);
2376 static inline MonoClassField*
2377 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2379 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2382 static inline MonoDomain*
2383 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2385 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2388 static inline MonoProperty*
2389 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2391 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2395 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2397 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2398 if (G_UNLIKELY (log_level >= 2) && klass) {
2401 s = mono_type_full_name (&klass->byval_arg);
2402 if (GetCurrentThreadId () == debugger_thread_id)
2403 DEBUG_PRINTF (2, "[dbg] send class [%s]\n", s);
2405 DEBUG_PRINTF (2, "[%p] send class [%s]\n", (gpointer)GetCurrentThreadId (), s);
2411 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2413 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2414 if (G_UNLIKELY (log_level >= 2) && method) {
2417 s = mono_method_full_name (method, 1);
2418 DEBUG_PRINTF (2, "[dbg] send method [%s]\n", s);
2424 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2428 id = buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2429 if (G_UNLIKELY (log_level >= 2) && assembly)
2430 DEBUG_PRINTF (2, "[dbg] send assembly [%s][%s][%d]\n", assembly->aname.name, domain->friendly_name, id);
2434 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2436 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2440 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2442 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2446 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2448 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2452 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2454 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2457 static void invoke_method (void);
2464 * save_thread_context:
2466 * Set CTX as the current threads context which is used for computing stack traces.
2467 * This function is signal-safe.
2470 save_thread_context (MonoContext *ctx)
2472 DebuggerTlsData *tls;
2474 tls = mono_native_tls_get_value (debugger_tls_id);
2478 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2480 mono_thread_state_init_from_current (&tls->context);
2483 /* Number of threads suspended */
2485 * If this is equal to the size of thread_to_tls, the runtime is considered
2488 static gint32 threads_suspend_count;
2490 static mono_mutex_t suspend_mutex;
2492 /* Cond variable used to wait for suspend_count becoming 0 */
2493 static mono_cond_t suspend_cond;
2495 /* Semaphore used to wait for a thread becoming suspended */
2496 static MonoSemType suspend_sem;
2501 mono_mutex_init (&suspend_mutex);
2502 mono_cond_init (&suspend_cond, NULL);
2503 MONO_SEM_INIT (&suspend_sem, 0);
2508 StackFrameInfo last_frame;
2509 gboolean last_frame_set;
2512 } GetLastFrameUserData;
2515 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2517 GetLastFrameUserData *data = user_data;
2519 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
2522 if (!data->last_frame_set) {
2523 /* Store the last frame */
2524 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2525 data->last_frame_set = TRUE;
2528 /* Store the context/lmf for the frame above the last frame */
2529 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2530 data->lmf = info->lmf;
2538 * Process interruption of a thread. If SIGCTX is set, process the current thread. If
2539 * INFO is set, process the thread described by INFO.
2540 * This should be signal safe.
2543 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, void *sigctx, MonoJitInfo *ji)
2547 MonoNativeThreadId tid;
2550 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2551 * guarantee the signal handler will be called that many times. Instead of tracking
2552 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2553 * has been requested that hasn't been handled yet, otherwise we can have threads
2554 * refuse to die when VM_EXIT is called
2556 #if defined(__APPLE__)
2557 if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
2561 * We use interrupt_count to determine whenever this interrupt should be processed
2562 * by us or the normal interrupt processing code in the signal handler.
2563 * There is no race here with notify_thread (), since the signal is sent after
2564 * incrementing interrupt_count.
2566 if (tls->interrupt_count == 0)
2569 InterlockedDecrement (&tls->interrupt_count);
2573 ip = mono_arch_ip_from_context (sigctx);
2575 ip = MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx);
2580 tid = mono_thread_info_get_tid (info);
2582 tid = (MonoNativeThreadId)GetCurrentThreadId ();
2584 // FIXME: Races when the thread leaves managed code before hitting a single step
2588 /* Running managed code, will be suspended by the single step code */
2589 DEBUG_PRINTF (1, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip);
2593 * Running native code, will be suspended when it returns to/enters
2594 * managed code. Treat it as already suspended.
2595 * This might interrupt the code in process_single_step_inner (), we use the
2596 * tls->suspending flag to avoid races when that happens.
2598 if (!tls->suspended && !tls->suspending) {
2600 GetLastFrameUserData data;
2602 // FIXME: printf is not signal safe, but this is only used during
2603 // debugger debugging
2605 DEBUG_PRINTF (1, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip);
2606 //save_thread_context (&ctx);
2609 /* Already terminated */
2613 * We are in a difficult position: we want to be able to provide stack
2614 * traces for this thread, but we can't use the current ctx+lmf, since
2615 * the thread is still running, so it might return to managed code,
2616 * making these invalid.
2617 * So we start a stack walk and save the first frame, along with the
2618 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2619 * suspended when it returns to managed code, so the parent's ctx should
2622 data.last_frame_set = FALSE;
2624 mono_sigctx_to_monoctx (sigctx, &ctx);
2626 * Don't pass MONO_UNWIND_ACTUAL_METHOD, its not signal safe, and
2627 * get_last_frame () doesn't need it, the last frame cannot be a ginst
2628 * since we are not in a JITted method.
2630 mono_walk_stack_with_ctx (get_last_frame, &ctx, MONO_UNWIND_NONE, &data);
2632 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, mono_thread_info_get_suspend_state (info), MONO_UNWIND_SIGNAL_SAFE, &data);
2634 if (data.last_frame_set) {
2635 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2636 res = mono_thread_state_init_from_monoctx (&tls->async_state, &ctx);
2638 mono_thread_state_init_from_monoctx (&tls->context, &ctx);
2641 memcpy (&tls->async_state.ctx, &data.ctx, sizeof (MonoContext));
2642 tls->async_state.unwind_data [MONO_UNWIND_DATA_LMF] = data.lmf;
2643 tls->async_state.unwind_data [MONO_UNWIND_DATA_JIT_TLS] = ((MonoThreadInfo*)tls->thread->thread_info)->jit_data;
2645 tls->async_state.valid = FALSE;
2648 mono_memory_barrier ();
2650 tls->suspended = TRUE;
2651 MONO_SEM_POST (&suspend_sem);
2658 * mono_debugger_agent_thread_interrupt:
2660 * Called by the abort signal handler.
2661 * Should be signal safe.
2664 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
2666 DebuggerTlsData *tls;
2671 tls = mono_native_tls_get_value (debugger_tls_id);
2673 DEBUG_PRINTF (1, "[%p] Received interrupt with no TLS, continuing.\n", (gpointer)GetCurrentThreadId ());
2677 return thread_interrupt (tls, NULL, sigctx, ji);
2681 static void CALLBACK notify_thread_apc (ULONG_PTR param)
2684 mono_debugger_agent_thread_interrupt (NULL, NULL);
2686 #endif /* HOST_WIN32 */
2689 * reset_native_thread_suspend_state:
2691 * Reset the suspended flag and state on native threads
2694 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2696 DebuggerTlsData *tls = value;
2698 if (!tls->really_suspended && tls->suspended) {
2699 tls->suspended = FALSE;
2701 * The thread might still be running if it was executing native code, so the state won't be invalided by
2702 * suspend_current ().
2704 tls->context.valid = FALSE;
2705 tls->async_state.valid = FALSE;
2706 invalidate_frames (tls);
2711 DebuggerTlsData *tls;
2712 gboolean valid_info;
2715 static SuspendThreadResult
2716 debugger_interrupt_critical (MonoThreadInfo *info, gpointer user_data)
2718 InterruptData *data = user_data;
2721 data->valid_info = TRUE;
2722 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));
2724 thread_interrupt (data->tls, info, NULL, ji);
2725 return MonoResumeThread;
2731 * Notify a thread that it needs to suspend.
2734 notify_thread (gpointer key, gpointer value, gpointer user_data)
2736 MonoInternalThread *thread = key;
2737 DebuggerTlsData *tls = value;
2738 gsize tid = thread->tid;
2743 if (GetCurrentThreadId () == tid || tls->terminated)
2746 DEBUG_PRINTF (1, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid);
2749 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2750 * guarantee the signal handler will be called that many times. Instead of tracking
2751 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2752 * has been requested that hasn't been handled yet, otherwise we can have threads
2753 * refuse to die when VM_EXIT is called
2755 #if defined(__APPLE__)
2756 if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
2760 * Maybe we could use the normal interrupt infrastructure, but that does a lot
2761 * of things like breaking waits etc. which we don't want.
2763 InterlockedIncrement (&tls->interrupt_count);
2766 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2767 if (mono_thread_info_new_interrupt_enabled ()) {
2768 InterruptData interrupt_data = { 0 };
2769 interrupt_data.tls = tls;
2771 mono_thread_info_safe_suspend_and_run ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE, debugger_interrupt_critical, &interrupt_data);
2772 if (!interrupt_data.valid_info) {
2773 DEBUG_PRINTF (1, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid);
2775 * Attached thread which died without detaching.
2777 tls->terminated = TRUE;
2781 // FIXME: Remove this since new interrupt is used on win32 now
2782 QueueUserAPC (notify_thread_apc, thread->handle, (ULONG_PTR)NULL);
2784 res = mono_thread_kill (thread, mono_thread_get_abort_signal ());
2786 DEBUG_PRINTF (1, "[%p] mono_thread_kill () failed for %p: %d...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid, res);
2788 * Attached thread which died without detaching.
2790 tls->terminated = TRUE;
2797 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2799 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2803 if (mono_loader_lock_is_owned_by_self ()) {
2805 * Shortcut for the check in suspend_current (). This speeds up processing
2806 * when executing long running code inside the loader lock, i.e. assembly load
2812 if (debugger_thread_id == GetCurrentThreadId ())
2815 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2816 if (suspend_count - tls->resume_count > 0)
2817 tls->suspending = TRUE;
2819 DEBUG_PRINTF (1, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ());
2821 if (suspend_count - tls->resume_count == 0) {
2823 * We are executing a single threaded invoke but the single step for
2824 * suspending is still active.
2825 * FIXME: This slows down single threaded invokes.
2827 DEBUG_PRINTF (1, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ());
2831 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2833 /* Can't suspend in these methods */
2834 method = jinfo_get_method (ji);
2835 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2838 save_thread_context (ctx);
2846 * Increase the suspend count of the VM. While the suspend count is greater
2847 * than 0, runtime threads are suspended at certain points during execution.
2852 mono_loader_lock ();
2854 mono_mutex_lock (&suspend_mutex);
2858 DEBUG_PRINTF (1, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ());
2860 if (suspend_count == 1) {
2861 // FIXME: Is it safe to call this inside the lock ?
2862 start_single_stepping ();
2863 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2866 mono_mutex_unlock (&suspend_mutex);
2868 if (suspend_count == 1)
2870 * Suspend creation of new threadpool threads, since they cannot run
2872 mono_thread_pool_suspend ();
2874 mono_loader_unlock ();
2880 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2888 g_assert (debugger_thread_id == GetCurrentThreadId ());
2890 mono_loader_lock ();
2892 mono_mutex_lock (&suspend_mutex);
2894 g_assert (suspend_count > 0);
2897 DEBUG_PRINTF (1, "[%p] Resuming vm, suspend count=%d...\n", (gpointer)GetCurrentThreadId (), suspend_count);
2899 if (suspend_count == 0) {
2900 // FIXME: Is it safe to call this inside the lock ?
2901 stop_single_stepping ();
2902 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2905 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2906 err = mono_cond_broadcast (&suspend_cond);
2907 g_assert (err == 0);
2909 mono_mutex_unlock (&suspend_mutex);
2910 //g_assert (err == 0);
2912 if (suspend_count == 0)
2913 mono_thread_pool_resume ();
2915 mono_loader_unlock ();
2921 * Resume just one thread.
2924 resume_thread (MonoInternalThread *thread)
2927 DebuggerTlsData *tls;
2929 g_assert (debugger_thread_id == GetCurrentThreadId ());
2931 mono_loader_lock ();
2933 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2936 mono_mutex_lock (&suspend_mutex);
2938 g_assert (suspend_count > 0);
2940 DEBUG_PRINTF (1, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid);
2942 tls->resume_count += suspend_count;
2945 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2946 * but only the one whose resume_count field is > 0 will be resumed.
2948 err = mono_cond_broadcast (&suspend_cond);
2949 g_assert (err == 0);
2951 mono_mutex_unlock (&suspend_mutex);
2952 //g_assert (err == 0);
2954 mono_loader_unlock ();
2958 free_frames (StackFrame **frames, int nframes)
2962 for (i = 0; i < nframes; ++i) {
2963 if (frames [i]->jit)
2964 mono_debug_free_method_jit_info (frames [i]->jit);
2965 g_free (frames [i]);
2971 invalidate_frames (DebuggerTlsData *tls)
2974 tls = mono_native_tls_get_value (debugger_tls_id);
2977 free_frames (tls->frames, tls->frame_count);
2978 tls->frame_count = 0;
2981 free_frames (tls->restore_frames, tls->restore_frame_count);
2982 tls->restore_frame_count = 0;
2983 tls->restore_frames = NULL;
2989 * Suspend the current thread until the runtime is resumed. If the thread has a
2990 * pending invoke, then the invoke is executed before this function returns.
2993 suspend_current (void)
2998 DebuggerTlsData *tls;
3000 g_assert (debugger_thread_id != GetCurrentThreadId ());
3002 if (mono_loader_lock_is_owned_by_self ()) {
3004 * If we own the loader mutex, can't suspend until we release it, since the
3005 * whole runtime can deadlock otherwise.
3010 tls = mono_native_tls_get_value (debugger_tls_id);
3013 mono_mutex_lock (&suspend_mutex);
3015 tls->suspending = FALSE;
3016 tls->really_suspended = TRUE;
3018 if (!tls->suspended) {
3019 tls->suspended = TRUE;
3020 MONO_SEM_POST (&suspend_sem);
3023 DEBUG_PRINTF (1, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ());
3025 while (suspend_count - tls->resume_count > 0) {
3027 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
3029 mono_mutex_unlock (&suspend_mutex);
3031 mono_mutex_lock (&suspend_mutex);
3037 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
3038 g_assert (err == 0);
3042 tls->suspended = FALSE;
3043 tls->really_suspended = FALSE;
3045 threads_suspend_count --;
3047 mono_mutex_unlock (&suspend_mutex);
3049 DEBUG_PRINTF (1, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ());
3051 if (tls->pending_invoke) {
3052 /* Save the original context */
3053 tls->pending_invoke->has_ctx = TRUE;
3054 tls->pending_invoke->ctx = tls->context.ctx;
3059 /* The frame info becomes invalid after a resume */
3060 tls->context.valid = FALSE;
3061 tls->async_state.valid = FALSE;
3062 invalidate_frames (tls);
3066 count_thread (gpointer key, gpointer value, gpointer user_data)
3068 DebuggerTlsData *tls = value;
3070 if (!tls->suspended && !tls->terminated)
3071 *(int*)user_data = *(int*)user_data + 1;
3075 count_threads_to_wait_for (void)
3079 mono_loader_lock ();
3080 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
3081 mono_loader_unlock ();
3089 * Wait until the runtime is completely suspended.
3092 wait_for_suspend (void)
3094 int nthreads, nwait, err;
3095 gboolean waited = FALSE;
3097 // FIXME: Threads starting/stopping ?
3098 mono_loader_lock ();
3099 nthreads = mono_g_hash_table_size (thread_to_tls);
3100 mono_loader_unlock ();
3103 nwait = count_threads_to_wait_for ();
3105 DEBUG_PRINTF (1, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads);
3106 err = MONO_SEM_WAIT (&suspend_sem);
3107 g_assert (err == 0);
3115 DEBUG_PRINTF (1, "%d threads suspended.\n", nthreads);
3121 * Return whenever the runtime is suspended.
3126 return count_threads_to_wait_for () == 0;
3130 no_seq_points_found (MonoMethod *method)
3133 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3135 printf ("Unable to find seq points for method '%s'.\n", mono_method_full_name (method, TRUE));
3139 DebuggerTlsData *tls;
3141 } ComputeFramesUserData;
3144 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3146 ComputeFramesUserData *ud = user_data;
3148 MonoMethod *method, *actual_method, *api_method;
3152 if (info->type != FRAME_TYPE_MANAGED) {
3153 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3154 /* Mark the last frame as an invoke frame */
3156 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3162 method = jinfo_get_method (info->ji);
3164 method = info->method;
3165 actual_method = info->actual_method;
3166 api_method = method;
3171 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3174 if (info->il_offset == -1) {
3175 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3176 if (ud->frames == NULL) {
3177 if (find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL, &sp))
3178 info->il_offset = sp.il_offset;
3180 if (info->il_offset == -1)
3181 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3184 DEBUG_PRINTF (1, "\tFrame: %s:%x(%x) %d\n", mono_method_full_name (method, TRUE), info->il_offset, info->native_offset, info->managed);
3186 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3187 if (!CHECK_PROTOCOL_VERSION (2, 17))
3188 /* Older clients can't handle this flag */
3190 api_method = mono_marshal_method_from_wrapper (method);
3193 actual_method = api_method;
3194 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3197 frame = g_new0 (StackFrame, 1);
3198 frame->method = method;
3199 frame->actual_method = actual_method;
3200 frame->api_method = api_method;
3201 frame->il_offset = info->il_offset;
3202 frame->native_offset = info->native_offset;
3203 frame->flags = flags;
3204 frame->ji = info->ji;
3205 if (info->reg_locations)
3206 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3209 frame->has_ctx = TRUE;
3211 frame->domain = info->domain;
3213 ud->frames = g_slist_append (ud->frames, frame);
3219 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3221 ComputeFramesUserData *ud = user_data;
3224 * 'tls->filter_ctx' is the location of the throw site.
3226 * mono_walk_stack() will never actually hit the throw site, but unwind
3227 * directly from the filter to the call site; we abort stack unwinding here
3228 * once this happens and resume from the throw site.
3231 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3234 return process_frame (info, ctx, user_data);
3238 * Return a malloc-ed list of StackFrame structures.
3241 compute_frame_info_from (MonoInternalThread *thread, DebuggerTlsData *tls, MonoThreadUnwindState *state, int *out_nframes)
3243 ComputeFramesUserData user_data;
3244 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3249 user_data.tls = tls;
3250 user_data.frames = NULL;
3252 mono_walk_stack_with_state (process_frame, state, opts, &user_data);
3254 nframes = g_slist_length (user_data.frames);
3255 res = g_new0 (StackFrame*, nframes);
3256 l = user_data.frames;
3257 for (i = 0; i < nframes; ++i) {
3261 *out_nframes = nframes;
3267 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3269 ComputeFramesUserData user_data;
3271 int i, findex, new_frame_count;
3272 StackFrame **new_frames, *f;
3273 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3275 // FIXME: Locking on tls
3276 if (tls->frames && tls->frames_up_to_date)
3279 DEBUG_PRINTF (1, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid);
3281 user_data.tls = tls;
3282 user_data.frames = NULL;
3283 if (tls->terminated) {
3284 tls->frame_count = 0;
3286 } if (!tls->really_suspended && tls->async_state.valid) {
3287 /* Have to use the state saved by the signal handler */
3288 process_frame (&tls->async_last_frame, NULL, &user_data);
3289 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3290 } else if (tls->filter_state.valid) {
3292 * We are inside an exception filter.
3294 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3296 if (tls->context.valid)
3297 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3299 * After that, we resume unwinding from the location where the exception has been thrown.
3301 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3302 } else if (tls->context.valid) {
3303 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3306 tls->frame_count = 0;
3310 new_frame_count = g_slist_length (user_data.frames);
3311 new_frames = g_new0 (StackFrame*, new_frame_count);
3313 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3317 * Reuse the id for already existing stack frames, so invokes don't invalidate
3318 * the still valid stack frames.
3320 for (i = 0; i < tls->frame_count; ++i) {
3321 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3322 f->id = tls->frames [i]->id;
3327 if (i >= tls->frame_count)
3328 f->id = InterlockedIncrement (&frame_id);
3330 new_frames [findex ++] = f;
3333 g_slist_free (user_data.frames);
3335 invalidate_frames (tls);
3337 tls->frames = new_frames;
3338 tls->frame_count = new_frame_count;
3339 tls->frames_up_to_date = TRUE;
3343 * GHFunc to emit an appdomain creation event
3344 * @param key Don't care
3345 * @param value A loaded appdomain
3346 * @param user_data Don't care
3349 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3351 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3352 g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
3356 * GHFunc to emit a thread start event
3357 * @param key A thread id
3358 * @param value A thread object
3359 * @param user_data Don't care
3362 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3364 if (GPOINTER_TO_INT (key) != debugger_thread_id)
3365 process_profiler_event (EVENT_KIND_THREAD_START, value);
3369 * GFunc to emit an assembly load event
3370 * @param value A loaded assembly
3371 * @param user_data Don't care
3374 emit_assembly_load (gpointer value, gpointer user_data)
3376 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3380 * GFunc to emit a type load event
3381 * @param value A loaded type
3382 * @param user_data Don't care
3385 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3387 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3391 strdup_tolower (char *s)
3396 for (p = s2; *p; ++p)
3402 * Same as g_path_get_basename () but handles windows paths as well,
3403 * which can occur in .mdb files created by pdb2mdb.
3406 dbg_path_get_basename (const char *filename)
3410 if (!filename || strchr (filename, '/') || !strchr (filename, '\\'))
3411 return g_path_get_basename (filename);
3415 /* No separator -> filename */
3416 r = strrchr (filename, '\\');
3418 return g_strdup (filename);
3420 /* Trailing slash, remove component */
3422 char *copy = g_strdup (filename);
3423 copy [r-filename] = 0;
3424 r = strrchr (copy, '\\');
3428 return g_strdup ("/");
3430 r = g_strdup (&r[1]);
3435 return g_strdup (&r[1]);
3439 init_jit_info_dbg_attrs (MonoJitInfo *ji)
3441 static MonoClass *hidden_klass, *step_through_klass, *non_user_klass;
3442 MonoCustomAttrInfo *ainfo;
3444 if (ji->dbg_attrs_inited)
3447 if (!hidden_klass) {
3448 hidden_klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3449 g_assert (hidden_klass);
3451 if (!step_through_klass) {
3452 step_through_klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3453 g_assert (step_through_klass);
3455 if (!non_user_klass) {
3456 non_user_klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute");
3457 g_assert (non_user_klass);
3460 ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji));
3462 if (mono_custom_attrs_has_attr (ainfo, hidden_klass))
3463 ji->dbg_hidden = TRUE;
3464 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3465 ji->dbg_step_through = TRUE;
3466 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3467 ji->dbg_non_user_code = TRUE;
3468 mono_custom_attrs_free (ainfo);
3471 ainfo = mono_custom_attrs_from_class (jinfo_get_method (ji)->klass);
3473 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3474 ji->dbg_step_through = TRUE;
3475 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3476 ji->dbg_non_user_code = TRUE;
3477 mono_custom_attrs_free (ainfo);
3480 mono_memory_barrier ();
3481 ji->dbg_attrs_inited = TRUE;
3489 * create_event_list:
3491 * Return a list of event request ids matching EVENT, starting from REQS, which
3492 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3494 * We return request ids, instead of requests, to simplify threading, since
3495 * requests could be deleted anytime when the loader lock is not held.
3496 * LOCKING: Assumes the loader lock is held.
3499 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3502 GSList *events = NULL;
3504 *suspend_policy = SUSPEND_POLICY_NONE;
3507 reqs = event_requests;
3512 for (i = 0; i < reqs->len; ++i) {
3513 EventRequest *req = g_ptr_array_index (reqs, i);
3514 if (req->event_kind == event) {
3515 gboolean filtered = FALSE;
3518 for (j = 0; j < req->nmodifiers; ++j) {
3519 Modifier *mod = &req->modifiers [j];
3521 if (mod->kind == MOD_KIND_COUNT) {
3523 if (mod->data.count > 0) {
3524 if (mod->data.count > 0) {
3526 if (mod->data.count == 0)
3530 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3531 if (mod->data.thread != mono_thread_internal_current ())
3533 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3534 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3536 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3538 if (ei->caught && !mod->caught)
3540 if (!ei->caught && !mod->uncaught)
3542 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3544 gboolean found = FALSE;
3545 MonoAssembly **assemblies = mod->data.assemblies;
3548 for (k = 0; assemblies [k]; ++k)
3549 if (assemblies [k] == jinfo_get_method (ji)->klass->image->assembly)
3554 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3555 gpointer iter = NULL;
3557 MonoDebugSourceInfo *sinfo;
3558 char *source_file, *s;
3559 gboolean found = FALSE;
3561 GPtrArray *source_file_list;
3563 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3564 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3567 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
3568 for (i = 0; i < source_file_list->len; ++i) {
3569 sinfo = g_ptr_array_index (source_file_list, i);
3571 * Do a case-insesitive match by converting the file name to
3574 s = strdup_tolower (sinfo->source_file);
3575 if (g_hash_table_lookup (mod->data.source_files, s))
3578 char *s2 = dbg_path_get_basename (sinfo->source_file);
3579 char *s3 = strdup_tolower (s2);
3581 if (g_hash_table_lookup (mod->data.source_files, s3))
3588 g_ptr_array_free (source_file_list, TRUE);
3593 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3596 s = mono_type_full_name (&ei->klass->byval_arg);
3597 if (!g_hash_table_lookup (mod->data.type_names, s))
3600 } else if (mod->kind == MOD_KIND_STEP) {
3601 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3602 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3603 !strcmp (jinfo_get_method (ji)->name, ".cctor") &&
3604 (jinfo_get_method (ji) != ((SingleStepReq*)req->info)->start_method))
3606 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3607 init_jit_info_dbg_attrs (ji);
3611 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3612 init_jit_info_dbg_attrs (ji);
3613 if (ji->dbg_step_through)
3616 if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3617 init_jit_info_dbg_attrs (ji);
3618 if (ji->dbg_non_user_code)
3625 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3626 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3631 /* Send a VM START/DEATH event by default */
3632 if (event == EVENT_KIND_VM_START)
3633 events = g_slist_append (events, GINT_TO_POINTER (0));
3634 if (event == EVENT_KIND_VM_DEATH)
3635 events = g_slist_append (events, GINT_TO_POINTER (0));
3640 static G_GNUC_UNUSED const char*
3641 event_to_string (EventKind event)
3644 case EVENT_KIND_VM_START: return "VM_START";
3645 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3646 case EVENT_KIND_THREAD_START: return "THREAD_START";
3647 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3648 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3649 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3650 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3651 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3652 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3653 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3654 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3655 case EVENT_KIND_STEP: return "STEP";
3656 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3657 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3658 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3659 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3660 case EVENT_KIND_USER_LOG: return "USER_LOG";
3662 g_assert_not_reached ();
3670 * Send an event to the client, suspending the vm if needed.
3671 * LOCKING: Since this can suspend the calling thread, no locks should be held
3673 * The EVENTS list is freed by this function.
3676 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3680 MonoDomain *domain = mono_domain_get ();
3681 MonoThread *thread = NULL;
3682 MonoObject *keepalive_obj = NULL;
3683 gboolean send_success = FALSE;
3688 DEBUG_PRINTF (2, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event));
3692 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3693 // FIXME: We miss those events
3694 DEBUG_PRINTF (2, "VM start event not sent yet: dropping %s\n", event_to_string (event));
3698 if (vm_death_event_sent) {
3699 DEBUG_PRINTF (2, "VM death event has been sent: dropping %s\n", event_to_string (event));
3703 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3704 DEBUG_PRINTF (2, "Mono runtime is shutting down: dropping %s\n", event_to_string (event));
3709 DEBUG_PRINTF (2, "Debugger client is not connected: dropping %s\n", event_to_string (event));
3713 if (event == EVENT_KIND_KEEPALIVE)
3714 suspend_policy = SUSPEND_POLICY_NONE;
3719 if (agent_config.defer) {
3720 /* Make sure the thread id is always set when doing deferred debugging */
3721 if (debugger_thread_id == GetCurrentThreadId ()) {
3722 /* Don't suspend on events from the debugger thread */
3723 suspend_policy = SUSPEND_POLICY_NONE;
3724 thread = mono_thread_get_main ();
3726 else thread = mono_thread_current ();
3728 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3729 // FIXME: Send these with a NULL thread, don't suspend the current thread
3734 nevents = g_slist_length (events);
3735 buffer_init (&buf, 128);
3736 buffer_add_byte (&buf, suspend_policy);
3737 buffer_add_int (&buf, nevents);
3739 for (l = events; l; l = l->next) {
3740 buffer_add_byte (&buf, event); // event kind
3741 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3746 thread = mono_thread_current ();
3748 if (event == EVENT_KIND_VM_START && arg != NULL)
3751 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3754 case EVENT_KIND_THREAD_START:
3755 case EVENT_KIND_THREAD_DEATH:
3757 case EVENT_KIND_APPDOMAIN_CREATE:
3758 case EVENT_KIND_APPDOMAIN_UNLOAD:
3759 buffer_add_domainid (&buf, arg);
3761 case EVENT_KIND_METHOD_ENTRY:
3762 case EVENT_KIND_METHOD_EXIT:
3763 buffer_add_methodid (&buf, domain, arg);
3765 case EVENT_KIND_ASSEMBLY_LOAD:
3766 buffer_add_assemblyid (&buf, domain, arg);
3768 case EVENT_KIND_ASSEMBLY_UNLOAD: {
3769 DebuggerTlsData *tls;
3771 /* The domain the assembly belonged to is not equal to the current domain */
3772 tls = mono_native_tls_get_value (debugger_tls_id);
3774 g_assert (tls->domain_unloading);
3776 buffer_add_assemblyid (&buf, tls->domain_unloading, arg);
3779 case EVENT_KIND_TYPE_LOAD:
3780 buffer_add_typeid (&buf, domain, arg);
3782 case EVENT_KIND_BREAKPOINT:
3783 case EVENT_KIND_STEP:
3784 buffer_add_methodid (&buf, domain, arg);
3785 buffer_add_long (&buf, il_offset);
3787 case EVENT_KIND_VM_START:
3788 buffer_add_domainid (&buf, mono_get_root_domain ());
3790 case EVENT_KIND_VM_DEATH:
3791 if (CHECK_PROTOCOL_VERSION (2, 27))
3792 buffer_add_int (&buf, mono_environment_exitcode_get ());
3794 case EVENT_KIND_EXCEPTION: {
3795 EventInfo *ei = arg;
3796 buffer_add_objid (&buf, ei->exc);
3798 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3799 * later after the suspension. (#12494).
3801 keepalive_obj = ei->exc;
3804 case EVENT_KIND_USER_BREAK:
3806 case EVENT_KIND_USER_LOG: {
3807 EventInfo *ei = arg;
3808 buffer_add_int (&buf, ei->level);
3809 buffer_add_string (&buf, ei->category ? ei->category : "");
3810 buffer_add_string (&buf, ei->message ? ei->message : "");
3813 case EVENT_KIND_KEEPALIVE:
3814 suspend_policy = SUSPEND_POLICY_NONE;
3817 g_assert_not_reached ();
3821 if (event == EVENT_KIND_VM_START) {
3822 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3823 if (!agent_config.defer)
3824 start_debugger_thread ();
3827 if (event == EVENT_KIND_VM_DEATH) {
3828 vm_death_event_sent = TRUE;
3829 suspend_policy = SUSPEND_POLICY_NONE;
3832 if (mono_runtime_is_shutting_down ())
3833 suspend_policy = SUSPEND_POLICY_NONE;
3835 if (suspend_policy != SUSPEND_POLICY_NONE) {
3837 * Save the thread context and start suspending before sending the packet,
3838 * since we could be receiving the resume request before send_packet ()
3841 save_thread_context (ctx);
3845 /* This will keep this object alive */
3846 get_objref (keepalive_obj);
3849 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3853 g_slist_free (events);
3856 if (!send_success) {
3857 DEBUG_PRINTF (2, "Sending command %s failed.\n", event_to_string (event));
3861 if (event == EVENT_KIND_VM_START) {
3862 vm_start_event_sent = TRUE;
3865 DEBUG_PRINTF (1, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer)GetCurrentThreadId (), nevents, event_to_string (event), ecount, suspend_policy);
3867 switch (suspend_policy) {
3868 case SUSPEND_POLICY_NONE:
3870 case SUSPEND_POLICY_ALL:
3873 case SUSPEND_POLICY_EVENT_THREAD:
3877 g_assert_not_reached ();
3882 process_profiler_event (EventKind event, gpointer arg)
3886 EventInfo ei, *ei_arg = NULL;
3888 if (event == EVENT_KIND_TYPE_LOAD) {
3893 mono_loader_lock ();
3894 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3895 mono_loader_unlock ();
3897 process_event (event, arg, 0, NULL, events, suspend_policy);
3901 runtime_initialized (MonoProfiler *prof)
3903 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3904 if (agent_config.defer)
3905 start_debugger_thread ();
3909 runtime_shutdown (MonoProfiler *prof)
3911 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3913 mono_debugger_agent_cleanup ();
3917 thread_startup (MonoProfiler *prof, uintptr_t tid)
3919 MonoInternalThread *thread = mono_thread_internal_current ();
3920 MonoInternalThread *old_thread;
3921 DebuggerTlsData *tls;
3923 if (tid == debugger_thread_id)
3926 g_assert (thread->tid == tid);
3928 mono_loader_lock ();
3929 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3930 mono_loader_unlock ();
3932 if (thread == old_thread) {
3934 * For some reason, thread_startup () might be called for the same thread
3935 * multiple times (attach ?).
3937 DEBUG_PRINTF (1, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid);
3941 * thread_end () might not be called for some threads, and the tid could
3944 DEBUG_PRINTF (1, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid);
3945 mono_loader_lock ();
3946 mono_g_hash_table_remove (thread_to_tls, old_thread);
3947 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3948 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3949 mono_loader_unlock ();
3953 tls = mono_native_tls_get_value (debugger_tls_id);
3955 // FIXME: Free this somewhere
3956 tls = g_new0 (DebuggerTlsData, 1);
3957 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3958 tls->thread = thread;
3959 mono_native_tls_set_value (debugger_tls_id, tls);
3961 DEBUG_PRINTF (1, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3963 mono_loader_lock ();
3964 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3965 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3966 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3967 mono_loader_unlock ();
3969 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3972 * suspend_vm () could have missed this thread, so wait for a resume.
3978 thread_end (MonoProfiler *prof, uintptr_t tid)
3980 MonoInternalThread *thread;
3981 DebuggerTlsData *tls = NULL;
3983 mono_loader_lock ();
3984 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3986 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3987 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3989 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3990 tls->terminated = TRUE;
3991 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3992 MONO_GC_UNREGISTER_ROOT (tls->thread);
3996 mono_loader_unlock ();
3998 /* We might be called for threads started before we registered the start callback */
4000 DEBUG_PRINTF (1, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
4002 if (GetCurrentThreadId () == tid && !mono_native_tls_get_value (debugger_tls_id)) {
4004 * This can happen on darwin since we deregister threads using pthread dtors.
4005 * process_profiler_event () and the code it calls cannot handle a null TLS value.
4010 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
4015 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
4017 mono_loader_lock ();
4018 g_hash_table_insert (domains, domain, domain);
4019 mono_loader_unlock ();
4021 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
4025 appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain)
4027 DebuggerTlsData *tls;
4029 /* This might be called during shutdown on the debugger thread from the CMD_VM_EXIT code */
4030 if (is_debugger_thread ())
4034 * Remember the currently unloading appdomain as it is needed to generate
4035 * proper ids for unloading assemblies.
4037 tls = mono_native_tls_get_value (debugger_tls_id);
4039 tls->domain_unloading = domain;
4043 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
4045 DebuggerTlsData *tls;
4047 if (is_debugger_thread ())
4050 tls = mono_native_tls_get_value (debugger_tls_id);
4052 tls->domain_unloading = NULL;
4054 clear_breakpoints_for_domain (domain);
4056 mono_loader_lock ();
4057 /* Invalidate each thread's frame stack */
4058 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
4059 mono_loader_unlock ();
4061 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
4065 * invalidate_each_thread:
4067 * A GHFunc to invalidate frames.
4068 * value must be a DebuggerTlsData*
4071 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
4073 invalidate_frames (value);
4077 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
4079 /* Sent later in jit_end () */
4081 g_ptr_array_add (pending_assembly_loads, assembly);
4086 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
4088 if (is_debugger_thread ())
4091 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
4093 clear_event_requests_for_assembly (assembly);
4094 clear_types_for_assembly (assembly);
4098 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
4100 #if defined(HOST_WIN32) && !defined(__GNUC__)
4101 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
4103 gpointer stackptr = __builtin_frame_address (1);
4105 MonoInternalThread *thread = mono_thread_internal_current ();
4106 DebuggerTlsData *tls;
4108 mono_loader_lock ();
4110 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4111 /* Could be the debugger thread with assembly/type load hooks */
4113 tls->invoke_addr = stackptr;
4115 mono_loader_unlock ();
4119 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
4122 #if defined(HOST_WIN32) && !defined(__GNUC__)
4123 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
4125 gpointer stackptr = __builtin_frame_address (1);
4128 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
4132 * We need to stop single stepping when exiting a runtime invoke, since if it is
4133 * a step out, it may return to native code, and thus never end.
4135 mono_loader_lock ();
4136 ss_invoke_addr = NULL;
4138 for (i = 0; i < event_requests->len; ++i) {
4139 EventRequest *req = g_ptr_array_index (event_requests, i);
4141 if (req->event_kind == EVENT_KIND_STEP) {
4142 ss_destroy (req->info);
4143 g_ptr_array_remove_index_fast (event_requests, i);
4148 mono_loader_unlock ();
4152 send_type_load (MonoClass *klass)
4154 gboolean type_load = FALSE;
4155 MonoDomain *domain = mono_domain_get ();
4156 AgentDomainInfo *info = NULL;
4158 mono_loader_lock ();
4159 mono_domain_lock (domain);
4161 info = get_agent_domain_info (domain);
4163 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
4165 g_hash_table_insert (info->loaded_classes, klass, klass);
4168 mono_domain_unlock (domain);
4169 mono_loader_unlock ();
4171 emit_type_load (klass, klass, NULL);
4175 * Emit load events for all types currently loaded in the domain.
4176 * Takes the loader and domain locks.
4177 * user_data is unused.
4180 send_types_for_domain (MonoDomain *domain, void *user_data)
4182 AgentDomainInfo *info = NULL;
4184 mono_loader_lock ();
4185 mono_domain_lock (domain);
4186 info = get_agent_domain_info (domain);
4188 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4189 mono_domain_unlock (domain);
4190 mono_loader_unlock ();
4194 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
4197 * We emit type load events when the first method of the type is JITted,
4198 * since the class load profiler callbacks might be called with the
4199 * loader lock held. They could also occur in the debugger thread.
4200 * Same for assembly load events.
4203 MonoAssembly *assembly = NULL;
4205 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4207 if (pending_assembly_loads->len > 0) {
4208 assembly = g_ptr_array_index (pending_assembly_loads, 0);
4209 g_ptr_array_remove_index (pending_assembly_loads, 0);
4214 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4220 send_type_load (method->klass);
4223 add_pending_breakpoints (method, jinfo);
4227 * BREAKPOINTS/SINGLE STEPPING
4231 * Contains information about an inserted breakpoint.
4234 long il_offset, native_offset;
4238 } BreakpointInstance;
4241 * Contains generic information about a breakpoint.
4245 * The method where the breakpoint is placed. Can be NULL in which case it
4246 * is inserted into every method. This is used to implement method entry/
4247 * exit events. Can be a generic method definition, in which case the
4248 * breakpoint is inserted into every instance.
4254 * A list of BreakpointInstance structures describing where the breakpoint
4255 * was inserted. There could be more than one because of
4256 * generics/appdomains/method entry/exit.
4258 GPtrArray *children;
4261 /* List of breakpoints */
4262 static GPtrArray *breakpoints;
4263 /* Maps breakpoint locations to the number of breakpoints at that location */
4264 static GHashTable *bp_locs;
4267 breakpoints_init (void)
4269 breakpoints = g_ptr_array_new ();
4270 bp_locs = g_hash_table_new (NULL, NULL);
4274 * insert_breakpoint:
4276 * Insert the breakpoint described by BP into the method described by
4280 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4283 BreakpointInstance *inst;
4284 SeqPointIterator it;
4285 gboolean it_has_sp = FALSE;
4288 mono_error_init (error);
4290 seq_point_iterator_init (&it, seq_points);
4291 while (seq_point_iterator_next (&it)) {
4292 if (it.seq_point.il_offset == bp->il_offset) {
4300 * The set of IL offsets with seq points doesn't completely match the
4301 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4303 seq_point_iterator_init (&it, seq_points);
4304 while (seq_point_iterator_next (&it)) {
4305 if (it.seq_point.il_offset != METHOD_ENTRY_IL_OFFSET &&
4306 it.seq_point.il_offset != METHOD_EXIT_IL_OFFSET &&
4307 it.seq_point.il_offset + 1 == bp->il_offset) {
4315 char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d", mono_method_full_name (jinfo_get_method (ji), TRUE), bp->il_offset);
4317 seq_point_iterator_init (&it, seq_points);
4318 while (seq_point_iterator_next (&it))
4319 DEBUG_PRINTF (1, "%d\n", it.seq_point.il_offset);
4322 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4323 g_warning ("%s", s);
4327 g_warning ("%s", s);
4333 inst = g_new0 (BreakpointInstance, 1);
4334 inst->il_offset = it.seq_point.il_offset;
4335 inst->native_offset = it.seq_point.native_offset;
4336 inst->ip = (guint8*)ji->code_start + it.seq_point.native_offset;
4338 inst->domain = domain;
4340 mono_loader_lock ();
4342 g_ptr_array_add (bp->children, inst);
4344 mono_loader_unlock ();
4347 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4348 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4351 if (it.seq_point.native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4352 DEBUG_PRINTF (1, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset);
4353 } else if (count == 0) {
4354 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4355 mono_arch_set_breakpoint (ji, inst->ip);
4361 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);
4365 remove_breakpoint (BreakpointInstance *inst)
4367 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4369 MonoJitInfo *ji = inst->ji;
4370 guint8 *ip = inst->ip;
4373 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4374 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4377 g_assert (count > 0);
4379 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4380 mono_arch_clear_breakpoint (ji, ip);
4381 DEBUG_PRINTF (1, "[dbg] Clear breakpoint at %s [%p].\n", mono_method_full_name (jinfo_get_method (ji), TRUE), ip);
4388 static inline gboolean
4389 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4395 if (method == bp->method)
4397 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4400 if (bp->method->is_inflated && method->is_inflated) {
4401 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4402 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4404 /* Open generic methods should match closed generic methods of the same class */
4405 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4406 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4407 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4409 /* FIXME: Handle !mvar */
4410 if (t1->type != MONO_TYPE_MVAR)
4421 * add_pending_breakpoints:
4423 * Insert pending breakpoints into the newly JITted method METHOD.
4426 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4429 MonoSeqPointInfo *seq_points;
4431 MonoMethod *jmethod;
4436 domain = mono_domain_get ();
4438 mono_loader_lock ();
4440 for (i = 0; i < breakpoints->len; ++i) {
4441 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4442 gboolean found = FALSE;
4444 if (!bp_matches_method (bp, method))
4447 for (j = 0; j < bp->children->len; ++j) {
4448 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4455 jmethod = jinfo_get_method (ji);
4456 mono_domain_lock (domain);
4457 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, jmethod);
4458 if (!seq_points && jmethod->is_inflated)
4459 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (jmethod));
4460 mono_domain_unlock (domain);
4462 /* Could be AOT code */
4464 g_assert (seq_points);
4466 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4470 mono_loader_unlock ();
4474 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4480 mono_error_init (error);
4482 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4484 /* Might be AOTed code */
4485 code = mono_aot_get_method (domain, method);
4487 ji = mono_jit_info_table_find (domain, code);
4492 insert_breakpoint (seq_points, domain, ji, bp, error);
4496 clear_breakpoint (MonoBreakpoint *bp);
4501 * Set a breakpoint at IL_OFFSET in METHOD.
4502 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4503 * METHOD can also be a generic method definition, in which case a breakpoint
4504 * is placed in all instances of the method.
4505 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4508 static MonoBreakpoint*
4509 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4512 GHashTableIter iter, iter2;
4515 MonoSeqPointInfo *seq_points;
4518 mono_error_init (error);
4521 // - suspend/resume the vm to prevent code patching problems
4522 // - multiple breakpoints on the same location
4523 // - dynamic methods
4526 bp = g_new0 (MonoBreakpoint, 1);
4527 bp->method = method;
4528 bp->il_offset = il_offset;
4530 bp->children = g_ptr_array_new ();
4532 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);
4534 mono_loader_lock ();
4536 g_hash_table_iter_init (&iter, domains);
4537 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4538 mono_domain_lock (domain);
4540 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4541 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4542 if (bp_matches_method (bp, m))
4543 set_bp_in_method (domain, m, seq_points, bp, error);
4546 mono_domain_unlock (domain);
4549 mono_loader_unlock ();
4551 mono_loader_lock ();
4552 g_ptr_array_add (breakpoints, bp);
4553 mono_loader_unlock ();
4555 if (error && !mono_error_ok (error)) {
4556 clear_breakpoint (bp);
4564 clear_breakpoint (MonoBreakpoint *bp)
4568 // FIXME: locking, races
4569 for (i = 0; i < bp->children->len; ++i) {
4570 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4572 remove_breakpoint (inst);
4577 mono_loader_lock ();
4578 g_ptr_array_remove (breakpoints, bp);
4579 mono_loader_unlock ();
4581 g_ptr_array_free (bp->children, TRUE);
4586 breakpoints_cleanup (void)
4590 mono_loader_lock ();
4592 while (i < event_requests->len) {
4593 EventRequest *req = g_ptr_array_index (event_requests, i);
4595 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4596 clear_breakpoint (req->info);
4597 g_ptr_array_remove_index_fast (event_requests, i);
4604 for (i = 0; i < breakpoints->len; ++i)
4605 g_free (g_ptr_array_index (breakpoints, i));
4607 g_ptr_array_free (breakpoints, TRUE);
4608 g_hash_table_destroy (bp_locs);
4613 mono_loader_unlock ();
4617 * clear_breakpoints_for_domain:
4619 * Clear breakpoint instances which reference DOMAIN.
4622 clear_breakpoints_for_domain (MonoDomain *domain)
4626 /* This could be called after shutdown */
4630 mono_loader_lock ();
4631 for (i = 0; i < breakpoints->len; ++i) {
4632 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4635 while (j < bp->children->len) {
4636 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4638 if (inst->domain == domain) {
4639 remove_breakpoint (inst);
4643 g_ptr_array_remove_index_fast (bp->children, j);
4649 mono_loader_unlock ();
4655 * Return FALSE if single stepping needs to continue.
4658 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp, DebuggerTlsData *tls, MonoContext *ctx)
4660 MonoDebugMethodInfo *minfo;
4661 MonoDebugSourceLocation *loc = NULL;
4662 gboolean hit = TRUE;
4665 if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK)) {
4667 * These seq points are inserted by the JIT after calls, step over needs to skip them.
4669 DEBUG_PRINTF (1, "[%p] Seq point at nonempty stack %x while stepping over, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset);
4673 if (req->depth == STEP_DEPTH_OVER && hit) {
4674 if (!tls->context.valid)
4675 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4676 compute_frame_info (tls->thread, tls);
4677 if (req->nframes && tls->frame_count && tls->frame_count > req->nframes) {
4678 /* Hit the breakpoint in a recursive call */
4679 DEBUG_PRINTF (1, "[%p] Breakpoint at lower frame while stepping over, continuing single stepping.\n", (gpointer)GetCurrentThreadId ());
4684 if (req->depth == STEP_DEPTH_INTO && req->size == STEP_SIZE_MIN && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) && ss_req->start_method){
4685 method = jinfo_get_method (ji);
4686 if (!tls->context.valid)
4687 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4688 compute_frame_info (tls->thread, tls);
4689 if (ss_req->start_method == method && req->nframes && tls->frame_count == req->nframes) {//Check also frame count(could be recursion)
4690 DEBUG_PRINTF (1, "[%p] Seq point at nonempty stack %x while stepping in, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset);
4695 if (req->size != STEP_SIZE_LINE)
4698 /* Have to check whenever a different source line was reached */
4699 method = jinfo_get_method (ji);
4700 minfo = mono_debug_lookup_method (method);
4703 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4706 DEBUG_PRINTF (1, "[%p] No line number info for il offset %x, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset);
4707 ss_req->last_method = method;
4709 } else if (loc && method == ss_req->last_method && loc->row == ss_req->last_line) {
4710 DEBUG_PRINTF (1, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer)GetCurrentThreadId (), loc->row);
4715 ss_req->last_method = method;
4716 ss_req->last_line = loc->row;
4717 mono_debug_free_source_location (loc);
4724 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4726 return bp->method && bp->method->klass->image->assembly == assembly;
4730 process_breakpoint_inner (DebuggerTlsData *tls, gboolean from_signal)
4734 int i, j, suspend_policy;
4735 guint32 native_offset;
4737 BreakpointInstance *inst;
4738 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4739 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4740 EventKind kind = EVENT_KIND_BREAKPOINT;
4741 MonoContext *ctx = &tls->restore_state.ctx;
4743 MonoSeqPointInfo *info;
4747 // FIXME: Speed this up
4749 ip = MONO_CONTEXT_GET_IP (ctx);
4750 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4752 method = jinfo_get_method (ji);
4754 /* Compute the native offset of the breakpoint from the ip */
4755 native_offset = ip - (guint8*)ji->code_start;
4758 * Skip the instruction causing the breakpoint signal.
4761 mono_arch_skip_breakpoint (ctx, ji);
4763 if (method->wrapper_type || tls->disable_breakpoints)
4766 bp_reqs = g_ptr_array_new ();
4767 ss_reqs = g_ptr_array_new ();
4768 ss_reqs_orig = g_ptr_array_new ();
4770 mono_loader_lock ();
4773 * The ip points to the instruction causing the breakpoint event, which is after
4774 * the offset recorded in the seq point map, so find the prev seq point before ip.
4776 found_sp = find_prev_seq_point_for_native_offset (mono_domain_get (), method, native_offset, &info, &sp);
4779 no_seq_points_found (method);
4781 g_assert (found_sp);
4783 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);
4786 for (i = 0; i < breakpoints->len; ++i) {
4787 bp = g_ptr_array_index (breakpoints, i);
4792 for (j = 0; j < bp->children->len; ++j) {
4793 inst = g_ptr_array_index (bp->children, j);
4794 if (inst->ji == ji && inst->il_offset == sp.il_offset && inst->native_offset == sp.native_offset) {
4795 if (bp->req->event_kind == EVENT_KIND_STEP) {
4796 g_ptr_array_add (ss_reqs_orig, bp->req);
4798 g_ptr_array_add (bp_reqs, bp->req);
4803 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4804 /* Maybe a method entry/exit event */
4805 if (sp.il_offset == METHOD_ENTRY_IL_OFFSET)
4806 kind = EVENT_KIND_METHOD_ENTRY;
4807 else if (sp.il_offset == METHOD_EXIT_IL_OFFSET)
4808 kind = EVENT_KIND_METHOD_EXIT;
4811 /* Process single step requests */
4812 for (i = 0; i < ss_reqs_orig->len; ++i) {
4813 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4814 SingleStepReq *ss_req = req->info;
4817 if (mono_thread_internal_current () != ss_req->thread)
4820 hit = ss_update (ss_req, ji, &sp, tls, ctx);
4822 g_ptr_array_add (ss_reqs, req);
4824 /* Start single stepping again from the current sequence point */
4825 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
4828 if (ss_reqs->len > 0)
4829 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4830 if (bp_reqs->len > 0)
4831 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4832 if (kind != EVENT_KIND_BREAKPOINT)
4833 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4835 mono_loader_unlock ();
4837 g_ptr_array_free (bp_reqs, TRUE);
4838 g_ptr_array_free (ss_reqs, TRUE);
4841 * FIXME: The first event will suspend, so the second will only be sent after the
4845 process_event (EVENT_KIND_STEP, method, 0, ctx, ss_events, suspend_policy);
4847 process_event (kind, method, 0, ctx, bp_events, suspend_policy);
4848 if (enter_leave_events)
4849 process_event (kind, method, 0, ctx, enter_leave_events, suspend_policy);
4852 /* Process a breakpoint/single step event after resuming from a signal handler */
4854 process_signal_event (void (*func) (DebuggerTlsData*, gboolean))
4856 DebuggerTlsData *tls;
4857 MonoThreadUnwindState orig_restore_state;
4860 tls = mono_native_tls_get_value (debugger_tls_id);
4861 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4862 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4863 mono_thread_state_init_from_monoctx (&tls->restore_state, &tls->handler_ctx);
4867 /* This is called when resuming from a signal handler, so it shouldn't return */
4868 memcpy (&ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4869 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4870 mono_restore_context (&ctx);
4871 g_assert_not_reached ();
4875 process_breakpoint (void)
4877 process_signal_event (process_breakpoint_inner);
4881 resume_from_signal_handler (void *sigctx, void *func)
4883 DebuggerTlsData *tls;
4886 /* Save the original context in TLS */
4887 // FIXME: This might not work on an altstack ?
4888 tls = mono_native_tls_get_value (debugger_tls_id);
4890 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer)GetCurrentThreadId ());
4893 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4894 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4895 // clob:c could be added to op_seq_point.
4897 mono_sigctx_to_monoctx (sigctx, &ctx);
4898 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4899 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4900 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4902 MONO_CONTEXT_SET_IP (&ctx, func);
4904 mono_monoctx_to_sigctx (&ctx, sigctx);
4906 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4907 mono_ppc_set_func_into_sigctx (sigctx, func);
4912 mono_debugger_agent_breakpoint_hit (void *sigctx)
4915 * We are called from a signal handler, and running code there causes all kinds of
4916 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4917 * So set up the signal context to return to the real breakpoint handler function.
4919 resume_from_signal_handler (sigctx, process_breakpoint);
4923 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4925 if (frame->managed) {
4926 *(MonoContext*)data = *ctx;
4935 * Called by System.Diagnostics.Debugger:Break ().
4938 mono_debugger_agent_user_break (void)
4940 if (agent_config.enabled) {
4945 /* Obtain a context */
4946 MONO_CONTEXT_SET_IP (&ctx, NULL);
4947 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4948 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4950 mono_loader_lock ();
4951 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4952 mono_loader_unlock ();
4954 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4961 ss_depth_to_string (StepDepth depth)
4964 case STEP_DEPTH_OVER:
4966 case STEP_DEPTH_OUT:
4968 case STEP_DEPTH_INTO:
4971 g_assert_not_reached ();
4977 process_single_step_inner (DebuggerTlsData *tls, gboolean from_signal)
4982 int il_offset, suspend_policy;
4985 MonoContext *ctx = &tls->restore_state.ctx;
4988 MonoSeqPointInfo *info;
4990 ip = MONO_CONTEXT_GET_IP (ctx);
4992 /* Skip the instruction causing the single step */
4994 mono_arch_skip_single_step (ctx);
4996 if (suspend_count > 0) {
4997 process_suspend (tls, ctx);
5002 // FIXME: A suspend race
5005 if (mono_thread_internal_current () != ss_req->thread)
5008 if (log_level > 0) {
5009 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
5011 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);
5014 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
5016 method = jinfo_get_method (ji);
5019 if (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
5024 * Stopping in memset makes half-initialized vtypes visible.
5025 * Stopping in memcpy makes half-copied vtypes visible.
5027 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
5031 * The ip points to the instruction causing the single step event, which is before
5032 * the offset recorded in the seq point map, so find the next seq point after ip.
5034 if (!find_next_seq_point_for_native_offset (domain, method, (guint8*)ip - (guint8*)ji->code_start, &info, &sp))
5037 il_offset = sp.il_offset;
5039 if (!ss_update (ss_req, ji, &sp, tls, ctx))
5042 /* Start single stepping again from the current sequence point */
5043 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
5045 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
5046 (method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
5047 !strcmp (method->name, ".cctor"))
5050 // FIXME: Has to lock earlier
5052 reqs = g_ptr_array_new ();
5054 mono_loader_lock ();
5056 g_ptr_array_add (reqs, ss_req->req);
5058 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
5060 g_ptr_array_free (reqs, TRUE);
5062 mono_loader_unlock ();
5064 process_event (EVENT_KIND_STEP, jinfo_get_method (ji), il_offset, ctx, events, suspend_policy);
5068 process_single_step (void)
5070 process_signal_event (process_single_step_inner);
5074 * mono_debugger_agent_single_step_event:
5076 * Called from a signal handler to handle a single step event.
5079 mono_debugger_agent_single_step_event (void *sigctx)
5081 /* Resume to process_single_step through the signal context */
5083 // FIXME: Since step out/over is implemented using step in, the step in case should
5084 // be as fast as possible. Move the relevant code from process_single_step_inner ()
5087 if (GetCurrentThreadId () == debugger_thread_id) {
5089 * This could happen despite our best effors when the runtime calls
5090 * assembly/type resolve hooks.
5091 * FIXME: Breakpoints too.
5095 mono_sigctx_to_monoctx (sigctx, &ctx);
5096 mono_arch_skip_single_step (&ctx);
5097 mono_monoctx_to_sigctx (&ctx, sigctx);
5101 resume_from_signal_handler (sigctx, process_single_step);
5105 debugger_agent_single_step_from_context (MonoContext *ctx)
5107 DebuggerTlsData *tls;
5108 MonoThreadUnwindState orig_restore_state;
5110 tls = mono_native_tls_get_value (debugger_tls_id);
5113 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
5114 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5115 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5117 process_single_step_inner (tls, FALSE);
5119 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5120 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5124 debugger_agent_breakpoint_from_context (MonoContext *ctx)
5126 DebuggerTlsData *tls;
5127 MonoThreadUnwindState orig_restore_state;
5129 tls = mono_native_tls_get_value (debugger_tls_id);
5131 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoContext));
5132 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5134 process_breakpoint_inner (tls, FALSE);
5136 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5137 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5141 * start_single_stepping:
5143 * Turn on single stepping. Can be called multiple times, for example,
5144 * by a single step event request + a suspend.
5147 start_single_stepping (void)
5149 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5150 int val = InterlockedIncrement (&ss_count);
5153 mono_arch_start_single_stepping ();
5155 if (ss_req != NULL && ss_invoke_addr == NULL) {
5156 DebuggerTlsData *tls;
5158 mono_loader_lock ();
5160 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
5161 ss_invoke_addr = tls->invoke_addr;
5163 mono_loader_unlock ();
5166 g_assert_not_reached ();
5171 stop_single_stepping (void)
5173 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5174 int val = InterlockedDecrement (&ss_count);
5177 mono_arch_stop_single_stepping ();
5179 ss_invoke_addr = NULL;
5181 g_assert_not_reached ();
5188 * Stop the single stepping operation given by SS_REQ.
5191 ss_stop (SingleStepReq *ss_req)
5196 for (l = ss_req->bps; l; l = l->next) {
5197 clear_breakpoint (l->data);
5199 g_slist_free (ss_req->bps);
5203 if (ss_req->global) {
5204 stop_single_stepping ();
5205 ss_req->global = FALSE;
5212 * Start the single stepping operation given by SS_REQ from the sequence point SP.
5213 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
5214 * belong to the same thread as CTX.
5215 * If FRAMES is not-null, use that instead of tls->frames for placing breakpoints etc.
5218 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint* sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls,
5219 gboolean step_to_catch, StackFrame **frames, int nframes)
5221 int i, j, frame_index;
5222 SeqPoint *next_sp, *parent_sp = NULL;
5223 SeqPoint local_sp, local_parent_sp;
5226 MonoSeqPointInfo *parent_info;
5227 MonoMethod *parent_sp_method = NULL;
5228 gboolean enable_global = FALSE;
5230 /* Stop the previous operation */
5234 * Implement single stepping using breakpoints if possible.
5236 if (step_to_catch) {
5237 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
5238 ss_req->bps = g_slist_append (ss_req->bps, bp);
5242 if (ctx && !frames) {
5243 /* Need parent frames */
5244 if (!tls->context.valid)
5245 mono_thread_state_init_from_monoctx (&tls->context, ctx);
5246 compute_frame_info (tls->thread, tls);
5247 frames = tls->frames;
5248 nframes = tls->frame_count;
5252 * Find the first sequence point in the current or in a previous frame which
5253 * is not the last in its method.
5255 if (ss_req->depth == STEP_DEPTH_OUT) {
5256 /* Ignore seq points in current method */
5257 while (frame_index < nframes) {
5258 StackFrame *frame = frames [frame_index];
5260 method = frame->method;
5261 found_sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5262 sp = (found_sp)? &local_sp : NULL;
5264 if (sp && sp->next_len != 0)
5267 // There could be method calls before the next seq point in the caller when using nested calls
5268 //enable_global = TRUE;
5270 if (sp && sp->next_len == 0) {
5272 while (frame_index < nframes) {
5273 StackFrame *frame = frames [frame_index];
5275 method = frame->method;
5276 found_sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5277 sp = (found_sp)? &local_sp : NULL;
5278 if (sp && sp->next_len != 0)
5284 /* Have to put a breakpoint into a parent frame since the seq points might not cover all control flow out of the method */
5285 while (frame_index < nframes) {
5286 StackFrame *frame = frames [frame_index];
5288 parent_sp_method = frame->method;
5289 found_sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &parent_info, &local_parent_sp);
5290 parent_sp = found_sp ? &local_parent_sp : NULL;
5291 if (found_sp && parent_sp->next_len != 0)
5299 if (sp && sp->next_len > 0) {
5300 SeqPoint* next = g_new(SeqPoint, sp->next_len);
5302 seq_point_init_next (info, *sp, next);
5303 for (i = 0; i < sp->next_len; i++) {
5306 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
5307 ss_req->bps = g_slist_append (ss_req->bps, bp);
5313 SeqPoint* next = g_new(SeqPoint, parent_sp->next_len);
5315 seq_point_init_next (parent_info, *parent_sp, next);
5316 for (i = 0; i < parent_sp->next_len; i++) {
5319 bp = set_breakpoint (parent_sp_method, next_sp->il_offset, ss_req->req, NULL);
5320 ss_req->bps = g_slist_append (ss_req->bps, bp);
5325 if (ss_req->nframes == 0)
5326 ss_req->nframes = nframes;
5328 if ((ss_req->depth == STEP_DEPTH_OVER) && (!sp && !parent_sp)) {
5329 DEBUG_PRINTF (1, "[dbg] No parent frame for step over, transition to step into.\n");
5331 * This is needed since if we leave managed code, and later return to it, step over
5332 * is not going to stop.
5333 * This approach is a bit ugly, since we change the step depth, but it only affects
5334 * clients who reuse the same step request, and only in this special case.
5336 ss_req->depth = STEP_DEPTH_INTO;
5339 if (ss_req->depth == STEP_DEPTH_OVER) {
5340 /* Need to stop in catch clauses as well */
5341 for (i = 0; i < nframes; ++i) {
5342 StackFrame *frame = frames [i];
5345 MonoJitInfo *jinfo = frame->ji;
5346 for (j = 0; j < jinfo->num_clauses; ++j) {
5347 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5349 found_sp = find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL, &local_sp);
5350 sp = (found_sp)? &local_sp : NULL;
5352 bp = set_breakpoint (frame->method, sp->il_offset, ss_req->req, NULL);
5353 ss_req->bps = g_slist_append (ss_req->bps, bp);
5360 if (ss_req->depth == STEP_DEPTH_INTO) {
5361 /* Enable global stepping so we stop at method entry too */
5362 enable_global = TRUE;
5366 * The ctx/frame info computed above will become invalid when we continue.
5368 tls->context.valid = FALSE;
5369 tls->async_state.valid = FALSE;
5370 invalidate_frames (tls);
5373 if (enable_global) {
5374 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5375 ss_req->global = TRUE;
5376 start_single_stepping ();
5377 } else if (!ss_req->bps) {
5378 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5379 ss_req->global = TRUE;
5380 start_single_stepping ();
5382 ss_req->global = FALSE;
5387 * Start single stepping of thread THREAD
5390 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req)
5392 DebuggerTlsData *tls;
5393 MonoSeqPointInfo *info = NULL;
5394 SeqPoint *sp = NULL;
5397 MonoMethod *method = NULL;
5398 MonoDebugMethodInfo *minfo;
5399 gboolean step_to_catch = FALSE;
5400 gboolean set_ip = FALSE;
5401 StackFrame **frames = NULL;
5404 if (suspend_count == 0)
5405 return ERR_NOT_SUSPENDED;
5407 wait_for_suspend ();
5409 // FIXME: Multiple requests
5411 DEBUG_PRINTF (0, "Received a single step request while the previous one was still active.\n");
5412 return ERR_NOT_IMPLEMENTED;
5415 DEBUG_PRINTF (1, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth));
5417 ss_req = g_new0 (SingleStepReq, 1);
5419 ss_req->thread = thread;
5420 ss_req->size = size;
5421 ss_req->depth = depth;
5422 ss_req->filter = filter;
5425 mono_loader_lock ();
5426 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5427 mono_loader_unlock ();
5429 g_assert (tls->context.valid);
5431 if (tls->restore_state.valid && MONO_CONTEXT_GET_IP (&tls->context.ctx) != MONO_CONTEXT_GET_IP (&tls->restore_state.ctx)) {
5433 * Need to start single stepping from restore_state and not from the current state
5436 frames = compute_frame_info_from (thread, tls, &tls->restore_state, &nframes);
5439 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5441 if (tls->catch_state.valid) {
5443 StackFrameInfo frame;
5444 MonoContext new_ctx;
5445 MonoLMF *lmf = NULL;
5448 * We are stopped at a throw site. Stepping should go to the catch site.
5451 /* Find the the jit info for the catch context */
5452 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);
5454 g_assert (frame.type == FRAME_TYPE_MANAGED);
5457 * Find the seq point corresponding to the landing site ip, which is the first seq
5460 found_sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info, &local_sp);
5461 sp = (found_sp)? &local_sp : NULL;
5463 no_seq_points_found (frame.method);
5466 method = frame.method;
5468 step_to_catch = TRUE;
5469 /* This make sure the seq point is not skipped by process_single_step () */
5470 ss_req->last_sp = NULL;
5473 if (!step_to_catch) {
5474 StackFrame *frame = NULL;
5477 if (frames && nframes)
5480 compute_frame_info (thread, tls);
5482 if (tls->frame_count)
5483 frame = tls->frames [0];
5486 if (ss_req->size == STEP_SIZE_LINE) {
5488 ss_req->last_method = frame->method;
5489 ss_req->last_line = -1;
5491 minfo = mono_debug_lookup_method (frame->method);
5492 if (minfo && frame->il_offset != -1) {
5493 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
5496 ss_req->last_line = loc->row;
5504 if (!method && frame->il_offset != -1) {
5505 /* FIXME: Sort the table and use a binary search */
5506 found_sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5507 sp = (found_sp)? &local_sp : NULL;
5509 no_seq_points_found (frame->method);
5511 method = frame->method;
5516 ss_req->start_method = method;
5518 ss_start (ss_req, method, sp, info, set_ip ? &tls->restore_state.ctx : &tls->context.ctx, tls, step_to_catch, frames, nframes);
5521 free_frames (frames, nframes);
5527 ss_destroy (SingleStepReq *req)
5530 g_assert (ss_req == req);
5539 ss_clear_for_assembly (SingleStepReq *req, MonoAssembly *assembly)
5542 gboolean found = TRUE;
5546 for (l = ss_req->bps; l; l = l->next) {
5547 if (breakpoint_matches_assembly (l->data, assembly)) {
5548 clear_breakpoint (l->data);
5549 ss_req->bps = g_slist_delete_link (ss_req->bps, l);
5558 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5561 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5567 if (!agent_config.enabled)
5570 mono_loader_lock ();
5571 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5572 mono_loader_unlock ();
5575 ei.category = category ? mono_string_to_utf8 (category) : NULL;
5576 ei.message = message ? mono_string_to_utf8 (message) : NULL;
5578 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5580 g_free (ei.category);
5581 g_free (ei.message);
5585 mono_debugger_agent_debug_log_is_enabled (void)
5587 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5588 return agent_config.enabled;
5591 #if defined(PLATFORM_ANDROID) || defined(TARGET_ANDROID)
5593 mono_debugger_agent_unhandled_exception (MonoException *exc)
5602 memset (&ei, 0, sizeof (EventInfo));
5603 ei.exc = (MonoObject*)exc;
5605 mono_loader_lock ();
5606 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5607 mono_loader_unlock ();
5609 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5614 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5615 MonoContext *catch_ctx)
5617 int i, j, suspend_policy;
5619 MonoJitInfo *ji, *catch_ji;
5621 DebuggerTlsData *tls = NULL;
5623 if (thread_to_tls != NULL) {
5624 MonoInternalThread *thread = mono_thread_internal_current ();
5626 mono_loader_lock ();
5627 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5628 mono_loader_unlock ();
5630 if (tls && tls->abort_requested)
5632 if (tls && tls->disable_breakpoints)
5636 memset (&ei, 0, sizeof (EventInfo));
5638 /* Just-In-Time debugging */
5640 if (agent_config.onuncaught && !inited) {
5641 finish_agent_init (FALSE);
5644 * Send an unsolicited EXCEPTION event with a dummy request id.
5646 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5647 ei.exc = (MonoObject*)exc;
5648 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5651 } else if (agent_config.onthrow && !inited) {
5653 gboolean found = FALSE;
5655 for (l = agent_config.onthrow; l; l = l->next) {
5656 char *ex_type = l->data;
5657 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5659 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5666 finish_agent_init (FALSE);
5669 * Send an unsolicited EXCEPTION event with a dummy request id.
5671 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5672 ei.exc = (MonoObject*)exc;
5673 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5681 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5683 catch_ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5687 ei.exc = (MonoObject*)exc;
5688 ei.caught = catch_ctx != NULL;
5690 mono_loader_lock ();
5692 /* Treat exceptions which are caught in non-user code as unhandled */
5693 for (i = 0; i < event_requests->len; ++i) {
5694 EventRequest *req = g_ptr_array_index (event_requests, i);
5695 if (req->event_kind != EVENT_KIND_EXCEPTION)
5698 for (j = 0; j < req->nmodifiers; ++j) {
5699 Modifier *mod = &req->modifiers [j];
5701 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5703 gboolean found = FALSE;
5704 MonoAssembly **assemblies = mod->data.assemblies;
5707 for (k = 0; assemblies [k]; ++k)
5708 if (assemblies [k] == jinfo_get_method (catch_ji)->klass->image->assembly)
5717 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5718 mono_loader_unlock ();
5720 if (tls && ei.caught && catch_ctx) {
5721 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5722 tls->catch_state.ctx = *catch_ctx;
5723 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5724 tls->catch_state.valid = TRUE;
5727 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5730 tls->catch_state.valid = FALSE;
5734 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5736 DebuggerTlsData *tls;
5741 tls = mono_native_tls_get_value (debugger_tls_id);
5746 * We're about to invoke an exception filter during the first pass of exception handling.
5748 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5749 * 'orig_ctx' is the context where the exception has been thrown.
5752 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5754 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5755 * the call site (line 37) and then continue to Main(), but it would never
5756 * include the throw site (line 32).
5758 * Since exception filters are invoked during the first pass of exception handling,
5759 * the stack frames of the throw site are still intact, so we should include them
5762 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5764 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5765 * but report the location of the 'throw' to the user.
5769 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5773 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5775 DebuggerTlsData *tls;
5780 tls = mono_native_tls_get_value (debugger_tls_id);
5784 tls->filter_state.valid = FALSE;
5788 * buffer_add_value_full:
5790 * Add the encoding of the value at ADDR described by T to the buffer.
5791 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5795 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5796 gboolean as_vtype, GHashTable *parent_vtypes)
5799 gboolean boxed_vtype = FALSE;
5802 if (!(*(void**)addr)) {
5803 /* This can happen with compiler generated locals */
5804 //printf ("%s\n", mono_type_full_name (t));
5805 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5808 g_assert (*(void**)addr);
5809 addr = *(void**)addr;
5814 case MONO_TYPE_BOOLEAN:
5817 case MONO_TYPE_CHAR:
5837 case MONO_TYPE_VOID:
5838 buffer_add_byte (buf, t->type);
5840 case MONO_TYPE_BOOLEAN:
5843 buffer_add_byte (buf, t->type);
5844 buffer_add_int (buf, *(gint8*)addr);
5846 case MONO_TYPE_CHAR:
5849 buffer_add_byte (buf, t->type);
5850 buffer_add_int (buf, *(gint16*)addr);
5855 buffer_add_byte (buf, t->type);
5856 buffer_add_int (buf, *(gint32*)addr);
5861 buffer_add_byte (buf, t->type);
5862 buffer_add_long (buf, *(gint64*)addr);
5866 /* Treat it as a vtype */
5868 case MONO_TYPE_PTR: {
5869 gssize val = *(gssize*)addr;
5871 buffer_add_byte (buf, t->type);
5872 buffer_add_long (buf, val);
5876 case MONO_TYPE_STRING:
5877 case MONO_TYPE_SZARRAY:
5878 case MONO_TYPE_OBJECT:
5879 case MONO_TYPE_CLASS:
5880 case MONO_TYPE_ARRAY:
5881 obj = *(MonoObject**)addr;
5884 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5886 if (obj->vtable->klass->valuetype) {
5887 t = &obj->vtable->klass->byval_arg;
5888 addr = mono_object_unbox (obj);
5891 } else if (obj->vtable->klass->rank) {
5892 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5893 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5894 buffer_add_byte (buf, MONO_TYPE_CLASS);
5896 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5898 buffer_add_objid (buf, obj);
5902 case MONO_TYPE_VALUETYPE:
5903 case MONO_TYPE_TYPEDBYREF: {
5907 MonoClass *klass = mono_class_from_mono_type (t);
5912 * Handle boxed vtypes recursively referencing themselves using fields.
5915 parent_vtypes = g_hash_table_new (NULL, NULL);
5916 vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
5918 if (CHECK_PROTOCOL_VERSION (2, 33)) {
5919 buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
5920 buffer_add_int (buf, vtype_index - 1);
5922 /* The client can't handle PARENT_VTYPE */
5923 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5927 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
5931 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5932 buffer_add_byte (buf, klass->enumtype);
5933 buffer_add_typeid (buf, domain, klass);
5937 while ((f = mono_class_get_fields (klass, &iter))) {
5938 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5940 if (mono_field_is_deleted (f))
5944 buffer_add_int (buf, nfields);
5947 while ((f = mono_class_get_fields (klass, &iter))) {
5948 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5950 if (mono_field_is_deleted (f))
5952 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE, parent_vtypes);
5956 g_hash_table_remove (parent_vtypes, addr);
5957 if (g_hash_table_size (parent_vtypes) == 0) {
5958 g_hash_table_destroy (parent_vtypes);
5959 parent_vtypes = NULL;
5964 case MONO_TYPE_GENERICINST:
5965 if (mono_type_generic_inst_is_valuetype (t)) {
5977 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5979 buffer_add_value_full (buf, t, addr, domain, FALSE, NULL);
5983 obj_is_of_type (MonoObject *obj, MonoType *t)
5985 MonoClass *klass = obj->vtable->klass;
5986 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5987 if (mono_class_is_transparent_proxy (klass)) {
5988 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5989 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5999 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
6002 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6008 gpointer iter = NULL;
6012 is_enum = decode_byte (buf, &buf, limit);
6013 /* Enums are sent as a normal vtype */
6015 return ERR_NOT_IMPLEMENTED;
6016 klass = decode_typeid (buf, &buf, limit, &d, &err);
6020 if (t && klass != mono_class_from_mono_type (t)) {
6021 char *name = mono_type_full_name (t);
6022 char *name2 = mono_type_full_name (&klass->byval_arg);
6023 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got %s.\n", (gpointer)GetCurrentThreadId (), name, name2);
6026 return ERR_INVALID_ARGUMENT;
6029 nfields = decode_int (buf, &buf, limit);
6030 while ((f = mono_class_get_fields (klass, &iter))) {
6031 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6033 if (mono_field_is_deleted (f))
6035 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
6040 g_assert (nfields == 0);
6048 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6052 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
6053 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
6054 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
6055 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
6056 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
6057 char *name = mono_type_full_name (t);
6058 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type);
6060 return ERR_INVALID_ARGUMENT;
6064 case MONO_TYPE_BOOLEAN:
6065 *(guint8*)addr = decode_int (buf, &buf, limit);
6067 case MONO_TYPE_CHAR:
6068 *(gunichar2*)addr = decode_int (buf, &buf, limit);
6071 *(gint8*)addr = decode_int (buf, &buf, limit);
6074 *(guint8*)addr = decode_int (buf, &buf, limit);
6077 *(gint16*)addr = decode_int (buf, &buf, limit);
6080 *(guint16*)addr = decode_int (buf, &buf, limit);
6083 *(gint32*)addr = decode_int (buf, &buf, limit);
6086 *(guint32*)addr = decode_int (buf, &buf, limit);
6089 *(gint64*)addr = decode_long (buf, &buf, limit);
6092 *(guint64*)addr = decode_long (buf, &buf, limit);
6095 *(guint32*)addr = decode_int (buf, &buf, limit);
6098 *(guint64*)addr = decode_long (buf, &buf, limit);
6101 /* We send these as I8, so we get them back as such */
6102 g_assert (type == MONO_TYPE_I8);
6103 *(gssize*)addr = decode_long (buf, &buf, limit);
6105 case MONO_TYPE_GENERICINST:
6106 if (MONO_TYPE_ISSTRUCT (t)) {
6107 /* The client sends these as a valuetype */
6115 /* We send these as vtypes, so we get them back as such */
6116 g_assert (type == MONO_TYPE_VALUETYPE);
6119 case MONO_TYPE_VALUETYPE:
6120 err = decode_vtype (t, domain, addr,buf, &buf, limit);
6126 if (MONO_TYPE_IS_REFERENCE (t)) {
6127 if (type == MONO_TYPE_OBJECT) {
6128 int objid = decode_objid (buf, &buf, limit);
6132 err = get_object (objid, (MonoObject**)&obj);
6137 if (!obj_is_of_type (obj, t)) {
6138 DEBUG_PRINTF (1, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6139 return ERR_INVALID_ARGUMENT;
6142 if (obj && obj->vtable->domain != domain)
6143 return ERR_INVALID_ARGUMENT;
6145 mono_gc_wbarrier_generic_store (addr, obj);
6146 } else if (type == VALUE_TYPE_ID_NULL) {
6147 *(MonoObject**)addr = NULL;
6148 } else if (type == MONO_TYPE_VALUETYPE) {
6156 /* This can happen when round-tripping boxed vtypes */
6158 * Obtain vtype class.
6159 * Same as the beginning of the handle_vtype case above.
6162 is_enum = decode_byte (buf, &buf, limit);
6164 return ERR_NOT_IMPLEMENTED;
6165 klass = decode_typeid (buf, &buf, limit, &d, &err);
6169 /* Decode the vtype into a temporary buffer, then box it. */
6170 vtype_buf_size = mono_class_value_size (klass, NULL);
6171 vtype_buf = g_malloc0 (vtype_buf_size);
6172 g_assert (vtype_buf);
6175 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
6180 *(MonoObject**)addr = mono_value_box (d, klass, vtype_buf);
6183 char *name = mono_type_full_name (t);
6184 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type);
6186 return ERR_INVALID_ARGUMENT;
6200 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6203 int type = decode_byte (buf, &buf, limit);
6205 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
6206 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
6207 guint8 *nullable_buf;
6210 * First try decoding it as a Nullable`1
6212 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6217 * Then try decoding as a primitive value or null.
6219 if (targ->type == type) {
6220 nullable_buf = g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
6221 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
6223 g_free (nullable_buf);
6226 mono_nullable_init (addr, mono_value_box (domain, mono_class_from_mono_type (targ), nullable_buf), mono_class_from_mono_type (t));
6227 g_free (nullable_buf);
6230 } else if (type == VALUE_TYPE_ID_NULL) {
6231 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
6237 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6241 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
6245 guint8 *addr, *gaddr;
6248 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6249 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6252 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
6253 reg_val = mono_arch_context_get_int_reg (ctx, reg);
6255 buffer_add_value_full (buf, t, ®_val, domain, as_vtype, NULL);
6257 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6258 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6259 addr += (gint32)var->offset;
6261 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6263 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6265 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6268 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6269 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
6270 /* Same as regoffset, but with an indirection */
6271 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6272 addr += (gint32)var->offset;
6274 gaddr = *(gpointer*)addr;
6276 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL);
6278 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
6279 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
6280 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
6281 MonoGSharedVtMethodRuntimeInfo *info;
6287 g_assert (info_var);
6288 g_assert (locals_var);
6290 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6291 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6292 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6293 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6294 addr += (gint32)info_var->offset;
6295 info = *(gpointer*)addr;
6296 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6297 info = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6299 g_assert_not_reached ();
6303 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6304 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6305 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6306 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6307 addr += (gint32)locals_var->offset;
6308 locals = *(gpointer*)addr;
6309 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6310 locals = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6312 g_assert_not_reached ();
6316 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6318 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6323 g_assert_not_reached ();
6328 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
6332 guint8 *addr, *gaddr;
6334 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6335 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6337 if (MONO_TYPE_IS_REFERENCE (t))
6338 size = sizeof (gpointer);
6340 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6343 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6344 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6346 gboolean is_signed = FALSE;
6349 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6352 // FIXME: Write barriers
6353 mono_gc_memmove_atomic (addr, val, size);
6358 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6363 v = is_signed ? *(gint8*)val : *(guint8*)val;
6366 v = is_signed ? *(gint16*)val : *(guint16*)val;
6369 v = is_signed ? *(gint32*)val : *(guint32*)val;
6372 v = is_signed ? *(gint64*)val : *(guint64*)val;
6375 g_assert_not_reached ();
6378 /* Set value on the stack or in the return ctx */
6379 if (reg_locations [reg]) {
6380 /* Saved on the stack */
6381 DEBUG_PRINTF (1, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v);
6382 *(reg_locations [reg]) = v;
6385 DEBUG_PRINTF (1, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v);
6386 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6389 // FIXME: Move these to mono-context.h/c.
6390 mono_arch_context_set_int_reg (ctx, reg, v);
6392 // FIXME: Can't set registers, so we disable linears
6397 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6398 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6399 addr += (gint32)var->offset;
6401 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6404 addr = *(guint8**)addr;
6410 // FIXME: Write barriers
6411 mono_gc_memmove_atomic (addr, val, size);
6413 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6414 /* Same as regoffset, but with an indirection */
6415 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6416 addr += (gint32)var->offset;
6418 gaddr = *(gpointer*)addr;
6420 // FIXME: Write barriers
6421 mono_gc_memmove_atomic (gaddr, val, size);
6423 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6427 g_assert_not_reached ();
6432 clear_event_request (int req_id, int etype)
6436 mono_loader_lock ();
6437 for (i = 0; i < event_requests->len; ++i) {
6438 EventRequest *req = g_ptr_array_index (event_requests, i);
6440 if (req->id == req_id && req->event_kind == etype) {
6441 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6442 clear_breakpoint (req->info);
6443 if (req->event_kind == EVENT_KIND_STEP)
6444 ss_destroy (req->info);
6445 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6446 clear_breakpoint (req->info);
6447 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6448 clear_breakpoint (req->info);
6449 g_ptr_array_remove_index_fast (event_requests, i);
6454 mono_loader_unlock ();
6458 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
6462 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6463 m->kind = MOD_KIND_NONE;
6464 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6465 int count = 0, match_count = 0, pos;
6466 MonoAssembly **newassemblies;
6468 for (i = 0; m->data.assemblies [i]; ++i) {
6470 if (m->data.assemblies [i] == assembly)
6475 newassemblies = g_new0 (MonoAssembly*, count - match_count);
6478 for (i = 0; i < count; ++i)
6479 if (m->data.assemblies [i] != assembly)
6480 newassemblies [pos ++] = m->data.assemblies [i];
6481 g_assert (pos == count - match_count);
6482 g_free (m->data.assemblies);
6483 m->data.assemblies = newassemblies;
6489 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
6493 for (i = 0; i < req->nmodifiers; ++i) {
6494 Modifier *m = &req->modifiers [i];
6496 clear_assembly_from_modifier (req, m, assembly);
6501 * clear_event_requests_for_assembly:
6503 * Clear all events requests which reference ASSEMBLY.
6506 clear_event_requests_for_assembly (MonoAssembly *assembly)
6511 mono_loader_lock ();
6515 for (i = 0; i < event_requests->len; ++i) {
6516 EventRequest *req = g_ptr_array_index (event_requests, i);
6518 clear_assembly_from_modifiers (req, assembly);
6520 if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly (req->info, assembly)) {
6521 clear_event_request (req->id, req->event_kind);
6526 if (req->event_kind == EVENT_KIND_STEP)
6527 ss_clear_for_assembly (req->info, assembly);
6530 mono_loader_unlock ();
6534 * type_comes_from_assembly:
6536 * GHRFunc that returns TRUE if klass comes from assembly
6539 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6541 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6545 * clear_types_for_assembly:
6547 * Clears types from loaded_classes for a given assembly
6550 clear_types_for_assembly (MonoAssembly *assembly)
6552 MonoDomain *domain = mono_domain_get ();
6553 AgentDomainInfo *info = NULL;
6555 if (!domain || !domain_jit_info (domain))
6556 /* Can happen during shutdown */
6559 mono_loader_lock ();
6560 info = get_agent_domain_info (domain);
6561 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6562 mono_loader_unlock ();
6566 add_thread (gpointer key, gpointer value, gpointer user_data)
6568 MonoInternalThread *thread = value;
6569 Buffer *buf = user_data;
6571 buffer_add_objid (buf, (MonoObject*)thread);
6575 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6577 guint8 *end = invoke->endp;
6580 MonoMethodSignature *sig;
6583 MonoObject *this, *res, *exc;
6586 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6589 MonoStopwatch watch;
6591 if (invoke->method) {
6593 * Invoke this method directly, currently only Environment.Exit () is supported.
6596 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>");
6597 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
6598 g_assert_not_reached ();
6601 m = decode_methodid (p, &p, end, &domain, &err);
6604 sig = mono_method_signature (m);
6606 if (m->klass->valuetype)
6607 this_buf = g_alloca (mono_class_instance_size (m->klass));
6609 this_buf = g_alloca (sizeof (MonoObject*));
6610 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6611 /* Should be null */
6612 int type = decode_byte (p, &p, end);
6613 if (type != VALUE_TYPE_ID_NULL) {
6614 DEBUG_PRINTF (1, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer)GetCurrentThreadId ());
6615 return ERR_INVALID_ARGUMENT;
6617 memset (this_buf, 0, mono_class_instance_size (m->klass));
6619 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6624 if (!m->klass->valuetype)
6625 this = *(MonoObject**)this_buf;
6629 if (MONO_CLASS_IS_INTERFACE (m->klass)) {
6631 DEBUG_PRINTF (1, "[%p] Error: Interface method invoked without this argument.\n", (gpointer)GetCurrentThreadId ());
6632 return ERR_INVALID_ARGUMENT;
6634 m = mono_object_get_virtual_method (this, m);
6635 } else if ((m->flags & METHOD_ATTRIBUTE_VIRTUAL) && !m->klass->valuetype && invoke->flags & INVOKE_FLAG_VIRTUAL) {
6637 DEBUG_PRINTF (1, "[%p] Error: invoke with INVOKE_FLAG_VIRTUAL flag set without this argument.\n", (gpointer)GetCurrentThreadId ());
6638 return ERR_INVALID_ARGUMENT;
6640 m = mono_object_get_virtual_method (this, m);
6643 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>");
6645 if (this && this->vtable->domain != domain)
6648 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
6649 if (!strcmp (m->name, ".ctor")) {
6650 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
6651 return ERR_INVALID_ARGUMENT;
6653 this = mono_object_new (domain, m->klass);
6655 return ERR_INVALID_ARGUMENT;
6659 if (this && !obj_is_of_type (this, &m->klass->byval_arg))
6660 return ERR_INVALID_ARGUMENT;
6662 nargs = decode_int (p, &p, end);
6663 if (nargs != sig->param_count)
6664 return ERR_INVALID_ARGUMENT;
6665 /* Use alloca to get gc tracking */
6666 arg_buf = g_alloca (nargs * sizeof (gpointer));
6667 memset (arg_buf, 0, nargs * sizeof (gpointer));
6668 args = g_alloca (nargs * sizeof (gpointer));
6669 for (i = 0; i < nargs; ++i) {
6670 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6671 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6674 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6677 if (sig->params [i]->byref) {
6678 arg_buf [i] = g_alloca (sizeof (mgreg_t));
6679 *(gpointer*)arg_buf [i] = args [i];
6680 args [i] = arg_buf [i];
6683 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6684 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6687 args [i] = arg_buf [i];
6694 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6695 tls->disable_breakpoints = TRUE;
6697 tls->disable_breakpoints = FALSE;
6700 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6702 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6703 if (invoke->has_ctx) {
6706 lmf_addr = mono_get_lmf_addr ();
6709 memset (&ext, 0, sizeof (ext));
6710 mono_arch_init_lmf_ext (&ext, *lmf_addr);
6712 ext.debugger_invoke = TRUE;
6713 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6715 mono_set_lmf ((MonoLMF*)&ext);
6719 mono_stopwatch_start (&watch);
6720 if (m->klass->valuetype)
6721 res = mono_runtime_invoke (m, this_buf, args, &exc);
6723 res = mono_runtime_invoke (m, this, args, &exc);
6724 mono_stopwatch_stop (&watch);
6725 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));
6727 buffer_add_byte (buf, 0);
6728 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6730 gboolean out_this = FALSE;
6731 gboolean out_args = FALSE;
6733 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_THIS) && CHECK_PROTOCOL_VERSION (2, 35))
6735 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_ARGS) && CHECK_PROTOCOL_VERSION (2, 35))
6737 buffer_add_byte (buf, 1 + (out_this ? 2 : 0) + (out_args ? 4 : 0));
6738 if (sig->ret->type == MONO_TYPE_VOID) {
6739 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
6740 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
6743 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6744 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6745 buffer_add_value (buf, sig->ret, &res, domain);
6746 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6747 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6748 MonoClass *k = mono_class_from_mono_type (sig->ret);
6749 guint8 *nullable_buf = g_alloca (mono_class_value_size (k, NULL));
6751 g_assert (nullable_buf);
6752 mono_nullable_init (nullable_buf, res, k);
6753 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6756 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6762 /* Return the new value of the receiver after the call */
6763 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
6765 buffer_add_int (buf, nargs);
6766 for (i = 0; i < nargs; ++i) {
6767 if (MONO_TYPE_IS_REFERENCE (sig->params [i]))
6768 buffer_add_value (buf, sig->params [i], &args [i], domain);
6769 else if (sig->params [i]->byref)
6770 /* add_value () does an indirection */
6771 buffer_add_value (buf, sig->params [i], &arg_buf [i], domain);
6773 buffer_add_value (buf, sig->params [i], arg_buf [i], domain);
6778 tls->disable_breakpoints = FALSE;
6780 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6781 if (invoke->has_ctx)
6782 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
6786 // FIXME: byref arguments
6794 * Invoke the method given by tls->pending_invoke in the current thread.
6797 invoke_method (void)
6799 DebuggerTlsData *tls;
6804 MonoContext restore_ctx;
6807 tls = mono_native_tls_get_value (debugger_tls_id);
6811 * Store the `InvokeData *' in `tls->invoke' until we're done with
6812 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6815 mono_loader_lock ();
6817 invoke = tls->pending_invoke;
6819 tls->pending_invoke = NULL;
6821 invoke->last_invoke = tls->invoke;
6822 tls->invoke = invoke;
6824 mono_loader_unlock ();
6826 tls->frames_up_to_date = FALSE;
6832 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6833 buffer_init (&buf, 128);
6836 /* Fail the other invokes as well */
6838 err = do_invoke_method (tls, &buf, invoke, p, &p);
6841 /* Start suspending before sending the reply */
6842 if (mindex == invoke->nmethods - 1) {
6843 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6844 for (i = 0; i < invoke->suspend_count; ++i)
6849 send_reply_packet (id, err, &buf);
6854 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6856 if (invoke->has_ctx)
6857 save_thread_context (&restore_ctx);
6859 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6860 g_assert (tls->resume_count);
6861 tls->resume_count -= invoke->suspend_count;
6864 DEBUG_PRINTF (1, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer)GetCurrentThreadId (), err, tls->resume_count);
6867 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6869 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
6870 * after the mono_runtime_invoke() already returned, but it doesn't matter
6871 * because we reset the abort here.
6874 mono_loader_lock ();
6876 if (tls->abort_requested)
6877 mono_thread_internal_reset_abort (tls->thread);
6879 tls->invoke = tls->invoke->last_invoke;
6880 tls->abort_requested = FALSE;
6882 mono_loader_unlock ();
6891 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6893 MonoThread *thread = value;
6894 DebuggerTlsData *tls;
6897 mono_loader_lock ();
6898 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6900 res = tls->really_suspended;
6901 mono_loader_unlock ();
6907 get_source_files_for_type (MonoClass *klass)
6909 gpointer iter = NULL;
6911 MonoDebugSourceInfo *sinfo;
6915 files = g_ptr_array_new ();
6917 while ((method = mono_class_get_methods (klass, &iter))) {
6918 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6919 GPtrArray *source_file_list;
6922 mono_debug_symfile_get_line_numbers_full (minfo, NULL, &source_file_list, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
6923 for (j = 0; j < source_file_list->len; ++j) {
6924 sinfo = g_ptr_array_index (source_file_list, j);
6925 for (i = 0; i < files->len; ++i)
6926 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6928 if (i == files->len)
6929 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6931 g_ptr_array_free (source_file_list, TRUE);
6939 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6942 case CMD_VM_VERSION: {
6943 char *build_info, *version;
6945 build_info = mono_get_runtime_build_info ();
6946 version = g_strdup_printf ("mono %s", build_info);
6948 buffer_add_string (buf, version); /* vm version */
6949 buffer_add_int (buf, MAJOR_VERSION);
6950 buffer_add_int (buf, MINOR_VERSION);
6951 g_free (build_info);
6955 case CMD_VM_SET_PROTOCOL_VERSION: {
6956 major_version = decode_int (p, &p, end);
6957 minor_version = decode_int (p, &p, end);
6958 protocol_version_set = TRUE;
6959 DEBUG_PRINTF (1, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version);
6962 case CMD_VM_ALL_THREADS: {
6964 mono_loader_lock ();
6965 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6966 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6967 mono_loader_unlock ();
6970 case CMD_VM_SUSPEND:
6972 wait_for_suspend ();
6975 if (suspend_count == 0)
6976 return ERR_NOT_SUSPENDED;
6978 clear_suspended_objs ();
6980 case CMD_VM_DISPOSE:
6981 /* Clear all event requests */
6982 mono_loader_lock ();
6983 while (event_requests->len > 0) {
6984 EventRequest *req = g_ptr_array_index (event_requests, 0);
6986 clear_event_request (req->id, req->event_kind);
6988 mono_loader_unlock ();
6990 while (suspend_count > 0)
6992 disconnected = TRUE;
6993 vm_start_event_sent = FALSE;
6996 MonoInternalThread *thread;
6997 DebuggerTlsData *tls;
6998 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6999 MonoClass *env_class;
7001 MonoMethod *exit_method = NULL;
7005 exit_code = decode_int (p, &p, end);
7007 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
7009 /* Have to send a reply before exiting */
7010 send_reply_packet (id, 0, buf);
7012 /* Clear all event requests */
7013 mono_loader_lock ();
7014 while (event_requests->len > 0) {
7015 EventRequest *req = g_ptr_array_index (event_requests, 0);
7017 clear_event_request (req->id, req->event_kind);
7019 mono_loader_unlock ();
7022 * The JDWP documentation says that the shutdown is not orderly. It doesn't
7023 * specify whenever a VM_DEATH event is sent. We currently do an orderly
7024 * shutdown by hijacking a thread to execute Environment.Exit (). This is
7025 * better than doing the shutdown ourselves, since it avoids various races.
7029 wait_for_suspend ();
7031 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7032 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
7034 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
7037 mono_loader_lock ();
7038 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
7039 mono_loader_unlock ();
7041 if (thread && exit_method) {
7042 mono_loader_lock ();
7043 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
7044 mono_loader_unlock ();
7046 args = g_new0 (gpointer, 1);
7047 args [0] = g_malloc (sizeof (int));
7048 *(int*)(args [0]) = exit_code;
7050 tls->pending_invoke = g_new0 (InvokeData, 1);
7051 tls->pending_invoke->method = exit_method;
7052 tls->pending_invoke->args = args;
7053 tls->pending_invoke->nmethods = 1;
7055 while (suspend_count > 0)
7059 * No thread found, do it ourselves.
7060 * FIXME: This can race with normal shutdown etc.
7062 while (suspend_count > 0)
7065 if (!mono_runtime_try_shutdown ())
7068 mono_environment_exitcode_set (exit_code);
7070 /* Suspend all managed threads since the runtime is going away */
7071 DEBUG_PRINTF (1, "Suspending all threads...\n");
7072 mono_thread_suspend_all_other_threads ();
7073 DEBUG_PRINTF (1, "Shutting down the runtime...\n");
7074 mono_runtime_quit ();
7075 transport_close2 ();
7076 DEBUG_PRINTF (1, "Exiting...\n");
7082 case CMD_VM_INVOKE_METHOD:
7083 case CMD_VM_INVOKE_METHODS: {
7084 int objid = decode_objid (p, &p, end);
7086 DebuggerTlsData *tls;
7087 int i, count, err, flags, nmethods;
7089 err = get_object (objid, (MonoObject**)&thread);
7093 flags = decode_int (p, &p, end);
7095 if (command == CMD_VM_INVOKE_METHODS)
7096 nmethods = decode_int (p, &p, end);
7100 // Wait for suspending if it already started
7102 wait_for_suspend ();
7103 if (!is_suspended ())
7104 return ERR_NOT_SUSPENDED;
7106 mono_loader_lock ();
7107 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7108 mono_loader_unlock ();
7111 if (!tls->really_suspended)
7112 /* The thread is still running native code, can't do invokes */
7113 return ERR_NOT_SUSPENDED;
7116 * Store the invoke data into tls, the thread will execute it after it is
7119 if (tls->pending_invoke)
7120 return ERR_NOT_SUSPENDED;
7121 tls->pending_invoke = g_new0 (InvokeData, 1);
7122 tls->pending_invoke->id = id;
7123 tls->pending_invoke->flags = flags;
7124 tls->pending_invoke->p = g_malloc (end - p);
7125 memcpy (tls->pending_invoke->p, p, end - p);
7126 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
7127 tls->pending_invoke->suspend_count = suspend_count;
7128 tls->pending_invoke->nmethods = nmethods;
7130 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
7131 resume_thread (THREAD_TO_INTERNAL (thread));
7134 count = suspend_count;
7135 for (i = 0; i < count; ++i)
7140 case CMD_VM_ABORT_INVOKE: {
7141 int objid = decode_objid (p, &p, end);
7143 DebuggerTlsData *tls;
7146 err = get_object (objid, (MonoObject**)&thread);
7150 invoke_id = decode_int (p, &p, end);
7152 mono_loader_lock ();
7153 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7156 if (tls->abort_requested) {
7157 mono_loader_unlock ();
7162 * Check whether we're still inside the mono_runtime_invoke() and that it's
7163 * actually the correct invocation.
7165 * Careful, we do not stop the thread that's doing the invocation, so we can't
7166 * inspect its stack. However, invoke_method() also acquires the loader lock
7167 * when it's done, so we're safe here.
7171 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
7172 mono_loader_unlock ();
7173 return ERR_NO_INVOCATION;
7176 tls->abort_requested = TRUE;
7178 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
7179 mono_loader_unlock ();
7183 case CMD_VM_SET_KEEPALIVE: {
7184 int timeout = decode_int (p, &p, end);
7185 agent_config.keepalive = timeout;
7187 #ifndef DISABLE_SOCKET_TRANSPORT
7194 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
7195 GHashTableIter iter, kiter;
7200 char *fname, *basename;
7201 gboolean ignore_case;
7202 GSList *class_list, *l;
7203 GPtrArray *res_classes, *res_domains;
7205 fname = decode_string (p, &p, end);
7206 ignore_case = decode_byte (p, &p, end);
7208 basename = dbg_path_get_basename (fname);
7210 res_classes = g_ptr_array_new ();
7211 res_domains = g_ptr_array_new ();
7213 mono_loader_lock ();
7214 g_hash_table_iter_init (&iter, domains);
7215 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7216 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
7218 /* Update 'source_file_to_class' cache */
7219 g_hash_table_iter_init (&kiter, info->loaded_classes);
7220 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
7221 if (!g_hash_table_lookup (info->source_files, klass)) {
7222 files = get_source_files_for_type (klass);
7223 g_hash_table_insert (info->source_files, klass, files);
7225 for (i = 0; i < files->len; ++i) {
7226 char *s = g_ptr_array_index (files, i);
7227 char *s2 = dbg_path_get_basename (s);
7230 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
7232 class_list = g_slist_prepend (class_list, klass);
7233 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
7235 class_list = g_slist_prepend (class_list, klass);
7236 g_hash_table_insert (info->source_file_to_class, s2, class_list);
7239 /* The _ignorecase hash contains the lowercase path */
7240 s3 = strdup_tolower (s2);
7241 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
7243 class_list = g_slist_prepend (class_list, klass);
7244 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
7246 class_list = g_slist_prepend (class_list, klass);
7247 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
7259 s = strdup_tolower (basename);
7260 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
7263 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
7266 for (l = class_list; l; l = l->next) {
7269 g_ptr_array_add (res_classes, klass);
7270 g_ptr_array_add (res_domains, domain);
7273 mono_loader_unlock ();
7278 buffer_add_int (buf, res_classes->len);
7279 for (i = 0; i < res_classes->len; ++i)
7280 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
7281 g_ptr_array_free (res_classes, TRUE);
7282 g_ptr_array_free (res_domains, TRUE);
7285 case CMD_VM_GET_TYPES: {
7286 GHashTableIter iter;
7290 gboolean ignore_case;
7291 GPtrArray *res_classes, *res_domains;
7292 MonoTypeNameParse info;
7294 name = decode_string (p, &p, end);
7295 ignore_case = decode_byte (p, &p, end);
7297 if (!mono_reflection_parse_type (name, &info)) {
7299 mono_reflection_free_type_info (&info);
7300 return ERR_INVALID_ARGUMENT;
7303 res_classes = g_ptr_array_new ();
7304 res_domains = g_ptr_array_new ();
7306 mono_loader_lock ();
7307 g_hash_table_iter_init (&iter, domains);
7308 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7310 gboolean type_resolve;
7314 mono_domain_assemblies_lock (domain);
7315 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7319 type_resolve = TRUE;
7320 t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
7322 g_ptr_array_add (res_classes, mono_type_get_class (t));
7323 g_ptr_array_add (res_domains, domain);
7327 mono_domain_assemblies_unlock (domain);
7329 mono_loader_unlock ();
7332 mono_reflection_free_type_info (&info);
7334 buffer_add_int (buf, res_classes->len);
7335 for (i = 0; i < res_classes->len; ++i)
7336 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
7337 g_ptr_array_free (res_classes, TRUE);
7338 g_ptr_array_free (res_domains, TRUE);
7341 case CMD_VM_START_BUFFERING:
7342 case CMD_VM_STOP_BUFFERING:
7343 /* Handled in the main loop */
7346 return ERR_NOT_IMPLEMENTED;
7353 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7359 case CMD_EVENT_REQUEST_SET: {
7361 int i, event_kind, suspend_policy, nmodifiers, mod;
7364 MonoThread *step_thread;
7365 int size = 0, depth = 0, filter = 0, step_thread_id = 0;
7369 event_kind = decode_byte (p, &p, end);
7370 suspend_policy = decode_byte (p, &p, end);
7371 nmodifiers = decode_byte (p, &p, end);
7373 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7374 req->id = InterlockedIncrement (&event_request_id);
7375 req->event_kind = event_kind;
7376 req->suspend_policy = suspend_policy;
7377 req->nmodifiers = nmodifiers;
7380 for (i = 0; i < nmodifiers; ++i) {
7381 mod = decode_byte (p, &p, end);
7383 req->modifiers [i].kind = mod;
7384 if (mod == MOD_KIND_COUNT) {
7385 req->modifiers [i].data.count = decode_int (p, &p, end);
7386 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7387 method = decode_methodid (p, &p, end, &domain, &err);
7390 location = decode_long (p, &p, end);
7391 } else if (mod == MOD_KIND_STEP) {
7392 step_thread_id = decode_id (p, &p, end);
7393 size = decode_int (p, &p, end);
7394 depth = decode_int (p, &p, end);
7395 if (CHECK_PROTOCOL_VERSION (2, 16))
7396 filter = decode_int (p, &p, end);
7397 req->modifiers [i].data.filter = filter;
7398 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7399 /* Treat STEP_THOUGH the same as HIDDEN */
7400 req->modifiers [i].data.filter |= STEP_FILTER_DEBUGGER_STEP_THROUGH;
7401 } else if (mod == MOD_KIND_THREAD_ONLY) {
7402 int id = decode_id (p, &p, end);
7404 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7409 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7410 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7414 req->modifiers [i].caught = decode_byte (p, &p, end);
7415 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7416 if (CHECK_PROTOCOL_VERSION (2, 25))
7417 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7419 req->modifiers [i].subclasses = TRUE;
7420 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" : "");
7422 req->modifiers [i].data.exc_class = exc_class;
7424 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
7426 return ERR_INVALID_ARGUMENT;
7429 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7430 int n = decode_int (p, &p, end);
7433 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
7434 for (j = 0; j < n; ++j) {
7435 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7437 g_free (req->modifiers [i].data.assemblies);
7441 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7442 int n = decode_int (p, &p, end);
7445 modifier = &req->modifiers [i];
7446 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7447 for (j = 0; j < n; ++j) {
7448 char *s = decode_string (p, &p, end);
7452 s2 = strdup_tolower (s);
7453 g_hash_table_insert (modifier->data.source_files, s2, s2);
7457 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7458 int n = decode_int (p, &p, end);
7461 modifier = &req->modifiers [i];
7462 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7463 for (j = 0; j < n; ++j) {
7464 char *s = decode_string (p, &p, end);
7467 g_hash_table_insert (modifier->data.type_names, s, s);
7471 return ERR_NOT_IMPLEMENTED;
7475 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7478 req->info = set_breakpoint (method, location, req, &error);
7479 if (!mono_error_ok (&error)) {
7481 DEBUG_PRINTF (1, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error));
7482 mono_error_cleanup (&error);
7483 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7485 } else if (req->event_kind == EVENT_KIND_STEP) {
7486 g_assert (step_thread_id);
7488 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7494 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, filter, req);
7499 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7500 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7501 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7502 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7503 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7504 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7506 if (req->nmodifiers) {
7508 return ERR_NOT_IMPLEMENTED;
7512 mono_loader_lock ();
7513 g_ptr_array_add (event_requests, req);
7515 if (agent_config.defer) {
7516 /* Transmit cached data to the client on receipt of the event request */
7517 switch (req->event_kind) {
7518 case EVENT_KIND_APPDOMAIN_CREATE:
7519 /* Emit load events for currently loaded domains */
7520 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7522 case EVENT_KIND_ASSEMBLY_LOAD:
7523 /* Emit load events for currently loaded assemblies */
7524 mono_assembly_foreach (emit_assembly_load, NULL);
7526 case EVENT_KIND_THREAD_START:
7527 /* Emit start events for currently started threads */
7528 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7530 case EVENT_KIND_TYPE_LOAD:
7531 /* Emit type load events for currently loaded types */
7532 mono_domain_foreach (send_types_for_domain, NULL);
7538 mono_loader_unlock ();
7540 buffer_add_int (buf, req->id);
7543 case CMD_EVENT_REQUEST_CLEAR: {
7544 int etype = decode_byte (p, &p, end);
7545 int req_id = decode_int (p, &p, end);
7547 // FIXME: Make a faster mapping from req_id to request
7548 mono_loader_lock ();
7549 clear_event_request (req_id, etype);
7550 mono_loader_unlock ();
7553 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7556 mono_loader_lock ();
7558 while (i < event_requests->len) {
7559 EventRequest *req = g_ptr_array_index (event_requests, i);
7561 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7562 clear_breakpoint (req->info);
7564 g_ptr_array_remove_index_fast (event_requests, i);
7570 mono_loader_unlock ();
7574 return ERR_NOT_IMPLEMENTED;
7581 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7587 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7588 buffer_add_domainid (buf, mono_get_root_domain ());
7591 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7592 domain = decode_domainid (p, &p, end, NULL, &err);
7595 buffer_add_string (buf, domain->friendly_name);
7598 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7603 domain = decode_domainid (p, &p, end, NULL, &err);
7606 mono_loader_lock ();
7608 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7611 buffer_add_int (buf, count);
7612 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7614 buffer_add_assemblyid (buf, domain, ass);
7616 mono_loader_unlock ();
7619 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7620 domain = decode_domainid (p, &p, end, NULL, &err);
7624 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7627 case CMD_APPDOMAIN_GET_CORLIB: {
7628 domain = decode_domainid (p, &p, end, NULL, &err);
7632 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7635 case CMD_APPDOMAIN_CREATE_STRING: {
7639 domain = decode_domainid (p, &p, end, NULL, &err);
7642 s = decode_string (p, &p, end);
7644 o = mono_string_new (domain, s);
7645 buffer_add_objid (buf, (MonoObject*)o);
7648 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7650 MonoDomain *domain2;
7653 domain = decode_domainid (p, &p, end, NULL, &err);
7656 klass = decode_typeid (p, &p, end, &domain2, &err);
7661 g_assert (domain == domain2);
7663 o = mono_object_new (domain, klass);
7665 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
7669 buffer_add_objid (buf, o);
7673 return ERR_NOT_IMPLEMENTED;
7680 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7686 ass = decode_assemblyid (p, &p, end, &domain, &err);
7691 case CMD_ASSEMBLY_GET_LOCATION: {
7692 buffer_add_string (buf, mono_image_get_filename (ass->image));
7695 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7699 if (ass->image->dynamic) {
7700 buffer_add_id (buf, 0);
7702 token = mono_image_get_entry_point (ass->image);
7704 buffer_add_id (buf, 0);
7706 m = mono_get_method (ass->image, token, NULL);
7707 buffer_add_methodid (buf, domain, m);
7712 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7713 buffer_add_moduleid (buf, domain, ass->image);
7716 case CMD_ASSEMBLY_GET_OBJECT: {
7717 MonoObject *o = (MonoObject*)mono_assembly_get_object (domain, ass);
7718 buffer_add_objid (buf, o);
7721 case CMD_ASSEMBLY_GET_TYPE: {
7722 char *s = decode_string (p, &p, end);
7723 gboolean ignorecase = decode_byte (p, &p, end);
7724 MonoTypeNameParse info;
7726 gboolean type_resolve, res;
7727 MonoDomain *d = mono_domain_get ();
7729 /* This is needed to be able to find referenced assemblies */
7730 res = mono_domain_set (domain, FALSE);
7733 if (!mono_reflection_parse_type (s, &info)) {
7736 if (info.assembly.name)
7738 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
7740 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
7741 mono_reflection_free_type_info (&info);
7744 mono_domain_set (d, TRUE);
7748 case CMD_ASSEMBLY_GET_NAME: {
7750 MonoAssembly *mass = ass;
7752 name = g_strdup_printf (
7753 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7755 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7756 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7757 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7758 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7760 buffer_add_string (buf, name);
7765 return ERR_NOT_IMPLEMENTED;
7772 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7778 case CMD_MODULE_GET_INFO: {
7779 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7782 basename = g_path_get_basename (image->name);
7783 buffer_add_string (buf, basename); // name
7784 buffer_add_string (buf, image->module_name); // scopename
7785 buffer_add_string (buf, image->name); // fqname
7786 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7787 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7792 return ERR_NOT_IMPLEMENTED;
7799 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7805 case CMD_FIELD_GET_INFO: {
7806 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
7808 buffer_add_string (buf, f->name);
7809 buffer_add_typeid (buf, domain, f->parent);
7810 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7811 buffer_add_int (buf, f->type->attrs);
7815 return ERR_NOT_IMPLEMENTED;
7822 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7824 if (val && val->vtable->klass == mono_defaults.monotype_class) {
7825 /* Special case these so the client doesn't have to handle Type objects */
7827 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7828 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7829 } else if (MONO_TYPE_IS_REFERENCE (t))
7830 buffer_add_value (buf, t, &val, domain);
7832 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7836 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7842 buffer_add_int (buf, 0);
7846 for (i = 0; i < cinfo->num_attrs; ++i) {
7847 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7850 buffer_add_int (buf, nattrs);
7852 for (i = 0; i < cinfo->num_attrs; ++i) {
7853 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7854 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7855 MonoArray *typed_args, *named_args;
7857 CattrNamedArg *arginfo = NULL;
7860 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
7861 if (!mono_error_ok (&error)) {
7862 DEBUG_PRINTF (2, "[dbg] mono_reflection_create_custom_attr_data_args () failed with: '%s'\n", mono_error_get_message (&error));
7863 mono_error_cleanup (&error);
7864 return ERR_LOADER_ERROR;
7867 buffer_add_methodid (buf, domain, attr->ctor);
7871 buffer_add_int (buf, mono_array_length (typed_args));
7872 for (j = 0; j < mono_array_length (typed_args); ++j) {
7873 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7875 t = mono_method_signature (attr->ctor)->params [j];
7877 buffer_add_cattr_arg (buf, t, domain, val);
7880 buffer_add_int (buf, 0);
7885 buffer_add_int (buf, mono_array_length (named_args));
7887 for (j = 0; j < mono_array_length (named_args); ++j) {
7888 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7890 if (arginfo [j].prop) {
7891 buffer_add_byte (buf, 0x54);
7892 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7893 } else if (arginfo [j].field) {
7894 buffer_add_byte (buf, 0x53);
7895 buffer_add_fieldid (buf, domain, arginfo [j].field);
7897 g_assert_not_reached ();
7900 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7903 buffer_add_int (buf, 0);
7912 /* FIXME: Code duplication with icall.c */
7914 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7919 mono_class_setup_interfaces (klass, error);
7920 if (!mono_error_ok (error))
7923 for (i = 0; i < klass->interface_count; i++) {
7924 ic = klass->interfaces [i];
7925 g_hash_table_insert (ifaces, ic, ic);
7927 collect_interfaces (ic, ifaces, error);
7928 if (!mono_error_ok (error))
7934 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7944 case CMD_TYPE_GET_INFO: {
7945 buffer_add_string (buf, klass->name_space);
7946 buffer_add_string (buf, klass->name);
7948 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7949 buffer_add_string (buf, name);
7951 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7952 buffer_add_moduleid (buf, domain, klass->image);
7953 buffer_add_typeid (buf, domain, klass->parent);
7954 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7955 buffer_add_typeid (buf, domain, klass->element_class);
7957 buffer_add_id (buf, 0);
7958 buffer_add_int (buf, klass->type_token);
7959 buffer_add_byte (buf, klass->rank);
7960 buffer_add_int (buf, klass->flags);
7962 type = &klass->byval_arg;
7963 // FIXME: Can't decide whenever a class represents a byref type
7966 if (type->type == MONO_TYPE_PTR)
7968 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7970 if (type->type == MONO_TYPE_VALUETYPE)
7972 if (klass->enumtype)
7974 if (klass->generic_container)
7976 if (klass->generic_container || klass->generic_class)
7978 buffer_add_byte (buf, b);
7981 while ((nested = mono_class_get_nested_types (klass, &iter)))
7983 buffer_add_int (buf, nnested);
7985 while ((nested = mono_class_get_nested_types (klass, &iter)))
7986 buffer_add_typeid (buf, domain, nested);
7987 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7988 if (klass->generic_container)
7989 buffer_add_typeid (buf, domain, klass);
7990 else if (klass->generic_class)
7991 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7993 buffer_add_id (buf, 0);
7995 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7998 if (klass->generic_class) {
7999 MonoGenericInst *inst = klass->generic_class->context.class_inst;
8001 count = inst->type_argc;
8002 buffer_add_int (buf, count);
8003 for (i = 0; i < count; i++)
8004 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8005 } else if (klass->generic_container) {
8006 MonoGenericContainer *container = klass->generic_container;
8009 count = container->type_argc;
8010 buffer_add_int (buf, count);
8011 for (i = 0; i < count; i++) {
8012 pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
8013 buffer_add_typeid (buf, domain, pklass);
8016 buffer_add_int (buf, 0);
8021 case CMD_TYPE_GET_METHODS: {
8024 gpointer iter = NULL;
8027 mono_class_setup_methods (klass);
8029 nmethods = mono_class_num_methods (klass);
8031 buffer_add_int (buf, nmethods);
8033 while ((m = mono_class_get_methods (klass, &iter))) {
8034 buffer_add_methodid (buf, domain, m);
8037 g_assert (i == nmethods);
8040 case CMD_TYPE_GET_FIELDS: {
8043 gpointer iter = NULL;
8046 nfields = mono_class_num_fields (klass);
8048 buffer_add_int (buf, nfields);
8050 while ((f = mono_class_get_fields (klass, &iter))) {
8051 buffer_add_fieldid (buf, domain, f);
8052 buffer_add_string (buf, f->name);
8053 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
8054 buffer_add_int (buf, f->type->attrs);
8057 g_assert (i == nfields);
8060 case CMD_TYPE_GET_PROPERTIES: {
8063 gpointer iter = NULL;
8066 nprops = mono_class_num_properties (klass);
8068 buffer_add_int (buf, nprops);
8070 while ((p = mono_class_get_properties (klass, &iter))) {
8071 buffer_add_propertyid (buf, domain, p);
8072 buffer_add_string (buf, p->name);
8073 buffer_add_methodid (buf, domain, p->get);
8074 buffer_add_methodid (buf, domain, p->set);
8075 buffer_add_int (buf, p->attrs);
8078 g_assert (i == nprops);
8081 case CMD_TYPE_GET_CATTRS: {
8082 MonoClass *attr_klass;
8083 MonoCustomAttrInfo *cinfo;
8085 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8086 /* attr_klass can be NULL */
8090 cinfo = mono_custom_attrs_from_class (klass);
8092 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8097 case CMD_TYPE_GET_FIELD_CATTRS: {
8098 MonoClass *attr_klass;
8099 MonoCustomAttrInfo *cinfo;
8100 MonoClassField *field;
8102 field = decode_fieldid (p, &p, end, NULL, &err);
8105 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8109 cinfo = mono_custom_attrs_from_field (klass, field);
8111 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8116 case CMD_TYPE_GET_PROPERTY_CATTRS: {
8117 MonoClass *attr_klass;
8118 MonoCustomAttrInfo *cinfo;
8121 prop = decode_propertyid (p, &p, end, NULL, &err);
8124 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8128 cinfo = mono_custom_attrs_from_property (klass, prop);
8130 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8135 case CMD_TYPE_GET_VALUES:
8136 case CMD_TYPE_GET_VALUES_2: {
8143 MonoThread *thread_obj;
8144 MonoInternalThread *thread = NULL;
8145 guint32 special_static_type;
8147 if (command == CMD_TYPE_GET_VALUES_2) {
8148 int objid = decode_objid (p, &p, end);
8151 err = get_object (objid, (MonoObject**)&thread_obj);
8155 thread = THREAD_TO_INTERNAL (thread_obj);
8158 len = decode_int (p, &p, end);
8159 for (i = 0; i < len; ++i) {
8160 f = decode_fieldid (p, &p, end, NULL, &err);
8164 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8165 return ERR_INVALID_FIELDID;
8166 special_static_type = mono_class_field_get_special_static_type (f);
8167 if (special_static_type != SPECIAL_STATIC_NONE) {
8168 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
8169 return ERR_INVALID_FIELDID;
8172 /* Check that the field belongs to the object */
8174 for (k = klass; k; k = k->parent) {
8175 if (k == f->parent) {
8181 return ERR_INVALID_FIELDID;
8183 vtable = mono_class_vtable (domain, f->parent);
8184 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8185 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
8186 buffer_add_value (buf, f->type, val, domain);
8191 case CMD_TYPE_SET_VALUES: {
8199 len = decode_int (p, &p, end);
8200 for (i = 0; i < len; ++i) {
8201 f = decode_fieldid (p, &p, end, NULL, &err);
8205 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8206 return ERR_INVALID_FIELDID;
8207 if (mono_class_field_is_special_static (f))
8208 return ERR_INVALID_FIELDID;
8210 /* Check that the field belongs to the object */
8212 for (k = klass; k; k = k->parent) {
8213 if (k == f->parent) {
8219 return ERR_INVALID_FIELDID;
8221 // FIXME: Check for literal/const
8223 vtable = mono_class_vtable (domain, f->parent);
8224 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8225 err = decode_value (f->type, domain, val, p, &p, end);
8230 if (MONO_TYPE_IS_REFERENCE (f->type))
8231 mono_field_static_set_value (vtable, f, *(gpointer*)val);
8233 mono_field_static_set_value (vtable, f, val);
8238 case CMD_TYPE_GET_OBJECT: {
8239 MonoObject *o = (MonoObject*)mono_type_get_object (domain, &klass->byval_arg);
8240 buffer_add_objid (buf, o);
8243 case CMD_TYPE_GET_SOURCE_FILES:
8244 case CMD_TYPE_GET_SOURCE_FILES_2: {
8245 char *source_file, *base;
8249 files = get_source_files_for_type (klass);
8251 buffer_add_int (buf, files->len);
8252 for (i = 0; i < files->len; ++i) {
8253 source_file = g_ptr_array_index (files, i);
8254 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8255 buffer_add_string (buf, source_file);
8257 base = dbg_path_get_basename (source_file);
8258 buffer_add_string (buf, base);
8261 g_free (source_file);
8263 g_ptr_array_free (files, TRUE);
8266 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8267 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8271 if (mono_class_is_assignable_from (klass, oklass))
8272 buffer_add_byte (buf, 1);
8274 buffer_add_byte (buf, 0);
8277 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8278 char *name = decode_string (p, &p, end);
8279 int i, flags = decode_int (p, &p, end);
8280 MonoException *ex = NULL;
8281 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
8284 return ERR_LOADER_ERROR;
8285 buffer_add_int (buf, array->len);
8286 for (i = 0; i < array->len; ++i) {
8287 MonoMethod *method = g_ptr_array_index (array, i);
8288 buffer_add_methodid (buf, domain, method);
8291 g_ptr_array_free (array, TRUE);
8295 case CMD_TYPE_GET_INTERFACES: {
8297 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8299 MonoClass *tclass, *iface;
8300 GHashTableIter iter;
8304 for (parent = tclass; parent; parent = parent->parent) {
8305 mono_class_setup_interfaces (parent, &error);
8306 if (!mono_error_ok (&error))
8307 return ERR_LOADER_ERROR;
8308 collect_interfaces (parent, iface_hash, &error);
8309 if (!mono_error_ok (&error))
8310 return ERR_LOADER_ERROR;
8313 buffer_add_int (buf, g_hash_table_size (iface_hash));
8315 g_hash_table_iter_init (&iter, iface_hash);
8316 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8317 buffer_add_typeid (buf, domain, iface);
8318 g_hash_table_destroy (iface_hash);
8321 case CMD_TYPE_GET_INTERFACE_MAP: {
8322 int tindex, ioffset;
8323 gboolean variance_used;
8325 int len, nmethods, i;
8329 len = decode_int (p, &p, end);
8330 mono_class_setup_vtable (klass);
8332 for (tindex = 0; tindex < len; ++tindex) {
8333 iclass = decode_typeid (p, &p, end, NULL, &err);
8337 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8339 return ERR_INVALID_ARGUMENT;
8341 nmethods = mono_class_num_methods (iclass);
8342 buffer_add_int (buf, nmethods);
8345 while ((method = mono_class_get_methods (iclass, &iter))) {
8346 buffer_add_methodid (buf, domain, method);
8348 for (i = 0; i < nmethods; ++i)
8349 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
8353 case CMD_TYPE_IS_INITIALIZED: {
8354 MonoVTable *vtable = mono_class_vtable (domain, klass);
8357 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8359 buffer_add_int (buf, 0);
8362 case CMD_TYPE_CREATE_INSTANCE: {
8365 obj = mono_object_new (domain, klass);
8366 buffer_add_objid (buf, obj);
8370 return ERR_NOT_IMPLEMENTED;
8377 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8380 MonoDomain *old_domain;
8384 klass = decode_typeid (p, &p, end, &domain, &err);
8388 old_domain = mono_domain_get ();
8390 mono_domain_set (domain, TRUE);
8392 err = type_commands_internal (command, klass, domain, p, end, buf);
8394 mono_domain_set (old_domain, TRUE);
8400 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8402 MonoMethodHeader *header;
8406 case CMD_METHOD_GET_NAME: {
8407 buffer_add_string (buf, method->name);
8410 case CMD_METHOD_GET_DECLARING_TYPE: {
8411 buffer_add_typeid (buf, domain, method->klass);
8414 case CMD_METHOD_GET_DEBUG_INFO: {
8415 MonoDebugMethodInfo *minfo;
8417 int i, j, n_il_offsets;
8420 int *column_numbers;
8421 int *end_line_numbers;
8422 int *end_column_numbers;
8424 GPtrArray *source_file_list;
8426 header = mono_method_get_header (method);
8428 buffer_add_int (buf, 0);
8429 buffer_add_string (buf, "");
8430 buffer_add_int (buf, 0);
8434 minfo = mono_debug_lookup_method (method);
8436 buffer_add_int (buf, header->code_size);
8437 buffer_add_string (buf, "");
8438 buffer_add_int (buf, 0);
8439 mono_metadata_free_mh (header);
8443 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);
8444 buffer_add_int (buf, header->code_size);
8445 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8446 buffer_add_int (buf, source_file_list->len);
8447 for (i = 0; i < source_file_list->len; ++i) {
8448 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
8449 buffer_add_string (buf, sinfo->source_file);
8450 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8451 for (j = 0; j < 16; ++j)
8452 buffer_add_byte (buf, sinfo->hash [j]);
8456 buffer_add_string (buf, source_file);
8458 buffer_add_int (buf, n_il_offsets);
8459 DEBUG_PRINTF (10, "Line number table for method %s:\n", mono_method_full_name (method, TRUE));
8460 for (i = 0; i < n_il_offsets; ++i) {
8461 const char *srcfile = "";
8463 if (source_files [i] != -1) {
8464 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
8465 srcfile = sinfo->source_file;
8467 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);
8468 buffer_add_int (buf, il_offsets [i]);
8469 buffer_add_int (buf, line_numbers [i]);
8470 if (CHECK_PROTOCOL_VERSION (2, 13))
8471 buffer_add_int (buf, source_files [i]);
8472 if (CHECK_PROTOCOL_VERSION (2, 19))
8473 buffer_add_int (buf, column_numbers ? column_numbers [i] : -1);
8474 if (CHECK_PROTOCOL_VERSION (2, 32)) {
8475 buffer_add_int (buf, end_line_numbers ? end_line_numbers [i] : -1);
8476 buffer_add_int (buf, end_column_numbers ? end_column_numbers [i] : -1);
8479 g_free (source_file);
8480 g_free (il_offsets);
8481 g_free (line_numbers);
8482 g_free (column_numbers);
8483 g_free (end_line_numbers);
8484 g_free (end_column_numbers);
8485 g_free (source_files);
8486 g_ptr_array_free (source_file_list, TRUE);
8487 mono_metadata_free_mh (header);
8490 case CMD_METHOD_GET_PARAM_INFO: {
8491 MonoMethodSignature *sig = mono_method_signature (method);
8495 /* FIXME: mono_class_from_mono_type () and byrefs */
8497 /* FIXME: Use a smaller encoding */
8498 buffer_add_int (buf, sig->call_convention);
8499 buffer_add_int (buf, sig->param_count);
8500 buffer_add_int (buf, sig->generic_param_count);
8501 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
8502 for (i = 0; i < sig->param_count; ++i) {
8504 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
8507 /* Emit parameter names */
8508 names = g_new (char *, sig->param_count);
8509 mono_method_get_param_names (method, (const char **) names);
8510 for (i = 0; i < sig->param_count; ++i)
8511 buffer_add_string (buf, names [i]);
8516 case CMD_METHOD_GET_LOCALS_INFO: {
8517 int i, j, num_locals;
8518 MonoDebugLocalsInfo *locals;
8520 header = mono_method_get_header (method);
8522 return ERR_INVALID_ARGUMENT;
8524 buffer_add_int (buf, header->num_locals);
8527 for (i = 0; i < header->num_locals; ++i)
8528 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
8531 locals = mono_debug_lookup_locals (method);
8533 num_locals = locals->num_locals;
8536 for (i = 0; i < header->num_locals; ++i) {
8537 for (j = 0; j < num_locals; ++j)
8538 if (locals->locals [j].index == i)
8541 buffer_add_string (buf, locals->locals [j].name);
8543 buffer_add_string (buf, "");
8547 for (i = 0; i < header->num_locals; ++i) {
8548 for (j = 0; j < num_locals; ++j)
8549 if (locals->locals [j].index == i)
8551 if (j < num_locals && locals->locals [j].block) {
8552 buffer_add_int (buf, locals->locals [j].block->start_offset);
8553 buffer_add_int (buf, locals->locals [j].block->end_offset);
8555 buffer_add_int (buf, 0);
8556 buffer_add_int (buf, header->code_size);
8559 mono_metadata_free_mh (header);
8562 mono_debug_symfile_free_locals (locals);
8566 case CMD_METHOD_GET_INFO:
8567 buffer_add_int (buf, method->flags);
8568 buffer_add_int (buf, method->iflags);
8569 buffer_add_int (buf, method->token);
8570 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8572 if (method->is_generic)
8574 if (mono_method_signature (method)->generic_param_count)
8576 buffer_add_byte (buf, attrs);
8577 if (method->is_generic || method->is_inflated) {
8580 if (method->is_generic) {
8583 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8585 result = imethod->declaring;
8586 if (imethod->context.class_inst) {
8587 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8588 /*Generic methods gets the context of the GTD.*/
8589 if (mono_class_get_context (klass)) {
8591 result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), &error);
8592 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8597 buffer_add_methodid (buf, domain, result);
8599 buffer_add_id (buf, 0);
8601 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8602 if (mono_method_signature (method)->generic_param_count) {
8605 if (method->is_inflated) {
8606 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
8608 count = inst->type_argc;
8609 buffer_add_int (buf, count);
8611 for (i = 0; i < count; i++)
8612 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8614 buffer_add_int (buf, 0);
8616 } else if (method->is_generic) {
8617 MonoGenericContainer *container = mono_method_get_generic_container (method);
8619 count = mono_method_signature (method)->generic_param_count;
8620 buffer_add_int (buf, count);
8621 for (i = 0; i < count; i++) {
8622 MonoGenericParam *param = mono_generic_container_get_param (container, i);
8623 MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
8624 buffer_add_typeid (buf, domain, pklass);
8627 buffer_add_int (buf, 0);
8630 buffer_add_int (buf, 0);
8635 case CMD_METHOD_GET_BODY: {
8638 header = mono_method_get_header (method);
8640 buffer_add_int (buf, 0);
8642 if (CHECK_PROTOCOL_VERSION (2, 18))
8643 buffer_add_int (buf, 0);
8645 buffer_add_int (buf, header->code_size);
8646 for (i = 0; i < header->code_size; ++i)
8647 buffer_add_byte (buf, header->code [i]);
8649 if (CHECK_PROTOCOL_VERSION (2, 18)) {
8650 buffer_add_int (buf, header->num_clauses);
8651 for (i = 0; i < header->num_clauses; ++i) {
8652 MonoExceptionClause *clause = &header->clauses [i];
8654 buffer_add_int (buf, clause->flags);
8655 buffer_add_int (buf, clause->try_offset);
8656 buffer_add_int (buf, clause->try_len);
8657 buffer_add_int (buf, clause->handler_offset);
8658 buffer_add_int (buf, clause->handler_len);
8659 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
8660 buffer_add_typeid (buf, domain, clause->data.catch_class);
8661 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8662 buffer_add_int (buf, clause->data.filter_offset);
8666 mono_metadata_free_mh (header);
8671 case CMD_METHOD_RESOLVE_TOKEN: {
8672 guint32 token = decode_int (p, &p, end);
8675 switch (mono_metadata_token_code (token)) {
8676 case MONO_TOKEN_STRING: {
8680 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
8683 s2 = mono_string_to_utf8 (s);
8685 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8686 buffer_add_string (buf, s2);
8692 MonoClass *handle_class;
8694 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8695 val = mono_method_get_wrapper_data (method, token);
8696 handle_class = mono_method_get_wrapper_data (method, token + 1);
8698 if (handle_class == NULL) {
8699 // Can't figure out the token type
8700 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8705 val = mono_ldtoken_checked (method->klass->image, token, &handle_class, NULL, &error);
8707 g_error ("Could not load token due to %s", mono_error_get_message (&error));
8710 if (handle_class == mono_defaults.typehandle_class) {
8711 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8712 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8713 buffer_add_typeid (buf, domain, (MonoClass *) val);
8715 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
8716 } else if (handle_class == mono_defaults.fieldhandle_class) {
8717 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8718 buffer_add_fieldid (buf, domain, val);
8719 } else if (handle_class == mono_defaults.methodhandle_class) {
8720 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8721 buffer_add_methodid (buf, domain, val);
8722 } else if (handle_class == mono_defaults.string_class) {
8725 s = mono_string_to_utf8 (val);
8726 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8727 buffer_add_string (buf, s);
8730 g_assert_not_reached ();
8737 case CMD_METHOD_GET_CATTRS: {
8738 MonoClass *attr_klass;
8739 MonoCustomAttrInfo *cinfo;
8741 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8742 /* attr_klass can be NULL */
8746 cinfo = mono_custom_attrs_from_method (method);
8748 err = buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
8753 case CMD_METHOD_MAKE_GENERIC_METHOD: {
8755 MonoType **type_argv;
8759 MonoGenericInst *ginst;
8760 MonoGenericContext tmp_context;
8761 MonoMethod *inflated;
8763 type_argc = decode_int (p, &p, end);
8764 type_argv = g_new0 (MonoType*, type_argc);
8765 for (i = 0; i < type_argc; ++i) {
8766 klass = decode_typeid (p, &p, end, &d, &err);
8773 return ERR_INVALID_ARGUMENT;
8775 type_argv [i] = &klass->byval_arg;
8777 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
8779 tmp_context.class_inst = method->klass->generic_class ? method->klass->generic_class->context.class_inst : NULL;
8780 tmp_context.method_inst = ginst;
8782 inflated = mono_class_inflate_generic_method_checked (method, &tmp_context, &error);
8783 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8784 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
8785 return ERR_INVALID_ARGUMENT;
8786 buffer_add_methodid (buf, domain, inflated);
8790 return ERR_NOT_IMPLEMENTED;
8797 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8800 MonoDomain *old_domain;
8804 method = decode_methodid (p, &p, end, &domain, &err);
8808 old_domain = mono_domain_get ();
8810 mono_domain_set (domain, TRUE);
8812 err = method_commands_internal (command, method, domain, p, end, buf);
8814 mono_domain_set (old_domain, TRUE);
8820 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8822 int objid = decode_objid (p, &p, end);
8824 MonoThread *thread_obj;
8825 MonoInternalThread *thread;
8827 err = get_object (objid, (MonoObject**)&thread_obj);
8831 thread = THREAD_TO_INTERNAL (thread_obj);
8834 case CMD_THREAD_GET_NAME: {
8836 gunichar2 *s = mono_thread_get_name (thread, &name_len);
8839 buffer_add_int (buf, 0);
8844 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
8846 buffer_add_int (buf, len);
8847 buffer_add_data (buf, (guint8*)name, len);
8852 case CMD_THREAD_GET_FRAME_INFO: {
8853 DebuggerTlsData *tls;
8854 int i, start_frame, length;
8856 // Wait for suspending if it already started
8857 // FIXME: Races with suspend_count
8858 while (!is_suspended ()) {
8860 wait_for_suspend ();
8864 wait_for_suspend ();
8865 if (!is_suspended ())
8866 return ERR_NOT_SUSPENDED;
8869 start_frame = decode_int (p, &p, end);
8870 length = decode_int (p, &p, end);
8872 if (start_frame != 0 || length != -1)
8873 return ERR_NOT_IMPLEMENTED;
8875 mono_loader_lock ();
8876 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8877 mono_loader_unlock ();
8880 compute_frame_info (thread, tls);
8882 buffer_add_int (buf, tls->frame_count);
8883 for (i = 0; i < tls->frame_count; ++i) {
8884 buffer_add_int (buf, tls->frames [i]->id);
8885 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
8886 buffer_add_int (buf, tls->frames [i]->il_offset);
8888 * Instead of passing the frame type directly to the client, we associate
8889 * it with the previous frame using a set of flags. This avoids lots of
8890 * conditional code in the client, since a frame whose type isn't
8891 * FRAME_TYPE_MANAGED has no method, location, etc.
8893 buffer_add_byte (buf, tls->frames [i]->flags);
8898 case CMD_THREAD_GET_STATE:
8899 buffer_add_int (buf, thread->state);
8901 case CMD_THREAD_GET_INFO:
8902 buffer_add_byte (buf, thread->threadpool_thread);
8904 case CMD_THREAD_GET_ID:
8905 buffer_add_long (buf, (guint64)(gsize)thread);
8907 case CMD_THREAD_GET_TID:
8908 buffer_add_long (buf, (guint64)thread->tid);
8910 case CMD_THREAD_SET_IP: {
8911 DebuggerTlsData *tls;
8914 MonoSeqPointInfo *seq_points;
8919 method = decode_methodid (p, &p, end, &domain, &err);
8922 il_offset = decode_long (p, &p, end);
8924 while (!is_suspended ()) {
8926 wait_for_suspend ();
8929 mono_loader_lock ();
8930 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8931 mono_loader_unlock ();
8934 compute_frame_info (thread, tls);
8935 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
8936 return ERR_INVALID_ARGUMENT;
8938 found_sp = find_seq_point (domain, method, il_offset, &seq_points, &sp);
8940 g_assert (seq_points);
8943 return ERR_INVALID_ARGUMENT;
8945 // FIXME: Check that the ip change is safe
8947 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);
8948 MONO_CONTEXT_SET_IP (&tls->restore_state.ctx, (guint8*)tls->frames [0]->ji->code_start + sp.native_offset);
8952 return ERR_NOT_IMPLEMENTED;
8959 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8963 MonoThread *thread_obj;
8964 MonoInternalThread *thread;
8965 int pos, i, len, frame_idx;
8966 DebuggerTlsData *tls;
8968 MonoDebugMethodJitInfo *jit;
8969 MonoMethodSignature *sig;
8971 MonoMethodHeader *header;
8973 objid = decode_objid (p, &p, end);
8974 err = get_object (objid, (MonoObject**)&thread_obj);
8978 thread = THREAD_TO_INTERNAL (thread_obj);
8980 id = decode_id (p, &p, end);
8982 mono_loader_lock ();
8983 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8984 mono_loader_unlock ();
8987 for (i = 0; i < tls->frame_count; ++i) {
8988 if (tls->frames [i]->id == id)
8991 if (i == tls->frame_count)
8992 return ERR_INVALID_FRAMEID;
8995 frame = tls->frames [frame_idx];
8997 /* This is supported for frames without has_ctx etc. set */
8998 if (command == CMD_STACK_FRAME_GET_DOMAIN) {
8999 if (CHECK_PROTOCOL_VERSION (2, 38))
9000 buffer_add_domainid (buf, frame->domain);
9004 if (!frame->has_ctx)
9005 return ERR_ABSENT_INFORMATION;
9008 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
9009 if (!frame->jit && frame->api_method->is_inflated)
9010 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
9014 /* This could happen for aot images with no jit debug info */
9015 s = mono_method_full_name (frame->api_method, TRUE);
9016 DEBUG_PRINTF (1, "[dbg] No debug information found for '%s'.\n", s);
9018 return ERR_ABSENT_INFORMATION;
9023 sig = mono_method_signature (frame->actual_method);
9025 if (!get_seq_points (frame->domain, frame->actual_method))
9027 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
9029 return ERR_ABSENT_INFORMATION;
9032 case CMD_STACK_FRAME_GET_VALUES: {
9033 len = decode_int (p, &p, end);
9034 header = mono_method_get_header (frame->actual_method);
9036 for (i = 0; i < len; ++i) {
9037 pos = decode_int (p, &p, end);
9042 g_assert (pos >= 0 && pos < jit->num_params);
9044 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
9046 g_assert (pos >= 0 && pos < jit->num_locals);
9048 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
9051 mono_metadata_free_mh (header);
9054 case CMD_STACK_FRAME_GET_THIS: {
9055 if (frame->api_method->klass->valuetype) {
9056 if (!sig->hasthis) {
9057 MonoObject *p = NULL;
9058 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
9060 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9063 if (!sig->hasthis) {
9064 MonoObject *p = NULL;
9065 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
9067 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9072 case CMD_STACK_FRAME_SET_VALUES: {
9075 MonoDebugVarInfo *var;
9077 len = decode_int (p, &p, end);
9078 header = mono_method_get_header (frame->actual_method);
9080 for (i = 0; i < len; ++i) {
9081 pos = decode_int (p, &p, end);
9086 g_assert (pos >= 0 && pos < jit->num_params);
9088 t = sig->params [pos];
9089 var = &jit->params [pos];
9091 g_assert (pos >= 0 && pos < jit->num_locals);
9093 t = header->locals [pos];
9094 var = &jit->locals [pos];
9097 if (MONO_TYPE_IS_REFERENCE (t))
9098 val_buf = g_alloca (sizeof (MonoObject*));
9100 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9101 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9105 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9107 mono_metadata_free_mh (header);
9110 case CMD_STACK_FRAME_GET_DOMAIN: {
9111 if (CHECK_PROTOCOL_VERSION (2, 38))
9112 buffer_add_domainid (buf, frame->domain);
9116 return ERR_NOT_IMPLEMENTED;
9123 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9126 int objid, err, index, len, i, esize;
9129 objid = decode_objid (p, &p, end);
9130 err = get_object (objid, (MonoObject**)&arr);
9135 case CMD_ARRAY_REF_GET_LENGTH:
9136 buffer_add_int (buf, arr->obj.vtable->klass->rank);
9138 buffer_add_int (buf, arr->max_length);
9139 buffer_add_int (buf, 0);
9141 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
9142 buffer_add_int (buf, arr->bounds [i].length);
9143 buffer_add_int (buf, arr->bounds [i].lower_bound);
9147 case CMD_ARRAY_REF_GET_VALUES:
9148 index = decode_int (p, &p, end);
9149 len = decode_int (p, &p, end);
9151 g_assert (index >= 0 && len >= 0);
9152 // Reordered to avoid integer overflow
9153 g_assert (!(index > arr->max_length - len));
9155 esize = mono_array_element_size (arr->obj.vtable->klass);
9156 for (i = index; i < index + len; ++i) {
9157 elem = (gpointer*)((char*)arr->vector + (i * esize));
9158 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
9161 case CMD_ARRAY_REF_SET_VALUES:
9162 index = decode_int (p, &p, end);
9163 len = decode_int (p, &p, end);
9165 g_assert (index >= 0 && len >= 0);
9166 // Reordered to avoid integer overflow
9167 g_assert (!(index > arr->max_length - len));
9169 esize = mono_array_element_size (arr->obj.vtable->klass);
9170 for (i = index; i < index + len; ++i) {
9171 elem = (gpointer*)((char*)arr->vector + (i * esize));
9173 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
9177 return ERR_NOT_IMPLEMENTED;
9184 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9189 int i, index, length;
9192 objid = decode_objid (p, &p, end);
9193 err = get_object (objid, (MonoObject**)&str);
9198 case CMD_STRING_REF_GET_VALUE:
9199 s = mono_string_to_utf8 (str);
9200 buffer_add_string (buf, s);
9203 case CMD_STRING_REF_GET_LENGTH:
9204 buffer_add_long (buf, mono_string_length (str));
9206 case CMD_STRING_REF_GET_CHARS:
9207 index = decode_long (p, &p, end);
9208 length = decode_long (p, &p, end);
9209 if (index > mono_string_length (str) - length)
9210 return ERR_INVALID_ARGUMENT;
9211 c = mono_string_chars (str) + index;
9212 for (i = 0; i < length; ++i)
9213 buffer_add_short (buf, c [i]);
9216 return ERR_NOT_IMPLEMENTED;
9223 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9232 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9233 objid = decode_objid (p, &p, end);
9234 err = get_object (objid, &obj);
9236 buffer_add_int (buf, 1);
9238 buffer_add_int (buf, 0);
9242 objid = decode_objid (p, &p, end);
9243 err = get_object (objid, &obj);
9248 case CMD_OBJECT_REF_GET_TYPE:
9249 /* This handles transparent proxies too */
9250 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9252 case CMD_OBJECT_REF_GET_VALUES:
9253 len = decode_int (p, &p, end);
9255 for (i = 0; i < len; ++i) {
9256 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9260 /* Check that the field belongs to the object */
9262 for (k = obj->vtable->klass; k; k = k->parent) {
9263 if (k == f->parent) {
9269 return ERR_INVALID_FIELDID;
9271 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9275 if (mono_class_field_is_special_static (f))
9276 return ERR_INVALID_FIELDID;
9278 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9279 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9280 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9281 mono_field_static_get_value (vtable, f, val);
9282 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9285 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
9289 case CMD_OBJECT_REF_SET_VALUES:
9290 len = decode_int (p, &p, end);
9292 for (i = 0; i < len; ++i) {
9293 f = decode_fieldid (p, &p, end, NULL, &err);
9297 /* Check that the field belongs to the object */
9299 for (k = obj->vtable->klass; k; k = k->parent) {
9300 if (k == f->parent) {
9306 return ERR_INVALID_FIELDID;
9308 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9312 if (mono_class_field_is_special_static (f))
9313 return ERR_INVALID_FIELDID;
9315 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9316 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9318 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9319 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
9324 mono_field_static_set_value (vtable, f, val);
9327 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
9333 case CMD_OBJECT_REF_GET_ADDRESS:
9334 buffer_add_long (buf, (gssize)obj);
9336 case CMD_OBJECT_REF_GET_DOMAIN:
9337 buffer_add_domainid (buf, obj->vtable->domain);
9339 case CMD_OBJECT_REF_GET_INFO:
9340 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9341 buffer_add_domainid (buf, obj->vtable->domain);
9344 return ERR_NOT_IMPLEMENTED;
9351 command_set_to_string (CommandSet command_set)
9353 switch (command_set) {
9356 case CMD_SET_OBJECT_REF:
9357 return "OBJECT_REF";
9358 case CMD_SET_STRING_REF:
9359 return "STRING_REF";
9360 case CMD_SET_THREAD:
9362 case CMD_SET_ARRAY_REF:
9364 case CMD_SET_EVENT_REQUEST:
9365 return "EVENT_REQUEST";
9366 case CMD_SET_STACK_FRAME:
9367 return "STACK_FRAME";
9368 case CMD_SET_APPDOMAIN:
9370 case CMD_SET_ASSEMBLY:
9372 case CMD_SET_METHOD:
9376 case CMD_SET_MODULE:
9387 static const char* vm_cmds_str [] = {
9395 "SET_PROTOCOL_VERSION",
9398 "GET_TYPES_FOR_SOURCE_FILE",
9403 static const char* thread_cmds_str[] = {
9413 static const char* event_cmds_str[] = {
9416 "REQUEST_CLEAR_ALL_BREAKPOINTS"
9419 static const char* appdomain_cmds_str[] = {
9421 "GET_FRIENDLY_NAME",
9423 "GET_ENTRY_ASSEMBLY",
9426 "CREATE_BOXED_VALUE"
9429 static const char* assembly_cmds_str[] = {
9432 "GET_MANIFEST_MODULE",
9438 static const char* module_cmds_str[] = {
9442 static const char* field_cmds_str[] = {
9446 static const char* method_cmds_str[] = {
9448 "GET_DECLARING_TYPE",
9456 "MAKE_GENERIC_METHOD"
9459 static const char* type_cmds_str[] = {
9467 "IS_ASSIGNABLE_FROM",
9471 "GET_PROPERTY_CATTRS",
9472 "GET_SOURCE_FILES_2",
9474 "GET_METHODS_BY_NAME_FLAGS",
9476 "GET_INTERFACE_MAP",
9480 static const char* stack_frame_cmds_str[] = {
9487 static const char* array_cmds_str[] = {
9493 static const char* string_cmds_str[] = {
9499 static const char* object_cmds_str[] = {
9510 cmd_to_string (CommandSet set, int command)
9518 cmds_len = G_N_ELEMENTS (vm_cmds_str);
9520 case CMD_SET_OBJECT_REF:
9521 cmds = object_cmds_str;
9522 cmds_len = G_N_ELEMENTS (object_cmds_str);
9524 case CMD_SET_STRING_REF:
9525 cmds = string_cmds_str;
9526 cmds_len = G_N_ELEMENTS (string_cmds_str);
9528 case CMD_SET_THREAD:
9529 cmds = thread_cmds_str;
9530 cmds_len = G_N_ELEMENTS (thread_cmds_str);
9532 case CMD_SET_ARRAY_REF:
9533 cmds = array_cmds_str;
9534 cmds_len = G_N_ELEMENTS (array_cmds_str);
9536 case CMD_SET_EVENT_REQUEST:
9537 cmds = event_cmds_str;
9538 cmds_len = G_N_ELEMENTS (event_cmds_str);
9540 case CMD_SET_STACK_FRAME:
9541 cmds = stack_frame_cmds_str;
9542 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
9544 case CMD_SET_APPDOMAIN:
9545 cmds = appdomain_cmds_str;
9546 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
9548 case CMD_SET_ASSEMBLY:
9549 cmds = assembly_cmds_str;
9550 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
9552 case CMD_SET_METHOD:
9553 cmds = method_cmds_str;
9554 cmds_len = G_N_ELEMENTS (method_cmds_str);
9557 cmds = type_cmds_str;
9558 cmds_len = G_N_ELEMENTS (type_cmds_str);
9560 case CMD_SET_MODULE:
9561 cmds = module_cmds_str;
9562 cmds_len = G_N_ELEMENTS (module_cmds_str);
9565 cmds = field_cmds_str;
9566 cmds_len = G_N_ELEMENTS (field_cmds_str);
9569 cmds = event_cmds_str;
9570 cmds_len = G_N_ELEMENTS (event_cmds_str);
9575 if (command > 0 && command <= cmds_len)
9576 return cmds [command - 1];
9582 wait_for_attach (void)
9584 #ifndef DISABLE_SOCKET_TRANSPORT
9585 if (listen_fd == -1) {
9586 DEBUG_PRINTF (1, "[dbg] Invalid listening socket\n");
9590 /* Block and wait for client connection */
9591 conn_fd = socket_transport_accept (listen_fd);
9592 DEBUG_PRINTF (1, "Accepted connection on %d\n", conn_fd);
9593 if (conn_fd == -1) {
9594 DEBUG_PRINTF (1, "[dbg] Bad client connection\n");
9598 g_assert_not_reached ();
9602 disconnected = !transport_handshake ();
9604 DEBUG_PRINTF (1, "Transport handshake failed!\n");
9614 * This thread handles communication with the debugger client using a JDWP
9617 static guint32 WINAPI
9618 debugger_thread (void *arg)
9620 int res, len, id, flags, command_set = 0, command = 0;
9621 guint8 header [HEADER_LENGTH];
9622 guint8 *data, *p, *end;
9626 gboolean attach_failed = FALSE;
9628 DEBUG_PRINTF (1, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ());
9630 debugger_thread_id = GetCurrentThreadId ();
9632 mono_jit_thread_attach (mono_get_root_domain ());
9634 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
9636 mono_set_is_debugger_attached (TRUE);
9638 if (agent_config.defer) {
9639 if (!wait_for_attach ()) {
9640 DEBUG_PRINTF (1, "[dbg] Can't attach, aborting debugger thread.\n");
9641 attach_failed = TRUE; // Don't abort process when we can't listen
9643 /* Send start event to client */
9644 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
9648 while (!attach_failed) {
9649 res = transport_recv (header, HEADER_LENGTH);
9651 /* This will break if the socket is closed during shutdown too */
9652 if (res != HEADER_LENGTH) {
9653 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH);
9658 end = header + HEADER_LENGTH;
9660 len = decode_int (p, &p, end);
9661 id = decode_int (p, &p, end);
9662 flags = decode_byte (p, &p, end);
9663 command_set = decode_byte (p, &p, end);
9664 command = decode_byte (p, &p, end);
9666 g_assert (flags == 0);
9669 const char *cmd_str;
9672 cmd_str = cmd_to_string (command_set, command);
9674 sprintf (cmd_num, "%d", command);
9678 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);
9681 data = g_malloc (len - HEADER_LENGTH);
9682 if (len - HEADER_LENGTH > 0)
9684 res = transport_recv (data, len - HEADER_LENGTH);
9685 if (res != len - HEADER_LENGTH) {
9686 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH);
9692 end = data + (len - HEADER_LENGTH);
9694 buffer_init (&buf, 128);
9699 /* Process the request */
9700 switch (command_set) {
9702 err = vm_commands (command, id, p, end, &buf);
9703 if (!err && command == CMD_VM_INVOKE_METHOD)
9704 /* Sent after the invoke is complete */
9707 case CMD_SET_EVENT_REQUEST:
9708 err = event_commands (command, p, end, &buf);
9710 case CMD_SET_APPDOMAIN:
9711 err = domain_commands (command, p, end, &buf);
9713 case CMD_SET_ASSEMBLY:
9714 err = assembly_commands (command, p, end, &buf);
9716 case CMD_SET_MODULE:
9717 err = module_commands (command, p, end, &buf);
9720 err = field_commands (command, p, end, &buf);
9723 err = type_commands (command, p, end, &buf);
9725 case CMD_SET_METHOD:
9726 err = method_commands (command, p, end, &buf);
9728 case CMD_SET_THREAD:
9729 err = thread_commands (command, p, end, &buf);
9731 case CMD_SET_STACK_FRAME:
9732 err = frame_commands (command, p, end, &buf);
9734 case CMD_SET_ARRAY_REF:
9735 err = array_commands (command, p, end, &buf);
9737 case CMD_SET_STRING_REF:
9738 err = string_commands (command, p, end, &buf);
9740 case CMD_SET_OBJECT_REF:
9741 err = object_commands (command, p, end, &buf);
9744 err = ERR_NOT_IMPLEMENTED;
9747 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
9748 buffer_replies = TRUE;
9752 if (buffer_replies) {
9753 buffer_reply_packet (id, err, &buf);
9755 send_reply_packet (id, err, &buf);
9756 //DEBUG_PRINTF (1, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000);
9760 if (!err && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
9761 send_buffered_reply_packets ();
9762 buffer_replies = FALSE;
9768 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
9772 mono_set_is_debugger_attached (FALSE);
9774 mono_mutex_lock (&debugger_thread_exited_mutex);
9775 debugger_thread_exited = TRUE;
9776 mono_cond_signal (&debugger_thread_exited_cond);
9777 mono_mutex_unlock (&debugger_thread_exited_mutex);
9779 DEBUG_PRINTF (1, "[dbg] Debugger thread exited.\n");
9781 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
9782 DEBUG_PRINTF (2, "[dbg] Detached - restarting clean debugger thread.\n");
9783 start_debugger_thread ();
9789 #else /* DISABLE_DEBUGGER_AGENT */
9792 mono_debugger_agent_parse_options (char *options)
9794 g_error ("This runtime is configured with the debugger agent disabled.");
9798 mono_debugger_agent_init (void)
9803 mono_debugger_agent_breakpoint_hit (void *sigctx)
9808 mono_debugger_agent_single_step_event (void *sigctx)
9813 mono_debugger_agent_free_domain_info (MonoDomain *domain)
9818 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
9824 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
9825 MonoContext *catch_ctx)
9830 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9835 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9840 mono_debugger_agent_user_break (void)
9846 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
9851 mono_debugger_agent_debug_log_is_enabled (void)
9857 mono_debugger_agent_unhandled_exception (MonoException *exc)
9859 g_assert_not_reached ();
9863 debugger_agent_single_step_from_context (MonoContext *ctx)
9865 g_assert_not_reached ();
9869 debugger_agent_breakpoint_from_context (MonoContext *ctx)
9871 g_assert_not_reached ();