2 * debugger-agent.c: Soft Debugger back-end module
5 * Zoltan Varga (vargaz@gmail.com)
7 * Copyright 2009-2010 Novell, Inc.
8 * Copyright 2011 Xamarin Inc.
9 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
16 #ifdef HAVE_SYS_TYPES_H
17 #include <sys/types.h>
19 #ifdef HAVE_SYS_SELECT_H
20 #include <sys/select.h>
22 #ifdef HAVE_SYS_SOCKET_H
23 #include <sys/socket.h>
25 #ifdef HAVE_NETINET_TCP_H
26 #include <netinet/tcp.h>
28 #ifdef HAVE_NETINET_IN_H
29 #include <netinet/in.h>
49 #ifdef PLATFORM_ANDROID
51 #include <linux/tcp.h>
52 #include <sys/endian.h>
55 #include <mono/metadata/mono-debug.h>
56 #include <mono/metadata/debug-internals.h>
57 #include <mono/metadata/gc-internals.h>
58 #include <mono/metadata/environment.h>
59 #include <mono/metadata/threads-types.h>
60 #include <mono/metadata/threadpool.h>
61 #include <mono/metadata/assembly.h>
62 #include <mono/metadata/runtime.h>
63 #include <mono/metadata/verify-internals.h>
64 #include <mono/metadata/reflection-internals.h>
65 #include <mono/metadata/w32socket.h>
66 #include <mono/utils/mono-coop-mutex.h>
67 #include <mono/utils/mono-coop-semaphore.h>
68 #include <mono/utils/mono-error-internals.h>
69 #include <mono/utils/mono-stack-unwinding.h>
70 #include <mono/utils/mono-time.h>
71 #include <mono/utils/mono-threads.h>
72 #include <mono/utils/networking.h>
73 #include <mono/utils/mono-proclib.h>
74 #include "debugger-agent.h"
76 #include "seq-points.h"
77 #include <mono/utils/w32api.h>
80 * On iOS we can't use System.Environment.Exit () as it will do the wrong
83 #if !defined (TARGET_IOS)
84 #define TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
88 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
89 #define DISABLE_DEBUGGER_AGENT 1
92 #ifdef DISABLE_SOFT_DEBUG
93 #define DISABLE_DEBUGGER_AGENT 1
96 #ifndef DISABLE_DEBUGGER_AGENT
98 #include <mono/utils/mono-os-mutex.h>
100 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
123 guint32 il_offset, native_offset;
127 * If method is gshared, this is the actual instance, otherwise this is equal to
130 MonoMethod *actual_method;
132 * This is the method which is visible to debugger clients. Same as method,
133 * except for native-to-managed wrappers.
135 MonoMethod *api_method;
137 MonoDebugMethodJitInfo *jit;
140 mgreg_t *reg_locations [MONO_MAX_IREGS];
142 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
143 * the frame can become invalid.
148 typedef struct _InvokeData InvokeData;
156 /* This is the context which needs to be restored after the invoke */
160 * If this is set, invoke this method with the arguments given by ARGS.
164 guint32 suspend_count;
167 InvokeData *last_invoke;
171 MonoThreadUnwindState context;
173 /* This is computed on demand when it is requested using the wire protocol */
174 /* It is freed up when the thread is resumed */
178 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
181 gboolean frames_up_to_date;
183 * Points to data about a pending invoke which needs to be executed after the thread
186 InvokeData *pending_invoke;
188 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
193 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
194 * within a finite amount of time.
198 * Set to TRUE if this thread is suspended in suspend_current ().
200 gboolean really_suspended;
201 /* Used to pass the context to the breakpoint/single step handler */
202 MonoContext handler_ctx;
203 /* Whenever thread_stop () was called for this thread */
206 /* Whenever to disable breakpoints (used during invokes) */
207 gboolean disable_breakpoints;
210 * Number of times this thread has been resumed using resume_thread ().
212 guint32 resume_count;
214 MonoInternalThread *thread;
217 * Information about the frame which transitioned to native code for running
220 StackFrameInfo async_last_frame;
223 * The context where the stack walk can be started for running threads.
225 MonoThreadUnwindState async_state;
228 * The context used for filter clauses
230 MonoThreadUnwindState filter_state;
232 gboolean abort_requested;
235 * The current mono_runtime_invoke_checked invocation.
240 * The context where single stepping should resume while the thread is suspended because
241 * of an EXCEPTION event.
243 MonoThreadUnwindState catch_state;
246 * The context which needs to be restored after handling a single step/breakpoint
247 * event. This is the same as the ctx at step/breakpoint site, but includes changes
248 * to caller saved registers done by set_var ().
250 MonoThreadUnwindState restore_state;
251 /* Frames computed from restore_state */
252 int restore_frame_count;
253 StackFrame **restore_frames;
255 /* The currently unloading appdomain */
256 MonoDomain *domain_unloading;
261 void (*connect) (const char *address);
262 void (*close1) (void);
263 void (*close2) (void);
264 gboolean (*send) (void *buf, int len);
265 int (*recv) (void *buf, int len);
269 * Wire Protocol definitions
272 #define HEADER_LENGTH 11
274 #define MAJOR_VERSION 2
275 #define MINOR_VERSION 45
279 CMD_SET_OBJECT_REF = 9,
280 CMD_SET_STRING_REF = 10,
282 CMD_SET_ARRAY_REF = 13,
283 CMD_SET_EVENT_REQUEST = 15,
284 CMD_SET_STACK_FRAME = 16,
285 CMD_SET_APPDOMAIN = 20,
286 CMD_SET_ASSEMBLY = 21,
295 EVENT_KIND_VM_START = 0,
296 EVENT_KIND_VM_DEATH = 1,
297 EVENT_KIND_THREAD_START = 2,
298 EVENT_KIND_THREAD_DEATH = 3,
299 EVENT_KIND_APPDOMAIN_CREATE = 4,
300 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
301 EVENT_KIND_METHOD_ENTRY = 6,
302 EVENT_KIND_METHOD_EXIT = 7,
303 EVENT_KIND_ASSEMBLY_LOAD = 8,
304 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
305 EVENT_KIND_BREAKPOINT = 10,
306 EVENT_KIND_STEP = 11,
307 EVENT_KIND_TYPE_LOAD = 12,
308 EVENT_KIND_EXCEPTION = 13,
309 EVENT_KIND_KEEPALIVE = 14,
310 EVENT_KIND_USER_BREAK = 15,
311 EVENT_KIND_USER_LOG = 16
315 SUSPEND_POLICY_NONE = 0,
316 SUSPEND_POLICY_EVENT_THREAD = 1,
317 SUSPEND_POLICY_ALL = 2
322 ERR_INVALID_OBJECT = 20,
323 ERR_INVALID_FIELDID = 25,
324 ERR_INVALID_FRAMEID = 30,
325 ERR_NOT_IMPLEMENTED = 100,
326 ERR_NOT_SUSPENDED = 101,
327 ERR_INVALID_ARGUMENT = 102,
329 ERR_NO_INVOCATION = 104,
330 ERR_ABSENT_INFORMATION = 105,
331 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
332 ERR_INVOKE_ABORTED = 107,
333 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
338 MOD_KIND_THREAD_ONLY = 3,
339 MOD_KIND_LOCATION_ONLY = 7,
340 MOD_KIND_EXCEPTION_ONLY = 8,
342 MOD_KIND_ASSEMBLY_ONLY = 11,
343 MOD_KIND_SOURCE_FILE_ONLY = 12,
344 MOD_KIND_TYPE_NAME_ONLY = 13,
360 STEP_FILTER_NONE = 0,
361 STEP_FILTER_STATIC_CTOR = 1,
362 STEP_FILTER_DEBUGGER_HIDDEN = 2,
363 STEP_FILTER_DEBUGGER_STEP_THROUGH = 4,
364 STEP_FILTER_DEBUGGER_NON_USER_CODE = 8
368 TOKEN_TYPE_STRING = 0,
370 TOKEN_TYPE_FIELD = 2,
371 TOKEN_TYPE_METHOD = 3,
372 TOKEN_TYPE_UNKNOWN = 4
376 VALUE_TYPE_ID_NULL = 0xf0,
377 VALUE_TYPE_ID_TYPE = 0xf1,
378 VALUE_TYPE_ID_PARENT_VTYPE = 0xf2
382 FRAME_FLAG_DEBUGGER_INVOKE = 1,
383 FRAME_FLAG_NATIVE_TRANSITION = 2
387 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
388 INVOKE_FLAG_SINGLE_THREADED = 2,
389 INVOKE_FLAG_RETURN_OUT_THIS = 4,
390 INVOKE_FLAG_RETURN_OUT_ARGS = 8,
391 INVOKE_FLAG_VIRTUAL = 16
395 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
396 } BindingFlagsExtensions;
400 CMD_VM_ALL_THREADS = 2,
405 CMD_VM_INVOKE_METHOD = 7,
406 CMD_VM_SET_PROTOCOL_VERSION = 8,
407 CMD_VM_ABORT_INVOKE = 9,
408 CMD_VM_SET_KEEPALIVE = 10,
409 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
410 CMD_VM_GET_TYPES = 12,
411 CMD_VM_INVOKE_METHODS = 13,
412 CMD_VM_START_BUFFERING = 14,
413 CMD_VM_STOP_BUFFERING = 15
417 CMD_THREAD_GET_FRAME_INFO = 1,
418 CMD_THREAD_GET_NAME = 2,
419 CMD_THREAD_GET_STATE = 3,
420 CMD_THREAD_GET_INFO = 4,
421 CMD_THREAD_GET_ID = 5,
422 CMD_THREAD_GET_TID = 6,
423 CMD_THREAD_SET_IP = 7
427 CMD_EVENT_REQUEST_SET = 1,
428 CMD_EVENT_REQUEST_CLEAR = 2,
429 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
437 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
438 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
439 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
440 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
441 CMD_APPDOMAIN_CREATE_STRING = 5,
442 CMD_APPDOMAIN_GET_CORLIB = 6,
443 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
447 CMD_ASSEMBLY_GET_LOCATION = 1,
448 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
449 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
450 CMD_ASSEMBLY_GET_OBJECT = 4,
451 CMD_ASSEMBLY_GET_TYPE = 5,
452 CMD_ASSEMBLY_GET_NAME = 6,
453 CMD_ASSEMBLY_GET_DOMAIN = 7
457 CMD_MODULE_GET_INFO = 1,
461 CMD_FIELD_GET_INFO = 1,
465 CMD_METHOD_GET_NAME = 1,
466 CMD_METHOD_GET_DECLARING_TYPE = 2,
467 CMD_METHOD_GET_DEBUG_INFO = 3,
468 CMD_METHOD_GET_PARAM_INFO = 4,
469 CMD_METHOD_GET_LOCALS_INFO = 5,
470 CMD_METHOD_GET_INFO = 6,
471 CMD_METHOD_GET_BODY = 7,
472 CMD_METHOD_RESOLVE_TOKEN = 8,
473 CMD_METHOD_GET_CATTRS = 9,
474 CMD_METHOD_MAKE_GENERIC_METHOD = 10
478 CMD_TYPE_GET_INFO = 1,
479 CMD_TYPE_GET_METHODS = 2,
480 CMD_TYPE_GET_FIELDS = 3,
481 CMD_TYPE_GET_VALUES = 4,
482 CMD_TYPE_GET_OBJECT = 5,
483 CMD_TYPE_GET_SOURCE_FILES = 6,
484 CMD_TYPE_SET_VALUES = 7,
485 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
486 CMD_TYPE_GET_PROPERTIES = 9,
487 CMD_TYPE_GET_CATTRS = 10,
488 CMD_TYPE_GET_FIELD_CATTRS = 11,
489 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
490 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
491 CMD_TYPE_GET_VALUES_2 = 14,
492 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
493 CMD_TYPE_GET_INTERFACES = 16,
494 CMD_TYPE_GET_INTERFACE_MAP = 17,
495 CMD_TYPE_IS_INITIALIZED = 18,
496 CMD_TYPE_CREATE_INSTANCE = 19
500 CMD_STACK_FRAME_GET_VALUES = 1,
501 CMD_STACK_FRAME_GET_THIS = 2,
502 CMD_STACK_FRAME_SET_VALUES = 3,
503 CMD_STACK_FRAME_GET_DOMAIN = 4,
504 CMD_STACK_FRAME_SET_THIS = 5,
508 CMD_ARRAY_REF_GET_LENGTH = 1,
509 CMD_ARRAY_REF_GET_VALUES = 2,
510 CMD_ARRAY_REF_SET_VALUES = 3,
514 CMD_STRING_REF_GET_VALUE = 1,
515 CMD_STRING_REF_GET_LENGTH = 2,
516 CMD_STRING_REF_GET_CHARS = 3
520 CMD_OBJECT_REF_GET_TYPE = 1,
521 CMD_OBJECT_REF_GET_VALUES = 2,
522 CMD_OBJECT_REF_IS_COLLECTED = 3,
523 CMD_OBJECT_REF_GET_ADDRESS = 4,
524 CMD_OBJECT_REF_GET_DOMAIN = 5,
525 CMD_OBJECT_REF_SET_VALUES = 6,
526 CMD_OBJECT_REF_GET_INFO = 7,
532 int count; /* For kind == MOD_KIND_COUNT */
533 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
534 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
535 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
536 GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
537 GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
538 StepFilter filter; /* For kind == MOD_KIND_STEP */
540 gboolean caught, uncaught, subclasses; /* For kind == MOD_KIND_EXCEPTION_ONLY */
549 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
553 * Describes a single step request.
557 MonoInternalThread *thread;
563 MonoMethod *start_method;
564 MonoMethod *last_method;
566 /* Whenever single stepping is performed using start/stop_single_stepping () */
568 /* The list of breakpoints used to implement step-over */
570 /* The number of frames at the start of a step-over */
572 /* If set, don't stop in methods that are not part of user assemblies */
573 MonoAssembly** user_assemblies;
574 /* Used to distinguish stepping breakpoint hits in parallel tasks executions */
576 /* Used to know if we are in process of async step-out and distishing from exception breakpoints */
577 MonoMethod* async_stepout_method;
581 * Contains additional information for an event
584 /* For EVENT_KIND_EXCEPTION */
586 MonoContext catch_ctx;
588 /* For EVENT_KIND_USER_LOG */
590 char *category, *message;
591 /* For EVENT_KIND_TYPE_LOAD */
595 /* Dummy structure used for the profiler callbacks */
601 guint8 *buf, *p, *end;
604 typedef struct ReplyPacket {
610 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
612 #ifdef PLATFORM_ANDROID
613 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { g_print (__VA_ARGS__); } } while (0)
615 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { fprintf (log_file, __VA_ARGS__); fflush (log_file); } } while (0)
619 #define get_last_sock_error() WSAGetLastError()
620 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
621 #define MONO_EINTR WSAEINTR
623 #define get_last_sock_error() errno
624 #define MONO_EWOULDBLOCK EWOULDBLOCK
625 #define MONO_EINTR EINTR
628 #define CHECK_PROTOCOL_VERSION(major,minor) \
629 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
635 static AgentConfig agent_config;
638 * Whenever the agent is fully initialized.
639 * When using the onuncaught or onthrow options, only some parts of the agent are
640 * initialized on startup, and the full initialization which includes connection
641 * establishment and the startup of the agent thread is only done in response to
644 static gint32 inited;
646 #ifndef DISABLE_SOCKET_TRANSPORT
648 static int listen_fd;
651 static int packet_id = 0;
653 static int objref_id = 0;
655 static int event_request_id = 0;
657 static int frame_id = 0;
659 static GPtrArray *event_requests;
661 static MonoNativeTlsKey debugger_tls_id;
663 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
665 /* Maps MonoInternalThread -> DebuggerTlsData */
666 /* Protected by the loader lock */
667 static MonoGHashTable *thread_to_tls;
669 /* Maps tid -> MonoInternalThread */
670 /* Protected by the loader lock */
671 static MonoGHashTable *tid_to_thread;
673 /* Maps tid -> MonoThread (not MonoInternalThread) */
674 /* Protected by the loader lock */
675 static MonoGHashTable *tid_to_thread_obj;
677 static MonoNativeThreadId debugger_thread_id;
679 static MonoThreadHandle *debugger_thread_handle;
681 static int log_level;
683 static gboolean embedding;
685 static FILE *log_file;
687 /* Assemblies whose assembly load event has no been sent yet */
688 /* Protected by the dbg lock */
689 static GPtrArray *pending_assembly_loads;
691 /* Whenever the debugger thread has exited */
692 static gboolean debugger_thread_exited;
694 /* Cond variable used to wait for debugger_thread_exited becoming true */
695 static MonoCoopCond debugger_thread_exited_cond;
697 /* Mutex for the cond var above */
698 static MonoCoopMutex debugger_thread_exited_mutex;
700 static DebuggerProfiler debugger_profiler;
702 /* The single step request instance */
703 static SingleStepReq *ss_req;
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 /* Protected by the loader lock */
718 static GHashTable *domains;
720 /* The number of times the runtime is suspended */
721 static gint32 suspend_count;
723 /* Whenever to buffer reply messages and send them together */
724 static gboolean buffer_replies;
726 /* Buffered reply packets */
727 static ReplyPacket reply_packets [128];
730 #define dbg_lock() mono_coop_mutex_lock (&debug_mutex)
731 #define dbg_unlock() mono_coop_mutex_unlock (&debug_mutex)
732 static MonoCoopMutex debug_mutex;
734 static void transport_init (void);
735 static void transport_connect (const char *address);
736 static gboolean transport_handshake (void);
737 static void register_transport (DebuggerTransport *trans);
739 static gsize WINAPI debugger_thread (void *arg);
741 static void runtime_initialized (MonoProfiler *prof);
743 static void runtime_shutdown (MonoProfiler *prof);
745 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
747 static void thread_end (MonoProfiler *prof, uintptr_t tid);
749 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
751 static void appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain);
753 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
755 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
757 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
759 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
761 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
763 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
765 static void emit_assembly_load (gpointer assembly, gpointer user_data);
767 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
769 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
771 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
773 static void start_single_stepping (void);
775 static void stop_single_stepping (void);
777 static void suspend_current (void);
779 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
781 static void clear_types_for_assembly (MonoAssembly *assembly);
783 static void clear_breakpoints_for_domain (MonoDomain *domain);
785 static void process_profiler_event (EventKind event, gpointer arg);
787 /* Submodule init/cleanup */
788 static void breakpoints_init (void);
789 static void breakpoints_cleanup (void);
791 static void objrefs_init (void);
792 static void objrefs_cleanup (void);
794 static void ids_init (void);
795 static void ids_cleanup (void);
797 static void suspend_init (void);
799 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch,
800 StackFrame **frames, int nframes);
801 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req);
802 static void ss_destroy (SingleStepReq *req);
804 static void start_debugger_thread (void);
805 static void stop_debugger_thread (void);
807 static void finish_agent_init (gboolean on_startup);
809 static void process_profiler_event (EventKind event, gpointer arg);
811 static void invalidate_frames (DebuggerTlsData *tls);
813 #ifndef DISABLE_SOCKET_TRANSPORT
815 register_socket_transport (void);
818 static inline gboolean
819 is_debugger_thread (void)
821 return mono_native_thread_id_equals (mono_native_thread_id_get (), debugger_thread_id);
825 parse_address (char *address, char **host, int *port)
827 char *pos = strchr (address, ':');
829 if (pos == NULL || pos == address)
832 size_t len = pos - address;
833 *host = (char *)g_malloc (len + 1);
834 memcpy (*host, address, len);
835 (*host) [len] = '\0';
837 *port = atoi (pos + 1);
845 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
846 fprintf (stderr, "Available options:\n");
847 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
848 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
849 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
850 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
851 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
852 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
853 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
854 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
855 fprintf (stderr, " setpgid=y/n\t\t\tWhether to call setpid(0, 0) after startup.\n");
856 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
860 parse_flag (const char *option, char *flag)
862 if (!strcmp (flag, "y"))
864 else if (!strcmp (flag, "n"))
867 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
874 mono_debugger_agent_parse_options (char *options)
881 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
882 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
886 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
888 options = g_strdup_printf ("%s,%s", options, extra);
890 agent_config.enabled = TRUE;
891 agent_config.suspend = TRUE;
892 agent_config.server = FALSE;
893 agent_config.defer = FALSE;
894 agent_config.address = NULL;
896 //agent_config.log_level = 10;
898 args = g_strsplit (options, ",", -1);
899 for (ptr = args; ptr && *ptr; ptr ++) {
902 if (strncmp (arg, "transport=", 10) == 0) {
903 agent_config.transport = g_strdup (arg + 10);
904 } else if (strncmp (arg, "address=", 8) == 0) {
905 agent_config.address = g_strdup (arg + 8);
906 } else if (strncmp (arg, "loglevel=", 9) == 0) {
907 agent_config.log_level = atoi (arg + 9);
908 } else if (strncmp (arg, "logfile=", 8) == 0) {
909 agent_config.log_file = g_strdup (arg + 8);
910 } else if (strncmp (arg, "suspend=", 8) == 0) {
911 agent_config.suspend = parse_flag ("suspend", arg + 8);
912 } else if (strncmp (arg, "server=", 7) == 0) {
913 agent_config.server = parse_flag ("server", arg + 7);
914 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
915 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
916 } else if (strncmp (arg, "onthrow=", 8) == 0) {
917 /* We support multiple onthrow= options */
918 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
919 } else if (strncmp (arg, "onthrow", 7) == 0) {
920 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
921 } else if (strncmp (arg, "help", 4) == 0) {
924 } else if (strncmp (arg, "timeout=", 8) == 0) {
925 agent_config.timeout = atoi (arg + 8);
926 } else if (strncmp (arg, "launch=", 7) == 0) {
927 agent_config.launch = g_strdup (arg + 7);
928 } else if (strncmp (arg, "embedding=", 10) == 0) {
929 agent_config.embedding = atoi (arg + 10) == 1;
930 } else if (strncmp (arg, "keepalive=", 10) == 0) {
931 agent_config.keepalive = atoi (arg + 10);
932 } else if (strncmp (arg, "setpgid=", 8) == 0) {
933 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
940 if (agent_config.server && !agent_config.suspend) {
941 /* Waiting for deferred attachment */
942 agent_config.defer = TRUE;
943 if (agent_config.address == NULL) {
944 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (mono_process_current_pid () % 1000));
948 //agent_config.log_level = 0;
950 if (agent_config.transport == NULL) {
951 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
955 if (agent_config.address == NULL && !agent_config.server) {
956 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
961 if (!strcmp (agent_config.transport, "dt_socket")) {
962 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
963 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
970 mono_debugger_agent_init (void)
972 mono_coop_mutex_init_recursive (&debug_mutex);
974 if (!agent_config.enabled)
979 /* Need to know whenever a thread has acquired the loader mutex */
980 mono_loader_lock_track_ownership (TRUE);
982 event_requests = g_ptr_array_new ();
984 mono_coop_mutex_init (&debugger_thread_exited_mutex);
985 mono_coop_cond_init (&debugger_thread_exited_cond);
987 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
988 mono_profiler_set_events ((MonoProfileFlags)(MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS));
989 mono_profiler_install_runtime_initialized (runtime_initialized);
990 mono_profiler_install_appdomain (NULL, appdomain_load, appdomain_start_unload, appdomain_unload);
991 mono_profiler_install_thread (thread_startup, thread_end);
992 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
993 mono_profiler_install_jit_end (jit_end);
995 mono_native_tls_alloc (&debugger_tls_id, NULL);
997 /* Needed by the hash_table_new_type () call below */
998 mono_gc_base_init ();
1000 thread_to_tls = mono_g_hash_table_new_type ((GHashFunc)mono_object_hash, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_DEBUGGER, "thread-to-tls table");
1002 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread table");
1004 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread object table");
1006 pending_assembly_loads = g_ptr_array_new ();
1007 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
1009 log_level = agent_config.log_level;
1011 embedding = agent_config.embedding;
1012 disconnected = TRUE;
1014 if (agent_config.log_file) {
1015 log_file = fopen (agent_config.log_file, "w+");
1017 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
1026 breakpoints_init ();
1029 mini_get_debug_options ()->gen_sdb_seq_points = TRUE;
1031 * This is needed because currently we don't handle liveness info.
1033 mini_get_debug_options ()->mdb_optimizations = TRUE;
1035 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
1036 /* This is needed because we can't set local variables in registers yet */
1037 mono_disable_optimizations (MONO_OPT_LINEARS);
1041 * The stack walk done from thread_interrupt () needs to be signal safe, but it
1042 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
1043 * safe (#3411). So load AOT info eagerly when the debugger is running as a
1046 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
1049 if (agent_config.setpgid)
1053 if (!agent_config.onuncaught && !agent_config.onthrow)
1054 finish_agent_init (TRUE);
1058 * finish_agent_init:
1060 * Finish the initialization of the agent. This involves connecting the transport
1061 * and starting the agent thread. This is either done at startup, or
1062 * in response to some event like an unhandled exception.
1065 finish_agent_init (gboolean on_startup)
1069 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
1072 if (agent_config.launch) {
1075 // FIXME: Generated address
1076 // FIXME: Races with transport_connect ()
1078 argv [0] = agent_config.launch;
1079 argv [1] = agent_config.transport;
1080 argv [2] = agent_config.address;
1083 res = g_spawn_async_with_pipes (NULL, argv, NULL, (GSpawnFlags)0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1085 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1090 transport_connect (agent_config.address);
1093 /* Do some which is usually done after sending the VMStart () event */
1094 vm_start_event_sent = TRUE;
1095 start_debugger_thread ();
1100 mono_debugger_agent_cleanup (void)
1105 stop_debugger_thread ();
1107 breakpoints_cleanup ();
1116 #ifndef DISABLE_SOCKET_TRANSPORT
1121 * recv() + handle incomplete reads and EINTR
1124 socket_transport_recv (void *buf, int len)
1130 static gint64 last_keepalive;
1137 res = recv (fd, (char *) buf + total, len - total, flags);
1140 if (agent_config.keepalive) {
1141 gboolean need_keepalive = FALSE;
1142 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1143 need_keepalive = TRUE;
1144 } else if (res == -1) {
1145 /* This could happen if recv () is interrupted repeatedly */
1146 msecs = mono_msec_ticks ();
1147 if (msecs - last_keepalive >= agent_config.keepalive) {
1148 need_keepalive = TRUE;
1149 last_keepalive = msecs;
1152 if (need_keepalive) {
1153 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1157 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1165 set_keepalive (void)
1170 if (!agent_config.keepalive || !conn_fd)
1173 tv.tv_sec = agent_config.keepalive / 1000;
1174 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1176 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1177 g_assert (result >= 0);
1181 socket_transport_accept (int socket_fd)
1184 conn_fd = accept (socket_fd, NULL, NULL);
1187 if (conn_fd == -1) {
1188 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1190 DEBUG_PRINTF (1, "Accepted connection from client, connection fd=%d.\n", conn_fd);
1197 socket_transport_send (void *data, int len)
1204 res = send (conn_fd, data, len, 0);
1205 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1216 * socket_transport_connect:
1218 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1221 socket_transport_connect (const char *address)
1223 MonoAddressInfo *result;
1224 MonoAddressEntry *rp;
1225 int sfd = -1, s, res;
1229 if (agent_config.address) {
1230 res = parse_address (agent_config.address, &host, &port);
1231 g_assert (res == 0);
1242 mono_network_init ();
1244 /* Obtain address(es) matching host/port */
1245 s = mono_get_address_info (host, port, MONO_HINT_UNSPECIFIED, &result);
1247 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, s); // FIXME add portable error conversion functions
1252 if (agent_config.server) {
1253 /* Wait for a connection */
1255 struct sockaddr_in addr;
1258 /* No address, generate one */
1259 sfd = socket (AF_INET, SOCK_STREAM, 0);
1262 /* This will bind the socket to a random port */
1263 res = listen (sfd, 16);
1265 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1270 addrlen = sizeof (addr);
1271 memset (&addr, 0, sizeof (addr));
1272 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1273 g_assert (res == 0);
1275 host = (char*)"127.0.0.1";
1276 port = ntohs (addr.sin_port);
1278 /* Emit the address to stdout */
1279 /* FIXME: Should print another interface, not localhost */
1280 printf ("%s:%d\n", host, port);
1282 /* Listen on the provided address */
1283 for (rp = result->entries; rp != NULL; rp = rp->next) {
1284 MonoSocketAddress sockaddr;
1288 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1290 sfd = socket (rp->family, rp->socktype,
1295 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1298 res = bind (sfd, &sockaddr.addr, sock_len);
1302 res = listen (sfd, 16);
1309 mono_free_address_info (result);
1312 if (agent_config.defer)
1315 DEBUG_PRINTF (1, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout);
1317 if (agent_config.timeout) {
1322 tv.tv_usec = agent_config.timeout * 1000;
1324 FD_SET (sfd, &readfds);
1327 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1331 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1336 conn_fd = socket_transport_accept (sfd);
1340 DEBUG_PRINTF (1, "Accepted connection from client, socket fd=%d.\n", conn_fd);
1342 /* Connect to the specified address */
1343 /* FIXME: Respect the timeout */
1344 for (rp = result->entries; rp != NULL; rp = rp->next) {
1345 MonoSocketAddress sockaddr;
1348 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1350 sfd = socket (rp->family, rp->socktype,
1356 res = connect (sfd, &sockaddr.addr, sock_len);
1360 break; /* Success */
1368 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1374 mono_free_address_info (result);
1377 if (!transport_handshake ())
1382 socket_transport_close1 (void)
1384 /* This will interrupt the agent thread */
1385 /* Close the read part only so it can still send back replies */
1386 /* Also shut down the connection listener so that we can exit normally */
1388 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1389 shutdown (conn_fd, SD_BOTH);
1390 shutdown (listen_fd, SD_BOTH);
1391 closesocket (listen_fd);
1393 shutdown (conn_fd, SHUT_RD);
1394 shutdown (listen_fd, SHUT_RDWR);
1402 socket_transport_close2 (void)
1405 shutdown (conn_fd, SD_BOTH);
1407 shutdown (conn_fd, SHUT_RDWR);
1412 register_socket_transport (void)
1414 DebuggerTransport trans;
1416 trans.name = "dt_socket";
1417 trans.connect = socket_transport_connect;
1418 trans.close1 = socket_transport_close1;
1419 trans.close2 = socket_transport_close2;
1420 trans.send = socket_transport_send;
1421 trans.recv = socket_transport_recv;
1423 register_transport (&trans);
1427 * socket_fd_transport_connect:
1431 socket_fd_transport_connect (const char *address)
1435 res = sscanf (address, "%d", &conn_fd);
1437 fprintf (stderr, "debugger-agent: socket-fd transport address is invalid: '%s'\n", address);
1441 if (!transport_handshake ())
1446 register_socket_fd_transport (void)
1448 DebuggerTransport trans;
1450 /* This is the same as the 'dt_socket' transport, but receives an already connected socket fd */
1451 trans.name = "socket-fd";
1452 trans.connect = socket_fd_transport_connect;
1453 trans.close1 = socket_transport_close1;
1454 trans.close2 = socket_transport_close2;
1455 trans.send = socket_transport_send;
1456 trans.recv = socket_transport_recv;
1458 register_transport (&trans);
1461 #endif /* DISABLE_SOCKET_TRANSPORT */
1467 #define MAX_TRANSPORTS 16
1469 static DebuggerTransport *transport;
1471 static DebuggerTransport transports [MAX_TRANSPORTS];
1472 static int ntransports;
1475 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1478 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1480 register_transport (trans);
1484 register_transport (DebuggerTransport *trans)
1486 g_assert (ntransports < MAX_TRANSPORTS);
1488 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1493 transport_init (void)
1497 #ifndef DISABLE_SOCKET_TRANSPORT
1498 register_socket_transport ();
1499 register_socket_fd_transport ();
1502 for (i = 0; i < ntransports; ++i) {
1503 if (!strcmp (agent_config.transport, transports [i].name))
1506 if (i == ntransports) {
1507 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1508 for (i = 0; i < ntransports; ++i)
1509 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1510 fprintf (stderr, "\n");
1513 transport = &transports [i];
1517 transport_connect (const char *address)
1519 transport->connect (address);
1523 transport_close1 (void)
1525 transport->close1 ();
1529 transport_close2 (void)
1531 transport->close2 ();
1535 transport_send (void *buf, int len)
1537 return transport->send (buf, len);
1541 transport_recv (void *buf, int len)
1543 return transport->recv (buf, len);
1547 mono_debugger_agent_transport_handshake (void)
1549 return transport_handshake ();
1553 transport_handshake (void)
1555 char handshake_msg [128];
1559 disconnected = TRUE;
1561 /* Write handshake message */
1562 sprintf (handshake_msg, "DWP-Handshake");
1565 res = transport_send (handshake_msg, strlen (handshake_msg));
1566 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1568 g_assert (res != -1);
1571 res = transport_recv (buf, strlen (handshake_msg));
1572 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg)) != 0)) {
1573 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1578 * To support older clients, the client sends its protocol version after connecting
1579 * using a command. Until that is received, default to our protocol version.
1581 major_version = MAJOR_VERSION;
1582 minor_version = MINOR_VERSION;
1583 protocol_version_set = FALSE;
1585 #ifndef DISABLE_SOCKET_TRANSPORT
1586 // FIXME: Move this somewhere else
1588 * Set TCP_NODELAY on the socket so the client receives events/command
1589 * results immediately.
1593 int result = setsockopt (conn_fd,
1598 g_assert (result >= 0);
1604 disconnected = FALSE;
1609 stop_debugger_thread (void)
1614 transport_close1 ();
1617 * Wait for the thread to exit.
1619 * If we continue with the shutdown without waiting for it, then the client might
1620 * not receive an answer to its last command like a resume.
1622 if (!is_debugger_thread ()) {
1624 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
1625 if (!debugger_thread_exited)
1626 mono_coop_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1627 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
1628 } while (!debugger_thread_exited);
1631 transport_close2 ();
1635 start_debugger_thread (void)
1637 debugger_thread_handle = mono_threads_create_thread (debugger_thread, NULL, NULL, NULL);
1638 g_assert (debugger_thread_handle);
1642 * Functions to decode protocol data
1646 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1649 g_assert (*endbuf <= limit);
1654 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1657 g_assert (*endbuf <= limit);
1659 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1662 static inline gint64
1663 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1665 guint32 high = decode_int (buf, &buf, limit);
1666 guint32 low = decode_int (buf, &buf, limit);
1670 return ((((guint64)high) << 32) | ((guint64)low));
1674 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1676 return decode_int (buf, endbuf, limit);
1680 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1682 int len = decode_int (buf, &buf, limit);
1690 s = (char *)g_malloc (len + 1);
1693 memcpy (s, buf, len);
1702 * Functions to encode protocol data
1706 buffer_init (Buffer *buf, int size)
1708 buf->buf = (guint8 *)g_malloc (size);
1710 buf->end = buf->buf + size;
1714 buffer_len (Buffer *buf)
1716 return buf->p - buf->buf;
1720 buffer_make_room (Buffer *buf, int size)
1722 if (buf->end - buf->p < size) {
1723 int new_size = buf->end - buf->buf + size + 32;
1724 guint8 *p = (guint8 *)g_realloc (buf->buf, new_size);
1725 size = buf->p - buf->buf;
1728 buf->end = buf->buf + new_size;
1733 buffer_add_byte (Buffer *buf, guint8 val)
1735 buffer_make_room (buf, 1);
1741 buffer_add_short (Buffer *buf, guint32 val)
1743 buffer_make_room (buf, 2);
1744 buf->p [0] = (val >> 8) & 0xff;
1745 buf->p [1] = (val >> 0) & 0xff;
1750 buffer_add_int (Buffer *buf, guint32 val)
1752 buffer_make_room (buf, 4);
1753 buf->p [0] = (val >> 24) & 0xff;
1754 buf->p [1] = (val >> 16) & 0xff;
1755 buf->p [2] = (val >> 8) & 0xff;
1756 buf->p [3] = (val >> 0) & 0xff;
1761 buffer_add_long (Buffer *buf, guint64 l)
1763 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1764 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1768 buffer_add_id (Buffer *buf, int id)
1770 buffer_add_int (buf, (guint64)id);
1774 buffer_add_data (Buffer *buf, guint8 *data, int len)
1776 buffer_make_room (buf, len);
1777 memcpy (buf->p, data, len);
1782 buffer_add_string (Buffer *buf, const char *str)
1787 buffer_add_int (buf, 0);
1790 buffer_add_int (buf, len);
1791 buffer_add_data (buf, (guint8*)str, len);
1796 buffer_add_buffer (Buffer *buf, Buffer *data)
1798 buffer_add_data (buf, data->buf, buffer_len (data));
1802 buffer_free (Buffer *buf)
1808 send_packet (int command_set, int command, Buffer *data)
1814 id = InterlockedIncrement (&packet_id);
1816 len = data->p - data->buf + 11;
1817 buffer_init (&buf, len);
1818 buffer_add_int (&buf, len);
1819 buffer_add_int (&buf, id);
1820 buffer_add_byte (&buf, 0); /* flags */
1821 buffer_add_byte (&buf, command_set);
1822 buffer_add_byte (&buf, command);
1823 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1825 res = transport_send (buf.buf, len);
1833 send_reply_packets (int npackets, ReplyPacket *packets)
1840 for (i = 0; i < npackets; ++i)
1841 len += buffer_len (packets [i].data) + 11;
1842 buffer_init (&buf, len);
1843 for (i = 0; i < npackets; ++i) {
1844 buffer_add_int (&buf, buffer_len (packets [i].data) + 11);
1845 buffer_add_int (&buf, packets [i].id);
1846 buffer_add_byte (&buf, 0x80); /* flags */
1847 buffer_add_byte (&buf, (packets [i].error >> 8) & 0xff);
1848 buffer_add_byte (&buf, packets [i].error);
1849 buffer_add_buffer (&buf, packets [i].data);
1852 res = transport_send (buf.buf, len);
1860 send_reply_packet (int id, int error, Buffer *data)
1864 memset (&packet, 0, sizeof (ReplyPacket));
1866 packet.error = error;
1869 return send_reply_packets (1, &packet);
1873 send_buffered_reply_packets (void)
1877 send_reply_packets (nreply_packets, reply_packets);
1878 for (i = 0; i < nreply_packets; ++i)
1879 buffer_free (reply_packets [i].data);
1880 DEBUG_PRINTF (1, "[dbg] Sent %d buffered reply packets [at=%lx].\n", nreply_packets, (long)mono_100ns_ticks () / 10000);
1885 buffer_reply_packet (int id, int error, Buffer *data)
1889 if (nreply_packets == 128)
1890 send_buffered_reply_packets ();
1892 p = &reply_packets [nreply_packets];
1895 p->data = g_new0 (Buffer, 1);
1896 buffer_init (p->data, buffer_len (data));
1897 buffer_add_buffer (p->data, data);
1906 * Represents an object accessible by the debugger client.
1909 /* Unique id used in the wire protocol to refer to objects */
1912 * A weakref gc handle pointing to the object. The gc handle is used to
1913 * detect if the object was garbage collected.
1918 /* Maps objid -> ObjRef */
1919 /* Protected by the loader lock */
1920 static GHashTable *objrefs;
1921 /* Protected by the loader lock */
1922 static GHashTable *obj_to_objref;
1923 /* Protected by the dbg lock */
1924 static MonoGHashTable *suspended_objs;
1927 free_objref (gpointer value)
1929 ObjRef *o = (ObjRef *)value;
1931 mono_gchandle_free (o->handle);
1939 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1940 obj_to_objref = g_hash_table_new (NULL, NULL);
1941 suspended_objs = mono_g_hash_table_new_type ((GHashFunc)mono_object_hash, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_DEBUGGER, "suspended objects table");
1945 objrefs_cleanup (void)
1947 g_hash_table_destroy (objrefs);
1952 * Return an ObjRef for OBJ.
1955 get_objref (MonoObject *obj)
1958 GSList *reflist = NULL, *l;
1964 if (suspend_count) {
1966 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1969 mono_g_hash_table_insert (suspended_objs, obj, NULL);
1973 mono_loader_lock ();
1975 /* FIXME: The tables can grow indefinitely */
1977 if (mono_gc_is_moving ()) {
1979 * Objects can move, so use a hash table mapping hash codes to lists of
1980 * ObjRef structures.
1982 hash = mono_object_hash (obj);
1984 reflist = (GSList *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1985 for (l = reflist; l; l = l->next) {
1986 ref = (ObjRef *)l->data;
1987 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1988 mono_loader_unlock ();
1993 /* Use a hash table with masked pointers to internalize object references */
1994 ref = (ObjRef *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1995 /* ref might refer to a different object with the same addr which was GCd */
1996 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1997 mono_loader_unlock ();
2002 ref = g_new0 (ObjRef, 1);
2003 ref->id = InterlockedIncrement (&objref_id);
2004 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
2006 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
2008 if (mono_gc_is_moving ()) {
2009 reflist = g_slist_append (reflist, ref);
2010 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
2012 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
2015 mono_loader_unlock ();
2021 true_pred (gpointer key, gpointer value, gpointer user_data)
2027 clear_suspended_objs (void)
2030 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
2035 get_objid (MonoObject *obj)
2040 return get_objref (obj)->id;
2044 * Set OBJ to the object identified by OBJID.
2045 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
2049 get_object_allow_null (int objid, MonoObject **obj)
2059 return ERR_INVALID_OBJECT;
2061 mono_loader_lock ();
2063 ref = (ObjRef *)g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
2066 *obj = mono_gchandle_get_target (ref->handle);
2067 mono_loader_unlock ();
2069 return ERR_INVALID_OBJECT;
2072 mono_loader_unlock ();
2073 return ERR_INVALID_OBJECT;
2078 get_object (int objid, MonoObject **obj)
2080 ErrorCode err = get_object_allow_null (objid, obj);
2082 if (err != ERR_NONE)
2085 return ERR_INVALID_OBJECT;
2090 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
2092 return decode_id (buf, endbuf, limit);
2096 buffer_add_objid (Buffer *buf, MonoObject *o)
2098 buffer_add_id (buf, get_objid (o));
2117 * Represents a runtime structure accessible to the debugger client
2120 /* Unique id used in the wire protocol */
2122 /* Domain of the runtime structure, NULL if the domain was unloaded */
2129 MonoAssembly *assembly;
2130 MonoClassField *field;
2132 MonoProperty *property;
2137 /* Maps runtime structure -> Id */
2138 /* Protected by the dbg lock */
2139 GHashTable *val_to_id [ID_NUM];
2140 /* Classes whose class load event has been sent */
2141 /* Protected by the loader lock */
2142 GHashTable *loaded_classes;
2143 /* Maps MonoClass->GPtrArray of file names */
2144 GHashTable *source_files;
2145 /* Maps source file basename -> GSList of classes */
2146 GHashTable *source_file_to_class;
2147 /* Same with ignore-case */
2148 GHashTable *source_file_to_class_ignorecase;
2152 /* Protected by the dbg lock */
2153 static GPtrArray *ids [ID_NUM];
2160 for (i = 0; i < ID_NUM; ++i)
2161 ids [i] = g_ptr_array_new ();
2169 for (i = 0; i < ID_NUM; ++i) {
2171 for (j = 0; j < ids [i]->len; ++j)
2172 g_free (g_ptr_array_index (ids [i], j));
2173 g_ptr_array_free (ids [i], TRUE);
2180 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2182 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2184 GHashTableIter iter;
2185 GPtrArray *file_names;
2190 for (i = 0; i < ID_NUM; ++i)
2191 if (info->val_to_id [i])
2192 g_hash_table_destroy (info->val_to_id [i]);
2193 g_hash_table_destroy (info->loaded_classes);
2195 g_hash_table_iter_init (&iter, info->source_files);
2196 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2197 for (i = 0; i < file_names->len; ++i)
2198 g_free (g_ptr_array_index (file_names, i));
2199 g_ptr_array_free (file_names, TRUE);
2202 g_hash_table_iter_init (&iter, info->source_file_to_class);
2203 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2208 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2209 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2217 domain_jit_info (domain)->agent_info = NULL;
2219 /* Clear ids referencing structures in the domain */
2221 for (i = 0; i < ID_NUM; ++i) {
2223 for (j = 0; j < ids [i]->len; ++j) {
2224 Id *id = (Id *)g_ptr_array_index (ids [i], j);
2225 if (id->domain == domain)
2232 mono_loader_lock ();
2233 g_hash_table_remove (domains, domain);
2234 mono_loader_unlock ();
2237 static AgentDomainInfo*
2238 get_agent_domain_info (MonoDomain *domain)
2240 AgentDomainInfo *info = NULL;
2242 mono_domain_lock (domain);
2244 info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2246 info = g_new0 (AgentDomainInfo, 1);
2247 domain_jit_info (domain)->agent_info = info;
2248 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2249 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2250 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2251 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2254 mono_domain_unlock (domain);
2260 get_id (MonoDomain *domain, IdType type, gpointer val)
2263 AgentDomainInfo *info;
2268 info = get_agent_domain_info (domain);
2272 if (info->val_to_id [type] == NULL)
2273 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2275 id = (Id *)g_hash_table_lookup (info->val_to_id [type], val);
2281 id = g_new0 (Id, 1);
2283 id->id = ids [type]->len + 1;
2284 id->domain = domain;
2287 g_hash_table_insert (info->val_to_id [type], val, id);
2288 g_ptr_array_add (ids [type], id);
2295 static inline gpointer
2296 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, ErrorCode *err)
2300 int id = decode_id (buf, endbuf, limit);
2309 // FIXME: error handling
2311 g_assert (id > 0 && id <= ids [type]->len);
2313 res = (Id *)g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2316 if (res->domain == NULL || res->domain->state == MONO_APPDOMAIN_UNLOADED) {
2317 DEBUG_PRINTF (1, "ERR_UNLOADED, id=%d, type=%d.\n", id, type);
2318 *err = ERR_UNLOADED;
2323 *domain = res->domain;
2325 return res->data.val;
2329 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2331 int id = get_id (domain, type, val);
2333 buffer_add_id (buf, id);
2337 static inline MonoClass*
2338 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2342 klass = (MonoClass *)decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2343 if (G_UNLIKELY (log_level >= 2) && klass) {
2346 s = mono_type_full_name (&klass->byval_arg);
2347 DEBUG_PRINTF (2, "[dbg] recv class [%s]\n", s);
2353 static inline MonoAssembly*
2354 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2356 return (MonoAssembly *)decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2359 static inline MonoImage*
2360 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2362 return (MonoImage *)decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2365 static inline MonoMethod*
2366 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2370 m = (MonoMethod *)decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2371 if (G_UNLIKELY (log_level >= 2) && m) {
2374 s = mono_method_full_name (m, TRUE);
2375 DEBUG_PRINTF (2, "[dbg] recv method [%s]\n", s);
2381 static inline MonoClassField*
2382 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2384 return (MonoClassField *)decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2387 static inline MonoDomain*
2388 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2390 return (MonoDomain *)decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2393 static inline MonoProperty*
2394 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2396 return (MonoProperty *)decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2400 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2402 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2403 if (G_UNLIKELY (log_level >= 2) && klass) {
2406 s = mono_type_full_name (&klass->byval_arg);
2407 if (is_debugger_thread ())
2408 DEBUG_PRINTF (2, "[dbg] send class [%s]\n", s);
2410 DEBUG_PRINTF (2, "[%p] send class [%s]\n", (gpointer) (gsize) mono_native_thread_id_get (), s);
2416 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2418 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2419 if (G_UNLIKELY (log_level >= 2) && method) {
2422 s = mono_method_full_name (method, 1);
2423 DEBUG_PRINTF (2, "[dbg] send method [%s]\n", s);
2429 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2433 id = buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2434 if (G_UNLIKELY (log_level >= 2) && assembly)
2435 DEBUG_PRINTF (2, "[dbg] send assembly [%s][%s][%d]\n", assembly->aname.name, domain->friendly_name, id);
2439 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2441 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2445 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2447 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2451 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2453 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2457 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2459 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2462 static void invoke_method (void);
2469 * save_thread_context:
2471 * Set CTX as the current threads context which is used for computing stack traces.
2472 * This function is signal-safe.
2475 save_thread_context (MonoContext *ctx)
2477 DebuggerTlsData *tls;
2479 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2483 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2485 mono_thread_state_init_from_current (&tls->context);
2488 /* Number of threads suspended */
2490 * If this is equal to the size of thread_to_tls, the runtime is considered
2493 static gint32 threads_suspend_count;
2495 static MonoCoopMutex suspend_mutex;
2497 /* Cond variable used to wait for suspend_count becoming 0 */
2498 static MonoCoopCond suspend_cond;
2500 /* Semaphore used to wait for a thread becoming suspended */
2501 static MonoCoopSem suspend_sem;
2506 mono_coop_mutex_init (&suspend_mutex);
2507 mono_coop_cond_init (&suspend_cond);
2508 mono_coop_sem_init (&suspend_sem, 0);
2513 StackFrameInfo last_frame;
2514 gboolean last_frame_set;
2518 } GetLastFrameUserData;
2521 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2523 GetLastFrameUserData *data = (GetLastFrameUserData *)user_data;
2525 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE || info->type == FRAME_TYPE_TRAMPOLINE)
2528 if (!data->last_frame_set) {
2529 /* Store the last frame */
2530 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2531 data->last_frame_set = TRUE;
2534 /* Store the context/lmf for the frame above the last frame */
2535 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2536 data->lmf = info->lmf;
2537 data->domain = info->domain;
2543 copy_unwind_state_from_frame_data (MonoThreadUnwindState *to, GetLastFrameUserData *data, gpointer jit_tls)
2545 memcpy (&to->ctx, &data->ctx, sizeof (MonoContext));
2547 to->unwind_data [MONO_UNWIND_DATA_DOMAIN] = data->domain;
2548 to->unwind_data [MONO_UNWIND_DATA_LMF] = data->lmf;
2549 to->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = jit_tls;
2556 * Process interruption of a thread. This should be signal safe.
2558 * This always runs in the debugger thread.
2561 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, MonoJitInfo *ji)
2564 MonoNativeThreadId tid;
2568 ip = MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx);
2569 tid = mono_thread_info_get_tid (info);
2571 // FIXME: Races when the thread leaves managed code before hitting a single step
2574 if (ji && !ji->is_trampoline) {
2575 /* Running managed code, will be suspended by the single step code */
2576 DEBUG_PRINTF (1, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip);
2579 * Running native code, will be suspended when it returns to/enters
2580 * managed code. Treat it as already suspended.
2581 * This might interrupt the code in process_single_step_inner (), we use the
2582 * tls->suspending flag to avoid races when that happens.
2584 if (!tls->suspended && !tls->suspending) {
2585 GetLastFrameUserData data;
2587 // FIXME: printf is not signal safe, but this is only used during
2588 // debugger debugging
2590 DEBUG_PRINTF (1, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip);
2591 //save_thread_context (&ctx);
2594 /* Already terminated */
2598 * We are in a difficult position: we want to be able to provide stack
2599 * traces for this thread, but we can't use the current ctx+lmf, since
2600 * the thread is still running, so it might return to managed code,
2601 * making these invalid.
2602 * So we start a stack walk and save the first frame, along with the
2603 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2604 * suspended when it returns to managed code, so the parent's ctx should
2607 data.last_frame_set = FALSE;
2608 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, mono_thread_info_get_suspend_state (info), MONO_UNWIND_SIGNAL_SAFE, &data);
2609 if (data.last_frame_set) {
2610 gpointer jit_tls = ((MonoThreadInfo*)tls->thread->thread_info)->jit_data;
2612 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2614 copy_unwind_state_from_frame_data (&tls->async_state, &data, jit_tls);
2615 copy_unwind_state_from_frame_data (&tls->context, &data, jit_tls);
2617 tls->async_state.valid = FALSE;
2620 mono_memory_barrier ();
2622 tls->suspended = TRUE;
2623 mono_coop_sem_post (&suspend_sem);
2629 * reset_native_thread_suspend_state:
2631 * Reset the suspended flag and state on native threads
2634 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2636 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2638 if (!tls->really_suspended && tls->suspended) {
2639 tls->suspended = FALSE;
2641 * The thread might still be running if it was executing native code, so the state won't be invalided by
2642 * suspend_current ().
2644 tls->context.valid = FALSE;
2645 tls->async_state.valid = FALSE;
2646 invalidate_frames (tls);
2651 DebuggerTlsData *tls;
2652 gboolean valid_info;
2655 static SuspendThreadResult
2656 debugger_interrupt_critical (MonoThreadInfo *info, gpointer user_data)
2658 InterruptData *data = (InterruptData *)user_data;
2661 data->valid_info = TRUE;
2662 ji = mono_jit_info_table_find_internal (
2663 (MonoDomain *)mono_thread_info_get_suspend_state (info)->unwind_data [MONO_UNWIND_DATA_DOMAIN],
2664 (char *)MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx),
2668 /* This is signal safe */
2669 thread_interrupt (data->tls, info, ji);
2670 return MonoResumeThread;
2676 * Notify a thread that it needs to suspend.
2679 notify_thread (gpointer key, gpointer value, gpointer user_data)
2681 MonoInternalThread *thread = (MonoInternalThread *)key;
2682 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2683 MonoNativeThreadId tid = MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid);
2685 if (mono_native_thread_id_equals (mono_native_thread_id_get (), tid) || tls->terminated)
2688 DEBUG_PRINTF (1, "[%p] Interrupting %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2690 /* This is _not_ equivalent to mono_thread_internal_abort () */
2691 InterruptData interrupt_data = { 0 };
2692 interrupt_data.tls = tls;
2694 mono_thread_info_safe_suspend_and_run ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE, debugger_interrupt_critical, &interrupt_data);
2695 if (!interrupt_data.valid_info) {
2696 DEBUG_PRINTF (1, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2698 * Attached thread which died without detaching.
2700 tls->terminated = TRUE;
2705 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2707 guint8 *ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
2711 if (mono_loader_lock_is_owned_by_self ()) {
2713 * Shortcut for the check in suspend_current (). This speeds up processing
2714 * when executing long running code inside the loader lock, i.e. assembly load
2720 if (is_debugger_thread ())
2723 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2724 if (suspend_count - tls->resume_count > 0)
2725 tls->suspending = TRUE;
2727 DEBUG_PRINTF (1, "[%p] Received single step event for suspending.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2729 if (suspend_count - tls->resume_count == 0) {
2731 * We are executing a single threaded invoke but the single step for
2732 * suspending is still active.
2733 * FIXME: This slows down single threaded invokes.
2735 DEBUG_PRINTF (1, "[%p] Ignored during single threaded invoke.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2739 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2741 /* Can't suspend in these methods */
2742 method = jinfo_get_method (ji);
2743 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2746 save_thread_context (ctx);
2754 * Increase the suspend count of the VM. While the suspend count is greater
2755 * than 0, runtime threads are suspended at certain points during execution.
2760 mono_loader_lock ();
2762 mono_coop_mutex_lock (&suspend_mutex);
2766 DEBUG_PRINTF (1, "[%p] Suspending vm...\n", (gpointer) (gsize) mono_native_thread_id_get ());
2768 if (suspend_count == 1) {
2769 // FIXME: Is it safe to call this inside the lock ?
2770 start_single_stepping ();
2771 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2774 mono_coop_mutex_unlock (&suspend_mutex);
2776 if (suspend_count == 1)
2778 * Suspend creation of new threadpool threads, since they cannot run
2780 mono_threadpool_suspend ();
2782 mono_loader_unlock ();
2788 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2794 g_assert (is_debugger_thread ());
2796 mono_loader_lock ();
2798 mono_coop_mutex_lock (&suspend_mutex);
2800 g_assert (suspend_count > 0);
2803 DEBUG_PRINTF (1, "[%p] Resuming vm, suspend count=%d...\n", (gpointer) (gsize) mono_native_thread_id_get (), suspend_count);
2805 if (suspend_count == 0) {
2806 // FIXME: Is it safe to call this inside the lock ?
2807 stop_single_stepping ();
2808 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2811 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2812 mono_coop_cond_broadcast (&suspend_cond);
2814 mono_coop_mutex_unlock (&suspend_mutex);
2815 //g_assert (err == 0);
2817 if (suspend_count == 0)
2818 mono_threadpool_resume ();
2820 mono_loader_unlock ();
2826 * Resume just one thread.
2829 resume_thread (MonoInternalThread *thread)
2831 DebuggerTlsData *tls;
2833 g_assert (is_debugger_thread ());
2835 mono_loader_lock ();
2837 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
2840 mono_coop_mutex_lock (&suspend_mutex);
2842 g_assert (suspend_count > 0);
2844 DEBUG_PRINTF (1, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid);
2846 tls->resume_count += suspend_count;
2849 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2850 * but only the one whose resume_count field is > 0 will be resumed.
2852 mono_coop_cond_broadcast (&suspend_cond);
2854 mono_coop_mutex_unlock (&suspend_mutex);
2855 //g_assert (err == 0);
2857 mono_loader_unlock ();
2861 free_frames (StackFrame **frames, int nframes)
2865 for (i = 0; i < nframes; ++i) {
2866 if (frames [i]->jit)
2867 mono_debug_free_method_jit_info (frames [i]->jit);
2868 g_free (frames [i]);
2874 invalidate_frames (DebuggerTlsData *tls)
2877 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2880 free_frames (tls->frames, tls->frame_count);
2881 tls->frame_count = 0;
2884 free_frames (tls->restore_frames, tls->restore_frame_count);
2885 tls->restore_frame_count = 0;
2886 tls->restore_frames = NULL;
2892 * Suspend the current thread until the runtime is resumed. If the thread has a
2893 * pending invoke, then the invoke is executed before this function returns.
2896 suspend_current (void)
2898 DebuggerTlsData *tls;
2900 g_assert (!is_debugger_thread ());
2902 if (mono_loader_lock_is_owned_by_self ()) {
2904 * If we own the loader mutex, can't suspend until we release it, since the
2905 * whole runtime can deadlock otherwise.
2910 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2913 mono_coop_mutex_lock (&suspend_mutex);
2915 tls->suspending = FALSE;
2916 tls->really_suspended = TRUE;
2918 if (!tls->suspended) {
2919 tls->suspended = TRUE;
2920 mono_coop_sem_post (&suspend_sem);
2923 DEBUG_PRINTF (1, "[%p] Suspended.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2925 while (suspend_count - tls->resume_count > 0) {
2926 mono_coop_cond_wait (&suspend_cond, &suspend_mutex);
2929 tls->suspended = FALSE;
2930 tls->really_suspended = FALSE;
2932 threads_suspend_count --;
2934 mono_coop_mutex_unlock (&suspend_mutex);
2936 DEBUG_PRINTF (1, "[%p] Resumed.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2938 if (tls->pending_invoke) {
2939 /* Save the original context */
2940 tls->pending_invoke->has_ctx = TRUE;
2941 tls->pending_invoke->ctx = tls->context.ctx;
2946 /* The frame info becomes invalid after a resume */
2947 tls->context.valid = FALSE;
2948 tls->async_state.valid = FALSE;
2949 invalidate_frames (tls);
2953 count_thread (gpointer key, gpointer value, gpointer user_data)
2955 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2957 if (!tls->suspended && !tls->terminated)
2958 *(int*)user_data = *(int*)user_data + 1;
2962 count_threads_to_wait_for (void)
2966 mono_loader_lock ();
2967 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2968 mono_loader_unlock ();
2976 * Wait until the runtime is completely suspended.
2979 wait_for_suspend (void)
2981 int nthreads, nwait, err;
2982 gboolean waited = FALSE;
2984 // FIXME: Threads starting/stopping ?
2985 mono_loader_lock ();
2986 nthreads = mono_g_hash_table_size (thread_to_tls);
2987 mono_loader_unlock ();
2990 nwait = count_threads_to_wait_for ();
2992 DEBUG_PRINTF (1, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads);
2993 err = mono_coop_sem_wait (&suspend_sem, MONO_SEM_FLAGS_NONE);
2994 g_assert (err == 0);
3002 DEBUG_PRINTF (1, "%d threads suspended.\n", nthreads);
3008 * Return whenever the runtime is suspended.
3013 return count_threads_to_wait_for () == 0;
3017 no_seq_points_found (MonoMethod *method, int offset)
3020 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3022 printf ("Unable to find seq points for method '%s', offset 0x%x.\n", mono_method_full_name (method, TRUE), offset);
3026 DebuggerTlsData *tls;
3028 } ComputeFramesUserData;
3031 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3033 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3035 MonoMethod *method, *actual_method, *api_method;
3039 if (info->type != FRAME_TYPE_MANAGED) {
3040 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3041 /* Mark the last frame as an invoke frame */
3043 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3049 method = jinfo_get_method (info->ji);
3051 method = info->method;
3052 actual_method = info->actual_method;
3053 api_method = method;
3058 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3061 if (info->il_offset == -1) {
3062 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3063 if (ud->frames == NULL) {
3064 if (mono_find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL, &sp))
3065 info->il_offset = sp.il_offset;
3067 if (info->il_offset == -1)
3068 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3071 DEBUG_PRINTF (1, "\tFrame: %s:[il=0x%x, native=0x%x] %d\n", mono_method_full_name (method, TRUE), info->il_offset, info->native_offset, info->managed);
3073 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3074 if (!CHECK_PROTOCOL_VERSION (2, 17))
3075 /* Older clients can't handle this flag */
3077 api_method = mono_marshal_method_from_wrapper (method);
3080 actual_method = api_method;
3081 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3084 frame = g_new0 (StackFrame, 1);
3085 frame->method = method;
3086 frame->actual_method = actual_method;
3087 frame->api_method = api_method;
3088 frame->il_offset = info->il_offset;
3089 frame->native_offset = info->native_offset;
3090 frame->flags = flags;
3091 frame->ji = info->ji;
3092 if (info->reg_locations)
3093 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3096 frame->has_ctx = TRUE;
3098 frame->domain = info->domain;
3100 ud->frames = g_slist_append (ud->frames, frame);
3106 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3108 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3111 * 'tls->filter_ctx' is the location of the throw site.
3113 * mono_walk_stack() will never actually hit the throw site, but unwind
3114 * directly from the filter to the call site; we abort stack unwinding here
3115 * once this happens and resume from the throw site.
3118 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3121 return process_frame (info, ctx, user_data);
3125 * Return a malloc-ed list of StackFrame structures.
3128 compute_frame_info_from (MonoInternalThread *thread, DebuggerTlsData *tls, MonoThreadUnwindState *state, int *out_nframes)
3130 ComputeFramesUserData user_data;
3131 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3136 user_data.tls = tls;
3137 user_data.frames = NULL;
3139 mono_walk_stack_with_state (process_frame, state, opts, &user_data);
3141 nframes = g_slist_length (user_data.frames);
3142 res = g_new0 (StackFrame*, nframes);
3143 l = user_data.frames;
3144 for (i = 0; i < nframes; ++i) {
3145 res [i] = (StackFrame *)l->data;
3148 *out_nframes = nframes;
3154 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3156 ComputeFramesUserData user_data;
3158 int i, findex, new_frame_count;
3159 StackFrame **new_frames, *f;
3160 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3162 // FIXME: Locking on tls
3163 if (tls->frames && tls->frames_up_to_date)
3166 DEBUG_PRINTF (1, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid);
3168 user_data.tls = tls;
3169 user_data.frames = NULL;
3170 if (tls->terminated) {
3171 tls->frame_count = 0;
3173 } if (!tls->really_suspended && tls->async_state.valid) {
3174 /* Have to use the state saved by the signal handler */
3175 process_frame (&tls->async_last_frame, NULL, &user_data);
3176 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3177 } else if (tls->filter_state.valid) {
3179 * We are inside an exception filter.
3181 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3183 if (tls->context.valid)
3184 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3186 * After that, we resume unwinding from the location where the exception has been thrown.
3188 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3189 } else if (tls->context.valid) {
3190 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3193 tls->frame_count = 0;
3197 new_frame_count = g_slist_length (user_data.frames);
3198 new_frames = g_new0 (StackFrame*, new_frame_count);
3200 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3201 f = (StackFrame *)tmp->data;
3204 * Reuse the id for already existing stack frames, so invokes don't invalidate
3205 * the still valid stack frames.
3207 for (i = 0; i < tls->frame_count; ++i) {
3208 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3209 f->id = tls->frames [i]->id;
3214 if (i >= tls->frame_count)
3215 f->id = InterlockedIncrement (&frame_id);
3217 new_frames [findex ++] = f;
3220 g_slist_free (user_data.frames);
3222 invalidate_frames (tls);
3224 tls->frames = new_frames;
3225 tls->frame_count = new_frame_count;
3226 tls->frames_up_to_date = TRUE;
3230 * GHFunc to emit an appdomain creation event
3231 * @param key Don't care
3232 * @param value A loaded appdomain
3233 * @param user_data Don't care
3236 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3238 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3239 g_hash_table_foreach (get_agent_domain_info ((MonoDomain *)value)->loaded_classes, emit_type_load, NULL);
3243 * GHFunc to emit a thread start event
3244 * @param key A thread id
3245 * @param value A thread object
3246 * @param user_data Don't care
3249 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3251 if (!mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (GPOINTER_TO_UINT (key)), debugger_thread_id))
3252 process_profiler_event (EVENT_KIND_THREAD_START, value);
3256 * GFunc to emit an assembly load event
3257 * @param value A loaded assembly
3258 * @param user_data Don't care
3261 emit_assembly_load (gpointer value, gpointer user_data)
3263 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3267 * GFunc to emit a type load event
3268 * @param value A loaded type
3269 * @param user_data Don't care
3272 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3274 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3278 strdup_tolower (char *s)
3283 for (p = s2; *p; ++p)
3289 * Same as g_path_get_basename () but handles windows paths as well,
3290 * which can occur in .mdb files created by pdb2mdb.
3293 dbg_path_get_basename (const char *filename)
3297 if (!filename || strchr (filename, '/') || !strchr (filename, '\\'))
3298 return g_path_get_basename (filename);
3302 /* No separator -> filename */
3303 r = strrchr (filename, '\\');
3305 return g_strdup (filename);
3307 /* Trailing slash, remove component */
3309 char *copy = g_strdup (filename);
3310 copy [r-filename] = 0;
3311 r = strrchr (copy, '\\');
3315 return g_strdup ("/");
3317 r = g_strdup (&r[1]);
3322 return g_strdup (&r[1]);
3326 init_jit_info_dbg_attrs (MonoJitInfo *ji)
3328 static MonoClass *hidden_klass, *step_through_klass, *non_user_klass;
3330 MonoCustomAttrInfo *ainfo;
3332 if (ji->dbg_attrs_inited)
3336 hidden_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3338 if (!step_through_klass)
3339 step_through_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3341 if (!non_user_klass)
3342 non_user_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute");
3344 ainfo = mono_custom_attrs_from_method_checked (jinfo_get_method (ji), &error);
3345 mono_error_cleanup (&error); /* FIXME don't swallow the error? */
3347 if (mono_custom_attrs_has_attr (ainfo, hidden_klass))
3348 ji->dbg_hidden = TRUE;
3349 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3350 ji->dbg_step_through = TRUE;
3351 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3352 ji->dbg_non_user_code = TRUE;
3353 mono_custom_attrs_free (ainfo);
3356 ainfo = mono_custom_attrs_from_class_checked (jinfo_get_method (ji)->klass, &error);
3357 mono_error_cleanup (&error); /* FIXME don't swallow the error? */
3359 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3360 ji->dbg_step_through = TRUE;
3361 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3362 ji->dbg_non_user_code = TRUE;
3363 mono_custom_attrs_free (ainfo);
3366 mono_memory_barrier ();
3367 ji->dbg_attrs_inited = TRUE;
3375 * create_event_list:
3377 * Return a list of event request ids matching EVENT, starting from REQS, which
3378 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3380 * We return request ids, instead of requests, to simplify threading, since
3381 * requests could be deleted anytime when the loader lock is not held.
3382 * LOCKING: Assumes the loader lock is held.
3385 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3388 GSList *events = NULL;
3390 *suspend_policy = SUSPEND_POLICY_NONE;
3393 reqs = event_requests;
3398 for (i = 0; i < reqs->len; ++i) {
3399 EventRequest *req = (EventRequest *)g_ptr_array_index (reqs, i);
3400 if (req->event_kind == event) {
3401 gboolean filtered = FALSE;
3404 for (j = 0; j < req->nmodifiers; ++j) {
3405 Modifier *mod = &req->modifiers [j];
3407 if (mod->kind == MOD_KIND_COUNT) {
3409 if (mod->data.count > 0) {
3410 if (mod->data.count > 0) {
3412 if (mod->data.count == 0)
3416 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3417 if (mod->data.thread != mono_thread_internal_current ())
3419 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3420 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3422 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3424 if (ei->caught && !mod->caught)
3426 if (!ei->caught && !mod->uncaught)
3428 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3430 gboolean found = FALSE;
3431 MonoAssembly **assemblies = mod->data.assemblies;
3434 for (k = 0; assemblies [k]; ++k)
3435 if (assemblies [k] == jinfo_get_method (ji)->klass->image->assembly)
3440 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3441 gpointer iter = NULL;
3443 MonoDebugSourceInfo *sinfo;
3444 char *source_file, *s;
3445 gboolean found = FALSE;
3447 GPtrArray *source_file_list;
3449 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3450 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3453 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, NULL, NULL, NULL);
3454 for (i = 0; i < source_file_list->len; ++i) {
3455 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
3457 * Do a case-insesitive match by converting the file name to
3460 s = strdup_tolower (sinfo->source_file);
3461 if (g_hash_table_lookup (mod->data.source_files, s))
3464 char *s2 = dbg_path_get_basename (sinfo->source_file);
3465 char *s3 = strdup_tolower (s2);
3467 if (g_hash_table_lookup (mod->data.source_files, s3))
3474 g_ptr_array_free (source_file_list, TRUE);
3479 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3482 s = mono_type_full_name (&ei->klass->byval_arg);
3483 if (!g_hash_table_lookup (mod->data.type_names, s))
3486 } else if (mod->kind == MOD_KIND_STEP) {
3487 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3488 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3489 !strcmp (jinfo_get_method (ji)->name, ".cctor") &&
3490 (jinfo_get_method (ji) != ((SingleStepReq*)req->info)->start_method))
3492 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3493 init_jit_info_dbg_attrs (ji);
3497 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3498 init_jit_info_dbg_attrs (ji);
3499 if (ji->dbg_step_through)
3502 if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3503 init_jit_info_dbg_attrs (ji);
3504 if (ji->dbg_non_user_code)
3511 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3512 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3517 /* Send a VM START/DEATH event by default */
3518 if (event == EVENT_KIND_VM_START)
3519 events = g_slist_append (events, GINT_TO_POINTER (0));
3520 if (event == EVENT_KIND_VM_DEATH)
3521 events = g_slist_append (events, GINT_TO_POINTER (0));
3526 static G_GNUC_UNUSED const char*
3527 event_to_string (EventKind event)
3530 case EVENT_KIND_VM_START: return "VM_START";
3531 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3532 case EVENT_KIND_THREAD_START: return "THREAD_START";
3533 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3534 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3535 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3536 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3537 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3538 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3539 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3540 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3541 case EVENT_KIND_STEP: return "STEP";
3542 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3543 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3544 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3545 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3546 case EVENT_KIND_USER_LOG: return "USER_LOG";
3548 g_assert_not_reached ();
3556 * Send an event to the client, suspending the vm if needed.
3557 * LOCKING: Since this can suspend the calling thread, no locks should be held
3559 * The EVENTS list is freed by this function.
3562 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3566 MonoDomain *domain = mono_domain_get ();
3567 MonoThread *thread = NULL;
3568 MonoObject *keepalive_obj = NULL;
3569 gboolean send_success = FALSE;
3574 DEBUG_PRINTF (2, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event));
3578 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3579 // FIXME: We miss those events
3580 DEBUG_PRINTF (2, "VM start event not sent yet: dropping %s\n", event_to_string (event));
3584 if (vm_death_event_sent) {
3585 DEBUG_PRINTF (2, "VM death event has been sent: dropping %s\n", event_to_string (event));
3589 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3590 DEBUG_PRINTF (2, "Mono runtime is shutting down: dropping %s\n", event_to_string (event));
3595 DEBUG_PRINTF (2, "Debugger client is not connected: dropping %s\n", event_to_string (event));
3599 if (event == EVENT_KIND_KEEPALIVE)
3600 suspend_policy = SUSPEND_POLICY_NONE;
3605 if (agent_config.defer) {
3606 /* Make sure the thread id is always set when doing deferred debugging */
3607 if (is_debugger_thread ()) {
3608 /* Don't suspend on events from the debugger thread */
3609 suspend_policy = SUSPEND_POLICY_NONE;
3610 thread = mono_thread_get_main ();
3612 else thread = mono_thread_current ();
3614 if (is_debugger_thread () && event != EVENT_KIND_VM_DEATH)
3615 // FIXME: Send these with a NULL thread, don't suspend the current thread
3620 nevents = g_slist_length (events);
3621 buffer_init (&buf, 128);
3622 buffer_add_byte (&buf, suspend_policy);
3623 buffer_add_int (&buf, nevents);
3625 for (l = events; l; l = l->next) {
3626 buffer_add_byte (&buf, event); // event kind
3627 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3631 if (event == EVENT_KIND_VM_DEATH) {
3635 thread = mono_thread_current ();
3637 if (event == EVENT_KIND_VM_START && arg != NULL)
3638 thread = (MonoThread *)arg;
3641 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3644 case EVENT_KIND_THREAD_START:
3645 case EVENT_KIND_THREAD_DEATH:
3647 case EVENT_KIND_APPDOMAIN_CREATE:
3648 case EVENT_KIND_APPDOMAIN_UNLOAD:
3649 buffer_add_domainid (&buf, (MonoDomain *)arg);
3651 case EVENT_KIND_METHOD_ENTRY:
3652 case EVENT_KIND_METHOD_EXIT:
3653 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3655 case EVENT_KIND_ASSEMBLY_LOAD:
3656 buffer_add_assemblyid (&buf, domain, (MonoAssembly *)arg);
3658 case EVENT_KIND_ASSEMBLY_UNLOAD: {
3659 DebuggerTlsData *tls;
3661 /* The domain the assembly belonged to is not equal to the current domain */
3662 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3664 g_assert (tls->domain_unloading);
3666 buffer_add_assemblyid (&buf, tls->domain_unloading, (MonoAssembly *)arg);
3669 case EVENT_KIND_TYPE_LOAD:
3670 buffer_add_typeid (&buf, domain, (MonoClass *)arg);
3672 case EVENT_KIND_BREAKPOINT:
3673 case EVENT_KIND_STEP:
3674 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3675 buffer_add_long (&buf, il_offset);
3677 case EVENT_KIND_VM_START:
3678 buffer_add_domainid (&buf, mono_get_root_domain ());
3680 case EVENT_KIND_VM_DEATH:
3681 if (CHECK_PROTOCOL_VERSION (2, 27))
3682 buffer_add_int (&buf, mono_environment_exitcode_get ());
3684 case EVENT_KIND_EXCEPTION: {
3685 EventInfo *ei = (EventInfo *)arg;
3686 buffer_add_objid (&buf, ei->exc);
3688 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3689 * later after the suspension. (#12494).
3691 keepalive_obj = ei->exc;
3694 case EVENT_KIND_USER_BREAK:
3696 case EVENT_KIND_USER_LOG: {
3697 EventInfo *ei = (EventInfo *)arg;
3698 buffer_add_int (&buf, ei->level);
3699 buffer_add_string (&buf, ei->category ? ei->category : "");
3700 buffer_add_string (&buf, ei->message ? ei->message : "");
3703 case EVENT_KIND_KEEPALIVE:
3704 suspend_policy = SUSPEND_POLICY_NONE;
3707 g_assert_not_reached ();
3711 if (event == EVENT_KIND_VM_START) {
3712 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3713 if (!agent_config.defer)
3714 start_debugger_thread ();
3717 if (event == EVENT_KIND_VM_DEATH) {
3718 vm_death_event_sent = TRUE;
3719 suspend_policy = SUSPEND_POLICY_NONE;
3722 if (mono_runtime_is_shutting_down ())
3723 suspend_policy = SUSPEND_POLICY_NONE;
3725 if (suspend_policy != SUSPEND_POLICY_NONE) {
3727 * Save the thread context and start suspending before sending the packet,
3728 * since we could be receiving the resume request before send_packet ()
3731 save_thread_context (ctx);
3735 /* This will keep this object alive */
3736 get_objref (keepalive_obj);
3739 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3743 g_slist_free (events);
3746 if (!send_success) {
3747 DEBUG_PRINTF (2, "Sending command %s failed.\n", event_to_string (event));
3751 if (event == EVENT_KIND_VM_START) {
3752 vm_start_event_sent = TRUE;
3755 DEBUG_PRINTF (1, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer) (gsize) mono_native_thread_id_get (), nevents, event_to_string (event), ecount, suspend_policy);
3757 switch (suspend_policy) {
3758 case SUSPEND_POLICY_NONE:
3760 case SUSPEND_POLICY_ALL:
3763 case SUSPEND_POLICY_EVENT_THREAD:
3767 g_assert_not_reached ();
3772 process_profiler_event (EventKind event, gpointer arg)
3776 EventInfo ei, *ei_arg = NULL;
3778 if (event == EVENT_KIND_TYPE_LOAD) {
3779 ei.klass = (MonoClass *)arg;
3783 mono_loader_lock ();
3784 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3785 mono_loader_unlock ();
3787 process_event (event, arg, 0, NULL, events, suspend_policy);
3791 runtime_initialized (MonoProfiler *prof)
3793 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3794 if (agent_config.defer)
3795 start_debugger_thread ();
3799 runtime_shutdown (MonoProfiler *prof)
3801 process_profiler_event (EVENT_KIND_VM_DEATH, NULL);
3803 mono_debugger_agent_cleanup ();
3807 thread_startup (MonoProfiler *prof, uintptr_t tid)
3809 MonoInternalThread *thread = mono_thread_internal_current ();
3810 MonoInternalThread *old_thread;
3811 DebuggerTlsData *tls;
3813 if (mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (tid), debugger_thread_id))
3816 g_assert (mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (tid), MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid)));
3818 mono_loader_lock ();
3819 old_thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3820 mono_loader_unlock ();
3822 if (thread == old_thread) {
3824 * For some reason, thread_startup () might be called for the same thread
3825 * multiple times (attach ?).
3827 DEBUG_PRINTF (1, "[%p] thread_start () called multiple times for %p, ignored.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3831 * thread_end () might not be called for some threads, and the tid could
3834 DEBUG_PRINTF (1, "[%p] Removing stale data for tid %p.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3835 mono_loader_lock ();
3836 mono_g_hash_table_remove (thread_to_tls, old_thread);
3837 mono_g_hash_table_remove (tid_to_thread, GUINT_TO_POINTER (tid));
3838 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3839 mono_loader_unlock ();
3843 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3845 // FIXME: Free this somewhere
3846 tls = g_new0 (DebuggerTlsData, 1);
3847 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread, MONO_ROOT_SOURCE_DEBUGGER, "debugger thread reference");
3848 tls->thread = thread;
3849 mono_native_tls_set_value (debugger_tls_id, tls);
3851 DEBUG_PRINTF (1, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3853 mono_loader_lock ();
3854 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3855 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3856 mono_g_hash_table_insert (tid_to_thread_obj, GUINT_TO_POINTER (tid), mono_thread_current ());
3857 mono_loader_unlock ();
3859 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3862 * suspend_vm () could have missed this thread, so wait for a resume.
3868 thread_end (MonoProfiler *prof, uintptr_t tid)
3870 MonoInternalThread *thread;
3871 DebuggerTlsData *tls = NULL;
3873 mono_loader_lock ();
3874 thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3876 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3877 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
3879 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3880 tls->terminated = TRUE;
3881 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3882 MONO_GC_UNREGISTER_ROOT (tls->thread);
3886 mono_loader_unlock ();
3888 /* We might be called for threads started before we registered the start callback */
3890 DEBUG_PRINTF (1, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3892 if (mono_native_thread_id_equals (mono_native_thread_id_get (), MONO_UINT_TO_NATIVE_THREAD_ID (tid))
3893 && !mono_native_tls_get_value (debugger_tls_id)
3896 * This can happen on darwin since we deregister threads using pthread dtors.
3897 * process_profiler_event () and the code it calls cannot handle a null TLS value.
3902 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3907 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3909 mono_loader_lock ();
3910 g_hash_table_insert (domains, domain, domain);
3911 mono_loader_unlock ();
3913 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3917 appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain)
3919 DebuggerTlsData *tls;
3921 /* This might be called during shutdown on the debugger thread from the CMD_VM_EXIT code */
3922 if (is_debugger_thread ())
3926 * Remember the currently unloading appdomain as it is needed to generate
3927 * proper ids for unloading assemblies.
3929 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3931 tls->domain_unloading = domain;
3935 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3937 DebuggerTlsData *tls;
3939 if (is_debugger_thread ())
3942 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3944 tls->domain_unloading = NULL;
3946 clear_breakpoints_for_domain (domain);
3948 mono_loader_lock ();
3949 /* Invalidate each thread's frame stack */
3950 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3951 mono_loader_unlock ();
3953 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3957 * invalidate_each_thread:
3959 * A GHFunc to invalidate frames.
3960 * value must be a DebuggerTlsData*
3963 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3965 invalidate_frames ((DebuggerTlsData *)value);
3969 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3971 /* Sent later in jit_end () */
3973 g_ptr_array_add (pending_assembly_loads, assembly);
3978 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3980 if (is_debugger_thread ())
3983 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3985 clear_event_requests_for_assembly (assembly);
3986 clear_types_for_assembly (assembly);
3990 send_type_load (MonoClass *klass)
3992 gboolean type_load = FALSE;
3993 MonoDomain *domain = mono_domain_get ();
3994 AgentDomainInfo *info = NULL;
3996 info = get_agent_domain_info (domain);
3998 mono_loader_lock ();
4000 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
4002 g_hash_table_insert (info->loaded_classes, klass, klass);
4005 mono_loader_unlock ();
4008 emit_type_load (klass, klass, NULL);
4012 * Emit load events for all types currently loaded in the domain.
4013 * Takes the loader and domain locks.
4014 * user_data is unused.
4017 send_types_for_domain (MonoDomain *domain, void *user_data)
4019 MonoDomain* old_domain;
4020 AgentDomainInfo *info = NULL;
4022 info = get_agent_domain_info (domain);
4025 old_domain = mono_domain_get ();
4027 mono_domain_set (domain, TRUE);
4029 mono_loader_lock ();
4030 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4031 mono_loader_unlock ();
4033 mono_domain_set (old_domain, TRUE);
4037 send_assemblies_for_domain (MonoDomain *domain, void *user_data)
4040 MonoDomain* old_domain;
4042 old_domain = mono_domain_get ();
4044 mono_domain_set (domain, TRUE);
4046 mono_domain_assemblies_lock (domain);
4047 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
4048 MonoAssembly* ass = (MonoAssembly *)tmp->data;
4049 emit_assembly_load (ass, NULL);
4051 mono_domain_assemblies_unlock (domain);
4053 mono_domain_set (old_domain, TRUE);
4057 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
4060 * We emit type load events when the first method of the type is JITted,
4061 * since the class load profiler callbacks might be called with the
4062 * loader lock held. They could also occur in the debugger thread.
4063 * Same for assembly load events.
4066 MonoAssembly *assembly = NULL;
4068 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4070 if (pending_assembly_loads->len > 0) {
4071 assembly = (MonoAssembly *)g_ptr_array_index (pending_assembly_loads, 0);
4072 g_ptr_array_remove_index (pending_assembly_loads, 0);
4077 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4083 send_type_load (method->klass);
4086 add_pending_breakpoints (method, jinfo);
4090 * BREAKPOINTS/SINGLE STEPPING
4094 * Contains information about an inserted breakpoint.
4097 long il_offset, native_offset;
4101 } BreakpointInstance;
4104 * Contains generic information about a breakpoint.
4108 * The method where the breakpoint is placed. Can be NULL in which case it
4109 * is inserted into every method. This is used to implement method entry/
4110 * exit events. Can be a generic method definition, in which case the
4111 * breakpoint is inserted into every instance.
4117 * A list of BreakpointInstance structures describing where the breakpoint
4118 * was inserted. There could be more than one because of
4119 * generics/appdomains/method entry/exit.
4121 GPtrArray *children;
4124 /* List of breakpoints */
4125 /* Protected by the loader lock */
4126 static GPtrArray *breakpoints;
4127 /* Maps breakpoint locations to the number of breakpoints at that location */
4128 static GHashTable *bp_locs;
4131 breakpoints_init (void)
4133 breakpoints = g_ptr_array_new ();
4134 bp_locs = g_hash_table_new (NULL, NULL);
4138 * insert_breakpoint:
4140 * Insert the breakpoint described by BP into the method described by
4144 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4147 BreakpointInstance *inst;
4148 SeqPointIterator it;
4149 gboolean it_has_sp = FALSE;
4154 mono_seq_point_iterator_init (&it, seq_points);
4155 while (mono_seq_point_iterator_next (&it)) {
4156 if (it.seq_point.il_offset == bp->il_offset) {
4164 * The set of IL offsets with seq points doesn't completely match the
4165 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4167 mono_seq_point_iterator_init (&it, seq_points);
4168 while (mono_seq_point_iterator_next (&it)) {
4169 if (it.seq_point.il_offset != METHOD_ENTRY_IL_OFFSET &&
4170 it.seq_point.il_offset != METHOD_EXIT_IL_OFFSET &&
4171 it.seq_point.il_offset + 1 == bp->il_offset) {
4179 char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d", mono_method_full_name (jinfo_get_method (ji), TRUE), bp->il_offset);
4181 mono_seq_point_iterator_init (&it, seq_points);
4182 while (mono_seq_point_iterator_next (&it))
4183 DEBUG_PRINTF (1, "%d\n", it.seq_point.il_offset);
4186 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4187 g_warning ("%s", s);
4191 g_warning ("%s", s);
4197 inst = g_new0 (BreakpointInstance, 1);
4198 inst->il_offset = it.seq_point.il_offset;
4199 inst->native_offset = it.seq_point.native_offset;
4200 inst->ip = (guint8*)ji->code_start + it.seq_point.native_offset;
4202 inst->domain = domain;
4204 mono_loader_lock ();
4206 g_ptr_array_add (bp->children, inst);
4208 mono_loader_unlock ();
4211 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4212 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4215 if (it.seq_point.native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4216 DEBUG_PRINTF (1, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset);
4217 } else if (count == 0) {
4218 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4219 mono_arch_set_breakpoint (ji, inst->ip);
4225 DEBUG_PRINTF (1, "[dbg] Inserted breakpoint at %s:[il=0x%x,native=0x%x] [%p](%d).\n", mono_method_full_name (jinfo_get_method (ji), TRUE), (int)it.seq_point.il_offset, (int)it.seq_point.native_offset, inst->ip, count);
4229 remove_breakpoint (BreakpointInstance *inst)
4231 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4233 MonoJitInfo *ji = inst->ji;
4234 guint8 *ip = inst->ip;
4237 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4238 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4241 g_assert (count > 0);
4243 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4244 mono_arch_clear_breakpoint (ji, ip);
4245 DEBUG_PRINTF (1, "[dbg] Clear breakpoint at %s [%p].\n", mono_method_full_name (jinfo_get_method (ji), TRUE), ip);
4253 * This doesn't take any locks.
4255 static inline gboolean
4256 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4262 if (method == bp->method)
4264 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4267 if (bp->method->is_inflated && method->is_inflated) {
4268 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4269 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4271 /* Open generic methods should match closed generic methods of the same class */
4272 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4273 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4274 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4276 /* FIXME: Handle !mvar */
4277 if (t1->type != MONO_TYPE_MVAR)
4288 * add_pending_breakpoints:
4290 * Insert pending breakpoints into the newly JITted method METHOD.
4293 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4296 MonoSeqPointInfo *seq_points;
4298 MonoMethod *jmethod;
4303 domain = mono_domain_get ();
4305 mono_loader_lock ();
4307 for (i = 0; i < breakpoints->len; ++i) {
4308 MonoBreakpoint *bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4309 gboolean found = FALSE;
4311 if (!bp_matches_method (bp, method))
4314 for (j = 0; j < bp->children->len; ++j) {
4315 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4322 MonoMethod *declaring = NULL;
4324 jmethod = jinfo_get_method (ji);
4325 if (jmethod->is_inflated)
4326 declaring = mono_method_get_declaring_generic_method (jmethod);
4328 mono_domain_lock (domain);
4329 seq_points = (MonoSeqPointInfo *)g_hash_table_lookup (domain_jit_info (domain)->seq_points, jmethod);
4330 if (!seq_points && declaring)
4331 seq_points = (MonoSeqPointInfo *)g_hash_table_lookup (domain_jit_info (domain)->seq_points, declaring);
4332 mono_domain_unlock (domain);
4334 /* Could be AOT code */
4336 g_assert (seq_points);
4338 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4342 mono_loader_unlock ();
4346 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4354 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4358 /* Might be AOTed code */
4359 mono_class_init (method->klass);
4360 code = mono_aot_get_method_checked (domain, method, &oerror);
4362 mono_error_assert_ok (&oerror);
4363 ji = mono_jit_info_table_find (domain, (char *)code);
4368 insert_breakpoint (seq_points, domain, ji, bp, error);
4372 clear_breakpoint (MonoBreakpoint *bp);
4377 * Set a breakpoint at IL_OFFSET in METHOD.
4378 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4379 * METHOD can also be a generic method definition, in which case a breakpoint
4380 * is placed in all instances of the method.
4381 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4384 static MonoBreakpoint*
4385 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4388 GHashTableIter iter, iter2;
4391 MonoSeqPointInfo *seq_points;
4393 GPtrArray *method_domains;
4394 GPtrArray *method_seq_points;
4401 // - suspend/resume the vm to prevent code patching problems
4402 // - multiple breakpoints on the same location
4403 // - dynamic methods
4406 bp = g_new0 (MonoBreakpoint, 1);
4407 bp->method = method;
4408 bp->il_offset = il_offset;
4410 bp->children = g_ptr_array_new ();
4412 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);
4414 methods = g_ptr_array_new ();
4415 method_domains = g_ptr_array_new ();
4416 method_seq_points = g_ptr_array_new ();
4418 mono_loader_lock ();
4419 g_hash_table_iter_init (&iter, domains);
4420 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4421 mono_domain_lock (domain);
4422 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4423 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4424 if (bp_matches_method (bp, m)) {
4425 /* Save the info locally to simplify the code inside the domain lock */
4426 g_ptr_array_add (methods, m);
4427 g_ptr_array_add (method_domains, domain);
4428 g_ptr_array_add (method_seq_points, seq_points);
4431 mono_domain_unlock (domain);
4434 for (i = 0; i < methods->len; ++i) {
4435 m = (MonoMethod *)g_ptr_array_index (methods, i);
4436 domain = (MonoDomain *)g_ptr_array_index (method_domains, i);
4437 seq_points = (MonoSeqPointInfo *)g_ptr_array_index (method_seq_points, i);
4438 set_bp_in_method (domain, m, seq_points, bp, error);
4441 g_ptr_array_add (breakpoints, bp);
4442 mono_loader_unlock ();
4444 g_ptr_array_free (methods, TRUE);
4445 g_ptr_array_free (method_domains, TRUE);
4446 g_ptr_array_free (method_seq_points, TRUE);
4448 if (error && !mono_error_ok (error)) {
4449 clear_breakpoint (bp);
4457 clear_breakpoint (MonoBreakpoint *bp)
4461 // FIXME: locking, races
4462 for (i = 0; i < bp->children->len; ++i) {
4463 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, i);
4465 remove_breakpoint (inst);
4470 mono_loader_lock ();
4471 g_ptr_array_remove (breakpoints, bp);
4472 mono_loader_unlock ();
4474 g_ptr_array_free (bp->children, TRUE);
4479 breakpoints_cleanup (void)
4483 mono_loader_lock ();
4485 while (i < event_requests->len) {
4486 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
4488 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4489 clear_breakpoint ((MonoBreakpoint *)req->info);
4490 g_ptr_array_remove_index_fast (event_requests, i);
4497 for (i = 0; i < breakpoints->len; ++i)
4498 g_free (g_ptr_array_index (breakpoints, i));
4500 g_ptr_array_free (breakpoints, TRUE);
4501 g_hash_table_destroy (bp_locs);
4506 mono_loader_unlock ();
4510 * clear_breakpoints_for_domain:
4512 * Clear breakpoint instances which reference DOMAIN.
4515 clear_breakpoints_for_domain (MonoDomain *domain)
4519 /* This could be called after shutdown */
4523 mono_loader_lock ();
4524 for (i = 0; i < breakpoints->len; ++i) {
4525 MonoBreakpoint *bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4528 while (j < bp->children->len) {
4529 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4531 if (inst->domain == domain) {
4532 remove_breakpoint (inst);
4536 g_ptr_array_remove_index_fast (bp->children, j);
4542 mono_loader_unlock ();
4546 * ss_calculate_framecount:
4548 * Ensure DebuggerTlsData fields are filled out.
4550 static void ss_calculate_framecount (DebuggerTlsData *tls, MonoContext *ctx)
4552 if (!tls->context.valid)
4553 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4554 compute_frame_info (tls->thread, tls);
4558 ensure_jit (StackFrame* frame)
4561 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
4562 if (!frame->jit && frame->api_method->is_inflated)
4563 frame->jit = mono_debug_find_method(mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
4567 /* This could happen for aot images with no jit debug info */
4568 s = mono_method_full_name (frame->api_method, TRUE);
4569 DEBUG_PRINTF(1, "[dbg] No debug information found for '%s'.\n", s);
4580 * Return FALSE if single stepping needs to continue.
4583 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp, DebuggerTlsData *tls, MonoContext *ctx, MonoMethod* method)
4585 MonoDebugMethodInfo *minfo;
4586 MonoDebugSourceLocation *loc = NULL;
4587 gboolean hit = TRUE;
4589 if (req->async_stepout_method == method) {
4590 DEBUG_PRINTF (1, "[%p] Breakpoint hit during async step-out at %s hit, continuing stepping out.\n", (gpointer)(gsize)mono_native_thread_id_get (), method->name);
4594 if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK)) {
4596 * These seq points are inserted by the JIT after calls, step over needs to skip them.
4598 DEBUG_PRINTF (1, "[%p] Seq point at nonempty stack %x while stepping over, continuing single stepping.\n", (gpointer) (gsize) mono_native_thread_id_get (), sp->il_offset);
4602 if ((req->depth == STEP_DEPTH_OVER || req->depth == STEP_DEPTH_OUT) && hit && !req->async_stepout_method) {
4603 gboolean is_step_out = req->depth == STEP_DEPTH_OUT;
4605 ss_calculate_framecount (tls, ctx);
4607 // Because functions can call themselves recursively, we need to make sure we're stopping at the right stack depth.
4608 // In case of step out, the target is the frame *enclosing* the one where the request was made.
4609 int target_frames = req->nframes + (is_step_out ? -1 : 0);
4610 if (req->nframes > 0 && tls->frame_count > 0 && tls->frame_count > target_frames) {
4611 /* Hit the breakpoint in a recursive call, don't halt */
4612 DEBUG_PRINTF (1, "[%p] Breakpoint at lower frame while stepping %s, continuing single stepping.\n", (gpointer) (gsize) mono_native_thread_id_get (), is_step_out ? "out" : "over");
4617 if (req->depth == STEP_DEPTH_INTO && req->size == STEP_SIZE_MIN && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) && ss_req->start_method){
4618 ss_calculate_framecount (tls, ctx);
4619 if (ss_req->start_method == method && req->nframes && tls->frame_count == req->nframes) {//Check also frame count(could be recursion)
4620 DEBUG_PRINTF (1, "[%p] Seq point at nonempty stack %x while stepping in, continuing single stepping.\n", (gpointer) (gsize) mono_native_thread_id_get (), sp->il_offset);
4625 MonoDebugMethodAsyncInfo* asyncMethod = mono_debug_lookup_method_async_debug_info (method);
4627 for (int i = 0; i < asyncMethod->num_awaits; i++)
4629 if (asyncMethod->yield_offsets[i] == sp->il_offset || asyncMethod->resume_offsets[i] == sp->il_offset) {
4630 mono_debug_free_method_async_debug_info (asyncMethod);
4634 mono_debug_free_method_async_debug_info (asyncMethod);
4637 if (req->size != STEP_SIZE_LINE)
4640 /* Have to check whenever a different source line was reached */
4641 minfo = mono_debug_lookup_method (method);
4644 loc = mono_debug_method_lookup_location (minfo, sp->il_offset);
4647 DEBUG_PRINTF (1, "[%p] No line number info for il offset %x, continuing single stepping.\n", (gpointer) (gsize) mono_native_thread_id_get (), sp->il_offset);
4648 ss_req->last_method = method;
4650 } else if (loc && method == ss_req->last_method && loc->row == ss_req->last_line) {
4651 ss_calculate_framecount (tls, ctx);
4652 if (tls->frame_count == req->nframes) { // If the frame has changed we're clearly not on the same source line.
4653 DEBUG_PRINTF (1, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer) (gsize) mono_native_thread_id_get (), loc->row);
4659 ss_req->last_method = method;
4660 ss_req->last_line = loc->row;
4661 mono_debug_free_source_location (loc);
4668 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4670 return bp->method && bp->method->klass->image->assembly == assembly;
4674 get_this (StackFrame *frame)
4676 //Logic inspiered by "add_var" method and took out path that happens in async method for getting this
4677 MonoDebugVarInfo *var = frame->jit->this_var;
4678 if ((var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS) != MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET)
4681 guint8 * addr = (guint8 *)mono_arch_context_get_int_reg (&frame->ctx, var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS);
4682 addr += (gint32)var->offset;
4683 return *(MonoObject**)addr;
4686 //This ID is used to figure out if breakpoint hit on resumeOffset belongs to us or not
4687 //since thread probably changed...
4689 get_this_async_id (StackFrame *frame)
4691 return get_objid (get_this (frame));
4694 static MonoMethod* set_notification_method_cache = NULL;
4697 get_set_notification_method ()
4699 if(set_notification_method_cache != NULL)
4700 return set_notification_method_cache;
4702 MonoClass* async_builder_class = mono_class_load_from_name (mono_defaults.corlib, "System.Runtime.CompilerServices", "AsyncTaskMethodBuilder");
4703 GPtrArray* array = mono_class_get_methods_by_name (async_builder_class, "SetNotificationForWaitCompletion", 0x24, FALSE, FALSE, &error);
4704 mono_error_assert_ok (&error);
4705 g_assert (array->len == 1);
4706 set_notification_method_cache = (MonoMethod *)g_ptr_array_index (array, 0);
4707 g_ptr_array_free (array, TRUE);
4708 return set_notification_method_cache;
4712 set_set_notification_for_wait_completion_flag (StackFrame *frame)
4714 MonoObject* obj = get_this (frame);
4716 MonoClassField *builder_field = mono_class_get_field_from_name (obj->vtable->klass, "<>t__builder");
4717 g_assert (builder_field);
4718 MonoObject* builder;
4720 builder = mono_field_get_value_object_checked (frame->domain, builder_field, obj, &error);
4721 mono_error_assert_ok (&error);
4725 gboolean arg = TRUE;
4727 mono_runtime_invoke_checked (get_set_notification_method(), mono_object_unbox (builder), args, &error);
4728 mono_error_assert_ok (&error);
4729 mono_field_set_value (obj, builder_field, mono_object_unbox (builder));
4732 static MonoMethod* notify_debugger_of_wait_completion_method_cache = NULL;
4735 get_notify_debugger_of_wait_completion_method ()
4737 if (notify_debugger_of_wait_completion_method_cache != NULL)
4738 return notify_debugger_of_wait_completion_method_cache;
4740 MonoClass* task_class = mono_class_load_from_name (mono_defaults.corlib, "System.Threading.Tasks", "Task");
4741 GPtrArray* array = mono_class_get_methods_by_name (task_class, "NotifyDebuggerOfWaitCompletion", 0x24, FALSE, FALSE, &error);
4742 mono_error_assert_ok (&error);
4743 g_assert (array->len == 1);
4744 notify_debugger_of_wait_completion_method_cache = (MonoMethod *)g_ptr_array_index (array, 0);
4745 g_ptr_array_free (array, TRUE);
4746 return notify_debugger_of_wait_completion_method_cache;
4750 process_breakpoint_inner (DebuggerTlsData *tls, gboolean from_signal)
4754 int i, j, suspend_policy;
4755 guint32 native_offset;
4757 BreakpointInstance *inst;
4758 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4759 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4760 EventKind kind = EVENT_KIND_BREAKPOINT;
4761 MonoContext *ctx = &tls->restore_state.ctx;
4763 MonoSeqPointInfo *info;
4767 // FIXME: Speed this up
4769 ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
4770 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4771 g_assert (ji && !ji->is_trampoline);
4772 method = jinfo_get_method (ji);
4774 /* Compute the native offset of the breakpoint from the ip */
4775 native_offset = ip - (guint8*)ji->code_start;
4778 * Skip the instruction causing the breakpoint signal.
4781 mono_arch_skip_breakpoint (ctx, ji);
4783 if (method->wrapper_type || tls->disable_breakpoints)
4786 bp_reqs = g_ptr_array_new ();
4787 ss_reqs = g_ptr_array_new ();
4788 ss_reqs_orig = g_ptr_array_new ();
4790 mono_loader_lock ();
4793 * The ip points to the instruction causing the breakpoint event, which is after
4794 * the offset recorded in the seq point map, so find the prev seq point before ip.
4796 found_sp = mono_find_prev_seq_point_for_native_offset (mono_domain_get (), method, native_offset, &info, &sp);
4799 no_seq_points_found (method, native_offset);
4801 g_assert (found_sp);
4803 DEBUG_PRINTF (1, "[%p] Breakpoint hit, method=%s, ip=%p, [il=0x%x,native=0x%x].\n", (gpointer) (gsize) mono_native_thread_id_get (), method->name, ip, sp.il_offset, native_offset);
4806 for (i = 0; i < breakpoints->len; ++i) {
4807 bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4812 for (j = 0; j < bp->children->len; ++j) {
4813 inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4814 if (inst->ji == ji && inst->il_offset == sp.il_offset && inst->native_offset == sp.native_offset) {
4815 if (bp->req->event_kind == EVENT_KIND_STEP) {
4816 g_ptr_array_add (ss_reqs_orig, bp->req);
4818 g_ptr_array_add (bp_reqs, bp->req);
4823 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4824 /* Maybe a method entry/exit event */
4825 if (sp.il_offset == METHOD_ENTRY_IL_OFFSET)
4826 kind = EVENT_KIND_METHOD_ENTRY;
4827 else if (sp.il_offset == METHOD_EXIT_IL_OFFSET)
4828 kind = EVENT_KIND_METHOD_EXIT;
4831 /* Process single step requests */
4832 for (i = 0; i < ss_reqs_orig->len; ++i) {
4833 EventRequest *req = (EventRequest *)g_ptr_array_index (ss_reqs_orig, i);
4834 SingleStepReq *ss_req = (SingleStepReq *)req->info;
4837 //if we hit async_stepout_method, it's our no matter which thread
4838 if ((ss_req->async_stepout_method != method) && (ss_req->async_id || mono_thread_internal_current () != ss_req->thread)) {
4839 //We have different thread and we don't have async stepping in progress
4840 //it's breakpoint in parallel thread, ignore it
4841 if (ss_req->async_id == 0)
4844 tls->context.valid = FALSE;
4845 tls->async_state.valid = FALSE;
4846 invalidate_frames (tls);
4847 ss_calculate_framecount(tls, ctx);
4848 //make sure we have enough data to get current async method instance id
4849 if (tls->frame_count == 0 || !ensure_jit (tls->frames [0]))
4852 //Check method is async before calling get_this_async_id
4853 MonoDebugMethodAsyncInfo* asyncMethod = mono_debug_lookup_method_async_debug_info (method);
4857 mono_debug_free_method_async_debug_info (asyncMethod);
4859 //breakpoint was hit in parallelly executing async method, ignore it
4860 if (ss_req->async_id != get_this_async_id (tls->frames [0]))
4864 //Update stepping request to new thread/frame_count that we are continuing on
4865 //so continuing with normal stepping works as expected
4866 if (ss_req->async_stepout_method || ss_req->async_id) {
4867 tls->context.valid = FALSE;
4868 tls->async_state.valid = FALSE;
4869 invalidate_frames (tls);
4870 ss_calculate_framecount (tls, ctx);
4871 ss_req->thread = mono_thread_internal_current ();
4872 ss_req->nframes = tls->frame_count;
4875 hit = ss_update (ss_req, ji, &sp, tls, ctx, method);
4877 g_ptr_array_add (ss_reqs, req);
4879 /* Start single stepping again from the current sequence point */
4880 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
4883 if (ss_reqs->len > 0)
4884 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4885 if (bp_reqs->len > 0)
4886 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4887 if (kind != EVENT_KIND_BREAKPOINT)
4888 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4890 mono_loader_unlock ();
4892 g_ptr_array_free (bp_reqs, TRUE);
4893 g_ptr_array_free (ss_reqs, TRUE);
4896 * FIXME: The first event will suspend, so the second will only be sent after the
4900 process_event (EVENT_KIND_STEP, method, 0, ctx, ss_events, suspend_policy);
4902 process_event (kind, method, 0, ctx, bp_events, suspend_policy);
4903 if (enter_leave_events)
4904 process_event (kind, method, 0, ctx, enter_leave_events, suspend_policy);
4907 /* Process a breakpoint/single step event after resuming from a signal handler */
4909 process_signal_event (void (*func) (DebuggerTlsData*, gboolean))
4911 DebuggerTlsData *tls;
4912 MonoThreadUnwindState orig_restore_state;
4915 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4916 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4917 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4918 mono_thread_state_init_from_monoctx (&tls->restore_state, &tls->handler_ctx);
4922 /* This is called when resuming from a signal handler, so it shouldn't return */
4923 memcpy (&ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4924 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4925 mono_restore_context (&ctx);
4926 g_assert_not_reached ();
4930 process_breakpoint (void)
4932 process_signal_event (process_breakpoint_inner);
4936 resume_from_signal_handler (void *sigctx, void *func)
4938 DebuggerTlsData *tls;
4941 /* Save the original context in TLS */
4942 // FIXME: This might not work on an altstack ?
4943 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4945 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer) (gsize) mono_native_thread_id_get ());
4948 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4949 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4950 // clob:c could be added to op_seq_point.
4952 mono_sigctx_to_monoctx (sigctx, &ctx);
4953 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4954 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4955 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4957 MONO_CONTEXT_SET_IP (&ctx, func);
4959 mono_monoctx_to_sigctx (&ctx, sigctx);
4961 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4962 mono_ppc_set_func_into_sigctx (sigctx, func);
4967 mono_debugger_agent_breakpoint_hit (void *sigctx)
4970 * We are called from a signal handler, and running code there causes all kinds of
4971 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4972 * So set up the signal context to return to the real breakpoint handler function.
4974 resume_from_signal_handler (sigctx, process_breakpoint);
4978 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4980 if (frame->managed) {
4981 *(MonoContext*)data = *ctx;
4990 * Called by System.Diagnostics.Debugger:Break ().
4993 mono_debugger_agent_user_break (void)
4995 if (agent_config.enabled) {
5000 /* Obtain a context */
5001 MONO_CONTEXT_SET_IP (&ctx, NULL);
5002 mono_walk_stack_with_ctx (user_break_cb, NULL, (MonoUnwindOptions)0, &ctx);
5003 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
5005 mono_loader_lock ();
5006 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
5007 mono_loader_unlock ();
5009 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
5010 } else if (debug_options.native_debugger_break) {
5016 ss_depth_to_string (StepDepth depth)
5019 case STEP_DEPTH_OVER:
5021 case STEP_DEPTH_OUT:
5023 case STEP_DEPTH_INTO:
5026 g_assert_not_reached ();
5032 process_single_step_inner (DebuggerTlsData *tls, gboolean from_signal)
5037 int il_offset, suspend_policy;
5040 MonoContext *ctx = &tls->restore_state.ctx;
5043 MonoSeqPointInfo *info;
5045 ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
5047 /* Skip the instruction causing the single step */
5049 mono_arch_skip_single_step (ctx);
5051 if (suspend_count > 0) {
5052 /* Fastpath during invokes, see in process_suspend () */
5053 if (suspend_count - tls->resume_count == 0)
5055 process_suspend (tls, ctx);
5060 // FIXME: A suspend race
5063 if (mono_thread_internal_current () != ss_req->thread)
5066 if (log_level > 0) {
5067 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
5069 DEBUG_PRINTF (1, "[%p] Single step event (depth=%s) at %s (%p)[0x%x], sp %p, last sp %p\n", (gpointer) (gsize) mono_native_thread_id_get (), ss_depth_to_string (ss_req->depth), mono_method_full_name (jinfo_get_method (ji), TRUE), MONO_CONTEXT_GET_IP (ctx), (int)((guint8*)MONO_CONTEXT_GET_IP (ctx) - (guint8*)ji->code_start), MONO_CONTEXT_GET_SP (ctx), ss_req->last_sp);
5072 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
5073 g_assert (ji && !ji->is_trampoline);
5074 method = jinfo_get_method (ji);
5077 if (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
5082 * Stopping in memset makes half-initialized vtypes visible.
5083 * Stopping in memcpy makes half-copied vtypes visible.
5085 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
5089 * This could be in ss_update method, but mono_find_next_seq_point_for_native_offset is pretty expensive method,
5090 * hence we prefer this check here.
5092 if (ss_req->user_assemblies) {
5093 gboolean found = FALSE;
5094 for (int k = 0; ss_req->user_assemblies[k]; k++)
5095 if (ss_req->user_assemblies[k] == method->klass->image->assembly) {
5105 * The ip points to the instruction causing the single step event, which is before
5106 * the offset recorded in the seq point map, so find the next seq point after ip.
5108 if (!mono_find_next_seq_point_for_native_offset (domain, method, (guint8*)ip - (guint8*)ji->code_start, &info, &sp))
5111 il_offset = sp.il_offset;
5113 if (!ss_update (ss_req, ji, &sp, tls, ctx, method))
5116 /* Start single stepping again from the current sequence point */
5117 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
5119 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
5120 (method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
5121 !strcmp (method->name, ".cctor"))
5124 // FIXME: Has to lock earlier
5126 reqs = g_ptr_array_new ();
5128 mono_loader_lock ();
5130 g_ptr_array_add (reqs, ss_req->req);
5132 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
5134 g_ptr_array_free (reqs, TRUE);
5136 mono_loader_unlock ();
5138 process_event (EVENT_KIND_STEP, jinfo_get_method (ji), il_offset, ctx, events, suspend_policy);
5142 process_single_step (void)
5144 process_signal_event (process_single_step_inner);
5148 * mono_debugger_agent_single_step_event:
5150 * Called from a signal handler to handle a single step event.
5153 mono_debugger_agent_single_step_event (void *sigctx)
5155 /* Resume to process_single_step through the signal context */
5157 // FIXME: Since step out/over is implemented using step in, the step in case should
5158 // be as fast as possible. Move the relevant code from process_single_step_inner ()
5161 if (is_debugger_thread ()) {
5163 * This could happen despite our best effors when the runtime calls
5164 * assembly/type resolve hooks.
5165 * FIXME: Breakpoints too.
5169 mono_sigctx_to_monoctx (sigctx, &ctx);
5170 mono_arch_skip_single_step (&ctx);
5171 mono_monoctx_to_sigctx (&ctx, sigctx);
5175 resume_from_signal_handler (sigctx, process_single_step);
5179 debugger_agent_single_step_from_context (MonoContext *ctx)
5181 DebuggerTlsData *tls;
5182 MonoThreadUnwindState orig_restore_state;
5184 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5185 /* Fastpath during invokes, see in process_suspend () */
5186 if (tls && suspend_count && suspend_count - tls->resume_count == 0)
5189 if (is_debugger_thread ())
5194 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
5195 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5196 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5197 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5199 process_single_step_inner (tls, FALSE);
5201 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5202 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5206 debugger_agent_breakpoint_from_context (MonoContext *ctx)
5208 DebuggerTlsData *tls;
5209 MonoThreadUnwindState orig_restore_state;
5212 if (is_debugger_thread ())
5215 orig_ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
5216 MONO_CONTEXT_SET_IP (ctx, orig_ip - 1);
5218 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5220 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5221 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5222 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5224 process_breakpoint_inner (tls, FALSE);
5226 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5227 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5228 if (MONO_CONTEXT_GET_IP (ctx) == orig_ip - 1)
5229 MONO_CONTEXT_SET_IP (ctx, orig_ip);
5233 * start_single_stepping:
5235 * Turn on single stepping. Can be called multiple times, for example,
5236 * by a single step event request + a suspend.
5239 start_single_stepping (void)
5241 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5242 int val = InterlockedIncrement (&ss_count);
5245 mono_arch_start_single_stepping ();
5247 g_assert_not_reached ();
5252 stop_single_stepping (void)
5254 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5255 int val = InterlockedDecrement (&ss_count);
5258 mono_arch_stop_single_stepping ();
5260 g_assert_not_reached ();
5267 * Stop the single stepping operation given by SS_REQ.
5270 ss_stop (SingleStepReq *ss_req)
5275 for (l = ss_req->bps; l; l = l->next) {
5276 clear_breakpoint ((MonoBreakpoint *)l->data);
5278 g_slist_free (ss_req->bps);
5282 ss_req->async_id = 0;
5283 ss_req->async_stepout_method = NULL;
5284 if (ss_req->global) {
5285 stop_single_stepping ();
5286 ss_req->global = FALSE;
5293 * Reject breakpoint if it is a duplicate of one already in list or hash table.
5296 ss_bp_is_unique (GSList *bps, GHashTable *ss_req_bp_cache, MonoMethod *method, guint32 il_offset)
5298 if (ss_req_bp_cache) {
5299 MonoBreakpoint dummy = {method, il_offset, NULL, NULL};
5300 return !g_hash_table_lookup (ss_req_bp_cache, &dummy);
5302 for (GSList *l = bps; l; l = l->next) {
5303 MonoBreakpoint *bp = (MonoBreakpoint *)l->data;
5304 if (bp->method == method && bp->il_offset == il_offset)
5313 * GHashTable equality for a MonoBreakpoint (only care about method and il_offset fields)
5316 ss_bp_eq (gconstpointer ka, gconstpointer kb)
5318 const MonoBreakpoint *s1 = (const MonoBreakpoint *)ka;
5319 const MonoBreakpoint *s2 = (const MonoBreakpoint *)kb;
5320 return (s1->method == s2->method && s1->il_offset == s2->il_offset) ? 1 : 0;
5326 * GHashTable hash for a MonoBreakpoint (only care about method and il_offset fields)
5329 ss_bp_hash (gconstpointer data)
5331 const MonoBreakpoint *s = (const MonoBreakpoint *)data;
5332 guint hash = (guint) (uintptr_t) s->method;
5333 hash ^= ((guint)s->il_offset) << 16; // Assume low bits are more interesting
5334 hash ^= ((guint)s->il_offset) >> 16;
5338 #define MAX_LINEAR_SCAN_BPS 7
5343 * Create a new breakpoint and add it to a step request.
5344 * Will adjust the bp count and cache used by ss_start.
5347 ss_bp_add_one (SingleStepReq *ss_req, int *ss_req_bp_count, GHashTable **ss_req_bp_cache,
5348 MonoMethod *method, guint32 il_offset)
5350 // This list is getting too long, switch to using the hash table
5351 if (!*ss_req_bp_cache && *ss_req_bp_count > MAX_LINEAR_SCAN_BPS) {
5352 *ss_req_bp_cache = g_hash_table_new (ss_bp_hash, ss_bp_eq);
5353 for (GSList *l = ss_req->bps; l; l = l->next)
5354 g_hash_table_insert (*ss_req_bp_cache, l->data, l->data);
5357 if (ss_bp_is_unique (ss_req->bps, *ss_req_bp_cache, method, il_offset)) {
5358 // Create and add breakpoint
5359 MonoBreakpoint *bp = set_breakpoint (method, il_offset, ss_req->req, NULL);
5360 ss_req->bps = g_slist_append (ss_req->bps, bp);
5361 if (*ss_req_bp_cache)
5362 g_hash_table_insert (*ss_req_bp_cache, bp, bp);
5363 (*ss_req_bp_count)++;
5365 DEBUG_PRINTF (1, "[dbg] Candidate breakpoint at %s:[il=0x%x] is a duplicate for this step request, will not add.\n", mono_method_full_name (method, TRUE), (int)il_offset);
5370 is_last_non_empty (SeqPoint* sp, MonoSeqPointInfo *info)
5374 SeqPoint* next = g_new (SeqPoint, sp->next_len);
5375 mono_seq_point_init_next (info, *sp, next);
5376 for (int i = 0; i < sp->next_len; i++) {
5377 if (next [i].flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) {
5378 if (!is_last_non_empty (&next [i], info)) {
5394 * Start the single stepping operation given by SS_REQ from the sequence point SP.
5395 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
5396 * belong to the same thread as CTX.
5397 * If FRAMES is not-null, use that instead of tls->frames for placing breakpoints etc.
5400 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint* sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls,
5401 gboolean step_to_catch, StackFrame **frames, int nframes)
5403 int i, j, frame_index;
5404 SeqPoint *next_sp, *parent_sp = NULL;
5405 SeqPoint local_sp, local_parent_sp;
5407 MonoSeqPointInfo *parent_info;
5408 MonoMethod *parent_sp_method = NULL;
5409 gboolean enable_global = FALSE;
5411 // When 8 or more entries are in bps, we build a hash table to serve as a set of breakpoints.
5412 // Recreating this on each pass is a little wasteful but at least keeps behavior linear.
5413 int ss_req_bp_count = g_slist_length (ss_req->bps);
5414 GHashTable *ss_req_bp_cache = NULL;
5416 /* Stop the previous operation */
5420 * Implement single stepping using breakpoints if possible.
5422 if (step_to_catch) {
5423 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, sp->il_offset);
5427 if (ctx && !frames) {
5428 /* Need parent frames */
5429 if (!tls->context.valid)
5430 mono_thread_state_init_from_monoctx (&tls->context, ctx);
5431 compute_frame_info (tls->thread, tls);
5432 frames = tls->frames;
5433 nframes = tls->frame_count;
5436 MonoDebugMethodAsyncInfo* asyncMethod = mono_debug_lookup_method_async_debug_info (method);
5438 /* Need to stop in catch clauses as well */
5439 for (i = ss_req->depth == STEP_DEPTH_OUT ? 1 : 0; i < nframes; ++i) {
5440 StackFrame *frame = frames [i];
5443 MonoJitInfo *jinfo = frame->ji;
5444 for (j = 0; j < jinfo->num_clauses; ++j) {
5445 // In case of async method we don't want to place breakpoint on last catch handler(which state machine added for whole method)
5446 if (asyncMethod && asyncMethod->num_awaits && i == 0 && j + 1 == jinfo->num_clauses)
5448 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5450 if (mono_find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL, &local_sp))
5451 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, frame->method, local_sp.il_offset);
5456 if (asyncMethod && asyncMethod->num_awaits && nframes && ensure_jit (frames [0])) {
5457 //asyncMethod has value and num_awaits > 0, this means we are inside async method with awaits
5459 // Check if we hit yield_offset during normal stepping, because if we did...
5460 // Go into special async stepping mode which places breakpoint on resumeOffset
5461 // of this await call and sets async_id so we can distinguish it from parallel executions
5462 for (i = 0; i < asyncMethod->num_awaits; i++) {
5463 if (sp->il_offset == asyncMethod->yield_offsets [i]) {
5464 ss_req->async_id = get_this_async_id (frames [0]);
5465 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, asyncMethod->resume_offsets [i]);
5466 if (ss_req_bp_cache)
5467 g_hash_table_destroy (ss_req_bp_cache);
5468 mono_debug_free_method_async_debug_info (asyncMethod);
5472 //If we are at end of async method and doing step-in or step-over...
5473 //Switch to step-out, so whole NotifyDebuggerOfWaitCompletion magic happens...
5474 if (is_last_non_empty (sp, info)) {
5475 ss_req->depth = STEP_DEPTH_OUT;//setting depth to step-out is important, don't inline IF, because code later depends on this
5477 if (ss_req->depth == STEP_DEPTH_OUT) {
5478 set_set_notification_for_wait_completion_flag (frames [0]);
5479 ss_req->async_id = get_this_async_id (frames [0]);
5480 ss_req->async_stepout_method = get_notify_debugger_of_wait_completion_method ();
5481 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, ss_req->async_stepout_method, 0);
5482 if (ss_req_bp_cache)
5483 g_hash_table_destroy (ss_req_bp_cache);
5484 mono_debug_free_method_async_debug_info (asyncMethod);
5490 mono_debug_free_method_async_debug_info (asyncMethod);
5493 * Find the first sequence point in the current or in a previous frame which
5494 * is not the last in its method.
5496 if (ss_req->depth == STEP_DEPTH_OUT) {
5497 /* Ignore seq points in current method */
5498 while (frame_index < nframes) {
5499 StackFrame *frame = frames [frame_index];
5501 method = frame->method;
5502 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5503 sp = (found_sp)? &local_sp : NULL;
5505 if (sp && sp->next_len != 0)
5508 // There could be method calls before the next seq point in the caller when using nested calls
5509 //enable_global = TRUE;
5511 if (sp && sp->next_len == 0) {
5513 while (frame_index < nframes) {
5514 StackFrame *frame = frames [frame_index];
5516 method = frame->method;
5517 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5518 sp = (found_sp)? &local_sp : NULL;
5519 if (sp && sp->next_len != 0)
5525 /* Have to put a breakpoint into a parent frame since the seq points might not cover all control flow out of the method */
5526 while (frame_index < nframes) {
5527 StackFrame *frame = frames [frame_index];
5529 parent_sp_method = frame->method;
5530 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &parent_info, &local_parent_sp);
5531 parent_sp = found_sp ? &local_parent_sp : NULL;
5532 if (found_sp && parent_sp->next_len != 0)
5540 if (sp && sp->next_len > 0) {
5541 SeqPoint* next = g_new(SeqPoint, sp->next_len);
5543 mono_seq_point_init_next (info, *sp, next);
5544 for (i = 0; i < sp->next_len; i++) {
5547 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, next_sp->il_offset);
5553 SeqPoint* next = g_new(SeqPoint, parent_sp->next_len);
5555 mono_seq_point_init_next (parent_info, *parent_sp, next);
5556 for (i = 0; i < parent_sp->next_len; i++) {
5559 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, parent_sp_method, next_sp->il_offset);
5564 if (ss_req->nframes == 0)
5565 ss_req->nframes = nframes;
5567 if ((ss_req->depth == STEP_DEPTH_OVER) && (!sp && !parent_sp)) {
5568 DEBUG_PRINTF (1, "[dbg] No parent frame for step over, transition to step into.\n");
5570 * This is needed since if we leave managed code, and later return to it, step over
5571 * is not going to stop.
5572 * This approach is a bit ugly, since we change the step depth, but it only affects
5573 * clients who reuse the same step request, and only in this special case.
5575 ss_req->depth = STEP_DEPTH_INTO;
5578 if (ss_req->depth == STEP_DEPTH_INTO) {
5579 /* Enable global stepping so we stop at method entry too */
5580 enable_global = TRUE;
5584 * The ctx/frame info computed above will become invalid when we continue.
5586 tls->context.valid = FALSE;
5587 tls->async_state.valid = FALSE;
5588 invalidate_frames (tls);
5591 if (enable_global) {
5592 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5593 ss_req->global = TRUE;
5594 start_single_stepping ();
5595 } else if (!ss_req->bps) {
5596 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5597 ss_req->global = TRUE;
5598 start_single_stepping ();
5600 ss_req->global = FALSE;
5603 if (ss_req_bp_cache)
5604 g_hash_table_destroy (ss_req_bp_cache);
5608 * Start single stepping of thread THREAD
5611 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req)
5613 DebuggerTlsData *tls;
5614 MonoSeqPointInfo *info = NULL;
5615 SeqPoint *sp = NULL;
5618 MonoMethod *method = NULL;
5619 MonoDebugMethodInfo *minfo;
5620 gboolean step_to_catch = FALSE;
5621 gboolean set_ip = FALSE;
5622 StackFrame **frames = NULL;
5625 if (suspend_count == 0)
5626 return ERR_NOT_SUSPENDED;
5628 wait_for_suspend ();
5630 // FIXME: Multiple requests
5632 DEBUG_PRINTF (0, "Received a single step request while the previous one was still active.\n");
5633 return ERR_NOT_IMPLEMENTED;
5636 DEBUG_PRINTF (1, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth));
5638 ss_req = g_new0 (SingleStepReq, 1);
5640 ss_req->thread = thread;
5641 ss_req->size = size;
5642 ss_req->depth = depth;
5643 ss_req->filter = filter;
5646 for (int i = 0; i < req->nmodifiers; i++) {
5647 if (req->modifiers[i].kind == MOD_KIND_ASSEMBLY_ONLY) {
5648 ss_req->user_assemblies = req->modifiers[i].data.assemblies;
5653 mono_loader_lock ();
5654 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5655 mono_loader_unlock ();
5657 if (!tls->context.valid) {
5658 DEBUG_PRINTF (1, "Received a single step request on a thread with no managed frames.");
5659 return ERR_INVALID_ARGUMENT;
5662 if (tls->restore_state.valid && MONO_CONTEXT_GET_IP (&tls->context.ctx) != MONO_CONTEXT_GET_IP (&tls->restore_state.ctx)) {
5664 * Need to start single stepping from restore_state and not from the current state
5667 frames = compute_frame_info_from (thread, tls, &tls->restore_state, &nframes);
5670 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5672 if (tls->catch_state.valid) {
5674 StackFrameInfo frame;
5675 MonoContext new_ctx;
5676 MonoLMF *lmf = NULL;
5679 * We are stopped at a throw site. Stepping should go to the catch site.
5682 /* Find the the jit info for the catch context */
5683 res = mono_find_jit_info_ext (
5684 (MonoDomain *)tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN],
5685 (MonoJitTlsData *)((MonoThreadInfo*)thread->thread_info)->jit_data,
5686 NULL, &tls->catch_state.ctx, &new_ctx, NULL, &lmf, NULL, &frame);
5688 g_assert (frame.type == FRAME_TYPE_MANAGED);
5691 * Find the seq point corresponding to the landing site ip, which is the first seq
5694 found_sp = mono_find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info, &local_sp);
5695 sp = (found_sp)? &local_sp : NULL;
5697 no_seq_points_found (frame.method, frame.native_offset);
5700 method = frame.method;
5702 step_to_catch = TRUE;
5703 /* This make sure the seq point is not skipped by process_single_step () */
5704 ss_req->last_sp = NULL;
5707 if (!step_to_catch) {
5708 StackFrame *frame = NULL;
5711 if (frames && nframes)
5714 compute_frame_info (thread, tls);
5716 if (tls->frame_count)
5717 frame = tls->frames [0];
5720 if (ss_req->size == STEP_SIZE_LINE) {
5722 ss_req->last_method = frame->method;
5723 ss_req->last_line = -1;
5725 minfo = mono_debug_lookup_method (frame->method);
5726 if (minfo && frame->il_offset != -1) {
5727 MonoDebugSourceLocation *loc = mono_debug_method_lookup_location (minfo, frame->il_offset);
5730 ss_req->last_line = loc->row;
5738 if (!method && frame->il_offset != -1) {
5739 /* FIXME: Sort the table and use a binary search */
5740 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5741 sp = (found_sp)? &local_sp : NULL;
5743 no_seq_points_found (frame->method, frame->native_offset);
5745 method = frame->method;
5750 ss_req->start_method = method;
5752 ss_start (ss_req, method, sp, info, set_ip ? &tls->restore_state.ctx : &tls->context.ctx, tls, step_to_catch, frames, nframes);
5755 free_frames (frames, nframes);
5761 ss_destroy (SingleStepReq *req)
5764 g_assert (ss_req == req);
5773 ss_clear_for_assembly (SingleStepReq *req, MonoAssembly *assembly)
5776 gboolean found = TRUE;
5780 for (l = ss_req->bps; l; l = l->next) {
5781 if (breakpoint_matches_assembly ((MonoBreakpoint *)l->data, assembly)) {
5782 clear_breakpoint ((MonoBreakpoint *)l->data);
5783 ss_req->bps = g_slist_delete_link (ss_req->bps, l);
5792 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5795 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5802 if (!agent_config.enabled)
5805 mono_loader_lock ();
5806 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5807 mono_loader_unlock ();
5812 ei.category = mono_string_to_utf8_checked (category, &error);
5813 mono_error_cleanup (&error);
5817 ei.message = mono_string_to_utf8_checked (message, &error);
5818 mono_error_cleanup (&error);
5821 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5823 g_free (ei.category);
5824 g_free (ei.message);
5828 mono_debugger_agent_debug_log_is_enabled (void)
5830 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5831 return agent_config.enabled;
5834 #if defined(PLATFORM_ANDROID) || defined(TARGET_ANDROID)
5836 mono_debugger_agent_unhandled_exception (MonoException *exc)
5845 memset (&ei, 0, sizeof (EventInfo));
5846 ei.exc = (MonoObject*)exc;
5848 mono_loader_lock ();
5849 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5850 mono_loader_unlock ();
5852 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5857 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5858 MonoContext *catch_ctx)
5860 int i, j, suspend_policy;
5862 MonoJitInfo *ji, *catch_ji;
5864 DebuggerTlsData *tls = NULL;
5866 if (thread_to_tls != NULL) {
5867 MonoInternalThread *thread = mono_thread_internal_current ();
5869 mono_loader_lock ();
5870 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5871 mono_loader_unlock ();
5873 if (tls && tls->abort_requested)
5875 if (tls && tls->disable_breakpoints)
5879 memset (&ei, 0, sizeof (EventInfo));
5881 /* Just-In-Time debugging */
5883 if (agent_config.onuncaught && !inited) {
5884 finish_agent_init (FALSE);
5887 * Send an unsolicited EXCEPTION event with a dummy request id.
5889 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5890 ei.exc = (MonoObject*)exc;
5891 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5894 } else if (agent_config.onthrow && !inited) {
5896 gboolean found = FALSE;
5898 for (l = agent_config.onthrow; l; l = l->next) {
5899 char *ex_type = (char *)l->data;
5900 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5902 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5909 finish_agent_init (FALSE);
5912 * Send an unsolicited EXCEPTION event with a dummy request id.
5914 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5915 ei.exc = (MonoObject*)exc;
5916 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5924 ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5926 catch_ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5930 ei.exc = (MonoObject*)exc;
5931 ei.caught = catch_ctx != NULL;
5933 mono_loader_lock ();
5935 /* Treat exceptions which are caught in non-user code as unhandled */
5936 for (i = 0; i < event_requests->len; ++i) {
5937 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
5938 if (req->event_kind != EVENT_KIND_EXCEPTION)
5941 for (j = 0; j < req->nmodifiers; ++j) {
5942 Modifier *mod = &req->modifiers [j];
5944 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5946 gboolean found = FALSE;
5947 MonoAssembly **assemblies = mod->data.assemblies;
5950 for (k = 0; assemblies [k]; ++k)
5951 if (assemblies [k] == jinfo_get_method (catch_ji)->klass->image->assembly)
5960 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5961 mono_loader_unlock ();
5963 if (tls && ei.caught && catch_ctx) {
5964 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5965 tls->catch_state.ctx = *catch_ctx;
5966 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5967 tls->catch_state.valid = TRUE;
5970 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5973 tls->catch_state.valid = FALSE;
5977 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5979 DebuggerTlsData *tls;
5984 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5989 * We're about to invoke an exception filter during the first pass of exception handling.
5991 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5992 * 'orig_ctx' is the context where the exception has been thrown.
5995 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5997 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5998 * the call site (line 37) and then continue to Main(), but it would never
5999 * include the throw site (line 32).
6001 * Since exception filters are invoked during the first pass of exception handling,
6002 * the stack frames of the throw site are still intact, so we should include them
6005 * We do this here by saving the context of the throw site in 'tls->filter_state'.
6007 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
6008 * but report the location of the 'throw' to the user.
6012 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
6016 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
6018 DebuggerTlsData *tls;
6023 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
6027 tls->filter_state.valid = FALSE;
6031 * buffer_add_value_full:
6033 * Add the encoding of the value at ADDR described by T to the buffer.
6034 * AS_VTYPE determines whenever to treat primitive types as primitive types or
6038 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
6039 gboolean as_vtype, GHashTable *parent_vtypes)
6042 gboolean boxed_vtype = FALSE;
6045 if (!(*(void**)addr)) {
6046 /* This can happen with compiler generated locals */
6047 //printf ("%s\n", mono_type_full_name (t));
6048 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
6051 g_assert (*(void**)addr);
6052 addr = *(void**)addr;
6057 case MONO_TYPE_BOOLEAN:
6060 case MONO_TYPE_CHAR:
6080 case MONO_TYPE_VOID:
6081 buffer_add_byte (buf, t->type);
6083 case MONO_TYPE_BOOLEAN:
6086 buffer_add_byte (buf, t->type);
6087 buffer_add_int (buf, *(gint8*)addr);
6089 case MONO_TYPE_CHAR:
6092 buffer_add_byte (buf, t->type);
6093 buffer_add_int (buf, *(gint16*)addr);
6098 buffer_add_byte (buf, t->type);
6099 buffer_add_int (buf, *(gint32*)addr);
6104 buffer_add_byte (buf, t->type);
6105 buffer_add_long (buf, *(gint64*)addr);
6109 /* Treat it as a vtype */
6111 case MONO_TYPE_PTR: {
6112 gssize val = *(gssize*)addr;
6114 buffer_add_byte (buf, t->type);
6115 buffer_add_long (buf, val);
6119 case MONO_TYPE_STRING:
6120 case MONO_TYPE_SZARRAY:
6121 case MONO_TYPE_OBJECT:
6122 case MONO_TYPE_CLASS:
6123 case MONO_TYPE_ARRAY:
6124 obj = *(MonoObject**)addr;
6127 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
6129 if (obj->vtable->klass->valuetype) {
6130 t = &obj->vtable->klass->byval_arg;
6131 addr = mono_object_unbox (obj);
6134 } else if (obj->vtable->klass->rank) {
6135 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
6136 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
6137 buffer_add_byte (buf, MONO_TYPE_CLASS);
6139 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
6141 buffer_add_objid (buf, obj);
6145 case MONO_TYPE_VALUETYPE:
6146 case MONO_TYPE_TYPEDBYREF: {
6150 MonoClass *klass = mono_class_from_mono_type (t);
6155 * Handle boxed vtypes recursively referencing themselves using fields.
6158 parent_vtypes = g_hash_table_new (NULL, NULL);
6159 vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
6161 if (CHECK_PROTOCOL_VERSION (2, 33)) {
6162 buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
6163 buffer_add_int (buf, vtype_index - 1);
6165 /* The client can't handle PARENT_VTYPE */
6166 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
6170 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
6174 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
6175 buffer_add_byte (buf, klass->enumtype);
6176 buffer_add_typeid (buf, domain, klass);
6180 while ((f = mono_class_get_fields (klass, &iter))) {
6181 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6183 if (mono_field_is_deleted (f))
6187 buffer_add_int (buf, nfields);
6190 while ((f = mono_class_get_fields (klass, &iter))) {
6191 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6193 if (mono_field_is_deleted (f))
6195 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE, parent_vtypes);
6199 g_hash_table_remove (parent_vtypes, addr);
6200 if (g_hash_table_size (parent_vtypes) == 0) {
6201 g_hash_table_destroy (parent_vtypes);
6202 parent_vtypes = NULL;
6207 case MONO_TYPE_GENERICINST:
6208 if (mono_type_generic_inst_is_valuetype (t)) {
6220 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
6222 buffer_add_value_full (buf, t, addr, domain, FALSE, NULL);
6226 obj_is_of_type (MonoObject *obj, MonoType *t)
6228 MonoClass *klass = obj->vtable->klass;
6229 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
6230 if (mono_class_is_transparent_proxy (klass)) {
6231 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
6232 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
6242 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
6245 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6251 gpointer iter = NULL;
6255 is_enum = decode_byte (buf, &buf, limit);
6256 /* Enums are sent as a normal vtype */
6258 return ERR_NOT_IMPLEMENTED;
6259 klass = decode_typeid (buf, &buf, limit, &d, &err);
6260 if (err != ERR_NONE)
6263 if (t && klass != mono_class_from_mono_type (t)) {
6264 char *name = mono_type_full_name (t);
6265 char *name2 = mono_type_full_name (&klass->byval_arg);
6266 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got %s.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, name2);
6269 return ERR_INVALID_ARGUMENT;
6272 nfields = decode_int (buf, &buf, limit);
6273 while ((f = mono_class_get_fields (klass, &iter))) {
6274 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6276 if (mono_field_is_deleted (f))
6278 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
6279 if (err != ERR_NONE)
6283 g_assert (nfields == 0);
6291 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6295 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
6296 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
6297 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
6298 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
6299 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE) &&
6300 !(t->type == MONO_TYPE_VALUETYPE && type == MONO_TYPE_OBJECT)) {
6301 char *name = mono_type_full_name (t);
6302 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
6304 return ERR_INVALID_ARGUMENT;
6308 case MONO_TYPE_BOOLEAN:
6309 *(guint8*)addr = decode_int (buf, &buf, limit);
6311 case MONO_TYPE_CHAR:
6312 *(gunichar2*)addr = decode_int (buf, &buf, limit);
6315 *(gint8*)addr = decode_int (buf, &buf, limit);
6318 *(guint8*)addr = decode_int (buf, &buf, limit);
6321 *(gint16*)addr = decode_int (buf, &buf, limit);
6324 *(guint16*)addr = decode_int (buf, &buf, limit);
6327 *(gint32*)addr = decode_int (buf, &buf, limit);
6330 *(guint32*)addr = decode_int (buf, &buf, limit);
6333 *(gint64*)addr = decode_long (buf, &buf, limit);
6336 *(guint64*)addr = decode_long (buf, &buf, limit);
6339 *(guint32*)addr = decode_int (buf, &buf, limit);
6342 *(guint64*)addr = decode_long (buf, &buf, limit);
6345 /* We send these as I8, so we get them back as such */
6346 g_assert (type == MONO_TYPE_I8);
6347 *(gssize*)addr = decode_long (buf, &buf, limit);
6349 case MONO_TYPE_GENERICINST:
6350 if (MONO_TYPE_ISSTRUCT (t)) {
6351 /* The client sends these as a valuetype */
6359 /* We send these as vtypes, so we get them back as such */
6360 g_assert (type == MONO_TYPE_VALUETYPE);
6363 case MONO_TYPE_VALUETYPE:
6364 if (type == MONO_TYPE_OBJECT) {
6366 int objid = decode_objid (buf, &buf, limit);
6370 err = get_object (objid, (MonoObject**)&obj);
6371 if (err != ERR_NONE)
6374 return ERR_INVALID_ARGUMENT;
6375 if (obj->vtable->klass != mono_class_from_mono_type (t)) {
6376 DEBUG_PRINTF (1, "Expected type '%s', got object '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6377 return ERR_INVALID_ARGUMENT;
6379 memcpy (addr, mono_object_unbox (obj), mono_class_value_size (obj->vtable->klass, NULL));
6381 err = decode_vtype (t, domain, addr, buf, &buf, limit);
6382 if (err != ERR_NONE)
6388 if (MONO_TYPE_IS_REFERENCE (t)) {
6389 if (type == MONO_TYPE_OBJECT) {
6390 int objid = decode_objid (buf, &buf, limit);
6394 err = get_object (objid, (MonoObject**)&obj);
6395 if (err != ERR_NONE)
6399 if (!obj_is_of_type (obj, t)) {
6400 DEBUG_PRINTF (1, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6401 return ERR_INVALID_ARGUMENT;
6404 if (obj && obj->vtable->domain != domain)
6405 return ERR_INVALID_ARGUMENT;
6407 mono_gc_wbarrier_generic_store (addr, obj);
6408 } else if (type == VALUE_TYPE_ID_NULL) {
6409 *(MonoObject**)addr = NULL;
6410 } else if (type == MONO_TYPE_VALUETYPE) {
6419 /* This can happen when round-tripping boxed vtypes */
6421 * Obtain vtype class.
6422 * Same as the beginning of the handle_vtype case above.
6425 is_enum = decode_byte (buf, &buf, limit);
6427 return ERR_NOT_IMPLEMENTED;
6428 klass = decode_typeid (buf, &buf, limit, &d, &err);
6429 if (err != ERR_NONE)
6432 /* Decode the vtype into a temporary buffer, then box it. */
6433 vtype_buf_size = mono_class_value_size (klass, NULL);
6434 vtype_buf = (guint8 *)g_malloc0 (vtype_buf_size);
6435 g_assert (vtype_buf);
6438 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
6439 if (err != ERR_NONE) {
6443 *(MonoObject**)addr = mono_value_box_checked (d, klass, vtype_buf, &error);
6444 mono_error_cleanup (&error);
6447 char *name = mono_type_full_name (t);
6448 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
6450 return ERR_INVALID_ARGUMENT;
6464 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6468 int type = decode_byte (buf, &buf, limit);
6470 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
6471 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
6472 guint8 *nullable_buf;
6475 * First try decoding it as a Nullable`1
6477 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6478 if (err == ERR_NONE)
6482 * Then try decoding as a primitive value or null.
6484 if (targ->type == type) {
6485 nullable_buf = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
6486 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
6487 if (err != ERR_NONE) {
6488 g_free (nullable_buf);
6491 MonoObject *boxed = mono_value_box_checked (domain, mono_class_from_mono_type (targ), nullable_buf, &error);
6492 if (!is_ok (&error)) {
6493 mono_error_cleanup (&error);
6494 return ERR_INVALID_OBJECT;
6496 mono_nullable_init (addr, boxed, mono_class_from_mono_type (t));
6497 g_free (nullable_buf);
6500 } else if (type == VALUE_TYPE_ID_NULL) {
6501 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
6507 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6511 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
6515 guint8 *addr, *gaddr;
6518 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6519 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6522 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
6523 reg_val = mono_arch_context_get_int_reg (ctx, reg);
6525 buffer_add_value_full (buf, t, ®_val, domain, as_vtype, NULL);
6527 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6528 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6529 addr += (gint32)var->offset;
6531 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6533 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6535 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6538 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6539 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
6540 /* Same as regoffset, but with an indirection */
6541 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6542 addr += (gint32)var->offset;
6544 gaddr = (guint8 *)*(gpointer*)addr;
6546 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL);
6548 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
6549 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
6550 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
6551 MonoGSharedVtMethodRuntimeInfo *info;
6557 g_assert (info_var);
6558 g_assert (locals_var);
6560 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6561 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6562 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6563 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6564 addr += (gint32)info_var->offset;
6565 info = (MonoGSharedVtMethodRuntimeInfo *)*(gpointer*)addr;
6566 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6567 info = (MonoGSharedVtMethodRuntimeInfo *)mono_arch_context_get_int_reg (ctx, reg);
6569 g_assert_not_reached ();
6573 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6574 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6575 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6576 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6577 addr += (gint32)locals_var->offset;
6578 locals = (guint8 *)*(gpointer*)addr;
6579 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6580 locals = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6582 g_assert_not_reached ();
6586 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6588 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6593 g_assert_not_reached ();
6598 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
6602 guint8 *addr, *gaddr;
6604 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6605 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6607 if (MONO_TYPE_IS_REFERENCE (t))
6608 size = sizeof (gpointer);
6610 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6613 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6614 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6616 gboolean is_signed = FALSE;
6619 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6622 // FIXME: Write barriers
6623 mono_gc_memmove_atomic (addr, val, size);
6628 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6633 v = is_signed ? *(gint8*)val : *(guint8*)val;
6636 v = is_signed ? *(gint16*)val : *(guint16*)val;
6639 v = is_signed ? *(gint32*)val : *(guint32*)val;
6642 v = is_signed ? *(gint64*)val : *(guint64*)val;
6645 g_assert_not_reached ();
6648 /* Set value on the stack or in the return ctx */
6649 if (reg_locations [reg]) {
6650 /* Saved on the stack */
6651 DEBUG_PRINTF (1, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v);
6652 *(reg_locations [reg]) = v;
6655 DEBUG_PRINTF (1, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v);
6656 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6659 // FIXME: Move these to mono-context.h/c.
6660 mono_arch_context_set_int_reg (ctx, reg, v);
6662 // FIXME: Can't set registers, so we disable linears
6667 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6668 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6669 addr += (gint32)var->offset;
6671 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6674 addr = *(guint8**)addr;
6680 // FIXME: Write barriers
6681 mono_gc_memmove_atomic (addr, val, size);
6683 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6684 /* Same as regoffset, but with an indirection */
6685 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6686 addr += (gint32)var->offset;
6688 gaddr = (guint8 *)*(gpointer*)addr;
6690 // FIXME: Write barriers
6691 mono_gc_memmove_atomic (gaddr, val, size);
6693 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6697 g_assert_not_reached ();
6702 clear_event_request (int req_id, int etype)
6706 mono_loader_lock ();
6707 for (i = 0; i < event_requests->len; ++i) {
6708 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6710 if (req->id == req_id && req->event_kind == etype) {
6711 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6712 clear_breakpoint ((MonoBreakpoint *)req->info);
6713 if (req->event_kind == EVENT_KIND_STEP)
6714 ss_destroy ((SingleStepReq *)req->info);
6715 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6716 clear_breakpoint ((MonoBreakpoint *)req->info);
6717 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6718 clear_breakpoint ((MonoBreakpoint *)req->info);
6719 g_ptr_array_remove_index_fast (event_requests, i);
6724 mono_loader_unlock ();
6728 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
6732 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6733 m->kind = MOD_KIND_NONE;
6734 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6735 int count = 0, match_count = 0, pos;
6736 MonoAssembly **newassemblies;
6738 for (i = 0; m->data.assemblies [i]; ++i) {
6740 if (m->data.assemblies [i] == assembly)
6745 // +1 because we don't know length and we use last element to check for end
6746 newassemblies = g_new0 (MonoAssembly*, count - match_count + 1);
6749 for (i = 0; i < count; ++i)
6750 if (m->data.assemblies [i] != assembly)
6751 newassemblies [pos ++] = m->data.assemblies [i];
6752 g_assert (pos == count - match_count);
6753 g_free (m->data.assemblies);
6754 m->data.assemblies = newassemblies;
6760 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
6764 for (i = 0; i < req->nmodifiers; ++i) {
6765 Modifier *m = &req->modifiers [i];
6767 clear_assembly_from_modifier (req, m, assembly);
6772 * clear_event_requests_for_assembly:
6774 * Clear all events requests which reference ASSEMBLY.
6777 clear_event_requests_for_assembly (MonoAssembly *assembly)
6782 mono_loader_lock ();
6786 for (i = 0; i < event_requests->len; ++i) {
6787 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6789 clear_assembly_from_modifiers (req, assembly);
6791 if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly ((MonoBreakpoint *)req->info, assembly)) {
6792 clear_event_request (req->id, req->event_kind);
6797 if (req->event_kind == EVENT_KIND_STEP)
6798 ss_clear_for_assembly ((SingleStepReq *)req->info, assembly);
6801 mono_loader_unlock ();
6805 * type_comes_from_assembly:
6807 * GHRFunc that returns TRUE if klass comes from assembly
6810 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6812 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6816 * clear_types_for_assembly:
6818 * Clears types from loaded_classes for a given assembly
6821 clear_types_for_assembly (MonoAssembly *assembly)
6823 MonoDomain *domain = mono_domain_get ();
6824 AgentDomainInfo *info = NULL;
6826 if (!domain || !domain_jit_info (domain))
6827 /* Can happen during shutdown */
6830 info = get_agent_domain_info (domain);
6832 mono_loader_lock ();
6833 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6834 mono_loader_unlock ();
6838 add_thread (gpointer key, gpointer value, gpointer user_data)
6840 MonoInternalThread *thread = (MonoInternalThread *)value;
6841 Buffer *buf = (Buffer *)user_data;
6843 buffer_add_objid (buf, (MonoObject*)thread);
6847 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6850 guint8 *end = invoke->endp;
6854 MonoMethodSignature *sig;
6857 MonoObject *this_arg, *res, *exc;
6860 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6863 MonoStopwatch watch;
6865 if (invoke->method) {
6867 * Invoke this method directly, currently only Environment.Exit () is supported.
6870 DEBUG_PRINTF (1, "[%p] Invoking method '%s' on receiver '%s'.\n", (gpointer) (gsize) mono_native_thread_id_get (), mono_method_full_name (invoke->method, TRUE), this_arg ? this_arg->vtable->klass->name : "<null>");
6872 mono_runtime_try_invoke (invoke->method, NULL, invoke->args, &exc, &error);
6873 mono_error_assert_ok (&error);
6875 g_assert_not_reached ();
6878 m = decode_methodid (p, &p, end, &domain, &err);
6879 if (err != ERR_NONE)
6881 sig = mono_method_signature (m);
6883 if (m->klass->valuetype)
6884 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6886 this_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
6887 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6888 /* Should be null */
6889 int type = decode_byte (p, &p, end);
6890 if (type != VALUE_TYPE_ID_NULL) {
6891 DEBUG_PRINTF (1, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6892 return ERR_INVALID_ARGUMENT;
6894 memset (this_buf, 0, mono_class_instance_size (m->klass));
6895 } else if (m->klass->valuetype && !strcmp (m->name, ".ctor")) {
6899 int type = decode_byte (p, &tmp_p, end);
6900 if (type == VALUE_TYPE_ID_NULL) {
6901 memset (this_buf, 0, mono_class_instance_size (m->klass));
6904 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6905 if (err != ERR_NONE)
6909 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6910 if (err != ERR_NONE)
6914 if (!m->klass->valuetype)
6915 this_arg = *(MonoObject**)this_buf;
6919 if (MONO_CLASS_IS_INTERFACE (m->klass)) {
6921 DEBUG_PRINTF (1, "[%p] Error: Interface method invoked without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6922 return ERR_INVALID_ARGUMENT;
6924 m = mono_object_get_virtual_method (this_arg, m);
6925 /* Transform this to the format the rest of the code expects it to be */
6926 if (m->klass->valuetype) {
6927 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6928 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
6930 } else if ((m->flags & METHOD_ATTRIBUTE_VIRTUAL) && !m->klass->valuetype && invoke->flags & INVOKE_FLAG_VIRTUAL) {
6932 DEBUG_PRINTF (1, "[%p] Error: invoke with INVOKE_FLAG_VIRTUAL flag set without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6933 return ERR_INVALID_ARGUMENT;
6935 m = mono_object_get_virtual_method (this_arg, m);
6936 if (m->klass->valuetype) {
6937 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6938 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
6942 DEBUG_PRINTF (1, "[%p] Invoking method '%s' on receiver '%s'.\n", (gpointer) (gsize) mono_native_thread_id_get (), mono_method_full_name (m, TRUE), this_arg ? this_arg->vtable->klass->name : "<null>");
6944 if (this_arg && this_arg->vtable->domain != domain)
6947 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this_arg) {
6948 if (!strcmp (m->name, ".ctor")) {
6949 if (mono_class_is_abstract (m->klass))
6950 return ERR_INVALID_ARGUMENT;
6953 this_arg = mono_object_new_checked (domain, m->klass, &error);
6954 mono_error_assert_ok (&error);
6957 return ERR_INVALID_ARGUMENT;
6961 if (this_arg && !obj_is_of_type (this_arg, &m->klass->byval_arg))
6962 return ERR_INVALID_ARGUMENT;
6964 nargs = decode_int (p, &p, end);
6965 if (nargs != sig->param_count)
6966 return ERR_INVALID_ARGUMENT;
6967 /* Use alloca to get gc tracking */
6968 arg_buf = (guint8 **)g_alloca (nargs * sizeof (gpointer));
6969 memset (arg_buf, 0, nargs * sizeof (gpointer));
6970 args = (gpointer *)g_alloca (nargs * sizeof (gpointer));
6971 for (i = 0; i < nargs; ++i) {
6972 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6973 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6974 if (err != ERR_NONE)
6976 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6979 if (sig->params [i]->byref) {
6980 arg_buf [i] = (guint8 *)g_alloca (sizeof (mgreg_t));
6981 *(gpointer*)arg_buf [i] = args [i];
6982 args [i] = arg_buf [i];
6985 arg_buf [i] = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6986 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6987 if (err != ERR_NONE)
6989 args [i] = arg_buf [i];
6996 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6997 tls->disable_breakpoints = TRUE;
6999 tls->disable_breakpoints = FALSE;
7002 * Add an LMF frame to link the stack frames on the invoke method with our caller.
7004 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
7005 if (invoke->has_ctx) {
7008 lmf_addr = mono_get_lmf_addr ();
7011 memset (&ext, 0, sizeof (ext));
7012 mono_arch_init_lmf_ext (&ext, *lmf_addr);
7014 ext.debugger_invoke = TRUE;
7015 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
7017 mono_set_lmf ((MonoLMF*)&ext);
7021 mono_stopwatch_start (&watch);
7022 res = mono_runtime_try_invoke (m, m->klass->valuetype ? (gpointer) this_buf : (gpointer) this_arg, args, &exc, &error);
7023 if (exc == NULL && !mono_error_ok (&error)) {
7024 exc = (MonoObject*) mono_error_convert_to_exception (&error);
7026 mono_error_cleanup (&error); /* FIXME report error */
7028 mono_stopwatch_stop (&watch);
7029 DEBUG_PRINTF (1, "[%p] Invoke result: %p, exc: %s, time: %ld ms.\n", (gpointer) (gsize) mono_native_thread_id_get (), res, exc ? exc->vtable->klass->name : NULL, (long)mono_stopwatch_elapsed_ms (&watch));
7031 buffer_add_byte (buf, 0);
7032 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
7034 gboolean out_this = FALSE;
7035 gboolean out_args = FALSE;
7037 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_THIS) && CHECK_PROTOCOL_VERSION (2, 35))
7039 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_ARGS) && CHECK_PROTOCOL_VERSION (2, 35))
7041 buffer_add_byte (buf, 1 + (out_this ? 2 : 0) + (out_args ? 4 : 0));
7042 if (sig->ret->type == MONO_TYPE_VOID) {
7043 if (!strcmp (m->name, ".ctor")) {
7044 if (!m->klass->valuetype)
7045 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this_arg, domain);
7047 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
7049 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
7051 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
7052 buffer_add_value (buf, sig->ret, &res, domain);
7053 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
7054 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
7055 MonoClass *k = mono_class_from_mono_type (sig->ret);
7056 guint8 *nullable_buf = (guint8 *)g_alloca (mono_class_value_size (k, NULL));
7058 g_assert (nullable_buf);
7059 mono_nullable_init (nullable_buf, res, k);
7060 buffer_add_value (buf, sig->ret, nullable_buf, domain);
7063 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
7069 /* Return the new value of the receiver after the call */
7070 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
7072 buffer_add_int (buf, nargs);
7073 for (i = 0; i < nargs; ++i) {
7074 if (MONO_TYPE_IS_REFERENCE (sig->params [i]))
7075 buffer_add_value (buf, sig->params [i], &args [i], domain);
7076 else if (sig->params [i]->byref)
7077 /* add_value () does an indirection */
7078 buffer_add_value (buf, sig->params [i], &arg_buf [i], domain);
7080 buffer_add_value (buf, sig->params [i], arg_buf [i], domain);
7085 tls->disable_breakpoints = FALSE;
7087 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
7088 if (invoke->has_ctx)
7089 mono_set_lmf ((MonoLMF *)(((gssize)ext.lmf.previous_lmf) & ~3));
7093 // FIXME: byref arguments
7101 * Invoke the method given by tls->pending_invoke in the current thread.
7104 invoke_method (void)
7106 DebuggerTlsData *tls;
7112 MonoContext restore_ctx;
7115 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
7119 * Store the `InvokeData *' in `tls->invoke' until we're done with
7120 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
7123 mono_loader_lock ();
7125 invoke = tls->pending_invoke;
7127 tls->pending_invoke = NULL;
7129 invoke->last_invoke = tls->invoke;
7130 tls->invoke = invoke;
7132 mono_loader_unlock ();
7134 tls->frames_up_to_date = FALSE;
7140 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
7141 buffer_init (&buf, 128);
7144 /* Fail the other invokes as well */
7146 err = do_invoke_method (tls, &buf, invoke, p, &p);
7149 if (tls->abort_requested) {
7150 if (CHECK_PROTOCOL_VERSION (2, 42))
7151 err = ERR_INVOKE_ABORTED;
7154 /* Start suspending before sending the reply */
7155 if (mindex == invoke->nmethods - 1) {
7156 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
7157 for (i = 0; i < invoke->suspend_count; ++i)
7162 send_reply_packet (id, err, &buf);
7167 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
7169 if (invoke->has_ctx)
7170 save_thread_context (&restore_ctx);
7172 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
7173 g_assert (tls->resume_count);
7174 tls->resume_count -= invoke->suspend_count;
7177 DEBUG_PRINTF (1, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer) (gsize) mono_native_thread_id_get (), err, tls->resume_count);
7180 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
7182 * It is possible that mono_thread_internal_abort () was called
7183 * after the mono_runtime_invoke_checked() already returned, but it doesn't matter
7184 * because we reset the abort here.
7187 mono_loader_lock ();
7189 if (tls->abort_requested)
7190 mono_thread_internal_reset_abort (tls->thread);
7192 tls->invoke = tls->invoke->last_invoke;
7193 tls->abort_requested = FALSE;
7195 mono_loader_unlock ();
7204 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
7206 MonoThread *thread = (MonoThread *)value;
7207 DebuggerTlsData *tls;
7210 mono_loader_lock ();
7211 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
7213 res = tls->really_suspended;
7214 mono_loader_unlock ();
7220 get_source_files_for_type (MonoClass *klass)
7222 gpointer iter = NULL;
7224 MonoDebugSourceInfo *sinfo;
7228 files = g_ptr_array_new ();
7230 while ((method = mono_class_get_methods (klass, &iter))) {
7231 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
7232 GPtrArray *source_file_list;
7235 mono_debug_get_seq_points (minfo, NULL, &source_file_list, NULL, NULL, NULL);
7236 for (j = 0; j < source_file_list->len; ++j) {
7237 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, j);
7238 for (i = 0; i < files->len; ++i)
7239 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
7241 if (i == files->len)
7242 g_ptr_array_add (files, g_strdup (sinfo->source_file));
7244 g_ptr_array_free (source_file_list, TRUE);
7252 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
7255 case CMD_VM_VERSION: {
7256 char *build_info, *version;
7258 build_info = mono_get_runtime_build_info ();
7259 version = g_strdup_printf ("mono %s", build_info);
7261 buffer_add_string (buf, version); /* vm version */
7262 buffer_add_int (buf, MAJOR_VERSION);
7263 buffer_add_int (buf, MINOR_VERSION);
7264 g_free (build_info);
7268 case CMD_VM_SET_PROTOCOL_VERSION: {
7269 major_version = decode_int (p, &p, end);
7270 minor_version = decode_int (p, &p, end);
7271 protocol_version_set = TRUE;
7272 DEBUG_PRINTF (1, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version);
7275 case CMD_VM_ALL_THREADS: {
7277 mono_loader_lock ();
7278 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
7279 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
7280 mono_loader_unlock ();
7283 case CMD_VM_SUSPEND:
7285 wait_for_suspend ();
7288 if (suspend_count == 0)
7289 return ERR_NOT_SUSPENDED;
7291 clear_suspended_objs ();
7293 case CMD_VM_DISPOSE:
7294 /* Clear all event requests */
7295 mono_loader_lock ();
7296 while (event_requests->len > 0) {
7297 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
7299 clear_event_request (req->id, req->event_kind);
7301 mono_loader_unlock ();
7303 while (suspend_count > 0)
7305 disconnected = TRUE;
7306 vm_start_event_sent = FALSE;
7309 MonoInternalThread *thread;
7310 DebuggerTlsData *tls;
7311 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7312 MonoClass *env_class;
7314 MonoMethod *exit_method = NULL;
7318 exit_code = decode_int (p, &p, end);
7320 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
7322 /* Have to send a reply before exiting */
7323 send_reply_packet (id, 0, buf);
7325 /* Clear all event requests */
7326 mono_loader_lock ();
7327 while (event_requests->len > 0) {
7328 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
7330 clear_event_request (req->id, req->event_kind);
7332 mono_loader_unlock ();
7335 * The JDWP documentation says that the shutdown is not orderly. It doesn't
7336 * specify whenever a VM_DEATH event is sent. We currently do an orderly
7337 * shutdown by hijacking a thread to execute Environment.Exit (). This is
7338 * better than doing the shutdown ourselves, since it avoids various races.
7342 wait_for_suspend ();
7344 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7345 env_class = mono_class_try_load_from_name (mono_defaults.corlib, "System", "Environment");
7347 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
7350 mono_loader_lock ();
7351 thread = (MonoInternalThread *)mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
7352 mono_loader_unlock ();
7354 if (thread && exit_method) {
7355 mono_loader_lock ();
7356 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
7357 mono_loader_unlock ();
7359 args = g_new0 (gpointer, 1);
7360 args [0] = g_malloc (sizeof (int));
7361 *(int*)(args [0]) = exit_code;
7363 tls->pending_invoke = g_new0 (InvokeData, 1);
7364 tls->pending_invoke->method = exit_method;
7365 tls->pending_invoke->args = args;
7366 tls->pending_invoke->nmethods = 1;
7368 while (suspend_count > 0)
7372 * No thread found, do it ourselves.
7373 * FIXME: This can race with normal shutdown etc.
7375 while (suspend_count > 0)
7378 if (!mono_runtime_try_shutdown ())
7381 mono_environment_exitcode_set (exit_code);
7383 /* Suspend all managed threads since the runtime is going away */
7384 DEBUG_PRINTF (1, "Suspending all threads...\n");
7385 mono_thread_suspend_all_other_threads ();
7386 DEBUG_PRINTF (1, "Shutting down the runtime...\n");
7387 mono_runtime_quit ();
7388 transport_close2 ();
7389 DEBUG_PRINTF (1, "Exiting...\n");
7395 case CMD_VM_INVOKE_METHOD:
7396 case CMD_VM_INVOKE_METHODS: {
7397 int objid = decode_objid (p, &p, end);
7399 DebuggerTlsData *tls;
7400 int i, count, flags, nmethods;
7403 err = get_object (objid, (MonoObject**)&thread);
7404 if (err != ERR_NONE)
7407 flags = decode_int (p, &p, end);
7409 if (command == CMD_VM_INVOKE_METHODS)
7410 nmethods = decode_int (p, &p, end);
7414 // Wait for suspending if it already started
7416 wait_for_suspend ();
7417 if (!is_suspended ())
7418 return ERR_NOT_SUSPENDED;
7420 mono_loader_lock ();
7421 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7422 mono_loader_unlock ();
7425 if (!tls->really_suspended)
7426 /* The thread is still running native code, can't do invokes */
7427 return ERR_NOT_SUSPENDED;
7430 * Store the invoke data into tls, the thread will execute it after it is
7433 if (tls->pending_invoke)
7434 return ERR_NOT_SUSPENDED;
7435 tls->pending_invoke = g_new0 (InvokeData, 1);
7436 tls->pending_invoke->id = id;
7437 tls->pending_invoke->flags = flags;
7438 tls->pending_invoke->p = (guint8 *)g_malloc (end - p);
7439 memcpy (tls->pending_invoke->p, p, end - p);
7440 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
7441 tls->pending_invoke->suspend_count = suspend_count;
7442 tls->pending_invoke->nmethods = nmethods;
7444 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
7445 resume_thread (THREAD_TO_INTERNAL (thread));
7448 count = suspend_count;
7449 for (i = 0; i < count; ++i)
7454 case CMD_VM_ABORT_INVOKE: {
7455 int objid = decode_objid (p, &p, end);
7457 DebuggerTlsData *tls;
7461 err = get_object (objid, (MonoObject**)&thread);
7462 if (err != ERR_NONE)
7465 invoke_id = decode_int (p, &p, end);
7467 mono_loader_lock ();
7468 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7471 if (tls->abort_requested) {
7472 DEBUG_PRINTF (1, "Abort already requested.\n");
7473 mono_loader_unlock ();
7478 * Check whether we're still inside the mono_runtime_invoke_checked() and that it's
7479 * actually the correct invocation.
7481 * Careful, we do not stop the thread that's doing the invocation, so we can't
7482 * inspect its stack. However, invoke_method() also acquires the loader lock
7483 * when it's done, so we're safe here.
7487 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
7488 mono_loader_unlock ();
7489 return ERR_NO_INVOCATION;
7492 tls->abort_requested = TRUE;
7494 mono_thread_internal_abort (THREAD_TO_INTERNAL (thread));
7495 mono_loader_unlock ();
7499 case CMD_VM_SET_KEEPALIVE: {
7500 int timeout = decode_int (p, &p, end);
7501 agent_config.keepalive = timeout;
7503 #ifndef DISABLE_SOCKET_TRANSPORT
7510 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
7511 GHashTableIter iter, kiter;
7516 char *fname, *basename;
7517 gboolean ignore_case;
7518 GSList *class_list, *l;
7519 GPtrArray *res_classes, *res_domains;
7521 fname = decode_string (p, &p, end);
7522 ignore_case = decode_byte (p, &p, end);
7524 basename = dbg_path_get_basename (fname);
7526 res_classes = g_ptr_array_new ();
7527 res_domains = g_ptr_array_new ();
7529 mono_loader_lock ();
7530 g_hash_table_iter_init (&iter, domains);
7531 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7532 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
7534 /* Update 'source_file_to_class' cache */
7535 g_hash_table_iter_init (&kiter, info->loaded_classes);
7536 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
7537 if (!g_hash_table_lookup (info->source_files, klass)) {
7538 files = get_source_files_for_type (klass);
7539 g_hash_table_insert (info->source_files, klass, files);
7541 for (i = 0; i < files->len; ++i) {
7542 char *s = (char *)g_ptr_array_index (files, i);
7543 char *s2 = dbg_path_get_basename (s);
7546 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, s2);
7548 class_list = g_slist_prepend (class_list, klass);
7549 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
7551 class_list = g_slist_prepend (class_list, klass);
7552 g_hash_table_insert (info->source_file_to_class, s2, class_list);
7555 /* The _ignorecase hash contains the lowercase path */
7556 s3 = strdup_tolower (s2);
7557 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
7559 class_list = g_slist_prepend (class_list, klass);
7560 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
7562 class_list = g_slist_prepend (class_list, klass);
7563 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
7575 s = strdup_tolower (basename);
7576 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
7579 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, basename);
7582 for (l = class_list; l; l = l->next) {
7583 klass = (MonoClass *)l->data;
7585 g_ptr_array_add (res_classes, klass);
7586 g_ptr_array_add (res_domains, domain);
7589 mono_loader_unlock ();
7594 buffer_add_int (buf, res_classes->len);
7595 for (i = 0; i < res_classes->len; ++i)
7596 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7597 g_ptr_array_free (res_classes, TRUE);
7598 g_ptr_array_free (res_domains, TRUE);
7601 case CMD_VM_GET_TYPES: {
7602 GHashTableIter iter;
7606 gboolean ignore_case;
7607 GPtrArray *res_classes, *res_domains;
7608 MonoTypeNameParse info;
7610 name = decode_string (p, &p, end);
7611 ignore_case = decode_byte (p, &p, end);
7613 if (!mono_reflection_parse_type (name, &info)) {
7615 mono_reflection_free_type_info (&info);
7616 return ERR_INVALID_ARGUMENT;
7619 res_classes = g_ptr_array_new ();
7620 res_domains = g_ptr_array_new ();
7622 mono_loader_lock ();
7623 g_hash_table_iter_init (&iter, domains);
7624 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7626 gboolean type_resolve;
7630 mono_domain_assemblies_lock (domain);
7631 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7632 ass = (MonoAssembly *)tmp->data;
7636 type_resolve = TRUE;
7637 /* FIXME really okay to call while holding locks? */
7638 t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignore_case, &type_resolve, &error);
7639 mono_error_cleanup (&error);
7641 g_ptr_array_add (res_classes, mono_type_get_class (t));
7642 g_ptr_array_add (res_domains, domain);
7646 mono_domain_assemblies_unlock (domain);
7648 mono_loader_unlock ();
7651 mono_reflection_free_type_info (&info);
7653 buffer_add_int (buf, res_classes->len);
7654 for (i = 0; i < res_classes->len; ++i)
7655 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7656 g_ptr_array_free (res_classes, TRUE);
7657 g_ptr_array_free (res_domains, TRUE);
7660 case CMD_VM_START_BUFFERING:
7661 case CMD_VM_STOP_BUFFERING:
7662 /* Handled in the main loop */
7665 return ERR_NOT_IMPLEMENTED;
7672 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7678 case CMD_EVENT_REQUEST_SET: {
7680 int i, event_kind, suspend_policy, nmodifiers;
7684 MonoThread *step_thread;
7685 int step_thread_id = 0;
7686 StepDepth depth = STEP_DEPTH_INTO;
7687 StepSize size = STEP_SIZE_MIN;
7688 StepFilter filter = STEP_FILTER_NONE;
7692 event_kind = decode_byte (p, &p, end);
7693 suspend_policy = decode_byte (p, &p, end);
7694 nmodifiers = decode_byte (p, &p, end);
7696 req = (EventRequest *)g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7697 req->id = InterlockedIncrement (&event_request_id);
7698 req->event_kind = event_kind;
7699 req->suspend_policy = suspend_policy;
7700 req->nmodifiers = nmodifiers;
7703 for (i = 0; i < nmodifiers; ++i) {
7704 mod = (ModifierKind)decode_byte (p, &p, end);
7706 req->modifiers [i].kind = mod;
7707 if (mod == MOD_KIND_COUNT) {
7708 req->modifiers [i].data.count = decode_int (p, &p, end);
7709 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7710 method = decode_methodid (p, &p, end, &domain, &err);
7711 if (err != ERR_NONE)
7713 location = decode_long (p, &p, end);
7714 } else if (mod == MOD_KIND_STEP) {
7715 step_thread_id = decode_id (p, &p, end);
7716 size = (StepSize)decode_int (p, &p, end);
7717 depth = (StepDepth)decode_int (p, &p, end);
7718 if (CHECK_PROTOCOL_VERSION (2, 16))
7719 filter = (StepFilter)decode_int (p, &p, end);
7720 req->modifiers [i].data.filter = filter;
7721 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7722 /* Treat STEP_THOUGH the same as HIDDEN */
7723 req->modifiers [i].data.filter = (StepFilter)(req->modifiers [i].data.filter | STEP_FILTER_DEBUGGER_STEP_THROUGH);
7724 } else if (mod == MOD_KIND_THREAD_ONLY) {
7725 int id = decode_id (p, &p, end);
7727 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7728 if (err != ERR_NONE) {
7732 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7733 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7735 if (err != ERR_NONE)
7737 req->modifiers [i].caught = decode_byte (p, &p, end);
7738 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7739 if (CHECK_PROTOCOL_VERSION (2, 25))
7740 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7742 req->modifiers [i].subclasses = TRUE;
7743 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" : "");
7745 req->modifiers [i].data.exc_class = exc_class;
7747 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
7749 return ERR_INVALID_ARGUMENT;
7752 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7753 int n = decode_int (p, &p, end);
7756 // +1 because we don't know length and we use last element to check for end
7757 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n + 1);
7758 for (j = 0; j < n; ++j) {
7759 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7760 if (err != ERR_NONE) {
7761 g_free (req->modifiers [i].data.assemblies);
7765 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7766 int n = decode_int (p, &p, end);
7769 modifier = &req->modifiers [i];
7770 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7771 for (j = 0; j < n; ++j) {
7772 char *s = decode_string (p, &p, end);
7776 s2 = strdup_tolower (s);
7777 g_hash_table_insert (modifier->data.source_files, s2, s2);
7781 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7782 int n = decode_int (p, &p, end);
7785 modifier = &req->modifiers [i];
7786 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7787 for (j = 0; j < n; ++j) {
7788 char *s = decode_string (p, &p, end);
7791 g_hash_table_insert (modifier->data.type_names, s, s);
7795 return ERR_NOT_IMPLEMENTED;
7799 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7802 req->info = set_breakpoint (method, location, req, &error);
7803 if (!mono_error_ok (&error)) {
7805 DEBUG_PRINTF (1, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error));
7806 mono_error_cleanup (&error);
7807 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7809 } else if (req->event_kind == EVENT_KIND_STEP) {
7810 g_assert (step_thread_id);
7812 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7813 if (err != ERR_NONE) {
7818 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, filter, req);
7819 if (err != ERR_NONE) {
7823 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7824 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7825 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7826 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7827 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7828 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7830 if (req->nmodifiers) {
7832 return ERR_NOT_IMPLEMENTED;
7836 mono_loader_lock ();
7837 g_ptr_array_add (event_requests, req);
7839 if (agent_config.defer) {
7840 /* Transmit cached data to the client on receipt of the event request */
7841 switch (req->event_kind) {
7842 case EVENT_KIND_APPDOMAIN_CREATE:
7843 /* Emit load events for currently loaded domains */
7844 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7846 case EVENT_KIND_ASSEMBLY_LOAD:
7847 /* Emit load events for currently loaded assemblies */
7848 mono_domain_foreach (send_assemblies_for_domain, NULL);
7850 case EVENT_KIND_THREAD_START:
7851 /* Emit start events for currently started threads */
7852 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7854 case EVENT_KIND_TYPE_LOAD:
7855 /* Emit type load events for currently loaded types */
7856 mono_domain_foreach (send_types_for_domain, NULL);
7862 mono_loader_unlock ();
7864 buffer_add_int (buf, req->id);
7867 case CMD_EVENT_REQUEST_CLEAR: {
7868 int etype = decode_byte (p, &p, end);
7869 int req_id = decode_int (p, &p, end);
7871 // FIXME: Make a faster mapping from req_id to request
7872 mono_loader_lock ();
7873 clear_event_request (req_id, etype);
7874 mono_loader_unlock ();
7877 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7880 mono_loader_lock ();
7882 while (i < event_requests->len) {
7883 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
7885 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7886 clear_breakpoint ((MonoBreakpoint *)req->info);
7888 g_ptr_array_remove_index_fast (event_requests, i);
7894 mono_loader_unlock ();
7898 return ERR_NOT_IMPLEMENTED;
7905 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7911 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7912 buffer_add_domainid (buf, mono_get_root_domain ());
7915 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7916 domain = decode_domainid (p, &p, end, NULL, &err);
7917 if (err != ERR_NONE)
7919 buffer_add_string (buf, domain->friendly_name);
7922 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7927 domain = decode_domainid (p, &p, end, NULL, &err);
7928 if (err != ERR_NONE)
7930 mono_loader_lock ();
7932 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7935 buffer_add_int (buf, count);
7936 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7937 ass = (MonoAssembly *)tmp->data;
7938 buffer_add_assemblyid (buf, domain, ass);
7940 mono_loader_unlock ();
7943 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7944 domain = decode_domainid (p, &p, end, NULL, &err);
7945 if (err != ERR_NONE)
7948 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7951 case CMD_APPDOMAIN_GET_CORLIB: {
7952 domain = decode_domainid (p, &p, end, NULL, &err);
7953 if (err != ERR_NONE)
7956 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7959 case CMD_APPDOMAIN_CREATE_STRING: {
7963 domain = decode_domainid (p, &p, end, NULL, &err);
7964 if (err != ERR_NONE)
7966 s = decode_string (p, &p, end);
7968 o = mono_string_new (domain, s);
7969 buffer_add_objid (buf, (MonoObject*)o);
7972 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7975 MonoDomain *domain2;
7978 domain = decode_domainid (p, &p, end, NULL, &err);
7979 if (err != ERR_NONE)
7981 klass = decode_typeid (p, &p, end, &domain2, &err);
7982 if (err != ERR_NONE)
7986 g_assert (domain == domain2);
7988 o = mono_object_new_checked (domain, klass, &error);
7989 mono_error_assert_ok (&error);
7991 err = decode_value (&klass->byval_arg, domain, (guint8 *)mono_object_unbox (o), p, &p, end);
7992 if (err != ERR_NONE)
7995 buffer_add_objid (buf, o);
7999 return ERR_NOT_IMPLEMENTED;
8006 get_assembly_object_command (MonoDomain *domain, MonoAssembly *ass, Buffer *buf, MonoError *error)
8008 HANDLE_FUNCTION_ENTER();
8009 ErrorCode err = ERR_NONE;
8011 MonoReflectionAssemblyHandle o = mono_assembly_get_object_handle (domain, ass, error);
8012 if (MONO_HANDLE_IS_NULL (o)) {
8013 err = ERR_INVALID_OBJECT;
8016 buffer_add_objid (buf, MONO_HANDLE_RAW (MONO_HANDLE_CAST (MonoObject, o)));
8018 HANDLE_FUNCTION_RETURN_VAL (err);
8023 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8029 ass = decode_assemblyid (p, &p, end, &domain, &err);
8030 if (err != ERR_NONE)
8034 case CMD_ASSEMBLY_GET_LOCATION: {
8035 buffer_add_string (buf, mono_image_get_filename (ass->image));
8038 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
8042 if (ass->image->dynamic) {
8043 buffer_add_id (buf, 0);
8045 token = mono_image_get_entry_point (ass->image);
8047 buffer_add_id (buf, 0);
8050 m = mono_get_method_checked (ass->image, token, NULL, NULL, &error);
8052 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8053 buffer_add_methodid (buf, domain, m);
8058 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
8059 buffer_add_moduleid (buf, domain, ass->image);
8062 case CMD_ASSEMBLY_GET_OBJECT: {
8064 err = get_assembly_object_command (domain, ass, buf, &error);
8065 mono_error_cleanup (&error);
8068 case CMD_ASSEMBLY_GET_DOMAIN: {
8069 buffer_add_domainid (buf, domain);
8072 case CMD_ASSEMBLY_GET_TYPE: {
8074 char *s = decode_string (p, &p, end);
8075 gboolean ignorecase = decode_byte (p, &p, end);
8076 MonoTypeNameParse info;
8078 gboolean type_resolve, res;
8079 MonoDomain *d = mono_domain_get ();
8081 /* This is needed to be able to find referenced assemblies */
8082 res = mono_domain_set (domain, FALSE);
8085 if (!mono_reflection_parse_type (s, &info)) {
8088 if (info.assembly.name)
8090 t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignorecase, &type_resolve, &error);
8091 if (!is_ok (&error)) {
8092 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8093 mono_reflection_free_type_info (&info);
8095 return ERR_INVALID_ARGUMENT;
8098 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
8099 mono_reflection_free_type_info (&info);
8102 mono_domain_set (d, TRUE);
8106 case CMD_ASSEMBLY_GET_NAME: {
8108 MonoAssembly *mass = ass;
8110 name = g_strdup_printf (
8111 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
8113 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
8114 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
8115 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
8116 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
8118 buffer_add_string (buf, name);
8123 return ERR_NOT_IMPLEMENTED;
8130 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8136 case CMD_MODULE_GET_INFO: {
8137 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
8140 basename = g_path_get_basename (image->name);
8141 buffer_add_string (buf, basename); // name
8142 buffer_add_string (buf, image->module_name); // scopename
8143 buffer_add_string (buf, image->name); // fqname
8144 buffer_add_string (buf, mono_image_get_guid (image)); // guid
8145 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
8150 return ERR_NOT_IMPLEMENTED;
8157 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8163 case CMD_FIELD_GET_INFO: {
8164 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
8166 buffer_add_string (buf, f->name);
8167 buffer_add_typeid (buf, domain, f->parent);
8168 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
8169 buffer_add_int (buf, f->type->attrs);
8173 return ERR_NOT_IMPLEMENTED;
8180 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
8182 if (val && val->vtable->klass == mono_defaults.runtimetype_class) {
8183 /* Special case these so the client doesn't have to handle Type objects */
8185 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
8186 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
8187 } else if (MONO_TYPE_IS_REFERENCE (t))
8188 buffer_add_value (buf, t, &val, domain);
8190 buffer_add_value (buf, t, mono_object_unbox (val), domain);
8194 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
8200 buffer_add_int (buf, 0);
8204 for (i = 0; i < cinfo->num_attrs; ++i) {
8205 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
8208 buffer_add_int (buf, nattrs);
8210 for (i = 0; i < cinfo->num_attrs; ++i) {
8211 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
8212 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
8213 MonoArray *typed_args, *named_args;
8215 CattrNamedArg *arginfo = NULL;
8218 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
8219 if (!mono_error_ok (&error)) {
8220 DEBUG_PRINTF (2, "[dbg] mono_reflection_create_custom_attr_data_args () failed with: '%s'\n", mono_error_get_message (&error));
8221 mono_error_cleanup (&error);
8222 return ERR_LOADER_ERROR;
8225 buffer_add_methodid (buf, domain, attr->ctor);
8229 buffer_add_int (buf, mono_array_length (typed_args));
8230 for (j = 0; j < mono_array_length (typed_args); ++j) {
8231 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
8233 t = mono_method_signature (attr->ctor)->params [j];
8235 buffer_add_cattr_arg (buf, t, domain, val);
8238 buffer_add_int (buf, 0);
8243 buffer_add_int (buf, mono_array_length (named_args));
8245 for (j = 0; j < mono_array_length (named_args); ++j) {
8246 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
8248 if (arginfo [j].prop) {
8249 buffer_add_byte (buf, 0x54);
8250 buffer_add_propertyid (buf, domain, arginfo [j].prop);
8251 } else if (arginfo [j].field) {
8252 buffer_add_byte (buf, 0x53);
8253 buffer_add_fieldid (buf, domain, arginfo [j].field);
8255 g_assert_not_reached ();
8258 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
8261 buffer_add_int (buf, 0);
8270 /* FIXME: Code duplication with icall.c */
8272 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
8277 mono_class_setup_interfaces (klass, error);
8278 if (!mono_error_ok (error))
8281 for (i = 0; i < klass->interface_count; i++) {
8282 ic = klass->interfaces [i];
8283 g_hash_table_insert (ifaces, ic, ic);
8285 collect_interfaces (ic, ifaces, error);
8286 if (!mono_error_ok (error))
8292 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8304 case CMD_TYPE_GET_INFO: {
8305 buffer_add_string (buf, klass->name_space);
8306 buffer_add_string (buf, klass->name);
8308 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
8309 buffer_add_string (buf, name);
8311 buffer_add_assemblyid (buf, domain, klass->image->assembly);
8312 buffer_add_moduleid (buf, domain, klass->image);
8313 buffer_add_typeid (buf, domain, klass->parent);
8314 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
8315 buffer_add_typeid (buf, domain, klass->element_class);
8317 buffer_add_id (buf, 0);
8318 buffer_add_int (buf, klass->type_token);
8319 buffer_add_byte (buf, klass->rank);
8320 buffer_add_int (buf, mono_class_get_flags (klass));
8322 type = &klass->byval_arg;
8323 // FIXME: Can't decide whenever a class represents a byref type
8326 if (type->type == MONO_TYPE_PTR)
8328 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
8330 if (type->type == MONO_TYPE_VALUETYPE)
8332 if (klass->enumtype)
8334 if (mono_class_is_gtd (klass))
8336 if (mono_class_is_gtd (klass) || mono_class_is_ginst (klass))
8338 buffer_add_byte (buf, b);
8341 while ((nested = mono_class_get_nested_types (klass, &iter)))
8343 buffer_add_int (buf, nnested);
8345 while ((nested = mono_class_get_nested_types (klass, &iter)))
8346 buffer_add_typeid (buf, domain, nested);
8347 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8348 if (mono_class_is_gtd (klass))
8349 buffer_add_typeid (buf, domain, klass);
8350 else if (mono_class_is_ginst (klass))
8351 buffer_add_typeid (buf, domain, mono_class_get_generic_class (klass)->container_class);
8353 buffer_add_id (buf, 0);
8355 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8358 if (mono_class_is_ginst (klass)) {
8359 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
8361 count = inst->type_argc;
8362 buffer_add_int (buf, count);
8363 for (i = 0; i < count; i++)
8364 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8365 } else if (mono_class_is_gtd (klass)) {
8366 MonoGenericContainer *container = mono_class_get_generic_container (klass);
8369 count = container->type_argc;
8370 buffer_add_int (buf, count);
8371 for (i = 0; i < count; i++) {
8372 pklass = mono_class_from_generic_parameter_internal (mono_generic_container_get_param (container, i));
8373 buffer_add_typeid (buf, domain, pklass);
8376 buffer_add_int (buf, 0);
8381 case CMD_TYPE_GET_METHODS: {
8384 gpointer iter = NULL;
8387 mono_class_setup_methods (klass);
8389 nmethods = mono_class_num_methods (klass);
8391 buffer_add_int (buf, nmethods);
8393 while ((m = mono_class_get_methods (klass, &iter))) {
8394 buffer_add_methodid (buf, domain, m);
8397 g_assert (i == nmethods);
8400 case CMD_TYPE_GET_FIELDS: {
8403 gpointer iter = NULL;
8406 nfields = mono_class_num_fields (klass);
8408 buffer_add_int (buf, nfields);
8410 while ((f = mono_class_get_fields (klass, &iter))) {
8411 buffer_add_fieldid (buf, domain, f);
8412 buffer_add_string (buf, f->name);
8413 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
8414 buffer_add_int (buf, f->type->attrs);
8417 g_assert (i == nfields);
8420 case CMD_TYPE_GET_PROPERTIES: {
8423 gpointer iter = NULL;
8426 nprops = mono_class_num_properties (klass);
8428 buffer_add_int (buf, nprops);
8430 while ((p = mono_class_get_properties (klass, &iter))) {
8431 buffer_add_propertyid (buf, domain, p);
8432 buffer_add_string (buf, p->name);
8433 buffer_add_methodid (buf, domain, p->get);
8434 buffer_add_methodid (buf, domain, p->set);
8435 buffer_add_int (buf, p->attrs);
8438 g_assert (i == nprops);
8441 case CMD_TYPE_GET_CATTRS: {
8442 MonoClass *attr_klass;
8443 MonoCustomAttrInfo *cinfo;
8445 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8446 /* attr_klass can be NULL */
8447 if (err != ERR_NONE)
8450 cinfo = mono_custom_attrs_from_class_checked (klass, &error);
8451 if (!is_ok (&error)) {
8452 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8453 return ERR_LOADER_ERROR;
8456 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8457 if (err != ERR_NONE)
8461 case CMD_TYPE_GET_FIELD_CATTRS: {
8462 MonoClass *attr_klass;
8463 MonoCustomAttrInfo *cinfo;
8464 MonoClassField *field;
8466 field = decode_fieldid (p, &p, end, NULL, &err);
8467 if (err != ERR_NONE)
8469 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8470 if (err != ERR_NONE)
8473 cinfo = mono_custom_attrs_from_field_checked (klass, field, &error);
8474 if (!is_ok (&error)) {
8475 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8476 return ERR_LOADER_ERROR;
8479 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8480 if (err != ERR_NONE)
8484 case CMD_TYPE_GET_PROPERTY_CATTRS: {
8485 MonoClass *attr_klass;
8486 MonoCustomAttrInfo *cinfo;
8489 prop = decode_propertyid (p, &p, end, NULL, &err);
8490 if (err != ERR_NONE)
8492 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8493 if (err != ERR_NONE)
8496 cinfo = mono_custom_attrs_from_property_checked (klass, prop, &error);
8497 if (!is_ok (&error)) {
8498 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8499 return ERR_LOADER_ERROR;
8502 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8503 if (err != ERR_NONE)
8507 case CMD_TYPE_GET_VALUES:
8508 case CMD_TYPE_GET_VALUES_2: {
8515 MonoThread *thread_obj;
8516 MonoInternalThread *thread = NULL;
8517 guint32 special_static_type;
8519 if (command == CMD_TYPE_GET_VALUES_2) {
8520 int objid = decode_objid (p, &p, end);
8523 err = get_object (objid, (MonoObject**)&thread_obj);
8524 if (err != ERR_NONE)
8527 thread = THREAD_TO_INTERNAL (thread_obj);
8530 len = decode_int (p, &p, end);
8531 for (i = 0; i < len; ++i) {
8532 f = decode_fieldid (p, &p, end, NULL, &err);
8533 if (err != ERR_NONE)
8536 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8537 return ERR_INVALID_FIELDID;
8538 special_static_type = mono_class_field_get_special_static_type (f);
8539 if (special_static_type != SPECIAL_STATIC_NONE) {
8540 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
8541 return ERR_INVALID_FIELDID;
8544 /* Check that the field belongs to the object */
8546 for (k = klass; k; k = k->parent) {
8547 if (k == f->parent) {
8553 return ERR_INVALID_FIELDID;
8555 vtable = mono_class_vtable (domain, f->parent);
8556 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8557 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val, &error);
8558 if (!is_ok (&error))
8559 return ERR_INVALID_FIELDID;
8560 buffer_add_value (buf, f->type, val, domain);
8565 case CMD_TYPE_SET_VALUES: {
8573 len = decode_int (p, &p, end);
8574 for (i = 0; i < len; ++i) {
8575 f = decode_fieldid (p, &p, end, NULL, &err);
8576 if (err != ERR_NONE)
8579 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8580 return ERR_INVALID_FIELDID;
8581 if (mono_class_field_is_special_static (f))
8582 return ERR_INVALID_FIELDID;
8584 /* Check that the field belongs to the object */
8586 for (k = klass; k; k = k->parent) {
8587 if (k == f->parent) {
8593 return ERR_INVALID_FIELDID;
8595 // FIXME: Check for literal/const
8597 vtable = mono_class_vtable (domain, f->parent);
8598 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8599 err = decode_value (f->type, domain, val, p, &p, end);
8600 if (err != ERR_NONE) {
8604 if (MONO_TYPE_IS_REFERENCE (f->type))
8605 mono_field_static_set_value (vtable, f, *(gpointer*)val);
8607 mono_field_static_set_value (vtable, f, val);
8612 case CMD_TYPE_GET_OBJECT: {
8613 MonoObject *o = (MonoObject*)mono_type_get_object_checked (domain, &klass->byval_arg, &error);
8614 if (!mono_error_ok (&error)) {
8615 mono_error_cleanup (&error);
8616 return ERR_INVALID_OBJECT;
8618 buffer_add_objid (buf, o);
8621 case CMD_TYPE_GET_SOURCE_FILES:
8622 case CMD_TYPE_GET_SOURCE_FILES_2: {
8623 char *source_file, *base;
8627 files = get_source_files_for_type (klass);
8629 buffer_add_int (buf, files->len);
8630 for (i = 0; i < files->len; ++i) {
8631 source_file = (char *)g_ptr_array_index (files, i);
8632 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8633 buffer_add_string (buf, source_file);
8635 base = dbg_path_get_basename (source_file);
8636 buffer_add_string (buf, base);
8639 g_free (source_file);
8641 g_ptr_array_free (files, TRUE);
8644 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8645 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8647 if (err != ERR_NONE)
8649 if (mono_class_is_assignable_from (klass, oklass))
8650 buffer_add_byte (buf, 1);
8652 buffer_add_byte (buf, 0);
8655 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8656 char *name = decode_string (p, &p, end);
8657 int i, flags = decode_int (p, &p, end);
8661 error_init (&error);
8662 array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &error);
8663 if (!is_ok (&error)) {
8664 mono_error_cleanup (&error);
8665 return ERR_LOADER_ERROR;
8667 buffer_add_int (buf, array->len);
8668 for (i = 0; i < array->len; ++i) {
8669 MonoMethod *method = (MonoMethod *)g_ptr_array_index (array, i);
8670 buffer_add_methodid (buf, domain, method);
8673 g_ptr_array_free (array, TRUE);
8677 case CMD_TYPE_GET_INTERFACES: {
8679 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8680 MonoClass *tclass, *iface;
8681 GHashTableIter iter;
8685 for (parent = tclass; parent; parent = parent->parent) {
8686 mono_class_setup_interfaces (parent, &error);
8687 if (!mono_error_ok (&error))
8688 return ERR_LOADER_ERROR;
8689 collect_interfaces (parent, iface_hash, &error);
8690 if (!mono_error_ok (&error))
8691 return ERR_LOADER_ERROR;
8694 buffer_add_int (buf, g_hash_table_size (iface_hash));
8696 g_hash_table_iter_init (&iter, iface_hash);
8697 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8698 buffer_add_typeid (buf, domain, iface);
8699 g_hash_table_destroy (iface_hash);
8702 case CMD_TYPE_GET_INTERFACE_MAP: {
8703 int tindex, ioffset;
8704 gboolean variance_used;
8706 int len, nmethods, i;
8710 len = decode_int (p, &p, end);
8711 mono_class_setup_vtable (klass);
8713 for (tindex = 0; tindex < len; ++tindex) {
8714 iclass = decode_typeid (p, &p, end, NULL, &err);
8715 if (err != ERR_NONE)
8718 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8720 return ERR_INVALID_ARGUMENT;
8722 nmethods = mono_class_num_methods (iclass);
8723 buffer_add_int (buf, nmethods);
8726 while ((method = mono_class_get_methods (iclass, &iter))) {
8727 buffer_add_methodid (buf, domain, method);
8729 for (i = 0; i < nmethods; ++i)
8730 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
8734 case CMD_TYPE_IS_INITIALIZED: {
8735 MonoVTable *vtable = mono_class_vtable (domain, klass);
8738 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8740 buffer_add_int (buf, 0);
8743 case CMD_TYPE_CREATE_INSTANCE: {
8747 obj = mono_object_new_checked (domain, klass, &error);
8748 mono_error_assert_ok (&error);
8749 buffer_add_objid (buf, obj);
8753 return ERR_NOT_IMPLEMENTED;
8760 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8763 MonoDomain *old_domain;
8767 klass = decode_typeid (p, &p, end, &domain, &err);
8768 if (err != ERR_NONE)
8771 old_domain = mono_domain_get ();
8773 mono_domain_set (domain, TRUE);
8775 err = type_commands_internal (command, klass, domain, p, end, buf);
8777 mono_domain_set (old_domain, TRUE);
8783 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8785 MonoMethodHeader *header;
8789 case CMD_METHOD_GET_NAME: {
8790 buffer_add_string (buf, method->name);
8793 case CMD_METHOD_GET_DECLARING_TYPE: {
8794 buffer_add_typeid (buf, domain, method->klass);
8797 case CMD_METHOD_GET_DEBUG_INFO: {
8799 MonoDebugMethodInfo *minfo;
8801 int i, j, n_il_offsets;
8803 GPtrArray *source_file_list;
8804 MonoSymSeqPoint *sym_seq_points;
8806 header = mono_method_get_header_checked (method, &error);
8808 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8809 buffer_add_int (buf, 0);
8810 buffer_add_string (buf, "");
8811 buffer_add_int (buf, 0);
8815 minfo = mono_debug_lookup_method (method);
8817 buffer_add_int (buf, header->code_size);
8818 buffer_add_string (buf, "");
8819 buffer_add_int (buf, 0);
8820 mono_metadata_free_mh (header);
8824 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, &source_files, &sym_seq_points, &n_il_offsets);
8825 buffer_add_int (buf, header->code_size);
8826 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8827 buffer_add_int (buf, source_file_list->len);
8828 for (i = 0; i < source_file_list->len; ++i) {
8829 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
8830 buffer_add_string (buf, sinfo->source_file);
8831 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8832 for (j = 0; j < 16; ++j)
8833 buffer_add_byte (buf, sinfo->hash [j]);
8837 buffer_add_string (buf, source_file);
8839 buffer_add_int (buf, n_il_offsets);
8840 DEBUG_PRINTF (10, "Line number table for method %s:\n", mono_method_full_name (method, TRUE));
8841 for (i = 0; i < n_il_offsets; ++i) {
8842 MonoSymSeqPoint *sp = &sym_seq_points [i];
8843 const char *srcfile = "";
8845 if (source_files [i] != -1) {
8846 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, source_files [i]);
8847 srcfile = sinfo->source_file;
8849 DEBUG_PRINTF (10, "IL%x -> %s:%d %d %d %d\n", sp->il_offset, srcfile, sp->line, sp->column, sp->end_line, sp->end_column);
8850 buffer_add_int (buf, sp->il_offset);
8851 buffer_add_int (buf, sp->line);
8852 if (CHECK_PROTOCOL_VERSION (2, 13))
8853 buffer_add_int (buf, source_files [i]);
8854 if (CHECK_PROTOCOL_VERSION (2, 19))
8855 buffer_add_int (buf, sp->column);
8856 if (CHECK_PROTOCOL_VERSION (2, 32)) {
8857 buffer_add_int (buf, sp->end_line);
8858 buffer_add_int (buf, sp->end_column);
8861 g_free (source_file);
8862 g_free (source_files);
8863 g_free (sym_seq_points);
8864 g_ptr_array_free (source_file_list, TRUE);
8865 mono_metadata_free_mh (header);
8868 case CMD_METHOD_GET_PARAM_INFO: {
8869 MonoMethodSignature *sig = mono_method_signature (method);
8873 /* FIXME: mono_class_from_mono_type () and byrefs */
8875 /* FIXME: Use a smaller encoding */
8876 buffer_add_int (buf, sig->call_convention);
8877 buffer_add_int (buf, sig->param_count);
8878 buffer_add_int (buf, sig->generic_param_count);
8879 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
8880 for (i = 0; i < sig->param_count; ++i) {
8882 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
8885 /* Emit parameter names */
8886 names = g_new (char *, sig->param_count);
8887 mono_method_get_param_names (method, (const char **) names);
8888 for (i = 0; i < sig->param_count; ++i)
8889 buffer_add_string (buf, names [i]);
8894 case CMD_METHOD_GET_LOCALS_INFO: {
8897 MonoDebugLocalsInfo *locals;
8898 int *locals_map = NULL;
8900 header = mono_method_get_header_checked (method, &error);
8902 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8903 return ERR_INVALID_ARGUMENT;
8906 locals = mono_debug_lookup_locals (method);
8908 if (CHECK_PROTOCOL_VERSION (2, 43)) {
8910 buffer_add_int (buf, 1);
8911 buffer_add_int (buf, 0);
8912 buffer_add_int (buf, header->code_size);
8914 buffer_add_int (buf, header->num_locals);
8916 for (i = 0; i < header->num_locals; ++i) {
8917 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
8920 for (i = 0; i < header->num_locals; ++i) {
8922 sprintf (lname, "V_%d", i);
8923 buffer_add_string (buf, lname);
8926 for (i = 0; i < header->num_locals; ++i) {
8927 buffer_add_int (buf, 0);
8928 buffer_add_int (buf, header->code_size);
8931 if (CHECK_PROTOCOL_VERSION (2, 43)) {
8933 buffer_add_int (buf, locals->num_blocks);
8935 for (i = 0; i < locals->num_blocks; ++i) {
8936 buffer_add_int (buf, locals->code_blocks [i].start_offset - last_start);
8937 buffer_add_int (buf, locals->code_blocks [i].end_offset - locals->code_blocks [i].start_offset);
8938 last_start = locals->code_blocks [i].start_offset;
8942 num_locals = locals->num_locals;
8943 buffer_add_int (buf, num_locals);
8946 for (i = 0; i < num_locals; ++i) {
8947 g_assert (locals->locals [i].index < header->num_locals);
8948 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [locals->locals [i].index]));
8951 for (i = 0; i < num_locals; ++i)
8952 buffer_add_string (buf, locals->locals [i].name);
8954 for (i = 0; i < num_locals; ++i) {
8955 if (locals->locals [i].block) {
8956 buffer_add_int (buf, locals->locals [i].block->start_offset);
8957 buffer_add_int (buf, locals->locals [i].block->end_offset);
8959 buffer_add_int (buf, 0);
8960 buffer_add_int (buf, header->code_size);
8964 mono_metadata_free_mh (header);
8967 mono_debug_free_locals (locals);
8968 g_free (locals_map);
8972 case CMD_METHOD_GET_INFO:
8973 buffer_add_int (buf, method->flags);
8974 buffer_add_int (buf, method->iflags);
8975 buffer_add_int (buf, method->token);
8976 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8978 if (method->is_generic)
8980 if (mono_method_signature (method)->generic_param_count)
8982 buffer_add_byte (buf, attrs);
8983 if (method->is_generic || method->is_inflated) {
8986 if (method->is_generic) {
8989 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8991 result = imethod->declaring;
8992 if (imethod->context.class_inst) {
8993 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8994 /*Generic methods gets the context of the GTD.*/
8995 if (mono_class_get_context (klass)) {
8997 result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), &error);
8998 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9003 buffer_add_methodid (buf, domain, result);
9005 buffer_add_id (buf, 0);
9007 if (CHECK_PROTOCOL_VERSION (2, 15)) {
9008 if (mono_method_signature (method)->generic_param_count) {
9011 if (method->is_inflated) {
9012 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
9014 count = inst->type_argc;
9015 buffer_add_int (buf, count);
9017 for (i = 0; i < count; i++)
9018 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
9020 buffer_add_int (buf, 0);
9022 } else if (method->is_generic) {
9023 MonoGenericContainer *container = mono_method_get_generic_container (method);
9025 count = mono_method_signature (method)->generic_param_count;
9026 buffer_add_int (buf, count);
9027 for (i = 0; i < count; i++) {
9028 MonoGenericParam *param = mono_generic_container_get_param (container, i);
9029 MonoClass *pklass = mono_class_from_generic_parameter_internal (param);
9030 buffer_add_typeid (buf, domain, pklass);
9033 buffer_add_int (buf, 0);
9036 buffer_add_int (buf, 0);
9041 case CMD_METHOD_GET_BODY: {
9045 header = mono_method_get_header_checked (method, &error);
9047 mono_error_cleanup (&error); /* FIXME don't swallow the error */
9048 buffer_add_int (buf, 0);
9050 if (CHECK_PROTOCOL_VERSION (2, 18))
9051 buffer_add_int (buf, 0);
9053 buffer_add_int (buf, header->code_size);
9054 for (i = 0; i < header->code_size; ++i)
9055 buffer_add_byte (buf, header->code [i]);
9057 if (CHECK_PROTOCOL_VERSION (2, 18)) {
9058 buffer_add_int (buf, header->num_clauses);
9059 for (i = 0; i < header->num_clauses; ++i) {
9060 MonoExceptionClause *clause = &header->clauses [i];
9062 buffer_add_int (buf, clause->flags);
9063 buffer_add_int (buf, clause->try_offset);
9064 buffer_add_int (buf, clause->try_len);
9065 buffer_add_int (buf, clause->handler_offset);
9066 buffer_add_int (buf, clause->handler_len);
9067 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
9068 buffer_add_typeid (buf, domain, clause->data.catch_class);
9069 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
9070 buffer_add_int (buf, clause->data.filter_offset);
9074 mono_metadata_free_mh (header);
9079 case CMD_METHOD_RESOLVE_TOKEN: {
9080 guint32 token = decode_int (p, &p, end);
9083 switch (mono_metadata_token_code (token)) {
9084 case MONO_TOKEN_STRING: {
9089 s = mono_ldstr_checked (domain, method->klass->image, mono_metadata_token_index (token), &error);
9090 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
9092 s2 = mono_string_to_utf8_checked (s, &error);
9093 mono_error_assert_ok (&error);
9095 buffer_add_byte (buf, TOKEN_TYPE_STRING);
9096 buffer_add_string (buf, s2);
9103 MonoClass *handle_class;
9105 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
9106 val = mono_method_get_wrapper_data (method, token);
9107 handle_class = (MonoClass *)mono_method_get_wrapper_data (method, token + 1);
9109 if (handle_class == NULL) {
9110 // Can't figure out the token type
9111 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
9115 val = mono_ldtoken_checked (method->klass->image, token, &handle_class, NULL, &error);
9117 g_error ("Could not load token due to %s", mono_error_get_message (&error));
9120 if (handle_class == mono_defaults.typehandle_class) {
9121 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
9122 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
9123 buffer_add_typeid (buf, domain, (MonoClass *) val);
9125 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
9126 } else if (handle_class == mono_defaults.fieldhandle_class) {
9127 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
9128 buffer_add_fieldid (buf, domain, (MonoClassField *)val);
9129 } else if (handle_class == mono_defaults.methodhandle_class) {
9130 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
9131 buffer_add_methodid (buf, domain, (MonoMethod *)val);
9132 } else if (handle_class == mono_defaults.string_class) {
9135 s = mono_string_to_utf8_checked ((MonoString *)val, &error);
9136 mono_error_assert_ok (&error);
9137 buffer_add_byte (buf, TOKEN_TYPE_STRING);
9138 buffer_add_string (buf, s);
9141 g_assert_not_reached ();
9148 case CMD_METHOD_GET_CATTRS: {
9150 MonoClass *attr_klass;
9151 MonoCustomAttrInfo *cinfo;
9153 attr_klass = decode_typeid (p, &p, end, NULL, &err);
9154 /* attr_klass can be NULL */
9155 if (err != ERR_NONE)
9158 cinfo = mono_custom_attrs_from_method_checked (method, &error);
9159 if (!is_ok (&error)) {
9160 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
9161 return ERR_LOADER_ERROR;
9164 err = buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
9165 if (err != ERR_NONE)
9169 case CMD_METHOD_MAKE_GENERIC_METHOD: {
9171 MonoType **type_argv;
9175 MonoGenericInst *ginst;
9176 MonoGenericContext tmp_context;
9177 MonoMethod *inflated;
9179 type_argc = decode_int (p, &p, end);
9180 type_argv = g_new0 (MonoType*, type_argc);
9181 for (i = 0; i < type_argc; ++i) {
9182 klass = decode_typeid (p, &p, end, &d, &err);
9183 if (err != ERR_NONE) {
9189 return ERR_INVALID_ARGUMENT;
9191 type_argv [i] = &klass->byval_arg;
9193 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
9195 tmp_context.class_inst = mono_class_is_ginst (method->klass) ? mono_class_get_generic_class (method->klass)->context.class_inst : NULL;
9196 tmp_context.method_inst = ginst;
9198 inflated = mono_class_inflate_generic_method_checked (method, &tmp_context, &error);
9199 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9200 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
9201 return ERR_INVALID_ARGUMENT;
9202 buffer_add_methodid (buf, domain, inflated);
9206 return ERR_NOT_IMPLEMENTED;
9213 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9216 MonoDomain *old_domain;
9220 method = decode_methodid (p, &p, end, &domain, &err);
9221 if (err != ERR_NONE)
9224 old_domain = mono_domain_get ();
9226 mono_domain_set (domain, TRUE);
9228 err = method_commands_internal (command, method, domain, p, end, buf);
9230 mono_domain_set (old_domain, TRUE);
9236 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9238 int objid = decode_objid (p, &p, end);
9240 MonoThread *thread_obj;
9241 MonoInternalThread *thread;
9243 err = get_object (objid, (MonoObject**)&thread_obj);
9244 if (err != ERR_NONE)
9247 thread = THREAD_TO_INTERNAL (thread_obj);
9250 case CMD_THREAD_GET_NAME: {
9252 gunichar2 *s = mono_thread_get_name (thread, &name_len);
9255 buffer_add_int (buf, 0);
9260 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
9262 buffer_add_int (buf, len);
9263 buffer_add_data (buf, (guint8*)name, len);
9268 case CMD_THREAD_GET_FRAME_INFO: {
9269 DebuggerTlsData *tls;
9270 int i, start_frame, length;
9272 // Wait for suspending if it already started
9273 // FIXME: Races with suspend_count
9274 while (!is_suspended ()) {
9276 wait_for_suspend ();
9280 wait_for_suspend ();
9281 if (!is_suspended ())
9282 return ERR_NOT_SUSPENDED;
9285 start_frame = decode_int (p, &p, end);
9286 length = decode_int (p, &p, end);
9288 if (start_frame != 0 || length != -1)
9289 return ERR_NOT_IMPLEMENTED;
9291 mono_loader_lock ();
9292 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9293 mono_loader_unlock ();
9296 compute_frame_info (thread, tls);
9298 buffer_add_int (buf, tls->frame_count);
9299 for (i = 0; i < tls->frame_count; ++i) {
9300 buffer_add_int (buf, tls->frames [i]->id);
9301 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
9302 buffer_add_int (buf, tls->frames [i]->il_offset);
9304 * Instead of passing the frame type directly to the client, we associate
9305 * it with the previous frame using a set of flags. This avoids lots of
9306 * conditional code in the client, since a frame whose type isn't
9307 * FRAME_TYPE_MANAGED has no method, location, etc.
9309 buffer_add_byte (buf, tls->frames [i]->flags);
9314 case CMD_THREAD_GET_STATE:
9315 buffer_add_int (buf, thread->state);
9317 case CMD_THREAD_GET_INFO:
9318 buffer_add_byte (buf, thread->threadpool_thread);
9320 case CMD_THREAD_GET_ID:
9321 buffer_add_long (buf, (guint64)(gsize)thread);
9323 case CMD_THREAD_GET_TID:
9324 buffer_add_long (buf, (guint64)thread->tid);
9326 case CMD_THREAD_SET_IP: {
9327 DebuggerTlsData *tls;
9330 MonoSeqPointInfo *seq_points;
9335 method = decode_methodid (p, &p, end, &domain, &err);
9336 if (err != ERR_NONE)
9338 il_offset = decode_long (p, &p, end);
9340 while (!is_suspended ()) {
9342 wait_for_suspend ();
9345 mono_loader_lock ();
9346 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9347 mono_loader_unlock ();
9350 compute_frame_info (thread, tls);
9351 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
9352 return ERR_INVALID_ARGUMENT;
9354 found_sp = mono_find_seq_point (domain, method, il_offset, &seq_points, &sp);
9356 g_assert (seq_points);
9359 return ERR_INVALID_ARGUMENT;
9361 // FIXME: Check that the ip change is safe
9363 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);
9364 MONO_CONTEXT_SET_IP (&tls->restore_state.ctx, (guint8*)tls->frames [0]->ji->code_start + sp.native_offset);
9368 return ERR_NOT_IMPLEMENTED;
9375 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9379 MonoThread *thread_obj;
9380 MonoInternalThread *thread;
9381 int pos, i, len, frame_idx;
9382 DebuggerTlsData *tls;
9384 MonoDebugMethodJitInfo *jit;
9385 MonoMethodSignature *sig;
9387 MonoMethodHeader *header;
9389 objid = decode_objid (p, &p, end);
9390 err = get_object (objid, (MonoObject**)&thread_obj);
9391 if (err != ERR_NONE)
9394 thread = THREAD_TO_INTERNAL (thread_obj);
9396 id = decode_id (p, &p, end);
9398 mono_loader_lock ();
9399 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9400 mono_loader_unlock ();
9403 for (i = 0; i < tls->frame_count; ++i) {
9404 if (tls->frames [i]->id == id)
9407 if (i == tls->frame_count)
9408 return ERR_INVALID_FRAMEID;
9411 frame = tls->frames [frame_idx];
9413 /* This is supported for frames without has_ctx etc. set */
9414 if (command == CMD_STACK_FRAME_GET_DOMAIN) {
9415 if (CHECK_PROTOCOL_VERSION (2, 38))
9416 buffer_add_domainid (buf, frame->domain);
9420 if (!frame->has_ctx)
9421 return ERR_ABSENT_INFORMATION;
9423 if (!ensure_jit (frame))
9424 return ERR_ABSENT_INFORMATION;
9428 sig = mono_method_signature (frame->actual_method);
9430 if (!jit->has_var_info || !mono_get_seq_points (frame->domain, frame->actual_method))
9432 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
9434 return ERR_ABSENT_INFORMATION;
9437 case CMD_STACK_FRAME_GET_VALUES: {
9439 len = decode_int (p, &p, end);
9440 header = mono_method_get_header_checked (frame->actual_method, &error);
9441 mono_error_assert_ok (&error); /* FIXME report error */
9443 for (i = 0; i < len; ++i) {
9444 pos = decode_int (p, &p, end);
9449 DEBUG_PRINTF (4, "[dbg] send arg %d.\n", pos);
9451 g_assert (pos >= 0 && pos < jit->num_params);
9453 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
9455 MonoDebugLocalsInfo *locals;
9457 locals = mono_debug_lookup_locals (frame->method);
9459 g_assert (pos < locals->num_locals);
9460 pos = locals->locals [pos].index;
9461 mono_debug_free_locals (locals);
9463 g_assert (pos >= 0 && pos < jit->num_locals);
9465 DEBUG_PRINTF (4, "[dbg] send local %d.\n", pos);
9467 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
9470 mono_metadata_free_mh (header);
9473 case CMD_STACK_FRAME_GET_THIS: {
9474 if (frame->api_method->klass->valuetype) {
9475 if (!sig->hasthis) {
9476 MonoObject *p = NULL;
9477 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
9479 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9482 if (!sig->hasthis) {
9483 MonoObject *p = NULL;
9484 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
9486 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9491 case CMD_STACK_FRAME_SET_VALUES: {
9495 MonoDebugVarInfo *var;
9497 len = decode_int (p, &p, end);
9498 header = mono_method_get_header_checked (frame->actual_method, &error);
9499 mono_error_assert_ok (&error); /* FIXME report error */
9501 for (i = 0; i < len; ++i) {
9502 pos = decode_int (p, &p, end);
9507 g_assert (pos >= 0 && pos < jit->num_params);
9509 t = sig->params [pos];
9510 var = &jit->params [pos];
9512 MonoDebugLocalsInfo *locals;
9514 locals = mono_debug_lookup_locals (frame->method);
9516 g_assert (pos < locals->num_locals);
9517 pos = locals->locals [pos].index;
9518 mono_debug_free_locals (locals);
9520 g_assert (pos >= 0 && pos < jit->num_locals);
9522 t = header->locals [pos];
9523 var = &jit->locals [pos];
9526 if (MONO_TYPE_IS_REFERENCE (t))
9527 val_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
9529 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9530 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9531 if (err != ERR_NONE)
9534 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9536 mono_metadata_free_mh (header);
9539 case CMD_STACK_FRAME_GET_DOMAIN: {
9540 if (CHECK_PROTOCOL_VERSION (2, 38))
9541 buffer_add_domainid (buf, frame->domain);
9544 case CMD_STACK_FRAME_SET_THIS: {
9547 MonoDebugVarInfo *var;
9549 t = &frame->actual_method->klass->byval_arg;
9550 /* Checked by the sender */
9551 g_assert (MONO_TYPE_ISSTRUCT (t));
9552 var = jit->this_var;
9555 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9556 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9557 if (err != ERR_NONE)
9560 set_var (&frame->actual_method->klass->this_arg, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9564 return ERR_NOT_IMPLEMENTED;
9571 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9574 int objid, index, len, i, esize;
9578 objid = decode_objid (p, &p, end);
9579 err = get_object (objid, (MonoObject**)&arr);
9580 if (err != ERR_NONE)
9584 case CMD_ARRAY_REF_GET_LENGTH:
9585 buffer_add_int (buf, arr->obj.vtable->klass->rank);
9587 buffer_add_int (buf, arr->max_length);
9588 buffer_add_int (buf, 0);
9590 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
9591 buffer_add_int (buf, arr->bounds [i].length);
9592 buffer_add_int (buf, arr->bounds [i].lower_bound);
9596 case CMD_ARRAY_REF_GET_VALUES:
9597 index = decode_int (p, &p, end);
9598 len = decode_int (p, &p, end);
9600 g_assert (index >= 0 && len >= 0);
9601 // Reordered to avoid integer overflow
9602 g_assert (!(index > arr->max_length - len));
9604 esize = mono_array_element_size (arr->obj.vtable->klass);
9605 for (i = index; i < index + len; ++i) {
9606 elem = (gpointer*)((char*)arr->vector + (i * esize));
9607 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
9610 case CMD_ARRAY_REF_SET_VALUES:
9611 index = decode_int (p, &p, end);
9612 len = decode_int (p, &p, end);
9614 g_assert (index >= 0 && len >= 0);
9615 // Reordered to avoid integer overflow
9616 g_assert (!(index > arr->max_length - len));
9618 esize = mono_array_element_size (arr->obj.vtable->klass);
9619 for (i = index; i < index + len; ++i) {
9620 elem = (gpointer*)((char*)arr->vector + (i * esize));
9622 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, (guint8 *)elem, p, &p, end);
9626 return ERR_NOT_IMPLEMENTED;
9633 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9639 int i, index, length;
9641 gboolean use_utf16 = FALSE;
9643 objid = decode_objid (p, &p, end);
9644 err = get_object (objid, (MonoObject**)&str);
9645 if (err != ERR_NONE)
9649 case CMD_STRING_REF_GET_VALUE:
9650 if (CHECK_PROTOCOL_VERSION (2, 41)) {
9651 for (i = 0; i < mono_string_length (str); ++i)
9652 if (mono_string_chars (str)[i] == 0)
9654 buffer_add_byte (buf, use_utf16 ? 1 : 0);
9657 buffer_add_int (buf, mono_string_length (str) * 2);
9658 buffer_add_data (buf, (guint8*)mono_string_chars (str), mono_string_length (str) * 2);
9661 s = mono_string_to_utf8_checked (str, &error);
9662 mono_error_assert_ok (&error);
9663 buffer_add_string (buf, s);
9667 case CMD_STRING_REF_GET_LENGTH:
9668 buffer_add_long (buf, mono_string_length (str));
9670 case CMD_STRING_REF_GET_CHARS:
9671 index = decode_long (p, &p, end);
9672 length = decode_long (p, &p, end);
9673 if (index > mono_string_length (str) - length)
9674 return ERR_INVALID_ARGUMENT;
9675 c = mono_string_chars (str) + index;
9676 for (i = 0; i < length; ++i)
9677 buffer_add_short (buf, c [i]);
9680 return ERR_NOT_IMPLEMENTED;
9687 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9698 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9699 objid = decode_objid (p, &p, end);
9700 err = get_object (objid, &obj);
9701 if (err != ERR_NONE)
9702 buffer_add_int (buf, 1);
9704 buffer_add_int (buf, 0);
9708 objid = decode_objid (p, &p, end);
9709 err = get_object (objid, &obj);
9710 if (err != ERR_NONE)
9713 MonoClass *obj_type;
9714 gboolean remote_obj = FALSE;
9716 obj_type = obj->vtable->klass;
9717 if (mono_class_is_transparent_proxy (obj_type)) {
9718 obj_type = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
9722 g_assert (obj_type);
9725 case CMD_OBJECT_REF_GET_TYPE:
9726 /* This handles transparent proxies too */
9727 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9729 case CMD_OBJECT_REF_GET_VALUES:
9730 len = decode_int (p, &p, end);
9732 for (i = 0; i < len; ++i) {
9733 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9734 if (err != ERR_NONE)
9737 /* Check that the field belongs to the object */
9739 for (k = obj_type; k; k = k->parent) {
9740 if (k == f->parent) {
9746 return ERR_INVALID_FIELDID;
9748 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9752 if (mono_class_field_is_special_static (f))
9753 return ERR_INVALID_FIELDID;
9755 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9756 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9757 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9758 mono_field_static_get_value_checked (vtable, f, val, &error);
9759 if (!is_ok (&error)) {
9760 mono_error_cleanup (&error); /* FIXME report the error */
9761 return ERR_INVALID_OBJECT;
9763 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9766 guint8 *field_value = NULL;
9769 #ifndef DISABLE_REMOTING
9770 void *field_storage = NULL;
9771 field_value = mono_load_remote_field_checked(obj, obj_type, f, &field_storage, &error);
9772 if (!is_ok (&error)) {
9773 mono_error_cleanup (&error); /* FIXME report the error */
9774 return ERR_INVALID_OBJECT;
9777 g_assert_not_reached ();
9780 field_value = (guint8*)obj + f->offset;
9782 buffer_add_value (buf, f->type, field_value, obj->vtable->domain);
9786 case CMD_OBJECT_REF_SET_VALUES:
9787 len = decode_int (p, &p, end);
9789 for (i = 0; i < len; ++i) {
9790 f = decode_fieldid (p, &p, end, NULL, &err);
9791 if (err != ERR_NONE)
9794 /* Check that the field belongs to the object */
9796 for (k = obj_type; k; k = k->parent) {
9797 if (k == f->parent) {
9803 return ERR_INVALID_FIELDID;
9805 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9809 if (mono_class_field_is_special_static (f))
9810 return ERR_INVALID_FIELDID;
9812 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9813 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9815 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9816 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
9817 if (err != ERR_NONE) {
9821 mono_field_static_set_value (vtable, f, val);
9824 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
9825 if (err != ERR_NONE)
9830 case CMD_OBJECT_REF_GET_ADDRESS:
9831 buffer_add_long (buf, (gssize)obj);
9833 case CMD_OBJECT_REF_GET_DOMAIN:
9834 buffer_add_domainid (buf, obj->vtable->domain);
9836 case CMD_OBJECT_REF_GET_INFO:
9837 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9838 buffer_add_domainid (buf, obj->vtable->domain);
9841 return ERR_NOT_IMPLEMENTED;
9848 command_set_to_string (CommandSet command_set)
9850 switch (command_set) {
9853 case CMD_SET_OBJECT_REF:
9854 return "OBJECT_REF";
9855 case CMD_SET_STRING_REF:
9856 return "STRING_REF";
9857 case CMD_SET_THREAD:
9859 case CMD_SET_ARRAY_REF:
9861 case CMD_SET_EVENT_REQUEST:
9862 return "EVENT_REQUEST";
9863 case CMD_SET_STACK_FRAME:
9864 return "STACK_FRAME";
9865 case CMD_SET_APPDOMAIN:
9867 case CMD_SET_ASSEMBLY:
9869 case CMD_SET_METHOD:
9873 case CMD_SET_MODULE:
9884 static const char* vm_cmds_str [] = {
9892 "SET_PROTOCOL_VERSION",
9895 "GET_TYPES_FOR_SOURCE_FILE",
9900 static const char* thread_cmds_str[] = {
9910 static const char* event_cmds_str[] = {
9913 "REQUEST_CLEAR_ALL_BREAKPOINTS"
9916 static const char* appdomain_cmds_str[] = {
9918 "GET_FRIENDLY_NAME",
9920 "GET_ENTRY_ASSEMBLY",
9923 "CREATE_BOXED_VALUE"
9926 static const char* assembly_cmds_str[] = {
9929 "GET_MANIFEST_MODULE",
9936 static const char* module_cmds_str[] = {
9940 static const char* field_cmds_str[] = {
9944 static const char* method_cmds_str[] = {
9946 "GET_DECLARING_TYPE",
9954 "MAKE_GENERIC_METHOD"
9957 static const char* type_cmds_str[] = {
9965 "IS_ASSIGNABLE_FROM",
9969 "GET_PROPERTY_CATTRS",
9970 "GET_SOURCE_FILES_2",
9972 "GET_METHODS_BY_NAME_FLAGS",
9974 "GET_INTERFACE_MAP",
9978 static const char* stack_frame_cmds_str[] = {
9986 static const char* array_cmds_str[] = {
9992 static const char* string_cmds_str[] = {
9998 static const char* object_cmds_str[] = {
10009 cmd_to_string (CommandSet set, int command)
10016 cmds = vm_cmds_str;
10017 cmds_len = G_N_ELEMENTS (vm_cmds_str);
10019 case CMD_SET_OBJECT_REF:
10020 cmds = object_cmds_str;
10021 cmds_len = G_N_ELEMENTS (object_cmds_str);
10023 case CMD_SET_STRING_REF:
10024 cmds = string_cmds_str;
10025 cmds_len = G_N_ELEMENTS (string_cmds_str);
10027 case CMD_SET_THREAD:
10028 cmds = thread_cmds_str;
10029 cmds_len = G_N_ELEMENTS (thread_cmds_str);
10031 case CMD_SET_ARRAY_REF:
10032 cmds = array_cmds_str;
10033 cmds_len = G_N_ELEMENTS (array_cmds_str);
10035 case CMD_SET_EVENT_REQUEST:
10036 cmds = event_cmds_str;
10037 cmds_len = G_N_ELEMENTS (event_cmds_str);
10039 case CMD_SET_STACK_FRAME:
10040 cmds = stack_frame_cmds_str;
10041 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
10043 case CMD_SET_APPDOMAIN:
10044 cmds = appdomain_cmds_str;
10045 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
10047 case CMD_SET_ASSEMBLY:
10048 cmds = assembly_cmds_str;
10049 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
10051 case CMD_SET_METHOD:
10052 cmds = method_cmds_str;
10053 cmds_len = G_N_ELEMENTS (method_cmds_str);
10056 cmds = type_cmds_str;
10057 cmds_len = G_N_ELEMENTS (type_cmds_str);
10059 case CMD_SET_MODULE:
10060 cmds = module_cmds_str;
10061 cmds_len = G_N_ELEMENTS (module_cmds_str);
10063 case CMD_SET_FIELD:
10064 cmds = field_cmds_str;
10065 cmds_len = G_N_ELEMENTS (field_cmds_str);
10067 case CMD_SET_EVENT:
10068 cmds = event_cmds_str;
10069 cmds_len = G_N_ELEMENTS (event_cmds_str);
10074 if (command > 0 && command <= cmds_len)
10075 return cmds [command - 1];
10081 wait_for_attach (void)
10083 #ifndef DISABLE_SOCKET_TRANSPORT
10084 if (listen_fd == -1) {
10085 DEBUG_PRINTF (1, "[dbg] Invalid listening socket\n");
10089 /* Block and wait for client connection */
10090 conn_fd = socket_transport_accept (listen_fd);
10092 DEBUG_PRINTF (1, "Accepted connection on %d\n", conn_fd);
10093 if (conn_fd == -1) {
10094 DEBUG_PRINTF (1, "[dbg] Bad client connection\n");
10098 g_assert_not_reached ();
10102 disconnected = !transport_handshake ();
10103 if (disconnected) {
10104 DEBUG_PRINTF (1, "Transport handshake failed!\n");
10114 * This thread handles communication with the debugger client using a JDWP
10117 static gsize WINAPI
10118 debugger_thread (void *arg)
10121 int res, len, id, flags, command = 0;
10122 CommandSet command_set = (CommandSet)0;
10123 guint8 header [HEADER_LENGTH];
10124 guint8 *data, *p, *end;
10128 gboolean attach_failed = FALSE;
10130 DEBUG_PRINTF (1, "[dbg] Agent thread started, pid=%p\n", (gpointer) (gsize) mono_native_thread_id_get ());
10132 debugger_thread_id = mono_native_thread_id_get ();
10134 MonoThread *thread = mono_thread_attach (mono_get_root_domain ());
10135 mono_thread_set_name_internal (thread->internal_thread, mono_string_new (mono_get_root_domain (), "Debugger agent"), TRUE, FALSE, &error);
10136 mono_error_assert_ok (&error);
10138 thread->internal_thread->state |= ThreadState_Background;
10139 thread->internal_thread->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
10141 if (agent_config.defer) {
10142 if (!wait_for_attach ()) {
10143 DEBUG_PRINTF (1, "[dbg] Can't attach, aborting debugger thread.\n");
10144 attach_failed = TRUE; // Don't abort process when we can't listen
10146 mono_set_is_debugger_attached (TRUE);
10147 /* Send start event to client */
10148 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
10151 mono_set_is_debugger_attached (TRUE);
10154 while (!attach_failed) {
10155 res = transport_recv (header, HEADER_LENGTH);
10157 /* This will break if the socket is closed during shutdown too */
10158 if (res != HEADER_LENGTH) {
10159 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH);
10164 end = header + HEADER_LENGTH;
10166 len = decode_int (p, &p, end);
10167 id = decode_int (p, &p, end);
10168 flags = decode_byte (p, &p, end);
10169 command_set = (CommandSet)decode_byte (p, &p, end);
10170 command = decode_byte (p, &p, end);
10172 g_assert (flags == 0);
10175 const char *cmd_str;
10176 char cmd_num [256];
10178 cmd_str = cmd_to_string (command_set, command);
10180 sprintf (cmd_num, "%d", command);
10184 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);
10187 data = (guint8 *)g_malloc (len - HEADER_LENGTH);
10188 if (len - HEADER_LENGTH > 0)
10190 res = transport_recv (data, len - HEADER_LENGTH);
10191 if (res != len - HEADER_LENGTH) {
10192 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH);
10198 end = data + (len - HEADER_LENGTH);
10200 buffer_init (&buf, 128);
10205 /* Process the request */
10206 switch (command_set) {
10208 err = vm_commands (command, id, p, end, &buf);
10209 if (err == ERR_NONE && command == CMD_VM_INVOKE_METHOD)
10210 /* Sent after the invoke is complete */
10213 case CMD_SET_EVENT_REQUEST:
10214 err = event_commands (command, p, end, &buf);
10216 case CMD_SET_APPDOMAIN:
10217 err = domain_commands (command, p, end, &buf);
10219 case CMD_SET_ASSEMBLY:
10220 err = assembly_commands (command, p, end, &buf);
10222 case CMD_SET_MODULE:
10223 err = module_commands (command, p, end, &buf);
10225 case CMD_SET_FIELD:
10226 err = field_commands (command, p, end, &buf);
10229 err = type_commands (command, p, end, &buf);
10231 case CMD_SET_METHOD:
10232 err = method_commands (command, p, end, &buf);
10234 case CMD_SET_THREAD:
10235 err = thread_commands (command, p, end, &buf);
10237 case CMD_SET_STACK_FRAME:
10238 err = frame_commands (command, p, end, &buf);
10240 case CMD_SET_ARRAY_REF:
10241 err = array_commands (command, p, end, &buf);
10243 case CMD_SET_STRING_REF:
10244 err = string_commands (command, p, end, &buf);
10246 case CMD_SET_OBJECT_REF:
10247 err = object_commands (command, p, end, &buf);
10250 err = ERR_NOT_IMPLEMENTED;
10253 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
10254 buffer_replies = TRUE;
10258 if (buffer_replies) {
10259 buffer_reply_packet (id, err, &buf);
10261 send_reply_packet (id, err, &buf);
10262 //DEBUG_PRINTF (1, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000);
10266 if (err == ERR_NONE && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
10267 send_buffered_reply_packets ();
10268 buffer_replies = FALSE;
10272 buffer_free (&buf);
10274 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
10278 mono_set_is_debugger_attached (FALSE);
10280 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
10281 debugger_thread_exited = TRUE;
10282 mono_coop_cond_signal (&debugger_thread_exited_cond);
10283 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
10285 DEBUG_PRINTF (1, "[dbg] Debugger thread exited.\n");
10287 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
10288 DEBUG_PRINTF (2, "[dbg] Detached - restarting clean debugger thread.\n");
10289 start_debugger_thread ();
10295 #else /* DISABLE_DEBUGGER_AGENT */
10298 mono_debugger_agent_parse_options (char *options)
10300 g_error ("This runtime is configured with the debugger agent disabled.");
10304 mono_debugger_agent_init (void)
10309 mono_debugger_agent_breakpoint_hit (void *sigctx)
10314 mono_debugger_agent_single_step_event (void *sigctx)
10319 mono_debugger_agent_free_domain_info (MonoDomain *domain)
10324 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
10325 MonoContext *catch_ctx)
10330 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
10335 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
10340 mono_debugger_agent_user_break (void)
10346 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
10351 mono_debugger_agent_debug_log_is_enabled (void)
10357 mono_debugger_agent_unhandled_exception (MonoException *exc)
10359 g_assert_not_reached ();
10363 debugger_agent_single_step_from_context (MonoContext *ctx)
10365 g_assert_not_reached ();
10369 debugger_agent_breakpoint_from_context (MonoContext *ctx)
10371 g_assert_not_reached ();