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 MonoInternalThread *internal;
823 internal = mono_thread_internal_current ();
827 return internal->debugger_thread;
831 parse_address (char *address, char **host, int *port)
833 char *pos = strchr (address, ':');
835 if (pos == NULL || pos == address)
838 size_t len = pos - address;
839 *host = (char *)g_malloc (len + 1);
840 memcpy (*host, address, len);
841 (*host) [len] = '\0';
843 *port = atoi (pos + 1);
851 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
852 fprintf (stderr, "Available options:\n");
853 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
854 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
855 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
856 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
857 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
858 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
859 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
860 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
861 fprintf (stderr, " setpgid=y/n\t\t\tWhether to call setpid(0, 0) after startup.\n");
862 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
866 parse_flag (const char *option, char *flag)
868 if (!strcmp (flag, "y"))
870 else if (!strcmp (flag, "n"))
873 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
880 mono_debugger_agent_parse_options (char *options)
887 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
888 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
892 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
894 options = g_strdup_printf ("%s,%s", options, extra);
896 agent_config.enabled = TRUE;
897 agent_config.suspend = TRUE;
898 agent_config.server = FALSE;
899 agent_config.defer = FALSE;
900 agent_config.address = NULL;
902 //agent_config.log_level = 10;
904 args = g_strsplit (options, ",", -1);
905 for (ptr = args; ptr && *ptr; ptr ++) {
908 if (strncmp (arg, "transport=", 10) == 0) {
909 agent_config.transport = g_strdup (arg + 10);
910 } else if (strncmp (arg, "address=", 8) == 0) {
911 agent_config.address = g_strdup (arg + 8);
912 } else if (strncmp (arg, "loglevel=", 9) == 0) {
913 agent_config.log_level = atoi (arg + 9);
914 } else if (strncmp (arg, "logfile=", 8) == 0) {
915 agent_config.log_file = g_strdup (arg + 8);
916 } else if (strncmp (arg, "suspend=", 8) == 0) {
917 agent_config.suspend = parse_flag ("suspend", arg + 8);
918 } else if (strncmp (arg, "server=", 7) == 0) {
919 agent_config.server = parse_flag ("server", arg + 7);
920 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
921 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
922 } else if (strncmp (arg, "onthrow=", 8) == 0) {
923 /* We support multiple onthrow= options */
924 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
925 } else if (strncmp (arg, "onthrow", 7) == 0) {
926 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
927 } else if (strncmp (arg, "help", 4) == 0) {
930 } else if (strncmp (arg, "timeout=", 8) == 0) {
931 agent_config.timeout = atoi (arg + 8);
932 } else if (strncmp (arg, "launch=", 7) == 0) {
933 agent_config.launch = g_strdup (arg + 7);
934 } else if (strncmp (arg, "embedding=", 10) == 0) {
935 agent_config.embedding = atoi (arg + 10) == 1;
936 } else if (strncmp (arg, "keepalive=", 10) == 0) {
937 agent_config.keepalive = atoi (arg + 10);
938 } else if (strncmp (arg, "setpgid=", 8) == 0) {
939 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
946 if (agent_config.server && !agent_config.suspend) {
947 /* Waiting for deferred attachment */
948 agent_config.defer = TRUE;
949 if (agent_config.address == NULL) {
950 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (mono_process_current_pid () % 1000));
954 //agent_config.log_level = 0;
956 if (agent_config.transport == NULL) {
957 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
961 if (agent_config.address == NULL && !agent_config.server) {
962 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
967 if (!strcmp (agent_config.transport, "dt_socket")) {
968 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
969 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
976 mono_debugger_agent_init (void)
978 mono_coop_mutex_init_recursive (&debug_mutex);
980 if (!agent_config.enabled)
985 /* Need to know whenever a thread has acquired the loader mutex */
986 mono_loader_lock_track_ownership (TRUE);
988 event_requests = g_ptr_array_new ();
990 mono_coop_mutex_init (&debugger_thread_exited_mutex);
991 mono_coop_cond_init (&debugger_thread_exited_cond);
993 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
994 mono_profiler_set_events ((MonoProfileFlags)(MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS));
995 mono_profiler_install_runtime_initialized (runtime_initialized);
996 mono_profiler_install_appdomain (NULL, appdomain_load, appdomain_start_unload, appdomain_unload);
997 mono_profiler_install_thread (thread_startup, thread_end);
998 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
999 mono_profiler_install_jit_end (jit_end);
1001 mono_native_tls_alloc (&debugger_tls_id, NULL);
1003 /* Needed by the hash_table_new_type () call below */
1004 mono_gc_base_init ();
1006 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");
1008 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread table");
1010 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");
1012 pending_assembly_loads = g_ptr_array_new ();
1013 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
1015 log_level = agent_config.log_level;
1017 embedding = agent_config.embedding;
1018 disconnected = TRUE;
1020 if (agent_config.log_file) {
1021 log_file = fopen (agent_config.log_file, "w+");
1023 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
1032 breakpoints_init ();
1035 mini_get_debug_options ()->gen_sdb_seq_points = TRUE;
1037 * This is needed because currently we don't handle liveness info.
1039 mini_get_debug_options ()->mdb_optimizations = TRUE;
1041 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
1042 /* This is needed because we can't set local variables in registers yet */
1043 mono_disable_optimizations (MONO_OPT_LINEARS);
1047 * The stack walk done from thread_interrupt () needs to be signal safe, but it
1048 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
1049 * safe (#3411). So load AOT info eagerly when the debugger is running as a
1052 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
1055 if (agent_config.setpgid)
1059 if (!agent_config.onuncaught && !agent_config.onthrow)
1060 finish_agent_init (TRUE);
1064 * finish_agent_init:
1066 * Finish the initialization of the agent. This involves connecting the transport
1067 * and starting the agent thread. This is either done at startup, or
1068 * in response to some event like an unhandled exception.
1071 finish_agent_init (gboolean on_startup)
1075 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
1078 if (agent_config.launch) {
1081 // FIXME: Generated address
1082 // FIXME: Races with transport_connect ()
1084 argv [0] = agent_config.launch;
1085 argv [1] = agent_config.transport;
1086 argv [2] = agent_config.address;
1089 res = g_spawn_async_with_pipes (NULL, argv, NULL, (GSpawnFlags)0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1091 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1096 transport_connect (agent_config.address);
1099 /* Do some which is usually done after sending the VMStart () event */
1100 vm_start_event_sent = TRUE;
1101 start_debugger_thread ();
1106 mono_debugger_agent_cleanup (void)
1111 stop_debugger_thread ();
1113 breakpoints_cleanup ();
1122 #ifndef DISABLE_SOCKET_TRANSPORT
1127 * recv() + handle incomplete reads and EINTR
1130 socket_transport_recv (void *buf, int len)
1136 static gint64 last_keepalive;
1143 res = recv (fd, (char *) buf + total, len - total, flags);
1146 if (agent_config.keepalive) {
1147 gboolean need_keepalive = FALSE;
1148 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1149 need_keepalive = TRUE;
1150 } else if (res == -1) {
1151 /* This could happen if recv () is interrupted repeatedly */
1152 msecs = mono_msec_ticks ();
1153 if (msecs - last_keepalive >= agent_config.keepalive) {
1154 need_keepalive = TRUE;
1155 last_keepalive = msecs;
1158 if (need_keepalive) {
1159 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1163 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1171 set_keepalive (void)
1176 if (!agent_config.keepalive || !conn_fd)
1179 tv.tv_sec = agent_config.keepalive / 1000;
1180 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1182 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1183 g_assert (result >= 0);
1187 socket_transport_accept (int socket_fd)
1190 conn_fd = accept (socket_fd, NULL, NULL);
1193 if (conn_fd == -1) {
1194 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1196 DEBUG_PRINTF (1, "Accepted connection from client, connection fd=%d.\n", conn_fd);
1203 socket_transport_send (void *data, int len)
1210 res = send (conn_fd, data, len, 0);
1211 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1222 * socket_transport_connect:
1224 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1227 socket_transport_connect (const char *address)
1229 MonoAddressInfo *result;
1230 MonoAddressEntry *rp;
1231 int sfd = -1, s, res;
1235 if (agent_config.address) {
1236 res = parse_address (agent_config.address, &host, &port);
1237 g_assert (res == 0);
1248 mono_network_init ();
1250 /* Obtain address(es) matching host/port */
1251 s = mono_get_address_info (host, port, MONO_HINT_UNSPECIFIED, &result);
1253 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, s); // FIXME add portable error conversion functions
1258 if (agent_config.server) {
1259 /* Wait for a connection */
1261 struct sockaddr_in addr;
1264 /* No address, generate one */
1265 sfd = socket (AF_INET, SOCK_STREAM, 0);
1268 /* This will bind the socket to a random port */
1269 res = listen (sfd, 16);
1271 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1276 addrlen = sizeof (addr);
1277 memset (&addr, 0, sizeof (addr));
1278 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1279 g_assert (res == 0);
1281 host = (char*)"127.0.0.1";
1282 port = ntohs (addr.sin_port);
1284 /* Emit the address to stdout */
1285 /* FIXME: Should print another interface, not localhost */
1286 printf ("%s:%d\n", host, port);
1288 /* Listen on the provided address */
1289 for (rp = result->entries; rp != NULL; rp = rp->next) {
1290 MonoSocketAddress sockaddr;
1294 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1296 sfd = socket (rp->family, rp->socktype,
1301 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1304 res = bind (sfd, &sockaddr.addr, sock_len);
1308 res = listen (sfd, 16);
1315 mono_free_address_info (result);
1318 if (agent_config.defer)
1321 DEBUG_PRINTF (1, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout);
1323 if (agent_config.timeout) {
1328 tv.tv_usec = agent_config.timeout * 1000;
1330 FD_SET (sfd, &readfds);
1333 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1337 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1342 conn_fd = socket_transport_accept (sfd);
1346 DEBUG_PRINTF (1, "Accepted connection from client, socket fd=%d.\n", conn_fd);
1348 /* Connect to the specified address */
1349 /* FIXME: Respect the timeout */
1350 for (rp = result->entries; rp != NULL; rp = rp->next) {
1351 MonoSocketAddress sockaddr;
1354 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1356 sfd = socket (rp->family, rp->socktype,
1362 res = connect (sfd, &sockaddr.addr, sock_len);
1366 break; /* Success */
1374 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1380 mono_free_address_info (result);
1383 if (!transport_handshake ())
1388 socket_transport_close1 (void)
1390 /* This will interrupt the agent thread */
1391 /* Close the read part only so it can still send back replies */
1392 /* Also shut down the connection listener so that we can exit normally */
1394 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1395 shutdown (conn_fd, SD_BOTH);
1396 shutdown (listen_fd, SD_BOTH);
1397 closesocket (listen_fd);
1399 shutdown (conn_fd, SHUT_RD);
1400 shutdown (listen_fd, SHUT_RDWR);
1408 socket_transport_close2 (void)
1411 shutdown (conn_fd, SD_BOTH);
1413 shutdown (conn_fd, SHUT_RDWR);
1418 register_socket_transport (void)
1420 DebuggerTransport trans;
1422 trans.name = "dt_socket";
1423 trans.connect = socket_transport_connect;
1424 trans.close1 = socket_transport_close1;
1425 trans.close2 = socket_transport_close2;
1426 trans.send = socket_transport_send;
1427 trans.recv = socket_transport_recv;
1429 register_transport (&trans);
1433 * socket_fd_transport_connect:
1437 socket_fd_transport_connect (const char *address)
1441 res = sscanf (address, "%d", &conn_fd);
1443 fprintf (stderr, "debugger-agent: socket-fd transport address is invalid: '%s'\n", address);
1447 if (!transport_handshake ())
1452 register_socket_fd_transport (void)
1454 DebuggerTransport trans;
1456 /* This is the same as the 'dt_socket' transport, but receives an already connected socket fd */
1457 trans.name = "socket-fd";
1458 trans.connect = socket_fd_transport_connect;
1459 trans.close1 = socket_transport_close1;
1460 trans.close2 = socket_transport_close2;
1461 trans.send = socket_transport_send;
1462 trans.recv = socket_transport_recv;
1464 register_transport (&trans);
1467 #endif /* DISABLE_SOCKET_TRANSPORT */
1473 #define MAX_TRANSPORTS 16
1475 static DebuggerTransport *transport;
1477 static DebuggerTransport transports [MAX_TRANSPORTS];
1478 static int ntransports;
1481 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1484 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1486 register_transport (trans);
1490 register_transport (DebuggerTransport *trans)
1492 g_assert (ntransports < MAX_TRANSPORTS);
1494 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1499 transport_init (void)
1503 #ifndef DISABLE_SOCKET_TRANSPORT
1504 register_socket_transport ();
1505 register_socket_fd_transport ();
1508 for (i = 0; i < ntransports; ++i) {
1509 if (!strcmp (agent_config.transport, transports [i].name))
1512 if (i == ntransports) {
1513 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1514 for (i = 0; i < ntransports; ++i)
1515 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1516 fprintf (stderr, "\n");
1519 transport = &transports [i];
1523 transport_connect (const char *address)
1525 transport->connect (address);
1529 transport_close1 (void)
1531 transport->close1 ();
1535 transport_close2 (void)
1537 transport->close2 ();
1541 transport_send (void *buf, int len)
1543 return transport->send (buf, len);
1547 transport_recv (void *buf, int len)
1549 return transport->recv (buf, len);
1553 mono_debugger_agent_transport_handshake (void)
1555 return transport_handshake ();
1559 transport_handshake (void)
1561 char handshake_msg [128];
1565 disconnected = TRUE;
1567 /* Write handshake message */
1568 sprintf (handshake_msg, "DWP-Handshake");
1571 res = transport_send (handshake_msg, strlen (handshake_msg));
1572 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1574 g_assert (res != -1);
1577 res = transport_recv (buf, strlen (handshake_msg));
1578 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg)) != 0)) {
1579 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1584 * To support older clients, the client sends its protocol version after connecting
1585 * using a command. Until that is received, default to our protocol version.
1587 major_version = MAJOR_VERSION;
1588 minor_version = MINOR_VERSION;
1589 protocol_version_set = FALSE;
1591 #ifndef DISABLE_SOCKET_TRANSPORT
1592 // FIXME: Move this somewhere else
1594 * Set TCP_NODELAY on the socket so the client receives events/command
1595 * results immediately.
1599 int result = setsockopt (conn_fd,
1604 g_assert (result >= 0);
1610 disconnected = FALSE;
1615 stop_debugger_thread (void)
1620 transport_close1 ();
1623 * Wait for the thread to exit.
1625 * If we continue with the shutdown without waiting for it, then the client might
1626 * not receive an answer to its last command like a resume.
1628 if (!is_debugger_thread ()) {
1630 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
1631 if (!debugger_thread_exited)
1632 mono_coop_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1633 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
1634 } while (!debugger_thread_exited);
1637 transport_close2 ();
1641 start_debugger_thread (void)
1644 MonoInternalThread *thread;
1646 thread = mono_thread_create_internal (mono_get_root_domain (), debugger_thread, NULL, MONO_THREAD_CREATE_FLAGS_DEBUGGER, &error);
1647 mono_error_assert_ok (&error);
1649 debugger_thread_handle = mono_threads_open_thread_handle (thread->handle);
1650 g_assert (debugger_thread_handle);
1654 * Functions to decode protocol data
1658 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1661 g_assert (*endbuf <= limit);
1666 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1669 g_assert (*endbuf <= limit);
1671 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1674 static inline gint64
1675 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1677 guint32 high = decode_int (buf, &buf, limit);
1678 guint32 low = decode_int (buf, &buf, limit);
1682 return ((((guint64)high) << 32) | ((guint64)low));
1686 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1688 return decode_int (buf, endbuf, limit);
1692 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1694 int len = decode_int (buf, &buf, limit);
1702 s = (char *)g_malloc (len + 1);
1705 memcpy (s, buf, len);
1714 * Functions to encode protocol data
1718 buffer_init (Buffer *buf, int size)
1720 buf->buf = (guint8 *)g_malloc (size);
1722 buf->end = buf->buf + size;
1726 buffer_len (Buffer *buf)
1728 return buf->p - buf->buf;
1732 buffer_make_room (Buffer *buf, int size)
1734 if (buf->end - buf->p < size) {
1735 int new_size = buf->end - buf->buf + size + 32;
1736 guint8 *p = (guint8 *)g_realloc (buf->buf, new_size);
1737 size = buf->p - buf->buf;
1740 buf->end = buf->buf + new_size;
1745 buffer_add_byte (Buffer *buf, guint8 val)
1747 buffer_make_room (buf, 1);
1753 buffer_add_short (Buffer *buf, guint32 val)
1755 buffer_make_room (buf, 2);
1756 buf->p [0] = (val >> 8) & 0xff;
1757 buf->p [1] = (val >> 0) & 0xff;
1762 buffer_add_int (Buffer *buf, guint32 val)
1764 buffer_make_room (buf, 4);
1765 buf->p [0] = (val >> 24) & 0xff;
1766 buf->p [1] = (val >> 16) & 0xff;
1767 buf->p [2] = (val >> 8) & 0xff;
1768 buf->p [3] = (val >> 0) & 0xff;
1773 buffer_add_long (Buffer *buf, guint64 l)
1775 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1776 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1780 buffer_add_id (Buffer *buf, int id)
1782 buffer_add_int (buf, (guint64)id);
1786 buffer_add_data (Buffer *buf, guint8 *data, int len)
1788 buffer_make_room (buf, len);
1789 memcpy (buf->p, data, len);
1794 buffer_add_string (Buffer *buf, const char *str)
1799 buffer_add_int (buf, 0);
1802 buffer_add_int (buf, len);
1803 buffer_add_data (buf, (guint8*)str, len);
1808 buffer_add_buffer (Buffer *buf, Buffer *data)
1810 buffer_add_data (buf, data->buf, buffer_len (data));
1814 buffer_free (Buffer *buf)
1820 send_packet (int command_set, int command, Buffer *data)
1826 id = InterlockedIncrement (&packet_id);
1828 len = data->p - data->buf + 11;
1829 buffer_init (&buf, len);
1830 buffer_add_int (&buf, len);
1831 buffer_add_int (&buf, id);
1832 buffer_add_byte (&buf, 0); /* flags */
1833 buffer_add_byte (&buf, command_set);
1834 buffer_add_byte (&buf, command);
1835 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1837 res = transport_send (buf.buf, len);
1845 send_reply_packets (int npackets, ReplyPacket *packets)
1852 for (i = 0; i < npackets; ++i)
1853 len += buffer_len (packets [i].data) + 11;
1854 buffer_init (&buf, len);
1855 for (i = 0; i < npackets; ++i) {
1856 buffer_add_int (&buf, buffer_len (packets [i].data) + 11);
1857 buffer_add_int (&buf, packets [i].id);
1858 buffer_add_byte (&buf, 0x80); /* flags */
1859 buffer_add_byte (&buf, (packets [i].error >> 8) & 0xff);
1860 buffer_add_byte (&buf, packets [i].error);
1861 buffer_add_buffer (&buf, packets [i].data);
1864 res = transport_send (buf.buf, len);
1872 send_reply_packet (int id, int error, Buffer *data)
1876 memset (&packet, 0, sizeof (ReplyPacket));
1878 packet.error = error;
1881 return send_reply_packets (1, &packet);
1885 send_buffered_reply_packets (void)
1889 send_reply_packets (nreply_packets, reply_packets);
1890 for (i = 0; i < nreply_packets; ++i)
1891 buffer_free (reply_packets [i].data);
1892 DEBUG_PRINTF (1, "[dbg] Sent %d buffered reply packets [at=%lx].\n", nreply_packets, (long)mono_100ns_ticks () / 10000);
1897 buffer_reply_packet (int id, int error, Buffer *data)
1901 if (nreply_packets == 128)
1902 send_buffered_reply_packets ();
1904 p = &reply_packets [nreply_packets];
1907 p->data = g_new0 (Buffer, 1);
1908 buffer_init (p->data, buffer_len (data));
1909 buffer_add_buffer (p->data, data);
1918 * Represents an object accessible by the debugger client.
1921 /* Unique id used in the wire protocol to refer to objects */
1924 * A weakref gc handle pointing to the object. The gc handle is used to
1925 * detect if the object was garbage collected.
1930 /* Maps objid -> ObjRef */
1931 /* Protected by the loader lock */
1932 static GHashTable *objrefs;
1933 /* Protected by the loader lock */
1934 static GHashTable *obj_to_objref;
1935 /* Protected by the dbg lock */
1936 static MonoGHashTable *suspended_objs;
1939 free_objref (gpointer value)
1941 ObjRef *o = (ObjRef *)value;
1943 mono_gchandle_free (o->handle);
1951 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1952 obj_to_objref = g_hash_table_new (NULL, NULL);
1953 suspended_objs = mono_g_hash_table_new_type ((GHashFunc)mono_object_hash, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_DEBUGGER, "suspended objects table");
1957 objrefs_cleanup (void)
1959 g_hash_table_destroy (objrefs);
1964 * Return an ObjRef for OBJ.
1967 get_objref (MonoObject *obj)
1970 GSList *reflist = NULL, *l;
1976 if (suspend_count) {
1978 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1981 mono_g_hash_table_insert (suspended_objs, obj, NULL);
1985 mono_loader_lock ();
1987 /* FIXME: The tables can grow indefinitely */
1989 if (mono_gc_is_moving ()) {
1991 * Objects can move, so use a hash table mapping hash codes to lists of
1992 * ObjRef structures.
1994 hash = mono_object_hash (obj);
1996 reflist = (GSList *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1997 for (l = reflist; l; l = l->next) {
1998 ref = (ObjRef *)l->data;
1999 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
2000 mono_loader_unlock ();
2005 /* Use a hash table with masked pointers to internalize object references */
2006 ref = (ObjRef *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
2007 /* ref might refer to a different object with the same addr which was GCd */
2008 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
2009 mono_loader_unlock ();
2014 ref = g_new0 (ObjRef, 1);
2015 ref->id = InterlockedIncrement (&objref_id);
2016 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
2018 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
2020 if (mono_gc_is_moving ()) {
2021 reflist = g_slist_append (reflist, ref);
2022 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
2024 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
2027 mono_loader_unlock ();
2033 true_pred (gpointer key, gpointer value, gpointer user_data)
2039 clear_suspended_objs (void)
2042 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
2047 get_objid (MonoObject *obj)
2052 return get_objref (obj)->id;
2056 * Set OBJ to the object identified by OBJID.
2057 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
2061 get_object_allow_null (int objid, MonoObject **obj)
2071 return ERR_INVALID_OBJECT;
2073 mono_loader_lock ();
2075 ref = (ObjRef *)g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
2078 *obj = mono_gchandle_get_target (ref->handle);
2079 mono_loader_unlock ();
2081 return ERR_INVALID_OBJECT;
2084 mono_loader_unlock ();
2085 return ERR_INVALID_OBJECT;
2090 get_object (int objid, MonoObject **obj)
2092 ErrorCode err = get_object_allow_null (objid, obj);
2094 if (err != ERR_NONE)
2097 return ERR_INVALID_OBJECT;
2102 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
2104 return decode_id (buf, endbuf, limit);
2108 buffer_add_objid (Buffer *buf, MonoObject *o)
2110 buffer_add_id (buf, get_objid (o));
2129 * Represents a runtime structure accessible to the debugger client
2132 /* Unique id used in the wire protocol */
2134 /* Domain of the runtime structure, NULL if the domain was unloaded */
2141 MonoAssembly *assembly;
2142 MonoClassField *field;
2144 MonoProperty *property;
2149 /* Maps runtime structure -> Id */
2150 /* Protected by the dbg lock */
2151 GHashTable *val_to_id [ID_NUM];
2152 /* Classes whose class load event has been sent */
2153 /* Protected by the loader lock */
2154 GHashTable *loaded_classes;
2155 /* Maps MonoClass->GPtrArray of file names */
2156 GHashTable *source_files;
2157 /* Maps source file basename -> GSList of classes */
2158 GHashTable *source_file_to_class;
2159 /* Same with ignore-case */
2160 GHashTable *source_file_to_class_ignorecase;
2164 /* Protected by the dbg lock */
2165 static GPtrArray *ids [ID_NUM];
2172 for (i = 0; i < ID_NUM; ++i)
2173 ids [i] = g_ptr_array_new ();
2181 for (i = 0; i < ID_NUM; ++i) {
2183 for (j = 0; j < ids [i]->len; ++j)
2184 g_free (g_ptr_array_index (ids [i], j));
2185 g_ptr_array_free (ids [i], TRUE);
2192 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2194 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2196 GHashTableIter iter;
2197 GPtrArray *file_names;
2202 for (i = 0; i < ID_NUM; ++i)
2203 if (info->val_to_id [i])
2204 g_hash_table_destroy (info->val_to_id [i]);
2205 g_hash_table_destroy (info->loaded_classes);
2207 g_hash_table_iter_init (&iter, info->source_files);
2208 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2209 for (i = 0; i < file_names->len; ++i)
2210 g_free (g_ptr_array_index (file_names, i));
2211 g_ptr_array_free (file_names, TRUE);
2214 g_hash_table_iter_init (&iter, info->source_file_to_class);
2215 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2220 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2221 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2229 domain_jit_info (domain)->agent_info = NULL;
2231 /* Clear ids referencing structures in the domain */
2233 for (i = 0; i < ID_NUM; ++i) {
2235 for (j = 0; j < ids [i]->len; ++j) {
2236 Id *id = (Id *)g_ptr_array_index (ids [i], j);
2237 if (id->domain == domain)
2244 mono_loader_lock ();
2245 g_hash_table_remove (domains, domain);
2246 mono_loader_unlock ();
2249 static AgentDomainInfo*
2250 get_agent_domain_info (MonoDomain *domain)
2252 AgentDomainInfo *info = NULL;
2254 mono_domain_lock (domain);
2256 info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2258 info = g_new0 (AgentDomainInfo, 1);
2259 domain_jit_info (domain)->agent_info = info;
2260 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2261 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2262 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2263 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2266 mono_domain_unlock (domain);
2272 get_id (MonoDomain *domain, IdType type, gpointer val)
2275 AgentDomainInfo *info;
2280 info = get_agent_domain_info (domain);
2284 if (info->val_to_id [type] == NULL)
2285 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2287 id = (Id *)g_hash_table_lookup (info->val_to_id [type], val);
2293 id = g_new0 (Id, 1);
2295 id->id = ids [type]->len + 1;
2296 id->domain = domain;
2299 g_hash_table_insert (info->val_to_id [type], val, id);
2300 g_ptr_array_add (ids [type], id);
2307 static inline gpointer
2308 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, ErrorCode *err)
2312 int id = decode_id (buf, endbuf, limit);
2321 // FIXME: error handling
2323 g_assert (id > 0 && id <= ids [type]->len);
2325 res = (Id *)g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2328 if (res->domain == NULL || res->domain->state == MONO_APPDOMAIN_UNLOADED) {
2329 DEBUG_PRINTF (1, "ERR_UNLOADED, id=%d, type=%d.\n", id, type);
2330 *err = ERR_UNLOADED;
2335 *domain = res->domain;
2337 return res->data.val;
2341 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2343 int id = get_id (domain, type, val);
2345 buffer_add_id (buf, id);
2349 static inline MonoClass*
2350 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2354 klass = (MonoClass *)decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2355 if (G_UNLIKELY (log_level >= 2) && klass) {
2358 s = mono_type_full_name (&klass->byval_arg);
2359 DEBUG_PRINTF (2, "[dbg] recv class [%s]\n", s);
2365 static inline MonoAssembly*
2366 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2368 return (MonoAssembly *)decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2371 static inline MonoImage*
2372 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2374 return (MonoImage *)decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2377 static inline MonoMethod*
2378 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2382 m = (MonoMethod *)decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2383 if (G_UNLIKELY (log_level >= 2) && m) {
2386 s = mono_method_full_name (m, TRUE);
2387 DEBUG_PRINTF (2, "[dbg] recv method [%s]\n", s);
2393 static inline MonoClassField*
2394 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2396 return (MonoClassField *)decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2399 static inline MonoDomain*
2400 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2402 return (MonoDomain *)decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2405 static inline MonoProperty*
2406 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2408 return (MonoProperty *)decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2412 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2414 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2415 if (G_UNLIKELY (log_level >= 2) && klass) {
2418 s = mono_type_full_name (&klass->byval_arg);
2419 if (is_debugger_thread ())
2420 DEBUG_PRINTF (2, "[dbg] send class [%s]\n", s);
2422 DEBUG_PRINTF (2, "[%p] send class [%s]\n", (gpointer) (gsize) mono_native_thread_id_get (), s);
2428 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2430 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2431 if (G_UNLIKELY (log_level >= 2) && method) {
2434 s = mono_method_full_name (method, 1);
2435 DEBUG_PRINTF (2, "[dbg] send method [%s]\n", s);
2441 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2445 id = buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2446 if (G_UNLIKELY (log_level >= 2) && assembly)
2447 DEBUG_PRINTF (2, "[dbg] send assembly [%s][%s][%d]\n", assembly->aname.name, domain->friendly_name, id);
2451 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2453 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2457 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2459 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2463 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2465 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2469 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2471 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2474 static void invoke_method (void);
2481 * save_thread_context:
2483 * Set CTX as the current threads context which is used for computing stack traces.
2484 * This function is signal-safe.
2487 save_thread_context (MonoContext *ctx)
2489 DebuggerTlsData *tls;
2491 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2495 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2497 mono_thread_state_init_from_current (&tls->context);
2500 /* Number of threads suspended */
2502 * If this is equal to the size of thread_to_tls, the runtime is considered
2505 static gint32 threads_suspend_count;
2507 static MonoCoopMutex suspend_mutex;
2509 /* Cond variable used to wait for suspend_count becoming 0 */
2510 static MonoCoopCond suspend_cond;
2512 /* Semaphore used to wait for a thread becoming suspended */
2513 static MonoCoopSem suspend_sem;
2518 mono_coop_mutex_init (&suspend_mutex);
2519 mono_coop_cond_init (&suspend_cond);
2520 mono_coop_sem_init (&suspend_sem, 0);
2525 StackFrameInfo last_frame;
2526 gboolean last_frame_set;
2530 } GetLastFrameUserData;
2533 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2535 GetLastFrameUserData *data = (GetLastFrameUserData *)user_data;
2537 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE || info->type == FRAME_TYPE_TRAMPOLINE)
2540 if (!data->last_frame_set) {
2541 /* Store the last frame */
2542 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2543 data->last_frame_set = TRUE;
2546 /* Store the context/lmf for the frame above the last frame */
2547 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2548 data->lmf = info->lmf;
2549 data->domain = info->domain;
2555 copy_unwind_state_from_frame_data (MonoThreadUnwindState *to, GetLastFrameUserData *data, gpointer jit_tls)
2557 memcpy (&to->ctx, &data->ctx, sizeof (MonoContext));
2559 to->unwind_data [MONO_UNWIND_DATA_DOMAIN] = data->domain;
2560 to->unwind_data [MONO_UNWIND_DATA_LMF] = data->lmf;
2561 to->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = jit_tls;
2568 * Process interruption of a thread. This should be signal safe.
2570 * This always runs in the debugger thread.
2573 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, MonoJitInfo *ji)
2576 MonoNativeThreadId tid;
2580 ip = MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx);
2581 tid = mono_thread_info_get_tid (info);
2583 // FIXME: Races when the thread leaves managed code before hitting a single step
2586 if (ji && !ji->is_trampoline) {
2587 /* Running managed code, will be suspended by the single step code */
2588 DEBUG_PRINTF (1, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip);
2591 * Running native code, will be suspended when it returns to/enters
2592 * managed code. Treat it as already suspended.
2593 * This might interrupt the code in process_single_step_inner (), we use the
2594 * tls->suspending flag to avoid races when that happens.
2596 if (!tls->suspended && !tls->suspending) {
2597 GetLastFrameUserData data;
2599 // FIXME: printf is not signal safe, but this is only used during
2600 // debugger debugging
2602 DEBUG_PRINTF (1, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip);
2603 //save_thread_context (&ctx);
2606 /* Already terminated */
2610 * We are in a difficult position: we want to be able to provide stack
2611 * traces for this thread, but we can't use the current ctx+lmf, since
2612 * the thread is still running, so it might return to managed code,
2613 * making these invalid.
2614 * So we start a stack walk and save the first frame, along with the
2615 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2616 * suspended when it returns to managed code, so the parent's ctx should
2619 data.last_frame_set = FALSE;
2620 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, mono_thread_info_get_suspend_state (info), MONO_UNWIND_SIGNAL_SAFE, &data);
2621 if (data.last_frame_set) {
2622 gpointer jit_tls = ((MonoThreadInfo*)tls->thread->thread_info)->jit_data;
2624 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2626 copy_unwind_state_from_frame_data (&tls->async_state, &data, jit_tls);
2627 copy_unwind_state_from_frame_data (&tls->context, &data, jit_tls);
2629 tls->async_state.valid = FALSE;
2632 mono_memory_barrier ();
2634 tls->suspended = TRUE;
2635 mono_coop_sem_post (&suspend_sem);
2641 * reset_native_thread_suspend_state:
2643 * Reset the suspended flag and state on native threads
2646 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2648 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2650 if (!tls->really_suspended && tls->suspended) {
2651 tls->suspended = FALSE;
2653 * The thread might still be running if it was executing native code, so the state won't be invalided by
2654 * suspend_current ().
2656 tls->context.valid = FALSE;
2657 tls->async_state.valid = FALSE;
2658 invalidate_frames (tls);
2663 DebuggerTlsData *tls;
2664 gboolean valid_info;
2667 static SuspendThreadResult
2668 debugger_interrupt_critical (MonoThreadInfo *info, gpointer user_data)
2670 InterruptData *data = (InterruptData *)user_data;
2673 data->valid_info = TRUE;
2674 ji = mono_jit_info_table_find_internal (
2675 (MonoDomain *)mono_thread_info_get_suspend_state (info)->unwind_data [MONO_UNWIND_DATA_DOMAIN],
2676 (char *)MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx),
2680 /* This is signal safe */
2681 thread_interrupt (data->tls, info, ji);
2682 return MonoResumeThread;
2688 * Notify a thread that it needs to suspend.
2691 notify_thread (gpointer key, gpointer value, gpointer user_data)
2693 MonoInternalThread *thread = (MonoInternalThread *)key;
2694 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2695 MonoNativeThreadId tid = MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid);
2697 if (mono_thread_internal_is_current (thread) || tls->terminated)
2700 DEBUG_PRINTF (1, "[%p] Interrupting %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2702 /* This is _not_ equivalent to mono_thread_internal_abort () */
2703 InterruptData interrupt_data = { 0 };
2704 interrupt_data.tls = tls;
2706 mono_thread_info_safe_suspend_and_run ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE, debugger_interrupt_critical, &interrupt_data);
2707 if (!interrupt_data.valid_info) {
2708 DEBUG_PRINTF (1, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2710 * Attached thread which died without detaching.
2712 tls->terminated = TRUE;
2717 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2719 guint8 *ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
2723 if (mono_loader_lock_is_owned_by_self ()) {
2725 * Shortcut for the check in suspend_current (). This speeds up processing
2726 * when executing long running code inside the loader lock, i.e. assembly load
2732 if (is_debugger_thread ())
2735 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2736 if (suspend_count - tls->resume_count > 0)
2737 tls->suspending = TRUE;
2739 DEBUG_PRINTF (1, "[%p] Received single step event for suspending.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2741 if (suspend_count - tls->resume_count == 0) {
2743 * We are executing a single threaded invoke but the single step for
2744 * suspending is still active.
2745 * FIXME: This slows down single threaded invokes.
2747 DEBUG_PRINTF (1, "[%p] Ignored during single threaded invoke.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2751 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2753 /* Can't suspend in these methods */
2754 method = jinfo_get_method (ji);
2755 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2758 save_thread_context (ctx);
2766 * Increase the suspend count of the VM. While the suspend count is greater
2767 * than 0, runtime threads are suspended at certain points during execution.
2772 mono_loader_lock ();
2774 mono_coop_mutex_lock (&suspend_mutex);
2778 DEBUG_PRINTF (1, "[%p] Suspending vm...\n", (gpointer) (gsize) mono_native_thread_id_get ());
2780 if (suspend_count == 1) {
2781 // FIXME: Is it safe to call this inside the lock ?
2782 start_single_stepping ();
2783 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2786 mono_coop_mutex_unlock (&suspend_mutex);
2788 if (suspend_count == 1)
2790 * Suspend creation of new threadpool threads, since they cannot run
2792 mono_threadpool_suspend ();
2794 mono_loader_unlock ();
2800 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2806 g_assert (is_debugger_thread ());
2808 mono_loader_lock ();
2810 mono_coop_mutex_lock (&suspend_mutex);
2812 g_assert (suspend_count > 0);
2815 DEBUG_PRINTF (1, "[%p] Resuming vm, suspend count=%d...\n", (gpointer) (gsize) mono_native_thread_id_get (), suspend_count);
2817 if (suspend_count == 0) {
2818 // FIXME: Is it safe to call this inside the lock ?
2819 stop_single_stepping ();
2820 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2823 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2824 mono_coop_cond_broadcast (&suspend_cond);
2826 mono_coop_mutex_unlock (&suspend_mutex);
2827 //g_assert (err == 0);
2829 if (suspend_count == 0)
2830 mono_threadpool_resume ();
2832 mono_loader_unlock ();
2838 * Resume just one thread.
2841 resume_thread (MonoInternalThread *thread)
2843 DebuggerTlsData *tls;
2845 g_assert (is_debugger_thread ());
2847 mono_loader_lock ();
2849 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
2852 mono_coop_mutex_lock (&suspend_mutex);
2854 g_assert (suspend_count > 0);
2856 DEBUG_PRINTF (1, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid);
2858 tls->resume_count += suspend_count;
2861 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2862 * but only the one whose resume_count field is > 0 will be resumed.
2864 mono_coop_cond_broadcast (&suspend_cond);
2866 mono_coop_mutex_unlock (&suspend_mutex);
2867 //g_assert (err == 0);
2869 mono_loader_unlock ();
2873 free_frames (StackFrame **frames, int nframes)
2877 for (i = 0; i < nframes; ++i) {
2878 if (frames [i]->jit)
2879 mono_debug_free_method_jit_info (frames [i]->jit);
2880 g_free (frames [i]);
2886 invalidate_frames (DebuggerTlsData *tls)
2889 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2892 free_frames (tls->frames, tls->frame_count);
2893 tls->frame_count = 0;
2896 free_frames (tls->restore_frames, tls->restore_frame_count);
2897 tls->restore_frame_count = 0;
2898 tls->restore_frames = NULL;
2904 * Suspend the current thread until the runtime is resumed. If the thread has a
2905 * pending invoke, then the invoke is executed before this function returns.
2908 suspend_current (void)
2910 DebuggerTlsData *tls;
2912 g_assert (!is_debugger_thread ());
2914 if (mono_loader_lock_is_owned_by_self ()) {
2916 * If we own the loader mutex, can't suspend until we release it, since the
2917 * whole runtime can deadlock otherwise.
2922 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2925 mono_coop_mutex_lock (&suspend_mutex);
2927 tls->suspending = FALSE;
2928 tls->really_suspended = TRUE;
2930 if (!tls->suspended) {
2931 tls->suspended = TRUE;
2932 mono_coop_sem_post (&suspend_sem);
2935 DEBUG_PRINTF (1, "[%p] Suspended.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2937 while (suspend_count - tls->resume_count > 0) {
2938 mono_coop_cond_wait (&suspend_cond, &suspend_mutex);
2941 tls->suspended = FALSE;
2942 tls->really_suspended = FALSE;
2944 threads_suspend_count --;
2946 mono_coop_mutex_unlock (&suspend_mutex);
2948 DEBUG_PRINTF (1, "[%p] Resumed.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2950 if (tls->pending_invoke) {
2951 /* Save the original context */
2952 tls->pending_invoke->has_ctx = TRUE;
2953 tls->pending_invoke->ctx = tls->context.ctx;
2958 /* The frame info becomes invalid after a resume */
2959 tls->context.valid = FALSE;
2960 tls->async_state.valid = FALSE;
2961 invalidate_frames (tls);
2965 count_thread (gpointer key, gpointer value, gpointer user_data)
2967 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2969 if (!tls->suspended && !tls->terminated && !mono_thread_internal_is_current (tls->thread))
2970 *(int*)user_data = *(int*)user_data + 1;
2974 count_threads_to_wait_for (void)
2978 mono_loader_lock ();
2979 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2980 mono_loader_unlock ();
2988 * Wait until the runtime is completely suspended.
2991 wait_for_suspend (void)
2993 int nthreads, nwait, err;
2994 gboolean waited = FALSE;
2996 // FIXME: Threads starting/stopping ?
2997 mono_loader_lock ();
2998 nthreads = mono_g_hash_table_size (thread_to_tls);
2999 mono_loader_unlock ();
3002 nwait = count_threads_to_wait_for ();
3004 DEBUG_PRINTF (1, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads);
3005 err = mono_coop_sem_wait (&suspend_sem, MONO_SEM_FLAGS_NONE);
3006 g_assert (err == 0);
3014 DEBUG_PRINTF (1, "%d threads suspended.\n", nthreads);
3020 * Return whenever the runtime is suspended.
3025 return count_threads_to_wait_for () == 0;
3029 no_seq_points_found (MonoMethod *method, int offset)
3032 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3034 printf ("Unable to find seq points for method '%s', offset 0x%x.\n", mono_method_full_name (method, TRUE), offset);
3038 DebuggerTlsData *tls;
3040 } ComputeFramesUserData;
3043 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3045 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3047 MonoMethod *method, *actual_method, *api_method;
3051 if (info->type != FRAME_TYPE_MANAGED) {
3052 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3053 /* Mark the last frame as an invoke frame */
3055 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3061 method = jinfo_get_method (info->ji);
3063 method = info->method;
3064 actual_method = info->actual_method;
3065 api_method = method;
3070 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3073 if (info->il_offset == -1) {
3074 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3075 if (ud->frames == NULL) {
3076 if (mono_find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL, &sp))
3077 info->il_offset = sp.il_offset;
3079 if (info->il_offset == -1)
3080 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3083 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);
3085 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3086 if (!CHECK_PROTOCOL_VERSION (2, 17))
3087 /* Older clients can't handle this flag */
3089 api_method = mono_marshal_method_from_wrapper (method);
3092 actual_method = api_method;
3093 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3096 frame = g_new0 (StackFrame, 1);
3097 frame->method = method;
3098 frame->actual_method = actual_method;
3099 frame->api_method = api_method;
3100 frame->il_offset = info->il_offset;
3101 frame->native_offset = info->native_offset;
3102 frame->flags = flags;
3103 frame->ji = info->ji;
3104 if (info->reg_locations)
3105 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3108 frame->has_ctx = TRUE;
3110 frame->domain = info->domain;
3112 ud->frames = g_slist_append (ud->frames, frame);
3118 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3120 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3123 * 'tls->filter_ctx' is the location of the throw site.
3125 * mono_walk_stack() will never actually hit the throw site, but unwind
3126 * directly from the filter to the call site; we abort stack unwinding here
3127 * once this happens and resume from the throw site.
3130 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3133 return process_frame (info, ctx, user_data);
3137 * Return a malloc-ed list of StackFrame structures.
3140 compute_frame_info_from (MonoInternalThread *thread, DebuggerTlsData *tls, MonoThreadUnwindState *state, int *out_nframes)
3142 ComputeFramesUserData user_data;
3143 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3148 user_data.tls = tls;
3149 user_data.frames = NULL;
3151 mono_walk_stack_with_state (process_frame, state, opts, &user_data);
3153 nframes = g_slist_length (user_data.frames);
3154 res = g_new0 (StackFrame*, nframes);
3155 l = user_data.frames;
3156 for (i = 0; i < nframes; ++i) {
3157 res [i] = (StackFrame *)l->data;
3160 *out_nframes = nframes;
3166 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3168 ComputeFramesUserData user_data;
3170 int i, findex, new_frame_count;
3171 StackFrame **new_frames, *f;
3172 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3174 // FIXME: Locking on tls
3175 if (tls->frames && tls->frames_up_to_date)
3178 DEBUG_PRINTF (1, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid);
3180 user_data.tls = tls;
3181 user_data.frames = NULL;
3182 if (tls->terminated) {
3183 tls->frame_count = 0;
3185 } if (!tls->really_suspended && tls->async_state.valid) {
3186 /* Have to use the state saved by the signal handler */
3187 process_frame (&tls->async_last_frame, NULL, &user_data);
3188 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3189 } else if (tls->filter_state.valid) {
3191 * We are inside an exception filter.
3193 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3195 if (tls->context.valid)
3196 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3198 * After that, we resume unwinding from the location where the exception has been thrown.
3200 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3201 } else if (tls->context.valid) {
3202 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3205 tls->frame_count = 0;
3209 new_frame_count = g_slist_length (user_data.frames);
3210 new_frames = g_new0 (StackFrame*, new_frame_count);
3212 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3213 f = (StackFrame *)tmp->data;
3216 * Reuse the id for already existing stack frames, so invokes don't invalidate
3217 * the still valid stack frames.
3219 for (i = 0; i < tls->frame_count; ++i) {
3220 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3221 f->id = tls->frames [i]->id;
3226 if (i >= tls->frame_count)
3227 f->id = InterlockedIncrement (&frame_id);
3229 new_frames [findex ++] = f;
3232 g_slist_free (user_data.frames);
3234 invalidate_frames (tls);
3236 tls->frames = new_frames;
3237 tls->frame_count = new_frame_count;
3238 tls->frames_up_to_date = TRUE;
3242 * GHFunc to emit an appdomain creation event
3243 * @param key Don't care
3244 * @param value A loaded appdomain
3245 * @param user_data Don't care
3248 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3250 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3251 g_hash_table_foreach (get_agent_domain_info ((MonoDomain *)value)->loaded_classes, emit_type_load, NULL);
3255 * GHFunc to emit a thread start event
3256 * @param key A thread id
3257 * @param value A thread object
3258 * @param user_data Don't care
3261 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3263 g_assert (!mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (GPOINTER_TO_UINT (key)), debugger_thread_id));
3264 process_profiler_event (EVENT_KIND_THREAD_START, value);
3268 * GFunc to emit an assembly load event
3269 * @param value A loaded assembly
3270 * @param user_data Don't care
3273 emit_assembly_load (gpointer value, gpointer user_data)
3275 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3279 * GFunc to emit a type load event
3280 * @param value A loaded type
3281 * @param user_data Don't care
3284 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3286 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3290 strdup_tolower (char *s)
3295 for (p = s2; *p; ++p)
3301 * Same as g_path_get_basename () but handles windows paths as well,
3302 * which can occur in .mdb files created by pdb2mdb.
3305 dbg_path_get_basename (const char *filename)
3309 if (!filename || strchr (filename, '/') || !strchr (filename, '\\'))
3310 return g_path_get_basename (filename);
3314 /* No separator -> filename */
3315 r = strrchr (filename, '\\');
3317 return g_strdup (filename);
3319 /* Trailing slash, remove component */
3321 char *copy = g_strdup (filename);
3322 copy [r-filename] = 0;
3323 r = strrchr (copy, '\\');
3327 return g_strdup ("/");
3329 r = g_strdup (&r[1]);
3334 return g_strdup (&r[1]);
3338 init_jit_info_dbg_attrs (MonoJitInfo *ji)
3340 static MonoClass *hidden_klass, *step_through_klass, *non_user_klass;
3342 MonoCustomAttrInfo *ainfo;
3344 if (ji->dbg_attrs_inited)
3348 hidden_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3350 if (!step_through_klass)
3351 step_through_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3353 if (!non_user_klass)
3354 non_user_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute");
3356 ainfo = mono_custom_attrs_from_method_checked (jinfo_get_method (ji), &error);
3357 mono_error_cleanup (&error); /* FIXME don't swallow the error? */
3359 if (mono_custom_attrs_has_attr (ainfo, hidden_klass))
3360 ji->dbg_hidden = TRUE;
3361 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3362 ji->dbg_step_through = TRUE;
3363 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3364 ji->dbg_non_user_code = TRUE;
3365 mono_custom_attrs_free (ainfo);
3368 ainfo = mono_custom_attrs_from_class_checked (jinfo_get_method (ji)->klass, &error);
3369 mono_error_cleanup (&error); /* FIXME don't swallow the error? */
3371 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3372 ji->dbg_step_through = TRUE;
3373 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3374 ji->dbg_non_user_code = TRUE;
3375 mono_custom_attrs_free (ainfo);
3378 mono_memory_barrier ();
3379 ji->dbg_attrs_inited = TRUE;
3387 * create_event_list:
3389 * Return a list of event request ids matching EVENT, starting from REQS, which
3390 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3392 * We return request ids, instead of requests, to simplify threading, since
3393 * requests could be deleted anytime when the loader lock is not held.
3394 * LOCKING: Assumes the loader lock is held.
3397 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3400 GSList *events = NULL;
3402 *suspend_policy = SUSPEND_POLICY_NONE;
3405 reqs = event_requests;
3410 for (i = 0; i < reqs->len; ++i) {
3411 EventRequest *req = (EventRequest *)g_ptr_array_index (reqs, i);
3412 if (req->event_kind == event) {
3413 gboolean filtered = FALSE;
3416 for (j = 0; j < req->nmodifiers; ++j) {
3417 Modifier *mod = &req->modifiers [j];
3419 if (mod->kind == MOD_KIND_COUNT) {
3421 if (mod->data.count > 0) {
3422 if (mod->data.count > 0) {
3424 if (mod->data.count == 0)
3428 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3429 if (mod->data.thread != mono_thread_internal_current ())
3431 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3432 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3434 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3436 if (ei->caught && !mod->caught)
3438 if (!ei->caught && !mod->uncaught)
3440 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3442 gboolean found = FALSE;
3443 MonoAssembly **assemblies = mod->data.assemblies;
3446 for (k = 0; assemblies [k]; ++k)
3447 if (assemblies [k] == jinfo_get_method (ji)->klass->image->assembly)
3452 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3453 gpointer iter = NULL;
3455 MonoDebugSourceInfo *sinfo;
3456 char *source_file, *s;
3457 gboolean found = FALSE;
3459 GPtrArray *source_file_list;
3461 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3462 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3465 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, NULL, NULL, NULL);
3466 for (i = 0; i < source_file_list->len; ++i) {
3467 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
3469 * Do a case-insesitive match by converting the file name to
3472 s = strdup_tolower (sinfo->source_file);
3473 if (g_hash_table_lookup (mod->data.source_files, s))
3476 char *s2 = dbg_path_get_basename (sinfo->source_file);
3477 char *s3 = strdup_tolower (s2);
3479 if (g_hash_table_lookup (mod->data.source_files, s3))
3486 g_ptr_array_free (source_file_list, TRUE);
3491 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3494 s = mono_type_full_name (&ei->klass->byval_arg);
3495 if (!g_hash_table_lookup (mod->data.type_names, s))
3498 } else if (mod->kind == MOD_KIND_STEP) {
3499 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3500 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3501 !strcmp (jinfo_get_method (ji)->name, ".cctor") &&
3502 (jinfo_get_method (ji) != ((SingleStepReq*)req->info)->start_method))
3504 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3505 init_jit_info_dbg_attrs (ji);
3509 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3510 init_jit_info_dbg_attrs (ji);
3511 if (ji->dbg_step_through)
3514 if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3515 init_jit_info_dbg_attrs (ji);
3516 if (ji->dbg_non_user_code)
3523 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3524 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3529 /* Send a VM START/DEATH event by default */
3530 if (event == EVENT_KIND_VM_START)
3531 events = g_slist_append (events, GINT_TO_POINTER (0));
3532 if (event == EVENT_KIND_VM_DEATH)
3533 events = g_slist_append (events, GINT_TO_POINTER (0));
3538 static G_GNUC_UNUSED const char*
3539 event_to_string (EventKind event)
3542 case EVENT_KIND_VM_START: return "VM_START";
3543 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3544 case EVENT_KIND_THREAD_START: return "THREAD_START";
3545 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3546 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3547 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3548 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3549 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3550 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3551 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3552 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3553 case EVENT_KIND_STEP: return "STEP";
3554 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3555 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3556 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3557 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3558 case EVENT_KIND_USER_LOG: return "USER_LOG";
3560 g_assert_not_reached ();
3568 * Send an event to the client, suspending the vm if needed.
3569 * LOCKING: Since this can suspend the calling thread, no locks should be held
3571 * The EVENTS list is freed by this function.
3574 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3578 MonoDomain *domain = mono_domain_get ();
3579 MonoThread *thread = NULL;
3580 MonoObject *keepalive_obj = NULL;
3581 gboolean send_success = FALSE;
3586 DEBUG_PRINTF (2, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event));
3590 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3591 // FIXME: We miss those events
3592 DEBUG_PRINTF (2, "VM start event not sent yet: dropping %s\n", event_to_string (event));
3596 if (vm_death_event_sent) {
3597 DEBUG_PRINTF (2, "VM death event has been sent: dropping %s\n", event_to_string (event));
3601 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3602 DEBUG_PRINTF (2, "Mono runtime is shutting down: dropping %s\n", event_to_string (event));
3607 DEBUG_PRINTF (2, "Debugger client is not connected: dropping %s\n", event_to_string (event));
3611 if (event == EVENT_KIND_KEEPALIVE)
3612 suspend_policy = SUSPEND_POLICY_NONE;
3617 if (agent_config.defer) {
3618 /* Make sure the thread id is always set when doing deferred debugging */
3619 if (is_debugger_thread ()) {
3620 /* Don't suspend on events from the debugger thread */
3621 suspend_policy = SUSPEND_POLICY_NONE;
3622 thread = mono_thread_get_main ();
3624 else thread = mono_thread_current ();
3626 if (is_debugger_thread () && event != EVENT_KIND_VM_DEATH)
3627 // FIXME: Send these with a NULL thread, don't suspend the current thread
3632 nevents = g_slist_length (events);
3633 buffer_init (&buf, 128);
3634 buffer_add_byte (&buf, suspend_policy);
3635 buffer_add_int (&buf, nevents);
3637 for (l = events; l; l = l->next) {
3638 buffer_add_byte (&buf, event); // event kind
3639 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3643 if (event == EVENT_KIND_VM_DEATH) {
3647 thread = mono_thread_current ();
3649 if (event == EVENT_KIND_VM_START && arg != NULL)
3650 thread = (MonoThread *)arg;
3653 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3656 case EVENT_KIND_THREAD_START:
3657 case EVENT_KIND_THREAD_DEATH:
3659 case EVENT_KIND_APPDOMAIN_CREATE:
3660 case EVENT_KIND_APPDOMAIN_UNLOAD:
3661 buffer_add_domainid (&buf, (MonoDomain *)arg);
3663 case EVENT_KIND_METHOD_ENTRY:
3664 case EVENT_KIND_METHOD_EXIT:
3665 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3667 case EVENT_KIND_ASSEMBLY_LOAD:
3668 buffer_add_assemblyid (&buf, domain, (MonoAssembly *)arg);
3670 case EVENT_KIND_ASSEMBLY_UNLOAD: {
3671 DebuggerTlsData *tls;
3673 /* The domain the assembly belonged to is not equal to the current domain */
3674 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3676 g_assert (tls->domain_unloading);
3678 buffer_add_assemblyid (&buf, tls->domain_unloading, (MonoAssembly *)arg);
3681 case EVENT_KIND_TYPE_LOAD:
3682 buffer_add_typeid (&buf, domain, (MonoClass *)arg);
3684 case EVENT_KIND_BREAKPOINT:
3685 case EVENT_KIND_STEP:
3686 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3687 buffer_add_long (&buf, il_offset);
3689 case EVENT_KIND_VM_START:
3690 buffer_add_domainid (&buf, mono_get_root_domain ());
3692 case EVENT_KIND_VM_DEATH:
3693 if (CHECK_PROTOCOL_VERSION (2, 27))
3694 buffer_add_int (&buf, mono_environment_exitcode_get ());
3696 case EVENT_KIND_EXCEPTION: {
3697 EventInfo *ei = (EventInfo *)arg;
3698 buffer_add_objid (&buf, ei->exc);
3700 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3701 * later after the suspension. (#12494).
3703 keepalive_obj = ei->exc;
3706 case EVENT_KIND_USER_BREAK:
3708 case EVENT_KIND_USER_LOG: {
3709 EventInfo *ei = (EventInfo *)arg;
3710 buffer_add_int (&buf, ei->level);
3711 buffer_add_string (&buf, ei->category ? ei->category : "");
3712 buffer_add_string (&buf, ei->message ? ei->message : "");
3715 case EVENT_KIND_KEEPALIVE:
3716 suspend_policy = SUSPEND_POLICY_NONE;
3719 g_assert_not_reached ();
3723 if (event == EVENT_KIND_VM_START) {
3724 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3725 if (!agent_config.defer)
3726 start_debugger_thread ();
3729 if (event == EVENT_KIND_VM_DEATH) {
3730 vm_death_event_sent = TRUE;
3731 suspend_policy = SUSPEND_POLICY_NONE;
3734 if (mono_runtime_is_shutting_down ())
3735 suspend_policy = SUSPEND_POLICY_NONE;
3737 if (suspend_policy != SUSPEND_POLICY_NONE) {
3739 * Save the thread context and start suspending before sending the packet,
3740 * since we could be receiving the resume request before send_packet ()
3743 save_thread_context (ctx);
3747 /* This will keep this object alive */
3748 get_objref (keepalive_obj);
3751 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3755 g_slist_free (events);
3758 if (!send_success) {
3759 DEBUG_PRINTF (2, "Sending command %s failed.\n", event_to_string (event));
3763 if (event == EVENT_KIND_VM_START) {
3764 vm_start_event_sent = TRUE;
3767 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);
3769 switch (suspend_policy) {
3770 case SUSPEND_POLICY_NONE:
3772 case SUSPEND_POLICY_ALL:
3775 case SUSPEND_POLICY_EVENT_THREAD:
3779 g_assert_not_reached ();
3784 process_profiler_event (EventKind event, gpointer arg)
3788 EventInfo ei, *ei_arg = NULL;
3790 if (event == EVENT_KIND_TYPE_LOAD) {
3791 ei.klass = (MonoClass *)arg;
3795 mono_loader_lock ();
3796 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3797 mono_loader_unlock ();
3799 process_event (event, arg, 0, NULL, events, suspend_policy);
3803 runtime_initialized (MonoProfiler *prof)
3805 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3806 if (agent_config.defer)
3807 start_debugger_thread ();
3811 runtime_shutdown (MonoProfiler *prof)
3813 process_profiler_event (EVENT_KIND_VM_DEATH, NULL);
3815 mono_debugger_agent_cleanup ();
3819 thread_startup (MonoProfiler *prof, uintptr_t tid)
3821 MonoInternalThread *thread = mono_thread_internal_current ();
3822 MonoInternalThread *old_thread;
3823 DebuggerTlsData *tls;
3825 if (is_debugger_thread ())
3828 g_assert (mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (tid), MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid)));
3830 mono_loader_lock ();
3831 old_thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3832 mono_loader_unlock ();
3834 if (thread == old_thread) {
3836 * For some reason, thread_startup () might be called for the same thread
3837 * multiple times (attach ?).
3839 DEBUG_PRINTF (1, "[%p] thread_start () called multiple times for %p, ignored.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3843 * thread_end () might not be called for some threads, and the tid could
3846 DEBUG_PRINTF (1, "[%p] Removing stale data for tid %p.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3847 mono_loader_lock ();
3848 mono_g_hash_table_remove (thread_to_tls, old_thread);
3849 mono_g_hash_table_remove (tid_to_thread, GUINT_TO_POINTER (tid));
3850 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3851 mono_loader_unlock ();
3855 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3857 // FIXME: Free this somewhere
3858 tls = g_new0 (DebuggerTlsData, 1);
3859 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread, MONO_ROOT_SOURCE_DEBUGGER, "debugger thread reference");
3860 tls->thread = thread;
3861 mono_native_tls_set_value (debugger_tls_id, tls);
3863 DEBUG_PRINTF (1, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3865 mono_loader_lock ();
3866 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3867 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3868 mono_g_hash_table_insert (tid_to_thread_obj, GUINT_TO_POINTER (tid), mono_thread_current ());
3869 mono_loader_unlock ();
3871 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3874 * suspend_vm () could have missed this thread, so wait for a resume.
3880 thread_end (MonoProfiler *prof, uintptr_t tid)
3882 MonoInternalThread *thread;
3883 DebuggerTlsData *tls = NULL;
3885 mono_loader_lock ();
3886 thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3888 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3889 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
3891 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3892 tls->terminated = TRUE;
3893 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3894 MONO_GC_UNREGISTER_ROOT (tls->thread);
3898 mono_loader_unlock ();
3900 /* We might be called for threads started before we registered the start callback */
3902 DEBUG_PRINTF (1, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3904 if (mono_thread_internal_is_current (thread) && !mono_native_tls_get_value (debugger_tls_id)
3907 * This can happen on darwin since we deregister threads using pthread dtors.
3908 * process_profiler_event () and the code it calls cannot handle a null TLS value.
3913 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3918 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3920 mono_loader_lock ();
3921 g_hash_table_insert (domains, domain, domain);
3922 mono_loader_unlock ();
3924 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3928 appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain)
3930 DebuggerTlsData *tls;
3932 /* This might be called during shutdown on the debugger thread from the CMD_VM_EXIT code */
3933 if (is_debugger_thread ())
3937 * Remember the currently unloading appdomain as it is needed to generate
3938 * proper ids for unloading assemblies.
3940 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3942 tls->domain_unloading = domain;
3946 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3948 DebuggerTlsData *tls;
3950 if (is_debugger_thread ())
3953 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3955 tls->domain_unloading = NULL;
3957 clear_breakpoints_for_domain (domain);
3959 mono_loader_lock ();
3960 /* Invalidate each thread's frame stack */
3961 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3962 mono_loader_unlock ();
3964 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3968 * invalidate_each_thread:
3970 * A GHFunc to invalidate frames.
3971 * value must be a DebuggerTlsData*
3974 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3976 invalidate_frames ((DebuggerTlsData *)value);
3980 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3982 /* Sent later in jit_end () */
3984 g_ptr_array_add (pending_assembly_loads, assembly);
3989 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3991 if (is_debugger_thread ())
3994 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3996 clear_event_requests_for_assembly (assembly);
3997 clear_types_for_assembly (assembly);
4001 send_type_load (MonoClass *klass)
4003 gboolean type_load = FALSE;
4004 MonoDomain *domain = mono_domain_get ();
4005 AgentDomainInfo *info = NULL;
4007 info = get_agent_domain_info (domain);
4009 mono_loader_lock ();
4011 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
4013 g_hash_table_insert (info->loaded_classes, klass, klass);
4016 mono_loader_unlock ();
4019 emit_type_load (klass, klass, NULL);
4023 * Emit load events for all types currently loaded in the domain.
4024 * Takes the loader and domain locks.
4025 * user_data is unused.
4028 send_types_for_domain (MonoDomain *domain, void *user_data)
4030 MonoDomain* old_domain;
4031 AgentDomainInfo *info = NULL;
4033 info = get_agent_domain_info (domain);
4036 old_domain = mono_domain_get ();
4038 mono_domain_set (domain, TRUE);
4040 mono_loader_lock ();
4041 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4042 mono_loader_unlock ();
4044 mono_domain_set (old_domain, TRUE);
4048 send_assemblies_for_domain (MonoDomain *domain, void *user_data)
4051 MonoDomain* old_domain;
4053 old_domain = mono_domain_get ();
4055 mono_domain_set (domain, TRUE);
4057 mono_domain_assemblies_lock (domain);
4058 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
4059 MonoAssembly* ass = (MonoAssembly *)tmp->data;
4060 emit_assembly_load (ass, NULL);
4062 mono_domain_assemblies_unlock (domain);
4064 mono_domain_set (old_domain, TRUE);
4068 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
4071 * We emit type load events when the first method of the type is JITted,
4072 * since the class load profiler callbacks might be called with the
4073 * loader lock held. They could also occur in the debugger thread.
4074 * Same for assembly load events.
4077 MonoAssembly *assembly = NULL;
4079 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4081 if (pending_assembly_loads->len > 0) {
4082 assembly = (MonoAssembly *)g_ptr_array_index (pending_assembly_loads, 0);
4083 g_ptr_array_remove_index (pending_assembly_loads, 0);
4088 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4094 send_type_load (method->klass);
4097 add_pending_breakpoints (method, jinfo);
4101 * BREAKPOINTS/SINGLE STEPPING
4105 * Contains information about an inserted breakpoint.
4108 long il_offset, native_offset;
4112 } BreakpointInstance;
4115 * Contains generic information about a breakpoint.
4119 * The method where the breakpoint is placed. Can be NULL in which case it
4120 * is inserted into every method. This is used to implement method entry/
4121 * exit events. Can be a generic method definition, in which case the
4122 * breakpoint is inserted into every instance.
4128 * A list of BreakpointInstance structures describing where the breakpoint
4129 * was inserted. There could be more than one because of
4130 * generics/appdomains/method entry/exit.
4132 GPtrArray *children;
4135 /* List of breakpoints */
4136 /* Protected by the loader lock */
4137 static GPtrArray *breakpoints;
4138 /* Maps breakpoint locations to the number of breakpoints at that location */
4139 static GHashTable *bp_locs;
4142 breakpoints_init (void)
4144 breakpoints = g_ptr_array_new ();
4145 bp_locs = g_hash_table_new (NULL, NULL);
4149 * insert_breakpoint:
4151 * Insert the breakpoint described by BP into the method described by
4155 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4158 BreakpointInstance *inst;
4159 SeqPointIterator it;
4160 gboolean it_has_sp = FALSE;
4165 mono_seq_point_iterator_init (&it, seq_points);
4166 while (mono_seq_point_iterator_next (&it)) {
4167 if (it.seq_point.il_offset == bp->il_offset) {
4175 * The set of IL offsets with seq points doesn't completely match the
4176 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4178 mono_seq_point_iterator_init (&it, seq_points);
4179 while (mono_seq_point_iterator_next (&it)) {
4180 if (it.seq_point.il_offset != METHOD_ENTRY_IL_OFFSET &&
4181 it.seq_point.il_offset != METHOD_EXIT_IL_OFFSET &&
4182 it.seq_point.il_offset + 1 == bp->il_offset) {
4190 char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d", mono_method_full_name (jinfo_get_method (ji), TRUE), bp->il_offset);
4192 mono_seq_point_iterator_init (&it, seq_points);
4193 while (mono_seq_point_iterator_next (&it))
4194 DEBUG_PRINTF (1, "%d\n", it.seq_point.il_offset);
4197 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4198 g_warning ("%s", s);
4202 g_warning ("%s", s);
4208 inst = g_new0 (BreakpointInstance, 1);
4209 inst->il_offset = it.seq_point.il_offset;
4210 inst->native_offset = it.seq_point.native_offset;
4211 inst->ip = (guint8*)ji->code_start + it.seq_point.native_offset;
4213 inst->domain = domain;
4215 mono_loader_lock ();
4217 g_ptr_array_add (bp->children, inst);
4219 mono_loader_unlock ();
4222 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4223 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4226 if (it.seq_point.native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4227 DEBUG_PRINTF (1, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset);
4228 } else if (count == 0) {
4229 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4230 mono_arch_set_breakpoint (ji, inst->ip);
4236 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);
4240 remove_breakpoint (BreakpointInstance *inst)
4242 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4244 MonoJitInfo *ji = inst->ji;
4245 guint8 *ip = inst->ip;
4248 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4249 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4252 g_assert (count > 0);
4254 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4255 mono_arch_clear_breakpoint (ji, ip);
4256 DEBUG_PRINTF (1, "[dbg] Clear breakpoint at %s [%p].\n", mono_method_full_name (jinfo_get_method (ji), TRUE), ip);
4264 * This doesn't take any locks.
4266 static inline gboolean
4267 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4273 if (method == bp->method)
4275 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4278 if (bp->method->is_inflated && method->is_inflated) {
4279 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4280 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4282 /* Open generic methods should match closed generic methods of the same class */
4283 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4284 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4285 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4287 /* FIXME: Handle !mvar */
4288 if (t1->type != MONO_TYPE_MVAR)
4299 * add_pending_breakpoints:
4301 * Insert pending breakpoints into the newly JITted method METHOD.
4304 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4307 MonoSeqPointInfo *seq_points;
4309 MonoMethod *jmethod;
4314 domain = mono_domain_get ();
4316 mono_loader_lock ();
4318 for (i = 0; i < breakpoints->len; ++i) {
4319 MonoBreakpoint *bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4320 gboolean found = FALSE;
4322 if (!bp_matches_method (bp, method))
4325 for (j = 0; j < bp->children->len; ++j) {
4326 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4333 MonoMethod *declaring = NULL;
4335 jmethod = jinfo_get_method (ji);
4336 if (jmethod->is_inflated)
4337 declaring = mono_method_get_declaring_generic_method (jmethod);
4339 mono_domain_lock (domain);
4340 seq_points = (MonoSeqPointInfo *)g_hash_table_lookup (domain_jit_info (domain)->seq_points, jmethod);
4341 if (!seq_points && declaring)
4342 seq_points = (MonoSeqPointInfo *)g_hash_table_lookup (domain_jit_info (domain)->seq_points, declaring);
4343 mono_domain_unlock (domain);
4345 /* Could be AOT code */
4347 g_assert (seq_points);
4349 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4353 mono_loader_unlock ();
4357 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4365 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4369 /* Might be AOTed code */
4370 mono_class_init (method->klass);
4371 code = mono_aot_get_method_checked (domain, method, &oerror);
4373 mono_error_assert_ok (&oerror);
4374 ji = mono_jit_info_table_find (domain, (char *)code);
4379 insert_breakpoint (seq_points, domain, ji, bp, error);
4383 clear_breakpoint (MonoBreakpoint *bp);
4388 * Set a breakpoint at IL_OFFSET in METHOD.
4389 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4390 * METHOD can also be a generic method definition, in which case a breakpoint
4391 * is placed in all instances of the method.
4392 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4395 static MonoBreakpoint*
4396 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4399 GHashTableIter iter, iter2;
4402 MonoSeqPointInfo *seq_points;
4404 GPtrArray *method_domains;
4405 GPtrArray *method_seq_points;
4412 // - suspend/resume the vm to prevent code patching problems
4413 // - multiple breakpoints on the same location
4414 // - dynamic methods
4417 bp = g_new0 (MonoBreakpoint, 1);
4418 bp->method = method;
4419 bp->il_offset = il_offset;
4421 bp->children = g_ptr_array_new ();
4423 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);
4425 methods = g_ptr_array_new ();
4426 method_domains = g_ptr_array_new ();
4427 method_seq_points = g_ptr_array_new ();
4429 mono_loader_lock ();
4430 g_hash_table_iter_init (&iter, domains);
4431 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4432 mono_domain_lock (domain);
4433 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4434 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4435 if (bp_matches_method (bp, m)) {
4436 /* Save the info locally to simplify the code inside the domain lock */
4437 g_ptr_array_add (methods, m);
4438 g_ptr_array_add (method_domains, domain);
4439 g_ptr_array_add (method_seq_points, seq_points);
4442 mono_domain_unlock (domain);
4445 for (i = 0; i < methods->len; ++i) {
4446 m = (MonoMethod *)g_ptr_array_index (methods, i);
4447 domain = (MonoDomain *)g_ptr_array_index (method_domains, i);
4448 seq_points = (MonoSeqPointInfo *)g_ptr_array_index (method_seq_points, i);
4449 set_bp_in_method (domain, m, seq_points, bp, error);
4452 g_ptr_array_add (breakpoints, bp);
4453 mono_loader_unlock ();
4455 g_ptr_array_free (methods, TRUE);
4456 g_ptr_array_free (method_domains, TRUE);
4457 g_ptr_array_free (method_seq_points, TRUE);
4459 if (error && !mono_error_ok (error)) {
4460 clear_breakpoint (bp);
4468 clear_breakpoint (MonoBreakpoint *bp)
4472 // FIXME: locking, races
4473 for (i = 0; i < bp->children->len; ++i) {
4474 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, i);
4476 remove_breakpoint (inst);
4481 mono_loader_lock ();
4482 g_ptr_array_remove (breakpoints, bp);
4483 mono_loader_unlock ();
4485 g_ptr_array_free (bp->children, TRUE);
4490 breakpoints_cleanup (void)
4494 mono_loader_lock ();
4496 while (i < event_requests->len) {
4497 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
4499 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4500 clear_breakpoint ((MonoBreakpoint *)req->info);
4501 g_ptr_array_remove_index_fast (event_requests, i);
4508 for (i = 0; i < breakpoints->len; ++i)
4509 g_free (g_ptr_array_index (breakpoints, i));
4511 g_ptr_array_free (breakpoints, TRUE);
4512 g_hash_table_destroy (bp_locs);
4517 mono_loader_unlock ();
4521 * clear_breakpoints_for_domain:
4523 * Clear breakpoint instances which reference DOMAIN.
4526 clear_breakpoints_for_domain (MonoDomain *domain)
4530 /* This could be called after shutdown */
4534 mono_loader_lock ();
4535 for (i = 0; i < breakpoints->len; ++i) {
4536 MonoBreakpoint *bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4539 while (j < bp->children->len) {
4540 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4542 if (inst->domain == domain) {
4543 remove_breakpoint (inst);
4547 g_ptr_array_remove_index_fast (bp->children, j);
4553 mono_loader_unlock ();
4557 * ss_calculate_framecount:
4559 * Ensure DebuggerTlsData fields are filled out.
4561 static void ss_calculate_framecount (DebuggerTlsData *tls, MonoContext *ctx)
4563 if (!tls->context.valid)
4564 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4565 compute_frame_info (tls->thread, tls);
4569 ensure_jit (StackFrame* frame)
4572 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
4573 if (!frame->jit && frame->api_method->is_inflated)
4574 frame->jit = mono_debug_find_method(mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
4578 /* This could happen for aot images with no jit debug info */
4579 s = mono_method_full_name (frame->api_method, TRUE);
4580 DEBUG_PRINTF(1, "[dbg] No debug information found for '%s'.\n", s);
4591 * Return FALSE if single stepping needs to continue.
4594 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp, DebuggerTlsData *tls, MonoContext *ctx, MonoMethod* method)
4596 MonoDebugMethodInfo *minfo;
4597 MonoDebugSourceLocation *loc = NULL;
4598 gboolean hit = TRUE;
4600 if (req->async_stepout_method == method) {
4601 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);
4605 if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK)) {
4607 * These seq points are inserted by the JIT after calls, step over needs to skip them.
4609 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);
4613 if ((req->depth == STEP_DEPTH_OVER || req->depth == STEP_DEPTH_OUT) && hit && !req->async_stepout_method) {
4614 gboolean is_step_out = req->depth == STEP_DEPTH_OUT;
4616 ss_calculate_framecount (tls, ctx);
4618 // Because functions can call themselves recursively, we need to make sure we're stopping at the right stack depth.
4619 // In case of step out, the target is the frame *enclosing* the one where the request was made.
4620 int target_frames = req->nframes + (is_step_out ? -1 : 0);
4621 if (req->nframes > 0 && tls->frame_count > 0 && tls->frame_count > target_frames) {
4622 /* Hit the breakpoint in a recursive call, don't halt */
4623 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");
4628 if (req->depth == STEP_DEPTH_INTO && req->size == STEP_SIZE_MIN && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) && ss_req->start_method){
4629 ss_calculate_framecount (tls, ctx);
4630 if (ss_req->start_method == method && req->nframes && tls->frame_count == req->nframes) {//Check also frame count(could be recursion)
4631 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);
4636 MonoDebugMethodAsyncInfo* asyncMethod = mono_debug_lookup_method_async_debug_info (method);
4638 for (int i = 0; i < asyncMethod->num_awaits; i++)
4640 if (asyncMethod->yield_offsets[i] == sp->il_offset || asyncMethod->resume_offsets[i] == sp->il_offset) {
4641 mono_debug_free_method_async_debug_info (asyncMethod);
4645 mono_debug_free_method_async_debug_info (asyncMethod);
4648 if (req->size != STEP_SIZE_LINE)
4651 /* Have to check whenever a different source line was reached */
4652 minfo = mono_debug_lookup_method (method);
4655 loc = mono_debug_method_lookup_location (minfo, sp->il_offset);
4658 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);
4659 ss_req->last_method = method;
4661 } else if (loc && method == ss_req->last_method && loc->row == ss_req->last_line) {
4662 ss_calculate_framecount (tls, ctx);
4663 if (tls->frame_count == req->nframes) { // If the frame has changed we're clearly not on the same source line.
4664 DEBUG_PRINTF (1, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer) (gsize) mono_native_thread_id_get (), loc->row);
4670 ss_req->last_method = method;
4671 ss_req->last_line = loc->row;
4672 mono_debug_free_source_location (loc);
4679 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4681 return bp->method && bp->method->klass->image->assembly == assembly;
4685 get_this (StackFrame *frame)
4687 //Logic inspiered by "add_var" method and took out path that happens in async method for getting this
4688 MonoDebugVarInfo *var = frame->jit->this_var;
4689 if ((var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS) != MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET)
4692 guint8 * addr = (guint8 *)mono_arch_context_get_int_reg (&frame->ctx, var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS);
4693 addr += (gint32)var->offset;
4694 return *(MonoObject**)addr;
4697 //This ID is used to figure out if breakpoint hit on resumeOffset belongs to us or not
4698 //since thread probably changed...
4700 get_this_async_id (StackFrame *frame)
4702 return get_objid (get_this (frame));
4705 static MonoMethod* set_notification_method_cache = NULL;
4708 get_set_notification_method ()
4710 if(set_notification_method_cache != NULL)
4711 return set_notification_method_cache;
4713 MonoClass* async_builder_class = mono_class_load_from_name (mono_defaults.corlib, "System.Runtime.CompilerServices", "AsyncTaskMethodBuilder");
4714 GPtrArray* array = mono_class_get_methods_by_name (async_builder_class, "SetNotificationForWaitCompletion", 0x24, FALSE, FALSE, &error);
4715 mono_error_assert_ok (&error);
4716 g_assert (array->len == 1);
4717 set_notification_method_cache = (MonoMethod *)g_ptr_array_index (array, 0);
4718 g_ptr_array_free (array, TRUE);
4719 return set_notification_method_cache;
4723 set_set_notification_for_wait_completion_flag (StackFrame *frame)
4725 MonoObject* obj = get_this (frame);
4727 MonoClassField *builder_field = mono_class_get_field_from_name (obj->vtable->klass, "<>t__builder");
4728 g_assert (builder_field);
4729 MonoObject* builder;
4731 builder = mono_field_get_value_object_checked (frame->domain, builder_field, obj, &error);
4732 mono_error_assert_ok (&error);
4736 gboolean arg = TRUE;
4738 mono_runtime_invoke_checked (get_set_notification_method(), mono_object_unbox (builder), args, &error);
4739 mono_error_assert_ok (&error);
4740 mono_field_set_value (obj, builder_field, mono_object_unbox (builder));
4743 static MonoMethod* notify_debugger_of_wait_completion_method_cache = NULL;
4746 get_notify_debugger_of_wait_completion_method ()
4748 if (notify_debugger_of_wait_completion_method_cache != NULL)
4749 return notify_debugger_of_wait_completion_method_cache;
4751 MonoClass* task_class = mono_class_load_from_name (mono_defaults.corlib, "System.Threading.Tasks", "Task");
4752 GPtrArray* array = mono_class_get_methods_by_name (task_class, "NotifyDebuggerOfWaitCompletion", 0x24, FALSE, FALSE, &error);
4753 mono_error_assert_ok (&error);
4754 g_assert (array->len == 1);
4755 notify_debugger_of_wait_completion_method_cache = (MonoMethod *)g_ptr_array_index (array, 0);
4756 g_ptr_array_free (array, TRUE);
4757 return notify_debugger_of_wait_completion_method_cache;
4761 process_breakpoint_inner (DebuggerTlsData *tls, gboolean from_signal)
4765 int i, j, suspend_policy;
4766 guint32 native_offset;
4768 BreakpointInstance *inst;
4769 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4770 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4771 EventKind kind = EVENT_KIND_BREAKPOINT;
4772 MonoContext *ctx = &tls->restore_state.ctx;
4774 MonoSeqPointInfo *info;
4778 // FIXME: Speed this up
4780 ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
4781 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4782 g_assert (ji && !ji->is_trampoline);
4783 method = jinfo_get_method (ji);
4785 /* Compute the native offset of the breakpoint from the ip */
4786 native_offset = ip - (guint8*)ji->code_start;
4789 * Skip the instruction causing the breakpoint signal.
4792 mono_arch_skip_breakpoint (ctx, ji);
4794 if (method->wrapper_type || tls->disable_breakpoints)
4797 bp_reqs = g_ptr_array_new ();
4798 ss_reqs = g_ptr_array_new ();
4799 ss_reqs_orig = g_ptr_array_new ();
4801 mono_loader_lock ();
4804 * The ip points to the instruction causing the breakpoint event, which is after
4805 * the offset recorded in the seq point map, so find the prev seq point before ip.
4807 found_sp = mono_find_prev_seq_point_for_native_offset (mono_domain_get (), method, native_offset, &info, &sp);
4810 no_seq_points_found (method, native_offset);
4812 g_assert (found_sp);
4814 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);
4817 for (i = 0; i < breakpoints->len; ++i) {
4818 bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4823 for (j = 0; j < bp->children->len; ++j) {
4824 inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4825 if (inst->ji == ji && inst->il_offset == sp.il_offset && inst->native_offset == sp.native_offset) {
4826 if (bp->req->event_kind == EVENT_KIND_STEP) {
4827 g_ptr_array_add (ss_reqs_orig, bp->req);
4829 g_ptr_array_add (bp_reqs, bp->req);
4834 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4835 /* Maybe a method entry/exit event */
4836 if (sp.il_offset == METHOD_ENTRY_IL_OFFSET)
4837 kind = EVENT_KIND_METHOD_ENTRY;
4838 else if (sp.il_offset == METHOD_EXIT_IL_OFFSET)
4839 kind = EVENT_KIND_METHOD_EXIT;
4842 /* Process single step requests */
4843 for (i = 0; i < ss_reqs_orig->len; ++i) {
4844 EventRequest *req = (EventRequest *)g_ptr_array_index (ss_reqs_orig, i);
4845 SingleStepReq *ss_req = (SingleStepReq *)req->info;
4848 //if we hit async_stepout_method, it's our no matter which thread
4849 if ((ss_req->async_stepout_method != method) && (ss_req->async_id || mono_thread_internal_current () != ss_req->thread)) {
4850 //We have different thread and we don't have async stepping in progress
4851 //it's breakpoint in parallel thread, ignore it
4852 if (ss_req->async_id == 0)
4855 tls->context.valid = FALSE;
4856 tls->async_state.valid = FALSE;
4857 invalidate_frames (tls);
4858 ss_calculate_framecount(tls, ctx);
4859 //make sure we have enough data to get current async method instance id
4860 if (tls->frame_count == 0 || !ensure_jit (tls->frames [0]))
4863 //Check method is async before calling get_this_async_id
4864 MonoDebugMethodAsyncInfo* asyncMethod = mono_debug_lookup_method_async_debug_info (method);
4868 mono_debug_free_method_async_debug_info (asyncMethod);
4870 //breakpoint was hit in parallelly executing async method, ignore it
4871 if (ss_req->async_id != get_this_async_id (tls->frames [0]))
4875 //Update stepping request to new thread/frame_count that we are continuing on
4876 //so continuing with normal stepping works as expected
4877 if (ss_req->async_stepout_method || ss_req->async_id) {
4878 tls->context.valid = FALSE;
4879 tls->async_state.valid = FALSE;
4880 invalidate_frames (tls);
4881 ss_calculate_framecount (tls, ctx);
4882 ss_req->thread = mono_thread_internal_current ();
4883 ss_req->nframes = tls->frame_count;
4886 hit = ss_update (ss_req, ji, &sp, tls, ctx, method);
4888 g_ptr_array_add (ss_reqs, req);
4890 /* Start single stepping again from the current sequence point */
4891 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
4894 if (ss_reqs->len > 0)
4895 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4896 if (bp_reqs->len > 0)
4897 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4898 if (kind != EVENT_KIND_BREAKPOINT)
4899 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4901 mono_loader_unlock ();
4903 g_ptr_array_free (bp_reqs, TRUE);
4904 g_ptr_array_free (ss_reqs, TRUE);
4907 * FIXME: The first event will suspend, so the second will only be sent after the
4911 process_event (EVENT_KIND_STEP, method, 0, ctx, ss_events, suspend_policy);
4913 process_event (kind, method, 0, ctx, bp_events, suspend_policy);
4914 if (enter_leave_events)
4915 process_event (kind, method, 0, ctx, enter_leave_events, suspend_policy);
4918 /* Process a breakpoint/single step event after resuming from a signal handler */
4920 process_signal_event (void (*func) (DebuggerTlsData*, gboolean))
4922 DebuggerTlsData *tls;
4923 MonoThreadUnwindState orig_restore_state;
4926 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4927 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4928 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4929 mono_thread_state_init_from_monoctx (&tls->restore_state, &tls->handler_ctx);
4933 /* This is called when resuming from a signal handler, so it shouldn't return */
4934 memcpy (&ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4935 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4936 mono_restore_context (&ctx);
4937 g_assert_not_reached ();
4941 process_breakpoint (void)
4943 process_signal_event (process_breakpoint_inner);
4947 resume_from_signal_handler (void *sigctx, void *func)
4949 DebuggerTlsData *tls;
4952 /* Save the original context in TLS */
4953 // FIXME: This might not work on an altstack ?
4954 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4956 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer) (gsize) mono_native_thread_id_get ());
4959 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4960 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4961 // clob:c could be added to op_seq_point.
4963 mono_sigctx_to_monoctx (sigctx, &ctx);
4964 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4965 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4966 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4968 MONO_CONTEXT_SET_IP (&ctx, func);
4970 mono_monoctx_to_sigctx (&ctx, sigctx);
4972 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4973 mono_ppc_set_func_into_sigctx (sigctx, func);
4978 mono_debugger_agent_breakpoint_hit (void *sigctx)
4981 * We are called from a signal handler, and running code there causes all kinds of
4982 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4983 * So set up the signal context to return to the real breakpoint handler function.
4985 resume_from_signal_handler (sigctx, process_breakpoint);
4989 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4991 if (frame->managed) {
4992 *(MonoContext*)data = *ctx;
5001 * Called by System.Diagnostics.Debugger:Break ().
5004 mono_debugger_agent_user_break (void)
5006 if (agent_config.enabled) {
5011 /* Obtain a context */
5012 MONO_CONTEXT_SET_IP (&ctx, NULL);
5013 mono_walk_stack_with_ctx (user_break_cb, NULL, (MonoUnwindOptions)0, &ctx);
5014 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
5016 mono_loader_lock ();
5017 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
5018 mono_loader_unlock ();
5020 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
5021 } else if (debug_options.native_debugger_break) {
5027 ss_depth_to_string (StepDepth depth)
5030 case STEP_DEPTH_OVER:
5032 case STEP_DEPTH_OUT:
5034 case STEP_DEPTH_INTO:
5037 g_assert_not_reached ();
5043 process_single_step_inner (DebuggerTlsData *tls, gboolean from_signal)
5048 int il_offset, suspend_policy;
5051 MonoContext *ctx = &tls->restore_state.ctx;
5054 MonoSeqPointInfo *info;
5056 ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
5058 /* Skip the instruction causing the single step */
5060 mono_arch_skip_single_step (ctx);
5062 if (suspend_count > 0) {
5063 /* Fastpath during invokes, see in process_suspend () */
5064 if (suspend_count - tls->resume_count == 0)
5066 process_suspend (tls, ctx);
5071 // FIXME: A suspend race
5074 if (mono_thread_internal_current () != ss_req->thread)
5077 if (log_level > 0) {
5078 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
5080 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);
5083 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
5084 g_assert (ji && !ji->is_trampoline);
5085 method = jinfo_get_method (ji);
5088 if (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
5093 * Stopping in memset makes half-initialized vtypes visible.
5094 * Stopping in memcpy makes half-copied vtypes visible.
5096 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
5100 * This could be in ss_update method, but mono_find_next_seq_point_for_native_offset is pretty expensive method,
5101 * hence we prefer this check here.
5103 if (ss_req->user_assemblies) {
5104 gboolean found = FALSE;
5105 for (int k = 0; ss_req->user_assemblies[k]; k++)
5106 if (ss_req->user_assemblies[k] == method->klass->image->assembly) {
5116 * The ip points to the instruction causing the single step event, which is before
5117 * the offset recorded in the seq point map, so find the next seq point after ip.
5119 if (!mono_find_next_seq_point_for_native_offset (domain, method, (guint8*)ip - (guint8*)ji->code_start, &info, &sp))
5122 il_offset = sp.il_offset;
5124 if (!ss_update (ss_req, ji, &sp, tls, ctx, method))
5127 /* Start single stepping again from the current sequence point */
5128 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
5130 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
5131 (method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
5132 !strcmp (method->name, ".cctor"))
5135 // FIXME: Has to lock earlier
5137 reqs = g_ptr_array_new ();
5139 mono_loader_lock ();
5141 g_ptr_array_add (reqs, ss_req->req);
5143 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
5145 g_ptr_array_free (reqs, TRUE);
5147 mono_loader_unlock ();
5149 process_event (EVENT_KIND_STEP, jinfo_get_method (ji), il_offset, ctx, events, suspend_policy);
5153 process_single_step (void)
5155 process_signal_event (process_single_step_inner);
5159 * mono_debugger_agent_single_step_event:
5161 * Called from a signal handler to handle a single step event.
5164 mono_debugger_agent_single_step_event (void *sigctx)
5166 /* Resume to process_single_step through the signal context */
5168 // FIXME: Since step out/over is implemented using step in, the step in case should
5169 // be as fast as possible. Move the relevant code from process_single_step_inner ()
5172 if (is_debugger_thread ()) {
5174 * This could happen despite our best effors when the runtime calls
5175 * assembly/type resolve hooks.
5176 * FIXME: Breakpoints too.
5180 mono_sigctx_to_monoctx (sigctx, &ctx);
5181 mono_arch_skip_single_step (&ctx);
5182 mono_monoctx_to_sigctx (&ctx, sigctx);
5186 resume_from_signal_handler (sigctx, process_single_step);
5190 debugger_agent_single_step_from_context (MonoContext *ctx)
5192 DebuggerTlsData *tls;
5193 MonoThreadUnwindState orig_restore_state;
5195 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5196 /* Fastpath during invokes, see in process_suspend () */
5197 if (tls && suspend_count && suspend_count - tls->resume_count == 0)
5200 if (is_debugger_thread ())
5205 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
5206 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5207 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5208 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5210 process_single_step_inner (tls, FALSE);
5212 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5213 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5217 debugger_agent_breakpoint_from_context (MonoContext *ctx)
5219 DebuggerTlsData *tls;
5220 MonoThreadUnwindState orig_restore_state;
5223 if (is_debugger_thread ())
5226 orig_ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
5227 MONO_CONTEXT_SET_IP (ctx, orig_ip - 1);
5229 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5231 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5232 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5233 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5235 process_breakpoint_inner (tls, FALSE);
5237 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5238 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5239 if (MONO_CONTEXT_GET_IP (ctx) == orig_ip - 1)
5240 MONO_CONTEXT_SET_IP (ctx, orig_ip);
5244 * start_single_stepping:
5246 * Turn on single stepping. Can be called multiple times, for example,
5247 * by a single step event request + a suspend.
5250 start_single_stepping (void)
5252 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5253 int val = InterlockedIncrement (&ss_count);
5256 mono_arch_start_single_stepping ();
5258 g_assert_not_reached ();
5263 stop_single_stepping (void)
5265 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5266 int val = InterlockedDecrement (&ss_count);
5269 mono_arch_stop_single_stepping ();
5271 g_assert_not_reached ();
5278 * Stop the single stepping operation given by SS_REQ.
5281 ss_stop (SingleStepReq *ss_req)
5286 for (l = ss_req->bps; l; l = l->next) {
5287 clear_breakpoint ((MonoBreakpoint *)l->data);
5289 g_slist_free (ss_req->bps);
5293 ss_req->async_id = 0;
5294 ss_req->async_stepout_method = NULL;
5295 if (ss_req->global) {
5296 stop_single_stepping ();
5297 ss_req->global = FALSE;
5304 * Reject breakpoint if it is a duplicate of one already in list or hash table.
5307 ss_bp_is_unique (GSList *bps, GHashTable *ss_req_bp_cache, MonoMethod *method, guint32 il_offset)
5309 if (ss_req_bp_cache) {
5310 MonoBreakpoint dummy = {method, il_offset, NULL, NULL};
5311 return !g_hash_table_lookup (ss_req_bp_cache, &dummy);
5313 for (GSList *l = bps; l; l = l->next) {
5314 MonoBreakpoint *bp = (MonoBreakpoint *)l->data;
5315 if (bp->method == method && bp->il_offset == il_offset)
5324 * GHashTable equality for a MonoBreakpoint (only care about method and il_offset fields)
5327 ss_bp_eq (gconstpointer ka, gconstpointer kb)
5329 const MonoBreakpoint *s1 = (const MonoBreakpoint *)ka;
5330 const MonoBreakpoint *s2 = (const MonoBreakpoint *)kb;
5331 return (s1->method == s2->method && s1->il_offset == s2->il_offset) ? 1 : 0;
5337 * GHashTable hash for a MonoBreakpoint (only care about method and il_offset fields)
5340 ss_bp_hash (gconstpointer data)
5342 const MonoBreakpoint *s = (const MonoBreakpoint *)data;
5343 guint hash = (guint) (uintptr_t) s->method;
5344 hash ^= ((guint)s->il_offset) << 16; // Assume low bits are more interesting
5345 hash ^= ((guint)s->il_offset) >> 16;
5349 #define MAX_LINEAR_SCAN_BPS 7
5354 * Create a new breakpoint and add it to a step request.
5355 * Will adjust the bp count and cache used by ss_start.
5358 ss_bp_add_one (SingleStepReq *ss_req, int *ss_req_bp_count, GHashTable **ss_req_bp_cache,
5359 MonoMethod *method, guint32 il_offset)
5361 // This list is getting too long, switch to using the hash table
5362 if (!*ss_req_bp_cache && *ss_req_bp_count > MAX_LINEAR_SCAN_BPS) {
5363 *ss_req_bp_cache = g_hash_table_new (ss_bp_hash, ss_bp_eq);
5364 for (GSList *l = ss_req->bps; l; l = l->next)
5365 g_hash_table_insert (*ss_req_bp_cache, l->data, l->data);
5368 if (ss_bp_is_unique (ss_req->bps, *ss_req_bp_cache, method, il_offset)) {
5369 // Create and add breakpoint
5370 MonoBreakpoint *bp = set_breakpoint (method, il_offset, ss_req->req, NULL);
5371 ss_req->bps = g_slist_append (ss_req->bps, bp);
5372 if (*ss_req_bp_cache)
5373 g_hash_table_insert (*ss_req_bp_cache, bp, bp);
5374 (*ss_req_bp_count)++;
5376 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);
5381 is_last_non_empty (SeqPoint* sp, MonoSeqPointInfo *info)
5385 SeqPoint* next = g_new (SeqPoint, sp->next_len);
5386 mono_seq_point_init_next (info, *sp, next);
5387 for (int i = 0; i < sp->next_len; i++) {
5388 if (next [i].flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) {
5389 if (!is_last_non_empty (&next [i], info)) {
5405 * Start the single stepping operation given by SS_REQ from the sequence point SP.
5406 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
5407 * belong to the same thread as CTX.
5408 * If FRAMES is not-null, use that instead of tls->frames for placing breakpoints etc.
5411 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint* sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls,
5412 gboolean step_to_catch, StackFrame **frames, int nframes)
5414 int i, j, frame_index;
5415 SeqPoint *next_sp, *parent_sp = NULL;
5416 SeqPoint local_sp, local_parent_sp;
5418 MonoSeqPointInfo *parent_info;
5419 MonoMethod *parent_sp_method = NULL;
5420 gboolean enable_global = FALSE;
5422 // When 8 or more entries are in bps, we build a hash table to serve as a set of breakpoints.
5423 // Recreating this on each pass is a little wasteful but at least keeps behavior linear.
5424 int ss_req_bp_count = g_slist_length (ss_req->bps);
5425 GHashTable *ss_req_bp_cache = NULL;
5427 /* Stop the previous operation */
5431 * Implement single stepping using breakpoints if possible.
5433 if (step_to_catch) {
5434 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, sp->il_offset);
5438 if (ctx && !frames) {
5439 /* Need parent frames */
5440 if (!tls->context.valid)
5441 mono_thread_state_init_from_monoctx (&tls->context, ctx);
5442 compute_frame_info (tls->thread, tls);
5443 frames = tls->frames;
5444 nframes = tls->frame_count;
5447 MonoDebugMethodAsyncInfo* asyncMethod = mono_debug_lookup_method_async_debug_info (method);
5449 /* Need to stop in catch clauses as well */
5450 for (i = ss_req->depth == STEP_DEPTH_OUT ? 1 : 0; i < nframes; ++i) {
5451 StackFrame *frame = frames [i];
5454 MonoJitInfo *jinfo = frame->ji;
5455 for (j = 0; j < jinfo->num_clauses; ++j) {
5456 // In case of async method we don't want to place breakpoint on last catch handler(which state machine added for whole method)
5457 if (asyncMethod && asyncMethod->num_awaits && i == 0 && j + 1 == jinfo->num_clauses)
5459 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5461 if (mono_find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL, &local_sp))
5462 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, frame->method, local_sp.il_offset);
5467 if (asyncMethod && asyncMethod->num_awaits && nframes && ensure_jit (frames [0])) {
5468 //asyncMethod has value and num_awaits > 0, this means we are inside async method with awaits
5470 // Check if we hit yield_offset during normal stepping, because if we did...
5471 // Go into special async stepping mode which places breakpoint on resumeOffset
5472 // of this await call and sets async_id so we can distinguish it from parallel executions
5473 for (i = 0; i < asyncMethod->num_awaits; i++) {
5474 if (sp->il_offset == asyncMethod->yield_offsets [i]) {
5475 ss_req->async_id = get_this_async_id (frames [0]);
5476 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, asyncMethod->resume_offsets [i]);
5477 if (ss_req_bp_cache)
5478 g_hash_table_destroy (ss_req_bp_cache);
5479 mono_debug_free_method_async_debug_info (asyncMethod);
5483 //If we are at end of async method and doing step-in or step-over...
5484 //Switch to step-out, so whole NotifyDebuggerOfWaitCompletion magic happens...
5485 if (is_last_non_empty (sp, info)) {
5486 ss_req->depth = STEP_DEPTH_OUT;//setting depth to step-out is important, don't inline IF, because code later depends on this
5488 if (ss_req->depth == STEP_DEPTH_OUT) {
5489 set_set_notification_for_wait_completion_flag (frames [0]);
5490 ss_req->async_id = get_this_async_id (frames [0]);
5491 ss_req->async_stepout_method = get_notify_debugger_of_wait_completion_method ();
5492 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, ss_req->async_stepout_method, 0);
5493 if (ss_req_bp_cache)
5494 g_hash_table_destroy (ss_req_bp_cache);
5495 mono_debug_free_method_async_debug_info (asyncMethod);
5501 mono_debug_free_method_async_debug_info (asyncMethod);
5504 * Find the first sequence point in the current or in a previous frame which
5505 * is not the last in its method.
5507 if (ss_req->depth == STEP_DEPTH_OUT) {
5508 /* Ignore seq points in current method */
5509 while (frame_index < nframes) {
5510 StackFrame *frame = frames [frame_index];
5512 method = frame->method;
5513 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5514 sp = (found_sp)? &local_sp : NULL;
5516 if (sp && sp->next_len != 0)
5519 // There could be method calls before the next seq point in the caller when using nested calls
5520 //enable_global = TRUE;
5522 if (sp && sp->next_len == 0) {
5524 while (frame_index < nframes) {
5525 StackFrame *frame = frames [frame_index];
5527 method = frame->method;
5528 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5529 sp = (found_sp)? &local_sp : NULL;
5530 if (sp && sp->next_len != 0)
5536 /* Have to put a breakpoint into a parent frame since the seq points might not cover all control flow out of the method */
5537 while (frame_index < nframes) {
5538 StackFrame *frame = frames [frame_index];
5540 parent_sp_method = frame->method;
5541 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &parent_info, &local_parent_sp);
5542 parent_sp = found_sp ? &local_parent_sp : NULL;
5543 if (found_sp && parent_sp->next_len != 0)
5551 if (sp && sp->next_len > 0) {
5552 SeqPoint* next = g_new(SeqPoint, sp->next_len);
5554 mono_seq_point_init_next (info, *sp, next);
5555 for (i = 0; i < sp->next_len; i++) {
5558 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, next_sp->il_offset);
5564 SeqPoint* next = g_new(SeqPoint, parent_sp->next_len);
5566 mono_seq_point_init_next (parent_info, *parent_sp, next);
5567 for (i = 0; i < parent_sp->next_len; i++) {
5570 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, parent_sp_method, next_sp->il_offset);
5575 if (ss_req->nframes == 0)
5576 ss_req->nframes = nframes;
5578 if ((ss_req->depth == STEP_DEPTH_OVER) && (!sp && !parent_sp)) {
5579 DEBUG_PRINTF (1, "[dbg] No parent frame for step over, transition to step into.\n");
5581 * This is needed since if we leave managed code, and later return to it, step over
5582 * is not going to stop.
5583 * This approach is a bit ugly, since we change the step depth, but it only affects
5584 * clients who reuse the same step request, and only in this special case.
5586 ss_req->depth = STEP_DEPTH_INTO;
5589 if (ss_req->depth == STEP_DEPTH_INTO) {
5590 /* Enable global stepping so we stop at method entry too */
5591 enable_global = TRUE;
5595 * The ctx/frame info computed above will become invalid when we continue.
5597 tls->context.valid = FALSE;
5598 tls->async_state.valid = FALSE;
5599 invalidate_frames (tls);
5602 if (enable_global) {
5603 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5604 ss_req->global = TRUE;
5605 start_single_stepping ();
5606 } else if (!ss_req->bps) {
5607 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5608 ss_req->global = TRUE;
5609 start_single_stepping ();
5611 ss_req->global = FALSE;
5614 if (ss_req_bp_cache)
5615 g_hash_table_destroy (ss_req_bp_cache);
5619 * Start single stepping of thread THREAD
5622 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req)
5624 DebuggerTlsData *tls;
5625 MonoSeqPointInfo *info = NULL;
5626 SeqPoint *sp = NULL;
5629 MonoMethod *method = NULL;
5630 MonoDebugMethodInfo *minfo;
5631 gboolean step_to_catch = FALSE;
5632 gboolean set_ip = FALSE;
5633 StackFrame **frames = NULL;
5636 if (suspend_count == 0)
5637 return ERR_NOT_SUSPENDED;
5639 wait_for_suspend ();
5641 // FIXME: Multiple requests
5643 DEBUG_PRINTF (0, "Received a single step request while the previous one was still active.\n");
5644 return ERR_NOT_IMPLEMENTED;
5647 DEBUG_PRINTF (1, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth));
5649 ss_req = g_new0 (SingleStepReq, 1);
5651 ss_req->thread = thread;
5652 ss_req->size = size;
5653 ss_req->depth = depth;
5654 ss_req->filter = filter;
5657 for (int i = 0; i < req->nmodifiers; i++) {
5658 if (req->modifiers[i].kind == MOD_KIND_ASSEMBLY_ONLY) {
5659 ss_req->user_assemblies = req->modifiers[i].data.assemblies;
5664 mono_loader_lock ();
5665 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5666 mono_loader_unlock ();
5668 if (!tls->context.valid) {
5669 DEBUG_PRINTF (1, "Received a single step request on a thread with no managed frames.");
5670 return ERR_INVALID_ARGUMENT;
5673 if (tls->restore_state.valid && MONO_CONTEXT_GET_IP (&tls->context.ctx) != MONO_CONTEXT_GET_IP (&tls->restore_state.ctx)) {
5675 * Need to start single stepping from restore_state and not from the current state
5678 frames = compute_frame_info_from (thread, tls, &tls->restore_state, &nframes);
5681 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5683 if (tls->catch_state.valid) {
5685 StackFrameInfo frame;
5686 MonoContext new_ctx;
5687 MonoLMF *lmf = NULL;
5690 * We are stopped at a throw site. Stepping should go to the catch site.
5693 /* Find the the jit info for the catch context */
5694 res = mono_find_jit_info_ext (
5695 (MonoDomain *)tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN],
5696 (MonoJitTlsData *)((MonoThreadInfo*)thread->thread_info)->jit_data,
5697 NULL, &tls->catch_state.ctx, &new_ctx, NULL, &lmf, NULL, &frame);
5699 g_assert (frame.type == FRAME_TYPE_MANAGED);
5702 * Find the seq point corresponding to the landing site ip, which is the first seq
5705 found_sp = mono_find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info, &local_sp);
5706 sp = (found_sp)? &local_sp : NULL;
5708 no_seq_points_found (frame.method, frame.native_offset);
5711 method = frame.method;
5713 step_to_catch = TRUE;
5714 /* This make sure the seq point is not skipped by process_single_step () */
5715 ss_req->last_sp = NULL;
5718 if (!step_to_catch) {
5719 StackFrame *frame = NULL;
5722 if (frames && nframes)
5725 compute_frame_info (thread, tls);
5727 if (tls->frame_count)
5728 frame = tls->frames [0];
5731 if (ss_req->size == STEP_SIZE_LINE) {
5733 ss_req->last_method = frame->method;
5734 ss_req->last_line = -1;
5736 minfo = mono_debug_lookup_method (frame->method);
5737 if (minfo && frame->il_offset != -1) {
5738 MonoDebugSourceLocation *loc = mono_debug_method_lookup_location (minfo, frame->il_offset);
5741 ss_req->last_line = loc->row;
5749 if (!method && frame->il_offset != -1) {
5750 /* FIXME: Sort the table and use a binary search */
5751 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5752 sp = (found_sp)? &local_sp : NULL;
5754 no_seq_points_found (frame->method, frame->native_offset);
5756 method = frame->method;
5761 ss_req->start_method = method;
5763 ss_start (ss_req, method, sp, info, set_ip ? &tls->restore_state.ctx : &tls->context.ctx, tls, step_to_catch, frames, nframes);
5766 free_frames (frames, nframes);
5772 ss_destroy (SingleStepReq *req)
5775 g_assert (ss_req == req);
5784 ss_clear_for_assembly (SingleStepReq *req, MonoAssembly *assembly)
5787 gboolean found = TRUE;
5791 for (l = ss_req->bps; l; l = l->next) {
5792 if (breakpoint_matches_assembly ((MonoBreakpoint *)l->data, assembly)) {
5793 clear_breakpoint ((MonoBreakpoint *)l->data);
5794 ss_req->bps = g_slist_delete_link (ss_req->bps, l);
5803 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5806 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5813 if (!agent_config.enabled)
5816 mono_loader_lock ();
5817 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5818 mono_loader_unlock ();
5823 ei.category = mono_string_to_utf8_checked (category, &error);
5824 mono_error_cleanup (&error);
5828 ei.message = mono_string_to_utf8_checked (message, &error);
5829 mono_error_cleanup (&error);
5832 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5834 g_free (ei.category);
5835 g_free (ei.message);
5839 mono_debugger_agent_debug_log_is_enabled (void)
5841 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5842 return agent_config.enabled;
5845 #if defined(PLATFORM_ANDROID) || defined(TARGET_ANDROID)
5847 mono_debugger_agent_unhandled_exception (MonoException *exc)
5856 memset (&ei, 0, sizeof (EventInfo));
5857 ei.exc = (MonoObject*)exc;
5859 mono_loader_lock ();
5860 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5861 mono_loader_unlock ();
5863 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5868 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5869 MonoContext *catch_ctx)
5871 int i, j, suspend_policy;
5873 MonoJitInfo *ji, *catch_ji;
5875 DebuggerTlsData *tls = NULL;
5877 if (thread_to_tls != NULL) {
5878 MonoInternalThread *thread = mono_thread_internal_current ();
5880 mono_loader_lock ();
5881 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5882 mono_loader_unlock ();
5884 if (tls && tls->abort_requested)
5886 if (tls && tls->disable_breakpoints)
5890 memset (&ei, 0, sizeof (EventInfo));
5892 /* Just-In-Time debugging */
5894 if (agent_config.onuncaught && !inited) {
5895 finish_agent_init (FALSE);
5898 * Send an unsolicited EXCEPTION event with a dummy request id.
5900 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5901 ei.exc = (MonoObject*)exc;
5902 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5905 } else if (agent_config.onthrow && !inited) {
5907 gboolean found = FALSE;
5909 for (l = agent_config.onthrow; l; l = l->next) {
5910 char *ex_type = (char *)l->data;
5911 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5913 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5920 finish_agent_init (FALSE);
5923 * Send an unsolicited EXCEPTION event with a dummy request id.
5925 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5926 ei.exc = (MonoObject*)exc;
5927 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5935 ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5937 catch_ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5941 ei.exc = (MonoObject*)exc;
5942 ei.caught = catch_ctx != NULL;
5944 mono_loader_lock ();
5946 /* Treat exceptions which are caught in non-user code as unhandled */
5947 for (i = 0; i < event_requests->len; ++i) {
5948 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
5949 if (req->event_kind != EVENT_KIND_EXCEPTION)
5952 for (j = 0; j < req->nmodifiers; ++j) {
5953 Modifier *mod = &req->modifiers [j];
5955 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5957 gboolean found = FALSE;
5958 MonoAssembly **assemblies = mod->data.assemblies;
5961 for (k = 0; assemblies [k]; ++k)
5962 if (assemblies [k] == jinfo_get_method (catch_ji)->klass->image->assembly)
5971 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5972 mono_loader_unlock ();
5974 if (tls && ei.caught && catch_ctx) {
5975 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5976 tls->catch_state.ctx = *catch_ctx;
5977 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5978 tls->catch_state.valid = TRUE;
5981 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5984 tls->catch_state.valid = FALSE;
5988 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5990 DebuggerTlsData *tls;
5995 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
6000 * We're about to invoke an exception filter during the first pass of exception handling.
6002 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
6003 * 'orig_ctx' is the context where the exception has been thrown.
6006 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
6008 * If we're stopped in Filter(), normal stack unwinding would first unwind to
6009 * the call site (line 37) and then continue to Main(), but it would never
6010 * include the throw site (line 32).
6012 * Since exception filters are invoked during the first pass of exception handling,
6013 * the stack frames of the throw site are still intact, so we should include them
6016 * We do this here by saving the context of the throw site in 'tls->filter_state'.
6018 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
6019 * but report the location of the 'throw' to the user.
6023 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
6027 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
6029 DebuggerTlsData *tls;
6034 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
6038 tls->filter_state.valid = FALSE;
6042 * buffer_add_value_full:
6044 * Add the encoding of the value at ADDR described by T to the buffer.
6045 * AS_VTYPE determines whenever to treat primitive types as primitive types or
6049 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
6050 gboolean as_vtype, GHashTable *parent_vtypes)
6053 gboolean boxed_vtype = FALSE;
6056 if (!(*(void**)addr)) {
6057 /* This can happen with compiler generated locals */
6058 //printf ("%s\n", mono_type_full_name (t));
6059 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
6062 g_assert (*(void**)addr);
6063 addr = *(void**)addr;
6068 case MONO_TYPE_BOOLEAN:
6071 case MONO_TYPE_CHAR:
6091 case MONO_TYPE_VOID:
6092 buffer_add_byte (buf, t->type);
6094 case MONO_TYPE_BOOLEAN:
6097 buffer_add_byte (buf, t->type);
6098 buffer_add_int (buf, *(gint8*)addr);
6100 case MONO_TYPE_CHAR:
6103 buffer_add_byte (buf, t->type);
6104 buffer_add_int (buf, *(gint16*)addr);
6109 buffer_add_byte (buf, t->type);
6110 buffer_add_int (buf, *(gint32*)addr);
6115 buffer_add_byte (buf, t->type);
6116 buffer_add_long (buf, *(gint64*)addr);
6120 /* Treat it as a vtype */
6122 case MONO_TYPE_PTR: {
6123 gssize val = *(gssize*)addr;
6125 buffer_add_byte (buf, t->type);
6126 buffer_add_long (buf, val);
6130 case MONO_TYPE_STRING:
6131 case MONO_TYPE_SZARRAY:
6132 case MONO_TYPE_OBJECT:
6133 case MONO_TYPE_CLASS:
6134 case MONO_TYPE_ARRAY:
6135 obj = *(MonoObject**)addr;
6138 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
6140 if (obj->vtable->klass->valuetype) {
6141 t = &obj->vtable->klass->byval_arg;
6142 addr = mono_object_unbox (obj);
6145 } else if (obj->vtable->klass->rank) {
6146 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
6147 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
6148 buffer_add_byte (buf, MONO_TYPE_CLASS);
6150 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
6152 buffer_add_objid (buf, obj);
6156 case MONO_TYPE_VALUETYPE:
6157 case MONO_TYPE_TYPEDBYREF: {
6161 MonoClass *klass = mono_class_from_mono_type (t);
6166 * Handle boxed vtypes recursively referencing themselves using fields.
6169 parent_vtypes = g_hash_table_new (NULL, NULL);
6170 vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
6172 if (CHECK_PROTOCOL_VERSION (2, 33)) {
6173 buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
6174 buffer_add_int (buf, vtype_index - 1);
6176 /* The client can't handle PARENT_VTYPE */
6177 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
6181 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
6185 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
6186 buffer_add_byte (buf, klass->enumtype);
6187 buffer_add_typeid (buf, domain, klass);
6191 while ((f = mono_class_get_fields (klass, &iter))) {
6192 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6194 if (mono_field_is_deleted (f))
6198 buffer_add_int (buf, nfields);
6201 while ((f = mono_class_get_fields (klass, &iter))) {
6202 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6204 if (mono_field_is_deleted (f))
6206 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE, parent_vtypes);
6210 g_hash_table_remove (parent_vtypes, addr);
6211 if (g_hash_table_size (parent_vtypes) == 0) {
6212 g_hash_table_destroy (parent_vtypes);
6213 parent_vtypes = NULL;
6218 case MONO_TYPE_GENERICINST:
6219 if (mono_type_generic_inst_is_valuetype (t)) {
6231 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
6233 buffer_add_value_full (buf, t, addr, domain, FALSE, NULL);
6237 obj_is_of_type (MonoObject *obj, MonoType *t)
6239 MonoClass *klass = obj->vtable->klass;
6240 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
6241 if (mono_class_is_transparent_proxy (klass)) {
6242 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
6243 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
6253 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
6256 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6262 gpointer iter = NULL;
6266 is_enum = decode_byte (buf, &buf, limit);
6267 /* Enums are sent as a normal vtype */
6269 return ERR_NOT_IMPLEMENTED;
6270 klass = decode_typeid (buf, &buf, limit, &d, &err);
6271 if (err != ERR_NONE)
6274 if (t && klass != mono_class_from_mono_type (t)) {
6275 char *name = mono_type_full_name (t);
6276 char *name2 = mono_type_full_name (&klass->byval_arg);
6277 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got %s.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, name2);
6280 return ERR_INVALID_ARGUMENT;
6283 nfields = decode_int (buf, &buf, limit);
6284 while ((f = mono_class_get_fields (klass, &iter))) {
6285 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6287 if (mono_field_is_deleted (f))
6289 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
6290 if (err != ERR_NONE)
6294 g_assert (nfields == 0);
6302 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6306 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
6307 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
6308 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
6309 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
6310 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE) &&
6311 !(t->type == MONO_TYPE_VALUETYPE && type == MONO_TYPE_OBJECT)) {
6312 char *name = mono_type_full_name (t);
6313 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
6315 return ERR_INVALID_ARGUMENT;
6319 case MONO_TYPE_BOOLEAN:
6320 *(guint8*)addr = decode_int (buf, &buf, limit);
6322 case MONO_TYPE_CHAR:
6323 *(gunichar2*)addr = decode_int (buf, &buf, limit);
6326 *(gint8*)addr = decode_int (buf, &buf, limit);
6329 *(guint8*)addr = decode_int (buf, &buf, limit);
6332 *(gint16*)addr = decode_int (buf, &buf, limit);
6335 *(guint16*)addr = decode_int (buf, &buf, limit);
6338 *(gint32*)addr = decode_int (buf, &buf, limit);
6341 *(guint32*)addr = decode_int (buf, &buf, limit);
6344 *(gint64*)addr = decode_long (buf, &buf, limit);
6347 *(guint64*)addr = decode_long (buf, &buf, limit);
6350 *(guint32*)addr = decode_int (buf, &buf, limit);
6353 *(guint64*)addr = decode_long (buf, &buf, limit);
6356 /* We send these as I8, so we get them back as such */
6357 g_assert (type == MONO_TYPE_I8);
6358 *(gssize*)addr = decode_long (buf, &buf, limit);
6360 case MONO_TYPE_GENERICINST:
6361 if (MONO_TYPE_ISSTRUCT (t)) {
6362 /* The client sends these as a valuetype */
6370 /* We send these as vtypes, so we get them back as such */
6371 g_assert (type == MONO_TYPE_VALUETYPE);
6374 case MONO_TYPE_VALUETYPE:
6375 if (type == MONO_TYPE_OBJECT) {
6377 int objid = decode_objid (buf, &buf, limit);
6381 err = get_object (objid, (MonoObject**)&obj);
6382 if (err != ERR_NONE)
6385 return ERR_INVALID_ARGUMENT;
6386 if (obj->vtable->klass != mono_class_from_mono_type (t)) {
6387 DEBUG_PRINTF (1, "Expected type '%s', got object '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6388 return ERR_INVALID_ARGUMENT;
6390 memcpy (addr, mono_object_unbox (obj), mono_class_value_size (obj->vtable->klass, NULL));
6392 err = decode_vtype (t, domain, addr, buf, &buf, limit);
6393 if (err != ERR_NONE)
6399 if (MONO_TYPE_IS_REFERENCE (t)) {
6400 if (type == MONO_TYPE_OBJECT) {
6401 int objid = decode_objid (buf, &buf, limit);
6405 err = get_object (objid, (MonoObject**)&obj);
6406 if (err != ERR_NONE)
6410 if (!obj_is_of_type (obj, t)) {
6411 DEBUG_PRINTF (1, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6412 return ERR_INVALID_ARGUMENT;
6415 if (obj && obj->vtable->domain != domain)
6416 return ERR_INVALID_ARGUMENT;
6418 mono_gc_wbarrier_generic_store (addr, obj);
6419 } else if (type == VALUE_TYPE_ID_NULL) {
6420 *(MonoObject**)addr = NULL;
6421 } else if (type == MONO_TYPE_VALUETYPE) {
6430 /* This can happen when round-tripping boxed vtypes */
6432 * Obtain vtype class.
6433 * Same as the beginning of the handle_vtype case above.
6436 is_enum = decode_byte (buf, &buf, limit);
6438 return ERR_NOT_IMPLEMENTED;
6439 klass = decode_typeid (buf, &buf, limit, &d, &err);
6440 if (err != ERR_NONE)
6443 /* Decode the vtype into a temporary buffer, then box it. */
6444 vtype_buf_size = mono_class_value_size (klass, NULL);
6445 vtype_buf = (guint8 *)g_malloc0 (vtype_buf_size);
6446 g_assert (vtype_buf);
6449 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
6450 if (err != ERR_NONE) {
6454 *(MonoObject**)addr = mono_value_box_checked (d, klass, vtype_buf, &error);
6455 mono_error_cleanup (&error);
6458 char *name = mono_type_full_name (t);
6459 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
6461 return ERR_INVALID_ARGUMENT;
6475 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6479 int type = decode_byte (buf, &buf, limit);
6481 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
6482 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
6483 guint8 *nullable_buf;
6486 * First try decoding it as a Nullable`1
6488 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6489 if (err == ERR_NONE)
6493 * Then try decoding as a primitive value or null.
6495 if (targ->type == type) {
6496 nullable_buf = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
6497 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
6498 if (err != ERR_NONE) {
6499 g_free (nullable_buf);
6502 MonoObject *boxed = mono_value_box_checked (domain, mono_class_from_mono_type (targ), nullable_buf, &error);
6503 if (!is_ok (&error)) {
6504 mono_error_cleanup (&error);
6505 return ERR_INVALID_OBJECT;
6507 mono_nullable_init (addr, boxed, mono_class_from_mono_type (t));
6508 g_free (nullable_buf);
6511 } else if (type == VALUE_TYPE_ID_NULL) {
6512 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
6518 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6522 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
6526 guint8 *addr, *gaddr;
6529 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6530 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6533 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
6534 reg_val = mono_arch_context_get_int_reg (ctx, reg);
6536 buffer_add_value_full (buf, t, ®_val, domain, as_vtype, NULL);
6538 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6539 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6540 addr += (gint32)var->offset;
6542 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6544 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6546 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6549 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6550 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
6551 /* Same as regoffset, but with an indirection */
6552 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6553 addr += (gint32)var->offset;
6555 gaddr = (guint8 *)*(gpointer*)addr;
6557 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL);
6559 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
6560 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
6561 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
6562 MonoGSharedVtMethodRuntimeInfo *info;
6568 g_assert (info_var);
6569 g_assert (locals_var);
6571 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6572 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6573 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6574 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6575 addr += (gint32)info_var->offset;
6576 info = (MonoGSharedVtMethodRuntimeInfo *)*(gpointer*)addr;
6577 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6578 info = (MonoGSharedVtMethodRuntimeInfo *)mono_arch_context_get_int_reg (ctx, reg);
6580 g_assert_not_reached ();
6584 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6585 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6586 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6587 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6588 addr += (gint32)locals_var->offset;
6589 locals = (guint8 *)*(gpointer*)addr;
6590 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6591 locals = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6593 g_assert_not_reached ();
6597 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6599 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6604 g_assert_not_reached ();
6609 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
6613 guint8 *addr, *gaddr;
6615 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6616 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6618 if (MONO_TYPE_IS_REFERENCE (t))
6619 size = sizeof (gpointer);
6621 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6624 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6625 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6627 gboolean is_signed = FALSE;
6630 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6633 // FIXME: Write barriers
6634 mono_gc_memmove_atomic (addr, val, size);
6639 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6644 v = is_signed ? *(gint8*)val : *(guint8*)val;
6647 v = is_signed ? *(gint16*)val : *(guint16*)val;
6650 v = is_signed ? *(gint32*)val : *(guint32*)val;
6653 v = is_signed ? *(gint64*)val : *(guint64*)val;
6656 g_assert_not_reached ();
6659 /* Set value on the stack or in the return ctx */
6660 if (reg_locations [reg]) {
6661 /* Saved on the stack */
6662 DEBUG_PRINTF (1, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v);
6663 *(reg_locations [reg]) = v;
6666 DEBUG_PRINTF (1, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v);
6667 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6670 // FIXME: Move these to mono-context.h/c.
6671 mono_arch_context_set_int_reg (ctx, reg, v);
6673 // FIXME: Can't set registers, so we disable linears
6678 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6679 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6680 addr += (gint32)var->offset;
6682 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6685 addr = *(guint8**)addr;
6691 // FIXME: Write barriers
6692 mono_gc_memmove_atomic (addr, val, size);
6694 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6695 /* Same as regoffset, but with an indirection */
6696 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6697 addr += (gint32)var->offset;
6699 gaddr = (guint8 *)*(gpointer*)addr;
6701 // FIXME: Write barriers
6702 mono_gc_memmove_atomic (gaddr, val, size);
6704 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6708 g_assert_not_reached ();
6713 clear_event_request (int req_id, int etype)
6717 mono_loader_lock ();
6718 for (i = 0; i < event_requests->len; ++i) {
6719 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6721 if (req->id == req_id && req->event_kind == etype) {
6722 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6723 clear_breakpoint ((MonoBreakpoint *)req->info);
6724 if (req->event_kind == EVENT_KIND_STEP)
6725 ss_destroy ((SingleStepReq *)req->info);
6726 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6727 clear_breakpoint ((MonoBreakpoint *)req->info);
6728 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6729 clear_breakpoint ((MonoBreakpoint *)req->info);
6730 g_ptr_array_remove_index_fast (event_requests, i);
6735 mono_loader_unlock ();
6739 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
6743 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6744 m->kind = MOD_KIND_NONE;
6745 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6746 int count = 0, match_count = 0, pos;
6747 MonoAssembly **newassemblies;
6749 for (i = 0; m->data.assemblies [i]; ++i) {
6751 if (m->data.assemblies [i] == assembly)
6756 // +1 because we don't know length and we use last element to check for end
6757 newassemblies = g_new0 (MonoAssembly*, count - match_count + 1);
6760 for (i = 0; i < count; ++i)
6761 if (m->data.assemblies [i] != assembly)
6762 newassemblies [pos ++] = m->data.assemblies [i];
6763 g_assert (pos == count - match_count);
6764 g_free (m->data.assemblies);
6765 m->data.assemblies = newassemblies;
6771 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
6775 for (i = 0; i < req->nmodifiers; ++i) {
6776 Modifier *m = &req->modifiers [i];
6778 clear_assembly_from_modifier (req, m, assembly);
6783 * clear_event_requests_for_assembly:
6785 * Clear all events requests which reference ASSEMBLY.
6788 clear_event_requests_for_assembly (MonoAssembly *assembly)
6793 mono_loader_lock ();
6797 for (i = 0; i < event_requests->len; ++i) {
6798 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6800 clear_assembly_from_modifiers (req, assembly);
6802 if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly ((MonoBreakpoint *)req->info, assembly)) {
6803 clear_event_request (req->id, req->event_kind);
6808 if (req->event_kind == EVENT_KIND_STEP)
6809 ss_clear_for_assembly ((SingleStepReq *)req->info, assembly);
6812 mono_loader_unlock ();
6816 * type_comes_from_assembly:
6818 * GHRFunc that returns TRUE if klass comes from assembly
6821 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6823 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6827 * clear_types_for_assembly:
6829 * Clears types from loaded_classes for a given assembly
6832 clear_types_for_assembly (MonoAssembly *assembly)
6834 MonoDomain *domain = mono_domain_get ();
6835 AgentDomainInfo *info = NULL;
6837 if (!domain || !domain_jit_info (domain))
6838 /* Can happen during shutdown */
6841 info = get_agent_domain_info (domain);
6843 mono_loader_lock ();
6844 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6845 mono_loader_unlock ();
6849 add_thread (gpointer key, gpointer value, gpointer user_data)
6851 MonoInternalThread *thread = (MonoInternalThread *)value;
6852 Buffer *buf = (Buffer *)user_data;
6854 buffer_add_objid (buf, (MonoObject*)thread);
6858 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6861 guint8 *end = invoke->endp;
6865 MonoMethodSignature *sig;
6868 MonoObject *this_arg, *res, *exc;
6871 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6874 MonoStopwatch watch;
6876 if (invoke->method) {
6878 * Invoke this method directly, currently only Environment.Exit () is supported.
6881 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>");
6883 mono_runtime_try_invoke (invoke->method, NULL, invoke->args, &exc, &error);
6884 mono_error_assert_ok (&error);
6886 g_assert_not_reached ();
6889 m = decode_methodid (p, &p, end, &domain, &err);
6890 if (err != ERR_NONE)
6892 sig = mono_method_signature (m);
6894 if (m->klass->valuetype)
6895 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6897 this_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
6898 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6899 /* Should be null */
6900 int type = decode_byte (p, &p, end);
6901 if (type != VALUE_TYPE_ID_NULL) {
6902 DEBUG_PRINTF (1, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6903 return ERR_INVALID_ARGUMENT;
6905 memset (this_buf, 0, mono_class_instance_size (m->klass));
6906 } else if (m->klass->valuetype && !strcmp (m->name, ".ctor")) {
6910 int type = decode_byte (p, &tmp_p, end);
6911 if (type == VALUE_TYPE_ID_NULL) {
6912 memset (this_buf, 0, mono_class_instance_size (m->klass));
6915 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6916 if (err != ERR_NONE)
6920 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6921 if (err != ERR_NONE)
6925 if (!m->klass->valuetype)
6926 this_arg = *(MonoObject**)this_buf;
6930 if (MONO_CLASS_IS_INTERFACE (m->klass)) {
6932 DEBUG_PRINTF (1, "[%p] Error: Interface method invoked 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 /* Transform this to the format the rest of the code expects it to be */
6937 if (m->klass->valuetype) {
6938 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6939 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
6941 } else if ((m->flags & METHOD_ATTRIBUTE_VIRTUAL) && !m->klass->valuetype && invoke->flags & INVOKE_FLAG_VIRTUAL) {
6943 DEBUG_PRINTF (1, "[%p] Error: invoke with INVOKE_FLAG_VIRTUAL flag set without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6944 return ERR_INVALID_ARGUMENT;
6946 m = mono_object_get_virtual_method (this_arg, m);
6947 if (m->klass->valuetype) {
6948 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6949 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
6953 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>");
6955 if (this_arg && this_arg->vtable->domain != domain)
6958 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this_arg) {
6959 if (!strcmp (m->name, ".ctor")) {
6960 if (mono_class_is_abstract (m->klass))
6961 return ERR_INVALID_ARGUMENT;
6964 this_arg = mono_object_new_checked (domain, m->klass, &error);
6965 mono_error_assert_ok (&error);
6968 return ERR_INVALID_ARGUMENT;
6972 if (this_arg && !obj_is_of_type (this_arg, &m->klass->byval_arg))
6973 return ERR_INVALID_ARGUMENT;
6975 nargs = decode_int (p, &p, end);
6976 if (nargs != sig->param_count)
6977 return ERR_INVALID_ARGUMENT;
6978 /* Use alloca to get gc tracking */
6979 arg_buf = (guint8 **)g_alloca (nargs * sizeof (gpointer));
6980 memset (arg_buf, 0, nargs * sizeof (gpointer));
6981 args = (gpointer *)g_alloca (nargs * sizeof (gpointer));
6982 for (i = 0; i < nargs; ++i) {
6983 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6984 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6985 if (err != ERR_NONE)
6987 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6990 if (sig->params [i]->byref) {
6991 arg_buf [i] = (guint8 *)g_alloca (sizeof (mgreg_t));
6992 *(gpointer*)arg_buf [i] = args [i];
6993 args [i] = arg_buf [i];
6996 arg_buf [i] = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6997 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6998 if (err != ERR_NONE)
7000 args [i] = arg_buf [i];
7007 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
7008 tls->disable_breakpoints = TRUE;
7010 tls->disable_breakpoints = FALSE;
7013 * Add an LMF frame to link the stack frames on the invoke method with our caller.
7015 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
7016 if (invoke->has_ctx) {
7019 lmf_addr = mono_get_lmf_addr ();
7022 memset (&ext, 0, sizeof (ext));
7023 mono_arch_init_lmf_ext (&ext, *lmf_addr);
7025 ext.debugger_invoke = TRUE;
7026 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
7028 mono_set_lmf ((MonoLMF*)&ext);
7032 mono_stopwatch_start (&watch);
7033 res = mono_runtime_try_invoke (m, m->klass->valuetype ? (gpointer) this_buf : (gpointer) this_arg, args, &exc, &error);
7034 if (exc == NULL && !mono_error_ok (&error)) {
7035 exc = (MonoObject*) mono_error_convert_to_exception (&error);
7037 mono_error_cleanup (&error); /* FIXME report error */
7039 mono_stopwatch_stop (&watch);
7040 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));
7042 buffer_add_byte (buf, 0);
7043 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
7045 gboolean out_this = FALSE;
7046 gboolean out_args = FALSE;
7048 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_THIS) && CHECK_PROTOCOL_VERSION (2, 35))
7050 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_ARGS) && CHECK_PROTOCOL_VERSION (2, 35))
7052 buffer_add_byte (buf, 1 + (out_this ? 2 : 0) + (out_args ? 4 : 0));
7053 if (sig->ret->type == MONO_TYPE_VOID) {
7054 if (!strcmp (m->name, ".ctor")) {
7055 if (!m->klass->valuetype)
7056 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this_arg, domain);
7058 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
7060 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
7062 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
7063 buffer_add_value (buf, sig->ret, &res, domain);
7064 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
7065 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
7066 MonoClass *k = mono_class_from_mono_type (sig->ret);
7067 guint8 *nullable_buf = (guint8 *)g_alloca (mono_class_value_size (k, NULL));
7069 g_assert (nullable_buf);
7070 mono_nullable_init (nullable_buf, res, k);
7071 buffer_add_value (buf, sig->ret, nullable_buf, domain);
7074 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
7080 /* Return the new value of the receiver after the call */
7081 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
7083 buffer_add_int (buf, nargs);
7084 for (i = 0; i < nargs; ++i) {
7085 if (MONO_TYPE_IS_REFERENCE (sig->params [i]))
7086 buffer_add_value (buf, sig->params [i], &args [i], domain);
7087 else if (sig->params [i]->byref)
7088 /* add_value () does an indirection */
7089 buffer_add_value (buf, sig->params [i], &arg_buf [i], domain);
7091 buffer_add_value (buf, sig->params [i], arg_buf [i], domain);
7096 tls->disable_breakpoints = FALSE;
7098 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
7099 if (invoke->has_ctx)
7100 mono_set_lmf ((MonoLMF *)(((gssize)ext.lmf.previous_lmf) & ~3));
7104 // FIXME: byref arguments
7112 * Invoke the method given by tls->pending_invoke in the current thread.
7115 invoke_method (void)
7117 DebuggerTlsData *tls;
7123 MonoContext restore_ctx;
7126 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
7130 * Store the `InvokeData *' in `tls->invoke' until we're done with
7131 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
7134 mono_loader_lock ();
7136 invoke = tls->pending_invoke;
7138 tls->pending_invoke = NULL;
7140 invoke->last_invoke = tls->invoke;
7141 tls->invoke = invoke;
7143 mono_loader_unlock ();
7145 tls->frames_up_to_date = FALSE;
7151 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
7152 buffer_init (&buf, 128);
7155 /* Fail the other invokes as well */
7157 err = do_invoke_method (tls, &buf, invoke, p, &p);
7160 if (tls->abort_requested) {
7161 if (CHECK_PROTOCOL_VERSION (2, 42))
7162 err = ERR_INVOKE_ABORTED;
7165 /* Start suspending before sending the reply */
7166 if (mindex == invoke->nmethods - 1) {
7167 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
7168 for (i = 0; i < invoke->suspend_count; ++i)
7173 send_reply_packet (id, err, &buf);
7178 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
7180 if (invoke->has_ctx)
7181 save_thread_context (&restore_ctx);
7183 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
7184 g_assert (tls->resume_count);
7185 tls->resume_count -= invoke->suspend_count;
7188 DEBUG_PRINTF (1, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer) (gsize) mono_native_thread_id_get (), err, tls->resume_count);
7191 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
7193 * It is possible that mono_thread_internal_abort () was called
7194 * after the mono_runtime_invoke_checked() already returned, but it doesn't matter
7195 * because we reset the abort here.
7198 mono_loader_lock ();
7200 if (tls->abort_requested)
7201 mono_thread_internal_reset_abort (tls->thread);
7203 tls->invoke = tls->invoke->last_invoke;
7204 tls->abort_requested = FALSE;
7206 mono_loader_unlock ();
7215 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
7217 MonoThread *thread = (MonoThread *)value;
7218 DebuggerTlsData *tls;
7221 mono_loader_lock ();
7222 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
7224 res = tls->really_suspended;
7225 mono_loader_unlock ();
7231 get_source_files_for_type (MonoClass *klass)
7233 gpointer iter = NULL;
7235 MonoDebugSourceInfo *sinfo;
7239 files = g_ptr_array_new ();
7241 while ((method = mono_class_get_methods (klass, &iter))) {
7242 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
7243 GPtrArray *source_file_list;
7246 mono_debug_get_seq_points (minfo, NULL, &source_file_list, NULL, NULL, NULL);
7247 for (j = 0; j < source_file_list->len; ++j) {
7248 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, j);
7249 for (i = 0; i < files->len; ++i)
7250 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
7252 if (i == files->len)
7253 g_ptr_array_add (files, g_strdup (sinfo->source_file));
7255 g_ptr_array_free (source_file_list, TRUE);
7263 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
7266 case CMD_VM_VERSION: {
7267 char *build_info, *version;
7269 build_info = mono_get_runtime_build_info ();
7270 version = g_strdup_printf ("mono %s", build_info);
7272 buffer_add_string (buf, version); /* vm version */
7273 buffer_add_int (buf, MAJOR_VERSION);
7274 buffer_add_int (buf, MINOR_VERSION);
7275 g_free (build_info);
7279 case CMD_VM_SET_PROTOCOL_VERSION: {
7280 major_version = decode_int (p, &p, end);
7281 minor_version = decode_int (p, &p, end);
7282 protocol_version_set = TRUE;
7283 DEBUG_PRINTF (1, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version);
7286 case CMD_VM_ALL_THREADS: {
7288 mono_loader_lock ();
7289 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
7290 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
7291 mono_loader_unlock ();
7294 case CMD_VM_SUSPEND:
7296 wait_for_suspend ();
7299 if (suspend_count == 0)
7300 return ERR_NOT_SUSPENDED;
7302 clear_suspended_objs ();
7304 case CMD_VM_DISPOSE:
7305 /* Clear all event requests */
7306 mono_loader_lock ();
7307 while (event_requests->len > 0) {
7308 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
7310 clear_event_request (req->id, req->event_kind);
7312 mono_loader_unlock ();
7314 while (suspend_count > 0)
7316 disconnected = TRUE;
7317 vm_start_event_sent = FALSE;
7320 MonoInternalThread *thread;
7321 DebuggerTlsData *tls;
7322 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7323 MonoClass *env_class;
7325 MonoMethod *exit_method = NULL;
7329 exit_code = decode_int (p, &p, end);
7331 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
7333 /* Have to send a reply before exiting */
7334 send_reply_packet (id, 0, buf);
7336 /* Clear all event requests */
7337 mono_loader_lock ();
7338 while (event_requests->len > 0) {
7339 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
7341 clear_event_request (req->id, req->event_kind);
7343 mono_loader_unlock ();
7346 * The JDWP documentation says that the shutdown is not orderly. It doesn't
7347 * specify whenever a VM_DEATH event is sent. We currently do an orderly
7348 * shutdown by hijacking a thread to execute Environment.Exit (). This is
7349 * better than doing the shutdown ourselves, since it avoids various races.
7353 wait_for_suspend ();
7355 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7356 env_class = mono_class_try_load_from_name (mono_defaults.corlib, "System", "Environment");
7358 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
7361 mono_loader_lock ();
7362 thread = (MonoInternalThread *)mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
7363 mono_loader_unlock ();
7365 if (thread && exit_method) {
7366 mono_loader_lock ();
7367 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
7368 mono_loader_unlock ();
7370 args = g_new0 (gpointer, 1);
7371 args [0] = g_malloc (sizeof (int));
7372 *(int*)(args [0]) = exit_code;
7374 tls->pending_invoke = g_new0 (InvokeData, 1);
7375 tls->pending_invoke->method = exit_method;
7376 tls->pending_invoke->args = args;
7377 tls->pending_invoke->nmethods = 1;
7379 while (suspend_count > 0)
7383 * No thread found, do it ourselves.
7384 * FIXME: This can race with normal shutdown etc.
7386 while (suspend_count > 0)
7389 if (!mono_runtime_try_shutdown ())
7392 mono_environment_exitcode_set (exit_code);
7394 /* Suspend all managed threads since the runtime is going away */
7395 DEBUG_PRINTF (1, "Suspending all threads...\n");
7396 mono_thread_suspend_all_other_threads ();
7397 DEBUG_PRINTF (1, "Shutting down the runtime...\n");
7398 mono_runtime_quit ();
7399 transport_close2 ();
7400 DEBUG_PRINTF (1, "Exiting...\n");
7406 case CMD_VM_INVOKE_METHOD:
7407 case CMD_VM_INVOKE_METHODS: {
7408 int objid = decode_objid (p, &p, end);
7410 DebuggerTlsData *tls;
7411 int i, count, flags, nmethods;
7414 err = get_object (objid, (MonoObject**)&thread);
7415 if (err != ERR_NONE)
7418 flags = decode_int (p, &p, end);
7420 if (command == CMD_VM_INVOKE_METHODS)
7421 nmethods = decode_int (p, &p, end);
7425 // Wait for suspending if it already started
7427 wait_for_suspend ();
7428 if (!is_suspended ())
7429 return ERR_NOT_SUSPENDED;
7431 mono_loader_lock ();
7432 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7433 mono_loader_unlock ();
7436 if (!tls->really_suspended)
7437 /* The thread is still running native code, can't do invokes */
7438 return ERR_NOT_SUSPENDED;
7441 * Store the invoke data into tls, the thread will execute it after it is
7444 if (tls->pending_invoke)
7445 return ERR_NOT_SUSPENDED;
7446 tls->pending_invoke = g_new0 (InvokeData, 1);
7447 tls->pending_invoke->id = id;
7448 tls->pending_invoke->flags = flags;
7449 tls->pending_invoke->p = (guint8 *)g_malloc (end - p);
7450 memcpy (tls->pending_invoke->p, p, end - p);
7451 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
7452 tls->pending_invoke->suspend_count = suspend_count;
7453 tls->pending_invoke->nmethods = nmethods;
7455 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
7456 resume_thread (THREAD_TO_INTERNAL (thread));
7459 count = suspend_count;
7460 for (i = 0; i < count; ++i)
7465 case CMD_VM_ABORT_INVOKE: {
7466 int objid = decode_objid (p, &p, end);
7468 DebuggerTlsData *tls;
7472 err = get_object (objid, (MonoObject**)&thread);
7473 if (err != ERR_NONE)
7476 invoke_id = decode_int (p, &p, end);
7478 mono_loader_lock ();
7479 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7482 if (tls->abort_requested) {
7483 DEBUG_PRINTF (1, "Abort already requested.\n");
7484 mono_loader_unlock ();
7489 * Check whether we're still inside the mono_runtime_invoke_checked() and that it's
7490 * actually the correct invocation.
7492 * Careful, we do not stop the thread that's doing the invocation, so we can't
7493 * inspect its stack. However, invoke_method() also acquires the loader lock
7494 * when it's done, so we're safe here.
7498 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
7499 mono_loader_unlock ();
7500 return ERR_NO_INVOCATION;
7503 tls->abort_requested = TRUE;
7505 mono_thread_internal_abort (THREAD_TO_INTERNAL (thread));
7506 mono_loader_unlock ();
7510 case CMD_VM_SET_KEEPALIVE: {
7511 int timeout = decode_int (p, &p, end);
7512 agent_config.keepalive = timeout;
7514 #ifndef DISABLE_SOCKET_TRANSPORT
7521 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
7522 GHashTableIter iter, kiter;
7527 char *fname, *basename;
7528 gboolean ignore_case;
7529 GSList *class_list, *l;
7530 GPtrArray *res_classes, *res_domains;
7532 fname = decode_string (p, &p, end);
7533 ignore_case = decode_byte (p, &p, end);
7535 basename = dbg_path_get_basename (fname);
7537 res_classes = g_ptr_array_new ();
7538 res_domains = g_ptr_array_new ();
7540 mono_loader_lock ();
7541 g_hash_table_iter_init (&iter, domains);
7542 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7543 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
7545 /* Update 'source_file_to_class' cache */
7546 g_hash_table_iter_init (&kiter, info->loaded_classes);
7547 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
7548 if (!g_hash_table_lookup (info->source_files, klass)) {
7549 files = get_source_files_for_type (klass);
7550 g_hash_table_insert (info->source_files, klass, files);
7552 for (i = 0; i < files->len; ++i) {
7553 char *s = (char *)g_ptr_array_index (files, i);
7554 char *s2 = dbg_path_get_basename (s);
7557 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, s2);
7559 class_list = g_slist_prepend (class_list, klass);
7560 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
7562 class_list = g_slist_prepend (class_list, klass);
7563 g_hash_table_insert (info->source_file_to_class, s2, class_list);
7566 /* The _ignorecase hash contains the lowercase path */
7567 s3 = strdup_tolower (s2);
7568 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
7570 class_list = g_slist_prepend (class_list, klass);
7571 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
7573 class_list = g_slist_prepend (class_list, klass);
7574 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
7586 s = strdup_tolower (basename);
7587 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
7590 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, basename);
7593 for (l = class_list; l; l = l->next) {
7594 klass = (MonoClass *)l->data;
7596 g_ptr_array_add (res_classes, klass);
7597 g_ptr_array_add (res_domains, domain);
7600 mono_loader_unlock ();
7605 buffer_add_int (buf, res_classes->len);
7606 for (i = 0; i < res_classes->len; ++i)
7607 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7608 g_ptr_array_free (res_classes, TRUE);
7609 g_ptr_array_free (res_domains, TRUE);
7612 case CMD_VM_GET_TYPES: {
7613 GHashTableIter iter;
7617 gboolean ignore_case;
7618 GPtrArray *res_classes, *res_domains;
7619 MonoTypeNameParse info;
7621 name = decode_string (p, &p, end);
7622 ignore_case = decode_byte (p, &p, end);
7624 if (!mono_reflection_parse_type (name, &info)) {
7626 mono_reflection_free_type_info (&info);
7627 return ERR_INVALID_ARGUMENT;
7630 res_classes = g_ptr_array_new ();
7631 res_domains = g_ptr_array_new ();
7633 mono_loader_lock ();
7634 g_hash_table_iter_init (&iter, domains);
7635 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7637 gboolean type_resolve;
7641 mono_domain_assemblies_lock (domain);
7642 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7643 ass = (MonoAssembly *)tmp->data;
7647 type_resolve = TRUE;
7648 /* FIXME really okay to call while holding locks? */
7649 t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignore_case, &type_resolve, &error);
7650 mono_error_cleanup (&error);
7652 g_ptr_array_add (res_classes, mono_type_get_class (t));
7653 g_ptr_array_add (res_domains, domain);
7657 mono_domain_assemblies_unlock (domain);
7659 mono_loader_unlock ();
7662 mono_reflection_free_type_info (&info);
7664 buffer_add_int (buf, res_classes->len);
7665 for (i = 0; i < res_classes->len; ++i)
7666 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7667 g_ptr_array_free (res_classes, TRUE);
7668 g_ptr_array_free (res_domains, TRUE);
7671 case CMD_VM_START_BUFFERING:
7672 case CMD_VM_STOP_BUFFERING:
7673 /* Handled in the main loop */
7676 return ERR_NOT_IMPLEMENTED;
7683 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7689 case CMD_EVENT_REQUEST_SET: {
7691 int i, event_kind, suspend_policy, nmodifiers;
7695 MonoThread *step_thread;
7696 int step_thread_id = 0;
7697 StepDepth depth = STEP_DEPTH_INTO;
7698 StepSize size = STEP_SIZE_MIN;
7699 StepFilter filter = STEP_FILTER_NONE;
7703 event_kind = decode_byte (p, &p, end);
7704 suspend_policy = decode_byte (p, &p, end);
7705 nmodifiers = decode_byte (p, &p, end);
7707 req = (EventRequest *)g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7708 req->id = InterlockedIncrement (&event_request_id);
7709 req->event_kind = event_kind;
7710 req->suspend_policy = suspend_policy;
7711 req->nmodifiers = nmodifiers;
7714 for (i = 0; i < nmodifiers; ++i) {
7715 mod = (ModifierKind)decode_byte (p, &p, end);
7717 req->modifiers [i].kind = mod;
7718 if (mod == MOD_KIND_COUNT) {
7719 req->modifiers [i].data.count = decode_int (p, &p, end);
7720 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7721 method = decode_methodid (p, &p, end, &domain, &err);
7722 if (err != ERR_NONE)
7724 location = decode_long (p, &p, end);
7725 } else if (mod == MOD_KIND_STEP) {
7726 step_thread_id = decode_id (p, &p, end);
7727 size = (StepSize)decode_int (p, &p, end);
7728 depth = (StepDepth)decode_int (p, &p, end);
7729 if (CHECK_PROTOCOL_VERSION (2, 16))
7730 filter = (StepFilter)decode_int (p, &p, end);
7731 req->modifiers [i].data.filter = filter;
7732 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7733 /* Treat STEP_THOUGH the same as HIDDEN */
7734 req->modifiers [i].data.filter = (StepFilter)(req->modifiers [i].data.filter | STEP_FILTER_DEBUGGER_STEP_THROUGH);
7735 } else if (mod == MOD_KIND_THREAD_ONLY) {
7736 int id = decode_id (p, &p, end);
7738 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7739 if (err != ERR_NONE) {
7743 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7744 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7746 if (err != ERR_NONE)
7748 req->modifiers [i].caught = decode_byte (p, &p, end);
7749 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7750 if (CHECK_PROTOCOL_VERSION (2, 25))
7751 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7753 req->modifiers [i].subclasses = TRUE;
7754 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" : "");
7756 req->modifiers [i].data.exc_class = exc_class;
7758 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
7760 return ERR_INVALID_ARGUMENT;
7763 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7764 int n = decode_int (p, &p, end);
7767 // +1 because we don't know length and we use last element to check for end
7768 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n + 1);
7769 for (j = 0; j < n; ++j) {
7770 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7771 if (err != ERR_NONE) {
7772 g_free (req->modifiers [i].data.assemblies);
7776 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7777 int n = decode_int (p, &p, end);
7780 modifier = &req->modifiers [i];
7781 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7782 for (j = 0; j < n; ++j) {
7783 char *s = decode_string (p, &p, end);
7787 s2 = strdup_tolower (s);
7788 g_hash_table_insert (modifier->data.source_files, s2, s2);
7792 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7793 int n = decode_int (p, &p, end);
7796 modifier = &req->modifiers [i];
7797 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7798 for (j = 0; j < n; ++j) {
7799 char *s = decode_string (p, &p, end);
7802 g_hash_table_insert (modifier->data.type_names, s, s);
7806 return ERR_NOT_IMPLEMENTED;
7810 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7813 req->info = set_breakpoint (method, location, req, &error);
7814 if (!mono_error_ok (&error)) {
7816 DEBUG_PRINTF (1, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error));
7817 mono_error_cleanup (&error);
7818 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7820 } else if (req->event_kind == EVENT_KIND_STEP) {
7821 g_assert (step_thread_id);
7823 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7824 if (err != ERR_NONE) {
7829 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, filter, req);
7830 if (err != ERR_NONE) {
7834 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7835 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7836 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7837 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7838 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7839 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7841 if (req->nmodifiers) {
7843 return ERR_NOT_IMPLEMENTED;
7847 mono_loader_lock ();
7848 g_ptr_array_add (event_requests, req);
7850 if (agent_config.defer) {
7851 /* Transmit cached data to the client on receipt of the event request */
7852 switch (req->event_kind) {
7853 case EVENT_KIND_APPDOMAIN_CREATE:
7854 /* Emit load events for currently loaded domains */
7855 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7857 case EVENT_KIND_ASSEMBLY_LOAD:
7858 /* Emit load events for currently loaded assemblies */
7859 mono_domain_foreach (send_assemblies_for_domain, NULL);
7861 case EVENT_KIND_THREAD_START:
7862 /* Emit start events for currently started threads */
7863 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7865 case EVENT_KIND_TYPE_LOAD:
7866 /* Emit type load events for currently loaded types */
7867 mono_domain_foreach (send_types_for_domain, NULL);
7873 mono_loader_unlock ();
7875 buffer_add_int (buf, req->id);
7878 case CMD_EVENT_REQUEST_CLEAR: {
7879 int etype = decode_byte (p, &p, end);
7880 int req_id = decode_int (p, &p, end);
7882 // FIXME: Make a faster mapping from req_id to request
7883 mono_loader_lock ();
7884 clear_event_request (req_id, etype);
7885 mono_loader_unlock ();
7888 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7891 mono_loader_lock ();
7893 while (i < event_requests->len) {
7894 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
7896 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7897 clear_breakpoint ((MonoBreakpoint *)req->info);
7899 g_ptr_array_remove_index_fast (event_requests, i);
7905 mono_loader_unlock ();
7909 return ERR_NOT_IMPLEMENTED;
7916 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7922 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7923 buffer_add_domainid (buf, mono_get_root_domain ());
7926 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7927 domain = decode_domainid (p, &p, end, NULL, &err);
7928 if (err != ERR_NONE)
7930 buffer_add_string (buf, domain->friendly_name);
7933 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7938 domain = decode_domainid (p, &p, end, NULL, &err);
7939 if (err != ERR_NONE)
7941 mono_loader_lock ();
7943 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7946 buffer_add_int (buf, count);
7947 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7948 ass = (MonoAssembly *)tmp->data;
7949 buffer_add_assemblyid (buf, domain, ass);
7951 mono_loader_unlock ();
7954 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7955 domain = decode_domainid (p, &p, end, NULL, &err);
7956 if (err != ERR_NONE)
7959 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7962 case CMD_APPDOMAIN_GET_CORLIB: {
7963 domain = decode_domainid (p, &p, end, NULL, &err);
7964 if (err != ERR_NONE)
7967 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7970 case CMD_APPDOMAIN_CREATE_STRING: {
7974 domain = decode_domainid (p, &p, end, NULL, &err);
7975 if (err != ERR_NONE)
7977 s = decode_string (p, &p, end);
7979 o = mono_string_new (domain, s);
7980 buffer_add_objid (buf, (MonoObject*)o);
7983 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7986 MonoDomain *domain2;
7989 domain = decode_domainid (p, &p, end, NULL, &err);
7990 if (err != ERR_NONE)
7992 klass = decode_typeid (p, &p, end, &domain2, &err);
7993 if (err != ERR_NONE)
7997 g_assert (domain == domain2);
7999 o = mono_object_new_checked (domain, klass, &error);
8000 mono_error_assert_ok (&error);
8002 err = decode_value (&klass->byval_arg, domain, (guint8 *)mono_object_unbox (o), p, &p, end);
8003 if (err != ERR_NONE)
8006 buffer_add_objid (buf, o);
8010 return ERR_NOT_IMPLEMENTED;
8017 get_assembly_object_command (MonoDomain *domain, MonoAssembly *ass, Buffer *buf, MonoError *error)
8019 HANDLE_FUNCTION_ENTER();
8020 ErrorCode err = ERR_NONE;
8022 MonoReflectionAssemblyHandle o = mono_assembly_get_object_handle (domain, ass, error);
8023 if (MONO_HANDLE_IS_NULL (o)) {
8024 err = ERR_INVALID_OBJECT;
8027 buffer_add_objid (buf, MONO_HANDLE_RAW (MONO_HANDLE_CAST (MonoObject, o)));
8029 HANDLE_FUNCTION_RETURN_VAL (err);
8034 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8040 ass = decode_assemblyid (p, &p, end, &domain, &err);
8041 if (err != ERR_NONE)
8045 case CMD_ASSEMBLY_GET_LOCATION: {
8046 buffer_add_string (buf, mono_image_get_filename (ass->image));
8049 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
8053 if (ass->image->dynamic) {
8054 buffer_add_id (buf, 0);
8056 token = mono_image_get_entry_point (ass->image);
8058 buffer_add_id (buf, 0);
8061 m = mono_get_method_checked (ass->image, token, NULL, NULL, &error);
8063 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8064 buffer_add_methodid (buf, domain, m);
8069 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
8070 buffer_add_moduleid (buf, domain, ass->image);
8073 case CMD_ASSEMBLY_GET_OBJECT: {
8075 err = get_assembly_object_command (domain, ass, buf, &error);
8076 mono_error_cleanup (&error);
8079 case CMD_ASSEMBLY_GET_DOMAIN: {
8080 buffer_add_domainid (buf, domain);
8083 case CMD_ASSEMBLY_GET_TYPE: {
8085 char *s = decode_string (p, &p, end);
8086 gboolean ignorecase = decode_byte (p, &p, end);
8087 MonoTypeNameParse info;
8089 gboolean type_resolve, res;
8090 MonoDomain *d = mono_domain_get ();
8092 /* This is needed to be able to find referenced assemblies */
8093 res = mono_domain_set (domain, FALSE);
8096 if (!mono_reflection_parse_type (s, &info)) {
8099 if (info.assembly.name)
8101 t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignorecase, &type_resolve, &error);
8102 if (!is_ok (&error)) {
8103 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8104 mono_reflection_free_type_info (&info);
8106 return ERR_INVALID_ARGUMENT;
8109 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
8110 mono_reflection_free_type_info (&info);
8113 mono_domain_set (d, TRUE);
8117 case CMD_ASSEMBLY_GET_NAME: {
8119 MonoAssembly *mass = ass;
8121 name = g_strdup_printf (
8122 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
8124 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
8125 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
8126 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
8127 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
8129 buffer_add_string (buf, name);
8134 return ERR_NOT_IMPLEMENTED;
8141 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8147 case CMD_MODULE_GET_INFO: {
8148 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
8151 basename = g_path_get_basename (image->name);
8152 buffer_add_string (buf, basename); // name
8153 buffer_add_string (buf, image->module_name); // scopename
8154 buffer_add_string (buf, image->name); // fqname
8155 buffer_add_string (buf, mono_image_get_guid (image)); // guid
8156 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
8161 return ERR_NOT_IMPLEMENTED;
8168 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8174 case CMD_FIELD_GET_INFO: {
8175 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
8177 buffer_add_string (buf, f->name);
8178 buffer_add_typeid (buf, domain, f->parent);
8179 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
8180 buffer_add_int (buf, f->type->attrs);
8184 return ERR_NOT_IMPLEMENTED;
8191 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
8193 if (val && val->vtable->klass == mono_defaults.runtimetype_class) {
8194 /* Special case these so the client doesn't have to handle Type objects */
8196 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
8197 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
8198 } else if (MONO_TYPE_IS_REFERENCE (t))
8199 buffer_add_value (buf, t, &val, domain);
8201 buffer_add_value (buf, t, mono_object_unbox (val), domain);
8205 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
8211 buffer_add_int (buf, 0);
8215 for (i = 0; i < cinfo->num_attrs; ++i) {
8216 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
8219 buffer_add_int (buf, nattrs);
8221 for (i = 0; i < cinfo->num_attrs; ++i) {
8222 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
8223 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
8224 MonoArray *typed_args, *named_args;
8226 CattrNamedArg *arginfo = NULL;
8229 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
8230 if (!mono_error_ok (&error)) {
8231 DEBUG_PRINTF (2, "[dbg] mono_reflection_create_custom_attr_data_args () failed with: '%s'\n", mono_error_get_message (&error));
8232 mono_error_cleanup (&error);
8233 return ERR_LOADER_ERROR;
8236 buffer_add_methodid (buf, domain, attr->ctor);
8240 buffer_add_int (buf, mono_array_length (typed_args));
8241 for (j = 0; j < mono_array_length (typed_args); ++j) {
8242 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
8244 t = mono_method_signature (attr->ctor)->params [j];
8246 buffer_add_cattr_arg (buf, t, domain, val);
8249 buffer_add_int (buf, 0);
8254 buffer_add_int (buf, mono_array_length (named_args));
8256 for (j = 0; j < mono_array_length (named_args); ++j) {
8257 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
8259 if (arginfo [j].prop) {
8260 buffer_add_byte (buf, 0x54);
8261 buffer_add_propertyid (buf, domain, arginfo [j].prop);
8262 } else if (arginfo [j].field) {
8263 buffer_add_byte (buf, 0x53);
8264 buffer_add_fieldid (buf, domain, arginfo [j].field);
8266 g_assert_not_reached ();
8269 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
8272 buffer_add_int (buf, 0);
8281 /* FIXME: Code duplication with icall.c */
8283 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
8288 mono_class_setup_interfaces (klass, error);
8289 if (!mono_error_ok (error))
8292 for (i = 0; i < klass->interface_count; i++) {
8293 ic = klass->interfaces [i];
8294 g_hash_table_insert (ifaces, ic, ic);
8296 collect_interfaces (ic, ifaces, error);
8297 if (!mono_error_ok (error))
8303 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8315 case CMD_TYPE_GET_INFO: {
8316 buffer_add_string (buf, klass->name_space);
8317 buffer_add_string (buf, klass->name);
8319 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
8320 buffer_add_string (buf, name);
8322 buffer_add_assemblyid (buf, domain, klass->image->assembly);
8323 buffer_add_moduleid (buf, domain, klass->image);
8324 buffer_add_typeid (buf, domain, klass->parent);
8325 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
8326 buffer_add_typeid (buf, domain, klass->element_class);
8328 buffer_add_id (buf, 0);
8329 buffer_add_int (buf, klass->type_token);
8330 buffer_add_byte (buf, klass->rank);
8331 buffer_add_int (buf, mono_class_get_flags (klass));
8333 type = &klass->byval_arg;
8334 // FIXME: Can't decide whenever a class represents a byref type
8337 if (type->type == MONO_TYPE_PTR)
8339 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
8341 if (type->type == MONO_TYPE_VALUETYPE)
8343 if (klass->enumtype)
8345 if (mono_class_is_gtd (klass))
8347 if (mono_class_is_gtd (klass) || mono_class_is_ginst (klass))
8349 buffer_add_byte (buf, b);
8352 while ((nested = mono_class_get_nested_types (klass, &iter)))
8354 buffer_add_int (buf, nnested);
8356 while ((nested = mono_class_get_nested_types (klass, &iter)))
8357 buffer_add_typeid (buf, domain, nested);
8358 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8359 if (mono_class_is_gtd (klass))
8360 buffer_add_typeid (buf, domain, klass);
8361 else if (mono_class_is_ginst (klass))
8362 buffer_add_typeid (buf, domain, mono_class_get_generic_class (klass)->container_class);
8364 buffer_add_id (buf, 0);
8366 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8369 if (mono_class_is_ginst (klass)) {
8370 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
8372 count = inst->type_argc;
8373 buffer_add_int (buf, count);
8374 for (i = 0; i < count; i++)
8375 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8376 } else if (mono_class_is_gtd (klass)) {
8377 MonoGenericContainer *container = mono_class_get_generic_container (klass);
8380 count = container->type_argc;
8381 buffer_add_int (buf, count);
8382 for (i = 0; i < count; i++) {
8383 pklass = mono_class_from_generic_parameter_internal (mono_generic_container_get_param (container, i));
8384 buffer_add_typeid (buf, domain, pklass);
8387 buffer_add_int (buf, 0);
8392 case CMD_TYPE_GET_METHODS: {
8395 gpointer iter = NULL;
8398 mono_class_setup_methods (klass);
8400 nmethods = mono_class_num_methods (klass);
8402 buffer_add_int (buf, nmethods);
8404 while ((m = mono_class_get_methods (klass, &iter))) {
8405 buffer_add_methodid (buf, domain, m);
8408 g_assert (i == nmethods);
8411 case CMD_TYPE_GET_FIELDS: {
8414 gpointer iter = NULL;
8417 nfields = mono_class_num_fields (klass);
8419 buffer_add_int (buf, nfields);
8421 while ((f = mono_class_get_fields (klass, &iter))) {
8422 buffer_add_fieldid (buf, domain, f);
8423 buffer_add_string (buf, f->name);
8424 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
8425 buffer_add_int (buf, f->type->attrs);
8428 g_assert (i == nfields);
8431 case CMD_TYPE_GET_PROPERTIES: {
8434 gpointer iter = NULL;
8437 nprops = mono_class_num_properties (klass);
8439 buffer_add_int (buf, nprops);
8441 while ((p = mono_class_get_properties (klass, &iter))) {
8442 buffer_add_propertyid (buf, domain, p);
8443 buffer_add_string (buf, p->name);
8444 buffer_add_methodid (buf, domain, p->get);
8445 buffer_add_methodid (buf, domain, p->set);
8446 buffer_add_int (buf, p->attrs);
8449 g_assert (i == nprops);
8452 case CMD_TYPE_GET_CATTRS: {
8453 MonoClass *attr_klass;
8454 MonoCustomAttrInfo *cinfo;
8456 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8457 /* attr_klass can be NULL */
8458 if (err != ERR_NONE)
8461 cinfo = mono_custom_attrs_from_class_checked (klass, &error);
8462 if (!is_ok (&error)) {
8463 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8464 return ERR_LOADER_ERROR;
8467 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8468 if (err != ERR_NONE)
8472 case CMD_TYPE_GET_FIELD_CATTRS: {
8473 MonoClass *attr_klass;
8474 MonoCustomAttrInfo *cinfo;
8475 MonoClassField *field;
8477 field = decode_fieldid (p, &p, end, NULL, &err);
8478 if (err != ERR_NONE)
8480 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8481 if (err != ERR_NONE)
8484 cinfo = mono_custom_attrs_from_field_checked (klass, field, &error);
8485 if (!is_ok (&error)) {
8486 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8487 return ERR_LOADER_ERROR;
8490 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8491 if (err != ERR_NONE)
8495 case CMD_TYPE_GET_PROPERTY_CATTRS: {
8496 MonoClass *attr_klass;
8497 MonoCustomAttrInfo *cinfo;
8500 prop = decode_propertyid (p, &p, end, NULL, &err);
8501 if (err != ERR_NONE)
8503 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8504 if (err != ERR_NONE)
8507 cinfo = mono_custom_attrs_from_property_checked (klass, prop, &error);
8508 if (!is_ok (&error)) {
8509 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8510 return ERR_LOADER_ERROR;
8513 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8514 if (err != ERR_NONE)
8518 case CMD_TYPE_GET_VALUES:
8519 case CMD_TYPE_GET_VALUES_2: {
8526 MonoThread *thread_obj;
8527 MonoInternalThread *thread = NULL;
8528 guint32 special_static_type;
8530 if (command == CMD_TYPE_GET_VALUES_2) {
8531 int objid = decode_objid (p, &p, end);
8534 err = get_object (objid, (MonoObject**)&thread_obj);
8535 if (err != ERR_NONE)
8538 thread = THREAD_TO_INTERNAL (thread_obj);
8541 len = decode_int (p, &p, end);
8542 for (i = 0; i < len; ++i) {
8543 f = decode_fieldid (p, &p, end, NULL, &err);
8544 if (err != ERR_NONE)
8547 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8548 return ERR_INVALID_FIELDID;
8549 special_static_type = mono_class_field_get_special_static_type (f);
8550 if (special_static_type != SPECIAL_STATIC_NONE) {
8551 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
8552 return ERR_INVALID_FIELDID;
8555 /* Check that the field belongs to the object */
8557 for (k = klass; k; k = k->parent) {
8558 if (k == f->parent) {
8564 return ERR_INVALID_FIELDID;
8566 vtable = mono_class_vtable (domain, f->parent);
8567 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8568 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val, &error);
8569 if (!is_ok (&error))
8570 return ERR_INVALID_FIELDID;
8571 buffer_add_value (buf, f->type, val, domain);
8576 case CMD_TYPE_SET_VALUES: {
8584 len = decode_int (p, &p, end);
8585 for (i = 0; i < len; ++i) {
8586 f = decode_fieldid (p, &p, end, NULL, &err);
8587 if (err != ERR_NONE)
8590 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8591 return ERR_INVALID_FIELDID;
8592 if (mono_class_field_is_special_static (f))
8593 return ERR_INVALID_FIELDID;
8595 /* Check that the field belongs to the object */
8597 for (k = klass; k; k = k->parent) {
8598 if (k == f->parent) {
8604 return ERR_INVALID_FIELDID;
8606 // FIXME: Check for literal/const
8608 vtable = mono_class_vtable (domain, f->parent);
8609 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8610 err = decode_value (f->type, domain, val, p, &p, end);
8611 if (err != ERR_NONE) {
8615 if (MONO_TYPE_IS_REFERENCE (f->type))
8616 mono_field_static_set_value (vtable, f, *(gpointer*)val);
8618 mono_field_static_set_value (vtable, f, val);
8623 case CMD_TYPE_GET_OBJECT: {
8624 MonoObject *o = (MonoObject*)mono_type_get_object_checked (domain, &klass->byval_arg, &error);
8625 if (!mono_error_ok (&error)) {
8626 mono_error_cleanup (&error);
8627 return ERR_INVALID_OBJECT;
8629 buffer_add_objid (buf, o);
8632 case CMD_TYPE_GET_SOURCE_FILES:
8633 case CMD_TYPE_GET_SOURCE_FILES_2: {
8634 char *source_file, *base;
8638 files = get_source_files_for_type (klass);
8640 buffer_add_int (buf, files->len);
8641 for (i = 0; i < files->len; ++i) {
8642 source_file = (char *)g_ptr_array_index (files, i);
8643 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8644 buffer_add_string (buf, source_file);
8646 base = dbg_path_get_basename (source_file);
8647 buffer_add_string (buf, base);
8650 g_free (source_file);
8652 g_ptr_array_free (files, TRUE);
8655 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8656 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8658 if (err != ERR_NONE)
8660 if (mono_class_is_assignable_from (klass, oklass))
8661 buffer_add_byte (buf, 1);
8663 buffer_add_byte (buf, 0);
8666 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8667 char *name = decode_string (p, &p, end);
8668 int i, flags = decode_int (p, &p, end);
8672 error_init (&error);
8673 array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &error);
8674 if (!is_ok (&error)) {
8675 mono_error_cleanup (&error);
8676 return ERR_LOADER_ERROR;
8678 buffer_add_int (buf, array->len);
8679 for (i = 0; i < array->len; ++i) {
8680 MonoMethod *method = (MonoMethod *)g_ptr_array_index (array, i);
8681 buffer_add_methodid (buf, domain, method);
8684 g_ptr_array_free (array, TRUE);
8688 case CMD_TYPE_GET_INTERFACES: {
8690 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8691 MonoClass *tclass, *iface;
8692 GHashTableIter iter;
8696 for (parent = tclass; parent; parent = parent->parent) {
8697 mono_class_setup_interfaces (parent, &error);
8698 if (!mono_error_ok (&error))
8699 return ERR_LOADER_ERROR;
8700 collect_interfaces (parent, iface_hash, &error);
8701 if (!mono_error_ok (&error))
8702 return ERR_LOADER_ERROR;
8705 buffer_add_int (buf, g_hash_table_size (iface_hash));
8707 g_hash_table_iter_init (&iter, iface_hash);
8708 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8709 buffer_add_typeid (buf, domain, iface);
8710 g_hash_table_destroy (iface_hash);
8713 case CMD_TYPE_GET_INTERFACE_MAP: {
8714 int tindex, ioffset;
8715 gboolean variance_used;
8717 int len, nmethods, i;
8721 len = decode_int (p, &p, end);
8722 mono_class_setup_vtable (klass);
8724 for (tindex = 0; tindex < len; ++tindex) {
8725 iclass = decode_typeid (p, &p, end, NULL, &err);
8726 if (err != ERR_NONE)
8729 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8731 return ERR_INVALID_ARGUMENT;
8733 nmethods = mono_class_num_methods (iclass);
8734 buffer_add_int (buf, nmethods);
8737 while ((method = mono_class_get_methods (iclass, &iter))) {
8738 buffer_add_methodid (buf, domain, method);
8740 for (i = 0; i < nmethods; ++i)
8741 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
8745 case CMD_TYPE_IS_INITIALIZED: {
8746 MonoVTable *vtable = mono_class_vtable (domain, klass);
8749 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8751 buffer_add_int (buf, 0);
8754 case CMD_TYPE_CREATE_INSTANCE: {
8758 obj = mono_object_new_checked (domain, klass, &error);
8759 mono_error_assert_ok (&error);
8760 buffer_add_objid (buf, obj);
8764 return ERR_NOT_IMPLEMENTED;
8771 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8774 MonoDomain *old_domain;
8778 klass = decode_typeid (p, &p, end, &domain, &err);
8779 if (err != ERR_NONE)
8782 old_domain = mono_domain_get ();
8784 mono_domain_set (domain, TRUE);
8786 err = type_commands_internal (command, klass, domain, p, end, buf);
8788 mono_domain_set (old_domain, TRUE);
8794 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8796 MonoMethodHeader *header;
8800 case CMD_METHOD_GET_NAME: {
8801 buffer_add_string (buf, method->name);
8804 case CMD_METHOD_GET_DECLARING_TYPE: {
8805 buffer_add_typeid (buf, domain, method->klass);
8808 case CMD_METHOD_GET_DEBUG_INFO: {
8810 MonoDebugMethodInfo *minfo;
8812 int i, j, n_il_offsets;
8814 GPtrArray *source_file_list;
8815 MonoSymSeqPoint *sym_seq_points;
8817 header = mono_method_get_header_checked (method, &error);
8819 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8820 buffer_add_int (buf, 0);
8821 buffer_add_string (buf, "");
8822 buffer_add_int (buf, 0);
8826 minfo = mono_debug_lookup_method (method);
8828 buffer_add_int (buf, header->code_size);
8829 buffer_add_string (buf, "");
8830 buffer_add_int (buf, 0);
8831 mono_metadata_free_mh (header);
8835 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, &source_files, &sym_seq_points, &n_il_offsets);
8836 buffer_add_int (buf, header->code_size);
8837 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8838 buffer_add_int (buf, source_file_list->len);
8839 for (i = 0; i < source_file_list->len; ++i) {
8840 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
8841 buffer_add_string (buf, sinfo->source_file);
8842 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8843 for (j = 0; j < 16; ++j)
8844 buffer_add_byte (buf, sinfo->hash [j]);
8848 buffer_add_string (buf, source_file);
8850 buffer_add_int (buf, n_il_offsets);
8851 DEBUG_PRINTF (10, "Line number table for method %s:\n", mono_method_full_name (method, TRUE));
8852 for (i = 0; i < n_il_offsets; ++i) {
8853 MonoSymSeqPoint *sp = &sym_seq_points [i];
8854 const char *srcfile = "";
8856 if (source_files [i] != -1) {
8857 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, source_files [i]);
8858 srcfile = sinfo->source_file;
8860 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);
8861 buffer_add_int (buf, sp->il_offset);
8862 buffer_add_int (buf, sp->line);
8863 if (CHECK_PROTOCOL_VERSION (2, 13))
8864 buffer_add_int (buf, source_files [i]);
8865 if (CHECK_PROTOCOL_VERSION (2, 19))
8866 buffer_add_int (buf, sp->column);
8867 if (CHECK_PROTOCOL_VERSION (2, 32)) {
8868 buffer_add_int (buf, sp->end_line);
8869 buffer_add_int (buf, sp->end_column);
8872 g_free (source_file);
8873 g_free (source_files);
8874 g_free (sym_seq_points);
8875 g_ptr_array_free (source_file_list, TRUE);
8876 mono_metadata_free_mh (header);
8879 case CMD_METHOD_GET_PARAM_INFO: {
8880 MonoMethodSignature *sig = mono_method_signature (method);
8884 /* FIXME: mono_class_from_mono_type () and byrefs */
8886 /* FIXME: Use a smaller encoding */
8887 buffer_add_int (buf, sig->call_convention);
8888 buffer_add_int (buf, sig->param_count);
8889 buffer_add_int (buf, sig->generic_param_count);
8890 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
8891 for (i = 0; i < sig->param_count; ++i) {
8893 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
8896 /* Emit parameter names */
8897 names = g_new (char *, sig->param_count);
8898 mono_method_get_param_names (method, (const char **) names);
8899 for (i = 0; i < sig->param_count; ++i)
8900 buffer_add_string (buf, names [i]);
8905 case CMD_METHOD_GET_LOCALS_INFO: {
8908 MonoDebugLocalsInfo *locals;
8909 int *locals_map = NULL;
8911 header = mono_method_get_header_checked (method, &error);
8913 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8914 return ERR_INVALID_ARGUMENT;
8917 locals = mono_debug_lookup_locals (method);
8919 if (CHECK_PROTOCOL_VERSION (2, 43)) {
8921 buffer_add_int (buf, 1);
8922 buffer_add_int (buf, 0);
8923 buffer_add_int (buf, header->code_size);
8925 buffer_add_int (buf, header->num_locals);
8927 for (i = 0; i < header->num_locals; ++i) {
8928 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
8931 for (i = 0; i < header->num_locals; ++i) {
8933 sprintf (lname, "V_%d", i);
8934 buffer_add_string (buf, lname);
8937 for (i = 0; i < header->num_locals; ++i) {
8938 buffer_add_int (buf, 0);
8939 buffer_add_int (buf, header->code_size);
8942 if (CHECK_PROTOCOL_VERSION (2, 43)) {
8944 buffer_add_int (buf, locals->num_blocks);
8946 for (i = 0; i < locals->num_blocks; ++i) {
8947 buffer_add_int (buf, locals->code_blocks [i].start_offset - last_start);
8948 buffer_add_int (buf, locals->code_blocks [i].end_offset - locals->code_blocks [i].start_offset);
8949 last_start = locals->code_blocks [i].start_offset;
8953 num_locals = locals->num_locals;
8954 buffer_add_int (buf, num_locals);
8957 for (i = 0; i < num_locals; ++i) {
8958 g_assert (locals->locals [i].index < header->num_locals);
8959 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [locals->locals [i].index]));
8962 for (i = 0; i < num_locals; ++i)
8963 buffer_add_string (buf, locals->locals [i].name);
8965 for (i = 0; i < num_locals; ++i) {
8966 if (locals->locals [i].block) {
8967 buffer_add_int (buf, locals->locals [i].block->start_offset);
8968 buffer_add_int (buf, locals->locals [i].block->end_offset);
8970 buffer_add_int (buf, 0);
8971 buffer_add_int (buf, header->code_size);
8975 mono_metadata_free_mh (header);
8978 mono_debug_free_locals (locals);
8979 g_free (locals_map);
8983 case CMD_METHOD_GET_INFO:
8984 buffer_add_int (buf, method->flags);
8985 buffer_add_int (buf, method->iflags);
8986 buffer_add_int (buf, method->token);
8987 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8989 if (method->is_generic)
8991 if (mono_method_signature (method)->generic_param_count)
8993 buffer_add_byte (buf, attrs);
8994 if (method->is_generic || method->is_inflated) {
8997 if (method->is_generic) {
9000 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
9002 result = imethod->declaring;
9003 if (imethod->context.class_inst) {
9004 MonoClass *klass = ((MonoMethod *) imethod)->klass;
9005 /*Generic methods gets the context of the GTD.*/
9006 if (mono_class_get_context (klass)) {
9008 result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), &error);
9009 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9014 buffer_add_methodid (buf, domain, result);
9016 buffer_add_id (buf, 0);
9018 if (CHECK_PROTOCOL_VERSION (2, 15)) {
9019 if (mono_method_signature (method)->generic_param_count) {
9022 if (method->is_inflated) {
9023 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
9025 count = inst->type_argc;
9026 buffer_add_int (buf, count);
9028 for (i = 0; i < count; i++)
9029 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
9031 buffer_add_int (buf, 0);
9033 } else if (method->is_generic) {
9034 MonoGenericContainer *container = mono_method_get_generic_container (method);
9036 count = mono_method_signature (method)->generic_param_count;
9037 buffer_add_int (buf, count);
9038 for (i = 0; i < count; i++) {
9039 MonoGenericParam *param = mono_generic_container_get_param (container, i);
9040 MonoClass *pklass = mono_class_from_generic_parameter_internal (param);
9041 buffer_add_typeid (buf, domain, pklass);
9044 buffer_add_int (buf, 0);
9047 buffer_add_int (buf, 0);
9052 case CMD_METHOD_GET_BODY: {
9056 header = mono_method_get_header_checked (method, &error);
9058 mono_error_cleanup (&error); /* FIXME don't swallow the error */
9059 buffer_add_int (buf, 0);
9061 if (CHECK_PROTOCOL_VERSION (2, 18))
9062 buffer_add_int (buf, 0);
9064 buffer_add_int (buf, header->code_size);
9065 for (i = 0; i < header->code_size; ++i)
9066 buffer_add_byte (buf, header->code [i]);
9068 if (CHECK_PROTOCOL_VERSION (2, 18)) {
9069 buffer_add_int (buf, header->num_clauses);
9070 for (i = 0; i < header->num_clauses; ++i) {
9071 MonoExceptionClause *clause = &header->clauses [i];
9073 buffer_add_int (buf, clause->flags);
9074 buffer_add_int (buf, clause->try_offset);
9075 buffer_add_int (buf, clause->try_len);
9076 buffer_add_int (buf, clause->handler_offset);
9077 buffer_add_int (buf, clause->handler_len);
9078 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
9079 buffer_add_typeid (buf, domain, clause->data.catch_class);
9080 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
9081 buffer_add_int (buf, clause->data.filter_offset);
9085 mono_metadata_free_mh (header);
9090 case CMD_METHOD_RESOLVE_TOKEN: {
9091 guint32 token = decode_int (p, &p, end);
9094 switch (mono_metadata_token_code (token)) {
9095 case MONO_TOKEN_STRING: {
9100 s = mono_ldstr_checked (domain, method->klass->image, mono_metadata_token_index (token), &error);
9101 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
9103 s2 = mono_string_to_utf8_checked (s, &error);
9104 mono_error_assert_ok (&error);
9106 buffer_add_byte (buf, TOKEN_TYPE_STRING);
9107 buffer_add_string (buf, s2);
9114 MonoClass *handle_class;
9116 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
9117 val = mono_method_get_wrapper_data (method, token);
9118 handle_class = (MonoClass *)mono_method_get_wrapper_data (method, token + 1);
9120 if (handle_class == NULL) {
9121 // Can't figure out the token type
9122 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
9126 val = mono_ldtoken_checked (method->klass->image, token, &handle_class, NULL, &error);
9128 g_error ("Could not load token due to %s", mono_error_get_message (&error));
9131 if (handle_class == mono_defaults.typehandle_class) {
9132 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
9133 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
9134 buffer_add_typeid (buf, domain, (MonoClass *) val);
9136 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
9137 } else if (handle_class == mono_defaults.fieldhandle_class) {
9138 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
9139 buffer_add_fieldid (buf, domain, (MonoClassField *)val);
9140 } else if (handle_class == mono_defaults.methodhandle_class) {
9141 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
9142 buffer_add_methodid (buf, domain, (MonoMethod *)val);
9143 } else if (handle_class == mono_defaults.string_class) {
9146 s = mono_string_to_utf8_checked ((MonoString *)val, &error);
9147 mono_error_assert_ok (&error);
9148 buffer_add_byte (buf, TOKEN_TYPE_STRING);
9149 buffer_add_string (buf, s);
9152 g_assert_not_reached ();
9159 case CMD_METHOD_GET_CATTRS: {
9161 MonoClass *attr_klass;
9162 MonoCustomAttrInfo *cinfo;
9164 attr_klass = decode_typeid (p, &p, end, NULL, &err);
9165 /* attr_klass can be NULL */
9166 if (err != ERR_NONE)
9169 cinfo = mono_custom_attrs_from_method_checked (method, &error);
9170 if (!is_ok (&error)) {
9171 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
9172 return ERR_LOADER_ERROR;
9175 err = buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
9176 if (err != ERR_NONE)
9180 case CMD_METHOD_MAKE_GENERIC_METHOD: {
9182 MonoType **type_argv;
9186 MonoGenericInst *ginst;
9187 MonoGenericContext tmp_context;
9188 MonoMethod *inflated;
9190 type_argc = decode_int (p, &p, end);
9191 type_argv = g_new0 (MonoType*, type_argc);
9192 for (i = 0; i < type_argc; ++i) {
9193 klass = decode_typeid (p, &p, end, &d, &err);
9194 if (err != ERR_NONE) {
9200 return ERR_INVALID_ARGUMENT;
9202 type_argv [i] = &klass->byval_arg;
9204 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
9206 tmp_context.class_inst = mono_class_is_ginst (method->klass) ? mono_class_get_generic_class (method->klass)->context.class_inst : NULL;
9207 tmp_context.method_inst = ginst;
9209 inflated = mono_class_inflate_generic_method_checked (method, &tmp_context, &error);
9210 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9211 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
9212 return ERR_INVALID_ARGUMENT;
9213 buffer_add_methodid (buf, domain, inflated);
9217 return ERR_NOT_IMPLEMENTED;
9224 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9227 MonoDomain *old_domain;
9231 method = decode_methodid (p, &p, end, &domain, &err);
9232 if (err != ERR_NONE)
9235 old_domain = mono_domain_get ();
9237 mono_domain_set (domain, TRUE);
9239 err = method_commands_internal (command, method, domain, p, end, buf);
9241 mono_domain_set (old_domain, TRUE);
9247 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9249 int objid = decode_objid (p, &p, end);
9251 MonoThread *thread_obj;
9252 MonoInternalThread *thread;
9254 err = get_object (objid, (MonoObject**)&thread_obj);
9255 if (err != ERR_NONE)
9258 thread = THREAD_TO_INTERNAL (thread_obj);
9261 case CMD_THREAD_GET_NAME: {
9263 gunichar2 *s = mono_thread_get_name (thread, &name_len);
9266 buffer_add_int (buf, 0);
9271 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
9273 buffer_add_int (buf, len);
9274 buffer_add_data (buf, (guint8*)name, len);
9279 case CMD_THREAD_GET_FRAME_INFO: {
9280 DebuggerTlsData *tls;
9281 int i, start_frame, length;
9283 // Wait for suspending if it already started
9284 // FIXME: Races with suspend_count
9285 while (!is_suspended ()) {
9287 wait_for_suspend ();
9291 wait_for_suspend ();
9292 if (!is_suspended ())
9293 return ERR_NOT_SUSPENDED;
9296 start_frame = decode_int (p, &p, end);
9297 length = decode_int (p, &p, end);
9299 if (start_frame != 0 || length != -1)
9300 return ERR_NOT_IMPLEMENTED;
9302 mono_loader_lock ();
9303 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9304 mono_loader_unlock ();
9307 compute_frame_info (thread, tls);
9309 buffer_add_int (buf, tls->frame_count);
9310 for (i = 0; i < tls->frame_count; ++i) {
9311 buffer_add_int (buf, tls->frames [i]->id);
9312 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
9313 buffer_add_int (buf, tls->frames [i]->il_offset);
9315 * Instead of passing the frame type directly to the client, we associate
9316 * it with the previous frame using a set of flags. This avoids lots of
9317 * conditional code in the client, since a frame whose type isn't
9318 * FRAME_TYPE_MANAGED has no method, location, etc.
9320 buffer_add_byte (buf, tls->frames [i]->flags);
9325 case CMD_THREAD_GET_STATE:
9326 buffer_add_int (buf, thread->state);
9328 case CMD_THREAD_GET_INFO:
9329 buffer_add_byte (buf, thread->threadpool_thread);
9331 case CMD_THREAD_GET_ID:
9332 buffer_add_long (buf, (guint64)(gsize)thread);
9334 case CMD_THREAD_GET_TID:
9335 buffer_add_long (buf, (guint64)thread->tid);
9337 case CMD_THREAD_SET_IP: {
9338 DebuggerTlsData *tls;
9341 MonoSeqPointInfo *seq_points;
9346 method = decode_methodid (p, &p, end, &domain, &err);
9347 if (err != ERR_NONE)
9349 il_offset = decode_long (p, &p, end);
9351 while (!is_suspended ()) {
9353 wait_for_suspend ();
9356 mono_loader_lock ();
9357 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9358 mono_loader_unlock ();
9361 compute_frame_info (thread, tls);
9362 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
9363 return ERR_INVALID_ARGUMENT;
9365 found_sp = mono_find_seq_point (domain, method, il_offset, &seq_points, &sp);
9367 g_assert (seq_points);
9370 return ERR_INVALID_ARGUMENT;
9372 // FIXME: Check that the ip change is safe
9374 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);
9375 MONO_CONTEXT_SET_IP (&tls->restore_state.ctx, (guint8*)tls->frames [0]->ji->code_start + sp.native_offset);
9379 return ERR_NOT_IMPLEMENTED;
9386 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9390 MonoThread *thread_obj;
9391 MonoInternalThread *thread;
9392 int pos, i, len, frame_idx;
9393 DebuggerTlsData *tls;
9395 MonoDebugMethodJitInfo *jit;
9396 MonoMethodSignature *sig;
9398 MonoMethodHeader *header;
9400 objid = decode_objid (p, &p, end);
9401 err = get_object (objid, (MonoObject**)&thread_obj);
9402 if (err != ERR_NONE)
9405 thread = THREAD_TO_INTERNAL (thread_obj);
9407 id = decode_id (p, &p, end);
9409 mono_loader_lock ();
9410 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9411 mono_loader_unlock ();
9414 for (i = 0; i < tls->frame_count; ++i) {
9415 if (tls->frames [i]->id == id)
9418 if (i == tls->frame_count)
9419 return ERR_INVALID_FRAMEID;
9422 frame = tls->frames [frame_idx];
9424 /* This is supported for frames without has_ctx etc. set */
9425 if (command == CMD_STACK_FRAME_GET_DOMAIN) {
9426 if (CHECK_PROTOCOL_VERSION (2, 38))
9427 buffer_add_domainid (buf, frame->domain);
9431 if (!frame->has_ctx)
9432 return ERR_ABSENT_INFORMATION;
9434 if (!ensure_jit (frame))
9435 return ERR_ABSENT_INFORMATION;
9439 sig = mono_method_signature (frame->actual_method);
9441 if (!jit->has_var_info || !mono_get_seq_points (frame->domain, frame->actual_method))
9443 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
9445 return ERR_ABSENT_INFORMATION;
9448 case CMD_STACK_FRAME_GET_VALUES: {
9450 len = decode_int (p, &p, end);
9451 header = mono_method_get_header_checked (frame->actual_method, &error);
9452 mono_error_assert_ok (&error); /* FIXME report error */
9454 for (i = 0; i < len; ++i) {
9455 pos = decode_int (p, &p, end);
9460 DEBUG_PRINTF (4, "[dbg] send arg %d.\n", pos);
9462 g_assert (pos >= 0 && pos < jit->num_params);
9464 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
9466 MonoDebugLocalsInfo *locals;
9468 locals = mono_debug_lookup_locals (frame->method);
9470 g_assert (pos < locals->num_locals);
9471 pos = locals->locals [pos].index;
9472 mono_debug_free_locals (locals);
9474 g_assert (pos >= 0 && pos < jit->num_locals);
9476 DEBUG_PRINTF (4, "[dbg] send local %d.\n", pos);
9478 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
9481 mono_metadata_free_mh (header);
9484 case CMD_STACK_FRAME_GET_THIS: {
9485 if (frame->api_method->klass->valuetype) {
9486 if (!sig->hasthis) {
9487 MonoObject *p = NULL;
9488 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
9490 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9493 if (!sig->hasthis) {
9494 MonoObject *p = NULL;
9495 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
9497 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9502 case CMD_STACK_FRAME_SET_VALUES: {
9506 MonoDebugVarInfo *var;
9508 len = decode_int (p, &p, end);
9509 header = mono_method_get_header_checked (frame->actual_method, &error);
9510 mono_error_assert_ok (&error); /* FIXME report error */
9512 for (i = 0; i < len; ++i) {
9513 pos = decode_int (p, &p, end);
9518 g_assert (pos >= 0 && pos < jit->num_params);
9520 t = sig->params [pos];
9521 var = &jit->params [pos];
9523 MonoDebugLocalsInfo *locals;
9525 locals = mono_debug_lookup_locals (frame->method);
9527 g_assert (pos < locals->num_locals);
9528 pos = locals->locals [pos].index;
9529 mono_debug_free_locals (locals);
9531 g_assert (pos >= 0 && pos < jit->num_locals);
9533 t = header->locals [pos];
9534 var = &jit->locals [pos];
9537 if (MONO_TYPE_IS_REFERENCE (t))
9538 val_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
9540 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9541 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9542 if (err != ERR_NONE)
9545 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9547 mono_metadata_free_mh (header);
9550 case CMD_STACK_FRAME_GET_DOMAIN: {
9551 if (CHECK_PROTOCOL_VERSION (2, 38))
9552 buffer_add_domainid (buf, frame->domain);
9555 case CMD_STACK_FRAME_SET_THIS: {
9558 MonoDebugVarInfo *var;
9560 t = &frame->actual_method->klass->byval_arg;
9561 /* Checked by the sender */
9562 g_assert (MONO_TYPE_ISSTRUCT (t));
9563 var = jit->this_var;
9566 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9567 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9568 if (err != ERR_NONE)
9571 set_var (&frame->actual_method->klass->this_arg, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9575 return ERR_NOT_IMPLEMENTED;
9582 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9585 int objid, index, len, i, esize;
9589 objid = decode_objid (p, &p, end);
9590 err = get_object (objid, (MonoObject**)&arr);
9591 if (err != ERR_NONE)
9595 case CMD_ARRAY_REF_GET_LENGTH:
9596 buffer_add_int (buf, arr->obj.vtable->klass->rank);
9598 buffer_add_int (buf, arr->max_length);
9599 buffer_add_int (buf, 0);
9601 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
9602 buffer_add_int (buf, arr->bounds [i].length);
9603 buffer_add_int (buf, arr->bounds [i].lower_bound);
9607 case CMD_ARRAY_REF_GET_VALUES:
9608 index = decode_int (p, &p, end);
9609 len = decode_int (p, &p, end);
9611 g_assert (index >= 0 && len >= 0);
9612 // Reordered to avoid integer overflow
9613 g_assert (!(index > arr->max_length - len));
9615 esize = mono_array_element_size (arr->obj.vtable->klass);
9616 for (i = index; i < index + len; ++i) {
9617 elem = (gpointer*)((char*)arr->vector + (i * esize));
9618 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
9621 case CMD_ARRAY_REF_SET_VALUES:
9622 index = decode_int (p, &p, end);
9623 len = decode_int (p, &p, end);
9625 g_assert (index >= 0 && len >= 0);
9626 // Reordered to avoid integer overflow
9627 g_assert (!(index > arr->max_length - len));
9629 esize = mono_array_element_size (arr->obj.vtable->klass);
9630 for (i = index; i < index + len; ++i) {
9631 elem = (gpointer*)((char*)arr->vector + (i * esize));
9633 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, (guint8 *)elem, p, &p, end);
9637 return ERR_NOT_IMPLEMENTED;
9644 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9650 int i, index, length;
9652 gboolean use_utf16 = FALSE;
9654 objid = decode_objid (p, &p, end);
9655 err = get_object (objid, (MonoObject**)&str);
9656 if (err != ERR_NONE)
9660 case CMD_STRING_REF_GET_VALUE:
9661 if (CHECK_PROTOCOL_VERSION (2, 41)) {
9662 for (i = 0; i < mono_string_length (str); ++i)
9663 if (mono_string_chars (str)[i] == 0)
9665 buffer_add_byte (buf, use_utf16 ? 1 : 0);
9668 buffer_add_int (buf, mono_string_length (str) * 2);
9669 buffer_add_data (buf, (guint8*)mono_string_chars (str), mono_string_length (str) * 2);
9672 s = mono_string_to_utf8_checked (str, &error);
9673 mono_error_assert_ok (&error);
9674 buffer_add_string (buf, s);
9678 case CMD_STRING_REF_GET_LENGTH:
9679 buffer_add_long (buf, mono_string_length (str));
9681 case CMD_STRING_REF_GET_CHARS:
9682 index = decode_long (p, &p, end);
9683 length = decode_long (p, &p, end);
9684 if (index > mono_string_length (str) - length)
9685 return ERR_INVALID_ARGUMENT;
9686 c = mono_string_chars (str) + index;
9687 for (i = 0; i < length; ++i)
9688 buffer_add_short (buf, c [i]);
9691 return ERR_NOT_IMPLEMENTED;
9698 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9709 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9710 objid = decode_objid (p, &p, end);
9711 err = get_object (objid, &obj);
9712 if (err != ERR_NONE)
9713 buffer_add_int (buf, 1);
9715 buffer_add_int (buf, 0);
9719 objid = decode_objid (p, &p, end);
9720 err = get_object (objid, &obj);
9721 if (err != ERR_NONE)
9724 MonoClass *obj_type;
9725 gboolean remote_obj = FALSE;
9727 obj_type = obj->vtable->klass;
9728 if (mono_class_is_transparent_proxy (obj_type)) {
9729 obj_type = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
9733 g_assert (obj_type);
9736 case CMD_OBJECT_REF_GET_TYPE:
9737 /* This handles transparent proxies too */
9738 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9740 case CMD_OBJECT_REF_GET_VALUES:
9741 len = decode_int (p, &p, end);
9743 for (i = 0; i < len; ++i) {
9744 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9745 if (err != ERR_NONE)
9748 /* Check that the field belongs to the object */
9750 for (k = obj_type; k; k = k->parent) {
9751 if (k == f->parent) {
9757 return ERR_INVALID_FIELDID;
9759 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9763 if (mono_class_field_is_special_static (f))
9764 return ERR_INVALID_FIELDID;
9766 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9767 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9768 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9769 mono_field_static_get_value_checked (vtable, f, val, &error);
9770 if (!is_ok (&error)) {
9771 mono_error_cleanup (&error); /* FIXME report the error */
9772 return ERR_INVALID_OBJECT;
9774 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9777 guint8 *field_value = NULL;
9780 #ifndef DISABLE_REMOTING
9781 void *field_storage = NULL;
9782 field_value = mono_load_remote_field_checked(obj, obj_type, f, &field_storage, &error);
9783 if (!is_ok (&error)) {
9784 mono_error_cleanup (&error); /* FIXME report the error */
9785 return ERR_INVALID_OBJECT;
9788 g_assert_not_reached ();
9791 field_value = (guint8*)obj + f->offset;
9793 buffer_add_value (buf, f->type, field_value, obj->vtable->domain);
9797 case CMD_OBJECT_REF_SET_VALUES:
9798 len = decode_int (p, &p, end);
9800 for (i = 0; i < len; ++i) {
9801 f = decode_fieldid (p, &p, end, NULL, &err);
9802 if (err != ERR_NONE)
9805 /* Check that the field belongs to the object */
9807 for (k = obj_type; k; k = k->parent) {
9808 if (k == f->parent) {
9814 return ERR_INVALID_FIELDID;
9816 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9820 if (mono_class_field_is_special_static (f))
9821 return ERR_INVALID_FIELDID;
9823 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9824 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9826 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9827 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
9828 if (err != ERR_NONE) {
9832 mono_field_static_set_value (vtable, f, val);
9835 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
9836 if (err != ERR_NONE)
9841 case CMD_OBJECT_REF_GET_ADDRESS:
9842 buffer_add_long (buf, (gssize)obj);
9844 case CMD_OBJECT_REF_GET_DOMAIN:
9845 buffer_add_domainid (buf, obj->vtable->domain);
9847 case CMD_OBJECT_REF_GET_INFO:
9848 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9849 buffer_add_domainid (buf, obj->vtable->domain);
9852 return ERR_NOT_IMPLEMENTED;
9859 command_set_to_string (CommandSet command_set)
9861 switch (command_set) {
9864 case CMD_SET_OBJECT_REF:
9865 return "OBJECT_REF";
9866 case CMD_SET_STRING_REF:
9867 return "STRING_REF";
9868 case CMD_SET_THREAD:
9870 case CMD_SET_ARRAY_REF:
9872 case CMD_SET_EVENT_REQUEST:
9873 return "EVENT_REQUEST";
9874 case CMD_SET_STACK_FRAME:
9875 return "STACK_FRAME";
9876 case CMD_SET_APPDOMAIN:
9878 case CMD_SET_ASSEMBLY:
9880 case CMD_SET_METHOD:
9884 case CMD_SET_MODULE:
9895 static const char* vm_cmds_str [] = {
9903 "SET_PROTOCOL_VERSION",
9906 "GET_TYPES_FOR_SOURCE_FILE",
9911 static const char* thread_cmds_str[] = {
9921 static const char* event_cmds_str[] = {
9924 "REQUEST_CLEAR_ALL_BREAKPOINTS"
9927 static const char* appdomain_cmds_str[] = {
9929 "GET_FRIENDLY_NAME",
9931 "GET_ENTRY_ASSEMBLY",
9934 "CREATE_BOXED_VALUE"
9937 static const char* assembly_cmds_str[] = {
9940 "GET_MANIFEST_MODULE",
9947 static const char* module_cmds_str[] = {
9951 static const char* field_cmds_str[] = {
9955 static const char* method_cmds_str[] = {
9957 "GET_DECLARING_TYPE",
9965 "MAKE_GENERIC_METHOD"
9968 static const char* type_cmds_str[] = {
9976 "IS_ASSIGNABLE_FROM",
9980 "GET_PROPERTY_CATTRS",
9981 "GET_SOURCE_FILES_2",
9983 "GET_METHODS_BY_NAME_FLAGS",
9985 "GET_INTERFACE_MAP",
9989 static const char* stack_frame_cmds_str[] = {
9997 static const char* array_cmds_str[] = {
10003 static const char* string_cmds_str[] = {
10009 static const char* object_cmds_str[] = {
10020 cmd_to_string (CommandSet set, int command)
10027 cmds = vm_cmds_str;
10028 cmds_len = G_N_ELEMENTS (vm_cmds_str);
10030 case CMD_SET_OBJECT_REF:
10031 cmds = object_cmds_str;
10032 cmds_len = G_N_ELEMENTS (object_cmds_str);
10034 case CMD_SET_STRING_REF:
10035 cmds = string_cmds_str;
10036 cmds_len = G_N_ELEMENTS (string_cmds_str);
10038 case CMD_SET_THREAD:
10039 cmds = thread_cmds_str;
10040 cmds_len = G_N_ELEMENTS (thread_cmds_str);
10042 case CMD_SET_ARRAY_REF:
10043 cmds = array_cmds_str;
10044 cmds_len = G_N_ELEMENTS (array_cmds_str);
10046 case CMD_SET_EVENT_REQUEST:
10047 cmds = event_cmds_str;
10048 cmds_len = G_N_ELEMENTS (event_cmds_str);
10050 case CMD_SET_STACK_FRAME:
10051 cmds = stack_frame_cmds_str;
10052 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
10054 case CMD_SET_APPDOMAIN:
10055 cmds = appdomain_cmds_str;
10056 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
10058 case CMD_SET_ASSEMBLY:
10059 cmds = assembly_cmds_str;
10060 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
10062 case CMD_SET_METHOD:
10063 cmds = method_cmds_str;
10064 cmds_len = G_N_ELEMENTS (method_cmds_str);
10067 cmds = type_cmds_str;
10068 cmds_len = G_N_ELEMENTS (type_cmds_str);
10070 case CMD_SET_MODULE:
10071 cmds = module_cmds_str;
10072 cmds_len = G_N_ELEMENTS (module_cmds_str);
10074 case CMD_SET_FIELD:
10075 cmds = field_cmds_str;
10076 cmds_len = G_N_ELEMENTS (field_cmds_str);
10078 case CMD_SET_EVENT:
10079 cmds = event_cmds_str;
10080 cmds_len = G_N_ELEMENTS (event_cmds_str);
10085 if (command > 0 && command <= cmds_len)
10086 return cmds [command - 1];
10092 wait_for_attach (void)
10094 #ifndef DISABLE_SOCKET_TRANSPORT
10095 if (listen_fd == -1) {
10096 DEBUG_PRINTF (1, "[dbg] Invalid listening socket\n");
10100 /* Block and wait for client connection */
10101 conn_fd = socket_transport_accept (listen_fd);
10103 DEBUG_PRINTF (1, "Accepted connection on %d\n", conn_fd);
10104 if (conn_fd == -1) {
10105 DEBUG_PRINTF (1, "[dbg] Bad client connection\n");
10109 g_assert_not_reached ();
10113 disconnected = !transport_handshake ();
10114 if (disconnected) {
10115 DEBUG_PRINTF (1, "Transport handshake failed!\n");
10125 * This thread handles communication with the debugger client using a JDWP
10128 static gsize WINAPI
10129 debugger_thread (void *arg)
10132 int res, len, id, flags, command = 0;
10133 CommandSet command_set = (CommandSet)0;
10134 guint8 header [HEADER_LENGTH];
10135 guint8 *data, *p, *end;
10139 gboolean attach_failed = FALSE;
10141 DEBUG_PRINTF (1, "[dbg] Agent thread started, pid=%p\n", (gpointer) (gsize) mono_native_thread_id_get ());
10143 debugger_thread_id = mono_native_thread_id_get ();
10145 MonoInternalThread *internal = mono_thread_internal_current ();
10146 mono_thread_set_name_internal (internal, mono_string_new (mono_domain_get (), "Debugger agent"), TRUE, FALSE, &error);
10147 mono_error_assert_ok (&error);
10149 internal->state |= ThreadState_Background;
10150 internal->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
10152 if (agent_config.defer) {
10153 if (!wait_for_attach ()) {
10154 DEBUG_PRINTF (1, "[dbg] Can't attach, aborting debugger thread.\n");
10155 attach_failed = TRUE; // Don't abort process when we can't listen
10157 mono_set_is_debugger_attached (TRUE);
10158 /* Send start event to client */
10159 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
10162 mono_set_is_debugger_attached (TRUE);
10165 while (!attach_failed) {
10166 res = transport_recv (header, HEADER_LENGTH);
10168 /* This will break if the socket is closed during shutdown too */
10169 if (res != HEADER_LENGTH) {
10170 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH);
10175 end = header + HEADER_LENGTH;
10177 len = decode_int (p, &p, end);
10178 id = decode_int (p, &p, end);
10179 flags = decode_byte (p, &p, end);
10180 command_set = (CommandSet)decode_byte (p, &p, end);
10181 command = decode_byte (p, &p, end);
10183 g_assert (flags == 0);
10186 const char *cmd_str;
10187 char cmd_num [256];
10189 cmd_str = cmd_to_string (command_set, command);
10191 sprintf (cmd_num, "%d", command);
10195 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);
10198 data = (guint8 *)g_malloc (len - HEADER_LENGTH);
10199 if (len - HEADER_LENGTH > 0)
10201 res = transport_recv (data, len - HEADER_LENGTH);
10202 if (res != len - HEADER_LENGTH) {
10203 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH);
10209 end = data + (len - HEADER_LENGTH);
10211 buffer_init (&buf, 128);
10216 /* Process the request */
10217 switch (command_set) {
10219 err = vm_commands (command, id, p, end, &buf);
10220 if (err == ERR_NONE && command == CMD_VM_INVOKE_METHOD)
10221 /* Sent after the invoke is complete */
10224 case CMD_SET_EVENT_REQUEST:
10225 err = event_commands (command, p, end, &buf);
10227 case CMD_SET_APPDOMAIN:
10228 err = domain_commands (command, p, end, &buf);
10230 case CMD_SET_ASSEMBLY:
10231 err = assembly_commands (command, p, end, &buf);
10233 case CMD_SET_MODULE:
10234 err = module_commands (command, p, end, &buf);
10236 case CMD_SET_FIELD:
10237 err = field_commands (command, p, end, &buf);
10240 err = type_commands (command, p, end, &buf);
10242 case CMD_SET_METHOD:
10243 err = method_commands (command, p, end, &buf);
10245 case CMD_SET_THREAD:
10246 err = thread_commands (command, p, end, &buf);
10248 case CMD_SET_STACK_FRAME:
10249 err = frame_commands (command, p, end, &buf);
10251 case CMD_SET_ARRAY_REF:
10252 err = array_commands (command, p, end, &buf);
10254 case CMD_SET_STRING_REF:
10255 err = string_commands (command, p, end, &buf);
10257 case CMD_SET_OBJECT_REF:
10258 err = object_commands (command, p, end, &buf);
10261 err = ERR_NOT_IMPLEMENTED;
10264 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
10265 buffer_replies = TRUE;
10269 if (buffer_replies) {
10270 buffer_reply_packet (id, err, &buf);
10272 send_reply_packet (id, err, &buf);
10273 //DEBUG_PRINTF (1, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000);
10277 if (err == ERR_NONE && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
10278 send_buffered_reply_packets ();
10279 buffer_replies = FALSE;
10283 buffer_free (&buf);
10285 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
10289 mono_set_is_debugger_attached (FALSE);
10291 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
10292 debugger_thread_exited = TRUE;
10293 mono_coop_cond_signal (&debugger_thread_exited_cond);
10294 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
10296 DEBUG_PRINTF (1, "[dbg] Debugger thread exited.\n");
10298 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
10299 DEBUG_PRINTF (2, "[dbg] Detached - restarting clean debugger thread.\n");
10300 start_debugger_thread ();
10306 #else /* DISABLE_DEBUGGER_AGENT */
10309 mono_debugger_agent_parse_options (char *options)
10311 g_error ("This runtime is configured with the debugger agent disabled.");
10315 mono_debugger_agent_init (void)
10320 mono_debugger_agent_breakpoint_hit (void *sigctx)
10325 mono_debugger_agent_single_step_event (void *sigctx)
10330 mono_debugger_agent_free_domain_info (MonoDomain *domain)
10335 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
10336 MonoContext *catch_ctx)
10341 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
10346 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
10351 mono_debugger_agent_user_break (void)
10357 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
10362 mono_debugger_agent_debug_log_is_enabled (void)
10368 mono_debugger_agent_unhandled_exception (MonoException *exc)
10370 g_assert_not_reached ();
10374 debugger_agent_single_step_from_context (MonoContext *ctx)
10376 g_assert_not_reached ();
10380 debugger_agent_breakpoint_from_context (MonoContext *ctx)
10382 g_assert_not_reached ();