3 * Soft Debugger back-end module
6 * Zoltan Varga (vargaz@gmail.com)
8 * Copyright 2009-2010 Novell, Inc.
9 * Copyright 2011 Xamarin Inc.
10 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
17 #ifdef HAVE_SYS_TYPES_H
18 #include <sys/types.h>
20 #ifdef HAVE_SYS_SELECT_H
21 #include <sys/select.h>
23 #ifdef HAVE_SYS_SOCKET_H
24 #include <sys/socket.h>
26 #ifdef HAVE_NETINET_TCP_H
27 #include <netinet/tcp.h>
29 #ifdef HAVE_NETINET_IN_H
30 #include <netinet/in.h>
50 #ifdef PLATFORM_ANDROID
52 #include <linux/tcp.h>
53 #include <sys/endian.h>
56 #include <mono/metadata/mono-debug.h>
57 #include <mono/metadata/debug-internals.h>
58 #include <mono/metadata/gc-internals.h>
59 #include <mono/metadata/environment.h>
60 #include <mono/metadata/threads-types.h>
61 #include <mono/metadata/threadpool.h>
62 #include <mono/metadata/assembly.h>
63 #include <mono/metadata/runtime.h>
64 #include <mono/metadata/verify-internals.h>
65 #include <mono/metadata/reflection-internals.h>
66 #include <mono/metadata/w32socket.h>
67 #include <mono/utils/mono-coop-mutex.h>
68 #include <mono/utils/mono-coop-semaphore.h>
69 #include <mono/utils/mono-error-internals.h>
70 #include <mono/utils/mono-stack-unwinding.h>
71 #include <mono/utils/mono-time.h>
72 #include <mono/utils/mono-threads.h>
73 #include <mono/utils/networking.h>
74 #include <mono/utils/mono-proclib.h>
75 #include <mono/utils/w32api.h>
76 #include "debugger-agent.h"
78 #include "seq-points.h"
79 #include "interp/interp.h"
82 * On iOS we can't use System.Environment.Exit () as it will do the wrong
85 #if !defined (TARGET_IOS)
86 #define TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
90 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
91 #define DISABLE_DEBUGGER_AGENT 1
94 #ifdef DISABLE_SOFT_DEBUG
95 #define DISABLE_DEBUGGER_AGENT 1
98 #ifndef DISABLE_DEBUGGER_AGENT
100 #include <mono/utils/mono-os-mutex.h>
102 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
125 guint32 il_offset, native_offset;
129 * If method is gshared, this is the actual instance, otherwise this is equal to
132 MonoMethod *actual_method;
134 * This is the method which is visible to debugger clients. Same as method,
135 * except for native-to-managed wrappers.
137 MonoMethod *api_method;
139 MonoDebugMethodJitInfo *jit;
141 MonoInterpFrameHandle interp_frame;
143 mgreg_t *reg_locations [MONO_MAX_IREGS];
145 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
146 * the frame can become invalid.
151 typedef struct _InvokeData InvokeData;
159 /* This is the context which needs to be restored after the invoke */
163 * If this is set, invoke this method with the arguments given by ARGS.
167 guint32 suspend_count;
170 InvokeData *last_invoke;
174 MonoThreadUnwindState context;
176 /* This is computed on demand when it is requested using the wire protocol */
177 /* It is freed up when the thread is resumed */
181 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
184 gboolean frames_up_to_date;
186 * Points to data about a pending invoke which needs to be executed after the thread
189 InvokeData *pending_invoke;
191 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
196 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
197 * within a finite amount of time.
201 * Set to TRUE if this thread is suspended in suspend_current ().
203 gboolean really_suspended;
204 /* Used to pass the context to the breakpoint/single step handler */
205 MonoContext handler_ctx;
206 /* Whenever thread_stop () was called for this thread */
209 /* Whenever to disable breakpoints (used during invokes) */
210 gboolean disable_breakpoints;
213 * Number of times this thread has been resumed using resume_thread ().
215 guint32 resume_count;
217 MonoInternalThread *thread;
220 * Information about the frame which transitioned to native code for running
223 StackFrameInfo async_last_frame;
226 * The context where the stack walk can be started for running threads.
228 MonoThreadUnwindState async_state;
231 * The context used for filter clauses
233 MonoThreadUnwindState filter_state;
235 gboolean abort_requested;
238 * The current mono_runtime_invoke_checked invocation.
243 * The context where single stepping should resume while the thread is suspended because
244 * of an EXCEPTION event.
246 MonoThreadUnwindState catch_state;
249 * The context which needs to be restored after handling a single step/breakpoint
250 * event. This is the same as the ctx at step/breakpoint site, but includes changes
251 * to caller saved registers done by set_var ().
253 MonoThreadUnwindState restore_state;
254 /* Frames computed from restore_state */
255 int restore_frame_count;
256 StackFrame **restore_frames;
258 /* The currently unloading appdomain */
259 MonoDomain *domain_unloading;
264 void (*connect) (const char *address);
265 void (*close1) (void);
266 void (*close2) (void);
267 gboolean (*send) (void *buf, int len);
268 int (*recv) (void *buf, int len);
272 * Wire Protocol definitions
275 #define HEADER_LENGTH 11
277 #define MAJOR_VERSION 2
278 #define MINOR_VERSION 45
282 CMD_SET_OBJECT_REF = 9,
283 CMD_SET_STRING_REF = 10,
285 CMD_SET_ARRAY_REF = 13,
286 CMD_SET_EVENT_REQUEST = 15,
287 CMD_SET_STACK_FRAME = 16,
288 CMD_SET_APPDOMAIN = 20,
289 CMD_SET_ASSEMBLY = 21,
298 EVENT_KIND_VM_START = 0,
299 EVENT_KIND_VM_DEATH = 1,
300 EVENT_KIND_THREAD_START = 2,
301 EVENT_KIND_THREAD_DEATH = 3,
302 EVENT_KIND_APPDOMAIN_CREATE = 4,
303 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
304 EVENT_KIND_METHOD_ENTRY = 6,
305 EVENT_KIND_METHOD_EXIT = 7,
306 EVENT_KIND_ASSEMBLY_LOAD = 8,
307 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
308 EVENT_KIND_BREAKPOINT = 10,
309 EVENT_KIND_STEP = 11,
310 EVENT_KIND_TYPE_LOAD = 12,
311 EVENT_KIND_EXCEPTION = 13,
312 EVENT_KIND_KEEPALIVE = 14,
313 EVENT_KIND_USER_BREAK = 15,
314 EVENT_KIND_USER_LOG = 16
318 SUSPEND_POLICY_NONE = 0,
319 SUSPEND_POLICY_EVENT_THREAD = 1,
320 SUSPEND_POLICY_ALL = 2
325 ERR_INVALID_OBJECT = 20,
326 ERR_INVALID_FIELDID = 25,
327 ERR_INVALID_FRAMEID = 30,
328 ERR_NOT_IMPLEMENTED = 100,
329 ERR_NOT_SUSPENDED = 101,
330 ERR_INVALID_ARGUMENT = 102,
332 ERR_NO_INVOCATION = 104,
333 ERR_ABSENT_INFORMATION = 105,
334 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
335 ERR_INVOKE_ABORTED = 107,
336 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
341 MOD_KIND_THREAD_ONLY = 3,
342 MOD_KIND_LOCATION_ONLY = 7,
343 MOD_KIND_EXCEPTION_ONLY = 8,
345 MOD_KIND_ASSEMBLY_ONLY = 11,
346 MOD_KIND_SOURCE_FILE_ONLY = 12,
347 MOD_KIND_TYPE_NAME_ONLY = 13,
363 STEP_FILTER_NONE = 0,
364 STEP_FILTER_STATIC_CTOR = 1,
365 STEP_FILTER_DEBUGGER_HIDDEN = 2,
366 STEP_FILTER_DEBUGGER_STEP_THROUGH = 4,
367 STEP_FILTER_DEBUGGER_NON_USER_CODE = 8
371 TOKEN_TYPE_STRING = 0,
373 TOKEN_TYPE_FIELD = 2,
374 TOKEN_TYPE_METHOD = 3,
375 TOKEN_TYPE_UNKNOWN = 4
379 VALUE_TYPE_ID_NULL = 0xf0,
380 VALUE_TYPE_ID_TYPE = 0xf1,
381 VALUE_TYPE_ID_PARENT_VTYPE = 0xf2
385 FRAME_FLAG_DEBUGGER_INVOKE = 1,
386 FRAME_FLAG_NATIVE_TRANSITION = 2
390 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
391 INVOKE_FLAG_SINGLE_THREADED = 2,
392 INVOKE_FLAG_RETURN_OUT_THIS = 4,
393 INVOKE_FLAG_RETURN_OUT_ARGS = 8,
394 INVOKE_FLAG_VIRTUAL = 16
398 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
399 } BindingFlagsExtensions;
403 CMD_VM_ALL_THREADS = 2,
408 CMD_VM_INVOKE_METHOD = 7,
409 CMD_VM_SET_PROTOCOL_VERSION = 8,
410 CMD_VM_ABORT_INVOKE = 9,
411 CMD_VM_SET_KEEPALIVE = 10,
412 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
413 CMD_VM_GET_TYPES = 12,
414 CMD_VM_INVOKE_METHODS = 13,
415 CMD_VM_START_BUFFERING = 14,
416 CMD_VM_STOP_BUFFERING = 15
420 CMD_THREAD_GET_FRAME_INFO = 1,
421 CMD_THREAD_GET_NAME = 2,
422 CMD_THREAD_GET_STATE = 3,
423 CMD_THREAD_GET_INFO = 4,
424 CMD_THREAD_GET_ID = 5,
425 CMD_THREAD_GET_TID = 6,
426 CMD_THREAD_SET_IP = 7
430 CMD_EVENT_REQUEST_SET = 1,
431 CMD_EVENT_REQUEST_CLEAR = 2,
432 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
440 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
441 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
442 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
443 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
444 CMD_APPDOMAIN_CREATE_STRING = 5,
445 CMD_APPDOMAIN_GET_CORLIB = 6,
446 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
450 CMD_ASSEMBLY_GET_LOCATION = 1,
451 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
452 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
453 CMD_ASSEMBLY_GET_OBJECT = 4,
454 CMD_ASSEMBLY_GET_TYPE = 5,
455 CMD_ASSEMBLY_GET_NAME = 6,
456 CMD_ASSEMBLY_GET_DOMAIN = 7
460 CMD_MODULE_GET_INFO = 1,
464 CMD_FIELD_GET_INFO = 1,
468 CMD_METHOD_GET_NAME = 1,
469 CMD_METHOD_GET_DECLARING_TYPE = 2,
470 CMD_METHOD_GET_DEBUG_INFO = 3,
471 CMD_METHOD_GET_PARAM_INFO = 4,
472 CMD_METHOD_GET_LOCALS_INFO = 5,
473 CMD_METHOD_GET_INFO = 6,
474 CMD_METHOD_GET_BODY = 7,
475 CMD_METHOD_RESOLVE_TOKEN = 8,
476 CMD_METHOD_GET_CATTRS = 9,
477 CMD_METHOD_MAKE_GENERIC_METHOD = 10
481 CMD_TYPE_GET_INFO = 1,
482 CMD_TYPE_GET_METHODS = 2,
483 CMD_TYPE_GET_FIELDS = 3,
484 CMD_TYPE_GET_VALUES = 4,
485 CMD_TYPE_GET_OBJECT = 5,
486 CMD_TYPE_GET_SOURCE_FILES = 6,
487 CMD_TYPE_SET_VALUES = 7,
488 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
489 CMD_TYPE_GET_PROPERTIES = 9,
490 CMD_TYPE_GET_CATTRS = 10,
491 CMD_TYPE_GET_FIELD_CATTRS = 11,
492 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
493 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
494 CMD_TYPE_GET_VALUES_2 = 14,
495 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
496 CMD_TYPE_GET_INTERFACES = 16,
497 CMD_TYPE_GET_INTERFACE_MAP = 17,
498 CMD_TYPE_IS_INITIALIZED = 18,
499 CMD_TYPE_CREATE_INSTANCE = 19
503 CMD_STACK_FRAME_GET_VALUES = 1,
504 CMD_STACK_FRAME_GET_THIS = 2,
505 CMD_STACK_FRAME_SET_VALUES = 3,
506 CMD_STACK_FRAME_GET_DOMAIN = 4,
507 CMD_STACK_FRAME_SET_THIS = 5,
511 CMD_ARRAY_REF_GET_LENGTH = 1,
512 CMD_ARRAY_REF_GET_VALUES = 2,
513 CMD_ARRAY_REF_SET_VALUES = 3,
517 CMD_STRING_REF_GET_VALUE = 1,
518 CMD_STRING_REF_GET_LENGTH = 2,
519 CMD_STRING_REF_GET_CHARS = 3
523 CMD_OBJECT_REF_GET_TYPE = 1,
524 CMD_OBJECT_REF_GET_VALUES = 2,
525 CMD_OBJECT_REF_IS_COLLECTED = 3,
526 CMD_OBJECT_REF_GET_ADDRESS = 4,
527 CMD_OBJECT_REF_GET_DOMAIN = 5,
528 CMD_OBJECT_REF_SET_VALUES = 6,
529 CMD_OBJECT_REF_GET_INFO = 7,
535 int count; /* For kind == MOD_KIND_COUNT */
536 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
537 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
538 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
539 GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
540 GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
541 StepFilter filter; /* For kind == MOD_KIND_STEP */
543 gboolean caught, uncaught, subclasses; /* For kind == MOD_KIND_EXCEPTION_ONLY */
552 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
556 * Describes a single step request.
560 MonoInternalThread *thread;
566 MonoMethod *start_method;
567 MonoMethod *last_method;
569 /* Whenever single stepping is performed using start/stop_single_stepping () */
571 /* The list of breakpoints used to implement step-over */
573 /* The number of frames at the start of a step-over */
575 /* If set, don't stop in methods that are not part of user assemblies */
576 MonoAssembly** user_assemblies;
577 /* Used to distinguish stepping breakpoint hits in parallel tasks executions */
579 /* Used to know if we are in process of async step-out and distishing from exception breakpoints */
580 MonoMethod* async_stepout_method;
584 * Contains additional information for an event
587 /* For EVENT_KIND_EXCEPTION */
589 MonoContext catch_ctx;
591 /* For EVENT_KIND_USER_LOG */
593 char *category, *message;
594 /* For EVENT_KIND_TYPE_LOAD */
599 guint8 *buf, *p, *end;
602 typedef struct ReplyPacket {
608 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
610 #ifdef PLATFORM_ANDROID
611 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { g_print (__VA_ARGS__); } } while (0)
613 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { fprintf (log_file, __VA_ARGS__); fflush (log_file); } } while (0)
617 #define get_last_sock_error() WSAGetLastError()
618 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
619 #define MONO_EINTR WSAEINTR
621 #define get_last_sock_error() errno
622 #define MONO_EWOULDBLOCK EWOULDBLOCK
623 #define MONO_EINTR EINTR
626 #define CHECK_PROTOCOL_VERSION(major,minor) \
627 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
633 static AgentConfig agent_config;
636 * Whenever the agent is fully initialized.
637 * When using the onuncaught or onthrow options, only some parts of the agent are
638 * initialized on startup, and the full initialization which includes connection
639 * establishment and the startup of the agent thread is only done in response to
642 static gint32 inited;
644 #ifndef DISABLE_SOCKET_TRANSPORT
646 static int listen_fd;
649 static int packet_id = 0;
651 static int objref_id = 0;
653 static int event_request_id = 0;
655 static int frame_id = 0;
657 static GPtrArray *event_requests;
659 static MonoNativeTlsKey debugger_tls_id;
661 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
663 /* Maps MonoInternalThread -> DebuggerTlsData */
664 /* Protected by the loader lock */
665 static MonoGHashTable *thread_to_tls;
667 /* Maps tid -> MonoInternalThread */
668 /* Protected by the loader lock */
669 static MonoGHashTable *tid_to_thread;
671 /* Maps tid -> MonoThread (not MonoInternalThread) */
672 /* Protected by the loader lock */
673 static MonoGHashTable *tid_to_thread_obj;
675 static MonoNativeThreadId debugger_thread_id;
677 static MonoThreadHandle *debugger_thread_handle;
679 static int log_level;
681 static gboolean embedding;
683 static FILE *log_file;
685 /* Assemblies whose assembly load event has no been sent yet */
686 /* Protected by the dbg lock */
687 static GPtrArray *pending_assembly_loads;
689 /* Whenever the debugger thread has exited */
690 static gboolean debugger_thread_exited;
692 /* Cond variable used to wait for debugger_thread_exited becoming true */
693 static MonoCoopCond debugger_thread_exited_cond;
695 /* Mutex for the cond var above */
696 static MonoCoopMutex debugger_thread_exited_mutex;
698 /* The single step request instance */
699 static SingleStepReq *ss_req;
701 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
702 /* Number of single stepping operations in progress */
706 /* The protocol version of the client */
707 static int major_version, minor_version;
709 /* Whenever the variables above are set by the client */
710 static gboolean protocol_version_set;
712 /* A hash table containing all active domains */
713 /* Protected by the loader lock */
714 static GHashTable *domains;
716 /* The number of times the runtime is suspended */
717 static gint32 suspend_count;
719 /* Whenever to buffer reply messages and send them together */
720 static gboolean buffer_replies;
722 /* Buffered reply packets */
723 static ReplyPacket reply_packets [128];
726 #define dbg_lock() mono_coop_mutex_lock (&debug_mutex)
727 #define dbg_unlock() mono_coop_mutex_unlock (&debug_mutex)
728 static MonoCoopMutex debug_mutex;
730 static void transport_init (void);
731 static void transport_connect (const char *address);
732 static gboolean transport_handshake (void);
733 static void register_transport (DebuggerTransport *trans);
735 static gsize WINAPI debugger_thread (void *arg);
737 static void runtime_initialized (MonoProfiler *prof);
739 static void runtime_shutdown (MonoProfiler *prof);
741 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
743 static void thread_end (MonoProfiler *prof, uintptr_t tid);
745 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain);
747 static void appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain);
749 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
751 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
753 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
755 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
757 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly);
759 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
761 static void emit_assembly_load (gpointer assembly, gpointer user_data);
763 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
765 static void jit_done (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo);
767 static void jit_failed (MonoProfiler *prof, MonoMethod *method);
769 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo);
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);
898 agent_config.enabled = TRUE;
899 agent_config.suspend = TRUE;
900 agent_config.server = FALSE;
901 agent_config.defer = FALSE;
902 agent_config.address = NULL;
904 //agent_config.log_level = 10;
906 args = g_strsplit (options, ",", -1);
907 for (ptr = args; ptr && *ptr; ptr ++) {
910 if (strncmp (arg, "transport=", 10) == 0) {
911 agent_config.transport = g_strdup (arg + 10);
912 } else if (strncmp (arg, "address=", 8) == 0) {
913 agent_config.address = g_strdup (arg + 8);
914 } else if (strncmp (arg, "loglevel=", 9) == 0) {
915 agent_config.log_level = atoi (arg + 9);
916 } else if (strncmp (arg, "logfile=", 8) == 0) {
917 agent_config.log_file = g_strdup (arg + 8);
918 } else if (strncmp (arg, "suspend=", 8) == 0) {
919 agent_config.suspend = parse_flag ("suspend", arg + 8);
920 } else if (strncmp (arg, "server=", 7) == 0) {
921 agent_config.server = parse_flag ("server", arg + 7);
922 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
923 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
924 } else if (strncmp (arg, "onthrow=", 8) == 0) {
925 /* We support multiple onthrow= options */
926 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
927 } else if (strncmp (arg, "onthrow", 7) == 0) {
928 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
929 } else if (strncmp (arg, "help", 4) == 0) {
932 } else if (strncmp (arg, "timeout=", 8) == 0) {
933 agent_config.timeout = atoi (arg + 8);
934 } else if (strncmp (arg, "launch=", 7) == 0) {
935 agent_config.launch = g_strdup (arg + 7);
936 } else if (strncmp (arg, "embedding=", 10) == 0) {
937 agent_config.embedding = atoi (arg + 10) == 1;
938 } else if (strncmp (arg, "keepalive=", 10) == 0) {
939 agent_config.keepalive = atoi (arg + 10);
940 } else if (strncmp (arg, "setpgid=", 8) == 0) {
941 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
948 if (agent_config.server && !agent_config.suspend) {
949 /* Waiting for deferred attachment */
950 agent_config.defer = TRUE;
951 if (agent_config.address == NULL) {
952 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (mono_process_current_pid () % 1000));
956 //agent_config.log_level = 0;
958 if (agent_config.transport == NULL) {
959 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
963 if (agent_config.address == NULL && !agent_config.server) {
964 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
969 if (!strcmp (agent_config.transport, "dt_socket")) {
970 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
971 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
978 mono_debugger_agent_init (void)
980 mono_coop_mutex_init_recursive (&debug_mutex);
982 if (!agent_config.enabled)
987 /* Need to know whenever a thread has acquired the loader mutex */
988 mono_loader_lock_track_ownership (TRUE);
990 event_requests = g_ptr_array_new ();
992 mono_coop_mutex_init (&debugger_thread_exited_mutex);
993 mono_coop_cond_init (&debugger_thread_exited_cond);
995 MonoProfilerHandle prof = mono_profiler_create (NULL);
996 mono_profiler_set_runtime_shutdown_end_callback (prof, runtime_shutdown);
997 mono_profiler_set_runtime_initialized_callback (prof, runtime_initialized);
998 mono_profiler_set_domain_loaded_callback (prof, appdomain_load);
999 mono_profiler_set_domain_unloading_callback (prof, appdomain_start_unload);
1000 mono_profiler_set_domain_unloaded_callback (prof, appdomain_unload);
1001 mono_profiler_set_thread_started_callback (prof, thread_startup);
1002 mono_profiler_set_thread_stopped_callback (prof, thread_end);
1003 mono_profiler_set_assembly_loaded_callback (prof, assembly_load);
1004 mono_profiler_set_assembly_unloading_callback (prof, assembly_unload);
1005 mono_profiler_set_jit_done_callback (prof, jit_done);
1006 mono_profiler_set_jit_failed_callback (prof, jit_failed);
1008 mono_native_tls_alloc (&debugger_tls_id, NULL);
1010 /* Needed by the hash_table_new_type () call below */
1011 mono_gc_base_init ();
1013 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");
1015 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread table");
1017 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");
1019 pending_assembly_loads = g_ptr_array_new ();
1020 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
1022 log_level = agent_config.log_level;
1024 embedding = agent_config.embedding;
1025 disconnected = TRUE;
1027 if (agent_config.log_file) {
1028 log_file = fopen (agent_config.log_file, "w+");
1030 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
1039 breakpoints_init ();
1042 mini_get_debug_options ()->gen_sdb_seq_points = TRUE;
1044 * This is needed because currently we don't handle liveness info.
1046 mini_get_debug_options ()->mdb_optimizations = TRUE;
1048 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
1049 /* This is needed because we can't set local variables in registers yet */
1050 mono_disable_optimizations (MONO_OPT_LINEARS);
1054 * The stack walk done from thread_interrupt () needs to be signal safe, but it
1055 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
1056 * safe (#3411). So load AOT info eagerly when the debugger is running as a
1059 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
1062 if (agent_config.setpgid)
1066 if (!agent_config.onuncaught && !agent_config.onthrow)
1067 finish_agent_init (TRUE);
1071 * finish_agent_init:
1073 * Finish the initialization of the agent. This involves connecting the transport
1074 * and starting the agent thread. This is either done at startup, or
1075 * in response to some event like an unhandled exception.
1078 finish_agent_init (gboolean on_startup)
1082 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
1085 if (agent_config.launch) {
1088 // FIXME: Generated address
1089 // FIXME: Races with transport_connect ()
1091 argv [0] = agent_config.launch;
1092 argv [1] = agent_config.transport;
1093 argv [2] = agent_config.address;
1096 res = g_spawn_async_with_pipes (NULL, argv, NULL, (GSpawnFlags)0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1098 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1103 transport_connect (agent_config.address);
1106 /* Do some which is usually done after sending the VMStart () event */
1107 vm_start_event_sent = TRUE;
1108 start_debugger_thread ();
1113 mono_debugger_agent_cleanup (void)
1118 stop_debugger_thread ();
1120 breakpoints_cleanup ();
1129 #ifndef DISABLE_SOCKET_TRANSPORT
1134 * recv() + handle incomplete reads and EINTR
1137 socket_transport_recv (void *buf, int len)
1143 static gint64 last_keepalive;
1150 res = recv (fd, (char *) buf + total, len - total, flags);
1153 if (agent_config.keepalive) {
1154 gboolean need_keepalive = FALSE;
1155 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1156 need_keepalive = TRUE;
1157 } else if (res == -1) {
1158 /* This could happen if recv () is interrupted repeatedly */
1159 msecs = mono_msec_ticks ();
1160 if (msecs - last_keepalive >= agent_config.keepalive) {
1161 need_keepalive = TRUE;
1162 last_keepalive = msecs;
1165 if (need_keepalive) {
1166 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1170 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1178 set_keepalive (void)
1183 if (!agent_config.keepalive || !conn_fd)
1186 tv.tv_sec = agent_config.keepalive / 1000;
1187 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1189 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1190 g_assert (result >= 0);
1194 socket_transport_accept (int socket_fd)
1197 conn_fd = accept (socket_fd, NULL, NULL);
1200 if (conn_fd == -1) {
1201 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1203 DEBUG_PRINTF (1, "Accepted connection from client, connection fd=%d.\n", conn_fd);
1210 socket_transport_send (void *data, int len)
1217 res = send (conn_fd, data, len, 0);
1218 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1229 * socket_transport_connect:
1231 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1234 socket_transport_connect (const char *address)
1236 MonoAddressInfo *result;
1237 MonoAddressEntry *rp;
1238 int sfd = -1, s, res;
1242 if (agent_config.address) {
1243 res = parse_address (agent_config.address, &host, &port);
1244 g_assert (res == 0);
1255 mono_network_init ();
1257 /* Obtain address(es) matching host/port */
1258 s = mono_get_address_info (host, port, MONO_HINT_UNSPECIFIED, &result);
1260 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, s); // FIXME add portable error conversion functions
1265 if (agent_config.server) {
1266 /* Wait for a connection */
1268 struct sockaddr_in addr;
1271 /* No address, generate one */
1272 sfd = socket (AF_INET, SOCK_STREAM, 0);
1275 /* This will bind the socket to a random port */
1276 res = listen (sfd, 16);
1278 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1283 addrlen = sizeof (addr);
1284 memset (&addr, 0, sizeof (addr));
1285 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1286 g_assert (res == 0);
1288 host = (char*)"127.0.0.1";
1289 port = ntohs (addr.sin_port);
1291 /* Emit the address to stdout */
1292 /* FIXME: Should print another interface, not localhost */
1293 printf ("%s:%d\n", host, port);
1295 /* Listen on the provided address */
1296 for (rp = result->entries; rp != NULL; rp = rp->next) {
1297 MonoSocketAddress sockaddr;
1301 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1303 sfd = socket (rp->family, rp->socktype,
1308 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1311 res = bind (sfd, &sockaddr.addr, sock_len);
1315 res = listen (sfd, 16);
1322 mono_free_address_info (result);
1325 if (agent_config.defer)
1328 DEBUG_PRINTF (1, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout);
1330 if (agent_config.timeout) {
1335 tv.tv_usec = agent_config.timeout * 1000;
1337 FD_SET (sfd, &readfds);
1340 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1344 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1349 conn_fd = socket_transport_accept (sfd);
1353 DEBUG_PRINTF (1, "Accepted connection from client, socket fd=%d.\n", conn_fd);
1355 /* Connect to the specified address */
1356 /* FIXME: Respect the timeout */
1357 for (rp = result->entries; rp != NULL; rp = rp->next) {
1358 MonoSocketAddress sockaddr;
1361 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1363 sfd = socket (rp->family, rp->socktype,
1369 res = connect (sfd, &sockaddr.addr, sock_len);
1373 break; /* Success */
1381 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1387 mono_free_address_info (result);
1390 if (!transport_handshake ())
1395 socket_transport_close1 (void)
1397 /* This will interrupt the agent thread */
1398 /* Close the read part only so it can still send back replies */
1399 /* Also shut down the connection listener so that we can exit normally */
1401 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1402 shutdown (conn_fd, SD_BOTH);
1403 shutdown (listen_fd, SD_BOTH);
1404 closesocket (listen_fd);
1406 shutdown (conn_fd, SHUT_RD);
1407 shutdown (listen_fd, SHUT_RDWR);
1415 socket_transport_close2 (void)
1418 shutdown (conn_fd, SD_BOTH);
1420 shutdown (conn_fd, SHUT_RDWR);
1425 register_socket_transport (void)
1427 DebuggerTransport trans;
1429 trans.name = "dt_socket";
1430 trans.connect = socket_transport_connect;
1431 trans.close1 = socket_transport_close1;
1432 trans.close2 = socket_transport_close2;
1433 trans.send = socket_transport_send;
1434 trans.recv = socket_transport_recv;
1436 register_transport (&trans);
1440 * socket_fd_transport_connect:
1444 socket_fd_transport_connect (const char *address)
1448 res = sscanf (address, "%d", &conn_fd);
1450 fprintf (stderr, "debugger-agent: socket-fd transport address is invalid: '%s'\n", address);
1454 if (!transport_handshake ())
1459 register_socket_fd_transport (void)
1461 DebuggerTransport trans;
1463 /* This is the same as the 'dt_socket' transport, but receives an already connected socket fd */
1464 trans.name = "socket-fd";
1465 trans.connect = socket_fd_transport_connect;
1466 trans.close1 = socket_transport_close1;
1467 trans.close2 = socket_transport_close2;
1468 trans.send = socket_transport_send;
1469 trans.recv = socket_transport_recv;
1471 register_transport (&trans);
1474 #endif /* DISABLE_SOCKET_TRANSPORT */
1480 #define MAX_TRANSPORTS 16
1482 static DebuggerTransport *transport;
1484 static DebuggerTransport transports [MAX_TRANSPORTS];
1485 static int ntransports;
1488 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1491 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1493 register_transport (trans);
1497 register_transport (DebuggerTransport *trans)
1499 g_assert (ntransports < MAX_TRANSPORTS);
1501 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1506 transport_init (void)
1510 #ifndef DISABLE_SOCKET_TRANSPORT
1511 register_socket_transport ();
1512 register_socket_fd_transport ();
1515 for (i = 0; i < ntransports; ++i) {
1516 if (!strcmp (agent_config.transport, transports [i].name))
1519 if (i == ntransports) {
1520 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1521 for (i = 0; i < ntransports; ++i)
1522 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1523 fprintf (stderr, "\n");
1526 transport = &transports [i];
1530 transport_connect (const char *address)
1532 transport->connect (address);
1536 transport_close1 (void)
1538 transport->close1 ();
1542 transport_close2 (void)
1544 transport->close2 ();
1548 transport_send (void *buf, int len)
1550 return transport->send (buf, len);
1554 transport_recv (void *buf, int len)
1556 return transport->recv (buf, len);
1560 mono_debugger_agent_transport_handshake (void)
1562 return transport_handshake ();
1566 transport_handshake (void)
1568 char handshake_msg [128];
1572 disconnected = TRUE;
1574 /* Write handshake message */
1575 sprintf (handshake_msg, "DWP-Handshake");
1578 res = transport_send (handshake_msg, strlen (handshake_msg));
1579 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1581 g_assert (res != -1);
1584 res = transport_recv (buf, strlen (handshake_msg));
1585 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg)) != 0)) {
1586 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1591 * To support older clients, the client sends its protocol version after connecting
1592 * using a command. Until that is received, default to our protocol version.
1594 major_version = MAJOR_VERSION;
1595 minor_version = MINOR_VERSION;
1596 protocol_version_set = FALSE;
1598 #ifndef DISABLE_SOCKET_TRANSPORT
1599 // FIXME: Move this somewhere else
1601 * Set TCP_NODELAY on the socket so the client receives events/command
1602 * results immediately.
1606 int result = setsockopt (conn_fd,
1611 g_assert (result >= 0);
1617 disconnected = FALSE;
1622 stop_debugger_thread (void)
1627 transport_close1 ();
1630 * Wait for the thread to exit.
1632 * If we continue with the shutdown without waiting for it, then the client might
1633 * not receive an answer to its last command like a resume.
1635 if (!is_debugger_thread ()) {
1637 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
1638 if (!debugger_thread_exited)
1639 mono_coop_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1640 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
1641 } while (!debugger_thread_exited);
1644 transport_close2 ();
1648 start_debugger_thread (void)
1651 MonoInternalThread *thread;
1653 thread = mono_thread_create_internal (mono_get_root_domain (), debugger_thread, NULL, MONO_THREAD_CREATE_FLAGS_DEBUGGER, &error);
1654 mono_error_assert_ok (&error);
1656 debugger_thread_handle = mono_threads_open_thread_handle (thread->handle);
1657 g_assert (debugger_thread_handle);
1661 * Functions to decode protocol data
1665 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1668 g_assert (*endbuf <= limit);
1673 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1676 g_assert (*endbuf <= limit);
1678 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1681 static inline gint64
1682 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1684 guint32 high = decode_int (buf, &buf, limit);
1685 guint32 low = decode_int (buf, &buf, limit);
1689 return ((((guint64)high) << 32) | ((guint64)low));
1693 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1695 return decode_int (buf, endbuf, limit);
1699 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1701 int len = decode_int (buf, &buf, limit);
1709 s = (char *)g_malloc (len + 1);
1712 memcpy (s, buf, len);
1721 * Functions to encode protocol data
1725 buffer_init (Buffer *buf, int size)
1727 buf->buf = (guint8 *)g_malloc (size);
1729 buf->end = buf->buf + size;
1733 buffer_len (Buffer *buf)
1735 return buf->p - buf->buf;
1739 buffer_make_room (Buffer *buf, int size)
1741 if (buf->end - buf->p < size) {
1742 int new_size = buf->end - buf->buf + size + 32;
1743 guint8 *p = (guint8 *)g_realloc (buf->buf, new_size);
1744 size = buf->p - buf->buf;
1747 buf->end = buf->buf + new_size;
1752 buffer_add_byte (Buffer *buf, guint8 val)
1754 buffer_make_room (buf, 1);
1760 buffer_add_short (Buffer *buf, guint32 val)
1762 buffer_make_room (buf, 2);
1763 buf->p [0] = (val >> 8) & 0xff;
1764 buf->p [1] = (val >> 0) & 0xff;
1769 buffer_add_int (Buffer *buf, guint32 val)
1771 buffer_make_room (buf, 4);
1772 buf->p [0] = (val >> 24) & 0xff;
1773 buf->p [1] = (val >> 16) & 0xff;
1774 buf->p [2] = (val >> 8) & 0xff;
1775 buf->p [3] = (val >> 0) & 0xff;
1780 buffer_add_long (Buffer *buf, guint64 l)
1782 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1783 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1787 buffer_add_id (Buffer *buf, int id)
1789 buffer_add_int (buf, (guint64)id);
1793 buffer_add_data (Buffer *buf, guint8 *data, int len)
1795 buffer_make_room (buf, len);
1796 memcpy (buf->p, data, len);
1801 buffer_add_string (Buffer *buf, const char *str)
1806 buffer_add_int (buf, 0);
1809 buffer_add_int (buf, len);
1810 buffer_add_data (buf, (guint8*)str, len);
1815 buffer_add_buffer (Buffer *buf, Buffer *data)
1817 buffer_add_data (buf, data->buf, buffer_len (data));
1821 buffer_free (Buffer *buf)
1827 send_packet (int command_set, int command, Buffer *data)
1833 id = InterlockedIncrement (&packet_id);
1835 len = data->p - data->buf + 11;
1836 buffer_init (&buf, len);
1837 buffer_add_int (&buf, len);
1838 buffer_add_int (&buf, id);
1839 buffer_add_byte (&buf, 0); /* flags */
1840 buffer_add_byte (&buf, command_set);
1841 buffer_add_byte (&buf, command);
1842 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1844 res = transport_send (buf.buf, len);
1852 send_reply_packets (int npackets, ReplyPacket *packets)
1859 for (i = 0; i < npackets; ++i)
1860 len += buffer_len (packets [i].data) + 11;
1861 buffer_init (&buf, len);
1862 for (i = 0; i < npackets; ++i) {
1863 buffer_add_int (&buf, buffer_len (packets [i].data) + 11);
1864 buffer_add_int (&buf, packets [i].id);
1865 buffer_add_byte (&buf, 0x80); /* flags */
1866 buffer_add_byte (&buf, (packets [i].error >> 8) & 0xff);
1867 buffer_add_byte (&buf, packets [i].error);
1868 buffer_add_buffer (&buf, packets [i].data);
1871 res = transport_send (buf.buf, len);
1879 send_reply_packet (int id, int error, Buffer *data)
1883 memset (&packet, 0, sizeof (ReplyPacket));
1885 packet.error = error;
1888 return send_reply_packets (1, &packet);
1892 send_buffered_reply_packets (void)
1896 send_reply_packets (nreply_packets, reply_packets);
1897 for (i = 0; i < nreply_packets; ++i)
1898 buffer_free (reply_packets [i].data);
1899 DEBUG_PRINTF (1, "[dbg] Sent %d buffered reply packets [at=%lx].\n", nreply_packets, (long)mono_100ns_ticks () / 10000);
1904 buffer_reply_packet (int id, int error, Buffer *data)
1908 if (nreply_packets == 128)
1909 send_buffered_reply_packets ();
1911 p = &reply_packets [nreply_packets];
1914 p->data = g_new0 (Buffer, 1);
1915 buffer_init (p->data, buffer_len (data));
1916 buffer_add_buffer (p->data, data);
1925 * Represents an object accessible by the debugger client.
1928 /* Unique id used in the wire protocol to refer to objects */
1931 * A weakref gc handle pointing to the object. The gc handle is used to
1932 * detect if the object was garbage collected.
1937 /* Maps objid -> ObjRef */
1938 /* Protected by the loader lock */
1939 static GHashTable *objrefs;
1940 /* Protected by the loader lock */
1941 static GHashTable *obj_to_objref;
1942 /* Protected by the dbg lock */
1943 static MonoGHashTable *suspended_objs;
1946 free_objref (gpointer value)
1948 ObjRef *o = (ObjRef *)value;
1950 mono_gchandle_free (o->handle);
1958 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1959 obj_to_objref = g_hash_table_new (NULL, NULL);
1960 suspended_objs = mono_g_hash_table_new_type ((GHashFunc)mono_object_hash, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_DEBUGGER, "suspended objects table");
1964 objrefs_cleanup (void)
1966 g_hash_table_destroy (objrefs);
1971 * Return an ObjRef for OBJ.
1974 get_objref (MonoObject *obj)
1977 GSList *reflist = NULL, *l;
1983 if (suspend_count) {
1985 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1988 mono_g_hash_table_insert (suspended_objs, obj, NULL);
1992 mono_loader_lock ();
1994 /* FIXME: The tables can grow indefinitely */
1996 if (mono_gc_is_moving ()) {
1998 * Objects can move, so use a hash table mapping hash codes to lists of
1999 * ObjRef structures.
2001 hash = mono_object_hash (obj);
2003 reflist = (GSList *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
2004 for (l = reflist; l; l = l->next) {
2005 ref = (ObjRef *)l->data;
2006 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
2007 mono_loader_unlock ();
2012 /* Use a hash table with masked pointers to internalize object references */
2013 ref = (ObjRef *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
2014 /* ref might refer to a different object with the same addr which was GCd */
2015 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
2016 mono_loader_unlock ();
2021 ref = g_new0 (ObjRef, 1);
2022 ref->id = InterlockedIncrement (&objref_id);
2023 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
2025 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
2027 if (mono_gc_is_moving ()) {
2028 reflist = g_slist_append (reflist, ref);
2029 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
2031 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
2034 mono_loader_unlock ();
2040 true_pred (gpointer key, gpointer value, gpointer user_data)
2046 clear_suspended_objs (void)
2049 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
2054 get_objid (MonoObject *obj)
2059 return get_objref (obj)->id;
2063 * Set OBJ to the object identified by OBJID.
2064 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
2068 get_object_allow_null (int objid, MonoObject **obj)
2078 return ERR_INVALID_OBJECT;
2080 mono_loader_lock ();
2082 ref = (ObjRef *)g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
2085 *obj = mono_gchandle_get_target (ref->handle);
2086 mono_loader_unlock ();
2088 return ERR_INVALID_OBJECT;
2091 mono_loader_unlock ();
2092 return ERR_INVALID_OBJECT;
2097 get_object (int objid, MonoObject **obj)
2099 ErrorCode err = get_object_allow_null (objid, obj);
2101 if (err != ERR_NONE)
2104 return ERR_INVALID_OBJECT;
2109 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
2111 return decode_id (buf, endbuf, limit);
2115 buffer_add_objid (Buffer *buf, MonoObject *o)
2117 buffer_add_id (buf, get_objid (o));
2136 * Represents a runtime structure accessible to the debugger client
2139 /* Unique id used in the wire protocol */
2141 /* Domain of the runtime structure, NULL if the domain was unloaded */
2148 MonoAssembly *assembly;
2149 MonoClassField *field;
2151 MonoProperty *property;
2156 /* Maps runtime structure -> Id */
2157 /* Protected by the dbg lock */
2158 GHashTable *val_to_id [ID_NUM];
2159 /* Classes whose class load event has been sent */
2160 /* Protected by the loader lock */
2161 GHashTable *loaded_classes;
2162 /* Maps MonoClass->GPtrArray of file names */
2163 GHashTable *source_files;
2164 /* Maps source file basename -> GSList of classes */
2165 GHashTable *source_file_to_class;
2166 /* Same with ignore-case */
2167 GHashTable *source_file_to_class_ignorecase;
2171 /* Protected by the dbg lock */
2172 static GPtrArray *ids [ID_NUM];
2179 for (i = 0; i < ID_NUM; ++i)
2180 ids [i] = g_ptr_array_new ();
2188 for (i = 0; i < ID_NUM; ++i) {
2190 for (j = 0; j < ids [i]->len; ++j)
2191 g_free (g_ptr_array_index (ids [i], j));
2192 g_ptr_array_free (ids [i], TRUE);
2199 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2201 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2203 GHashTableIter iter;
2204 GPtrArray *file_names;
2209 for (i = 0; i < ID_NUM; ++i)
2210 if (info->val_to_id [i])
2211 g_hash_table_destroy (info->val_to_id [i]);
2212 g_hash_table_destroy (info->loaded_classes);
2214 g_hash_table_iter_init (&iter, info->source_files);
2215 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2216 for (i = 0; i < file_names->len; ++i)
2217 g_free (g_ptr_array_index (file_names, i));
2218 g_ptr_array_free (file_names, TRUE);
2221 g_hash_table_iter_init (&iter, info->source_file_to_class);
2222 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2227 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2228 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2236 domain_jit_info (domain)->agent_info = NULL;
2238 /* Clear ids referencing structures in the domain */
2240 for (i = 0; i < ID_NUM; ++i) {
2242 for (j = 0; j < ids [i]->len; ++j) {
2243 Id *id = (Id *)g_ptr_array_index (ids [i], j);
2244 if (id->domain == domain)
2251 mono_loader_lock ();
2252 g_hash_table_remove (domains, domain);
2253 mono_loader_unlock ();
2256 static AgentDomainInfo*
2257 get_agent_domain_info (MonoDomain *domain)
2259 AgentDomainInfo *info = NULL;
2261 mono_domain_lock (domain);
2263 info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2265 info = g_new0 (AgentDomainInfo, 1);
2266 domain_jit_info (domain)->agent_info = info;
2267 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2268 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2269 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2270 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2273 mono_domain_unlock (domain);
2279 get_id (MonoDomain *domain, IdType type, gpointer val)
2282 AgentDomainInfo *info;
2287 info = get_agent_domain_info (domain);
2291 if (info->val_to_id [type] == NULL)
2292 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2294 id = (Id *)g_hash_table_lookup (info->val_to_id [type], val);
2300 id = g_new0 (Id, 1);
2302 id->id = ids [type]->len + 1;
2303 id->domain = domain;
2306 g_hash_table_insert (info->val_to_id [type], val, id);
2307 g_ptr_array_add (ids [type], id);
2314 static inline gpointer
2315 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, ErrorCode *err)
2319 int id = decode_id (buf, endbuf, limit);
2328 // FIXME: error handling
2330 g_assert (id > 0 && id <= ids [type]->len);
2332 res = (Id *)g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2335 if (res->domain == NULL || res->domain->state == MONO_APPDOMAIN_UNLOADED) {
2336 DEBUG_PRINTF (1, "ERR_UNLOADED, id=%d, type=%d.\n", id, type);
2337 *err = ERR_UNLOADED;
2342 *domain = res->domain;
2344 return res->data.val;
2348 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2350 int id = get_id (domain, type, val);
2352 buffer_add_id (buf, id);
2356 static inline MonoClass*
2357 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2361 klass = (MonoClass *)decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2362 if (G_UNLIKELY (log_level >= 2) && klass) {
2365 s = mono_type_full_name (&klass->byval_arg);
2366 DEBUG_PRINTF (2, "[dbg] recv class [%s]\n", s);
2372 static inline MonoAssembly*
2373 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2375 return (MonoAssembly *)decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2378 static inline MonoImage*
2379 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2381 return (MonoImage *)decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2384 static inline MonoMethod*
2385 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2389 m = (MonoMethod *)decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2390 if (G_UNLIKELY (log_level >= 2) && m) {
2393 s = mono_method_full_name (m, TRUE);
2394 DEBUG_PRINTF (2, "[dbg] recv method [%s]\n", s);
2400 static inline MonoClassField*
2401 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2403 return (MonoClassField *)decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2406 static inline MonoDomain*
2407 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2409 return (MonoDomain *)decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2412 static inline MonoProperty*
2413 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2415 return (MonoProperty *)decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2419 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2421 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2422 if (G_UNLIKELY (log_level >= 2) && klass) {
2425 s = mono_type_full_name (&klass->byval_arg);
2426 if (is_debugger_thread ())
2427 DEBUG_PRINTF (2, "[dbg] send class [%s]\n", s);
2429 DEBUG_PRINTF (2, "[%p] send class [%s]\n", (gpointer) (gsize) mono_native_thread_id_get (), s);
2435 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2437 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2438 if (G_UNLIKELY (log_level >= 2) && method) {
2441 s = mono_method_full_name (method, 1);
2442 DEBUG_PRINTF (2, "[dbg] send method [%s]\n", s);
2448 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2452 id = buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2453 if (G_UNLIKELY (log_level >= 2) && assembly)
2454 DEBUG_PRINTF (2, "[dbg] send assembly [%s][%s][%d]\n", assembly->aname.name, domain->friendly_name, id);
2458 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2460 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2464 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2466 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2470 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2472 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2476 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2478 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2481 static void invoke_method (void);
2488 get_top_method_ji (gpointer ip, MonoDomain **domain, gpointer *out_ip)
2495 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, domain);
2497 /* Could be an interpreter method */
2499 MonoLMF *lmf = mono_get_lmf ();
2500 MonoInterpFrameHandle *frame;
2502 g_assert (((guint64)lmf->previous_lmf) & 2);
2503 MonoLMFExt *ext = (MonoLMFExt*)lmf;
2505 g_assert (ext->interp_exit);
2506 frame = ext->interp_exit_data;
2507 ji = mono_interp_frame_get_jit_info (frame);
2509 *domain = mono_domain_get ();
2511 *out_ip = mono_interp_frame_get_ip (frame);
2517 * save_thread_context:
2519 * Set CTX as the current threads context which is used for computing stack traces.
2520 * This function is signal-safe.
2523 save_thread_context (MonoContext *ctx)
2525 DebuggerTlsData *tls;
2527 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2531 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2533 mono_thread_state_init_from_current (&tls->context);
2536 /* Number of threads suspended */
2538 * If this is equal to the size of thread_to_tls, the runtime is considered
2541 static gint32 threads_suspend_count;
2543 static MonoCoopMutex suspend_mutex;
2545 /* Cond variable used to wait for suspend_count becoming 0 */
2546 static MonoCoopCond suspend_cond;
2548 /* Semaphore used to wait for a thread becoming suspended */
2549 static MonoCoopSem suspend_sem;
2554 mono_coop_mutex_init (&suspend_mutex);
2555 mono_coop_cond_init (&suspend_cond);
2556 mono_coop_sem_init (&suspend_sem, 0);
2561 StackFrameInfo last_frame;
2562 gboolean last_frame_set;
2566 } GetLastFrameUserData;
2569 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2571 GetLastFrameUserData *data = (GetLastFrameUserData *)user_data;
2573 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE || info->type == FRAME_TYPE_TRAMPOLINE)
2576 if (!data->last_frame_set) {
2577 /* Store the last frame */
2578 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2579 data->last_frame_set = TRUE;
2582 /* Store the context/lmf for the frame above the last frame */
2583 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2584 data->lmf = info->lmf;
2585 data->domain = info->domain;
2591 copy_unwind_state_from_frame_data (MonoThreadUnwindState *to, GetLastFrameUserData *data, gpointer jit_tls)
2593 memcpy (&to->ctx, &data->ctx, sizeof (MonoContext));
2595 to->unwind_data [MONO_UNWIND_DATA_DOMAIN] = data->domain;
2596 to->unwind_data [MONO_UNWIND_DATA_LMF] = data->lmf;
2597 to->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = jit_tls;
2604 * Process interruption of a thread. This should be signal safe.
2606 * This always runs in the debugger thread.
2609 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, MonoJitInfo *ji)
2612 MonoNativeThreadId tid;
2616 ip = MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx);
2617 tid = mono_thread_info_get_tid (info);
2619 // FIXME: Races when the thread leaves managed code before hitting a single step
2622 if (ji && !ji->is_trampoline) {
2623 /* Running managed code, will be suspended by the single step code */
2624 DEBUG_PRINTF (1, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip);
2627 * Running native code, will be suspended when it returns to/enters
2628 * managed code. Treat it as already suspended.
2629 * This might interrupt the code in process_single_step_inner (), we use the
2630 * tls->suspending flag to avoid races when that happens.
2632 if (!tls->suspended && !tls->suspending) {
2633 GetLastFrameUserData data;
2635 // FIXME: printf is not signal safe, but this is only used during
2636 // debugger debugging
2638 DEBUG_PRINTF (1, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip);
2639 //save_thread_context (&ctx);
2642 /* Already terminated */
2646 * We are in a difficult position: we want to be able to provide stack
2647 * traces for this thread, but we can't use the current ctx+lmf, since
2648 * the thread is still running, so it might return to managed code,
2649 * making these invalid.
2650 * So we start a stack walk and save the first frame, along with the
2651 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2652 * suspended when it returns to managed code, so the parent's ctx should
2655 MonoThreadUnwindState *state = mono_thread_info_get_suspend_state (info);
2657 data.last_frame_set = FALSE;
2658 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, state, MONO_UNWIND_SIGNAL_SAFE, &data);
2659 if (data.last_frame_set) {
2660 gpointer jit_tls = ((MonoThreadInfo*)tls->thread->thread_info)->jit_data;
2662 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2664 if (data.last_frame.type == FRAME_TYPE_INTERP_TO_MANAGED) {
2666 * Store the current lmf instead of the parent one, since that
2667 * contains the interp exit data.
2669 data.lmf = state->unwind_data [MONO_UNWIND_DATA_LMF];
2672 copy_unwind_state_from_frame_data (&tls->async_state, &data, jit_tls);
2673 copy_unwind_state_from_frame_data (&tls->context, &data, jit_tls);
2675 tls->async_state.valid = FALSE;
2678 mono_memory_barrier ();
2680 tls->suspended = TRUE;
2681 mono_coop_sem_post (&suspend_sem);
2687 * reset_native_thread_suspend_state:
2689 * Reset the suspended flag and state on native threads
2692 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2694 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2696 if (!tls->really_suspended && tls->suspended) {
2697 tls->suspended = FALSE;
2699 * The thread might still be running if it was executing native code, so the state won't be invalided by
2700 * suspend_current ().
2702 tls->context.valid = FALSE;
2703 tls->async_state.valid = FALSE;
2704 invalidate_frames (tls);
2709 DebuggerTlsData *tls;
2710 gboolean valid_info;
2713 static SuspendThreadResult
2714 debugger_interrupt_critical (MonoThreadInfo *info, gpointer user_data)
2716 InterruptData *data = (InterruptData *)user_data;
2719 data->valid_info = TRUE;
2720 ji = mono_jit_info_table_find_internal (
2721 (MonoDomain *)mono_thread_info_get_suspend_state (info)->unwind_data [MONO_UNWIND_DATA_DOMAIN],
2722 (char *)MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx),
2726 /* This is signal safe */
2727 thread_interrupt (data->tls, info, ji);
2728 return MonoResumeThread;
2734 * Notify a thread that it needs to suspend.
2737 notify_thread (gpointer key, gpointer value, gpointer user_data)
2739 MonoInternalThread *thread = (MonoInternalThread *)key;
2740 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2741 MonoNativeThreadId tid = MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid);
2743 if (mono_thread_internal_is_current (thread) || tls->terminated)
2746 DEBUG_PRINTF (1, "[%p] Interrupting %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2748 /* This is _not_ equivalent to mono_thread_internal_abort () */
2749 InterruptData interrupt_data = { 0 };
2750 interrupt_data.tls = tls;
2752 mono_thread_info_safe_suspend_and_run ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE, debugger_interrupt_critical, &interrupt_data);
2753 if (!interrupt_data.valid_info) {
2754 DEBUG_PRINTF (1, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2756 * Attached thread which died without detaching.
2758 tls->terminated = TRUE;
2763 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2765 guint8 *ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
2769 if (mono_loader_lock_is_owned_by_self ()) {
2771 * Shortcut for the check in suspend_current (). This speeds up processing
2772 * when executing long running code inside the loader lock, i.e. assembly load
2778 if (is_debugger_thread ())
2781 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2782 if (suspend_count - tls->resume_count > 0)
2783 tls->suspending = TRUE;
2785 DEBUG_PRINTF (1, "[%p] Received single step event for suspending.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2787 if (suspend_count - tls->resume_count == 0) {
2789 * We are executing a single threaded invoke but the single step for
2790 * suspending is still active.
2791 * FIXME: This slows down single threaded invokes.
2793 DEBUG_PRINTF (1, "[%p] Ignored during single threaded invoke.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2797 ji = get_top_method_ji (ip, NULL, NULL);
2799 /* Can't suspend in these methods */
2800 method = jinfo_get_method (ji);
2801 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2804 save_thread_context (ctx);
2812 * Increase the suspend count of the VM. While the suspend count is greater
2813 * than 0, runtime threads are suspended at certain points during execution.
2818 mono_loader_lock ();
2820 mono_coop_mutex_lock (&suspend_mutex);
2824 DEBUG_PRINTF (1, "[%p] Suspending vm...\n", (gpointer) (gsize) mono_native_thread_id_get ());
2826 if (suspend_count == 1) {
2827 // FIXME: Is it safe to call this inside the lock ?
2828 start_single_stepping ();
2829 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2832 mono_coop_mutex_unlock (&suspend_mutex);
2834 if (suspend_count == 1)
2836 * Suspend creation of new threadpool threads, since they cannot run
2838 mono_threadpool_suspend ();
2840 mono_loader_unlock ();
2846 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2852 g_assert (is_debugger_thread ());
2854 mono_loader_lock ();
2856 mono_coop_mutex_lock (&suspend_mutex);
2858 g_assert (suspend_count > 0);
2861 DEBUG_PRINTF (1, "[%p] Resuming vm, suspend count=%d...\n", (gpointer) (gsize) mono_native_thread_id_get (), suspend_count);
2863 if (suspend_count == 0) {
2864 // FIXME: Is it safe to call this inside the lock ?
2865 stop_single_stepping ();
2866 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2869 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2870 mono_coop_cond_broadcast (&suspend_cond);
2872 mono_coop_mutex_unlock (&suspend_mutex);
2873 //g_assert (err == 0);
2875 if (suspend_count == 0)
2876 mono_threadpool_resume ();
2878 mono_loader_unlock ();
2884 * Resume just one thread.
2887 resume_thread (MonoInternalThread *thread)
2889 DebuggerTlsData *tls;
2891 g_assert (is_debugger_thread ());
2893 mono_loader_lock ();
2895 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
2898 mono_coop_mutex_lock (&suspend_mutex);
2900 g_assert (suspend_count > 0);
2902 DEBUG_PRINTF (1, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid);
2904 tls->resume_count += suspend_count;
2907 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2908 * but only the one whose resume_count field is > 0 will be resumed.
2910 mono_coop_cond_broadcast (&suspend_cond);
2912 mono_coop_mutex_unlock (&suspend_mutex);
2913 //g_assert (err == 0);
2915 mono_loader_unlock ();
2919 free_frames (StackFrame **frames, int nframes)
2923 for (i = 0; i < nframes; ++i) {
2924 if (frames [i]->jit)
2925 mono_debug_free_method_jit_info (frames [i]->jit);
2926 g_free (frames [i]);
2932 invalidate_frames (DebuggerTlsData *tls)
2935 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2938 free_frames (tls->frames, tls->frame_count);
2939 tls->frame_count = 0;
2942 free_frames (tls->restore_frames, tls->restore_frame_count);
2943 tls->restore_frame_count = 0;
2944 tls->restore_frames = NULL;
2950 * Suspend the current thread until the runtime is resumed. If the thread has a
2951 * pending invoke, then the invoke is executed before this function returns.
2954 suspend_current (void)
2956 DebuggerTlsData *tls;
2958 g_assert (!is_debugger_thread ());
2960 if (mono_loader_lock_is_owned_by_self ()) {
2962 * If we own the loader mutex, can't suspend until we release it, since the
2963 * whole runtime can deadlock otherwise.
2968 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2971 mono_coop_mutex_lock (&suspend_mutex);
2973 tls->suspending = FALSE;
2974 tls->really_suspended = TRUE;
2976 if (!tls->suspended) {
2977 tls->suspended = TRUE;
2978 mono_coop_sem_post (&suspend_sem);
2981 DEBUG_PRINTF (1, "[%p] Suspended.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2983 while (suspend_count - tls->resume_count > 0) {
2984 mono_coop_cond_wait (&suspend_cond, &suspend_mutex);
2987 tls->suspended = FALSE;
2988 tls->really_suspended = FALSE;
2990 threads_suspend_count --;
2992 mono_coop_mutex_unlock (&suspend_mutex);
2994 DEBUG_PRINTF (1, "[%p] Resumed.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2996 if (tls->pending_invoke) {
2997 /* Save the original context */
2998 tls->pending_invoke->has_ctx = TRUE;
2999 tls->pending_invoke->ctx = tls->context.ctx;
3004 /* The frame info becomes invalid after a resume */
3005 tls->context.valid = FALSE;
3006 tls->async_state.valid = FALSE;
3007 invalidate_frames (tls);
3011 count_thread (gpointer key, gpointer value, gpointer user_data)
3013 DebuggerTlsData *tls = (DebuggerTlsData *)value;
3015 if (!tls->suspended && !tls->terminated && !mono_thread_internal_is_current (tls->thread))
3016 *(int*)user_data = *(int*)user_data + 1;
3020 count_threads_to_wait_for (void)
3024 mono_loader_lock ();
3025 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
3026 mono_loader_unlock ();
3034 * Wait until the runtime is completely suspended.
3037 wait_for_suspend (void)
3039 int nthreads, nwait, err;
3040 gboolean waited = FALSE;
3042 // FIXME: Threads starting/stopping ?
3043 mono_loader_lock ();
3044 nthreads = mono_g_hash_table_size (thread_to_tls);
3045 mono_loader_unlock ();
3048 nwait = count_threads_to_wait_for ();
3050 DEBUG_PRINTF (1, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads);
3051 err = mono_coop_sem_wait (&suspend_sem, MONO_SEM_FLAGS_NONE);
3052 g_assert (err == 0);
3060 DEBUG_PRINTF (1, "%d threads suspended.\n", nthreads);
3066 * Return whenever the runtime is suspended.
3071 return count_threads_to_wait_for () == 0;
3075 no_seq_points_found (MonoMethod *method, int offset)
3078 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3080 printf ("Unable to find seq points for method '%s', offset 0x%x.\n", mono_method_full_name (method, TRUE), offset);
3084 DebuggerTlsData *tls;
3086 } ComputeFramesUserData;
3089 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3091 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3093 MonoMethod *method, *actual_method, *api_method;
3097 if (info->type != FRAME_TYPE_MANAGED && info->type != FRAME_TYPE_INTERP) {
3098 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3099 /* Mark the last frame as an invoke frame */
3101 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3107 method = jinfo_get_method (info->ji);
3109 method = info->method;
3110 actual_method = info->actual_method;
3111 api_method = method;
3116 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3119 if (info->il_offset == -1) {
3120 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3121 if (ud->frames == NULL) {
3122 if (mono_find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL, &sp))
3123 info->il_offset = sp.il_offset;
3125 if (info->il_offset == -1)
3126 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3129 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);
3131 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3132 if (!CHECK_PROTOCOL_VERSION (2, 17))
3133 /* Older clients can't handle this flag */
3135 api_method = mono_marshal_method_from_wrapper (method);
3138 actual_method = api_method;
3139 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3142 frame = g_new0 (StackFrame, 1);
3143 frame->method = method;
3144 frame->actual_method = actual_method;
3145 frame->api_method = api_method;
3146 frame->il_offset = info->il_offset;
3147 frame->native_offset = info->native_offset;
3148 frame->flags = flags;
3149 frame->ji = info->ji;
3150 frame->interp_frame = info->interp_frame;
3151 if (info->reg_locations)
3152 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3155 frame->has_ctx = TRUE;
3157 frame->domain = info->domain;
3159 ud->frames = g_slist_append (ud->frames, frame);
3165 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3167 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3170 * 'tls->filter_ctx' is the location of the throw site.
3172 * mono_walk_stack() will never actually hit the throw site, but unwind
3173 * directly from the filter to the call site; we abort stack unwinding here
3174 * once this happens and resume from the throw site.
3177 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3180 return process_frame (info, ctx, user_data);
3184 * Return a malloc-ed list of StackFrame structures.
3187 compute_frame_info_from (MonoInternalThread *thread, DebuggerTlsData *tls, MonoThreadUnwindState *state, int *out_nframes)
3189 ComputeFramesUserData user_data;
3190 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3195 user_data.tls = tls;
3196 user_data.frames = NULL;
3198 mono_walk_stack_with_state (process_frame, state, opts, &user_data);
3200 nframes = g_slist_length (user_data.frames);
3201 res = g_new0 (StackFrame*, nframes);
3202 l = user_data.frames;
3203 for (i = 0; i < nframes; ++i) {
3204 res [i] = (StackFrame *)l->data;
3207 *out_nframes = nframes;
3213 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3215 ComputeFramesUserData user_data;
3217 int i, findex, new_frame_count;
3218 StackFrame **new_frames, *f;
3219 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3221 // FIXME: Locking on tls
3222 if (tls->frames && tls->frames_up_to_date)
3225 DEBUG_PRINTF (1, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid);
3227 user_data.tls = tls;
3228 user_data.frames = NULL;
3229 if (tls->terminated) {
3230 tls->frame_count = 0;
3232 } if (!tls->really_suspended && tls->async_state.valid) {
3233 /* Have to use the state saved by the signal handler */
3234 process_frame (&tls->async_last_frame, NULL, &user_data);
3235 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3236 } else if (tls->filter_state.valid) {
3238 * We are inside an exception filter.
3240 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3242 if (tls->context.valid)
3243 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3245 * After that, we resume unwinding from the location where the exception has been thrown.
3247 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3248 } else if (tls->context.valid) {
3249 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3252 tls->frame_count = 0;
3256 new_frame_count = g_slist_length (user_data.frames);
3257 new_frames = g_new0 (StackFrame*, new_frame_count);
3259 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3260 f = (StackFrame *)tmp->data;
3263 * Reuse the id for already existing stack frames, so invokes don't invalidate
3264 * the still valid stack frames.
3266 for (i = 0; i < tls->frame_count; ++i) {
3267 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3268 f->id = tls->frames [i]->id;
3273 if (i >= tls->frame_count)
3274 f->id = InterlockedIncrement (&frame_id);
3276 new_frames [findex ++] = f;
3279 g_slist_free (user_data.frames);
3281 invalidate_frames (tls);
3283 tls->frames = new_frames;
3284 tls->frame_count = new_frame_count;
3285 tls->frames_up_to_date = TRUE;
3289 * GHFunc to emit an appdomain creation event
3290 * @param key Don't care
3291 * @param value A loaded appdomain
3292 * @param user_data Don't care
3295 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3297 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3298 g_hash_table_foreach (get_agent_domain_info ((MonoDomain *)value)->loaded_classes, emit_type_load, NULL);
3302 * GHFunc to emit a thread start event
3303 * @param key A thread id
3304 * @param value A thread object
3305 * @param user_data Don't care
3308 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3310 g_assert (!mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (GPOINTER_TO_UINT (key)), debugger_thread_id));
3311 process_profiler_event (EVENT_KIND_THREAD_START, value);
3315 * GFunc to emit an assembly load event
3316 * @param value A loaded assembly
3317 * @param user_data Don't care
3320 emit_assembly_load (gpointer value, gpointer user_data)
3322 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3326 * GFunc to emit a type load event
3327 * @param value A loaded type
3328 * @param user_data Don't care
3331 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3333 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3337 strdup_tolower (char *s)
3342 for (p = s2; *p; ++p)
3348 * Same as g_path_get_basename () but handles windows paths as well,
3349 * which can occur in .mdb files created by pdb2mdb.
3352 dbg_path_get_basename (const char *filename)
3356 if (!filename || strchr (filename, '/') || !strchr (filename, '\\'))
3357 return g_path_get_basename (filename);
3361 /* No separator -> filename */
3362 r = strrchr (filename, '\\');
3364 return g_strdup (filename);
3366 /* Trailing slash, remove component */
3368 char *copy = g_strdup (filename);
3369 copy [r-filename] = 0;
3370 r = strrchr (copy, '\\');
3374 return g_strdup ("/");
3376 r = g_strdup (&r[1]);
3381 return g_strdup (&r[1]);
3385 init_jit_info_dbg_attrs (MonoJitInfo *ji)
3387 static MonoClass *hidden_klass, *step_through_klass, *non_user_klass;
3389 MonoCustomAttrInfo *ainfo;
3391 if (ji->dbg_attrs_inited)
3395 hidden_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3397 if (!step_through_klass)
3398 step_through_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3400 if (!non_user_klass)
3401 non_user_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute");
3403 ainfo = mono_custom_attrs_from_method_checked (jinfo_get_method (ji), &error);
3404 mono_error_cleanup (&error); /* FIXME don't swallow the error? */
3406 if (mono_custom_attrs_has_attr (ainfo, hidden_klass))
3407 ji->dbg_hidden = TRUE;
3408 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3409 ji->dbg_step_through = TRUE;
3410 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3411 ji->dbg_non_user_code = TRUE;
3412 mono_custom_attrs_free (ainfo);
3415 ainfo = mono_custom_attrs_from_class_checked (jinfo_get_method (ji)->klass, &error);
3416 mono_error_cleanup (&error); /* FIXME don't swallow the error? */
3418 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3419 ji->dbg_step_through = TRUE;
3420 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3421 ji->dbg_non_user_code = TRUE;
3422 mono_custom_attrs_free (ainfo);
3425 mono_memory_barrier ();
3426 ji->dbg_attrs_inited = TRUE;
3434 * create_event_list:
3436 * Return a list of event request ids matching EVENT, starting from REQS, which
3437 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3439 * We return request ids, instead of requests, to simplify threading, since
3440 * requests could be deleted anytime when the loader lock is not held.
3441 * LOCKING: Assumes the loader lock is held.
3444 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3447 GSList *events = NULL;
3449 *suspend_policy = SUSPEND_POLICY_NONE;
3452 reqs = event_requests;
3457 for (i = 0; i < reqs->len; ++i) {
3458 EventRequest *req = (EventRequest *)g_ptr_array_index (reqs, i);
3459 if (req->event_kind == event) {
3460 gboolean filtered = FALSE;
3463 for (j = 0; j < req->nmodifiers; ++j) {
3464 Modifier *mod = &req->modifiers [j];
3466 if (mod->kind == MOD_KIND_COUNT) {
3468 if (mod->data.count > 0) {
3469 if (mod->data.count > 0) {
3471 if (mod->data.count == 0)
3475 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3476 if (mod->data.thread != mono_thread_internal_current ())
3478 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3479 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3481 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3483 if (ei->caught && !mod->caught)
3485 if (!ei->caught && !mod->uncaught)
3487 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3489 gboolean found = FALSE;
3490 MonoAssembly **assemblies = mod->data.assemblies;
3493 for (k = 0; assemblies [k]; ++k)
3494 if (assemblies [k] == jinfo_get_method (ji)->klass->image->assembly)
3499 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3500 gpointer iter = NULL;
3502 MonoDebugSourceInfo *sinfo;
3503 char *source_file, *s;
3504 gboolean found = FALSE;
3506 GPtrArray *source_file_list;
3508 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3509 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3512 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, NULL, NULL, NULL);
3513 for (i = 0; i < source_file_list->len; ++i) {
3514 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
3516 * Do a case-insesitive match by converting the file name to
3519 s = strdup_tolower (sinfo->source_file);
3520 if (g_hash_table_lookup (mod->data.source_files, s))
3523 char *s2 = dbg_path_get_basename (sinfo->source_file);
3524 char *s3 = strdup_tolower (s2);
3526 if (g_hash_table_lookup (mod->data.source_files, s3))
3533 g_ptr_array_free (source_file_list, TRUE);
3538 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3541 s = mono_type_full_name (&ei->klass->byval_arg);
3542 if (!g_hash_table_lookup (mod->data.type_names, s))
3545 } else if (mod->kind == MOD_KIND_STEP) {
3546 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3547 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3548 !strcmp (jinfo_get_method (ji)->name, ".cctor") &&
3549 (jinfo_get_method (ji) != ((SingleStepReq*)req->info)->start_method))
3551 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3552 init_jit_info_dbg_attrs (ji);
3556 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3557 init_jit_info_dbg_attrs (ji);
3558 if (ji->dbg_step_through)
3561 if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3562 init_jit_info_dbg_attrs (ji);
3563 if (ji->dbg_non_user_code)
3570 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3571 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3576 /* Send a VM START/DEATH event by default */
3577 if (event == EVENT_KIND_VM_START)
3578 events = g_slist_append (events, GINT_TO_POINTER (0));
3579 if (event == EVENT_KIND_VM_DEATH)
3580 events = g_slist_append (events, GINT_TO_POINTER (0));
3585 static G_GNUC_UNUSED const char*
3586 event_to_string (EventKind event)
3589 case EVENT_KIND_VM_START: return "VM_START";
3590 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3591 case EVENT_KIND_THREAD_START: return "THREAD_START";
3592 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3593 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3594 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3595 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3596 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3597 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3598 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3599 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3600 case EVENT_KIND_STEP: return "STEP";
3601 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3602 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3603 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3604 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3605 case EVENT_KIND_USER_LOG: return "USER_LOG";
3607 g_assert_not_reached ();
3615 * Send an event to the client, suspending the vm if needed.
3616 * LOCKING: Since this can suspend the calling thread, no locks should be held
3618 * The EVENTS list is freed by this function.
3621 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3625 MonoDomain *domain = mono_domain_get ();
3626 MonoThread *thread = NULL;
3627 MonoObject *keepalive_obj = NULL;
3628 gboolean send_success = FALSE;
3633 DEBUG_PRINTF (2, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event));
3637 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3638 // FIXME: We miss those events
3639 DEBUG_PRINTF (2, "VM start event not sent yet: dropping %s\n", event_to_string (event));
3643 if (vm_death_event_sent) {
3644 DEBUG_PRINTF (2, "VM death event has been sent: dropping %s\n", event_to_string (event));
3648 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3649 DEBUG_PRINTF (2, "Mono runtime is shutting down: dropping %s\n", event_to_string (event));
3654 DEBUG_PRINTF (2, "Debugger client is not connected: dropping %s\n", event_to_string (event));
3658 if (event == EVENT_KIND_KEEPALIVE)
3659 suspend_policy = SUSPEND_POLICY_NONE;
3664 if (agent_config.defer) {
3665 /* Make sure the thread id is always set when doing deferred debugging */
3666 if (is_debugger_thread ()) {
3667 /* Don't suspend on events from the debugger thread */
3668 suspend_policy = SUSPEND_POLICY_NONE;
3669 thread = mono_thread_get_main ();
3671 else thread = mono_thread_current ();
3673 if (is_debugger_thread () && event != EVENT_KIND_VM_DEATH)
3674 // FIXME: Send these with a NULL thread, don't suspend the current thread
3679 nevents = g_slist_length (events);
3680 buffer_init (&buf, 128);
3681 buffer_add_byte (&buf, suspend_policy);
3682 buffer_add_int (&buf, nevents);
3684 for (l = events; l; l = l->next) {
3685 buffer_add_byte (&buf, event); // event kind
3686 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3690 if (event == EVENT_KIND_VM_DEATH) {
3694 thread = mono_thread_current ();
3696 if (event == EVENT_KIND_VM_START && arg != NULL)
3697 thread = (MonoThread *)arg;
3700 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3703 case EVENT_KIND_THREAD_START:
3704 case EVENT_KIND_THREAD_DEATH:
3706 case EVENT_KIND_APPDOMAIN_CREATE:
3707 case EVENT_KIND_APPDOMAIN_UNLOAD:
3708 buffer_add_domainid (&buf, (MonoDomain *)arg);
3710 case EVENT_KIND_METHOD_ENTRY:
3711 case EVENT_KIND_METHOD_EXIT:
3712 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3714 case EVENT_KIND_ASSEMBLY_LOAD:
3715 buffer_add_assemblyid (&buf, domain, (MonoAssembly *)arg);
3717 case EVENT_KIND_ASSEMBLY_UNLOAD: {
3718 DebuggerTlsData *tls;
3720 /* The domain the assembly belonged to is not equal to the current domain */
3721 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3723 g_assert (tls->domain_unloading);
3725 buffer_add_assemblyid (&buf, tls->domain_unloading, (MonoAssembly *)arg);
3728 case EVENT_KIND_TYPE_LOAD:
3729 buffer_add_typeid (&buf, domain, (MonoClass *)arg);
3731 case EVENT_KIND_BREAKPOINT:
3732 case EVENT_KIND_STEP:
3733 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3734 buffer_add_long (&buf, il_offset);
3736 case EVENT_KIND_VM_START:
3737 buffer_add_domainid (&buf, mono_get_root_domain ());
3739 case EVENT_KIND_VM_DEATH:
3740 if (CHECK_PROTOCOL_VERSION (2, 27))
3741 buffer_add_int (&buf, mono_environment_exitcode_get ());
3743 case EVENT_KIND_EXCEPTION: {
3744 EventInfo *ei = (EventInfo *)arg;
3745 buffer_add_objid (&buf, ei->exc);
3747 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3748 * later after the suspension. (#12494).
3750 keepalive_obj = ei->exc;
3753 case EVENT_KIND_USER_BREAK:
3755 case EVENT_KIND_USER_LOG: {
3756 EventInfo *ei = (EventInfo *)arg;
3757 buffer_add_int (&buf, ei->level);
3758 buffer_add_string (&buf, ei->category ? ei->category : "");
3759 buffer_add_string (&buf, ei->message ? ei->message : "");
3762 case EVENT_KIND_KEEPALIVE:
3763 suspend_policy = SUSPEND_POLICY_NONE;
3766 g_assert_not_reached ();
3770 if (event == EVENT_KIND_VM_START) {
3771 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3772 if (!agent_config.defer)
3773 start_debugger_thread ();
3776 if (event == EVENT_KIND_VM_DEATH) {
3777 vm_death_event_sent = TRUE;
3778 suspend_policy = SUSPEND_POLICY_NONE;
3781 if (mono_runtime_is_shutting_down ())
3782 suspend_policy = SUSPEND_POLICY_NONE;
3784 if (suspend_policy != SUSPEND_POLICY_NONE) {
3786 * Save the thread context and start suspending before sending the packet,
3787 * since we could be receiving the resume request before send_packet ()
3790 save_thread_context (ctx);
3794 /* This will keep this object alive */
3795 get_objref (keepalive_obj);
3798 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3802 g_slist_free (events);
3805 if (!send_success) {
3806 DEBUG_PRINTF (2, "Sending command %s failed.\n", event_to_string (event));
3810 if (event == EVENT_KIND_VM_START) {
3811 vm_start_event_sent = TRUE;
3814 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);
3816 switch (suspend_policy) {
3817 case SUSPEND_POLICY_NONE:
3819 case SUSPEND_POLICY_ALL:
3822 case SUSPEND_POLICY_EVENT_THREAD:
3826 g_assert_not_reached ();
3831 process_profiler_event (EventKind event, gpointer arg)
3835 EventInfo ei, *ei_arg = NULL;
3837 if (event == EVENT_KIND_TYPE_LOAD) {
3838 ei.klass = (MonoClass *)arg;
3842 mono_loader_lock ();
3843 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3844 mono_loader_unlock ();
3846 process_event (event, arg, 0, NULL, events, suspend_policy);
3850 runtime_initialized (MonoProfiler *prof)
3852 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3853 if (agent_config.defer)
3854 start_debugger_thread ();
3858 runtime_shutdown (MonoProfiler *prof)
3860 process_profiler_event (EVENT_KIND_VM_DEATH, NULL);
3862 mono_debugger_agent_cleanup ();
3866 thread_startup (MonoProfiler *prof, uintptr_t tid)
3868 MonoInternalThread *thread = mono_thread_internal_current ();
3869 MonoInternalThread *old_thread;
3870 DebuggerTlsData *tls;
3872 if (is_debugger_thread ())
3875 g_assert (mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (tid), MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid)));
3877 mono_loader_lock ();
3878 old_thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3879 mono_loader_unlock ();
3881 if (thread == old_thread) {
3883 * For some reason, thread_startup () might be called for the same thread
3884 * multiple times (attach ?).
3886 DEBUG_PRINTF (1, "[%p] thread_start () called multiple times for %p, ignored.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3890 * thread_end () might not be called for some threads, and the tid could
3893 DEBUG_PRINTF (1, "[%p] Removing stale data for tid %p.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3894 mono_loader_lock ();
3895 mono_g_hash_table_remove (thread_to_tls, old_thread);
3896 mono_g_hash_table_remove (tid_to_thread, GUINT_TO_POINTER (tid));
3897 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3898 mono_loader_unlock ();
3902 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3904 // FIXME: Free this somewhere
3905 tls = g_new0 (DebuggerTlsData, 1);
3906 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread, MONO_ROOT_SOURCE_DEBUGGER, "debugger thread reference");
3907 tls->thread = thread;
3908 mono_native_tls_set_value (debugger_tls_id, tls);
3910 DEBUG_PRINTF (1, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3912 mono_loader_lock ();
3913 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3914 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3915 mono_g_hash_table_insert (tid_to_thread_obj, GUINT_TO_POINTER (tid), mono_thread_current ());
3916 mono_loader_unlock ();
3918 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3921 * suspend_vm () could have missed this thread, so wait for a resume.
3927 thread_end (MonoProfiler *prof, uintptr_t tid)
3929 MonoInternalThread *thread;
3930 DebuggerTlsData *tls = NULL;
3932 mono_loader_lock ();
3933 thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3935 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3936 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
3938 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3939 tls->terminated = TRUE;
3940 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3941 MONO_GC_UNREGISTER_ROOT (tls->thread);
3945 mono_loader_unlock ();
3947 /* We might be called for threads started before we registered the start callback */
3949 DEBUG_PRINTF (1, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3951 if (mono_thread_internal_is_current (thread) && !mono_native_tls_get_value (debugger_tls_id)
3954 * This can happen on darwin since we deregister threads using pthread dtors.
3955 * process_profiler_event () and the code it calls cannot handle a null TLS value.
3960 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3965 appdomain_load (MonoProfiler *prof, MonoDomain *domain)
3967 mono_loader_lock ();
3968 g_hash_table_insert (domains, domain, domain);
3969 mono_loader_unlock ();
3971 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3975 appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain)
3977 DebuggerTlsData *tls;
3979 /* This might be called during shutdown on the debugger thread from the CMD_VM_EXIT code */
3980 if (is_debugger_thread ())
3984 * Remember the currently unloading appdomain as it is needed to generate
3985 * proper ids for unloading assemblies.
3987 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3989 tls->domain_unloading = domain;
3993 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3995 DebuggerTlsData *tls;
3997 if (is_debugger_thread ())
4000 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4002 tls->domain_unloading = NULL;
4004 clear_breakpoints_for_domain (domain);
4006 mono_loader_lock ();
4007 /* Invalidate each thread's frame stack */
4008 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
4009 mono_loader_unlock ();
4011 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
4015 * invalidate_each_thread:
4017 * A GHFunc to invalidate frames.
4018 * value must be a DebuggerTlsData*
4021 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
4023 invalidate_frames ((DebuggerTlsData *)value);
4027 assembly_load (MonoProfiler *prof, MonoAssembly *assembly)
4029 /* Sent later in jit_end () */
4031 g_ptr_array_add (pending_assembly_loads, assembly);
4036 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
4038 if (is_debugger_thread ())
4041 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
4043 clear_event_requests_for_assembly (assembly);
4044 clear_types_for_assembly (assembly);
4048 send_type_load (MonoClass *klass)
4050 gboolean type_load = FALSE;
4051 MonoDomain *domain = mono_domain_get ();
4052 AgentDomainInfo *info = NULL;
4054 info = get_agent_domain_info (domain);
4056 mono_loader_lock ();
4058 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
4060 g_hash_table_insert (info->loaded_classes, klass, klass);
4063 mono_loader_unlock ();
4066 emit_type_load (klass, klass, NULL);
4070 * Emit load events for all types currently loaded in the domain.
4071 * Takes the loader and domain locks.
4072 * user_data is unused.
4075 send_types_for_domain (MonoDomain *domain, void *user_data)
4077 MonoDomain* old_domain;
4078 AgentDomainInfo *info = NULL;
4080 info = get_agent_domain_info (domain);
4083 old_domain = mono_domain_get ();
4085 mono_domain_set (domain, TRUE);
4087 mono_loader_lock ();
4088 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4089 mono_loader_unlock ();
4091 mono_domain_set (old_domain, TRUE);
4095 send_assemblies_for_domain (MonoDomain *domain, void *user_data)
4098 MonoDomain* old_domain;
4100 old_domain = mono_domain_get ();
4102 mono_domain_set (domain, TRUE);
4104 mono_domain_assemblies_lock (domain);
4105 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
4106 MonoAssembly* ass = (MonoAssembly *)tmp->data;
4107 emit_assembly_load (ass, NULL);
4109 mono_domain_assemblies_unlock (domain);
4111 mono_domain_set (old_domain, TRUE);
4115 jit_done (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo)
4117 jit_end (prof, method, jinfo);
4121 jit_failed (MonoProfiler *prof, MonoMethod *method)
4123 jit_end (prof, method, NULL);
4127 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo)
4130 * We emit type load events when the first method of the type is JITted,
4131 * since the class load profiler callbacks might be called with the
4132 * loader lock held. They could also occur in the debugger thread.
4133 * Same for assembly load events.
4136 MonoAssembly *assembly = NULL;
4138 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4140 if (pending_assembly_loads->len > 0) {
4141 assembly = (MonoAssembly *)g_ptr_array_index (pending_assembly_loads, 0);
4142 g_ptr_array_remove_index (pending_assembly_loads, 0);
4147 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4153 send_type_load (method->klass);
4156 add_pending_breakpoints (method, jinfo);
4160 * BREAKPOINTS/SINGLE STEPPING
4164 * Contains information about an inserted breakpoint.
4167 long il_offset, native_offset;
4171 } BreakpointInstance;
4174 * Contains generic information about a breakpoint.
4178 * The method where the breakpoint is placed. Can be NULL in which case it
4179 * is inserted into every method. This is used to implement method entry/
4180 * exit events. Can be a generic method definition, in which case the
4181 * breakpoint is inserted into every instance.
4187 * A list of BreakpointInstance structures describing where the breakpoint
4188 * was inserted. There could be more than one because of
4189 * generics/appdomains/method entry/exit.
4191 GPtrArray *children;
4194 /* List of breakpoints */
4195 /* Protected by the loader lock */
4196 static GPtrArray *breakpoints;
4197 /* Maps breakpoint locations to the number of breakpoints at that location */
4198 static GHashTable *bp_locs;
4201 breakpoints_init (void)
4203 breakpoints = g_ptr_array_new ();
4204 bp_locs = g_hash_table_new (NULL, NULL);
4208 * insert_breakpoint:
4210 * Insert the breakpoint described by BP into the method described by
4214 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4217 BreakpointInstance *inst;
4218 SeqPointIterator it;
4219 gboolean it_has_sp = FALSE;
4224 mono_seq_point_iterator_init (&it, seq_points);
4225 while (mono_seq_point_iterator_next (&it)) {
4226 if (it.seq_point.il_offset == bp->il_offset) {
4234 * The set of IL offsets with seq points doesn't completely match the
4235 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4237 mono_seq_point_iterator_init (&it, seq_points);
4238 while (mono_seq_point_iterator_next (&it)) {
4239 if (it.seq_point.il_offset != METHOD_ENTRY_IL_OFFSET &&
4240 it.seq_point.il_offset != METHOD_EXIT_IL_OFFSET &&
4241 it.seq_point.il_offset + 1 == bp->il_offset) {
4249 char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d", mono_method_full_name (jinfo_get_method (ji), TRUE), bp->il_offset);
4251 mono_seq_point_iterator_init (&it, seq_points);
4252 while (mono_seq_point_iterator_next (&it))
4253 DEBUG_PRINTF (1, "%d\n", it.seq_point.il_offset);
4256 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4257 g_warning ("%s", s);
4261 g_warning ("%s", s);
4267 inst = g_new0 (BreakpointInstance, 1);
4268 inst->il_offset = it.seq_point.il_offset;
4269 inst->native_offset = it.seq_point.native_offset;
4270 inst->ip = (guint8*)ji->code_start + it.seq_point.native_offset;
4272 inst->domain = domain;
4274 mono_loader_lock ();
4276 g_ptr_array_add (bp->children, inst);
4278 mono_loader_unlock ();
4281 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4282 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4285 if (it.seq_point.native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4286 DEBUG_PRINTF (1, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset);
4287 } else if (count == 0) {
4288 if (ji->is_interp) {
4289 mono_interp_set_breakpoint (ji, inst->ip);
4291 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4292 mono_arch_set_breakpoint (ji, inst->ip);
4299 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);
4303 remove_breakpoint (BreakpointInstance *inst)
4305 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4307 MonoJitInfo *ji = inst->ji;
4308 guint8 *ip = inst->ip;
4311 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4312 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4315 g_assert (count > 0);
4317 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4319 mono_interp_clear_breakpoint (ji, ip);
4321 mono_arch_clear_breakpoint (ji, ip);
4322 DEBUG_PRINTF (1, "[dbg] Clear breakpoint at %s [%p].\n", mono_method_full_name (jinfo_get_method (ji), TRUE), ip);
4330 * This doesn't take any locks.
4332 static inline gboolean
4333 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4339 if (method == bp->method)
4341 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4344 if (bp->method->is_inflated && method->is_inflated) {
4345 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4346 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4348 /* Open generic methods should match closed generic methods of the same class */
4349 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4350 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4351 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4353 /* FIXME: Handle !mvar */
4354 if (t1->type != MONO_TYPE_MVAR)
4365 * add_pending_breakpoints:
4367 * Insert pending breakpoints into the newly JITted method METHOD.
4370 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4373 MonoSeqPointInfo *seq_points;
4375 MonoMethod *jmethod;
4380 domain = mono_domain_get ();
4382 mono_loader_lock ();
4384 for (i = 0; i < breakpoints->len; ++i) {
4385 MonoBreakpoint *bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4386 gboolean found = FALSE;
4388 if (!bp_matches_method (bp, method))
4391 for (j = 0; j < bp->children->len; ++j) {
4392 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4399 MonoMethod *declaring = NULL;
4401 jmethod = jinfo_get_method (ji);
4402 if (jmethod->is_inflated)
4403 declaring = mono_method_get_declaring_generic_method (jmethod);
4405 mono_domain_lock (domain);
4406 seq_points = (MonoSeqPointInfo *)g_hash_table_lookup (domain_jit_info (domain)->seq_points, jmethod);
4407 if (!seq_points && declaring)
4408 seq_points = (MonoSeqPointInfo *)g_hash_table_lookup (domain_jit_info (domain)->seq_points, declaring);
4409 mono_domain_unlock (domain);
4411 /* Could be AOT code */
4413 g_assert (seq_points);
4415 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4419 mono_loader_unlock ();
4423 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4431 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4435 /* Might be AOTed code */
4436 mono_class_init (method->klass);
4437 code = mono_aot_get_method_checked (domain, method, &oerror);
4439 mono_error_assert_ok (&oerror);
4440 ji = mono_jit_info_table_find (domain, (char *)code);
4442 /* Might be interpreted */
4443 ji = mono_interp_find_jit_info (domain, method);
4448 insert_breakpoint (seq_points, domain, ji, bp, error);
4452 clear_breakpoint (MonoBreakpoint *bp);
4457 * Set a breakpoint at IL_OFFSET in METHOD.
4458 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4459 * METHOD can also be a generic method definition, in which case a breakpoint
4460 * is placed in all instances of the method.
4461 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4464 static MonoBreakpoint*
4465 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4468 GHashTableIter iter, iter2;
4471 MonoSeqPointInfo *seq_points;
4473 GPtrArray *method_domains;
4474 GPtrArray *method_seq_points;
4481 // - suspend/resume the vm to prevent code patching problems
4482 // - multiple breakpoints on the same location
4483 // - dynamic methods
4486 bp = g_new0 (MonoBreakpoint, 1);
4487 bp->method = method;
4488 bp->il_offset = il_offset;
4490 bp->children = g_ptr_array_new ();
4492 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);
4494 methods = g_ptr_array_new ();
4495 method_domains = g_ptr_array_new ();
4496 method_seq_points = g_ptr_array_new ();
4498 mono_loader_lock ();
4499 g_hash_table_iter_init (&iter, domains);
4500 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4501 mono_domain_lock (domain);
4502 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4503 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4504 if (bp_matches_method (bp, m)) {
4505 /* Save the info locally to simplify the code inside the domain lock */
4506 g_ptr_array_add (methods, m);
4507 g_ptr_array_add (method_domains, domain);
4508 g_ptr_array_add (method_seq_points, seq_points);
4511 mono_domain_unlock (domain);
4514 for (i = 0; i < methods->len; ++i) {
4515 m = (MonoMethod *)g_ptr_array_index (methods, i);
4516 domain = (MonoDomain *)g_ptr_array_index (method_domains, i);
4517 seq_points = (MonoSeqPointInfo *)g_ptr_array_index (method_seq_points, i);
4518 set_bp_in_method (domain, m, seq_points, bp, error);
4521 g_ptr_array_add (breakpoints, bp);
4522 mono_loader_unlock ();
4524 g_ptr_array_free (methods, TRUE);
4525 g_ptr_array_free (method_domains, TRUE);
4526 g_ptr_array_free (method_seq_points, TRUE);
4528 if (error && !mono_error_ok (error)) {
4529 clear_breakpoint (bp);
4537 clear_breakpoint (MonoBreakpoint *bp)
4541 // FIXME: locking, races
4542 for (i = 0; i < bp->children->len; ++i) {
4543 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, i);
4545 remove_breakpoint (inst);
4550 mono_loader_lock ();
4551 g_ptr_array_remove (breakpoints, bp);
4552 mono_loader_unlock ();
4554 g_ptr_array_free (bp->children, TRUE);
4559 breakpoints_cleanup (void)
4563 mono_loader_lock ();
4565 while (i < event_requests->len) {
4566 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
4568 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4569 clear_breakpoint ((MonoBreakpoint *)req->info);
4570 g_ptr_array_remove_index_fast (event_requests, i);
4577 for (i = 0; i < breakpoints->len; ++i)
4578 g_free (g_ptr_array_index (breakpoints, i));
4580 g_ptr_array_free (breakpoints, TRUE);
4581 g_hash_table_destroy (bp_locs);
4586 mono_loader_unlock ();
4590 * clear_breakpoints_for_domain:
4592 * Clear breakpoint instances which reference DOMAIN.
4595 clear_breakpoints_for_domain (MonoDomain *domain)
4599 /* This could be called after shutdown */
4603 mono_loader_lock ();
4604 for (i = 0; i < breakpoints->len; ++i) {
4605 MonoBreakpoint *bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4608 while (j < bp->children->len) {
4609 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4611 if (inst->domain == domain) {
4612 remove_breakpoint (inst);
4616 g_ptr_array_remove_index_fast (bp->children, j);
4622 mono_loader_unlock ();
4626 * ss_calculate_framecount:
4628 * Ensure DebuggerTlsData fields are filled out.
4630 static void ss_calculate_framecount (DebuggerTlsData *tls, MonoContext *ctx)
4632 if (!tls->context.valid)
4633 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4634 compute_frame_info (tls->thread, tls);
4638 ensure_jit (StackFrame* frame)
4641 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
4642 if (!frame->jit && frame->api_method->is_inflated)
4643 frame->jit = mono_debug_find_method(mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
4647 /* This could happen for aot images with no jit debug info */
4648 s = mono_method_full_name (frame->api_method, TRUE);
4649 DEBUG_PRINTF(1, "[dbg] No debug information found for '%s'.\n", s);
4660 * Return FALSE if single stepping needs to continue.
4663 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp, DebuggerTlsData *tls, MonoContext *ctx, MonoMethod* method)
4665 MonoDebugMethodInfo *minfo;
4666 MonoDebugSourceLocation *loc = NULL;
4667 gboolean hit = TRUE;
4669 if (req->async_stepout_method == method) {
4670 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);
4674 if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK)) {
4676 * These seq points are inserted by the JIT after calls, step over needs to skip them.
4678 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);
4682 if ((req->depth == STEP_DEPTH_OVER || req->depth == STEP_DEPTH_OUT) && hit && !req->async_stepout_method) {
4683 gboolean is_step_out = req->depth == STEP_DEPTH_OUT;
4685 ss_calculate_framecount (tls, ctx);
4687 // Because functions can call themselves recursively, we need to make sure we're stopping at the right stack depth.
4688 // In case of step out, the target is the frame *enclosing* the one where the request was made.
4689 int target_frames = req->nframes + (is_step_out ? -1 : 0);
4690 if (req->nframes > 0 && tls->frame_count > 0 && tls->frame_count > target_frames) {
4691 /* Hit the breakpoint in a recursive call, don't halt */
4692 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");
4697 if (req->depth == STEP_DEPTH_INTO && req->size == STEP_SIZE_MIN && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) && ss_req->start_method){
4698 ss_calculate_framecount (tls, ctx);
4699 if (ss_req->start_method == method && req->nframes && tls->frame_count == req->nframes) {//Check also frame count(could be recursion)
4700 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);
4705 MonoDebugMethodAsyncInfo* async_method = mono_debug_lookup_method_async_debug_info (method);
4707 for (int i = 0; i < async_method->num_awaits; i++) {
4708 if (async_method->yield_offsets[i] == sp->il_offset || async_method->resume_offsets[i] == sp->il_offset) {
4709 mono_debug_free_method_async_debug_info (async_method);
4713 mono_debug_free_method_async_debug_info (async_method);
4716 if (req->size != STEP_SIZE_LINE)
4719 /* Have to check whenever a different source line was reached */
4720 minfo = mono_debug_lookup_method (method);
4723 loc = mono_debug_method_lookup_location (minfo, sp->il_offset);
4726 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);
4727 ss_req->last_method = method;
4729 } else if (loc && method == ss_req->last_method && loc->row == ss_req->last_line) {
4730 ss_calculate_framecount (tls, ctx);
4731 if (tls->frame_count == req->nframes) { // If the frame has changed we're clearly not on the same source line.
4732 DEBUG_PRINTF (1, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer) (gsize) mono_native_thread_id_get (), loc->row);
4738 ss_req->last_method = method;
4739 ss_req->last_line = loc->row;
4740 mono_debug_free_source_location (loc);
4747 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4749 return bp->method && bp->method->klass->image->assembly == assembly;
4753 get_this (StackFrame *frame)
4755 //Logic inspiered by "add_var" method and took out path that happens in async method for getting this
4756 MonoDebugVarInfo *var = frame->jit->this_var;
4757 if ((var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS) != MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET)
4760 guint8 * addr = (guint8 *)mono_arch_context_get_int_reg (&frame->ctx, var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS);
4761 addr += (gint32)var->offset;
4762 return *(MonoObject**)addr;
4765 //This ID is used to figure out if breakpoint hit on resumeOffset belongs to us or not
4766 //since thread probably changed...
4768 get_this_async_id (StackFrame *frame)
4770 return get_objid (get_this (frame));
4774 get_set_notification_method (MonoClass* async_builder_class)
4777 GPtrArray* array = mono_class_get_methods_by_name (async_builder_class, "SetNotificationForWaitCompletion", 0x24, FALSE, FALSE, &error);
4778 mono_error_assert_ok (&error);
4779 g_assert (array->len == 1);
4780 MonoMethod* set_notification_method = (MonoMethod *)g_ptr_array_index (array, 0);
4781 g_ptr_array_free (array, TRUE);
4782 return set_notification_method;
4786 set_set_notification_for_wait_completion_flag (StackFrame *frame)
4788 MonoObject* obj = get_this (frame);
4790 MonoClassField *builder_field = mono_class_get_field_from_name (obj->vtable->klass, "<>t__builder");
4791 g_assert (builder_field);
4792 MonoObject* builder;
4794 builder = mono_field_get_value_object_checked (frame->domain, builder_field, obj, &error);
4795 mono_error_assert_ok (&error);
4799 gboolean arg = TRUE;
4801 mono_runtime_invoke_checked (get_set_notification_method (builder->vtable->klass), mono_object_unbox (builder), args, &error);
4802 mono_error_assert_ok (&error);
4803 mono_field_set_value (obj, builder_field, mono_object_unbox (builder));
4806 static MonoMethod* notify_debugger_of_wait_completion_method_cache = NULL;
4809 get_notify_debugger_of_wait_completion_method (void)
4811 if (notify_debugger_of_wait_completion_method_cache != NULL)
4812 return notify_debugger_of_wait_completion_method_cache;
4814 MonoClass* task_class = mono_class_load_from_name (mono_defaults.corlib, "System.Threading.Tasks", "Task");
4815 GPtrArray* array = mono_class_get_methods_by_name (task_class, "NotifyDebuggerOfWaitCompletion", 0x24, FALSE, FALSE, &error);
4816 mono_error_assert_ok (&error);
4817 g_assert (array->len == 1);
4818 notify_debugger_of_wait_completion_method_cache = (MonoMethod *)g_ptr_array_index (array, 0);
4819 g_ptr_array_free (array, TRUE);
4820 return notify_debugger_of_wait_completion_method_cache;
4824 process_breakpoint (DebuggerTlsData *tls, gboolean from_signal)
4828 int i, j, suspend_policy;
4829 guint32 native_offset;
4831 BreakpointInstance *inst;
4832 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4833 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4834 EventKind kind = EVENT_KIND_BREAKPOINT;
4835 MonoContext *ctx = &tls->restore_state.ctx;
4837 MonoSeqPointInfo *info;
4841 // FIXME: Speed this up
4843 ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
4844 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4848 // FIXME: Pass a flag instead to detect this
4849 MonoLMF *lmf = mono_get_lmf ();
4850 MonoInterpFrameHandle *frame;
4852 g_assert (((guint64)lmf->previous_lmf) & 2);
4853 MonoLMFExt *ext = (MonoLMFExt*)lmf;
4855 g_assert (ext->interp_exit);
4856 frame = ext->interp_exit_data;
4857 ji = mono_interp_frame_get_jit_info (frame);
4858 ip = mono_interp_frame_get_ip (frame);
4861 g_assert (ji && !ji->is_trampoline);
4862 method = jinfo_get_method (ji);
4864 /* Compute the native offset of the breakpoint from the ip */
4865 native_offset = ip - (guint8*)ji->code_start;
4868 * Skip the instruction causing the breakpoint signal.
4871 mono_arch_skip_breakpoint (ctx, ji);
4873 if (method->wrapper_type || tls->disable_breakpoints)
4876 bp_reqs = g_ptr_array_new ();
4877 ss_reqs = g_ptr_array_new ();
4878 ss_reqs_orig = g_ptr_array_new ();
4880 mono_loader_lock ();
4883 * The ip points to the instruction causing the breakpoint event, which is after
4884 * the offset recorded in the seq point map, so find the prev seq point before ip.
4886 found_sp = mono_find_prev_seq_point_for_native_offset (mono_domain_get (), method, native_offset, &info, &sp);
4889 no_seq_points_found (method, native_offset);
4891 g_assert (found_sp);
4893 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);
4896 for (i = 0; i < breakpoints->len; ++i) {
4897 bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4902 for (j = 0; j < bp->children->len; ++j) {
4903 inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4904 if (inst->ji == ji && inst->il_offset == sp.il_offset && inst->native_offset == sp.native_offset) {
4905 if (bp->req->event_kind == EVENT_KIND_STEP) {
4906 g_ptr_array_add (ss_reqs_orig, bp->req);
4908 g_ptr_array_add (bp_reqs, bp->req);
4913 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4914 /* Maybe a method entry/exit event */
4915 if (sp.il_offset == METHOD_ENTRY_IL_OFFSET)
4916 kind = EVENT_KIND_METHOD_ENTRY;
4917 else if (sp.il_offset == METHOD_EXIT_IL_OFFSET)
4918 kind = EVENT_KIND_METHOD_EXIT;
4921 /* Process single step requests */
4922 for (i = 0; i < ss_reqs_orig->len; ++i) {
4923 EventRequest *req = (EventRequest *)g_ptr_array_index (ss_reqs_orig, i);
4924 SingleStepReq *ss_req = (SingleStepReq *)req->info;
4927 //if we hit async_stepout_method, it's our no matter which thread
4928 if ((ss_req->async_stepout_method != method) && (ss_req->async_id || mono_thread_internal_current () != ss_req->thread)) {
4929 //We have different thread and we don't have async stepping in progress
4930 //it's breakpoint in parallel thread, ignore it
4931 if (ss_req->async_id == 0)
4934 tls->context.valid = FALSE;
4935 tls->async_state.valid = FALSE;
4936 invalidate_frames (tls);
4937 ss_calculate_framecount(tls, ctx);
4938 //make sure we have enough data to get current async method instance id
4939 if (tls->frame_count == 0 || !ensure_jit (tls->frames [0]))
4942 //Check method is async before calling get_this_async_id
4943 MonoDebugMethodAsyncInfo* asyncMethod = mono_debug_lookup_method_async_debug_info (method);
4947 mono_debug_free_method_async_debug_info (asyncMethod);
4949 //breakpoint was hit in parallelly executing async method, ignore it
4950 if (ss_req->async_id != get_this_async_id (tls->frames [0]))
4954 //Update stepping request to new thread/frame_count that we are continuing on
4955 //so continuing with normal stepping works as expected
4956 if (ss_req->async_stepout_method || ss_req->async_id) {
4957 tls->context.valid = FALSE;
4958 tls->async_state.valid = FALSE;
4959 invalidate_frames (tls);
4960 ss_calculate_framecount (tls, ctx);
4961 ss_req->thread = mono_thread_internal_current ();
4962 ss_req->nframes = tls->frame_count;
4965 hit = ss_update (ss_req, ji, &sp, tls, ctx, method);
4967 g_ptr_array_add (ss_reqs, req);
4969 /* Start single stepping again from the current sequence point */
4970 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
4973 if (ss_reqs->len > 0)
4974 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4975 if (bp_reqs->len > 0)
4976 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4977 if (kind != EVENT_KIND_BREAKPOINT)
4978 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4980 mono_loader_unlock ();
4982 g_ptr_array_free (bp_reqs, TRUE);
4983 g_ptr_array_free (ss_reqs, TRUE);
4986 * FIXME: The first event will suspend, so the second will only be sent after the
4990 process_event (EVENT_KIND_STEP, method, 0, ctx, ss_events, suspend_policy);
4992 process_event (kind, method, 0, ctx, bp_events, suspend_policy);
4993 if (enter_leave_events)
4994 process_event (kind, method, 0, ctx, enter_leave_events, suspend_policy);
4997 /* Process a breakpoint/single step event after resuming from a signal handler */
4999 process_signal_event (void (*func) (DebuggerTlsData*, gboolean))
5001 DebuggerTlsData *tls;
5002 MonoThreadUnwindState orig_restore_state;
5005 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5006 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
5007 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5008 mono_thread_state_init_from_monoctx (&tls->restore_state, &tls->handler_ctx);
5012 /* This is called when resuming from a signal handler, so it shouldn't return */
5013 memcpy (&ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5014 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5015 mono_restore_context (&ctx);
5016 g_assert_not_reached ();
5020 process_breakpoint_from_signal (void)
5022 process_signal_event (process_breakpoint);
5026 resume_from_signal_handler (void *sigctx, void *func)
5028 DebuggerTlsData *tls;
5031 /* Save the original context in TLS */
5032 // FIXME: This might not work on an altstack ?
5033 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5035 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer) (gsize) mono_native_thread_id_get ());
5038 // FIXME: MonoContext usually doesn't include the fp registers, so these are
5039 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
5040 // clob:c could be added to op_seq_point.
5042 mono_sigctx_to_monoctx (sigctx, &ctx);
5043 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
5044 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
5045 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
5047 MONO_CONTEXT_SET_IP (&ctx, func);
5049 mono_monoctx_to_sigctx (&ctx, sigctx);
5051 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
5052 mono_ppc_set_func_into_sigctx (sigctx, func);
5057 mono_debugger_agent_breakpoint_hit (void *sigctx)
5060 * We are called from a signal handler, and running code there causes all kinds of
5061 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
5062 * So set up the signal context to return to the real breakpoint handler function.
5064 resume_from_signal_handler (sigctx, process_breakpoint_from_signal);
5073 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer user_data)
5075 UserBreakCbData *data = user_data;
5077 if (frame->type == FRAME_TYPE_INTERP_TO_MANAGED) {
5081 if (frame->managed) {
5091 * Called by System.Diagnostics.Debugger:Break ().
5094 mono_debugger_agent_user_break (void)
5096 if (agent_config.enabled) {
5100 UserBreakCbData data;
5102 memset (&data, 0, sizeof (UserBreakCbData));
5105 /* Obtain a context */
5106 MONO_CONTEXT_SET_IP (&ctx, NULL);
5107 mono_walk_stack_with_ctx (user_break_cb, NULL, (MonoUnwindOptions)0, &data);
5108 g_assert (data.found);
5110 mono_loader_lock ();
5111 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
5112 mono_loader_unlock ();
5114 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
5115 } else if (debug_options.native_debugger_break) {
5121 ss_depth_to_string (StepDepth depth)
5124 case STEP_DEPTH_OVER:
5126 case STEP_DEPTH_OUT:
5128 case STEP_DEPTH_INTO:
5131 g_assert_not_reached ();
5137 process_single_step_inner (DebuggerTlsData *tls, gboolean from_signal)
5142 int il_offset, suspend_policy;
5145 MonoContext *ctx = &tls->restore_state.ctx;
5148 MonoSeqPointInfo *info;
5150 /* Skip the instruction causing the single step */
5152 mono_arch_skip_single_step (ctx);
5154 if (suspend_count > 0) {
5155 /* Fastpath during invokes, see in process_suspend () */
5156 if (suspend_count - tls->resume_count == 0)
5158 process_suspend (tls, ctx);
5163 // FIXME: A suspend race
5166 if (mono_thread_internal_current () != ss_req->thread)
5169 ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
5171 ji = get_top_method_ji (ip, &domain, (gpointer*)&ip);
5172 g_assert (ji && !ji->is_trampoline);
5174 if (log_level > 0) {
5175 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);
5178 method = jinfo_get_method (ji);
5181 if (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
5186 * Stopping in memset makes half-initialized vtypes visible.
5187 * Stopping in memcpy makes half-copied vtypes visible.
5189 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
5193 * This could be in ss_update method, but mono_find_next_seq_point_for_native_offset is pretty expensive method,
5194 * hence we prefer this check here.
5196 if (ss_req->user_assemblies) {
5197 gboolean found = FALSE;
5198 for (int k = 0; ss_req->user_assemblies[k]; k++)
5199 if (ss_req->user_assemblies[k] == method->klass->image->assembly) {
5209 * The ip points to the instruction causing the single step event, which is before
5210 * the offset recorded in the seq point map, so find the next seq point after ip.
5212 if (!mono_find_next_seq_point_for_native_offset (domain, method, (guint8*)ip - (guint8*)ji->code_start, &info, &sp)) {
5213 g_assert_not_reached ();
5217 il_offset = sp.il_offset;
5219 if (!ss_update (ss_req, ji, &sp, tls, ctx, method))
5222 /* Start single stepping again from the current sequence point */
5223 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
5225 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
5226 (method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
5227 !strcmp (method->name, ".cctor"))
5230 // FIXME: Has to lock earlier
5232 reqs = g_ptr_array_new ();
5234 mono_loader_lock ();
5236 g_ptr_array_add (reqs, ss_req->req);
5238 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
5240 g_ptr_array_free (reqs, TRUE);
5242 mono_loader_unlock ();
5244 process_event (EVENT_KIND_STEP, jinfo_get_method (ji), il_offset, ctx, events, suspend_policy);
5248 process_single_step (void)
5250 process_signal_event (process_single_step_inner);
5254 * mono_debugger_agent_single_step_event:
5256 * Called from a signal handler to handle a single step event.
5259 mono_debugger_agent_single_step_event (void *sigctx)
5261 /* Resume to process_single_step through the signal context */
5263 // FIXME: Since step out/over is implemented using step in, the step in case should
5264 // be as fast as possible. Move the relevant code from process_single_step_inner ()
5267 if (is_debugger_thread ()) {
5269 * This could happen despite our best effors when the runtime calls
5270 * assembly/type resolve hooks.
5271 * FIXME: Breakpoints too.
5275 mono_sigctx_to_monoctx (sigctx, &ctx);
5276 mono_arch_skip_single_step (&ctx);
5277 mono_monoctx_to_sigctx (&ctx, sigctx);
5281 resume_from_signal_handler (sigctx, process_single_step);
5285 debugger_agent_single_step_from_context (MonoContext *ctx)
5287 DebuggerTlsData *tls;
5288 MonoThreadUnwindState orig_restore_state;
5290 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5291 /* Fastpath during invokes, see in process_suspend () */
5292 if (tls && suspend_count && suspend_count - tls->resume_count == 0)
5295 if (is_debugger_thread ())
5300 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
5301 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5302 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5303 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5305 process_single_step_inner (tls, FALSE);
5307 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5308 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5312 debugger_agent_breakpoint_from_context (MonoContext *ctx)
5314 DebuggerTlsData *tls;
5315 MonoThreadUnwindState orig_restore_state;
5318 if (is_debugger_thread ())
5321 orig_ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
5322 MONO_CONTEXT_SET_IP (ctx, orig_ip - 1);
5324 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5326 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5327 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5328 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5330 process_breakpoint (tls, FALSE);
5332 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5333 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5334 if (MONO_CONTEXT_GET_IP (ctx) == orig_ip - 1)
5335 MONO_CONTEXT_SET_IP (ctx, orig_ip);
5339 * start_single_stepping:
5341 * Turn on single stepping. Can be called multiple times, for example,
5342 * by a single step event request + a suspend.
5345 start_single_stepping (void)
5347 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5348 int val = InterlockedIncrement (&ss_count);
5351 mono_arch_start_single_stepping ();
5352 mono_interp_start_single_stepping ();
5355 g_assert_not_reached ();
5360 stop_single_stepping (void)
5362 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5363 int val = InterlockedDecrement (&ss_count);
5366 mono_arch_stop_single_stepping ();
5367 mono_interp_stop_single_stepping ();
5370 g_assert_not_reached ();
5377 * Stop the single stepping operation given by SS_REQ.
5380 ss_stop (SingleStepReq *ss_req)
5385 for (l = ss_req->bps; l; l = l->next) {
5386 clear_breakpoint ((MonoBreakpoint *)l->data);
5388 g_slist_free (ss_req->bps);
5392 ss_req->async_id = 0;
5393 ss_req->async_stepout_method = NULL;
5394 if (ss_req->global) {
5395 stop_single_stepping ();
5396 ss_req->global = FALSE;
5403 * Reject breakpoint if it is a duplicate of one already in list or hash table.
5406 ss_bp_is_unique (GSList *bps, GHashTable *ss_req_bp_cache, MonoMethod *method, guint32 il_offset)
5408 if (ss_req_bp_cache) {
5409 MonoBreakpoint dummy = {method, il_offset, NULL, NULL};
5410 return !g_hash_table_lookup (ss_req_bp_cache, &dummy);
5412 for (GSList *l = bps; l; l = l->next) {
5413 MonoBreakpoint *bp = (MonoBreakpoint *)l->data;
5414 if (bp->method == method && bp->il_offset == il_offset)
5423 * GHashTable equality for a MonoBreakpoint (only care about method and il_offset fields)
5426 ss_bp_eq (gconstpointer ka, gconstpointer kb)
5428 const MonoBreakpoint *s1 = (const MonoBreakpoint *)ka;
5429 const MonoBreakpoint *s2 = (const MonoBreakpoint *)kb;
5430 return (s1->method == s2->method && s1->il_offset == s2->il_offset) ? 1 : 0;
5436 * GHashTable hash for a MonoBreakpoint (only care about method and il_offset fields)
5439 ss_bp_hash (gconstpointer data)
5441 const MonoBreakpoint *s = (const MonoBreakpoint *)data;
5442 guint hash = (guint) (uintptr_t) s->method;
5443 hash ^= ((guint)s->il_offset) << 16; // Assume low bits are more interesting
5444 hash ^= ((guint)s->il_offset) >> 16;
5448 #define MAX_LINEAR_SCAN_BPS 7
5453 * Create a new breakpoint and add it to a step request.
5454 * Will adjust the bp count and cache used by ss_start.
5457 ss_bp_add_one (SingleStepReq *ss_req, int *ss_req_bp_count, GHashTable **ss_req_bp_cache,
5458 MonoMethod *method, guint32 il_offset)
5460 // This list is getting too long, switch to using the hash table
5461 if (!*ss_req_bp_cache && *ss_req_bp_count > MAX_LINEAR_SCAN_BPS) {
5462 *ss_req_bp_cache = g_hash_table_new (ss_bp_hash, ss_bp_eq);
5463 for (GSList *l = ss_req->bps; l; l = l->next)
5464 g_hash_table_insert (*ss_req_bp_cache, l->data, l->data);
5467 if (ss_bp_is_unique (ss_req->bps, *ss_req_bp_cache, method, il_offset)) {
5468 // Create and add breakpoint
5469 MonoBreakpoint *bp = set_breakpoint (method, il_offset, ss_req->req, NULL);
5470 ss_req->bps = g_slist_append (ss_req->bps, bp);
5471 if (*ss_req_bp_cache)
5472 g_hash_table_insert (*ss_req_bp_cache, bp, bp);
5473 (*ss_req_bp_count)++;
5475 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);
5480 is_last_non_empty (SeqPoint* sp, MonoSeqPointInfo *info)
5484 SeqPoint* next = g_new (SeqPoint, sp->next_len);
5485 mono_seq_point_init_next (info, *sp, next);
5486 for (int i = 0; i < sp->next_len; i++) {
5487 if (next [i].flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) {
5488 if (!is_last_non_empty (&next [i], info)) {
5504 * Start the single stepping operation given by SS_REQ from the sequence point SP.
5505 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
5506 * belong to the same thread as CTX.
5507 * If FRAMES is not-null, use that instead of tls->frames for placing breakpoints etc.
5510 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint* sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls,
5511 gboolean step_to_catch, StackFrame **frames, int nframes)
5513 int i, j, frame_index;
5514 SeqPoint *next_sp, *parent_sp = NULL;
5515 SeqPoint local_sp, local_parent_sp;
5517 MonoSeqPointInfo *parent_info;
5518 MonoMethod *parent_sp_method = NULL;
5519 gboolean enable_global = FALSE;
5521 // When 8 or more entries are in bps, we build a hash table to serve as a set of breakpoints.
5522 // Recreating this on each pass is a little wasteful but at least keeps behavior linear.
5523 int ss_req_bp_count = g_slist_length (ss_req->bps);
5524 GHashTable *ss_req_bp_cache = NULL;
5526 /* Stop the previous operation */
5530 * Implement single stepping using breakpoints if possible.
5532 if (step_to_catch) {
5533 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, sp->il_offset);
5537 if (ctx && !frames) {
5538 /* Need parent frames */
5539 if (!tls->context.valid)
5540 mono_thread_state_init_from_monoctx (&tls->context, ctx);
5541 compute_frame_info (tls->thread, tls);
5542 frames = tls->frames;
5543 nframes = tls->frame_count;
5546 MonoDebugMethodAsyncInfo* asyncMethod = mono_debug_lookup_method_async_debug_info (method);
5548 /* Need to stop in catch clauses as well */
5549 for (i = ss_req->depth == STEP_DEPTH_OUT ? 1 : 0; i < nframes; ++i) {
5550 StackFrame *frame = frames [i];
5553 MonoJitInfo *jinfo = frame->ji;
5554 for (j = 0; j < jinfo->num_clauses; ++j) {
5555 // In case of async method we don't want to place breakpoint on last catch handler(which state machine added for whole method)
5556 if (asyncMethod && asyncMethod->num_awaits && i == 0 && j + 1 == jinfo->num_clauses)
5558 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5560 if (mono_find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL, &local_sp))
5561 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, frame->method, local_sp.il_offset);
5566 if (asyncMethod && asyncMethod->num_awaits && nframes && ensure_jit (frames [0])) {
5567 //asyncMethod has value and num_awaits > 0, this means we are inside async method with awaits
5569 // Check if we hit yield_offset during normal stepping, because if we did...
5570 // Go into special async stepping mode which places breakpoint on resumeOffset
5571 // of this await call and sets async_id so we can distinguish it from parallel executions
5572 for (i = 0; i < asyncMethod->num_awaits; i++) {
5573 if (sp->il_offset == asyncMethod->yield_offsets [i]) {
5574 ss_req->async_id = get_this_async_id (frames [0]);
5575 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, asyncMethod->resume_offsets [i]);
5576 if (ss_req_bp_cache)
5577 g_hash_table_destroy (ss_req_bp_cache);
5578 mono_debug_free_method_async_debug_info (asyncMethod);
5582 //If we are at end of async method and doing step-in or step-over...
5583 //Switch to step-out, so whole NotifyDebuggerOfWaitCompletion magic happens...
5584 if (is_last_non_empty (sp, info)) {
5585 ss_req->depth = STEP_DEPTH_OUT;//setting depth to step-out is important, don't inline IF, because code later depends on this
5587 if (ss_req->depth == STEP_DEPTH_OUT) {
5588 set_set_notification_for_wait_completion_flag (frames [0]);
5589 ss_req->async_id = get_this_async_id (frames [0]);
5590 ss_req->async_stepout_method = get_notify_debugger_of_wait_completion_method ();
5591 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, ss_req->async_stepout_method, 0);
5592 if (ss_req_bp_cache)
5593 g_hash_table_destroy (ss_req_bp_cache);
5594 mono_debug_free_method_async_debug_info (asyncMethod);
5600 mono_debug_free_method_async_debug_info (asyncMethod);
5603 * Find the first sequence point in the current or in a previous frame which
5604 * is not the last in its method.
5606 if (ss_req->depth == STEP_DEPTH_OUT) {
5607 /* Ignore seq points in current method */
5608 while (frame_index < nframes) {
5609 StackFrame *frame = frames [frame_index];
5611 method = frame->method;
5612 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5613 sp = (found_sp)? &local_sp : NULL;
5615 if (sp && sp->next_len != 0)
5618 // There could be method calls before the next seq point in the caller when using nested calls
5619 //enable_global = TRUE;
5621 if (sp && sp->next_len == 0) {
5623 while (frame_index < nframes) {
5624 StackFrame *frame = frames [frame_index];
5626 method = frame->method;
5627 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5628 sp = (found_sp)? &local_sp : NULL;
5629 if (sp && sp->next_len != 0)
5635 /* Have to put a breakpoint into a parent frame since the seq points might not cover all control flow out of the method */
5636 while (frame_index < nframes) {
5637 StackFrame *frame = frames [frame_index];
5639 parent_sp_method = frame->method;
5640 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &parent_info, &local_parent_sp);
5641 parent_sp = found_sp ? &local_parent_sp : NULL;
5642 if (found_sp && parent_sp->next_len != 0)
5650 if (sp && sp->next_len > 0) {
5651 SeqPoint* next = g_new(SeqPoint, sp->next_len);
5653 mono_seq_point_init_next (info, *sp, next);
5654 for (i = 0; i < sp->next_len; i++) {
5657 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, next_sp->il_offset);
5663 SeqPoint* next = g_new(SeqPoint, parent_sp->next_len);
5665 mono_seq_point_init_next (parent_info, *parent_sp, next);
5666 for (i = 0; i < parent_sp->next_len; i++) {
5669 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, parent_sp_method, next_sp->il_offset);
5674 if (ss_req->nframes == 0)
5675 ss_req->nframes = nframes;
5677 if ((ss_req->depth == STEP_DEPTH_OVER) && (!sp && !parent_sp)) {
5678 DEBUG_PRINTF (1, "[dbg] No parent frame for step over, transition to step into.\n");
5680 * This is needed since if we leave managed code, and later return to it, step over
5681 * is not going to stop.
5682 * This approach is a bit ugly, since we change the step depth, but it only affects
5683 * clients who reuse the same step request, and only in this special case.
5685 ss_req->depth = STEP_DEPTH_INTO;
5688 if (ss_req->depth == STEP_DEPTH_INTO) {
5689 /* Enable global stepping so we stop at method entry too */
5690 enable_global = TRUE;
5694 * The ctx/frame info computed above will become invalid when we continue.
5696 tls->context.valid = FALSE;
5697 tls->async_state.valid = FALSE;
5698 invalidate_frames (tls);
5701 if (enable_global) {
5702 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5703 ss_req->global = TRUE;
5704 start_single_stepping ();
5705 } else if (!ss_req->bps) {
5706 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5707 ss_req->global = TRUE;
5708 start_single_stepping ();
5710 ss_req->global = FALSE;
5713 if (ss_req_bp_cache)
5714 g_hash_table_destroy (ss_req_bp_cache);
5718 * Start single stepping of thread THREAD
5721 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req)
5723 DebuggerTlsData *tls;
5724 MonoSeqPointInfo *info = NULL;
5725 SeqPoint *sp = NULL;
5728 MonoMethod *method = NULL;
5729 MonoDebugMethodInfo *minfo;
5730 gboolean step_to_catch = FALSE;
5731 gboolean set_ip = FALSE;
5732 StackFrame **frames = NULL;
5735 if (suspend_count == 0)
5736 return ERR_NOT_SUSPENDED;
5738 wait_for_suspend ();
5740 // FIXME: Multiple requests
5742 DEBUG_PRINTF (0, "Received a single step request while the previous one was still active.\n");
5743 return ERR_NOT_IMPLEMENTED;
5746 DEBUG_PRINTF (1, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth));
5748 ss_req = g_new0 (SingleStepReq, 1);
5750 ss_req->thread = thread;
5751 ss_req->size = size;
5752 ss_req->depth = depth;
5753 ss_req->filter = filter;
5756 for (int i = 0; i < req->nmodifiers; i++) {
5757 if (req->modifiers[i].kind == MOD_KIND_ASSEMBLY_ONLY) {
5758 ss_req->user_assemblies = req->modifiers[i].data.assemblies;
5763 mono_loader_lock ();
5764 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5765 mono_loader_unlock ();
5767 if (!tls->context.valid) {
5768 DEBUG_PRINTF (1, "Received a single step request on a thread with no managed frames.");
5769 return ERR_INVALID_ARGUMENT;
5772 if (tls->restore_state.valid && MONO_CONTEXT_GET_IP (&tls->context.ctx) != MONO_CONTEXT_GET_IP (&tls->restore_state.ctx)) {
5774 * Need to start single stepping from restore_state and not from the current state
5777 frames = compute_frame_info_from (thread, tls, &tls->restore_state, &nframes);
5780 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5782 if (tls->catch_state.valid) {
5784 StackFrameInfo frame;
5785 MonoContext new_ctx;
5786 MonoLMF *lmf = NULL;
5789 * We are stopped at a throw site. Stepping should go to the catch site.
5792 /* Find the the jit info for the catch context */
5793 res = mono_find_jit_info_ext (
5794 (MonoDomain *)tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN],
5795 (MonoJitTlsData *)((MonoThreadInfo*)thread->thread_info)->jit_data,
5796 NULL, &tls->catch_state.ctx, &new_ctx, NULL, &lmf, NULL, &frame);
5798 g_assert (frame.type == FRAME_TYPE_MANAGED);
5801 * Find the seq point corresponding to the landing site ip, which is the first seq
5804 found_sp = mono_find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info, &local_sp);
5805 sp = (found_sp)? &local_sp : NULL;
5807 no_seq_points_found (frame.method, frame.native_offset);
5810 method = frame.method;
5812 step_to_catch = TRUE;
5813 /* This make sure the seq point is not skipped by process_single_step () */
5814 ss_req->last_sp = NULL;
5817 if (!step_to_catch) {
5818 StackFrame *frame = NULL;
5821 if (frames && nframes)
5824 compute_frame_info (thread, tls);
5826 if (tls->frame_count)
5827 frame = tls->frames [0];
5830 if (ss_req->size == STEP_SIZE_LINE) {
5832 ss_req->last_method = frame->method;
5833 ss_req->last_line = -1;
5835 minfo = mono_debug_lookup_method (frame->method);
5836 if (minfo && frame->il_offset != -1) {
5837 MonoDebugSourceLocation *loc = mono_debug_method_lookup_location (minfo, frame->il_offset);
5840 ss_req->last_line = loc->row;
5848 if (!method && frame->il_offset != -1) {
5849 /* FIXME: Sort the table and use a binary search */
5850 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5851 sp = (found_sp)? &local_sp : NULL;
5853 no_seq_points_found (frame->method, frame->native_offset);
5855 method = frame->method;
5860 ss_req->start_method = method;
5862 ss_start (ss_req, method, sp, info, set_ip ? &tls->restore_state.ctx : &tls->context.ctx, tls, step_to_catch, frames, nframes);
5865 free_frames (frames, nframes);
5871 ss_destroy (SingleStepReq *req)
5874 g_assert (ss_req == req);
5883 ss_clear_for_assembly (SingleStepReq *req, MonoAssembly *assembly)
5886 gboolean found = TRUE;
5890 for (l = ss_req->bps; l; l = l->next) {
5891 if (breakpoint_matches_assembly ((MonoBreakpoint *)l->data, assembly)) {
5892 clear_breakpoint ((MonoBreakpoint *)l->data);
5893 ss_req->bps = g_slist_delete_link (ss_req->bps, l);
5902 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5905 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5912 if (!agent_config.enabled)
5915 mono_loader_lock ();
5916 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5917 mono_loader_unlock ();
5922 ei.category = mono_string_to_utf8_checked (category, &error);
5923 mono_error_cleanup (&error);
5927 ei.message = mono_string_to_utf8_checked (message, &error);
5928 mono_error_cleanup (&error);
5931 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5933 g_free (ei.category);
5934 g_free (ei.message);
5938 mono_debugger_agent_debug_log_is_enabled (void)
5940 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5941 return agent_config.enabled;
5944 #if defined(PLATFORM_ANDROID) || defined(TARGET_ANDROID)
5946 mono_debugger_agent_unhandled_exception (MonoException *exc)
5955 memset (&ei, 0, sizeof (EventInfo));
5956 ei.exc = (MonoObject*)exc;
5958 mono_loader_lock ();
5959 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5960 mono_loader_unlock ();
5962 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5967 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5968 MonoContext *catch_ctx)
5970 int i, j, suspend_policy;
5972 MonoJitInfo *ji, *catch_ji;
5974 DebuggerTlsData *tls = NULL;
5976 if (thread_to_tls != NULL) {
5977 MonoInternalThread *thread = mono_thread_internal_current ();
5979 mono_loader_lock ();
5980 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5981 mono_loader_unlock ();
5983 if (tls && tls->abort_requested)
5985 if (tls && tls->disable_breakpoints)
5989 memset (&ei, 0, sizeof (EventInfo));
5991 /* Just-In-Time debugging */
5993 if (agent_config.onuncaught && !inited) {
5994 finish_agent_init (FALSE);
5997 * Send an unsolicited EXCEPTION event with a dummy request id.
5999 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
6000 ei.exc = (MonoObject*)exc;
6001 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
6004 } else if (agent_config.onthrow && !inited) {
6006 gboolean found = FALSE;
6008 for (l = agent_config.onthrow; l; l = l->next) {
6009 char *ex_type = (char *)l->data;
6010 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
6012 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
6019 finish_agent_init (FALSE);
6022 * Send an unsolicited EXCEPTION event with a dummy request id.
6024 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
6025 ei.exc = (MonoObject*)exc;
6026 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
6034 ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (throw_ctx), NULL);
6036 catch_ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (catch_ctx), NULL);
6040 ei.exc = (MonoObject*)exc;
6041 ei.caught = catch_ctx != NULL;
6043 mono_loader_lock ();
6045 /* Treat exceptions which are caught in non-user code as unhandled */
6046 for (i = 0; i < event_requests->len; ++i) {
6047 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6048 if (req->event_kind != EVENT_KIND_EXCEPTION)
6051 for (j = 0; j < req->nmodifiers; ++j) {
6052 Modifier *mod = &req->modifiers [j];
6054 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
6056 gboolean found = FALSE;
6057 MonoAssembly **assemblies = mod->data.assemblies;
6060 for (k = 0; assemblies [k]; ++k)
6061 if (assemblies [k] == jinfo_get_method (catch_ji)->klass->image->assembly)
6070 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
6071 mono_loader_unlock ();
6073 if (tls && ei.caught && catch_ctx) {
6074 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
6075 tls->catch_state.ctx = *catch_ctx;
6076 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
6077 tls->catch_state.valid = TRUE;
6080 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
6083 tls->catch_state.valid = FALSE;
6087 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
6089 DebuggerTlsData *tls;
6094 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
6099 * We're about to invoke an exception filter during the first pass of exception handling.
6101 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
6102 * 'orig_ctx' is the context where the exception has been thrown.
6105 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
6107 * If we're stopped in Filter(), normal stack unwinding would first unwind to
6108 * the call site (line 37) and then continue to Main(), but it would never
6109 * include the throw site (line 32).
6111 * Since exception filters are invoked during the first pass of exception handling,
6112 * the stack frames of the throw site are still intact, so we should include them
6115 * We do this here by saving the context of the throw site in 'tls->filter_state'.
6117 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
6118 * but report the location of the 'throw' to the user.
6122 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
6126 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
6128 DebuggerTlsData *tls;
6133 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
6137 tls->filter_state.valid = FALSE;
6141 * buffer_add_value_full:
6143 * Add the encoding of the value at ADDR described by T to the buffer.
6144 * AS_VTYPE determines whenever to treat primitive types as primitive types or
6148 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
6149 gboolean as_vtype, GHashTable *parent_vtypes)
6152 gboolean boxed_vtype = FALSE;
6155 if (!(*(void**)addr)) {
6156 /* This can happen with compiler generated locals */
6157 //printf ("%s\n", mono_type_full_name (t));
6158 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
6161 g_assert (*(void**)addr);
6162 addr = *(void**)addr;
6167 case MONO_TYPE_BOOLEAN:
6170 case MONO_TYPE_CHAR:
6190 case MONO_TYPE_VOID:
6191 buffer_add_byte (buf, t->type);
6193 case MONO_TYPE_BOOLEAN:
6196 buffer_add_byte (buf, t->type);
6197 buffer_add_int (buf, *(gint8*)addr);
6199 case MONO_TYPE_CHAR:
6202 buffer_add_byte (buf, t->type);
6203 buffer_add_int (buf, *(gint16*)addr);
6208 buffer_add_byte (buf, t->type);
6209 buffer_add_int (buf, *(gint32*)addr);
6214 buffer_add_byte (buf, t->type);
6215 buffer_add_long (buf, *(gint64*)addr);
6219 /* Treat it as a vtype */
6221 case MONO_TYPE_PTR: {
6222 gssize val = *(gssize*)addr;
6224 buffer_add_byte (buf, t->type);
6225 buffer_add_long (buf, val);
6229 case MONO_TYPE_STRING:
6230 case MONO_TYPE_SZARRAY:
6231 case MONO_TYPE_OBJECT:
6232 case MONO_TYPE_CLASS:
6233 case MONO_TYPE_ARRAY:
6234 obj = *(MonoObject**)addr;
6237 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
6239 if (obj->vtable->klass->valuetype) {
6240 t = &obj->vtable->klass->byval_arg;
6241 addr = mono_object_unbox (obj);
6244 } else if (obj->vtable->klass->rank) {
6245 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
6246 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
6247 buffer_add_byte (buf, MONO_TYPE_CLASS);
6249 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
6251 buffer_add_objid (buf, obj);
6255 case MONO_TYPE_VALUETYPE:
6256 case MONO_TYPE_TYPEDBYREF: {
6260 MonoClass *klass = mono_class_from_mono_type (t);
6265 * Handle boxed vtypes recursively referencing themselves using fields.
6268 parent_vtypes = g_hash_table_new (NULL, NULL);
6269 vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
6271 if (CHECK_PROTOCOL_VERSION (2, 33)) {
6272 buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
6273 buffer_add_int (buf, vtype_index - 1);
6275 /* The client can't handle PARENT_VTYPE */
6276 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
6280 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
6284 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
6285 buffer_add_byte (buf, klass->enumtype);
6286 buffer_add_typeid (buf, domain, klass);
6290 while ((f = mono_class_get_fields (klass, &iter))) {
6291 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6293 if (mono_field_is_deleted (f))
6297 buffer_add_int (buf, nfields);
6300 while ((f = mono_class_get_fields (klass, &iter))) {
6301 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6303 if (mono_field_is_deleted (f))
6305 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE, parent_vtypes);
6309 g_hash_table_remove (parent_vtypes, addr);
6310 if (g_hash_table_size (parent_vtypes) == 0) {
6311 g_hash_table_destroy (parent_vtypes);
6312 parent_vtypes = NULL;
6317 case MONO_TYPE_GENERICINST:
6318 if (mono_type_generic_inst_is_valuetype (t)) {
6330 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
6332 buffer_add_value_full (buf, t, addr, domain, FALSE, NULL);
6336 obj_is_of_type (MonoObject *obj, MonoType *t)
6338 MonoClass *klass = obj->vtable->klass;
6339 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
6340 if (mono_class_is_transparent_proxy (klass)) {
6341 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
6342 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
6352 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
6355 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6361 gpointer iter = NULL;
6365 is_enum = decode_byte (buf, &buf, limit);
6366 /* Enums are sent as a normal vtype */
6368 return ERR_NOT_IMPLEMENTED;
6369 klass = decode_typeid (buf, &buf, limit, &d, &err);
6370 if (err != ERR_NONE)
6373 if (t && klass != mono_class_from_mono_type (t)) {
6374 char *name = mono_type_full_name (t);
6375 char *name2 = mono_type_full_name (&klass->byval_arg);
6376 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got %s.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, name2);
6379 return ERR_INVALID_ARGUMENT;
6382 nfields = decode_int (buf, &buf, limit);
6383 while ((f = mono_class_get_fields (klass, &iter))) {
6384 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6386 if (mono_field_is_deleted (f))
6388 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
6389 if (err != ERR_NONE)
6393 g_assert (nfields == 0);
6401 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6405 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
6406 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
6407 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
6408 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
6409 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE) &&
6410 !(t->type == MONO_TYPE_VALUETYPE && type == MONO_TYPE_OBJECT)) {
6411 char *name = mono_type_full_name (t);
6412 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
6414 return ERR_INVALID_ARGUMENT;
6418 case MONO_TYPE_BOOLEAN:
6419 *(guint8*)addr = decode_int (buf, &buf, limit);
6421 case MONO_TYPE_CHAR:
6422 *(gunichar2*)addr = decode_int (buf, &buf, limit);
6425 *(gint8*)addr = decode_int (buf, &buf, limit);
6428 *(guint8*)addr = decode_int (buf, &buf, limit);
6431 *(gint16*)addr = decode_int (buf, &buf, limit);
6434 *(guint16*)addr = decode_int (buf, &buf, limit);
6437 *(gint32*)addr = decode_int (buf, &buf, limit);
6440 *(guint32*)addr = decode_int (buf, &buf, limit);
6443 *(gint64*)addr = decode_long (buf, &buf, limit);
6446 *(guint64*)addr = decode_long (buf, &buf, limit);
6449 *(guint32*)addr = decode_int (buf, &buf, limit);
6452 *(guint64*)addr = decode_long (buf, &buf, limit);
6455 /* We send these as I8, so we get them back as such */
6456 g_assert (type == MONO_TYPE_I8);
6457 *(gssize*)addr = decode_long (buf, &buf, limit);
6459 case MONO_TYPE_GENERICINST:
6460 if (MONO_TYPE_ISSTRUCT (t)) {
6461 /* The client sends these as a valuetype */
6469 /* We send these as vtypes, so we get them back as such */
6470 g_assert (type == MONO_TYPE_VALUETYPE);
6473 case MONO_TYPE_VALUETYPE:
6474 if (type == MONO_TYPE_OBJECT) {
6476 int objid = decode_objid (buf, &buf, limit);
6480 err = get_object (objid, (MonoObject**)&obj);
6481 if (err != ERR_NONE)
6484 return ERR_INVALID_ARGUMENT;
6485 if (obj->vtable->klass != mono_class_from_mono_type (t)) {
6486 DEBUG_PRINTF (1, "Expected type '%s', got object '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6487 return ERR_INVALID_ARGUMENT;
6489 memcpy (addr, mono_object_unbox (obj), mono_class_value_size (obj->vtable->klass, NULL));
6491 err = decode_vtype (t, domain, addr, buf, &buf, limit);
6492 if (err != ERR_NONE)
6498 if (MONO_TYPE_IS_REFERENCE (t)) {
6499 if (type == MONO_TYPE_OBJECT) {
6500 int objid = decode_objid (buf, &buf, limit);
6504 err = get_object (objid, (MonoObject**)&obj);
6505 if (err != ERR_NONE)
6509 if (!obj_is_of_type (obj, t)) {
6510 DEBUG_PRINTF (1, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6511 return ERR_INVALID_ARGUMENT;
6514 if (obj && obj->vtable->domain != domain)
6515 return ERR_INVALID_ARGUMENT;
6517 mono_gc_wbarrier_generic_store (addr, obj);
6518 } else if (type == VALUE_TYPE_ID_NULL) {
6519 *(MonoObject**)addr = NULL;
6520 } else if (type == MONO_TYPE_VALUETYPE) {
6529 /* This can happen when round-tripping boxed vtypes */
6531 * Obtain vtype class.
6532 * Same as the beginning of the handle_vtype case above.
6535 is_enum = decode_byte (buf, &buf, limit);
6537 return ERR_NOT_IMPLEMENTED;
6538 klass = decode_typeid (buf, &buf, limit, &d, &err);
6539 if (err != ERR_NONE)
6542 /* Decode the vtype into a temporary buffer, then box it. */
6543 vtype_buf_size = mono_class_value_size (klass, NULL);
6544 vtype_buf = (guint8 *)g_malloc0 (vtype_buf_size);
6545 g_assert (vtype_buf);
6548 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
6549 if (err != ERR_NONE) {
6553 *(MonoObject**)addr = mono_value_box_checked (d, klass, vtype_buf, &error);
6554 mono_error_cleanup (&error);
6557 char *name = mono_type_full_name (t);
6558 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
6560 return ERR_INVALID_ARGUMENT;
6574 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6578 int type = decode_byte (buf, &buf, limit);
6580 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
6581 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
6582 guint8 *nullable_buf;
6585 * First try decoding it as a Nullable`1
6587 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6588 if (err == ERR_NONE)
6592 * Then try decoding as a primitive value or null.
6594 if (targ->type == type) {
6595 nullable_buf = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
6596 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
6597 if (err != ERR_NONE) {
6598 g_free (nullable_buf);
6601 MonoObject *boxed = mono_value_box_checked (domain, mono_class_from_mono_type (targ), nullable_buf, &error);
6602 if (!is_ok (&error)) {
6603 mono_error_cleanup (&error);
6604 return ERR_INVALID_OBJECT;
6606 mono_nullable_init (addr, boxed, mono_class_from_mono_type (t));
6607 g_free (nullable_buf);
6610 } else if (type == VALUE_TYPE_ID_NULL) {
6611 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
6617 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6621 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
6625 guint8 *addr, *gaddr;
6628 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6629 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6632 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
6633 reg_val = mono_arch_context_get_int_reg (ctx, reg);
6635 buffer_add_value_full (buf, t, ®_val, domain, as_vtype, NULL);
6637 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6638 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6639 addr += (gint32)var->offset;
6641 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6643 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6645 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6648 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6649 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
6650 /* Same as regoffset, but with an indirection */
6651 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6652 addr += (gint32)var->offset;
6654 gaddr = (guint8 *)*(gpointer*)addr;
6656 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL);
6658 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
6659 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
6660 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
6661 MonoGSharedVtMethodRuntimeInfo *info;
6667 g_assert (info_var);
6668 g_assert (locals_var);
6670 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6671 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6672 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6673 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6674 addr += (gint32)info_var->offset;
6675 info = (MonoGSharedVtMethodRuntimeInfo *)*(gpointer*)addr;
6676 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6677 info = (MonoGSharedVtMethodRuntimeInfo *)mono_arch_context_get_int_reg (ctx, reg);
6679 g_assert_not_reached ();
6683 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6684 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6685 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6686 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6687 addr += (gint32)locals_var->offset;
6688 locals = (guint8 *)*(gpointer*)addr;
6689 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6690 locals = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6692 g_assert_not_reached ();
6696 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6698 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6703 g_assert_not_reached ();
6708 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
6712 guint8 *addr, *gaddr;
6714 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6715 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6717 if (MONO_TYPE_IS_REFERENCE (t))
6718 size = sizeof (gpointer);
6720 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6723 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6724 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6726 gboolean is_signed = FALSE;
6729 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6732 // FIXME: Write barriers
6733 mono_gc_memmove_atomic (addr, val, size);
6738 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6743 v = is_signed ? *(gint8*)val : *(guint8*)val;
6746 v = is_signed ? *(gint16*)val : *(guint16*)val;
6749 v = is_signed ? *(gint32*)val : *(guint32*)val;
6752 v = is_signed ? *(gint64*)val : *(guint64*)val;
6755 g_assert_not_reached ();
6758 /* Set value on the stack or in the return ctx */
6759 if (reg_locations [reg]) {
6760 /* Saved on the stack */
6761 DEBUG_PRINTF (1, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v);
6762 *(reg_locations [reg]) = v;
6765 DEBUG_PRINTF (1, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v);
6766 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6769 // FIXME: Move these to mono-context.h/c.
6770 mono_arch_context_set_int_reg (ctx, reg, v);
6772 // FIXME: Can't set registers, so we disable linears
6777 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6778 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6779 addr += (gint32)var->offset;
6781 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6784 addr = *(guint8**)addr;
6790 // FIXME: Write barriers
6791 mono_gc_memmove_atomic (addr, val, size);
6793 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6794 /* Same as regoffset, but with an indirection */
6795 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6796 addr += (gint32)var->offset;
6798 gaddr = (guint8 *)*(gpointer*)addr;
6800 // FIXME: Write barriers
6801 mono_gc_memmove_atomic (gaddr, val, size);
6803 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6807 g_assert_not_reached ();
6812 set_interp_var (MonoType *t, gpointer addr, guint8 *val_buf)
6817 addr = *(gpointer*)addr;
6821 if (MONO_TYPE_IS_REFERENCE (t))
6822 size = sizeof (gpointer);
6824 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6826 memcpy (addr, val_buf, size);
6830 clear_event_request (int req_id, int etype)
6834 mono_loader_lock ();
6835 for (i = 0; i < event_requests->len; ++i) {
6836 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6838 if (req->id == req_id && req->event_kind == etype) {
6839 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6840 clear_breakpoint ((MonoBreakpoint *)req->info);
6841 if (req->event_kind == EVENT_KIND_STEP)
6842 ss_destroy ((SingleStepReq *)req->info);
6843 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6844 clear_breakpoint ((MonoBreakpoint *)req->info);
6845 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6846 clear_breakpoint ((MonoBreakpoint *)req->info);
6847 g_ptr_array_remove_index_fast (event_requests, i);
6852 mono_loader_unlock ();
6856 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
6860 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6861 m->kind = MOD_KIND_NONE;
6862 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6863 int count = 0, match_count = 0, pos;
6864 MonoAssembly **newassemblies;
6866 for (i = 0; m->data.assemblies [i]; ++i) {
6868 if (m->data.assemblies [i] == assembly)
6873 // +1 because we don't know length and we use last element to check for end
6874 newassemblies = g_new0 (MonoAssembly*, count - match_count + 1);
6877 for (i = 0; i < count; ++i)
6878 if (m->data.assemblies [i] != assembly)
6879 newassemblies [pos ++] = m->data.assemblies [i];
6880 g_assert (pos == count - match_count);
6881 g_free (m->data.assemblies);
6882 m->data.assemblies = newassemblies;
6888 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
6892 for (i = 0; i < req->nmodifiers; ++i) {
6893 Modifier *m = &req->modifiers [i];
6895 clear_assembly_from_modifier (req, m, assembly);
6900 * clear_event_requests_for_assembly:
6902 * Clear all events requests which reference ASSEMBLY.
6905 clear_event_requests_for_assembly (MonoAssembly *assembly)
6910 mono_loader_lock ();
6914 for (i = 0; i < event_requests->len; ++i) {
6915 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6917 clear_assembly_from_modifiers (req, assembly);
6919 if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly ((MonoBreakpoint *)req->info, assembly)) {
6920 clear_event_request (req->id, req->event_kind);
6925 if (req->event_kind == EVENT_KIND_STEP)
6926 ss_clear_for_assembly ((SingleStepReq *)req->info, assembly);
6929 mono_loader_unlock ();
6933 * type_comes_from_assembly:
6935 * GHRFunc that returns TRUE if klass comes from assembly
6938 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6940 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6944 * clear_types_for_assembly:
6946 * Clears types from loaded_classes for a given assembly
6949 clear_types_for_assembly (MonoAssembly *assembly)
6951 MonoDomain *domain = mono_domain_get ();
6952 AgentDomainInfo *info = NULL;
6954 if (!domain || !domain_jit_info (domain))
6955 /* Can happen during shutdown */
6958 info = get_agent_domain_info (domain);
6960 mono_loader_lock ();
6961 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6962 mono_loader_unlock ();
6966 add_thread (gpointer key, gpointer value, gpointer user_data)
6968 MonoInternalThread *thread = (MonoInternalThread *)value;
6969 Buffer *buf = (Buffer *)user_data;
6971 buffer_add_objid (buf, (MonoObject*)thread);
6975 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6978 guint8 *end = invoke->endp;
6982 MonoMethodSignature *sig;
6985 MonoObject *this_arg, *res, *exc;
6988 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6991 MonoStopwatch watch;
6993 if (invoke->method) {
6995 * Invoke this method directly, currently only Environment.Exit () is supported.
6998 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>");
7000 mono_runtime_try_invoke (invoke->method, NULL, invoke->args, &exc, &error);
7001 mono_error_assert_ok (&error);
7003 g_assert_not_reached ();
7006 m = decode_methodid (p, &p, end, &domain, &err);
7007 if (err != ERR_NONE)
7009 sig = mono_method_signature (m);
7011 if (m->klass->valuetype)
7012 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
7014 this_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
7015 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
7016 /* Should be null */
7017 int type = decode_byte (p, &p, end);
7018 if (type != VALUE_TYPE_ID_NULL) {
7019 DEBUG_PRINTF (1, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
7020 return ERR_INVALID_ARGUMENT;
7022 memset (this_buf, 0, mono_class_instance_size (m->klass));
7023 } else if (m->klass->valuetype && !strcmp (m->name, ".ctor")) {
7027 int type = decode_byte (p, &tmp_p, end);
7028 if (type == VALUE_TYPE_ID_NULL) {
7029 memset (this_buf, 0, mono_class_instance_size (m->klass));
7032 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
7033 if (err != ERR_NONE)
7037 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
7038 if (err != ERR_NONE)
7042 if (!m->klass->valuetype)
7043 this_arg = *(MonoObject**)this_buf;
7047 if (MONO_CLASS_IS_INTERFACE (m->klass)) {
7049 DEBUG_PRINTF (1, "[%p] Error: Interface method invoked without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
7050 return ERR_INVALID_ARGUMENT;
7052 m = mono_object_get_virtual_method (this_arg, m);
7053 /* Transform this to the format the rest of the code expects it to be */
7054 if (m->klass->valuetype) {
7055 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
7056 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
7058 } else if ((m->flags & METHOD_ATTRIBUTE_VIRTUAL) && !m->klass->valuetype && invoke->flags & INVOKE_FLAG_VIRTUAL) {
7060 DEBUG_PRINTF (1, "[%p] Error: invoke with INVOKE_FLAG_VIRTUAL flag set without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
7061 return ERR_INVALID_ARGUMENT;
7063 m = mono_object_get_virtual_method (this_arg, m);
7064 if (m->klass->valuetype) {
7065 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
7066 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
7070 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>");
7072 if (this_arg && this_arg->vtable->domain != domain)
7075 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this_arg) {
7076 if (!strcmp (m->name, ".ctor")) {
7077 if (mono_class_is_abstract (m->klass))
7078 return ERR_INVALID_ARGUMENT;
7081 this_arg = mono_object_new_checked (domain, m->klass, &error);
7082 mono_error_assert_ok (&error);
7085 return ERR_INVALID_ARGUMENT;
7089 if (this_arg && !obj_is_of_type (this_arg, &m->klass->byval_arg))
7090 return ERR_INVALID_ARGUMENT;
7092 nargs = decode_int (p, &p, end);
7093 if (nargs != sig->param_count)
7094 return ERR_INVALID_ARGUMENT;
7095 /* Use alloca to get gc tracking */
7096 arg_buf = (guint8 **)g_alloca (nargs * sizeof (gpointer));
7097 memset (arg_buf, 0, nargs * sizeof (gpointer));
7098 args = (gpointer *)g_alloca (nargs * sizeof (gpointer));
7099 for (i = 0; i < nargs; ++i) {
7100 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
7101 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
7102 if (err != ERR_NONE)
7104 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
7107 if (sig->params [i]->byref) {
7108 arg_buf [i] = (guint8 *)g_alloca (sizeof (mgreg_t));
7109 *(gpointer*)arg_buf [i] = args [i];
7110 args [i] = arg_buf [i];
7113 MonoClass *arg_class = mono_class_from_mono_type (sig->params [i]);
7114 arg_buf [i] = (guint8 *)g_alloca (mono_class_instance_size (arg_class));
7115 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
7116 if (err != ERR_NONE)
7118 if (mono_class_is_nullable (arg_class)) {
7119 args [i] = mono_nullable_box (arg_buf [i], arg_class, &error);
7120 mono_error_assert_ok (&error);
7122 args [i] = arg_buf [i];
7130 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
7131 tls->disable_breakpoints = TRUE;
7133 tls->disable_breakpoints = FALSE;
7136 * Add an LMF frame to link the stack frames on the invoke method with our caller.
7138 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
7139 if (invoke->has_ctx) {
7142 lmf_addr = mono_get_lmf_addr ();
7145 memset (&ext, 0, sizeof (ext));
7146 mono_arch_init_lmf_ext (&ext, *lmf_addr);
7148 ext.debugger_invoke = TRUE;
7149 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
7151 mono_set_lmf ((MonoLMF*)&ext);
7155 mono_stopwatch_start (&watch);
7156 res = mono_runtime_try_invoke (m, m->klass->valuetype ? (gpointer) this_buf : (gpointer) this_arg, args, &exc, &error);
7157 if (exc == NULL && !mono_error_ok (&error)) {
7158 exc = (MonoObject*) mono_error_convert_to_exception (&error);
7160 mono_error_cleanup (&error); /* FIXME report error */
7162 mono_stopwatch_stop (&watch);
7163 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));
7165 buffer_add_byte (buf, 0);
7166 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
7168 gboolean out_this = FALSE;
7169 gboolean out_args = FALSE;
7171 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_THIS) && CHECK_PROTOCOL_VERSION (2, 35))
7173 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_ARGS) && CHECK_PROTOCOL_VERSION (2, 35))
7175 buffer_add_byte (buf, 1 + (out_this ? 2 : 0) + (out_args ? 4 : 0));
7176 if (m->string_ctor) {
7177 buffer_add_value (buf, &mono_get_string_class ()->byval_arg, &res, domain);
7178 } else if (sig->ret->type == MONO_TYPE_VOID && !m->string_ctor) {
7179 if (!strcmp (m->name, ".ctor")) {
7180 if (!m->klass->valuetype)
7181 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this_arg, domain);
7183 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
7185 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
7187 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
7188 buffer_add_value (buf, sig->ret, &res, domain);
7189 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
7190 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
7191 MonoClass *k = mono_class_from_mono_type (sig->ret);
7192 guint8 *nullable_buf = (guint8 *)g_alloca (mono_class_value_size (k, NULL));
7194 g_assert (nullable_buf);
7195 mono_nullable_init (nullable_buf, res, k);
7196 buffer_add_value (buf, sig->ret, nullable_buf, domain);
7199 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
7205 /* Return the new value of the receiver after the call */
7206 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
7208 buffer_add_int (buf, nargs);
7209 for (i = 0; i < nargs; ++i) {
7210 if (MONO_TYPE_IS_REFERENCE (sig->params [i]))
7211 buffer_add_value (buf, sig->params [i], &args [i], domain);
7212 else if (sig->params [i]->byref)
7213 /* add_value () does an indirection */
7214 buffer_add_value (buf, sig->params [i], &arg_buf [i], domain);
7216 buffer_add_value (buf, sig->params [i], arg_buf [i], domain);
7221 tls->disable_breakpoints = FALSE;
7223 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
7224 if (invoke->has_ctx)
7225 mono_set_lmf ((MonoLMF *)(((gssize)ext.lmf.previous_lmf) & ~3));
7229 // FIXME: byref arguments
7237 * Invoke the method given by tls->pending_invoke in the current thread.
7240 invoke_method (void)
7242 DebuggerTlsData *tls;
7248 MonoContext restore_ctx;
7251 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
7255 * Store the `InvokeData *' in `tls->invoke' until we're done with
7256 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
7259 mono_loader_lock ();
7261 invoke = tls->pending_invoke;
7263 tls->pending_invoke = NULL;
7265 invoke->last_invoke = tls->invoke;
7266 tls->invoke = invoke;
7268 mono_loader_unlock ();
7270 tls->frames_up_to_date = FALSE;
7276 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
7277 buffer_init (&buf, 128);
7280 /* Fail the other invokes as well */
7282 err = do_invoke_method (tls, &buf, invoke, p, &p);
7285 if (tls->abort_requested) {
7286 if (CHECK_PROTOCOL_VERSION (2, 42))
7287 err = ERR_INVOKE_ABORTED;
7290 /* Start suspending before sending the reply */
7291 if (mindex == invoke->nmethods - 1) {
7292 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
7293 for (i = 0; i < invoke->suspend_count; ++i)
7298 send_reply_packet (id, err, &buf);
7303 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
7305 if (invoke->has_ctx)
7306 save_thread_context (&restore_ctx);
7308 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
7309 g_assert (tls->resume_count);
7310 tls->resume_count -= invoke->suspend_count;
7313 DEBUG_PRINTF (1, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer) (gsize) mono_native_thread_id_get (), err, tls->resume_count);
7316 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
7318 * It is possible that mono_thread_internal_abort () was called
7319 * after the mono_runtime_invoke_checked() already returned, but it doesn't matter
7320 * because we reset the abort here.
7323 mono_loader_lock ();
7325 if (tls->abort_requested)
7326 mono_thread_internal_reset_abort (tls->thread);
7328 tls->invoke = tls->invoke->last_invoke;
7329 tls->abort_requested = FALSE;
7331 mono_loader_unlock ();
7340 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
7342 MonoThread *thread = (MonoThread *)value;
7343 DebuggerTlsData *tls;
7346 mono_loader_lock ();
7347 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
7349 res = tls->really_suspended;
7350 mono_loader_unlock ();
7356 get_source_files_for_type (MonoClass *klass)
7358 gpointer iter = NULL;
7360 MonoDebugSourceInfo *sinfo;
7364 files = g_ptr_array_new ();
7366 while ((method = mono_class_get_methods (klass, &iter))) {
7367 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
7368 GPtrArray *source_file_list;
7371 mono_debug_get_seq_points (minfo, NULL, &source_file_list, NULL, NULL, NULL);
7372 for (j = 0; j < source_file_list->len; ++j) {
7373 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, j);
7374 for (i = 0; i < files->len; ++i)
7375 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
7377 if (i == files->len)
7378 g_ptr_array_add (files, g_strdup (sinfo->source_file));
7380 g_ptr_array_free (source_file_list, TRUE);
7388 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
7391 case CMD_VM_VERSION: {
7392 char *build_info, *version;
7394 build_info = mono_get_runtime_build_info ();
7395 version = g_strdup_printf ("mono %s", build_info);
7397 buffer_add_string (buf, version); /* vm version */
7398 buffer_add_int (buf, MAJOR_VERSION);
7399 buffer_add_int (buf, MINOR_VERSION);
7400 g_free (build_info);
7404 case CMD_VM_SET_PROTOCOL_VERSION: {
7405 major_version = decode_int (p, &p, end);
7406 minor_version = decode_int (p, &p, end);
7407 protocol_version_set = TRUE;
7408 DEBUG_PRINTF (1, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version);
7411 case CMD_VM_ALL_THREADS: {
7413 mono_loader_lock ();
7414 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
7415 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
7416 mono_loader_unlock ();
7419 case CMD_VM_SUSPEND:
7421 wait_for_suspend ();
7424 if (suspend_count == 0)
7425 return ERR_NOT_SUSPENDED;
7427 clear_suspended_objs ();
7429 case CMD_VM_DISPOSE:
7430 /* Clear all event requests */
7431 mono_loader_lock ();
7432 while (event_requests->len > 0) {
7433 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
7435 clear_event_request (req->id, req->event_kind);
7437 mono_loader_unlock ();
7439 while (suspend_count > 0)
7441 disconnected = TRUE;
7442 vm_start_event_sent = FALSE;
7445 MonoInternalThread *thread;
7446 DebuggerTlsData *tls;
7447 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7448 MonoClass *env_class;
7450 MonoMethod *exit_method = NULL;
7454 exit_code = decode_int (p, &p, end);
7456 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
7458 /* Have to send a reply before exiting */
7459 send_reply_packet (id, 0, buf);
7461 /* Clear all event requests */
7462 mono_loader_lock ();
7463 while (event_requests->len > 0) {
7464 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
7466 clear_event_request (req->id, req->event_kind);
7468 mono_loader_unlock ();
7471 * The JDWP documentation says that the shutdown is not orderly. It doesn't
7472 * specify whenever a VM_DEATH event is sent. We currently do an orderly
7473 * shutdown by hijacking a thread to execute Environment.Exit (). This is
7474 * better than doing the shutdown ourselves, since it avoids various races.
7478 wait_for_suspend ();
7480 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7481 env_class = mono_class_try_load_from_name (mono_defaults.corlib, "System", "Environment");
7483 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
7486 mono_loader_lock ();
7487 thread = (MonoInternalThread *)mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
7488 mono_loader_unlock ();
7490 if (thread && exit_method) {
7491 mono_loader_lock ();
7492 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
7493 mono_loader_unlock ();
7495 args = g_new0 (gpointer, 1);
7496 args [0] = g_malloc (sizeof (int));
7497 *(int*)(args [0]) = exit_code;
7499 tls->pending_invoke = g_new0 (InvokeData, 1);
7500 tls->pending_invoke->method = exit_method;
7501 tls->pending_invoke->args = args;
7502 tls->pending_invoke->nmethods = 1;
7504 while (suspend_count > 0)
7508 * No thread found, do it ourselves.
7509 * FIXME: This can race with normal shutdown etc.
7511 while (suspend_count > 0)
7514 if (!mono_runtime_try_shutdown ())
7517 mono_environment_exitcode_set (exit_code);
7519 /* Suspend all managed threads since the runtime is going away */
7520 DEBUG_PRINTF (1, "Suspending all threads...\n");
7521 mono_thread_suspend_all_other_threads ();
7522 DEBUG_PRINTF (1, "Shutting down the runtime...\n");
7523 mono_runtime_quit ();
7524 transport_close2 ();
7525 DEBUG_PRINTF (1, "Exiting...\n");
7531 case CMD_VM_INVOKE_METHOD:
7532 case CMD_VM_INVOKE_METHODS: {
7533 int objid = decode_objid (p, &p, end);
7535 DebuggerTlsData *tls;
7536 int i, count, flags, nmethods;
7539 err = get_object (objid, (MonoObject**)&thread);
7540 if (err != ERR_NONE)
7543 flags = decode_int (p, &p, end);
7545 if (command == CMD_VM_INVOKE_METHODS)
7546 nmethods = decode_int (p, &p, end);
7550 // Wait for suspending if it already started
7552 wait_for_suspend ();
7553 if (!is_suspended ())
7554 return ERR_NOT_SUSPENDED;
7556 mono_loader_lock ();
7557 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7558 mono_loader_unlock ();
7561 if (!tls->really_suspended)
7562 /* The thread is still running native code, can't do invokes */
7563 return ERR_NOT_SUSPENDED;
7566 * Store the invoke data into tls, the thread will execute it after it is
7569 if (tls->pending_invoke)
7570 return ERR_NOT_SUSPENDED;
7571 tls->pending_invoke = g_new0 (InvokeData, 1);
7572 tls->pending_invoke->id = id;
7573 tls->pending_invoke->flags = flags;
7574 tls->pending_invoke->p = (guint8 *)g_malloc (end - p);
7575 memcpy (tls->pending_invoke->p, p, end - p);
7576 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
7577 tls->pending_invoke->suspend_count = suspend_count;
7578 tls->pending_invoke->nmethods = nmethods;
7580 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
7581 resume_thread (THREAD_TO_INTERNAL (thread));
7584 count = suspend_count;
7585 for (i = 0; i < count; ++i)
7590 case CMD_VM_ABORT_INVOKE: {
7591 int objid = decode_objid (p, &p, end);
7593 DebuggerTlsData *tls;
7597 err = get_object (objid, (MonoObject**)&thread);
7598 if (err != ERR_NONE)
7601 invoke_id = decode_int (p, &p, end);
7603 mono_loader_lock ();
7604 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7607 if (tls->abort_requested) {
7608 DEBUG_PRINTF (1, "Abort already requested.\n");
7609 mono_loader_unlock ();
7614 * Check whether we're still inside the mono_runtime_invoke_checked() and that it's
7615 * actually the correct invocation.
7617 * Careful, we do not stop the thread that's doing the invocation, so we can't
7618 * inspect its stack. However, invoke_method() also acquires the loader lock
7619 * when it's done, so we're safe here.
7623 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
7624 mono_loader_unlock ();
7625 return ERR_NO_INVOCATION;
7628 tls->abort_requested = TRUE;
7630 mono_thread_internal_abort (THREAD_TO_INTERNAL (thread));
7631 mono_loader_unlock ();
7635 case CMD_VM_SET_KEEPALIVE: {
7636 int timeout = decode_int (p, &p, end);
7637 agent_config.keepalive = timeout;
7639 #ifndef DISABLE_SOCKET_TRANSPORT
7646 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
7647 GHashTableIter iter, kiter;
7652 char *fname, *basename;
7653 gboolean ignore_case;
7654 GSList *class_list, *l;
7655 GPtrArray *res_classes, *res_domains;
7657 fname = decode_string (p, &p, end);
7658 ignore_case = decode_byte (p, &p, end);
7660 basename = dbg_path_get_basename (fname);
7662 res_classes = g_ptr_array_new ();
7663 res_domains = g_ptr_array_new ();
7665 mono_loader_lock ();
7666 g_hash_table_iter_init (&iter, domains);
7667 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7668 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
7670 /* Update 'source_file_to_class' cache */
7671 g_hash_table_iter_init (&kiter, info->loaded_classes);
7672 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
7673 if (!g_hash_table_lookup (info->source_files, klass)) {
7674 files = get_source_files_for_type (klass);
7675 g_hash_table_insert (info->source_files, klass, files);
7677 for (i = 0; i < files->len; ++i) {
7678 char *s = (char *)g_ptr_array_index (files, i);
7679 char *s2 = dbg_path_get_basename (s);
7682 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, s2);
7684 class_list = g_slist_prepend (class_list, klass);
7685 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
7687 class_list = g_slist_prepend (class_list, klass);
7688 g_hash_table_insert (info->source_file_to_class, s2, class_list);
7691 /* The _ignorecase hash contains the lowercase path */
7692 s3 = strdup_tolower (s2);
7693 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
7695 class_list = g_slist_prepend (class_list, klass);
7696 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
7698 class_list = g_slist_prepend (class_list, klass);
7699 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
7711 s = strdup_tolower (basename);
7712 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
7715 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, basename);
7718 for (l = class_list; l; l = l->next) {
7719 klass = (MonoClass *)l->data;
7721 g_ptr_array_add (res_classes, klass);
7722 g_ptr_array_add (res_domains, domain);
7725 mono_loader_unlock ();
7730 buffer_add_int (buf, res_classes->len);
7731 for (i = 0; i < res_classes->len; ++i)
7732 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7733 g_ptr_array_free (res_classes, TRUE);
7734 g_ptr_array_free (res_domains, TRUE);
7737 case CMD_VM_GET_TYPES: {
7738 GHashTableIter iter;
7742 gboolean ignore_case;
7743 GPtrArray *res_classes, *res_domains;
7744 MonoTypeNameParse info;
7746 name = decode_string (p, &p, end);
7747 ignore_case = decode_byte (p, &p, end);
7749 if (!mono_reflection_parse_type (name, &info)) {
7751 mono_reflection_free_type_info (&info);
7752 return ERR_INVALID_ARGUMENT;
7755 res_classes = g_ptr_array_new ();
7756 res_domains = g_ptr_array_new ();
7758 mono_loader_lock ();
7759 g_hash_table_iter_init (&iter, domains);
7760 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7762 gboolean type_resolve;
7766 mono_domain_assemblies_lock (domain);
7767 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7768 ass = (MonoAssembly *)tmp->data;
7772 type_resolve = TRUE;
7773 /* FIXME really okay to call while holding locks? */
7774 t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignore_case, &type_resolve, &error);
7775 mono_error_cleanup (&error);
7777 g_ptr_array_add (res_classes, mono_type_get_class (t));
7778 g_ptr_array_add (res_domains, domain);
7782 mono_domain_assemblies_unlock (domain);
7784 mono_loader_unlock ();
7787 mono_reflection_free_type_info (&info);
7789 buffer_add_int (buf, res_classes->len);
7790 for (i = 0; i < res_classes->len; ++i)
7791 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7792 g_ptr_array_free (res_classes, TRUE);
7793 g_ptr_array_free (res_domains, TRUE);
7796 case CMD_VM_START_BUFFERING:
7797 case CMD_VM_STOP_BUFFERING:
7798 /* Handled in the main loop */
7801 return ERR_NOT_IMPLEMENTED;
7808 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7814 case CMD_EVENT_REQUEST_SET: {
7816 int i, event_kind, suspend_policy, nmodifiers;
7820 MonoThread *step_thread;
7821 int step_thread_id = 0;
7822 StepDepth depth = STEP_DEPTH_INTO;
7823 StepSize size = STEP_SIZE_MIN;
7824 StepFilter filter = STEP_FILTER_NONE;
7828 event_kind = decode_byte (p, &p, end);
7829 suspend_policy = decode_byte (p, &p, end);
7830 nmodifiers = decode_byte (p, &p, end);
7832 req = (EventRequest *)g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7833 req->id = InterlockedIncrement (&event_request_id);
7834 req->event_kind = event_kind;
7835 req->suspend_policy = suspend_policy;
7836 req->nmodifiers = nmodifiers;
7839 for (i = 0; i < nmodifiers; ++i) {
7840 mod = (ModifierKind)decode_byte (p, &p, end);
7842 req->modifiers [i].kind = mod;
7843 if (mod == MOD_KIND_COUNT) {
7844 req->modifiers [i].data.count = decode_int (p, &p, end);
7845 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7846 method = decode_methodid (p, &p, end, &domain, &err);
7847 if (err != ERR_NONE)
7849 location = decode_long (p, &p, end);
7850 } else if (mod == MOD_KIND_STEP) {
7851 step_thread_id = decode_id (p, &p, end);
7852 size = (StepSize)decode_int (p, &p, end);
7853 depth = (StepDepth)decode_int (p, &p, end);
7854 if (CHECK_PROTOCOL_VERSION (2, 16))
7855 filter = (StepFilter)decode_int (p, &p, end);
7856 req->modifiers [i].data.filter = filter;
7857 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7858 /* Treat STEP_THOUGH the same as HIDDEN */
7859 req->modifiers [i].data.filter = (StepFilter)(req->modifiers [i].data.filter | STEP_FILTER_DEBUGGER_STEP_THROUGH);
7860 } else if (mod == MOD_KIND_THREAD_ONLY) {
7861 int id = decode_id (p, &p, end);
7863 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7864 if (err != ERR_NONE) {
7868 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7869 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7871 if (err != ERR_NONE)
7873 req->modifiers [i].caught = decode_byte (p, &p, end);
7874 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7875 if (CHECK_PROTOCOL_VERSION (2, 25))
7876 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7878 req->modifiers [i].subclasses = TRUE;
7879 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" : "");
7881 req->modifiers [i].data.exc_class = exc_class;
7883 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
7885 return ERR_INVALID_ARGUMENT;
7888 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7889 int n = decode_int (p, &p, end);
7892 // +1 because we don't know length and we use last element to check for end
7893 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n + 1);
7894 for (j = 0; j < n; ++j) {
7895 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7896 if (err != ERR_NONE) {
7897 g_free (req->modifiers [i].data.assemblies);
7901 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7902 int n = decode_int (p, &p, end);
7905 modifier = &req->modifiers [i];
7906 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7907 for (j = 0; j < n; ++j) {
7908 char *s = decode_string (p, &p, end);
7912 s2 = strdup_tolower (s);
7913 g_hash_table_insert (modifier->data.source_files, s2, s2);
7917 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7918 int n = decode_int (p, &p, end);
7921 modifier = &req->modifiers [i];
7922 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7923 for (j = 0; j < n; ++j) {
7924 char *s = decode_string (p, &p, end);
7927 g_hash_table_insert (modifier->data.type_names, s, s);
7931 return ERR_NOT_IMPLEMENTED;
7935 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7938 req->info = set_breakpoint (method, location, req, &error);
7939 if (!mono_error_ok (&error)) {
7941 DEBUG_PRINTF (1, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error));
7942 mono_error_cleanup (&error);
7943 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7945 } else if (req->event_kind == EVENT_KIND_STEP) {
7946 g_assert (step_thread_id);
7948 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7949 if (err != ERR_NONE) {
7954 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, filter, req);
7955 if (err != ERR_NONE) {
7959 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7960 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7961 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7962 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7963 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7964 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7966 if (req->nmodifiers) {
7968 return ERR_NOT_IMPLEMENTED;
7972 mono_loader_lock ();
7973 g_ptr_array_add (event_requests, req);
7975 if (agent_config.defer) {
7976 /* Transmit cached data to the client on receipt of the event request */
7977 switch (req->event_kind) {
7978 case EVENT_KIND_APPDOMAIN_CREATE:
7979 /* Emit load events for currently loaded domains */
7980 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7982 case EVENT_KIND_ASSEMBLY_LOAD:
7983 /* Emit load events for currently loaded assemblies */
7984 mono_domain_foreach (send_assemblies_for_domain, NULL);
7986 case EVENT_KIND_THREAD_START:
7987 /* Emit start events for currently started threads */
7988 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7990 case EVENT_KIND_TYPE_LOAD:
7991 /* Emit type load events for currently loaded types */
7992 mono_domain_foreach (send_types_for_domain, NULL);
7998 mono_loader_unlock ();
8000 buffer_add_int (buf, req->id);
8003 case CMD_EVENT_REQUEST_CLEAR: {
8004 int etype = decode_byte (p, &p, end);
8005 int req_id = decode_int (p, &p, end);
8007 // FIXME: Make a faster mapping from req_id to request
8008 mono_loader_lock ();
8009 clear_event_request (req_id, etype);
8010 mono_loader_unlock ();
8013 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
8016 mono_loader_lock ();
8018 while (i < event_requests->len) {
8019 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
8021 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
8022 clear_breakpoint ((MonoBreakpoint *)req->info);
8024 g_ptr_array_remove_index_fast (event_requests, i);
8030 mono_loader_unlock ();
8034 return ERR_NOT_IMPLEMENTED;
8041 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8047 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
8048 buffer_add_domainid (buf, mono_get_root_domain ());
8051 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
8052 domain = decode_domainid (p, &p, end, NULL, &err);
8053 if (err != ERR_NONE)
8055 buffer_add_string (buf, domain->friendly_name);
8058 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
8063 domain = decode_domainid (p, &p, end, NULL, &err);
8064 if (err != ERR_NONE)
8066 mono_loader_lock ();
8068 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
8071 buffer_add_int (buf, count);
8072 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
8073 ass = (MonoAssembly *)tmp->data;
8074 buffer_add_assemblyid (buf, domain, ass);
8076 mono_loader_unlock ();
8079 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
8080 domain = decode_domainid (p, &p, end, NULL, &err);
8081 if (err != ERR_NONE)
8084 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
8087 case CMD_APPDOMAIN_GET_CORLIB: {
8088 domain = decode_domainid (p, &p, end, NULL, &err);
8089 if (err != ERR_NONE)
8092 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
8095 case CMD_APPDOMAIN_CREATE_STRING: {
8100 domain = decode_domainid (p, &p, end, NULL, &err);
8101 if (err != ERR_NONE)
8103 s = decode_string (p, &p, end);
8105 o = mono_string_new_checked (domain, s, &error);
8106 if (!is_ok (&error)) {
8107 DEBUG_PRINTF (1, "[dbg] Failed to allocate String object '%s': %s\n", s, mono_error_get_message (&error));
8108 mono_error_cleanup (&error);
8109 return ERR_INVALID_OBJECT;
8111 buffer_add_objid (buf, (MonoObject*)o);
8114 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
8117 MonoDomain *domain2;
8120 domain = decode_domainid (p, &p, end, NULL, &err);
8121 if (err != ERR_NONE)
8123 klass = decode_typeid (p, &p, end, &domain2, &err);
8124 if (err != ERR_NONE)
8128 g_assert (domain == domain2);
8130 o = mono_object_new_checked (domain, klass, &error);
8131 mono_error_assert_ok (&error);
8133 err = decode_value (&klass->byval_arg, domain, (guint8 *)mono_object_unbox (o), p, &p, end);
8134 if (err != ERR_NONE)
8137 buffer_add_objid (buf, o);
8141 return ERR_NOT_IMPLEMENTED;
8148 get_assembly_object_command (MonoDomain *domain, MonoAssembly *ass, Buffer *buf, MonoError *error)
8150 HANDLE_FUNCTION_ENTER();
8151 ErrorCode err = ERR_NONE;
8153 MonoReflectionAssemblyHandle o = mono_assembly_get_object_handle (domain, ass, error);
8154 if (MONO_HANDLE_IS_NULL (o)) {
8155 err = ERR_INVALID_OBJECT;
8158 buffer_add_objid (buf, MONO_HANDLE_RAW (MONO_HANDLE_CAST (MonoObject, o)));
8160 HANDLE_FUNCTION_RETURN_VAL (err);
8165 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8171 ass = decode_assemblyid (p, &p, end, &domain, &err);
8172 if (err != ERR_NONE)
8176 case CMD_ASSEMBLY_GET_LOCATION: {
8177 buffer_add_string (buf, mono_image_get_filename (ass->image));
8180 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
8184 if (ass->image->dynamic) {
8185 buffer_add_id (buf, 0);
8187 token = mono_image_get_entry_point (ass->image);
8189 buffer_add_id (buf, 0);
8192 m = mono_get_method_checked (ass->image, token, NULL, NULL, &error);
8194 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8195 buffer_add_methodid (buf, domain, m);
8200 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
8201 buffer_add_moduleid (buf, domain, ass->image);
8204 case CMD_ASSEMBLY_GET_OBJECT: {
8206 err = get_assembly_object_command (domain, ass, buf, &error);
8207 mono_error_cleanup (&error);
8210 case CMD_ASSEMBLY_GET_DOMAIN: {
8211 buffer_add_domainid (buf, domain);
8214 case CMD_ASSEMBLY_GET_TYPE: {
8216 char *s = decode_string (p, &p, end);
8217 gboolean ignorecase = decode_byte (p, &p, end);
8218 MonoTypeNameParse info;
8220 gboolean type_resolve, res;
8221 MonoDomain *d = mono_domain_get ();
8223 /* This is needed to be able to find referenced assemblies */
8224 res = mono_domain_set (domain, FALSE);
8227 if (!mono_reflection_parse_type (s, &info)) {
8230 if (info.assembly.name)
8232 t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignorecase, &type_resolve, &error);
8233 if (!is_ok (&error)) {
8234 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8235 mono_reflection_free_type_info (&info);
8237 return ERR_INVALID_ARGUMENT;
8240 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
8241 mono_reflection_free_type_info (&info);
8244 mono_domain_set (d, TRUE);
8248 case CMD_ASSEMBLY_GET_NAME: {
8250 MonoAssembly *mass = ass;
8252 name = g_strdup_printf (
8253 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
8255 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
8256 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
8257 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
8258 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
8260 buffer_add_string (buf, name);
8265 return ERR_NOT_IMPLEMENTED;
8272 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8278 case CMD_MODULE_GET_INFO: {
8279 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
8282 basename = g_path_get_basename (image->name);
8283 buffer_add_string (buf, basename); // name
8284 buffer_add_string (buf, image->module_name); // scopename
8285 buffer_add_string (buf, image->name); // fqname
8286 buffer_add_string (buf, mono_image_get_guid (image)); // guid
8287 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
8292 return ERR_NOT_IMPLEMENTED;
8299 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8305 case CMD_FIELD_GET_INFO: {
8306 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
8308 buffer_add_string (buf, f->name);
8309 buffer_add_typeid (buf, domain, f->parent);
8310 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
8311 buffer_add_int (buf, f->type->attrs);
8315 return ERR_NOT_IMPLEMENTED;
8322 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
8324 if (val && val->vtable->klass == mono_defaults.runtimetype_class) {
8325 /* Special case these so the client doesn't have to handle Type objects */
8327 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
8328 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
8329 } else if (MONO_TYPE_IS_REFERENCE (t))
8330 buffer_add_value (buf, t, &val, domain);
8332 buffer_add_value (buf, t, mono_object_unbox (val), domain);
8336 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
8342 buffer_add_int (buf, 0);
8346 for (i = 0; i < cinfo->num_attrs; ++i) {
8347 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
8350 buffer_add_int (buf, nattrs);
8352 for (i = 0; i < cinfo->num_attrs; ++i) {
8353 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
8354 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
8355 MonoArray *typed_args, *named_args;
8357 CattrNamedArg *arginfo = NULL;
8360 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
8361 if (!mono_error_ok (&error)) {
8362 DEBUG_PRINTF (2, "[dbg] mono_reflection_create_custom_attr_data_args () failed with: '%s'\n", mono_error_get_message (&error));
8363 mono_error_cleanup (&error);
8364 return ERR_LOADER_ERROR;
8367 buffer_add_methodid (buf, domain, attr->ctor);
8371 buffer_add_int (buf, mono_array_length (typed_args));
8372 for (j = 0; j < mono_array_length (typed_args); ++j) {
8373 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
8375 t = mono_method_signature (attr->ctor)->params [j];
8377 buffer_add_cattr_arg (buf, t, domain, val);
8380 buffer_add_int (buf, 0);
8385 buffer_add_int (buf, mono_array_length (named_args));
8387 for (j = 0; j < mono_array_length (named_args); ++j) {
8388 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
8390 if (arginfo [j].prop) {
8391 buffer_add_byte (buf, 0x54);
8392 buffer_add_propertyid (buf, domain, arginfo [j].prop);
8393 } else if (arginfo [j].field) {
8394 buffer_add_byte (buf, 0x53);
8395 buffer_add_fieldid (buf, domain, arginfo [j].field);
8397 g_assert_not_reached ();
8400 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
8403 buffer_add_int (buf, 0);
8412 /* FIXME: Code duplication with icall.c */
8414 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
8419 mono_class_setup_interfaces (klass, error);
8420 if (!mono_error_ok (error))
8423 for (i = 0; i < klass->interface_count; i++) {
8424 ic = klass->interfaces [i];
8425 g_hash_table_insert (ifaces, ic, ic);
8427 collect_interfaces (ic, ifaces, error);
8428 if (!mono_error_ok (error))
8434 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8446 case CMD_TYPE_GET_INFO: {
8447 buffer_add_string (buf, klass->name_space);
8448 buffer_add_string (buf, klass->name);
8450 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
8451 buffer_add_string (buf, name);
8453 buffer_add_assemblyid (buf, domain, klass->image->assembly);
8454 buffer_add_moduleid (buf, domain, klass->image);
8455 buffer_add_typeid (buf, domain, klass->parent);
8456 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
8457 buffer_add_typeid (buf, domain, klass->element_class);
8459 buffer_add_id (buf, 0);
8460 buffer_add_int (buf, klass->type_token);
8461 buffer_add_byte (buf, klass->rank);
8462 buffer_add_int (buf, mono_class_get_flags (klass));
8464 type = &klass->byval_arg;
8465 // FIXME: Can't decide whenever a class represents a byref type
8468 if (type->type == MONO_TYPE_PTR)
8470 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
8472 if (type->type == MONO_TYPE_VALUETYPE)
8474 if (klass->enumtype)
8476 if (mono_class_is_gtd (klass))
8478 if (mono_class_is_gtd (klass) || mono_class_is_ginst (klass))
8480 buffer_add_byte (buf, b);
8483 while ((nested = mono_class_get_nested_types (klass, &iter)))
8485 buffer_add_int (buf, nnested);
8487 while ((nested = mono_class_get_nested_types (klass, &iter)))
8488 buffer_add_typeid (buf, domain, nested);
8489 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8490 if (mono_class_is_gtd (klass))
8491 buffer_add_typeid (buf, domain, klass);
8492 else if (mono_class_is_ginst (klass))
8493 buffer_add_typeid (buf, domain, mono_class_get_generic_class (klass)->container_class);
8495 buffer_add_id (buf, 0);
8497 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8500 if (mono_class_is_ginst (klass)) {
8501 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
8503 count = inst->type_argc;
8504 buffer_add_int (buf, count);
8505 for (i = 0; i < count; i++)
8506 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8507 } else if (mono_class_is_gtd (klass)) {
8508 MonoGenericContainer *container = mono_class_get_generic_container (klass);
8511 count = container->type_argc;
8512 buffer_add_int (buf, count);
8513 for (i = 0; i < count; i++) {
8514 pklass = mono_class_from_generic_parameter_internal (mono_generic_container_get_param (container, i));
8515 buffer_add_typeid (buf, domain, pklass);
8518 buffer_add_int (buf, 0);
8523 case CMD_TYPE_GET_METHODS: {
8526 gpointer iter = NULL;
8529 mono_class_setup_methods (klass);
8531 nmethods = mono_class_num_methods (klass);
8533 buffer_add_int (buf, nmethods);
8535 while ((m = mono_class_get_methods (klass, &iter))) {
8536 buffer_add_methodid (buf, domain, m);
8539 g_assert (i == nmethods);
8542 case CMD_TYPE_GET_FIELDS: {
8545 gpointer iter = NULL;
8548 nfields = mono_class_num_fields (klass);
8550 buffer_add_int (buf, nfields);
8552 while ((f = mono_class_get_fields (klass, &iter))) {
8553 buffer_add_fieldid (buf, domain, f);
8554 buffer_add_string (buf, f->name);
8555 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
8556 buffer_add_int (buf, f->type->attrs);
8559 g_assert (i == nfields);
8562 case CMD_TYPE_GET_PROPERTIES: {
8565 gpointer iter = NULL;
8568 nprops = mono_class_num_properties (klass);
8570 buffer_add_int (buf, nprops);
8572 while ((p = mono_class_get_properties (klass, &iter))) {
8573 buffer_add_propertyid (buf, domain, p);
8574 buffer_add_string (buf, p->name);
8575 buffer_add_methodid (buf, domain, p->get);
8576 buffer_add_methodid (buf, domain, p->set);
8577 buffer_add_int (buf, p->attrs);
8580 g_assert (i == nprops);
8583 case CMD_TYPE_GET_CATTRS: {
8584 MonoClass *attr_klass;
8585 MonoCustomAttrInfo *cinfo;
8587 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8588 /* attr_klass can be NULL */
8589 if (err != ERR_NONE)
8592 cinfo = mono_custom_attrs_from_class_checked (klass, &error);
8593 if (!is_ok (&error)) {
8594 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8595 return ERR_LOADER_ERROR;
8598 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8599 if (err != ERR_NONE)
8603 case CMD_TYPE_GET_FIELD_CATTRS: {
8604 MonoClass *attr_klass;
8605 MonoCustomAttrInfo *cinfo;
8606 MonoClassField *field;
8608 field = decode_fieldid (p, &p, end, NULL, &err);
8609 if (err != ERR_NONE)
8611 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8612 if (err != ERR_NONE)
8615 cinfo = mono_custom_attrs_from_field_checked (klass, field, &error);
8616 if (!is_ok (&error)) {
8617 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8618 return ERR_LOADER_ERROR;
8621 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8622 if (err != ERR_NONE)
8626 case CMD_TYPE_GET_PROPERTY_CATTRS: {
8627 MonoClass *attr_klass;
8628 MonoCustomAttrInfo *cinfo;
8631 prop = decode_propertyid (p, &p, end, NULL, &err);
8632 if (err != ERR_NONE)
8634 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8635 if (err != ERR_NONE)
8638 cinfo = mono_custom_attrs_from_property_checked (klass, prop, &error);
8639 if (!is_ok (&error)) {
8640 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8641 return ERR_LOADER_ERROR;
8644 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8645 if (err != ERR_NONE)
8649 case CMD_TYPE_GET_VALUES:
8650 case CMD_TYPE_GET_VALUES_2: {
8657 MonoThread *thread_obj;
8658 MonoInternalThread *thread = NULL;
8659 guint32 special_static_type;
8661 if (command == CMD_TYPE_GET_VALUES_2) {
8662 int objid = decode_objid (p, &p, end);
8665 err = get_object (objid, (MonoObject**)&thread_obj);
8666 if (err != ERR_NONE)
8669 thread = THREAD_TO_INTERNAL (thread_obj);
8672 len = decode_int (p, &p, end);
8673 for (i = 0; i < len; ++i) {
8674 f = decode_fieldid (p, &p, end, NULL, &err);
8675 if (err != ERR_NONE)
8678 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8679 return ERR_INVALID_FIELDID;
8680 special_static_type = mono_class_field_get_special_static_type (f);
8681 if (special_static_type != SPECIAL_STATIC_NONE) {
8682 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
8683 return ERR_INVALID_FIELDID;
8686 /* Check that the field belongs to the object */
8688 for (k = klass; k; k = k->parent) {
8689 if (k == f->parent) {
8695 return ERR_INVALID_FIELDID;
8697 vtable = mono_class_vtable (domain, f->parent);
8698 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8699 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val, &error);
8700 if (!is_ok (&error))
8701 return ERR_INVALID_FIELDID;
8702 buffer_add_value (buf, f->type, val, domain);
8707 case CMD_TYPE_SET_VALUES: {
8715 len = decode_int (p, &p, end);
8716 for (i = 0; i < len; ++i) {
8717 f = decode_fieldid (p, &p, end, NULL, &err);
8718 if (err != ERR_NONE)
8721 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8722 return ERR_INVALID_FIELDID;
8723 if (mono_class_field_is_special_static (f))
8724 return ERR_INVALID_FIELDID;
8726 /* Check that the field belongs to the object */
8728 for (k = klass; k; k = k->parent) {
8729 if (k == f->parent) {
8735 return ERR_INVALID_FIELDID;
8737 // FIXME: Check for literal/const
8739 vtable = mono_class_vtable (domain, f->parent);
8740 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8741 err = decode_value (f->type, domain, val, p, &p, end);
8742 if (err != ERR_NONE) {
8746 if (MONO_TYPE_IS_REFERENCE (f->type))
8747 mono_field_static_set_value (vtable, f, *(gpointer*)val);
8749 mono_field_static_set_value (vtable, f, val);
8754 case CMD_TYPE_GET_OBJECT: {
8755 MonoObject *o = (MonoObject*)mono_type_get_object_checked (domain, &klass->byval_arg, &error);
8756 if (!mono_error_ok (&error)) {
8757 mono_error_cleanup (&error);
8758 return ERR_INVALID_OBJECT;
8760 buffer_add_objid (buf, o);
8763 case CMD_TYPE_GET_SOURCE_FILES:
8764 case CMD_TYPE_GET_SOURCE_FILES_2: {
8765 char *source_file, *base;
8769 files = get_source_files_for_type (klass);
8771 buffer_add_int (buf, files->len);
8772 for (i = 0; i < files->len; ++i) {
8773 source_file = (char *)g_ptr_array_index (files, i);
8774 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8775 buffer_add_string (buf, source_file);
8777 base = dbg_path_get_basename (source_file);
8778 buffer_add_string (buf, base);
8781 g_free (source_file);
8783 g_ptr_array_free (files, TRUE);
8786 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8787 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8789 if (err != ERR_NONE)
8791 if (mono_class_is_assignable_from (klass, oklass))
8792 buffer_add_byte (buf, 1);
8794 buffer_add_byte (buf, 0);
8797 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8798 char *name = decode_string (p, &p, end);
8799 int i, flags = decode_int (p, &p, end);
8803 error_init (&error);
8804 array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &error);
8805 if (!is_ok (&error)) {
8806 mono_error_cleanup (&error);
8807 return ERR_LOADER_ERROR;
8809 buffer_add_int (buf, array->len);
8810 for (i = 0; i < array->len; ++i) {
8811 MonoMethod *method = (MonoMethod *)g_ptr_array_index (array, i);
8812 buffer_add_methodid (buf, domain, method);
8815 g_ptr_array_free (array, TRUE);
8819 case CMD_TYPE_GET_INTERFACES: {
8821 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8822 MonoClass *tclass, *iface;
8823 GHashTableIter iter;
8827 for (parent = tclass; parent; parent = parent->parent) {
8828 mono_class_setup_interfaces (parent, &error);
8829 if (!mono_error_ok (&error))
8830 return ERR_LOADER_ERROR;
8831 collect_interfaces (parent, iface_hash, &error);
8832 if (!mono_error_ok (&error))
8833 return ERR_LOADER_ERROR;
8836 buffer_add_int (buf, g_hash_table_size (iface_hash));
8838 g_hash_table_iter_init (&iter, iface_hash);
8839 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8840 buffer_add_typeid (buf, domain, iface);
8841 g_hash_table_destroy (iface_hash);
8844 case CMD_TYPE_GET_INTERFACE_MAP: {
8845 int tindex, ioffset;
8846 gboolean variance_used;
8848 int len, nmethods, i;
8852 len = decode_int (p, &p, end);
8853 mono_class_setup_vtable (klass);
8855 for (tindex = 0; tindex < len; ++tindex) {
8856 iclass = decode_typeid (p, &p, end, NULL, &err);
8857 if (err != ERR_NONE)
8860 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8862 return ERR_INVALID_ARGUMENT;
8864 nmethods = mono_class_num_methods (iclass);
8865 buffer_add_int (buf, nmethods);
8868 while ((method = mono_class_get_methods (iclass, &iter))) {
8869 buffer_add_methodid (buf, domain, method);
8871 for (i = 0; i < nmethods; ++i)
8872 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
8876 case CMD_TYPE_IS_INITIALIZED: {
8877 MonoVTable *vtable = mono_class_vtable (domain, klass);
8880 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8882 buffer_add_int (buf, 0);
8885 case CMD_TYPE_CREATE_INSTANCE: {
8889 obj = mono_object_new_checked (domain, klass, &error);
8890 mono_error_assert_ok (&error);
8891 buffer_add_objid (buf, obj);
8895 return ERR_NOT_IMPLEMENTED;
8902 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8905 MonoDomain *old_domain;
8909 klass = decode_typeid (p, &p, end, &domain, &err);
8910 if (err != ERR_NONE)
8913 old_domain = mono_domain_get ();
8915 mono_domain_set (domain, TRUE);
8917 err = type_commands_internal (command, klass, domain, p, end, buf);
8919 mono_domain_set (old_domain, TRUE);
8925 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8927 MonoMethodHeader *header;
8931 case CMD_METHOD_GET_NAME: {
8932 buffer_add_string (buf, method->name);
8935 case CMD_METHOD_GET_DECLARING_TYPE: {
8936 buffer_add_typeid (buf, domain, method->klass);
8939 case CMD_METHOD_GET_DEBUG_INFO: {
8941 MonoDebugMethodInfo *minfo;
8943 int i, j, n_il_offsets;
8945 GPtrArray *source_file_list;
8946 MonoSymSeqPoint *sym_seq_points;
8948 header = mono_method_get_header_checked (method, &error);
8950 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8951 buffer_add_int (buf, 0);
8952 buffer_add_string (buf, "");
8953 buffer_add_int (buf, 0);
8957 minfo = mono_debug_lookup_method (method);
8959 buffer_add_int (buf, header->code_size);
8960 buffer_add_string (buf, "");
8961 buffer_add_int (buf, 0);
8962 mono_metadata_free_mh (header);
8966 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, &source_files, &sym_seq_points, &n_il_offsets);
8967 buffer_add_int (buf, header->code_size);
8968 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8969 buffer_add_int (buf, source_file_list->len);
8970 for (i = 0; i < source_file_list->len; ++i) {
8971 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
8972 buffer_add_string (buf, sinfo->source_file);
8973 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8974 for (j = 0; j < 16; ++j)
8975 buffer_add_byte (buf, sinfo->hash [j]);
8979 buffer_add_string (buf, source_file);
8981 buffer_add_int (buf, n_il_offsets);
8982 DEBUG_PRINTF (10, "Line number table for method %s:\n", mono_method_full_name (method, TRUE));
8983 for (i = 0; i < n_il_offsets; ++i) {
8984 MonoSymSeqPoint *sp = &sym_seq_points [i];
8985 const char *srcfile = "";
8987 if (source_files [i] != -1) {
8988 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, source_files [i]);
8989 srcfile = sinfo->source_file;
8991 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);
8992 buffer_add_int (buf, sp->il_offset);
8993 buffer_add_int (buf, sp->line);
8994 if (CHECK_PROTOCOL_VERSION (2, 13))
8995 buffer_add_int (buf, source_files [i]);
8996 if (CHECK_PROTOCOL_VERSION (2, 19))
8997 buffer_add_int (buf, sp->column);
8998 if (CHECK_PROTOCOL_VERSION (2, 32)) {
8999 buffer_add_int (buf, sp->end_line);
9000 buffer_add_int (buf, sp->end_column);
9003 g_free (source_file);
9004 g_free (source_files);
9005 g_free (sym_seq_points);
9006 g_ptr_array_free (source_file_list, TRUE);
9007 mono_metadata_free_mh (header);
9010 case CMD_METHOD_GET_PARAM_INFO: {
9011 MonoMethodSignature *sig = mono_method_signature (method);
9015 /* FIXME: mono_class_from_mono_type () and byrefs */
9017 /* FIXME: Use a smaller encoding */
9018 buffer_add_int (buf, sig->call_convention);
9019 buffer_add_int (buf, sig->param_count);
9020 buffer_add_int (buf, sig->generic_param_count);
9021 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
9022 for (i = 0; i < sig->param_count; ++i) {
9024 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
9027 /* Emit parameter names */
9028 names = g_new (char *, sig->param_count);
9029 mono_method_get_param_names (method, (const char **) names);
9030 for (i = 0; i < sig->param_count; ++i)
9031 buffer_add_string (buf, names [i]);
9036 case CMD_METHOD_GET_LOCALS_INFO: {
9039 MonoDebugLocalsInfo *locals;
9040 int *locals_map = NULL;
9042 header = mono_method_get_header_checked (method, &error);
9044 mono_error_cleanup (&error); /* FIXME don't swallow the error */
9045 return ERR_INVALID_ARGUMENT;
9048 locals = mono_debug_lookup_locals (method);
9050 if (CHECK_PROTOCOL_VERSION (2, 43)) {
9052 buffer_add_int (buf, 1);
9053 buffer_add_int (buf, 0);
9054 buffer_add_int (buf, header->code_size);
9056 buffer_add_int (buf, header->num_locals);
9058 for (i = 0; i < header->num_locals; ++i) {
9059 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
9062 for (i = 0; i < header->num_locals; ++i) {
9064 sprintf (lname, "V_%d", i);
9065 buffer_add_string (buf, lname);
9068 for (i = 0; i < header->num_locals; ++i) {
9069 buffer_add_int (buf, 0);
9070 buffer_add_int (buf, header->code_size);
9073 if (CHECK_PROTOCOL_VERSION (2, 43)) {
9075 buffer_add_int (buf, locals->num_blocks);
9077 for (i = 0; i < locals->num_blocks; ++i) {
9078 buffer_add_int (buf, locals->code_blocks [i].start_offset - last_start);
9079 buffer_add_int (buf, locals->code_blocks [i].end_offset - locals->code_blocks [i].start_offset);
9080 last_start = locals->code_blocks [i].start_offset;
9084 num_locals = locals->num_locals;
9085 buffer_add_int (buf, num_locals);
9088 for (i = 0; i < num_locals; ++i) {
9089 g_assert (locals->locals [i].index < header->num_locals);
9090 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [locals->locals [i].index]));
9093 for (i = 0; i < num_locals; ++i)
9094 buffer_add_string (buf, locals->locals [i].name);
9096 for (i = 0; i < num_locals; ++i) {
9097 if (locals->locals [i].block) {
9098 buffer_add_int (buf, locals->locals [i].block->start_offset);
9099 buffer_add_int (buf, locals->locals [i].block->end_offset);
9101 buffer_add_int (buf, 0);
9102 buffer_add_int (buf, header->code_size);
9106 mono_metadata_free_mh (header);
9109 mono_debug_free_locals (locals);
9110 g_free (locals_map);
9114 case CMD_METHOD_GET_INFO:
9115 buffer_add_int (buf, method->flags);
9116 buffer_add_int (buf, method->iflags);
9117 buffer_add_int (buf, method->token);
9118 if (CHECK_PROTOCOL_VERSION (2, 12)) {
9120 if (method->is_generic)
9122 if (mono_method_signature (method)->generic_param_count)
9124 buffer_add_byte (buf, attrs);
9125 if (method->is_generic || method->is_inflated) {
9128 if (method->is_generic) {
9131 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
9133 result = imethod->declaring;
9134 if (imethod->context.class_inst) {
9135 MonoClass *klass = ((MonoMethod *) imethod)->klass;
9136 /*Generic methods gets the context of the GTD.*/
9137 if (mono_class_get_context (klass)) {
9139 result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), &error);
9140 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9145 buffer_add_methodid (buf, domain, result);
9147 buffer_add_id (buf, 0);
9149 if (CHECK_PROTOCOL_VERSION (2, 15)) {
9150 if (mono_method_signature (method)->generic_param_count) {
9153 if (method->is_inflated) {
9154 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
9156 count = inst->type_argc;
9157 buffer_add_int (buf, count);
9159 for (i = 0; i < count; i++)
9160 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
9162 buffer_add_int (buf, 0);
9164 } else if (method->is_generic) {
9165 MonoGenericContainer *container = mono_method_get_generic_container (method);
9167 count = mono_method_signature (method)->generic_param_count;
9168 buffer_add_int (buf, count);
9169 for (i = 0; i < count; i++) {
9170 MonoGenericParam *param = mono_generic_container_get_param (container, i);
9171 MonoClass *pklass = mono_class_from_generic_parameter_internal (param);
9172 buffer_add_typeid (buf, domain, pklass);
9175 buffer_add_int (buf, 0);
9178 buffer_add_int (buf, 0);
9183 case CMD_METHOD_GET_BODY: {
9187 header = mono_method_get_header_checked (method, &error);
9189 mono_error_cleanup (&error); /* FIXME don't swallow the error */
9190 buffer_add_int (buf, 0);
9192 if (CHECK_PROTOCOL_VERSION (2, 18))
9193 buffer_add_int (buf, 0);
9195 buffer_add_int (buf, header->code_size);
9196 for (i = 0; i < header->code_size; ++i)
9197 buffer_add_byte (buf, header->code [i]);
9199 if (CHECK_PROTOCOL_VERSION (2, 18)) {
9200 buffer_add_int (buf, header->num_clauses);
9201 for (i = 0; i < header->num_clauses; ++i) {
9202 MonoExceptionClause *clause = &header->clauses [i];
9204 buffer_add_int (buf, clause->flags);
9205 buffer_add_int (buf, clause->try_offset);
9206 buffer_add_int (buf, clause->try_len);
9207 buffer_add_int (buf, clause->handler_offset);
9208 buffer_add_int (buf, clause->handler_len);
9209 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
9210 buffer_add_typeid (buf, domain, clause->data.catch_class);
9211 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
9212 buffer_add_int (buf, clause->data.filter_offset);
9216 mono_metadata_free_mh (header);
9221 case CMD_METHOD_RESOLVE_TOKEN: {
9222 guint32 token = decode_int (p, &p, end);
9225 switch (mono_metadata_token_code (token)) {
9226 case MONO_TOKEN_STRING: {
9231 s = mono_ldstr_checked (domain, method->klass->image, mono_metadata_token_index (token), &error);
9232 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
9234 s2 = mono_string_to_utf8_checked (s, &error);
9235 mono_error_assert_ok (&error);
9237 buffer_add_byte (buf, TOKEN_TYPE_STRING);
9238 buffer_add_string (buf, s2);
9245 MonoClass *handle_class;
9247 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
9248 val = mono_method_get_wrapper_data (method, token);
9249 handle_class = (MonoClass *)mono_method_get_wrapper_data (method, token + 1);
9251 if (handle_class == NULL) {
9252 // Can't figure out the token type
9253 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
9257 val = mono_ldtoken_checked (method->klass->image, token, &handle_class, NULL, &error);
9259 g_error ("Could not load token due to %s", mono_error_get_message (&error));
9262 if (handle_class == mono_defaults.typehandle_class) {
9263 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
9264 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
9265 buffer_add_typeid (buf, domain, (MonoClass *) val);
9267 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
9268 } else if (handle_class == mono_defaults.fieldhandle_class) {
9269 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
9270 buffer_add_fieldid (buf, domain, (MonoClassField *)val);
9271 } else if (handle_class == mono_defaults.methodhandle_class) {
9272 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
9273 buffer_add_methodid (buf, domain, (MonoMethod *)val);
9274 } else if (handle_class == mono_defaults.string_class) {
9277 s = mono_string_to_utf8_checked ((MonoString *)val, &error);
9278 mono_error_assert_ok (&error);
9279 buffer_add_byte (buf, TOKEN_TYPE_STRING);
9280 buffer_add_string (buf, s);
9283 g_assert_not_reached ();
9290 case CMD_METHOD_GET_CATTRS: {
9292 MonoClass *attr_klass;
9293 MonoCustomAttrInfo *cinfo;
9295 attr_klass = decode_typeid (p, &p, end, NULL, &err);
9296 /* attr_klass can be NULL */
9297 if (err != ERR_NONE)
9300 cinfo = mono_custom_attrs_from_method_checked (method, &error);
9301 if (!is_ok (&error)) {
9302 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
9303 return ERR_LOADER_ERROR;
9306 err = buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
9307 if (err != ERR_NONE)
9311 case CMD_METHOD_MAKE_GENERIC_METHOD: {
9313 MonoType **type_argv;
9317 MonoGenericInst *ginst;
9318 MonoGenericContext tmp_context;
9319 MonoMethod *inflated;
9321 type_argc = decode_int (p, &p, end);
9322 type_argv = g_new0 (MonoType*, type_argc);
9323 for (i = 0; i < type_argc; ++i) {
9324 klass = decode_typeid (p, &p, end, &d, &err);
9325 if (err != ERR_NONE) {
9331 return ERR_INVALID_ARGUMENT;
9333 type_argv [i] = &klass->byval_arg;
9335 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
9337 tmp_context.class_inst = mono_class_is_ginst (method->klass) ? mono_class_get_generic_class (method->klass)->context.class_inst : NULL;
9338 tmp_context.method_inst = ginst;
9340 inflated = mono_class_inflate_generic_method_checked (method, &tmp_context, &error);
9341 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9342 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
9343 return ERR_INVALID_ARGUMENT;
9344 buffer_add_methodid (buf, domain, inflated);
9348 return ERR_NOT_IMPLEMENTED;
9355 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9358 MonoDomain *old_domain;
9362 method = decode_methodid (p, &p, end, &domain, &err);
9363 if (err != ERR_NONE)
9366 old_domain = mono_domain_get ();
9368 mono_domain_set (domain, TRUE);
9370 err = method_commands_internal (command, method, domain, p, end, buf);
9372 mono_domain_set (old_domain, TRUE);
9378 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9380 int objid = decode_objid (p, &p, end);
9382 MonoThread *thread_obj;
9383 MonoInternalThread *thread;
9385 err = get_object (objid, (MonoObject**)&thread_obj);
9386 if (err != ERR_NONE)
9389 thread = THREAD_TO_INTERNAL (thread_obj);
9392 case CMD_THREAD_GET_NAME: {
9394 gunichar2 *s = mono_thread_get_name (thread, &name_len);
9397 buffer_add_int (buf, 0);
9402 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
9404 buffer_add_int (buf, len);
9405 buffer_add_data (buf, (guint8*)name, len);
9410 case CMD_THREAD_GET_FRAME_INFO: {
9411 DebuggerTlsData *tls;
9412 int i, start_frame, length;
9414 // Wait for suspending if it already started
9415 // FIXME: Races with suspend_count
9416 while (!is_suspended ()) {
9418 wait_for_suspend ();
9422 wait_for_suspend ();
9423 if (!is_suspended ())
9424 return ERR_NOT_SUSPENDED;
9427 start_frame = decode_int (p, &p, end);
9428 length = decode_int (p, &p, end);
9430 if (start_frame != 0 || length != -1)
9431 return ERR_NOT_IMPLEMENTED;
9433 mono_loader_lock ();
9434 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9435 mono_loader_unlock ();
9438 compute_frame_info (thread, tls);
9440 buffer_add_int (buf, tls->frame_count);
9441 for (i = 0; i < tls->frame_count; ++i) {
9442 buffer_add_int (buf, tls->frames [i]->id);
9443 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
9444 buffer_add_int (buf, tls->frames [i]->il_offset);
9446 * Instead of passing the frame type directly to the client, we associate
9447 * it with the previous frame using a set of flags. This avoids lots of
9448 * conditional code in the client, since a frame whose type isn't
9449 * FRAME_TYPE_MANAGED has no method, location, etc.
9451 buffer_add_byte (buf, tls->frames [i]->flags);
9456 case CMD_THREAD_GET_STATE:
9457 buffer_add_int (buf, thread->state);
9459 case CMD_THREAD_GET_INFO:
9460 buffer_add_byte (buf, thread->threadpool_thread);
9462 case CMD_THREAD_GET_ID:
9463 buffer_add_long (buf, (guint64)(gsize)thread);
9465 case CMD_THREAD_GET_TID:
9466 buffer_add_long (buf, (guint64)thread->tid);
9468 case CMD_THREAD_SET_IP: {
9469 DebuggerTlsData *tls;
9472 MonoSeqPointInfo *seq_points;
9477 method = decode_methodid (p, &p, end, &domain, &err);
9478 if (err != ERR_NONE)
9480 il_offset = decode_long (p, &p, end);
9482 while (!is_suspended ()) {
9484 wait_for_suspend ();
9487 mono_loader_lock ();
9488 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9489 mono_loader_unlock ();
9492 compute_frame_info (thread, tls);
9493 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
9494 return ERR_INVALID_ARGUMENT;
9496 found_sp = mono_find_seq_point (domain, method, il_offset, &seq_points, &sp);
9498 g_assert (seq_points);
9501 return ERR_INVALID_ARGUMENT;
9503 // FIXME: Check that the ip change is safe
9505 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);
9507 if (tls->frames [0]->ji->is_interp) {
9508 MonoJitTlsData *jit_data = ((MonoThreadInfo*)thread->thread_info)->jit_data;
9509 mono_interp_set_resume_state (jit_data, NULL, tls->frames [0]->interp_frame, (guint8*)tls->frames [0]->ji->code_start + sp.native_offset);
9511 MONO_CONTEXT_SET_IP (&tls->restore_state.ctx, (guint8*)tls->frames [0]->ji->code_start + sp.native_offset);
9516 return ERR_NOT_IMPLEMENTED;
9523 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9527 MonoThread *thread_obj;
9528 MonoInternalThread *thread;
9529 int pos, i, len, frame_idx;
9530 DebuggerTlsData *tls;
9532 MonoDebugMethodJitInfo *jit;
9533 MonoMethodSignature *sig;
9535 MonoMethodHeader *header;
9537 objid = decode_objid (p, &p, end);
9538 err = get_object (objid, (MonoObject**)&thread_obj);
9539 if (err != ERR_NONE)
9542 thread = THREAD_TO_INTERNAL (thread_obj);
9544 id = decode_id (p, &p, end);
9546 mono_loader_lock ();
9547 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9548 mono_loader_unlock ();
9551 for (i = 0; i < tls->frame_count; ++i) {
9552 if (tls->frames [i]->id == id)
9555 if (i == tls->frame_count)
9556 return ERR_INVALID_FRAMEID;
9559 frame = tls->frames [frame_idx];
9561 /* This is supported for frames without has_ctx etc. set */
9562 if (command == CMD_STACK_FRAME_GET_DOMAIN) {
9563 if (CHECK_PROTOCOL_VERSION (2, 38))
9564 buffer_add_domainid (buf, frame->domain);
9568 if (!frame->has_ctx)
9569 return ERR_ABSENT_INFORMATION;
9571 if (!ensure_jit (frame))
9572 return ERR_ABSENT_INFORMATION;
9576 sig = mono_method_signature (frame->actual_method);
9578 if (!(jit->has_var_info || frame->ji->is_interp) || !mono_get_seq_points (frame->domain, frame->actual_method))
9580 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
9582 return ERR_ABSENT_INFORMATION;
9585 case CMD_STACK_FRAME_GET_VALUES: {
9587 len = decode_int (p, &p, end);
9588 header = mono_method_get_header_checked (frame->actual_method, &error);
9589 mono_error_assert_ok (&error); /* FIXME report error */
9591 for (i = 0; i < len; ++i) {
9592 pos = decode_int (p, &p, end);
9597 DEBUG_PRINTF (4, "[dbg] send arg %d.\n", pos);
9599 if (frame->ji->is_interp) {
9602 addr = mono_interp_frame_get_arg (frame->interp_frame, pos);
9604 buffer_add_value_full (buf, sig->params [pos], addr, frame->domain, FALSE, NULL);
9606 g_assert (pos >= 0 && pos < jit->num_params);
9608 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
9611 MonoDebugLocalsInfo *locals;
9613 locals = mono_debug_lookup_locals (frame->method);
9615 g_assert (pos < locals->num_locals);
9616 pos = locals->locals [pos].index;
9617 mono_debug_free_locals (locals);
9620 DEBUG_PRINTF (4, "[dbg] send local %d.\n", pos);
9622 if (frame->ji->is_interp) {
9625 addr = mono_interp_frame_get_local (frame->interp_frame, pos);
9627 buffer_add_value_full (buf, header->locals [pos], addr, frame->domain, FALSE, NULL);
9629 g_assert (pos >= 0 && pos < jit->num_locals);
9631 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
9635 mono_metadata_free_mh (header);
9638 case CMD_STACK_FRAME_GET_THIS: {
9639 if (frame->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE)
9640 return ERR_ABSENT_INFORMATION;
9641 if (frame->api_method->klass->valuetype) {
9642 if (!sig->hasthis) {
9643 MonoObject *p = NULL;
9644 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
9646 if (frame->ji->is_interp) {
9649 addr = mono_interp_frame_get_this (frame->interp_frame);
9651 buffer_add_value_full (buf, &frame->actual_method->klass->this_arg, addr, frame->domain, FALSE, NULL);
9653 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9657 if (!sig->hasthis) {
9658 MonoObject *p = NULL;
9659 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
9661 if (frame->ji->is_interp) {
9664 addr = mono_interp_frame_get_this (frame->interp_frame);
9666 buffer_add_value_full (buf, &frame->api_method->klass->byval_arg, addr, frame->domain, FALSE, NULL);
9668 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9674 case CMD_STACK_FRAME_SET_VALUES: {
9678 MonoDebugVarInfo *var = NULL;
9679 gboolean is_arg = FALSE;
9681 len = decode_int (p, &p, end);
9682 header = mono_method_get_header_checked (frame->actual_method, &error);
9683 mono_error_assert_ok (&error); /* FIXME report error */
9685 for (i = 0; i < len; ++i) {
9686 pos = decode_int (p, &p, end);
9691 g_assert (pos >= 0 && pos < jit->num_params);
9693 t = sig->params [pos];
9694 var = &jit->params [pos];
9697 MonoDebugLocalsInfo *locals;
9699 locals = mono_debug_lookup_locals (frame->method);
9701 g_assert (pos < locals->num_locals);
9702 pos = locals->locals [pos].index;
9703 mono_debug_free_locals (locals);
9705 g_assert (pos >= 0 && pos < jit->num_locals);
9707 t = header->locals [pos];
9708 var = &jit->locals [pos];
9711 if (MONO_TYPE_IS_REFERENCE (t))
9712 val_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
9714 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9715 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9716 if (err != ERR_NONE)
9719 if (frame->ji->is_interp) {
9723 addr = mono_interp_frame_get_arg (frame->interp_frame, pos);
9725 addr = mono_interp_frame_get_local (frame->interp_frame, pos);
9726 set_interp_var (t, addr, val_buf);
9728 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9731 mono_metadata_free_mh (header);
9734 case CMD_STACK_FRAME_GET_DOMAIN: {
9735 if (CHECK_PROTOCOL_VERSION (2, 38))
9736 buffer_add_domainid (buf, frame->domain);
9739 case CMD_STACK_FRAME_SET_THIS: {
9742 MonoDebugVarInfo *var;
9744 t = &frame->actual_method->klass->byval_arg;
9745 /* Checked by the sender */
9746 g_assert (MONO_TYPE_ISSTRUCT (t));
9748 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9749 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9750 if (err != ERR_NONE)
9753 if (frame->ji->is_interp) {
9756 addr = mono_interp_frame_get_this (frame->interp_frame);
9757 set_interp_var (&frame->actual_method->klass->this_arg, addr, val_buf);
9759 var = jit->this_var;
9762 set_var (&frame->actual_method->klass->this_arg, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9767 return ERR_NOT_IMPLEMENTED;
9774 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9777 int objid, index, len, i, esize;
9781 objid = decode_objid (p, &p, end);
9782 err = get_object (objid, (MonoObject**)&arr);
9783 if (err != ERR_NONE)
9787 case CMD_ARRAY_REF_GET_LENGTH:
9788 buffer_add_int (buf, arr->obj.vtable->klass->rank);
9790 buffer_add_int (buf, arr->max_length);
9791 buffer_add_int (buf, 0);
9793 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
9794 buffer_add_int (buf, arr->bounds [i].length);
9795 buffer_add_int (buf, arr->bounds [i].lower_bound);
9799 case CMD_ARRAY_REF_GET_VALUES:
9800 index = decode_int (p, &p, end);
9801 len = decode_int (p, &p, end);
9803 g_assert (index >= 0 && len >= 0);
9804 // Reordered to avoid integer overflow
9805 g_assert (!(index > arr->max_length - len));
9807 esize = mono_array_element_size (arr->obj.vtable->klass);
9808 for (i = index; i < index + len; ++i) {
9809 elem = (gpointer*)((char*)arr->vector + (i * esize));
9810 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
9813 case CMD_ARRAY_REF_SET_VALUES:
9814 index = decode_int (p, &p, end);
9815 len = decode_int (p, &p, end);
9817 g_assert (index >= 0 && len >= 0);
9818 // Reordered to avoid integer overflow
9819 g_assert (!(index > arr->max_length - len));
9821 esize = mono_array_element_size (arr->obj.vtable->klass);
9822 for (i = index; i < index + len; ++i) {
9823 elem = (gpointer*)((char*)arr->vector + (i * esize));
9825 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, (guint8 *)elem, p, &p, end);
9829 return ERR_NOT_IMPLEMENTED;
9836 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9842 int i, index, length;
9844 gboolean use_utf16 = FALSE;
9846 objid = decode_objid (p, &p, end);
9847 err = get_object (objid, (MonoObject**)&str);
9848 if (err != ERR_NONE)
9852 case CMD_STRING_REF_GET_VALUE:
9853 if (CHECK_PROTOCOL_VERSION (2, 41)) {
9854 for (i = 0; i < mono_string_length (str); ++i)
9855 if (mono_string_chars (str)[i] == 0)
9857 buffer_add_byte (buf, use_utf16 ? 1 : 0);
9860 buffer_add_int (buf, mono_string_length (str) * 2);
9861 buffer_add_data (buf, (guint8*)mono_string_chars (str), mono_string_length (str) * 2);
9864 s = mono_string_to_utf8_checked (str, &error);
9865 mono_error_assert_ok (&error);
9866 buffer_add_string (buf, s);
9870 case CMD_STRING_REF_GET_LENGTH:
9871 buffer_add_long (buf, mono_string_length (str));
9873 case CMD_STRING_REF_GET_CHARS:
9874 index = decode_long (p, &p, end);
9875 length = decode_long (p, &p, end);
9876 if (index > mono_string_length (str) - length)
9877 return ERR_INVALID_ARGUMENT;
9878 c = mono_string_chars (str) + index;
9879 for (i = 0; i < length; ++i)
9880 buffer_add_short (buf, c [i]);
9883 return ERR_NOT_IMPLEMENTED;
9890 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9901 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9902 objid = decode_objid (p, &p, end);
9903 err = get_object (objid, &obj);
9904 if (err != ERR_NONE)
9905 buffer_add_int (buf, 1);
9907 buffer_add_int (buf, 0);
9911 objid = decode_objid (p, &p, end);
9912 err = get_object (objid, &obj);
9913 if (err != ERR_NONE)
9916 MonoClass *obj_type;
9917 gboolean remote_obj = FALSE;
9919 obj_type = obj->vtable->klass;
9920 if (mono_class_is_transparent_proxy (obj_type)) {
9921 obj_type = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
9925 g_assert (obj_type);
9928 case CMD_OBJECT_REF_GET_TYPE:
9929 /* This handles transparent proxies too */
9930 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9932 case CMD_OBJECT_REF_GET_VALUES:
9933 len = decode_int (p, &p, end);
9935 for (i = 0; i < len; ++i) {
9936 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9937 if (err != ERR_NONE)
9940 /* Check that the field belongs to the object */
9942 for (k = obj_type; k; k = k->parent) {
9943 if (k == f->parent) {
9949 return ERR_INVALID_FIELDID;
9951 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9955 if (mono_class_field_is_special_static (f))
9956 return ERR_INVALID_FIELDID;
9958 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9959 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9960 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9961 mono_field_static_get_value_checked (vtable, f, val, &error);
9962 if (!is_ok (&error)) {
9963 mono_error_cleanup (&error); /* FIXME report the error */
9964 return ERR_INVALID_OBJECT;
9966 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9969 guint8 *field_value = NULL;
9972 #ifndef DISABLE_REMOTING
9973 void *field_storage = NULL;
9974 field_value = mono_load_remote_field_checked(obj, obj_type, f, &field_storage, &error);
9975 if (!is_ok (&error)) {
9976 mono_error_cleanup (&error); /* FIXME report the error */
9977 return ERR_INVALID_OBJECT;
9980 g_assert_not_reached ();
9983 field_value = (guint8*)obj + f->offset;
9985 buffer_add_value (buf, f->type, field_value, obj->vtable->domain);
9989 case CMD_OBJECT_REF_SET_VALUES:
9990 len = decode_int (p, &p, end);
9992 for (i = 0; i < len; ++i) {
9993 f = decode_fieldid (p, &p, end, NULL, &err);
9994 if (err != ERR_NONE)
9997 /* Check that the field belongs to the object */
9999 for (k = obj_type; k; k = k->parent) {
10000 if (k == f->parent) {
10006 return ERR_INVALID_FIELDID;
10008 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
10010 MonoVTable *vtable;
10012 if (mono_class_field_is_special_static (f))
10013 return ERR_INVALID_FIELDID;
10015 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
10016 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
10018 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
10019 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
10020 if (err != ERR_NONE) {
10024 mono_field_static_set_value (vtable, f, val);
10027 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
10028 if (err != ERR_NONE)
10033 case CMD_OBJECT_REF_GET_ADDRESS:
10034 buffer_add_long (buf, (gssize)obj);
10036 case CMD_OBJECT_REF_GET_DOMAIN:
10037 buffer_add_domainid (buf, obj->vtable->domain);
10039 case CMD_OBJECT_REF_GET_INFO:
10040 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
10041 buffer_add_domainid (buf, obj->vtable->domain);
10044 return ERR_NOT_IMPLEMENTED;
10051 command_set_to_string (CommandSet command_set)
10053 switch (command_set) {
10056 case CMD_SET_OBJECT_REF:
10057 return "OBJECT_REF";
10058 case CMD_SET_STRING_REF:
10059 return "STRING_REF";
10060 case CMD_SET_THREAD:
10062 case CMD_SET_ARRAY_REF:
10063 return "ARRAY_REF";
10064 case CMD_SET_EVENT_REQUEST:
10065 return "EVENT_REQUEST";
10066 case CMD_SET_STACK_FRAME:
10067 return "STACK_FRAME";
10068 case CMD_SET_APPDOMAIN:
10069 return "APPDOMAIN";
10070 case CMD_SET_ASSEMBLY:
10072 case CMD_SET_METHOD:
10076 case CMD_SET_MODULE:
10078 case CMD_SET_FIELD:
10080 case CMD_SET_EVENT:
10087 static const char* vm_cmds_str [] = {
10095 "SET_PROTOCOL_VERSION",
10098 "GET_TYPES_FOR_SOURCE_FILE",
10103 static const char* thread_cmds_str[] = {
10113 static const char* event_cmds_str[] = {
10116 "REQUEST_CLEAR_ALL_BREAKPOINTS"
10119 static const char* appdomain_cmds_str[] = {
10121 "GET_FRIENDLY_NAME",
10123 "GET_ENTRY_ASSEMBLY",
10126 "CREATE_BOXED_VALUE"
10129 static const char* assembly_cmds_str[] = {
10132 "GET_MANIFEST_MODULE",
10139 static const char* module_cmds_str[] = {
10143 static const char* field_cmds_str[] = {
10147 static const char* method_cmds_str[] = {
10149 "GET_DECLARING_TYPE",
10157 "MAKE_GENERIC_METHOD"
10160 static const char* type_cmds_str[] = {
10166 "GET_SOURCE_FILES",
10168 "IS_ASSIGNABLE_FROM",
10171 "GET_FIELD_CATTRS",
10172 "GET_PROPERTY_CATTRS",
10173 "GET_SOURCE_FILES_2",
10175 "GET_METHODS_BY_NAME_FLAGS",
10177 "GET_INTERFACE_MAP",
10181 static const char* stack_frame_cmds_str[] = {
10189 static const char* array_cmds_str[] = {
10195 static const char* string_cmds_str[] = {
10201 static const char* object_cmds_str[] = {
10212 cmd_to_string (CommandSet set, int command)
10219 cmds = vm_cmds_str;
10220 cmds_len = G_N_ELEMENTS (vm_cmds_str);
10222 case CMD_SET_OBJECT_REF:
10223 cmds = object_cmds_str;
10224 cmds_len = G_N_ELEMENTS (object_cmds_str);
10226 case CMD_SET_STRING_REF:
10227 cmds = string_cmds_str;
10228 cmds_len = G_N_ELEMENTS (string_cmds_str);
10230 case CMD_SET_THREAD:
10231 cmds = thread_cmds_str;
10232 cmds_len = G_N_ELEMENTS (thread_cmds_str);
10234 case CMD_SET_ARRAY_REF:
10235 cmds = array_cmds_str;
10236 cmds_len = G_N_ELEMENTS (array_cmds_str);
10238 case CMD_SET_EVENT_REQUEST:
10239 cmds = event_cmds_str;
10240 cmds_len = G_N_ELEMENTS (event_cmds_str);
10242 case CMD_SET_STACK_FRAME:
10243 cmds = stack_frame_cmds_str;
10244 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
10246 case CMD_SET_APPDOMAIN:
10247 cmds = appdomain_cmds_str;
10248 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
10250 case CMD_SET_ASSEMBLY:
10251 cmds = assembly_cmds_str;
10252 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
10254 case CMD_SET_METHOD:
10255 cmds = method_cmds_str;
10256 cmds_len = G_N_ELEMENTS (method_cmds_str);
10259 cmds = type_cmds_str;
10260 cmds_len = G_N_ELEMENTS (type_cmds_str);
10262 case CMD_SET_MODULE:
10263 cmds = module_cmds_str;
10264 cmds_len = G_N_ELEMENTS (module_cmds_str);
10266 case CMD_SET_FIELD:
10267 cmds = field_cmds_str;
10268 cmds_len = G_N_ELEMENTS (field_cmds_str);
10270 case CMD_SET_EVENT:
10271 cmds = event_cmds_str;
10272 cmds_len = G_N_ELEMENTS (event_cmds_str);
10277 if (command > 0 && command <= cmds_len)
10278 return cmds [command - 1];
10284 wait_for_attach (void)
10286 #ifndef DISABLE_SOCKET_TRANSPORT
10287 if (listen_fd == -1) {
10288 DEBUG_PRINTF (1, "[dbg] Invalid listening socket\n");
10292 /* Block and wait for client connection */
10293 conn_fd = socket_transport_accept (listen_fd);
10295 DEBUG_PRINTF (1, "Accepted connection on %d\n", conn_fd);
10296 if (conn_fd == -1) {
10297 DEBUG_PRINTF (1, "[dbg] Bad client connection\n");
10301 g_assert_not_reached ();
10305 disconnected = !transport_handshake ();
10306 if (disconnected) {
10307 DEBUG_PRINTF (1, "Transport handshake failed!\n");
10317 * This thread handles communication with the debugger client using a JDWP
10320 static gsize WINAPI
10321 debugger_thread (void *arg)
10324 int res, len, id, flags, command = 0;
10325 CommandSet command_set = (CommandSet)0;
10326 guint8 header [HEADER_LENGTH];
10327 guint8 *data, *p, *end;
10331 gboolean attach_failed = FALSE;
10333 DEBUG_PRINTF (1, "[dbg] Agent thread started, pid=%p\n", (gpointer) (gsize) mono_native_thread_id_get ());
10335 debugger_thread_id = mono_native_thread_id_get ();
10337 MonoInternalThread *internal = mono_thread_internal_current ();
10338 MonoString *str = mono_string_new_checked (mono_domain_get (), "Debugger agent", &error);
10339 mono_error_assert_ok (&error);
10340 mono_thread_set_name_internal (internal, str, TRUE, FALSE, &error);
10341 mono_error_assert_ok (&error);
10343 internal->state |= ThreadState_Background;
10344 internal->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
10346 if (agent_config.defer) {
10347 if (!wait_for_attach ()) {
10348 DEBUG_PRINTF (1, "[dbg] Can't attach, aborting debugger thread.\n");
10349 attach_failed = TRUE; // Don't abort process when we can't listen
10351 mono_set_is_debugger_attached (TRUE);
10352 /* Send start event to client */
10353 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
10356 mono_set_is_debugger_attached (TRUE);
10359 while (!attach_failed) {
10360 res = transport_recv (header, HEADER_LENGTH);
10362 /* This will break if the socket is closed during shutdown too */
10363 if (res != HEADER_LENGTH) {
10364 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH);
10369 end = header + HEADER_LENGTH;
10371 len = decode_int (p, &p, end);
10372 id = decode_int (p, &p, end);
10373 flags = decode_byte (p, &p, end);
10374 command_set = (CommandSet)decode_byte (p, &p, end);
10375 command = decode_byte (p, &p, end);
10377 g_assert (flags == 0);
10380 const char *cmd_str;
10381 char cmd_num [256];
10383 cmd_str = cmd_to_string (command_set, command);
10385 sprintf (cmd_num, "%d", command);
10389 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);
10392 data = (guint8 *)g_malloc (len - HEADER_LENGTH);
10393 if (len - HEADER_LENGTH > 0)
10395 res = transport_recv (data, len - HEADER_LENGTH);
10396 if (res != len - HEADER_LENGTH) {
10397 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH);
10403 end = data + (len - HEADER_LENGTH);
10405 buffer_init (&buf, 128);
10410 /* Process the request */
10411 switch (command_set) {
10413 err = vm_commands (command, id, p, end, &buf);
10414 if (err == ERR_NONE && command == CMD_VM_INVOKE_METHOD)
10415 /* Sent after the invoke is complete */
10418 case CMD_SET_EVENT_REQUEST:
10419 err = event_commands (command, p, end, &buf);
10421 case CMD_SET_APPDOMAIN:
10422 err = domain_commands (command, p, end, &buf);
10424 case CMD_SET_ASSEMBLY:
10425 err = assembly_commands (command, p, end, &buf);
10427 case CMD_SET_MODULE:
10428 err = module_commands (command, p, end, &buf);
10430 case CMD_SET_FIELD:
10431 err = field_commands (command, p, end, &buf);
10434 err = type_commands (command, p, end, &buf);
10436 case CMD_SET_METHOD:
10437 err = method_commands (command, p, end, &buf);
10439 case CMD_SET_THREAD:
10440 err = thread_commands (command, p, end, &buf);
10442 case CMD_SET_STACK_FRAME:
10443 err = frame_commands (command, p, end, &buf);
10445 case CMD_SET_ARRAY_REF:
10446 err = array_commands (command, p, end, &buf);
10448 case CMD_SET_STRING_REF:
10449 err = string_commands (command, p, end, &buf);
10451 case CMD_SET_OBJECT_REF:
10452 err = object_commands (command, p, end, &buf);
10455 err = ERR_NOT_IMPLEMENTED;
10458 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
10459 buffer_replies = TRUE;
10463 if (buffer_replies) {
10464 buffer_reply_packet (id, err, &buf);
10466 send_reply_packet (id, err, &buf);
10467 //DEBUG_PRINTF (1, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000);
10471 if (err == ERR_NONE && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
10472 send_buffered_reply_packets ();
10473 buffer_replies = FALSE;
10477 buffer_free (&buf);
10479 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
10483 mono_set_is_debugger_attached (FALSE);
10485 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
10486 debugger_thread_exited = TRUE;
10487 mono_coop_cond_signal (&debugger_thread_exited_cond);
10488 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
10490 DEBUG_PRINTF (1, "[dbg] Debugger thread exited.\n");
10492 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
10493 DEBUG_PRINTF (2, "[dbg] Detached - restarting clean debugger thread.\n");
10494 start_debugger_thread ();
10500 #else /* DISABLE_DEBUGGER_AGENT */
10503 mono_debugger_agent_parse_options (char *options)
10505 g_error ("This runtime is configured with the debugger agent disabled.");
10509 mono_debugger_agent_init (void)
10514 mono_debugger_agent_breakpoint_hit (void *sigctx)
10519 mono_debugger_agent_single_step_event (void *sigctx)
10524 mono_debugger_agent_free_domain_info (MonoDomain *domain)
10529 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
10530 MonoContext *catch_ctx)
10535 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
10540 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
10545 mono_debugger_agent_user_break (void)
10551 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
10556 mono_debugger_agent_debug_log_is_enabled (void)
10562 mono_debugger_agent_unhandled_exception (MonoException *exc)
10564 g_assert_not_reached ();
10568 debugger_agent_single_step_from_context (MonoContext *ctx)
10570 g_assert_not_reached ();
10574 debugger_agent_breakpoint_from_context (MonoContext *ctx)
10576 g_assert_not_reached ();