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 */
598 /* Dummy structure used for the profiler callbacks */
604 guint8 *buf, *p, *end;
607 typedef struct ReplyPacket {
613 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
615 #ifdef PLATFORM_ANDROID
616 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { g_print (__VA_ARGS__); } } while (0)
618 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { fprintf (log_file, __VA_ARGS__); fflush (log_file); } } while (0)
622 #define get_last_sock_error() WSAGetLastError()
623 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
624 #define MONO_EINTR WSAEINTR
626 #define get_last_sock_error() errno
627 #define MONO_EWOULDBLOCK EWOULDBLOCK
628 #define MONO_EINTR EINTR
631 #define CHECK_PROTOCOL_VERSION(major,minor) \
632 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
638 static AgentConfig agent_config;
641 * Whenever the agent is fully initialized.
642 * When using the onuncaught or onthrow options, only some parts of the agent are
643 * initialized on startup, and the full initialization which includes connection
644 * establishment and the startup of the agent thread is only done in response to
647 static gint32 inited;
649 #ifndef DISABLE_SOCKET_TRANSPORT
651 static int listen_fd;
654 static int packet_id = 0;
656 static int objref_id = 0;
658 static int event_request_id = 0;
660 static int frame_id = 0;
662 static GPtrArray *event_requests;
664 static MonoNativeTlsKey debugger_tls_id;
666 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
668 /* Maps MonoInternalThread -> DebuggerTlsData */
669 /* Protected by the loader lock */
670 static MonoGHashTable *thread_to_tls;
672 /* Maps tid -> MonoInternalThread */
673 /* Protected by the loader lock */
674 static MonoGHashTable *tid_to_thread;
676 /* Maps tid -> MonoThread (not MonoInternalThread) */
677 /* Protected by the loader lock */
678 static MonoGHashTable *tid_to_thread_obj;
680 static MonoNativeThreadId debugger_thread_id;
682 static MonoThreadHandle *debugger_thread_handle;
684 static int log_level;
686 static gboolean embedding;
688 static FILE *log_file;
690 /* Assemblies whose assembly load event has no been sent yet */
691 /* Protected by the dbg lock */
692 static GPtrArray *pending_assembly_loads;
694 /* Whenever the debugger thread has exited */
695 static gboolean debugger_thread_exited;
697 /* Cond variable used to wait for debugger_thread_exited becoming true */
698 static MonoCoopCond debugger_thread_exited_cond;
700 /* Mutex for the cond var above */
701 static MonoCoopMutex debugger_thread_exited_mutex;
703 static DebuggerProfiler debugger_profiler;
705 /* The single step request instance */
706 static SingleStepReq *ss_req;
708 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
709 /* Number of single stepping operations in progress */
713 /* The protocol version of the client */
714 static int major_version, minor_version;
716 /* Whenever the variables above are set by the client */
717 static gboolean protocol_version_set;
719 /* A hash table containing all active domains */
720 /* Protected by the loader lock */
721 static GHashTable *domains;
723 /* The number of times the runtime is suspended */
724 static gint32 suspend_count;
726 /* Whenever to buffer reply messages and send them together */
727 static gboolean buffer_replies;
729 /* Buffered reply packets */
730 static ReplyPacket reply_packets [128];
733 #define dbg_lock() mono_coop_mutex_lock (&debug_mutex)
734 #define dbg_unlock() mono_coop_mutex_unlock (&debug_mutex)
735 static MonoCoopMutex debug_mutex;
737 static void transport_init (void);
738 static void transport_connect (const char *address);
739 static gboolean transport_handshake (void);
740 static void register_transport (DebuggerTransport *trans);
742 static gsize WINAPI debugger_thread (void *arg);
744 static void runtime_initialized (MonoProfiler *prof);
746 static void runtime_shutdown (MonoProfiler *prof);
748 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
750 static void thread_end (MonoProfiler *prof, uintptr_t tid);
752 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
754 static void appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain);
756 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
758 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
760 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
762 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
764 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
766 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
768 static void emit_assembly_load (gpointer assembly, gpointer user_data);
770 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
772 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
774 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
776 static void start_single_stepping (void);
778 static void stop_single_stepping (void);
780 static void suspend_current (void);
782 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
784 static void clear_types_for_assembly (MonoAssembly *assembly);
786 static void clear_breakpoints_for_domain (MonoDomain *domain);
788 static void process_profiler_event (EventKind event, gpointer arg);
790 /* Submodule init/cleanup */
791 static void breakpoints_init (void);
792 static void breakpoints_cleanup (void);
794 static void objrefs_init (void);
795 static void objrefs_cleanup (void);
797 static void ids_init (void);
798 static void ids_cleanup (void);
800 static void suspend_init (void);
802 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch,
803 StackFrame **frames, int nframes);
804 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req);
805 static void ss_destroy (SingleStepReq *req);
807 static void start_debugger_thread (void);
808 static void stop_debugger_thread (void);
810 static void finish_agent_init (gboolean on_startup);
812 static void process_profiler_event (EventKind event, gpointer arg);
814 static void invalidate_frames (DebuggerTlsData *tls);
816 #ifndef DISABLE_SOCKET_TRANSPORT
818 register_socket_transport (void);
821 static inline gboolean
822 is_debugger_thread (void)
824 MonoInternalThread *internal;
826 internal = mono_thread_internal_current ();
830 return internal->debugger_thread;
834 parse_address (char *address, char **host, int *port)
836 char *pos = strchr (address, ':');
838 if (pos == NULL || pos == address)
841 size_t len = pos - address;
842 *host = (char *)g_malloc (len + 1);
843 memcpy (*host, address, len);
844 (*host) [len] = '\0';
846 *port = atoi (pos + 1);
854 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
855 fprintf (stderr, "Available options:\n");
856 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
857 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
858 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
859 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
860 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
861 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
862 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
863 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
864 fprintf (stderr, " setpgid=y/n\t\t\tWhether to call setpid(0, 0) after startup.\n");
865 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
869 parse_flag (const char *option, char *flag)
871 if (!strcmp (flag, "y"))
873 else if (!strcmp (flag, "n"))
876 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
883 mono_debugger_agent_parse_options (char *options)
890 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
891 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
895 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
897 options = g_strdup_printf ("%s,%s", options, extra);
901 agent_config.enabled = TRUE;
902 agent_config.suspend = TRUE;
903 agent_config.server = FALSE;
904 agent_config.defer = FALSE;
905 agent_config.address = NULL;
907 //agent_config.log_level = 10;
909 args = g_strsplit (options, ",", -1);
910 for (ptr = args; ptr && *ptr; ptr ++) {
913 if (strncmp (arg, "transport=", 10) == 0) {
914 agent_config.transport = g_strdup (arg + 10);
915 } else if (strncmp (arg, "address=", 8) == 0) {
916 agent_config.address = g_strdup (arg + 8);
917 } else if (strncmp (arg, "loglevel=", 9) == 0) {
918 agent_config.log_level = atoi (arg + 9);
919 } else if (strncmp (arg, "logfile=", 8) == 0) {
920 agent_config.log_file = g_strdup (arg + 8);
921 } else if (strncmp (arg, "suspend=", 8) == 0) {
922 agent_config.suspend = parse_flag ("suspend", arg + 8);
923 } else if (strncmp (arg, "server=", 7) == 0) {
924 agent_config.server = parse_flag ("server", arg + 7);
925 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
926 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
927 } else if (strncmp (arg, "onthrow=", 8) == 0) {
928 /* We support multiple onthrow= options */
929 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
930 } else if (strncmp (arg, "onthrow", 7) == 0) {
931 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
932 } else if (strncmp (arg, "help", 4) == 0) {
935 } else if (strncmp (arg, "timeout=", 8) == 0) {
936 agent_config.timeout = atoi (arg + 8);
937 } else if (strncmp (arg, "launch=", 7) == 0) {
938 agent_config.launch = g_strdup (arg + 7);
939 } else if (strncmp (arg, "embedding=", 10) == 0) {
940 agent_config.embedding = atoi (arg + 10) == 1;
941 } else if (strncmp (arg, "keepalive=", 10) == 0) {
942 agent_config.keepalive = atoi (arg + 10);
943 } else if (strncmp (arg, "setpgid=", 8) == 0) {
944 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
951 if (agent_config.server && !agent_config.suspend) {
952 /* Waiting for deferred attachment */
953 agent_config.defer = TRUE;
954 if (agent_config.address == NULL) {
955 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (mono_process_current_pid () % 1000));
959 //agent_config.log_level = 0;
961 if (agent_config.transport == NULL) {
962 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
966 if (agent_config.address == NULL && !agent_config.server) {
967 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
972 if (!strcmp (agent_config.transport, "dt_socket")) {
973 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
974 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
981 mono_debugger_agent_init (void)
983 mono_coop_mutex_init_recursive (&debug_mutex);
985 if (!agent_config.enabled)
990 /* Need to know whenever a thread has acquired the loader mutex */
991 mono_loader_lock_track_ownership (TRUE);
993 event_requests = g_ptr_array_new ();
995 mono_coop_mutex_init (&debugger_thread_exited_mutex);
996 mono_coop_cond_init (&debugger_thread_exited_cond);
998 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
999 mono_profiler_set_events ((MonoProfileFlags)(MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS));
1000 mono_profiler_install_runtime_initialized (runtime_initialized);
1001 mono_profiler_install_appdomain (NULL, appdomain_load, appdomain_start_unload, appdomain_unload);
1002 mono_profiler_install_thread (thread_startup, thread_end);
1003 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
1004 mono_profiler_install_jit_end (jit_end);
1006 mono_native_tls_alloc (&debugger_tls_id, NULL);
1008 /* Needed by the hash_table_new_type () call below */
1009 mono_gc_base_init ();
1011 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");
1013 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread table");
1015 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");
1017 pending_assembly_loads = g_ptr_array_new ();
1018 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
1020 log_level = agent_config.log_level;
1022 embedding = agent_config.embedding;
1023 disconnected = TRUE;
1025 if (agent_config.log_file) {
1026 log_file = fopen (agent_config.log_file, "w+");
1028 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
1037 breakpoints_init ();
1040 mini_get_debug_options ()->gen_sdb_seq_points = TRUE;
1042 * This is needed because currently we don't handle liveness info.
1044 mini_get_debug_options ()->mdb_optimizations = TRUE;
1046 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
1047 /* This is needed because we can't set local variables in registers yet */
1048 mono_disable_optimizations (MONO_OPT_LINEARS);
1052 * The stack walk done from thread_interrupt () needs to be signal safe, but it
1053 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
1054 * safe (#3411). So load AOT info eagerly when the debugger is running as a
1057 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
1060 if (agent_config.setpgid)
1064 if (!agent_config.onuncaught && !agent_config.onthrow)
1065 finish_agent_init (TRUE);
1069 * finish_agent_init:
1071 * Finish the initialization of the agent. This involves connecting the transport
1072 * and starting the agent thread. This is either done at startup, or
1073 * in response to some event like an unhandled exception.
1076 finish_agent_init (gboolean on_startup)
1080 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
1083 if (agent_config.launch) {
1086 // FIXME: Generated address
1087 // FIXME: Races with transport_connect ()
1089 argv [0] = agent_config.launch;
1090 argv [1] = agent_config.transport;
1091 argv [2] = agent_config.address;
1094 res = g_spawn_async_with_pipes (NULL, argv, NULL, (GSpawnFlags)0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1096 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1101 transport_connect (agent_config.address);
1104 /* Do some which is usually done after sending the VMStart () event */
1105 vm_start_event_sent = TRUE;
1106 start_debugger_thread ();
1111 mono_debugger_agent_cleanup (void)
1116 stop_debugger_thread ();
1118 breakpoints_cleanup ();
1127 #ifndef DISABLE_SOCKET_TRANSPORT
1132 * recv() + handle incomplete reads and EINTR
1135 socket_transport_recv (void *buf, int len)
1141 static gint64 last_keepalive;
1148 res = recv (fd, (char *) buf + total, len - total, flags);
1151 if (agent_config.keepalive) {
1152 gboolean need_keepalive = FALSE;
1153 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1154 need_keepalive = TRUE;
1155 } else if (res == -1) {
1156 /* This could happen if recv () is interrupted repeatedly */
1157 msecs = mono_msec_ticks ();
1158 if (msecs - last_keepalive >= agent_config.keepalive) {
1159 need_keepalive = TRUE;
1160 last_keepalive = msecs;
1163 if (need_keepalive) {
1164 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1168 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1176 set_keepalive (void)
1181 if (!agent_config.keepalive || !conn_fd)
1184 tv.tv_sec = agent_config.keepalive / 1000;
1185 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1187 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1188 g_assert (result >= 0);
1192 socket_transport_accept (int socket_fd)
1195 conn_fd = accept (socket_fd, NULL, NULL);
1198 if (conn_fd == -1) {
1199 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1201 DEBUG_PRINTF (1, "Accepted connection from client, connection fd=%d.\n", conn_fd);
1208 socket_transport_send (void *data, int len)
1215 res = send (conn_fd, data, len, 0);
1216 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1227 * socket_transport_connect:
1229 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1232 socket_transport_connect (const char *address)
1234 MonoAddressInfo *result;
1235 MonoAddressEntry *rp;
1236 int sfd = -1, s, res;
1240 if (agent_config.address) {
1241 res = parse_address (agent_config.address, &host, &port);
1242 g_assert (res == 0);
1253 mono_network_init ();
1255 /* Obtain address(es) matching host/port */
1256 s = mono_get_address_info (host, port, MONO_HINT_UNSPECIFIED, &result);
1258 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, s); // FIXME add portable error conversion functions
1263 if (agent_config.server) {
1264 /* Wait for a connection */
1266 struct sockaddr_in addr;
1269 /* No address, generate one */
1270 sfd = socket (AF_INET, SOCK_STREAM, 0);
1273 /* This will bind the socket to a random port */
1274 res = listen (sfd, 16);
1276 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1281 addrlen = sizeof (addr);
1282 memset (&addr, 0, sizeof (addr));
1283 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1284 g_assert (res == 0);
1286 host = (char*)"127.0.0.1";
1287 port = ntohs (addr.sin_port);
1289 /* Emit the address to stdout */
1290 /* FIXME: Should print another interface, not localhost */
1291 printf ("%s:%d\n", host, port);
1293 /* Listen on the provided address */
1294 for (rp = result->entries; rp != NULL; rp = rp->next) {
1295 MonoSocketAddress sockaddr;
1299 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1301 sfd = socket (rp->family, rp->socktype,
1306 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1309 res = bind (sfd, &sockaddr.addr, sock_len);
1313 res = listen (sfd, 16);
1320 mono_free_address_info (result);
1323 if (agent_config.defer)
1326 DEBUG_PRINTF (1, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout);
1328 if (agent_config.timeout) {
1333 tv.tv_usec = agent_config.timeout * 1000;
1335 FD_SET (sfd, &readfds);
1338 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1342 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1347 conn_fd = socket_transport_accept (sfd);
1351 DEBUG_PRINTF (1, "Accepted connection from client, socket fd=%d.\n", conn_fd);
1353 /* Connect to the specified address */
1354 /* FIXME: Respect the timeout */
1355 for (rp = result->entries; rp != NULL; rp = rp->next) {
1356 MonoSocketAddress sockaddr;
1359 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1361 sfd = socket (rp->family, rp->socktype,
1367 res = connect (sfd, &sockaddr.addr, sock_len);
1371 break; /* Success */
1379 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1385 mono_free_address_info (result);
1388 if (!transport_handshake ())
1393 socket_transport_close1 (void)
1395 /* This will interrupt the agent thread */
1396 /* Close the read part only so it can still send back replies */
1397 /* Also shut down the connection listener so that we can exit normally */
1399 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1400 shutdown (conn_fd, SD_BOTH);
1401 shutdown (listen_fd, SD_BOTH);
1402 closesocket (listen_fd);
1404 shutdown (conn_fd, SHUT_RD);
1405 shutdown (listen_fd, SHUT_RDWR);
1413 socket_transport_close2 (void)
1416 shutdown (conn_fd, SD_BOTH);
1418 shutdown (conn_fd, SHUT_RDWR);
1423 register_socket_transport (void)
1425 DebuggerTransport trans;
1427 trans.name = "dt_socket";
1428 trans.connect = socket_transport_connect;
1429 trans.close1 = socket_transport_close1;
1430 trans.close2 = socket_transport_close2;
1431 trans.send = socket_transport_send;
1432 trans.recv = socket_transport_recv;
1434 register_transport (&trans);
1438 * socket_fd_transport_connect:
1442 socket_fd_transport_connect (const char *address)
1446 res = sscanf (address, "%d", &conn_fd);
1448 fprintf (stderr, "debugger-agent: socket-fd transport address is invalid: '%s'\n", address);
1452 if (!transport_handshake ())
1457 register_socket_fd_transport (void)
1459 DebuggerTransport trans;
1461 /* This is the same as the 'dt_socket' transport, but receives an already connected socket fd */
1462 trans.name = "socket-fd";
1463 trans.connect = socket_fd_transport_connect;
1464 trans.close1 = socket_transport_close1;
1465 trans.close2 = socket_transport_close2;
1466 trans.send = socket_transport_send;
1467 trans.recv = socket_transport_recv;
1469 register_transport (&trans);
1472 #endif /* DISABLE_SOCKET_TRANSPORT */
1478 #define MAX_TRANSPORTS 16
1480 static DebuggerTransport *transport;
1482 static DebuggerTransport transports [MAX_TRANSPORTS];
1483 static int ntransports;
1486 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1489 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1491 register_transport (trans);
1495 register_transport (DebuggerTransport *trans)
1497 g_assert (ntransports < MAX_TRANSPORTS);
1499 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1504 transport_init (void)
1508 #ifndef DISABLE_SOCKET_TRANSPORT
1509 register_socket_transport ();
1510 register_socket_fd_transport ();
1513 for (i = 0; i < ntransports; ++i) {
1514 if (!strcmp (agent_config.transport, transports [i].name))
1517 if (i == ntransports) {
1518 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1519 for (i = 0; i < ntransports; ++i)
1520 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1521 fprintf (stderr, "\n");
1524 transport = &transports [i];
1528 transport_connect (const char *address)
1530 transport->connect (address);
1534 transport_close1 (void)
1536 transport->close1 ();
1540 transport_close2 (void)
1542 transport->close2 ();
1546 transport_send (void *buf, int len)
1548 return transport->send (buf, len);
1552 transport_recv (void *buf, int len)
1554 return transport->recv (buf, len);
1558 mono_debugger_agent_transport_handshake (void)
1560 return transport_handshake ();
1564 transport_handshake (void)
1566 char handshake_msg [128];
1570 disconnected = TRUE;
1572 /* Write handshake message */
1573 sprintf (handshake_msg, "DWP-Handshake");
1576 res = transport_send (handshake_msg, strlen (handshake_msg));
1577 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1579 g_assert (res != -1);
1582 res = transport_recv (buf, strlen (handshake_msg));
1583 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg)) != 0)) {
1584 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1589 * To support older clients, the client sends its protocol version after connecting
1590 * using a command. Until that is received, default to our protocol version.
1592 major_version = MAJOR_VERSION;
1593 minor_version = MINOR_VERSION;
1594 protocol_version_set = FALSE;
1596 #ifndef DISABLE_SOCKET_TRANSPORT
1597 // FIXME: Move this somewhere else
1599 * Set TCP_NODELAY on the socket so the client receives events/command
1600 * results immediately.
1604 int result = setsockopt (conn_fd,
1609 g_assert (result >= 0);
1615 disconnected = FALSE;
1620 stop_debugger_thread (void)
1625 transport_close1 ();
1628 * Wait for the thread to exit.
1630 * If we continue with the shutdown without waiting for it, then the client might
1631 * not receive an answer to its last command like a resume.
1633 if (!is_debugger_thread ()) {
1635 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
1636 if (!debugger_thread_exited)
1637 mono_coop_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1638 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
1639 } while (!debugger_thread_exited);
1642 transport_close2 ();
1646 start_debugger_thread (void)
1649 MonoInternalThread *thread;
1651 thread = mono_thread_create_internal (mono_get_root_domain (), debugger_thread, NULL, MONO_THREAD_CREATE_FLAGS_DEBUGGER, &error);
1652 mono_error_assert_ok (&error);
1654 debugger_thread_handle = mono_threads_open_thread_handle (thread->handle);
1655 g_assert (debugger_thread_handle);
1659 * Functions to decode protocol data
1663 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1666 g_assert (*endbuf <= limit);
1671 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1674 g_assert (*endbuf <= limit);
1676 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1679 static inline gint64
1680 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1682 guint32 high = decode_int (buf, &buf, limit);
1683 guint32 low = decode_int (buf, &buf, limit);
1687 return ((((guint64)high) << 32) | ((guint64)low));
1691 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1693 return decode_int (buf, endbuf, limit);
1697 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1699 int len = decode_int (buf, &buf, limit);
1707 s = (char *)g_malloc (len + 1);
1710 memcpy (s, buf, len);
1719 * Functions to encode protocol data
1723 buffer_init (Buffer *buf, int size)
1725 buf->buf = (guint8 *)g_malloc (size);
1727 buf->end = buf->buf + size;
1731 buffer_len (Buffer *buf)
1733 return buf->p - buf->buf;
1737 buffer_make_room (Buffer *buf, int size)
1739 if (buf->end - buf->p < size) {
1740 int new_size = buf->end - buf->buf + size + 32;
1741 guint8 *p = (guint8 *)g_realloc (buf->buf, new_size);
1742 size = buf->p - buf->buf;
1745 buf->end = buf->buf + new_size;
1750 buffer_add_byte (Buffer *buf, guint8 val)
1752 buffer_make_room (buf, 1);
1758 buffer_add_short (Buffer *buf, guint32 val)
1760 buffer_make_room (buf, 2);
1761 buf->p [0] = (val >> 8) & 0xff;
1762 buf->p [1] = (val >> 0) & 0xff;
1767 buffer_add_int (Buffer *buf, guint32 val)
1769 buffer_make_room (buf, 4);
1770 buf->p [0] = (val >> 24) & 0xff;
1771 buf->p [1] = (val >> 16) & 0xff;
1772 buf->p [2] = (val >> 8) & 0xff;
1773 buf->p [3] = (val >> 0) & 0xff;
1778 buffer_add_long (Buffer *buf, guint64 l)
1780 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1781 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1785 buffer_add_id (Buffer *buf, int id)
1787 buffer_add_int (buf, (guint64)id);
1791 buffer_add_data (Buffer *buf, guint8 *data, int len)
1793 buffer_make_room (buf, len);
1794 memcpy (buf->p, data, len);
1799 buffer_add_string (Buffer *buf, const char *str)
1804 buffer_add_int (buf, 0);
1807 buffer_add_int (buf, len);
1808 buffer_add_data (buf, (guint8*)str, len);
1813 buffer_add_buffer (Buffer *buf, Buffer *data)
1815 buffer_add_data (buf, data->buf, buffer_len (data));
1819 buffer_free (Buffer *buf)
1825 send_packet (int command_set, int command, Buffer *data)
1831 id = InterlockedIncrement (&packet_id);
1833 len = data->p - data->buf + 11;
1834 buffer_init (&buf, len);
1835 buffer_add_int (&buf, len);
1836 buffer_add_int (&buf, id);
1837 buffer_add_byte (&buf, 0); /* flags */
1838 buffer_add_byte (&buf, command_set);
1839 buffer_add_byte (&buf, command);
1840 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1842 res = transport_send (buf.buf, len);
1850 send_reply_packets (int npackets, ReplyPacket *packets)
1857 for (i = 0; i < npackets; ++i)
1858 len += buffer_len (packets [i].data) + 11;
1859 buffer_init (&buf, len);
1860 for (i = 0; i < npackets; ++i) {
1861 buffer_add_int (&buf, buffer_len (packets [i].data) + 11);
1862 buffer_add_int (&buf, packets [i].id);
1863 buffer_add_byte (&buf, 0x80); /* flags */
1864 buffer_add_byte (&buf, (packets [i].error >> 8) & 0xff);
1865 buffer_add_byte (&buf, packets [i].error);
1866 buffer_add_buffer (&buf, packets [i].data);
1869 res = transport_send (buf.buf, len);
1877 send_reply_packet (int id, int error, Buffer *data)
1881 memset (&packet, 0, sizeof (ReplyPacket));
1883 packet.error = error;
1886 return send_reply_packets (1, &packet);
1890 send_buffered_reply_packets (void)
1894 send_reply_packets (nreply_packets, reply_packets);
1895 for (i = 0; i < nreply_packets; ++i)
1896 buffer_free (reply_packets [i].data);
1897 DEBUG_PRINTF (1, "[dbg] Sent %d buffered reply packets [at=%lx].\n", nreply_packets, (long)mono_100ns_ticks () / 10000);
1902 buffer_reply_packet (int id, int error, Buffer *data)
1906 if (nreply_packets == 128)
1907 send_buffered_reply_packets ();
1909 p = &reply_packets [nreply_packets];
1912 p->data = g_new0 (Buffer, 1);
1913 buffer_init (p->data, buffer_len (data));
1914 buffer_add_buffer (p->data, data);
1923 * Represents an object accessible by the debugger client.
1926 /* Unique id used in the wire protocol to refer to objects */
1929 * A weakref gc handle pointing to the object. The gc handle is used to
1930 * detect if the object was garbage collected.
1935 /* Maps objid -> ObjRef */
1936 /* Protected by the loader lock */
1937 static GHashTable *objrefs;
1938 /* Protected by the loader lock */
1939 static GHashTable *obj_to_objref;
1940 /* Protected by the dbg lock */
1941 static MonoGHashTable *suspended_objs;
1944 free_objref (gpointer value)
1946 ObjRef *o = (ObjRef *)value;
1948 mono_gchandle_free (o->handle);
1956 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1957 obj_to_objref = g_hash_table_new (NULL, NULL);
1958 suspended_objs = mono_g_hash_table_new_type ((GHashFunc)mono_object_hash, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_DEBUGGER, "suspended objects table");
1962 objrefs_cleanup (void)
1964 g_hash_table_destroy (objrefs);
1969 * Return an ObjRef for OBJ.
1972 get_objref (MonoObject *obj)
1975 GSList *reflist = NULL, *l;
1981 if (suspend_count) {
1983 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1986 mono_g_hash_table_insert (suspended_objs, obj, NULL);
1990 mono_loader_lock ();
1992 /* FIXME: The tables can grow indefinitely */
1994 if (mono_gc_is_moving ()) {
1996 * Objects can move, so use a hash table mapping hash codes to lists of
1997 * ObjRef structures.
1999 hash = mono_object_hash (obj);
2001 reflist = (GSList *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
2002 for (l = reflist; l; l = l->next) {
2003 ref = (ObjRef *)l->data;
2004 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
2005 mono_loader_unlock ();
2010 /* Use a hash table with masked pointers to internalize object references */
2011 ref = (ObjRef *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
2012 /* ref might refer to a different object with the same addr which was GCd */
2013 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
2014 mono_loader_unlock ();
2019 ref = g_new0 (ObjRef, 1);
2020 ref->id = InterlockedIncrement (&objref_id);
2021 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
2023 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
2025 if (mono_gc_is_moving ()) {
2026 reflist = g_slist_append (reflist, ref);
2027 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
2029 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
2032 mono_loader_unlock ();
2038 true_pred (gpointer key, gpointer value, gpointer user_data)
2044 clear_suspended_objs (void)
2047 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
2052 get_objid (MonoObject *obj)
2057 return get_objref (obj)->id;
2061 * Set OBJ to the object identified by OBJID.
2062 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
2066 get_object_allow_null (int objid, MonoObject **obj)
2076 return ERR_INVALID_OBJECT;
2078 mono_loader_lock ();
2080 ref = (ObjRef *)g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
2083 *obj = mono_gchandle_get_target (ref->handle);
2084 mono_loader_unlock ();
2086 return ERR_INVALID_OBJECT;
2089 mono_loader_unlock ();
2090 return ERR_INVALID_OBJECT;
2095 get_object (int objid, MonoObject **obj)
2097 ErrorCode err = get_object_allow_null (objid, obj);
2099 if (err != ERR_NONE)
2102 return ERR_INVALID_OBJECT;
2107 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
2109 return decode_id (buf, endbuf, limit);
2113 buffer_add_objid (Buffer *buf, MonoObject *o)
2115 buffer_add_id (buf, get_objid (o));
2134 * Represents a runtime structure accessible to the debugger client
2137 /* Unique id used in the wire protocol */
2139 /* Domain of the runtime structure, NULL if the domain was unloaded */
2146 MonoAssembly *assembly;
2147 MonoClassField *field;
2149 MonoProperty *property;
2154 /* Maps runtime structure -> Id */
2155 /* Protected by the dbg lock */
2156 GHashTable *val_to_id [ID_NUM];
2157 /* Classes whose class load event has been sent */
2158 /* Protected by the loader lock */
2159 GHashTable *loaded_classes;
2160 /* Maps MonoClass->GPtrArray of file names */
2161 GHashTable *source_files;
2162 /* Maps source file basename -> GSList of classes */
2163 GHashTable *source_file_to_class;
2164 /* Same with ignore-case */
2165 GHashTable *source_file_to_class_ignorecase;
2169 /* Protected by the dbg lock */
2170 static GPtrArray *ids [ID_NUM];
2177 for (i = 0; i < ID_NUM; ++i)
2178 ids [i] = g_ptr_array_new ();
2186 for (i = 0; i < ID_NUM; ++i) {
2188 for (j = 0; j < ids [i]->len; ++j)
2189 g_free (g_ptr_array_index (ids [i], j));
2190 g_ptr_array_free (ids [i], TRUE);
2197 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2199 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2201 GHashTableIter iter;
2202 GPtrArray *file_names;
2207 for (i = 0; i < ID_NUM; ++i)
2208 if (info->val_to_id [i])
2209 g_hash_table_destroy (info->val_to_id [i]);
2210 g_hash_table_destroy (info->loaded_classes);
2212 g_hash_table_iter_init (&iter, info->source_files);
2213 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2214 for (i = 0; i < file_names->len; ++i)
2215 g_free (g_ptr_array_index (file_names, i));
2216 g_ptr_array_free (file_names, TRUE);
2219 g_hash_table_iter_init (&iter, info->source_file_to_class);
2220 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2225 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2226 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2234 domain_jit_info (domain)->agent_info = NULL;
2236 /* Clear ids referencing structures in the domain */
2238 for (i = 0; i < ID_NUM; ++i) {
2240 for (j = 0; j < ids [i]->len; ++j) {
2241 Id *id = (Id *)g_ptr_array_index (ids [i], j);
2242 if (id->domain == domain)
2249 mono_loader_lock ();
2250 g_hash_table_remove (domains, domain);
2251 mono_loader_unlock ();
2254 static AgentDomainInfo*
2255 get_agent_domain_info (MonoDomain *domain)
2257 AgentDomainInfo *info = NULL;
2259 mono_domain_lock (domain);
2261 info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2263 info = g_new0 (AgentDomainInfo, 1);
2264 domain_jit_info (domain)->agent_info = info;
2265 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2266 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2267 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2268 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2271 mono_domain_unlock (domain);
2277 get_id (MonoDomain *domain, IdType type, gpointer val)
2280 AgentDomainInfo *info;
2285 info = get_agent_domain_info (domain);
2289 if (info->val_to_id [type] == NULL)
2290 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2292 id = (Id *)g_hash_table_lookup (info->val_to_id [type], val);
2298 id = g_new0 (Id, 1);
2300 id->id = ids [type]->len + 1;
2301 id->domain = domain;
2304 g_hash_table_insert (info->val_to_id [type], val, id);
2305 g_ptr_array_add (ids [type], id);
2312 static inline gpointer
2313 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, ErrorCode *err)
2317 int id = decode_id (buf, endbuf, limit);
2326 // FIXME: error handling
2328 g_assert (id > 0 && id <= ids [type]->len);
2330 res = (Id *)g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2333 if (res->domain == NULL || res->domain->state == MONO_APPDOMAIN_UNLOADED) {
2334 DEBUG_PRINTF (1, "ERR_UNLOADED, id=%d, type=%d.\n", id, type);
2335 *err = ERR_UNLOADED;
2340 *domain = res->domain;
2342 return res->data.val;
2346 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2348 int id = get_id (domain, type, val);
2350 buffer_add_id (buf, id);
2354 static inline MonoClass*
2355 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2359 klass = (MonoClass *)decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2360 if (G_UNLIKELY (log_level >= 2) && klass) {
2363 s = mono_type_full_name (&klass->byval_arg);
2364 DEBUG_PRINTF (2, "[dbg] recv class [%s]\n", s);
2370 static inline MonoAssembly*
2371 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2373 return (MonoAssembly *)decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2376 static inline MonoImage*
2377 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2379 return (MonoImage *)decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2382 static inline MonoMethod*
2383 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2387 m = (MonoMethod *)decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2388 if (G_UNLIKELY (log_level >= 2) && m) {
2391 s = mono_method_full_name (m, TRUE);
2392 DEBUG_PRINTF (2, "[dbg] recv method [%s]\n", s);
2398 static inline MonoClassField*
2399 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2401 return (MonoClassField *)decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2404 static inline MonoDomain*
2405 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2407 return (MonoDomain *)decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2410 static inline MonoProperty*
2411 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2413 return (MonoProperty *)decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2417 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2419 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2420 if (G_UNLIKELY (log_level >= 2) && klass) {
2423 s = mono_type_full_name (&klass->byval_arg);
2424 if (is_debugger_thread ())
2425 DEBUG_PRINTF (2, "[dbg] send class [%s]\n", s);
2427 DEBUG_PRINTF (2, "[%p] send class [%s]\n", (gpointer) (gsize) mono_native_thread_id_get (), s);
2433 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2435 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2436 if (G_UNLIKELY (log_level >= 2) && method) {
2439 s = mono_method_full_name (method, 1);
2440 DEBUG_PRINTF (2, "[dbg] send method [%s]\n", s);
2446 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2450 id = buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2451 if (G_UNLIKELY (log_level >= 2) && assembly)
2452 DEBUG_PRINTF (2, "[dbg] send assembly [%s][%s][%d]\n", assembly->aname.name, domain->friendly_name, id);
2456 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2458 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2462 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2464 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2468 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2470 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2474 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2476 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2479 static void invoke_method (void);
2486 get_top_method_ji (gpointer ip, MonoDomain **domain, gpointer *out_ip)
2493 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, domain);
2495 /* Could be an interpreter method */
2497 MonoLMF *lmf = mono_get_lmf ();
2498 MonoInterpFrameHandle *frame;
2500 g_assert (((guint64)lmf->previous_lmf) & 2);
2501 MonoLMFExt *ext = (MonoLMFExt*)lmf;
2503 g_assert (ext->interp_exit);
2504 frame = ext->interp_exit_data;
2505 ji = mono_interp_frame_get_jit_info (frame);
2507 *domain = mono_domain_get ();
2509 *out_ip = mono_interp_frame_get_ip (frame);
2515 * save_thread_context:
2517 * Set CTX as the current threads context which is used for computing stack traces.
2518 * This function is signal-safe.
2521 save_thread_context (MonoContext *ctx)
2523 DebuggerTlsData *tls;
2525 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2529 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2531 mono_thread_state_init_from_current (&tls->context);
2534 /* Number of threads suspended */
2536 * If this is equal to the size of thread_to_tls, the runtime is considered
2539 static gint32 threads_suspend_count;
2541 static MonoCoopMutex suspend_mutex;
2543 /* Cond variable used to wait for suspend_count becoming 0 */
2544 static MonoCoopCond suspend_cond;
2546 /* Semaphore used to wait for a thread becoming suspended */
2547 static MonoCoopSem suspend_sem;
2552 mono_coop_mutex_init (&suspend_mutex);
2553 mono_coop_cond_init (&suspend_cond);
2554 mono_coop_sem_init (&suspend_sem, 0);
2559 StackFrameInfo last_frame;
2560 gboolean last_frame_set;
2564 } GetLastFrameUserData;
2567 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2569 GetLastFrameUserData *data = (GetLastFrameUserData *)user_data;
2571 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE || info->type == FRAME_TYPE_TRAMPOLINE)
2574 if (!data->last_frame_set) {
2575 /* Store the last frame */
2576 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2577 data->last_frame_set = TRUE;
2580 /* Store the context/lmf for the frame above the last frame */
2581 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2582 data->lmf = info->lmf;
2583 data->domain = info->domain;
2589 copy_unwind_state_from_frame_data (MonoThreadUnwindState *to, GetLastFrameUserData *data, gpointer jit_tls)
2591 memcpy (&to->ctx, &data->ctx, sizeof (MonoContext));
2593 to->unwind_data [MONO_UNWIND_DATA_DOMAIN] = data->domain;
2594 to->unwind_data [MONO_UNWIND_DATA_LMF] = data->lmf;
2595 to->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = jit_tls;
2602 * Process interruption of a thread. This should be signal safe.
2604 * This always runs in the debugger thread.
2607 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, MonoJitInfo *ji)
2610 MonoNativeThreadId tid;
2614 ip = MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx);
2615 tid = mono_thread_info_get_tid (info);
2617 // FIXME: Races when the thread leaves managed code before hitting a single step
2620 if (ji && !ji->is_trampoline) {
2621 /* Running managed code, will be suspended by the single step code */
2622 DEBUG_PRINTF (1, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip);
2625 * Running native code, will be suspended when it returns to/enters
2626 * managed code. Treat it as already suspended.
2627 * This might interrupt the code in process_single_step_inner (), we use the
2628 * tls->suspending flag to avoid races when that happens.
2630 if (!tls->suspended && !tls->suspending) {
2631 GetLastFrameUserData data;
2633 // FIXME: printf is not signal safe, but this is only used during
2634 // debugger debugging
2636 DEBUG_PRINTF (1, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip);
2637 //save_thread_context (&ctx);
2640 /* Already terminated */
2644 * We are in a difficult position: we want to be able to provide stack
2645 * traces for this thread, but we can't use the current ctx+lmf, since
2646 * the thread is still running, so it might return to managed code,
2647 * making these invalid.
2648 * So we start a stack walk and save the first frame, along with the
2649 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2650 * suspended when it returns to managed code, so the parent's ctx should
2653 MonoThreadUnwindState *state = mono_thread_info_get_suspend_state (info);
2655 data.last_frame_set = FALSE;
2656 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, state, MONO_UNWIND_SIGNAL_SAFE, &data);
2657 if (data.last_frame_set) {
2658 gpointer jit_tls = ((MonoThreadInfo*)tls->thread->thread_info)->jit_data;
2660 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2662 if (data.last_frame.type == FRAME_TYPE_INTERP_TO_MANAGED) {
2664 * Store the current lmf instead of the parent one, since that
2665 * contains the interp exit data.
2667 data.lmf = state->unwind_data [MONO_UNWIND_DATA_LMF];
2670 copy_unwind_state_from_frame_data (&tls->async_state, &data, jit_tls);
2671 copy_unwind_state_from_frame_data (&tls->context, &data, jit_tls);
2673 tls->async_state.valid = FALSE;
2676 mono_memory_barrier ();
2678 tls->suspended = TRUE;
2679 mono_coop_sem_post (&suspend_sem);
2685 * reset_native_thread_suspend_state:
2687 * Reset the suspended flag and state on native threads
2690 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2692 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2694 if (!tls->really_suspended && tls->suspended) {
2695 tls->suspended = FALSE;
2697 * The thread might still be running if it was executing native code, so the state won't be invalided by
2698 * suspend_current ().
2700 tls->context.valid = FALSE;
2701 tls->async_state.valid = FALSE;
2702 invalidate_frames (tls);
2707 DebuggerTlsData *tls;
2708 gboolean valid_info;
2711 static SuspendThreadResult
2712 debugger_interrupt_critical (MonoThreadInfo *info, gpointer user_data)
2714 InterruptData *data = (InterruptData *)user_data;
2717 data->valid_info = TRUE;
2718 ji = mono_jit_info_table_find_internal (
2719 (MonoDomain *)mono_thread_info_get_suspend_state (info)->unwind_data [MONO_UNWIND_DATA_DOMAIN],
2720 (char *)MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx),
2724 /* This is signal safe */
2725 thread_interrupt (data->tls, info, ji);
2726 return MonoResumeThread;
2732 * Notify a thread that it needs to suspend.
2735 notify_thread (gpointer key, gpointer value, gpointer user_data)
2737 MonoInternalThread *thread = (MonoInternalThread *)key;
2738 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2739 MonoNativeThreadId tid = MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid);
2741 if (mono_thread_internal_is_current (thread) || tls->terminated)
2744 DEBUG_PRINTF (1, "[%p] Interrupting %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2746 /* This is _not_ equivalent to mono_thread_internal_abort () */
2747 InterruptData interrupt_data = { 0 };
2748 interrupt_data.tls = tls;
2750 mono_thread_info_safe_suspend_and_run ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE, debugger_interrupt_critical, &interrupt_data);
2751 if (!interrupt_data.valid_info) {
2752 DEBUG_PRINTF (1, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2754 * Attached thread which died without detaching.
2756 tls->terminated = TRUE;
2761 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2763 guint8 *ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
2767 if (mono_loader_lock_is_owned_by_self ()) {
2769 * Shortcut for the check in suspend_current (). This speeds up processing
2770 * when executing long running code inside the loader lock, i.e. assembly load
2776 if (is_debugger_thread ())
2779 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2780 if (suspend_count - tls->resume_count > 0)
2781 tls->suspending = TRUE;
2783 DEBUG_PRINTF (1, "[%p] Received single step event for suspending.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2785 if (suspend_count - tls->resume_count == 0) {
2787 * We are executing a single threaded invoke but the single step for
2788 * suspending is still active.
2789 * FIXME: This slows down single threaded invokes.
2791 DEBUG_PRINTF (1, "[%p] Ignored during single threaded invoke.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2795 ji = get_top_method_ji (ip, NULL, NULL);
2797 /* Can't suspend in these methods */
2798 method = jinfo_get_method (ji);
2799 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2802 save_thread_context (ctx);
2810 * Increase the suspend count of the VM. While the suspend count is greater
2811 * than 0, runtime threads are suspended at certain points during execution.
2816 mono_loader_lock ();
2818 mono_coop_mutex_lock (&suspend_mutex);
2822 DEBUG_PRINTF (1, "[%p] Suspending vm...\n", (gpointer) (gsize) mono_native_thread_id_get ());
2824 if (suspend_count == 1) {
2825 // FIXME: Is it safe to call this inside the lock ?
2826 start_single_stepping ();
2827 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2830 mono_coop_mutex_unlock (&suspend_mutex);
2832 if (suspend_count == 1)
2834 * Suspend creation of new threadpool threads, since they cannot run
2836 mono_threadpool_suspend ();
2838 mono_loader_unlock ();
2844 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2850 g_assert (is_debugger_thread ());
2852 mono_loader_lock ();
2854 mono_coop_mutex_lock (&suspend_mutex);
2856 g_assert (suspend_count > 0);
2859 DEBUG_PRINTF (1, "[%p] Resuming vm, suspend count=%d...\n", (gpointer) (gsize) mono_native_thread_id_get (), suspend_count);
2861 if (suspend_count == 0) {
2862 // FIXME: Is it safe to call this inside the lock ?
2863 stop_single_stepping ();
2864 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2867 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2868 mono_coop_cond_broadcast (&suspend_cond);
2870 mono_coop_mutex_unlock (&suspend_mutex);
2871 //g_assert (err == 0);
2873 if (suspend_count == 0)
2874 mono_threadpool_resume ();
2876 mono_loader_unlock ();
2882 * Resume just one thread.
2885 resume_thread (MonoInternalThread *thread)
2887 DebuggerTlsData *tls;
2889 g_assert (is_debugger_thread ());
2891 mono_loader_lock ();
2893 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
2896 mono_coop_mutex_lock (&suspend_mutex);
2898 g_assert (suspend_count > 0);
2900 DEBUG_PRINTF (1, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid);
2902 tls->resume_count += suspend_count;
2905 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2906 * but only the one whose resume_count field is > 0 will be resumed.
2908 mono_coop_cond_broadcast (&suspend_cond);
2910 mono_coop_mutex_unlock (&suspend_mutex);
2911 //g_assert (err == 0);
2913 mono_loader_unlock ();
2917 free_frames (StackFrame **frames, int nframes)
2921 for (i = 0; i < nframes; ++i) {
2922 if (frames [i]->jit)
2923 mono_debug_free_method_jit_info (frames [i]->jit);
2924 g_free (frames [i]);
2930 invalidate_frames (DebuggerTlsData *tls)
2933 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2936 free_frames (tls->frames, tls->frame_count);
2937 tls->frame_count = 0;
2940 free_frames (tls->restore_frames, tls->restore_frame_count);
2941 tls->restore_frame_count = 0;
2942 tls->restore_frames = NULL;
2948 * Suspend the current thread until the runtime is resumed. If the thread has a
2949 * pending invoke, then the invoke is executed before this function returns.
2952 suspend_current (void)
2954 DebuggerTlsData *tls;
2956 g_assert (!is_debugger_thread ());
2958 if (mono_loader_lock_is_owned_by_self ()) {
2960 * If we own the loader mutex, can't suspend until we release it, since the
2961 * whole runtime can deadlock otherwise.
2966 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2969 mono_coop_mutex_lock (&suspend_mutex);
2971 tls->suspending = FALSE;
2972 tls->really_suspended = TRUE;
2974 if (!tls->suspended) {
2975 tls->suspended = TRUE;
2976 mono_coop_sem_post (&suspend_sem);
2979 DEBUG_PRINTF (1, "[%p] Suspended.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2981 while (suspend_count - tls->resume_count > 0) {
2982 mono_coop_cond_wait (&suspend_cond, &suspend_mutex);
2985 tls->suspended = FALSE;
2986 tls->really_suspended = FALSE;
2988 threads_suspend_count --;
2990 mono_coop_mutex_unlock (&suspend_mutex);
2992 DEBUG_PRINTF (1, "[%p] Resumed.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2994 if (tls->pending_invoke) {
2995 /* Save the original context */
2996 tls->pending_invoke->has_ctx = TRUE;
2997 tls->pending_invoke->ctx = tls->context.ctx;
3002 /* The frame info becomes invalid after a resume */
3003 tls->context.valid = FALSE;
3004 tls->async_state.valid = FALSE;
3005 invalidate_frames (tls);
3009 count_thread (gpointer key, gpointer value, gpointer user_data)
3011 DebuggerTlsData *tls = (DebuggerTlsData *)value;
3013 if (!tls->suspended && !tls->terminated && !mono_thread_internal_is_current (tls->thread))
3014 *(int*)user_data = *(int*)user_data + 1;
3018 count_threads_to_wait_for (void)
3022 mono_loader_lock ();
3023 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
3024 mono_loader_unlock ();
3032 * Wait until the runtime is completely suspended.
3035 wait_for_suspend (void)
3037 int nthreads, nwait, err;
3038 gboolean waited = FALSE;
3040 // FIXME: Threads starting/stopping ?
3041 mono_loader_lock ();
3042 nthreads = mono_g_hash_table_size (thread_to_tls);
3043 mono_loader_unlock ();
3046 nwait = count_threads_to_wait_for ();
3048 DEBUG_PRINTF (1, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads);
3049 err = mono_coop_sem_wait (&suspend_sem, MONO_SEM_FLAGS_NONE);
3050 g_assert (err == 0);
3058 DEBUG_PRINTF (1, "%d threads suspended.\n", nthreads);
3064 * Return whenever the runtime is suspended.
3069 return count_threads_to_wait_for () == 0;
3073 no_seq_points_found (MonoMethod *method, int offset)
3076 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3078 printf ("Unable to find seq points for method '%s', offset 0x%x.\n", mono_method_full_name (method, TRUE), offset);
3082 DebuggerTlsData *tls;
3084 } ComputeFramesUserData;
3087 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3089 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3091 MonoMethod *method, *actual_method, *api_method;
3095 if (info->type != FRAME_TYPE_MANAGED && info->type != FRAME_TYPE_INTERP) {
3096 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3097 /* Mark the last frame as an invoke frame */
3099 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3105 method = jinfo_get_method (info->ji);
3107 method = info->method;
3108 actual_method = info->actual_method;
3109 api_method = method;
3114 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3117 if (info->il_offset == -1) {
3118 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3119 if (ud->frames == NULL) {
3120 if (mono_find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL, &sp))
3121 info->il_offset = sp.il_offset;
3123 if (info->il_offset == -1)
3124 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3127 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);
3129 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3130 if (!CHECK_PROTOCOL_VERSION (2, 17))
3131 /* Older clients can't handle this flag */
3133 api_method = mono_marshal_method_from_wrapper (method);
3136 actual_method = api_method;
3137 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3140 frame = g_new0 (StackFrame, 1);
3141 frame->method = method;
3142 frame->actual_method = actual_method;
3143 frame->api_method = api_method;
3144 frame->il_offset = info->il_offset;
3145 frame->native_offset = info->native_offset;
3146 frame->flags = flags;
3147 frame->ji = info->ji;
3148 frame->interp_frame = info->interp_frame;
3149 if (info->reg_locations)
3150 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3153 frame->has_ctx = TRUE;
3155 frame->domain = info->domain;
3157 ud->frames = g_slist_append (ud->frames, frame);
3163 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3165 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3168 * 'tls->filter_ctx' is the location of the throw site.
3170 * mono_walk_stack() will never actually hit the throw site, but unwind
3171 * directly from the filter to the call site; we abort stack unwinding here
3172 * once this happens and resume from the throw site.
3175 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3178 return process_frame (info, ctx, user_data);
3182 * Return a malloc-ed list of StackFrame structures.
3185 compute_frame_info_from (MonoInternalThread *thread, DebuggerTlsData *tls, MonoThreadUnwindState *state, int *out_nframes)
3187 ComputeFramesUserData user_data;
3188 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3193 user_data.tls = tls;
3194 user_data.frames = NULL;
3196 mono_walk_stack_with_state (process_frame, state, opts, &user_data);
3198 nframes = g_slist_length (user_data.frames);
3199 res = g_new0 (StackFrame*, nframes);
3200 l = user_data.frames;
3201 for (i = 0; i < nframes; ++i) {
3202 res [i] = (StackFrame *)l->data;
3205 *out_nframes = nframes;
3211 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3213 ComputeFramesUserData user_data;
3215 int i, findex, new_frame_count;
3216 StackFrame **new_frames, *f;
3217 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3219 // FIXME: Locking on tls
3220 if (tls->frames && tls->frames_up_to_date)
3223 DEBUG_PRINTF (1, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid);
3225 user_data.tls = tls;
3226 user_data.frames = NULL;
3227 if (tls->terminated) {
3228 tls->frame_count = 0;
3230 } if (!tls->really_suspended && tls->async_state.valid) {
3231 /* Have to use the state saved by the signal handler */
3232 process_frame (&tls->async_last_frame, NULL, &user_data);
3233 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3234 } else if (tls->filter_state.valid) {
3236 * We are inside an exception filter.
3238 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3240 if (tls->context.valid)
3241 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3243 * After that, we resume unwinding from the location where the exception has been thrown.
3245 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3246 } else if (tls->context.valid) {
3247 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3250 tls->frame_count = 0;
3254 new_frame_count = g_slist_length (user_data.frames);
3255 new_frames = g_new0 (StackFrame*, new_frame_count);
3257 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3258 f = (StackFrame *)tmp->data;
3261 * Reuse the id for already existing stack frames, so invokes don't invalidate
3262 * the still valid stack frames.
3264 for (i = 0; i < tls->frame_count; ++i) {
3265 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3266 f->id = tls->frames [i]->id;
3271 if (i >= tls->frame_count)
3272 f->id = InterlockedIncrement (&frame_id);
3274 new_frames [findex ++] = f;
3277 g_slist_free (user_data.frames);
3279 invalidate_frames (tls);
3281 tls->frames = new_frames;
3282 tls->frame_count = new_frame_count;
3283 tls->frames_up_to_date = TRUE;
3287 * GHFunc to emit an appdomain creation event
3288 * @param key Don't care
3289 * @param value A loaded appdomain
3290 * @param user_data Don't care
3293 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3295 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3296 g_hash_table_foreach (get_agent_domain_info ((MonoDomain *)value)->loaded_classes, emit_type_load, NULL);
3300 * GHFunc to emit a thread start event
3301 * @param key A thread id
3302 * @param value A thread object
3303 * @param user_data Don't care
3306 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3308 g_assert (!mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (GPOINTER_TO_UINT (key)), debugger_thread_id));
3309 process_profiler_event (EVENT_KIND_THREAD_START, value);
3313 * GFunc to emit an assembly load event
3314 * @param value A loaded assembly
3315 * @param user_data Don't care
3318 emit_assembly_load (gpointer value, gpointer user_data)
3320 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3324 * GFunc to emit a type load event
3325 * @param value A loaded type
3326 * @param user_data Don't care
3329 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3331 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3335 strdup_tolower (char *s)
3340 for (p = s2; *p; ++p)
3346 * Same as g_path_get_basename () but handles windows paths as well,
3347 * which can occur in .mdb files created by pdb2mdb.
3350 dbg_path_get_basename (const char *filename)
3354 if (!filename || strchr (filename, '/') || !strchr (filename, '\\'))
3355 return g_path_get_basename (filename);
3359 /* No separator -> filename */
3360 r = strrchr (filename, '\\');
3362 return g_strdup (filename);
3364 /* Trailing slash, remove component */
3366 char *copy = g_strdup (filename);
3367 copy [r-filename] = 0;
3368 r = strrchr (copy, '\\');
3372 return g_strdup ("/");
3374 r = g_strdup (&r[1]);
3379 return g_strdup (&r[1]);
3383 init_jit_info_dbg_attrs (MonoJitInfo *ji)
3385 static MonoClass *hidden_klass, *step_through_klass, *non_user_klass;
3387 MonoCustomAttrInfo *ainfo;
3389 if (ji->dbg_attrs_inited)
3393 hidden_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3395 if (!step_through_klass)
3396 step_through_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3398 if (!non_user_klass)
3399 non_user_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute");
3401 ainfo = mono_custom_attrs_from_method_checked (jinfo_get_method (ji), &error);
3402 mono_error_cleanup (&error); /* FIXME don't swallow the error? */
3404 if (mono_custom_attrs_has_attr (ainfo, hidden_klass))
3405 ji->dbg_hidden = TRUE;
3406 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3407 ji->dbg_step_through = TRUE;
3408 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3409 ji->dbg_non_user_code = TRUE;
3410 mono_custom_attrs_free (ainfo);
3413 ainfo = mono_custom_attrs_from_class_checked (jinfo_get_method (ji)->klass, &error);
3414 mono_error_cleanup (&error); /* FIXME don't swallow the error? */
3416 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3417 ji->dbg_step_through = TRUE;
3418 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3419 ji->dbg_non_user_code = TRUE;
3420 mono_custom_attrs_free (ainfo);
3423 mono_memory_barrier ();
3424 ji->dbg_attrs_inited = TRUE;
3432 * create_event_list:
3434 * Return a list of event request ids matching EVENT, starting from REQS, which
3435 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3437 * We return request ids, instead of requests, to simplify threading, since
3438 * requests could be deleted anytime when the loader lock is not held.
3439 * LOCKING: Assumes the loader lock is held.
3442 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3445 GSList *events = NULL;
3447 *suspend_policy = SUSPEND_POLICY_NONE;
3450 reqs = event_requests;
3455 for (i = 0; i < reqs->len; ++i) {
3456 EventRequest *req = (EventRequest *)g_ptr_array_index (reqs, i);
3457 if (req->event_kind == event) {
3458 gboolean filtered = FALSE;
3461 for (j = 0; j < req->nmodifiers; ++j) {
3462 Modifier *mod = &req->modifiers [j];
3464 if (mod->kind == MOD_KIND_COUNT) {
3466 if (mod->data.count > 0) {
3467 if (mod->data.count > 0) {
3469 if (mod->data.count == 0)
3473 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3474 if (mod->data.thread != mono_thread_internal_current ())
3476 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3477 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3479 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3481 if (ei->caught && !mod->caught)
3483 if (!ei->caught && !mod->uncaught)
3485 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3487 gboolean found = FALSE;
3488 MonoAssembly **assemblies = mod->data.assemblies;
3491 for (k = 0; assemblies [k]; ++k)
3492 if (assemblies [k] == jinfo_get_method (ji)->klass->image->assembly)
3497 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3498 gpointer iter = NULL;
3500 MonoDebugSourceInfo *sinfo;
3501 char *source_file, *s;
3502 gboolean found = FALSE;
3504 GPtrArray *source_file_list;
3506 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3507 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3510 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, NULL, NULL, NULL);
3511 for (i = 0; i < source_file_list->len; ++i) {
3512 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
3514 * Do a case-insesitive match by converting the file name to
3517 s = strdup_tolower (sinfo->source_file);
3518 if (g_hash_table_lookup (mod->data.source_files, s))
3521 char *s2 = dbg_path_get_basename (sinfo->source_file);
3522 char *s3 = strdup_tolower (s2);
3524 if (g_hash_table_lookup (mod->data.source_files, s3))
3531 g_ptr_array_free (source_file_list, TRUE);
3536 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3539 s = mono_type_full_name (&ei->klass->byval_arg);
3540 if (!g_hash_table_lookup (mod->data.type_names, s))
3543 } else if (mod->kind == MOD_KIND_STEP) {
3544 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3545 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3546 !strcmp (jinfo_get_method (ji)->name, ".cctor") &&
3547 (jinfo_get_method (ji) != ((SingleStepReq*)req->info)->start_method))
3549 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3550 init_jit_info_dbg_attrs (ji);
3554 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3555 init_jit_info_dbg_attrs (ji);
3556 if (ji->dbg_step_through)
3559 if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3560 init_jit_info_dbg_attrs (ji);
3561 if (ji->dbg_non_user_code)
3568 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3569 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3574 /* Send a VM START/DEATH event by default */
3575 if (event == EVENT_KIND_VM_START)
3576 events = g_slist_append (events, GINT_TO_POINTER (0));
3577 if (event == EVENT_KIND_VM_DEATH)
3578 events = g_slist_append (events, GINT_TO_POINTER (0));
3583 static G_GNUC_UNUSED const char*
3584 event_to_string (EventKind event)
3587 case EVENT_KIND_VM_START: return "VM_START";
3588 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3589 case EVENT_KIND_THREAD_START: return "THREAD_START";
3590 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3591 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3592 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3593 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3594 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3595 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3596 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3597 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3598 case EVENT_KIND_STEP: return "STEP";
3599 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3600 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3601 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3602 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3603 case EVENT_KIND_USER_LOG: return "USER_LOG";
3605 g_assert_not_reached ();
3613 * Send an event to the client, suspending the vm if needed.
3614 * LOCKING: Since this can suspend the calling thread, no locks should be held
3616 * The EVENTS list is freed by this function.
3619 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3623 MonoDomain *domain = mono_domain_get ();
3624 MonoThread *thread = NULL;
3625 MonoObject *keepalive_obj = NULL;
3626 gboolean send_success = FALSE;
3631 DEBUG_PRINTF (2, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event));
3635 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3636 // FIXME: We miss those events
3637 DEBUG_PRINTF (2, "VM start event not sent yet: dropping %s\n", event_to_string (event));
3641 if (vm_death_event_sent) {
3642 DEBUG_PRINTF (2, "VM death event has been sent: dropping %s\n", event_to_string (event));
3646 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3647 DEBUG_PRINTF (2, "Mono runtime is shutting down: dropping %s\n", event_to_string (event));
3652 DEBUG_PRINTF (2, "Debugger client is not connected: dropping %s\n", event_to_string (event));
3656 if (event == EVENT_KIND_KEEPALIVE)
3657 suspend_policy = SUSPEND_POLICY_NONE;
3662 if (agent_config.defer) {
3663 /* Make sure the thread id is always set when doing deferred debugging */
3664 if (is_debugger_thread ()) {
3665 /* Don't suspend on events from the debugger thread */
3666 suspend_policy = SUSPEND_POLICY_NONE;
3667 thread = mono_thread_get_main ();
3669 else thread = mono_thread_current ();
3671 if (is_debugger_thread () && event != EVENT_KIND_VM_DEATH)
3672 // FIXME: Send these with a NULL thread, don't suspend the current thread
3677 nevents = g_slist_length (events);
3678 buffer_init (&buf, 128);
3679 buffer_add_byte (&buf, suspend_policy);
3680 buffer_add_int (&buf, nevents);
3682 for (l = events; l; l = l->next) {
3683 buffer_add_byte (&buf, event); // event kind
3684 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3688 if (event == EVENT_KIND_VM_DEATH) {
3692 thread = mono_thread_current ();
3694 if (event == EVENT_KIND_VM_START && arg != NULL)
3695 thread = (MonoThread *)arg;
3698 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3701 case EVENT_KIND_THREAD_START:
3702 case EVENT_KIND_THREAD_DEATH:
3704 case EVENT_KIND_APPDOMAIN_CREATE:
3705 case EVENT_KIND_APPDOMAIN_UNLOAD:
3706 buffer_add_domainid (&buf, (MonoDomain *)arg);
3708 case EVENT_KIND_METHOD_ENTRY:
3709 case EVENT_KIND_METHOD_EXIT:
3710 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3712 case EVENT_KIND_ASSEMBLY_LOAD:
3713 buffer_add_assemblyid (&buf, domain, (MonoAssembly *)arg);
3715 case EVENT_KIND_ASSEMBLY_UNLOAD: {
3716 DebuggerTlsData *tls;
3718 /* The domain the assembly belonged to is not equal to the current domain */
3719 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3721 g_assert (tls->domain_unloading);
3723 buffer_add_assemblyid (&buf, tls->domain_unloading, (MonoAssembly *)arg);
3726 case EVENT_KIND_TYPE_LOAD:
3727 buffer_add_typeid (&buf, domain, (MonoClass *)arg);
3729 case EVENT_KIND_BREAKPOINT:
3730 case EVENT_KIND_STEP:
3731 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3732 buffer_add_long (&buf, il_offset);
3734 case EVENT_KIND_VM_START:
3735 buffer_add_domainid (&buf, mono_get_root_domain ());
3737 case EVENT_KIND_VM_DEATH:
3738 if (CHECK_PROTOCOL_VERSION (2, 27))
3739 buffer_add_int (&buf, mono_environment_exitcode_get ());
3741 case EVENT_KIND_EXCEPTION: {
3742 EventInfo *ei = (EventInfo *)arg;
3743 buffer_add_objid (&buf, ei->exc);
3745 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3746 * later after the suspension. (#12494).
3748 keepalive_obj = ei->exc;
3751 case EVENT_KIND_USER_BREAK:
3753 case EVENT_KIND_USER_LOG: {
3754 EventInfo *ei = (EventInfo *)arg;
3755 buffer_add_int (&buf, ei->level);
3756 buffer_add_string (&buf, ei->category ? ei->category : "");
3757 buffer_add_string (&buf, ei->message ? ei->message : "");
3760 case EVENT_KIND_KEEPALIVE:
3761 suspend_policy = SUSPEND_POLICY_NONE;
3764 g_assert_not_reached ();
3768 if (event == EVENT_KIND_VM_START) {
3769 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3770 if (!agent_config.defer)
3771 start_debugger_thread ();
3774 if (event == EVENT_KIND_VM_DEATH) {
3775 vm_death_event_sent = TRUE;
3776 suspend_policy = SUSPEND_POLICY_NONE;
3779 if (mono_runtime_is_shutting_down ())
3780 suspend_policy = SUSPEND_POLICY_NONE;
3782 if (suspend_policy != SUSPEND_POLICY_NONE) {
3784 * Save the thread context and start suspending before sending the packet,
3785 * since we could be receiving the resume request before send_packet ()
3788 save_thread_context (ctx);
3792 /* This will keep this object alive */
3793 get_objref (keepalive_obj);
3796 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3800 g_slist_free (events);
3803 if (!send_success) {
3804 DEBUG_PRINTF (2, "Sending command %s failed.\n", event_to_string (event));
3808 if (event == EVENT_KIND_VM_START) {
3809 vm_start_event_sent = TRUE;
3812 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);
3814 switch (suspend_policy) {
3815 case SUSPEND_POLICY_NONE:
3817 case SUSPEND_POLICY_ALL:
3820 case SUSPEND_POLICY_EVENT_THREAD:
3824 g_assert_not_reached ();
3829 process_profiler_event (EventKind event, gpointer arg)
3833 EventInfo ei, *ei_arg = NULL;
3835 if (event == EVENT_KIND_TYPE_LOAD) {
3836 ei.klass = (MonoClass *)arg;
3840 mono_loader_lock ();
3841 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3842 mono_loader_unlock ();
3844 process_event (event, arg, 0, NULL, events, suspend_policy);
3848 runtime_initialized (MonoProfiler *prof)
3850 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3851 if (agent_config.defer)
3852 start_debugger_thread ();
3856 runtime_shutdown (MonoProfiler *prof)
3858 process_profiler_event (EVENT_KIND_VM_DEATH, NULL);
3860 mono_debugger_agent_cleanup ();
3864 thread_startup (MonoProfiler *prof, uintptr_t tid)
3866 MonoInternalThread *thread = mono_thread_internal_current ();
3867 MonoInternalThread *old_thread;
3868 DebuggerTlsData *tls;
3870 if (is_debugger_thread ())
3873 g_assert (mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (tid), MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid)));
3875 mono_loader_lock ();
3876 old_thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3877 mono_loader_unlock ();
3879 if (thread == old_thread) {
3881 * For some reason, thread_startup () might be called for the same thread
3882 * multiple times (attach ?).
3884 DEBUG_PRINTF (1, "[%p] thread_start () called multiple times for %p, ignored.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3888 * thread_end () might not be called for some threads, and the tid could
3891 DEBUG_PRINTF (1, "[%p] Removing stale data for tid %p.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3892 mono_loader_lock ();
3893 mono_g_hash_table_remove (thread_to_tls, old_thread);
3894 mono_g_hash_table_remove (tid_to_thread, GUINT_TO_POINTER (tid));
3895 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3896 mono_loader_unlock ();
3900 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3902 // FIXME: Free this somewhere
3903 tls = g_new0 (DebuggerTlsData, 1);
3904 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread, MONO_ROOT_SOURCE_DEBUGGER, "debugger thread reference");
3905 tls->thread = thread;
3906 mono_native_tls_set_value (debugger_tls_id, tls);
3908 DEBUG_PRINTF (1, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3910 mono_loader_lock ();
3911 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3912 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3913 mono_g_hash_table_insert (tid_to_thread_obj, GUINT_TO_POINTER (tid), mono_thread_current ());
3914 mono_loader_unlock ();
3916 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3919 * suspend_vm () could have missed this thread, so wait for a resume.
3925 thread_end (MonoProfiler *prof, uintptr_t tid)
3927 MonoInternalThread *thread;
3928 DebuggerTlsData *tls = NULL;
3930 mono_loader_lock ();
3931 thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3933 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3934 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
3936 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3937 tls->terminated = TRUE;
3938 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3939 MONO_GC_UNREGISTER_ROOT (tls->thread);
3943 mono_loader_unlock ();
3945 /* We might be called for threads started before we registered the start callback */
3947 DEBUG_PRINTF (1, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3949 if (mono_thread_internal_is_current (thread) && !mono_native_tls_get_value (debugger_tls_id)
3952 * This can happen on darwin since we deregister threads using pthread dtors.
3953 * process_profiler_event () and the code it calls cannot handle a null TLS value.
3958 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3963 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3965 mono_loader_lock ();
3966 g_hash_table_insert (domains, domain, domain);
3967 mono_loader_unlock ();
3969 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3973 appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain)
3975 DebuggerTlsData *tls;
3977 /* This might be called during shutdown on the debugger thread from the CMD_VM_EXIT code */
3978 if (is_debugger_thread ())
3982 * Remember the currently unloading appdomain as it is needed to generate
3983 * proper ids for unloading assemblies.
3985 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3987 tls->domain_unloading = domain;
3991 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3993 DebuggerTlsData *tls;
3995 if (is_debugger_thread ())
3998 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4000 tls->domain_unloading = NULL;
4002 clear_breakpoints_for_domain (domain);
4004 mono_loader_lock ();
4005 /* Invalidate each thread's frame stack */
4006 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
4007 mono_loader_unlock ();
4009 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
4013 * invalidate_each_thread:
4015 * A GHFunc to invalidate frames.
4016 * value must be a DebuggerTlsData*
4019 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
4021 invalidate_frames ((DebuggerTlsData *)value);
4025 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
4027 /* Sent later in jit_end () */
4029 g_ptr_array_add (pending_assembly_loads, assembly);
4034 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
4036 if (is_debugger_thread ())
4039 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
4041 clear_event_requests_for_assembly (assembly);
4042 clear_types_for_assembly (assembly);
4046 send_type_load (MonoClass *klass)
4048 gboolean type_load = FALSE;
4049 MonoDomain *domain = mono_domain_get ();
4050 AgentDomainInfo *info = NULL;
4052 info = get_agent_domain_info (domain);
4054 mono_loader_lock ();
4056 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
4058 g_hash_table_insert (info->loaded_classes, klass, klass);
4061 mono_loader_unlock ();
4064 emit_type_load (klass, klass, NULL);
4068 * Emit load events for all types currently loaded in the domain.
4069 * Takes the loader and domain locks.
4070 * user_data is unused.
4073 send_types_for_domain (MonoDomain *domain, void *user_data)
4075 MonoDomain* old_domain;
4076 AgentDomainInfo *info = NULL;
4078 info = get_agent_domain_info (domain);
4081 old_domain = mono_domain_get ();
4083 mono_domain_set (domain, TRUE);
4085 mono_loader_lock ();
4086 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4087 mono_loader_unlock ();
4089 mono_domain_set (old_domain, TRUE);
4093 send_assemblies_for_domain (MonoDomain *domain, void *user_data)
4096 MonoDomain* old_domain;
4098 old_domain = mono_domain_get ();
4100 mono_domain_set (domain, TRUE);
4102 mono_domain_assemblies_lock (domain);
4103 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
4104 MonoAssembly* ass = (MonoAssembly *)tmp->data;
4105 emit_assembly_load (ass, NULL);
4107 mono_domain_assemblies_unlock (domain);
4109 mono_domain_set (old_domain, TRUE);
4113 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
4116 * We emit type load events when the first method of the type is JITted,
4117 * since the class load profiler callbacks might be called with the
4118 * loader lock held. They could also occur in the debugger thread.
4119 * Same for assembly load events.
4122 MonoAssembly *assembly = NULL;
4124 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4126 if (pending_assembly_loads->len > 0) {
4127 assembly = (MonoAssembly *)g_ptr_array_index (pending_assembly_loads, 0);
4128 g_ptr_array_remove_index (pending_assembly_loads, 0);
4133 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4139 send_type_load (method->klass);
4141 if (!result && jinfo)
4142 add_pending_breakpoints (method, jinfo);
4146 * BREAKPOINTS/SINGLE STEPPING
4150 * Contains information about an inserted breakpoint.
4153 long il_offset, native_offset;
4157 } BreakpointInstance;
4160 * Contains generic information about a breakpoint.
4164 * The method where the breakpoint is placed. Can be NULL in which case it
4165 * is inserted into every method. This is used to implement method entry/
4166 * exit events. Can be a generic method definition, in which case the
4167 * breakpoint is inserted into every instance.
4173 * A list of BreakpointInstance structures describing where the breakpoint
4174 * was inserted. There could be more than one because of
4175 * generics/appdomains/method entry/exit.
4177 GPtrArray *children;
4180 /* List of breakpoints */
4181 /* Protected by the loader lock */
4182 static GPtrArray *breakpoints;
4183 /* Maps breakpoint locations to the number of breakpoints at that location */
4184 static GHashTable *bp_locs;
4187 breakpoints_init (void)
4189 breakpoints = g_ptr_array_new ();
4190 bp_locs = g_hash_table_new (NULL, NULL);
4194 * insert_breakpoint:
4196 * Insert the breakpoint described by BP into the method described by
4200 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4203 BreakpointInstance *inst;
4204 SeqPointIterator it;
4205 gboolean it_has_sp = FALSE;
4210 mono_seq_point_iterator_init (&it, seq_points);
4211 while (mono_seq_point_iterator_next (&it)) {
4212 if (it.seq_point.il_offset == bp->il_offset) {
4220 * The set of IL offsets with seq points doesn't completely match the
4221 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4223 mono_seq_point_iterator_init (&it, seq_points);
4224 while (mono_seq_point_iterator_next (&it)) {
4225 if (it.seq_point.il_offset != METHOD_ENTRY_IL_OFFSET &&
4226 it.seq_point.il_offset != METHOD_EXIT_IL_OFFSET &&
4227 it.seq_point.il_offset + 1 == bp->il_offset) {
4235 char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d", mono_method_full_name (jinfo_get_method (ji), TRUE), bp->il_offset);
4237 mono_seq_point_iterator_init (&it, seq_points);
4238 while (mono_seq_point_iterator_next (&it))
4239 DEBUG_PRINTF (1, "%d\n", it.seq_point.il_offset);
4242 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4243 g_warning ("%s", s);
4247 g_warning ("%s", s);
4253 inst = g_new0 (BreakpointInstance, 1);
4254 inst->il_offset = it.seq_point.il_offset;
4255 inst->native_offset = it.seq_point.native_offset;
4256 inst->ip = (guint8*)ji->code_start + it.seq_point.native_offset;
4258 inst->domain = domain;
4260 mono_loader_lock ();
4262 g_ptr_array_add (bp->children, inst);
4264 mono_loader_unlock ();
4267 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4268 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4271 if (it.seq_point.native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4272 DEBUG_PRINTF (1, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset);
4273 } else if (count == 0) {
4274 if (ji->is_interp) {
4275 mono_interp_set_breakpoint (ji, inst->ip);
4277 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4278 mono_arch_set_breakpoint (ji, inst->ip);
4285 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);
4289 remove_breakpoint (BreakpointInstance *inst)
4291 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4293 MonoJitInfo *ji = inst->ji;
4294 guint8 *ip = inst->ip;
4297 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4298 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4301 g_assert (count > 0);
4303 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4305 mono_interp_clear_breakpoint (ji, ip);
4307 mono_arch_clear_breakpoint (ji, ip);
4308 DEBUG_PRINTF (1, "[dbg] Clear breakpoint at %s [%p].\n", mono_method_full_name (jinfo_get_method (ji), TRUE), ip);
4316 * This doesn't take any locks.
4318 static inline gboolean
4319 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4325 if (method == bp->method)
4327 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4330 if (bp->method->is_inflated && method->is_inflated) {
4331 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4332 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4334 /* Open generic methods should match closed generic methods of the same class */
4335 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4336 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4337 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4339 /* FIXME: Handle !mvar */
4340 if (t1->type != MONO_TYPE_MVAR)
4351 * add_pending_breakpoints:
4353 * Insert pending breakpoints into the newly JITted method METHOD.
4356 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4359 MonoSeqPointInfo *seq_points;
4361 MonoMethod *jmethod;
4366 domain = mono_domain_get ();
4368 mono_loader_lock ();
4370 for (i = 0; i < breakpoints->len; ++i) {
4371 MonoBreakpoint *bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4372 gboolean found = FALSE;
4374 if (!bp_matches_method (bp, method))
4377 for (j = 0; j < bp->children->len; ++j) {
4378 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4385 MonoMethod *declaring = NULL;
4387 jmethod = jinfo_get_method (ji);
4388 if (jmethod->is_inflated)
4389 declaring = mono_method_get_declaring_generic_method (jmethod);
4391 mono_domain_lock (domain);
4392 seq_points = (MonoSeqPointInfo *)g_hash_table_lookup (domain_jit_info (domain)->seq_points, jmethod);
4393 if (!seq_points && declaring)
4394 seq_points = (MonoSeqPointInfo *)g_hash_table_lookup (domain_jit_info (domain)->seq_points, declaring);
4395 mono_domain_unlock (domain);
4397 /* Could be AOT code */
4399 g_assert (seq_points);
4401 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4405 mono_loader_unlock ();
4409 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4417 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4421 /* Might be AOTed code */
4422 mono_class_init (method->klass);
4423 code = mono_aot_get_method_checked (domain, method, &oerror);
4425 mono_error_assert_ok (&oerror);
4426 ji = mono_jit_info_table_find (domain, (char *)code);
4428 /* Might be interpreted */
4429 ji = mono_interp_find_jit_info (domain, method);
4434 insert_breakpoint (seq_points, domain, ji, bp, error);
4438 clear_breakpoint (MonoBreakpoint *bp);
4443 * Set a breakpoint at IL_OFFSET in METHOD.
4444 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4445 * METHOD can also be a generic method definition, in which case a breakpoint
4446 * is placed in all instances of the method.
4447 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4450 static MonoBreakpoint*
4451 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4454 GHashTableIter iter, iter2;
4457 MonoSeqPointInfo *seq_points;
4459 GPtrArray *method_domains;
4460 GPtrArray *method_seq_points;
4467 // - suspend/resume the vm to prevent code patching problems
4468 // - multiple breakpoints on the same location
4469 // - dynamic methods
4472 bp = g_new0 (MonoBreakpoint, 1);
4473 bp->method = method;
4474 bp->il_offset = il_offset;
4476 bp->children = g_ptr_array_new ();
4478 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);
4480 methods = g_ptr_array_new ();
4481 method_domains = g_ptr_array_new ();
4482 method_seq_points = g_ptr_array_new ();
4484 mono_loader_lock ();
4485 g_hash_table_iter_init (&iter, domains);
4486 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4487 mono_domain_lock (domain);
4488 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4489 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4490 if (bp_matches_method (bp, m)) {
4491 /* Save the info locally to simplify the code inside the domain lock */
4492 g_ptr_array_add (methods, m);
4493 g_ptr_array_add (method_domains, domain);
4494 g_ptr_array_add (method_seq_points, seq_points);
4497 mono_domain_unlock (domain);
4500 for (i = 0; i < methods->len; ++i) {
4501 m = (MonoMethod *)g_ptr_array_index (methods, i);
4502 domain = (MonoDomain *)g_ptr_array_index (method_domains, i);
4503 seq_points = (MonoSeqPointInfo *)g_ptr_array_index (method_seq_points, i);
4504 set_bp_in_method (domain, m, seq_points, bp, error);
4507 g_ptr_array_add (breakpoints, bp);
4508 mono_loader_unlock ();
4510 g_ptr_array_free (methods, TRUE);
4511 g_ptr_array_free (method_domains, TRUE);
4512 g_ptr_array_free (method_seq_points, TRUE);
4514 if (error && !mono_error_ok (error)) {
4515 clear_breakpoint (bp);
4523 clear_breakpoint (MonoBreakpoint *bp)
4527 // FIXME: locking, races
4528 for (i = 0; i < bp->children->len; ++i) {
4529 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, i);
4531 remove_breakpoint (inst);
4536 mono_loader_lock ();
4537 g_ptr_array_remove (breakpoints, bp);
4538 mono_loader_unlock ();
4540 g_ptr_array_free (bp->children, TRUE);
4545 breakpoints_cleanup (void)
4549 mono_loader_lock ();
4551 while (i < event_requests->len) {
4552 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
4554 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4555 clear_breakpoint ((MonoBreakpoint *)req->info);
4556 g_ptr_array_remove_index_fast (event_requests, i);
4563 for (i = 0; i < breakpoints->len; ++i)
4564 g_free (g_ptr_array_index (breakpoints, i));
4566 g_ptr_array_free (breakpoints, TRUE);
4567 g_hash_table_destroy (bp_locs);
4572 mono_loader_unlock ();
4576 * clear_breakpoints_for_domain:
4578 * Clear breakpoint instances which reference DOMAIN.
4581 clear_breakpoints_for_domain (MonoDomain *domain)
4585 /* This could be called after shutdown */
4589 mono_loader_lock ();
4590 for (i = 0; i < breakpoints->len; ++i) {
4591 MonoBreakpoint *bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4594 while (j < bp->children->len) {
4595 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4597 if (inst->domain == domain) {
4598 remove_breakpoint (inst);
4602 g_ptr_array_remove_index_fast (bp->children, j);
4608 mono_loader_unlock ();
4612 * ss_calculate_framecount:
4614 * Ensure DebuggerTlsData fields are filled out.
4616 static void ss_calculate_framecount (DebuggerTlsData *tls, MonoContext *ctx)
4618 if (!tls->context.valid)
4619 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4620 compute_frame_info (tls->thread, tls);
4624 ensure_jit (StackFrame* frame)
4627 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
4628 if (!frame->jit && frame->api_method->is_inflated)
4629 frame->jit = mono_debug_find_method(mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
4633 /* This could happen for aot images with no jit debug info */
4634 s = mono_method_full_name (frame->api_method, TRUE);
4635 DEBUG_PRINTF(1, "[dbg] No debug information found for '%s'.\n", s);
4646 * Return FALSE if single stepping needs to continue.
4649 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp, DebuggerTlsData *tls, MonoContext *ctx, MonoMethod* method)
4651 MonoDebugMethodInfo *minfo;
4652 MonoDebugSourceLocation *loc = NULL;
4653 gboolean hit = TRUE;
4655 if (req->async_stepout_method == method) {
4656 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);
4660 if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK)) {
4662 * These seq points are inserted by the JIT after calls, step over needs to skip them.
4664 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);
4668 if ((req->depth == STEP_DEPTH_OVER || req->depth == STEP_DEPTH_OUT) && hit && !req->async_stepout_method) {
4669 gboolean is_step_out = req->depth == STEP_DEPTH_OUT;
4671 ss_calculate_framecount (tls, ctx);
4673 // Because functions can call themselves recursively, we need to make sure we're stopping at the right stack depth.
4674 // In case of step out, the target is the frame *enclosing* the one where the request was made.
4675 int target_frames = req->nframes + (is_step_out ? -1 : 0);
4676 if (req->nframes > 0 && tls->frame_count > 0 && tls->frame_count > target_frames) {
4677 /* Hit the breakpoint in a recursive call, don't halt */
4678 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");
4683 if (req->depth == STEP_DEPTH_INTO && req->size == STEP_SIZE_MIN && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) && ss_req->start_method){
4684 ss_calculate_framecount (tls, ctx);
4685 if (ss_req->start_method == method && req->nframes && tls->frame_count == req->nframes) {//Check also frame count(could be recursion)
4686 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);
4691 MonoDebugMethodAsyncInfo* async_method = mono_debug_lookup_method_async_debug_info (method);
4693 for (int i = 0; i < async_method->num_awaits; i++) {
4694 if (async_method->yield_offsets[i] == sp->il_offset || async_method->resume_offsets[i] == sp->il_offset) {
4695 mono_debug_free_method_async_debug_info (async_method);
4699 mono_debug_free_method_async_debug_info (async_method);
4702 if (req->size != STEP_SIZE_LINE)
4705 /* Have to check whenever a different source line was reached */
4706 minfo = mono_debug_lookup_method (method);
4709 loc = mono_debug_method_lookup_location (minfo, sp->il_offset);
4712 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);
4713 ss_req->last_method = method;
4715 } else if (loc && method == ss_req->last_method && loc->row == ss_req->last_line) {
4716 ss_calculate_framecount (tls, ctx);
4717 if (tls->frame_count == req->nframes) { // If the frame has changed we're clearly not on the same source line.
4718 DEBUG_PRINTF (1, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer) (gsize) mono_native_thread_id_get (), loc->row);
4724 ss_req->last_method = method;
4725 ss_req->last_line = loc->row;
4726 mono_debug_free_source_location (loc);
4733 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4735 return bp->method && bp->method->klass->image->assembly == assembly;
4739 get_this (StackFrame *frame)
4741 //Logic inspiered by "add_var" method and took out path that happens in async method for getting this
4742 MonoDebugVarInfo *var = frame->jit->this_var;
4743 if ((var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS) != MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET)
4746 guint8 * addr = (guint8 *)mono_arch_context_get_int_reg (&frame->ctx, var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS);
4747 addr += (gint32)var->offset;
4748 return *(MonoObject**)addr;
4751 //This ID is used to figure out if breakpoint hit on resumeOffset belongs to us or not
4752 //since thread probably changed...
4754 get_this_async_id (StackFrame *frame)
4756 return get_objid (get_this (frame));
4760 get_set_notification_method (MonoClass* async_builder_class)
4763 GPtrArray* array = mono_class_get_methods_by_name (async_builder_class, "SetNotificationForWaitCompletion", 0x24, FALSE, FALSE, &error);
4764 mono_error_assert_ok (&error);
4765 g_assert (array->len == 1);
4766 MonoMethod* set_notification_method = (MonoMethod *)g_ptr_array_index (array, 0);
4767 g_ptr_array_free (array, TRUE);
4768 return set_notification_method;
4772 set_set_notification_for_wait_completion_flag (StackFrame *frame)
4774 MonoObject* obj = get_this (frame);
4776 MonoClassField *builder_field = mono_class_get_field_from_name (obj->vtable->klass, "<>t__builder");
4777 g_assert (builder_field);
4778 MonoObject* builder;
4780 builder = mono_field_get_value_object_checked (frame->domain, builder_field, obj, &error);
4781 mono_error_assert_ok (&error);
4785 gboolean arg = TRUE;
4787 mono_runtime_invoke_checked (get_set_notification_method (builder->vtable->klass), mono_object_unbox (builder), args, &error);
4788 mono_error_assert_ok (&error);
4789 mono_field_set_value (obj, builder_field, mono_object_unbox (builder));
4792 static MonoMethod* notify_debugger_of_wait_completion_method_cache = NULL;
4795 get_notify_debugger_of_wait_completion_method ()
4797 if (notify_debugger_of_wait_completion_method_cache != NULL)
4798 return notify_debugger_of_wait_completion_method_cache;
4800 MonoClass* task_class = mono_class_load_from_name (mono_defaults.corlib, "System.Threading.Tasks", "Task");
4801 GPtrArray* array = mono_class_get_methods_by_name (task_class, "NotifyDebuggerOfWaitCompletion", 0x24, FALSE, FALSE, &error);
4802 mono_error_assert_ok (&error);
4803 g_assert (array->len == 1);
4804 notify_debugger_of_wait_completion_method_cache = (MonoMethod *)g_ptr_array_index (array, 0);
4805 g_ptr_array_free (array, TRUE);
4806 return notify_debugger_of_wait_completion_method_cache;
4810 process_breakpoint (DebuggerTlsData *tls, gboolean from_signal)
4814 int i, j, suspend_policy;
4815 guint32 native_offset;
4817 BreakpointInstance *inst;
4818 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4819 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4820 EventKind kind = EVENT_KIND_BREAKPOINT;
4821 MonoContext *ctx = &tls->restore_state.ctx;
4823 MonoSeqPointInfo *info;
4827 // FIXME: Speed this up
4829 ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
4830 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4834 // FIXME: Pass a flag instead to detect this
4835 MonoLMF *lmf = mono_get_lmf ();
4836 MonoInterpFrameHandle *frame;
4838 g_assert (((guint64)lmf->previous_lmf) & 2);
4839 MonoLMFExt *ext = (MonoLMFExt*)lmf;
4841 g_assert (ext->interp_exit);
4842 frame = ext->interp_exit_data;
4843 ji = mono_interp_frame_get_jit_info (frame);
4844 ip = mono_interp_frame_get_ip (frame);
4847 g_assert (ji && !ji->is_trampoline);
4848 method = jinfo_get_method (ji);
4850 /* Compute the native offset of the breakpoint from the ip */
4851 native_offset = ip - (guint8*)ji->code_start;
4854 * Skip the instruction causing the breakpoint signal.
4857 mono_arch_skip_breakpoint (ctx, ji);
4859 if (method->wrapper_type || tls->disable_breakpoints)
4862 bp_reqs = g_ptr_array_new ();
4863 ss_reqs = g_ptr_array_new ();
4864 ss_reqs_orig = g_ptr_array_new ();
4866 mono_loader_lock ();
4869 * The ip points to the instruction causing the breakpoint event, which is after
4870 * the offset recorded in the seq point map, so find the prev seq point before ip.
4872 found_sp = mono_find_prev_seq_point_for_native_offset (mono_domain_get (), method, native_offset, &info, &sp);
4875 no_seq_points_found (method, native_offset);
4877 g_assert (found_sp);
4879 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);
4882 for (i = 0; i < breakpoints->len; ++i) {
4883 bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4888 for (j = 0; j < bp->children->len; ++j) {
4889 inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4890 if (inst->ji == ji && inst->il_offset == sp.il_offset && inst->native_offset == sp.native_offset) {
4891 if (bp->req->event_kind == EVENT_KIND_STEP) {
4892 g_ptr_array_add (ss_reqs_orig, bp->req);
4894 g_ptr_array_add (bp_reqs, bp->req);
4899 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4900 /* Maybe a method entry/exit event */
4901 if (sp.il_offset == METHOD_ENTRY_IL_OFFSET)
4902 kind = EVENT_KIND_METHOD_ENTRY;
4903 else if (sp.il_offset == METHOD_EXIT_IL_OFFSET)
4904 kind = EVENT_KIND_METHOD_EXIT;
4907 /* Process single step requests */
4908 for (i = 0; i < ss_reqs_orig->len; ++i) {
4909 EventRequest *req = (EventRequest *)g_ptr_array_index (ss_reqs_orig, i);
4910 SingleStepReq *ss_req = (SingleStepReq *)req->info;
4913 //if we hit async_stepout_method, it's our no matter which thread
4914 if ((ss_req->async_stepout_method != method) && (ss_req->async_id || mono_thread_internal_current () != ss_req->thread)) {
4915 //We have different thread and we don't have async stepping in progress
4916 //it's breakpoint in parallel thread, ignore it
4917 if (ss_req->async_id == 0)
4920 tls->context.valid = FALSE;
4921 tls->async_state.valid = FALSE;
4922 invalidate_frames (tls);
4923 ss_calculate_framecount(tls, ctx);
4924 //make sure we have enough data to get current async method instance id
4925 if (tls->frame_count == 0 || !ensure_jit (tls->frames [0]))
4928 //Check method is async before calling get_this_async_id
4929 MonoDebugMethodAsyncInfo* asyncMethod = mono_debug_lookup_method_async_debug_info (method);
4933 mono_debug_free_method_async_debug_info (asyncMethod);
4935 //breakpoint was hit in parallelly executing async method, ignore it
4936 if (ss_req->async_id != get_this_async_id (tls->frames [0]))
4940 //Update stepping request to new thread/frame_count that we are continuing on
4941 //so continuing with normal stepping works as expected
4942 if (ss_req->async_stepout_method || ss_req->async_id) {
4943 tls->context.valid = FALSE;
4944 tls->async_state.valid = FALSE;
4945 invalidate_frames (tls);
4946 ss_calculate_framecount (tls, ctx);
4947 ss_req->thread = mono_thread_internal_current ();
4948 ss_req->nframes = tls->frame_count;
4951 hit = ss_update (ss_req, ji, &sp, tls, ctx, method);
4953 g_ptr_array_add (ss_reqs, req);
4955 /* Start single stepping again from the current sequence point */
4956 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
4959 if (ss_reqs->len > 0)
4960 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4961 if (bp_reqs->len > 0)
4962 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4963 if (kind != EVENT_KIND_BREAKPOINT)
4964 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4966 mono_loader_unlock ();
4968 g_ptr_array_free (bp_reqs, TRUE);
4969 g_ptr_array_free (ss_reqs, TRUE);
4972 * FIXME: The first event will suspend, so the second will only be sent after the
4976 process_event (EVENT_KIND_STEP, method, 0, ctx, ss_events, suspend_policy);
4978 process_event (kind, method, 0, ctx, bp_events, suspend_policy);
4979 if (enter_leave_events)
4980 process_event (kind, method, 0, ctx, enter_leave_events, suspend_policy);
4983 /* Process a breakpoint/single step event after resuming from a signal handler */
4985 process_signal_event (void (*func) (DebuggerTlsData*, gboolean))
4987 DebuggerTlsData *tls;
4988 MonoThreadUnwindState orig_restore_state;
4991 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4992 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4993 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4994 mono_thread_state_init_from_monoctx (&tls->restore_state, &tls->handler_ctx);
4998 /* This is called when resuming from a signal handler, so it shouldn't return */
4999 memcpy (&ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5000 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5001 mono_restore_context (&ctx);
5002 g_assert_not_reached ();
5006 process_breakpoint_from_signal (void)
5008 process_signal_event (process_breakpoint);
5012 resume_from_signal_handler (void *sigctx, void *func)
5014 DebuggerTlsData *tls;
5017 /* Save the original context in TLS */
5018 // FIXME: This might not work on an altstack ?
5019 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5021 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer) (gsize) mono_native_thread_id_get ());
5024 // FIXME: MonoContext usually doesn't include the fp registers, so these are
5025 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
5026 // clob:c could be added to op_seq_point.
5028 mono_sigctx_to_monoctx (sigctx, &ctx);
5029 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
5030 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
5031 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
5033 MONO_CONTEXT_SET_IP (&ctx, func);
5035 mono_monoctx_to_sigctx (&ctx, sigctx);
5037 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
5038 mono_ppc_set_func_into_sigctx (sigctx, func);
5043 mono_debugger_agent_breakpoint_hit (void *sigctx)
5046 * We are called from a signal handler, and running code there causes all kinds of
5047 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
5048 * So set up the signal context to return to the real breakpoint handler function.
5050 resume_from_signal_handler (sigctx, process_breakpoint_from_signal);
5059 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer user_data)
5061 UserBreakCbData *data = user_data;
5063 if (frame->type == FRAME_TYPE_INTERP_TO_MANAGED) {
5067 if (frame->managed) {
5077 * Called by System.Diagnostics.Debugger:Break ().
5080 mono_debugger_agent_user_break (void)
5082 if (agent_config.enabled) {
5086 UserBreakCbData data;
5088 memset (&data, 0, sizeof (UserBreakCbData));
5091 /* Obtain a context */
5092 MONO_CONTEXT_SET_IP (&ctx, NULL);
5093 mono_walk_stack_with_ctx (user_break_cb, NULL, (MonoUnwindOptions)0, &data);
5094 g_assert (data.found);
5096 mono_loader_lock ();
5097 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
5098 mono_loader_unlock ();
5100 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
5101 } else if (debug_options.native_debugger_break) {
5107 ss_depth_to_string (StepDepth depth)
5110 case STEP_DEPTH_OVER:
5112 case STEP_DEPTH_OUT:
5114 case STEP_DEPTH_INTO:
5117 g_assert_not_reached ();
5123 process_single_step_inner (DebuggerTlsData *tls, gboolean from_signal)
5128 int il_offset, suspend_policy;
5131 MonoContext *ctx = &tls->restore_state.ctx;
5134 MonoSeqPointInfo *info;
5136 /* Skip the instruction causing the single step */
5138 mono_arch_skip_single_step (ctx);
5140 if (suspend_count > 0) {
5141 /* Fastpath during invokes, see in process_suspend () */
5142 if (suspend_count - tls->resume_count == 0)
5144 process_suspend (tls, ctx);
5149 // FIXME: A suspend race
5152 if (mono_thread_internal_current () != ss_req->thread)
5155 ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
5157 ji = get_top_method_ji (ip, &domain, (gpointer*)&ip);
5158 g_assert (ji && !ji->is_trampoline);
5160 if (log_level > 0) {
5161 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);
5164 method = jinfo_get_method (ji);
5167 if (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
5172 * Stopping in memset makes half-initialized vtypes visible.
5173 * Stopping in memcpy makes half-copied vtypes visible.
5175 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
5179 * This could be in ss_update method, but mono_find_next_seq_point_for_native_offset is pretty expensive method,
5180 * hence we prefer this check here.
5182 if (ss_req->user_assemblies) {
5183 gboolean found = FALSE;
5184 for (int k = 0; ss_req->user_assemblies[k]; k++)
5185 if (ss_req->user_assemblies[k] == method->klass->image->assembly) {
5195 * The ip points to the instruction causing the single step event, which is before
5196 * the offset recorded in the seq point map, so find the next seq point after ip.
5198 if (!mono_find_next_seq_point_for_native_offset (domain, method, (guint8*)ip - (guint8*)ji->code_start, &info, &sp)) {
5199 g_assert_not_reached ();
5203 il_offset = sp.il_offset;
5205 if (!ss_update (ss_req, ji, &sp, tls, ctx, method))
5208 /* Start single stepping again from the current sequence point */
5209 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
5211 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
5212 (method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
5213 !strcmp (method->name, ".cctor"))
5216 // FIXME: Has to lock earlier
5218 reqs = g_ptr_array_new ();
5220 mono_loader_lock ();
5222 g_ptr_array_add (reqs, ss_req->req);
5224 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
5226 g_ptr_array_free (reqs, TRUE);
5228 mono_loader_unlock ();
5230 process_event (EVENT_KIND_STEP, jinfo_get_method (ji), il_offset, ctx, events, suspend_policy);
5234 process_single_step (void)
5236 process_signal_event (process_single_step_inner);
5240 * mono_debugger_agent_single_step_event:
5242 * Called from a signal handler to handle a single step event.
5245 mono_debugger_agent_single_step_event (void *sigctx)
5247 /* Resume to process_single_step through the signal context */
5249 // FIXME: Since step out/over is implemented using step in, the step in case should
5250 // be as fast as possible. Move the relevant code from process_single_step_inner ()
5253 if (is_debugger_thread ()) {
5255 * This could happen despite our best effors when the runtime calls
5256 * assembly/type resolve hooks.
5257 * FIXME: Breakpoints too.
5261 mono_sigctx_to_monoctx (sigctx, &ctx);
5262 mono_arch_skip_single_step (&ctx);
5263 mono_monoctx_to_sigctx (&ctx, sigctx);
5267 resume_from_signal_handler (sigctx, process_single_step);
5271 debugger_agent_single_step_from_context (MonoContext *ctx)
5273 DebuggerTlsData *tls;
5274 MonoThreadUnwindState orig_restore_state;
5276 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5277 /* Fastpath during invokes, see in process_suspend () */
5278 if (tls && suspend_count && suspend_count - tls->resume_count == 0)
5281 if (is_debugger_thread ())
5286 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
5287 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5288 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5289 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5291 process_single_step_inner (tls, FALSE);
5293 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5294 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5298 debugger_agent_breakpoint_from_context (MonoContext *ctx)
5300 DebuggerTlsData *tls;
5301 MonoThreadUnwindState orig_restore_state;
5304 if (is_debugger_thread ())
5307 orig_ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
5308 MONO_CONTEXT_SET_IP (ctx, orig_ip - 1);
5310 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5312 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5313 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5314 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5316 process_breakpoint (tls, FALSE);
5318 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5319 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5320 if (MONO_CONTEXT_GET_IP (ctx) == orig_ip - 1)
5321 MONO_CONTEXT_SET_IP (ctx, orig_ip);
5325 * start_single_stepping:
5327 * Turn on single stepping. Can be called multiple times, for example,
5328 * by a single step event request + a suspend.
5331 start_single_stepping (void)
5333 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5334 int val = InterlockedIncrement (&ss_count);
5337 mono_arch_start_single_stepping ();
5338 mono_interp_start_single_stepping ();
5341 g_assert_not_reached ();
5346 stop_single_stepping (void)
5348 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5349 int val = InterlockedDecrement (&ss_count);
5352 mono_arch_stop_single_stepping ();
5353 mono_interp_stop_single_stepping ();
5356 g_assert_not_reached ();
5363 * Stop the single stepping operation given by SS_REQ.
5366 ss_stop (SingleStepReq *ss_req)
5371 for (l = ss_req->bps; l; l = l->next) {
5372 clear_breakpoint ((MonoBreakpoint *)l->data);
5374 g_slist_free (ss_req->bps);
5378 ss_req->async_id = 0;
5379 ss_req->async_stepout_method = NULL;
5380 if (ss_req->global) {
5381 stop_single_stepping ();
5382 ss_req->global = FALSE;
5389 * Reject breakpoint if it is a duplicate of one already in list or hash table.
5392 ss_bp_is_unique (GSList *bps, GHashTable *ss_req_bp_cache, MonoMethod *method, guint32 il_offset)
5394 if (ss_req_bp_cache) {
5395 MonoBreakpoint dummy = {method, il_offset, NULL, NULL};
5396 return !g_hash_table_lookup (ss_req_bp_cache, &dummy);
5398 for (GSList *l = bps; l; l = l->next) {
5399 MonoBreakpoint *bp = (MonoBreakpoint *)l->data;
5400 if (bp->method == method && bp->il_offset == il_offset)
5409 * GHashTable equality for a MonoBreakpoint (only care about method and il_offset fields)
5412 ss_bp_eq (gconstpointer ka, gconstpointer kb)
5414 const MonoBreakpoint *s1 = (const MonoBreakpoint *)ka;
5415 const MonoBreakpoint *s2 = (const MonoBreakpoint *)kb;
5416 return (s1->method == s2->method && s1->il_offset == s2->il_offset) ? 1 : 0;
5422 * GHashTable hash for a MonoBreakpoint (only care about method and il_offset fields)
5425 ss_bp_hash (gconstpointer data)
5427 const MonoBreakpoint *s = (const MonoBreakpoint *)data;
5428 guint hash = (guint) (uintptr_t) s->method;
5429 hash ^= ((guint)s->il_offset) << 16; // Assume low bits are more interesting
5430 hash ^= ((guint)s->il_offset) >> 16;
5434 #define MAX_LINEAR_SCAN_BPS 7
5439 * Create a new breakpoint and add it to a step request.
5440 * Will adjust the bp count and cache used by ss_start.
5443 ss_bp_add_one (SingleStepReq *ss_req, int *ss_req_bp_count, GHashTable **ss_req_bp_cache,
5444 MonoMethod *method, guint32 il_offset)
5446 // This list is getting too long, switch to using the hash table
5447 if (!*ss_req_bp_cache && *ss_req_bp_count > MAX_LINEAR_SCAN_BPS) {
5448 *ss_req_bp_cache = g_hash_table_new (ss_bp_hash, ss_bp_eq);
5449 for (GSList *l = ss_req->bps; l; l = l->next)
5450 g_hash_table_insert (*ss_req_bp_cache, l->data, l->data);
5453 if (ss_bp_is_unique (ss_req->bps, *ss_req_bp_cache, method, il_offset)) {
5454 // Create and add breakpoint
5455 MonoBreakpoint *bp = set_breakpoint (method, il_offset, ss_req->req, NULL);
5456 ss_req->bps = g_slist_append (ss_req->bps, bp);
5457 if (*ss_req_bp_cache)
5458 g_hash_table_insert (*ss_req_bp_cache, bp, bp);
5459 (*ss_req_bp_count)++;
5461 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);
5466 is_last_non_empty (SeqPoint* sp, MonoSeqPointInfo *info)
5470 SeqPoint* next = g_new (SeqPoint, sp->next_len);
5471 mono_seq_point_init_next (info, *sp, next);
5472 for (int i = 0; i < sp->next_len; i++) {
5473 if (next [i].flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) {
5474 if (!is_last_non_empty (&next [i], info)) {
5490 * Start the single stepping operation given by SS_REQ from the sequence point SP.
5491 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
5492 * belong to the same thread as CTX.
5493 * If FRAMES is not-null, use that instead of tls->frames for placing breakpoints etc.
5496 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint* sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls,
5497 gboolean step_to_catch, StackFrame **frames, int nframes)
5499 int i, j, frame_index;
5500 SeqPoint *next_sp, *parent_sp = NULL;
5501 SeqPoint local_sp, local_parent_sp;
5503 MonoSeqPointInfo *parent_info;
5504 MonoMethod *parent_sp_method = NULL;
5505 gboolean enable_global = FALSE;
5507 // When 8 or more entries are in bps, we build a hash table to serve as a set of breakpoints.
5508 // Recreating this on each pass is a little wasteful but at least keeps behavior linear.
5509 int ss_req_bp_count = g_slist_length (ss_req->bps);
5510 GHashTable *ss_req_bp_cache = NULL;
5512 /* Stop the previous operation */
5516 * Implement single stepping using breakpoints if possible.
5518 if (step_to_catch) {
5519 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, sp->il_offset);
5523 if (ctx && !frames) {
5524 /* Need parent frames */
5525 if (!tls->context.valid)
5526 mono_thread_state_init_from_monoctx (&tls->context, ctx);
5527 compute_frame_info (tls->thread, tls);
5528 frames = tls->frames;
5529 nframes = tls->frame_count;
5532 MonoDebugMethodAsyncInfo* asyncMethod = mono_debug_lookup_method_async_debug_info (method);
5534 /* Need to stop in catch clauses as well */
5535 for (i = ss_req->depth == STEP_DEPTH_OUT ? 1 : 0; i < nframes; ++i) {
5536 StackFrame *frame = frames [i];
5539 MonoJitInfo *jinfo = frame->ji;
5540 for (j = 0; j < jinfo->num_clauses; ++j) {
5541 // In case of async method we don't want to place breakpoint on last catch handler(which state machine added for whole method)
5542 if (asyncMethod && asyncMethod->num_awaits && i == 0 && j + 1 == jinfo->num_clauses)
5544 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5546 if (mono_find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL, &local_sp))
5547 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, frame->method, local_sp.il_offset);
5552 if (asyncMethod && asyncMethod->num_awaits && nframes && ensure_jit (frames [0])) {
5553 //asyncMethod has value and num_awaits > 0, this means we are inside async method with awaits
5555 // Check if we hit yield_offset during normal stepping, because if we did...
5556 // Go into special async stepping mode which places breakpoint on resumeOffset
5557 // of this await call and sets async_id so we can distinguish it from parallel executions
5558 for (i = 0; i < asyncMethod->num_awaits; i++) {
5559 if (sp->il_offset == asyncMethod->yield_offsets [i]) {
5560 ss_req->async_id = get_this_async_id (frames [0]);
5561 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, asyncMethod->resume_offsets [i]);
5562 if (ss_req_bp_cache)
5563 g_hash_table_destroy (ss_req_bp_cache);
5564 mono_debug_free_method_async_debug_info (asyncMethod);
5568 //If we are at end of async method and doing step-in or step-over...
5569 //Switch to step-out, so whole NotifyDebuggerOfWaitCompletion magic happens...
5570 if (is_last_non_empty (sp, info)) {
5571 ss_req->depth = STEP_DEPTH_OUT;//setting depth to step-out is important, don't inline IF, because code later depends on this
5573 if (ss_req->depth == STEP_DEPTH_OUT) {
5574 set_set_notification_for_wait_completion_flag (frames [0]);
5575 ss_req->async_id = get_this_async_id (frames [0]);
5576 ss_req->async_stepout_method = get_notify_debugger_of_wait_completion_method ();
5577 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, ss_req->async_stepout_method, 0);
5578 if (ss_req_bp_cache)
5579 g_hash_table_destroy (ss_req_bp_cache);
5580 mono_debug_free_method_async_debug_info (asyncMethod);
5586 mono_debug_free_method_async_debug_info (asyncMethod);
5589 * Find the first sequence point in the current or in a previous frame which
5590 * is not the last in its method.
5592 if (ss_req->depth == STEP_DEPTH_OUT) {
5593 /* Ignore seq points in current method */
5594 while (frame_index < nframes) {
5595 StackFrame *frame = frames [frame_index];
5597 method = frame->method;
5598 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5599 sp = (found_sp)? &local_sp : NULL;
5601 if (sp && sp->next_len != 0)
5604 // There could be method calls before the next seq point in the caller when using nested calls
5605 //enable_global = TRUE;
5607 if (sp && sp->next_len == 0) {
5609 while (frame_index < nframes) {
5610 StackFrame *frame = frames [frame_index];
5612 method = frame->method;
5613 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5614 sp = (found_sp)? &local_sp : NULL;
5615 if (sp && sp->next_len != 0)
5621 /* Have to put a breakpoint into a parent frame since the seq points might not cover all control flow out of the method */
5622 while (frame_index < nframes) {
5623 StackFrame *frame = frames [frame_index];
5625 parent_sp_method = frame->method;
5626 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &parent_info, &local_parent_sp);
5627 parent_sp = found_sp ? &local_parent_sp : NULL;
5628 if (found_sp && parent_sp->next_len != 0)
5636 if (sp && sp->next_len > 0) {
5637 SeqPoint* next = g_new(SeqPoint, sp->next_len);
5639 mono_seq_point_init_next (info, *sp, next);
5640 for (i = 0; i < sp->next_len; i++) {
5643 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, next_sp->il_offset);
5649 SeqPoint* next = g_new(SeqPoint, parent_sp->next_len);
5651 mono_seq_point_init_next (parent_info, *parent_sp, next);
5652 for (i = 0; i < parent_sp->next_len; i++) {
5655 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, parent_sp_method, next_sp->il_offset);
5660 if (ss_req->nframes == 0)
5661 ss_req->nframes = nframes;
5663 if ((ss_req->depth == STEP_DEPTH_OVER) && (!sp && !parent_sp)) {
5664 DEBUG_PRINTF (1, "[dbg] No parent frame for step over, transition to step into.\n");
5666 * This is needed since if we leave managed code, and later return to it, step over
5667 * is not going to stop.
5668 * This approach is a bit ugly, since we change the step depth, but it only affects
5669 * clients who reuse the same step request, and only in this special case.
5671 ss_req->depth = STEP_DEPTH_INTO;
5674 if (ss_req->depth == STEP_DEPTH_INTO) {
5675 /* Enable global stepping so we stop at method entry too */
5676 enable_global = TRUE;
5680 * The ctx/frame info computed above will become invalid when we continue.
5682 tls->context.valid = FALSE;
5683 tls->async_state.valid = FALSE;
5684 invalidate_frames (tls);
5687 if (enable_global) {
5688 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5689 ss_req->global = TRUE;
5690 start_single_stepping ();
5691 } else if (!ss_req->bps) {
5692 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5693 ss_req->global = TRUE;
5694 start_single_stepping ();
5696 ss_req->global = FALSE;
5699 if (ss_req_bp_cache)
5700 g_hash_table_destroy (ss_req_bp_cache);
5704 * Start single stepping of thread THREAD
5707 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req)
5709 DebuggerTlsData *tls;
5710 MonoSeqPointInfo *info = NULL;
5711 SeqPoint *sp = NULL;
5714 MonoMethod *method = NULL;
5715 MonoDebugMethodInfo *minfo;
5716 gboolean step_to_catch = FALSE;
5717 gboolean set_ip = FALSE;
5718 StackFrame **frames = NULL;
5721 if (suspend_count == 0)
5722 return ERR_NOT_SUSPENDED;
5724 wait_for_suspend ();
5726 // FIXME: Multiple requests
5728 DEBUG_PRINTF (0, "Received a single step request while the previous one was still active.\n");
5729 return ERR_NOT_IMPLEMENTED;
5732 DEBUG_PRINTF (1, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth));
5734 ss_req = g_new0 (SingleStepReq, 1);
5736 ss_req->thread = thread;
5737 ss_req->size = size;
5738 ss_req->depth = depth;
5739 ss_req->filter = filter;
5742 for (int i = 0; i < req->nmodifiers; i++) {
5743 if (req->modifiers[i].kind == MOD_KIND_ASSEMBLY_ONLY) {
5744 ss_req->user_assemblies = req->modifiers[i].data.assemblies;
5749 mono_loader_lock ();
5750 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5751 mono_loader_unlock ();
5753 if (!tls->context.valid) {
5754 DEBUG_PRINTF (1, "Received a single step request on a thread with no managed frames.");
5755 return ERR_INVALID_ARGUMENT;
5758 if (tls->restore_state.valid && MONO_CONTEXT_GET_IP (&tls->context.ctx) != MONO_CONTEXT_GET_IP (&tls->restore_state.ctx)) {
5760 * Need to start single stepping from restore_state and not from the current state
5763 frames = compute_frame_info_from (thread, tls, &tls->restore_state, &nframes);
5766 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5768 if (tls->catch_state.valid) {
5770 StackFrameInfo frame;
5771 MonoContext new_ctx;
5772 MonoLMF *lmf = NULL;
5775 * We are stopped at a throw site. Stepping should go to the catch site.
5778 /* Find the the jit info for the catch context */
5779 res = mono_find_jit_info_ext (
5780 (MonoDomain *)tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN],
5781 (MonoJitTlsData *)((MonoThreadInfo*)thread->thread_info)->jit_data,
5782 NULL, &tls->catch_state.ctx, &new_ctx, NULL, &lmf, NULL, &frame);
5784 g_assert (frame.type == FRAME_TYPE_MANAGED);
5787 * Find the seq point corresponding to the landing site ip, which is the first seq
5790 found_sp = mono_find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info, &local_sp);
5791 sp = (found_sp)? &local_sp : NULL;
5793 no_seq_points_found (frame.method, frame.native_offset);
5796 method = frame.method;
5798 step_to_catch = TRUE;
5799 /* This make sure the seq point is not skipped by process_single_step () */
5800 ss_req->last_sp = NULL;
5803 if (!step_to_catch) {
5804 StackFrame *frame = NULL;
5807 if (frames && nframes)
5810 compute_frame_info (thread, tls);
5812 if (tls->frame_count)
5813 frame = tls->frames [0];
5816 if (ss_req->size == STEP_SIZE_LINE) {
5818 ss_req->last_method = frame->method;
5819 ss_req->last_line = -1;
5821 minfo = mono_debug_lookup_method (frame->method);
5822 if (minfo && frame->il_offset != -1) {
5823 MonoDebugSourceLocation *loc = mono_debug_method_lookup_location (minfo, frame->il_offset);
5826 ss_req->last_line = loc->row;
5834 if (!method && frame->il_offset != -1) {
5835 /* FIXME: Sort the table and use a binary search */
5836 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5837 sp = (found_sp)? &local_sp : NULL;
5839 no_seq_points_found (frame->method, frame->native_offset);
5841 method = frame->method;
5846 ss_req->start_method = method;
5848 ss_start (ss_req, method, sp, info, set_ip ? &tls->restore_state.ctx : &tls->context.ctx, tls, step_to_catch, frames, nframes);
5851 free_frames (frames, nframes);
5857 ss_destroy (SingleStepReq *req)
5860 g_assert (ss_req == req);
5869 ss_clear_for_assembly (SingleStepReq *req, MonoAssembly *assembly)
5872 gboolean found = TRUE;
5876 for (l = ss_req->bps; l; l = l->next) {
5877 if (breakpoint_matches_assembly ((MonoBreakpoint *)l->data, assembly)) {
5878 clear_breakpoint ((MonoBreakpoint *)l->data);
5879 ss_req->bps = g_slist_delete_link (ss_req->bps, l);
5888 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5891 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5898 if (!agent_config.enabled)
5901 mono_loader_lock ();
5902 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5903 mono_loader_unlock ();
5908 ei.category = mono_string_to_utf8_checked (category, &error);
5909 mono_error_cleanup (&error);
5913 ei.message = mono_string_to_utf8_checked (message, &error);
5914 mono_error_cleanup (&error);
5917 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5919 g_free (ei.category);
5920 g_free (ei.message);
5924 mono_debugger_agent_debug_log_is_enabled (void)
5926 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5927 return agent_config.enabled;
5930 #if defined(PLATFORM_ANDROID) || defined(TARGET_ANDROID)
5932 mono_debugger_agent_unhandled_exception (MonoException *exc)
5941 memset (&ei, 0, sizeof (EventInfo));
5942 ei.exc = (MonoObject*)exc;
5944 mono_loader_lock ();
5945 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5946 mono_loader_unlock ();
5948 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5953 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5954 MonoContext *catch_ctx)
5956 int i, j, suspend_policy;
5958 MonoJitInfo *ji, *catch_ji;
5960 DebuggerTlsData *tls = NULL;
5962 if (thread_to_tls != NULL) {
5963 MonoInternalThread *thread = mono_thread_internal_current ();
5965 mono_loader_lock ();
5966 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5967 mono_loader_unlock ();
5969 if (tls && tls->abort_requested)
5971 if (tls && tls->disable_breakpoints)
5975 memset (&ei, 0, sizeof (EventInfo));
5977 /* Just-In-Time debugging */
5979 if (agent_config.onuncaught && !inited) {
5980 finish_agent_init (FALSE);
5983 * Send an unsolicited EXCEPTION event with a dummy request id.
5985 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5986 ei.exc = (MonoObject*)exc;
5987 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5990 } else if (agent_config.onthrow && !inited) {
5992 gboolean found = FALSE;
5994 for (l = agent_config.onthrow; l; l = l->next) {
5995 char *ex_type = (char *)l->data;
5996 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5998 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
6005 finish_agent_init (FALSE);
6008 * Send an unsolicited EXCEPTION event with a dummy request id.
6010 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
6011 ei.exc = (MonoObject*)exc;
6012 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
6020 ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (throw_ctx), NULL);
6022 catch_ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (catch_ctx), NULL);
6026 ei.exc = (MonoObject*)exc;
6027 ei.caught = catch_ctx != NULL;
6029 mono_loader_lock ();
6031 /* Treat exceptions which are caught in non-user code as unhandled */
6032 for (i = 0; i < event_requests->len; ++i) {
6033 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6034 if (req->event_kind != EVENT_KIND_EXCEPTION)
6037 for (j = 0; j < req->nmodifiers; ++j) {
6038 Modifier *mod = &req->modifiers [j];
6040 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
6042 gboolean found = FALSE;
6043 MonoAssembly **assemblies = mod->data.assemblies;
6046 for (k = 0; assemblies [k]; ++k)
6047 if (assemblies [k] == jinfo_get_method (catch_ji)->klass->image->assembly)
6056 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
6057 mono_loader_unlock ();
6059 if (tls && ei.caught && catch_ctx) {
6060 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
6061 tls->catch_state.ctx = *catch_ctx;
6062 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
6063 tls->catch_state.valid = TRUE;
6066 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
6069 tls->catch_state.valid = FALSE;
6073 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
6075 DebuggerTlsData *tls;
6080 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
6085 * We're about to invoke an exception filter during the first pass of exception handling.
6087 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
6088 * 'orig_ctx' is the context where the exception has been thrown.
6091 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
6093 * If we're stopped in Filter(), normal stack unwinding would first unwind to
6094 * the call site (line 37) and then continue to Main(), but it would never
6095 * include the throw site (line 32).
6097 * Since exception filters are invoked during the first pass of exception handling,
6098 * the stack frames of the throw site are still intact, so we should include them
6101 * We do this here by saving the context of the throw site in 'tls->filter_state'.
6103 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
6104 * but report the location of the 'throw' to the user.
6108 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
6112 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
6114 DebuggerTlsData *tls;
6119 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
6123 tls->filter_state.valid = FALSE;
6127 * buffer_add_value_full:
6129 * Add the encoding of the value at ADDR described by T to the buffer.
6130 * AS_VTYPE determines whenever to treat primitive types as primitive types or
6134 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
6135 gboolean as_vtype, GHashTable *parent_vtypes)
6138 gboolean boxed_vtype = FALSE;
6141 if (!(*(void**)addr)) {
6142 /* This can happen with compiler generated locals */
6143 //printf ("%s\n", mono_type_full_name (t));
6144 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
6147 g_assert (*(void**)addr);
6148 addr = *(void**)addr;
6153 case MONO_TYPE_BOOLEAN:
6156 case MONO_TYPE_CHAR:
6176 case MONO_TYPE_VOID:
6177 buffer_add_byte (buf, t->type);
6179 case MONO_TYPE_BOOLEAN:
6182 buffer_add_byte (buf, t->type);
6183 buffer_add_int (buf, *(gint8*)addr);
6185 case MONO_TYPE_CHAR:
6188 buffer_add_byte (buf, t->type);
6189 buffer_add_int (buf, *(gint16*)addr);
6194 buffer_add_byte (buf, t->type);
6195 buffer_add_int (buf, *(gint32*)addr);
6200 buffer_add_byte (buf, t->type);
6201 buffer_add_long (buf, *(gint64*)addr);
6205 /* Treat it as a vtype */
6207 case MONO_TYPE_PTR: {
6208 gssize val = *(gssize*)addr;
6210 buffer_add_byte (buf, t->type);
6211 buffer_add_long (buf, val);
6215 case MONO_TYPE_STRING:
6216 case MONO_TYPE_SZARRAY:
6217 case MONO_TYPE_OBJECT:
6218 case MONO_TYPE_CLASS:
6219 case MONO_TYPE_ARRAY:
6220 obj = *(MonoObject**)addr;
6223 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
6225 if (obj->vtable->klass->valuetype) {
6226 t = &obj->vtable->klass->byval_arg;
6227 addr = mono_object_unbox (obj);
6230 } else if (obj->vtable->klass->rank) {
6231 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
6232 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
6233 buffer_add_byte (buf, MONO_TYPE_CLASS);
6235 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
6237 buffer_add_objid (buf, obj);
6241 case MONO_TYPE_VALUETYPE:
6242 case MONO_TYPE_TYPEDBYREF: {
6246 MonoClass *klass = mono_class_from_mono_type (t);
6251 * Handle boxed vtypes recursively referencing themselves using fields.
6254 parent_vtypes = g_hash_table_new (NULL, NULL);
6255 vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
6257 if (CHECK_PROTOCOL_VERSION (2, 33)) {
6258 buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
6259 buffer_add_int (buf, vtype_index - 1);
6261 /* The client can't handle PARENT_VTYPE */
6262 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
6266 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
6270 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
6271 buffer_add_byte (buf, klass->enumtype);
6272 buffer_add_typeid (buf, domain, klass);
6276 while ((f = mono_class_get_fields (klass, &iter))) {
6277 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6279 if (mono_field_is_deleted (f))
6283 buffer_add_int (buf, nfields);
6286 while ((f = mono_class_get_fields (klass, &iter))) {
6287 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6289 if (mono_field_is_deleted (f))
6291 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE, parent_vtypes);
6295 g_hash_table_remove (parent_vtypes, addr);
6296 if (g_hash_table_size (parent_vtypes) == 0) {
6297 g_hash_table_destroy (parent_vtypes);
6298 parent_vtypes = NULL;
6303 case MONO_TYPE_GENERICINST:
6304 if (mono_type_generic_inst_is_valuetype (t)) {
6316 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
6318 buffer_add_value_full (buf, t, addr, domain, FALSE, NULL);
6322 obj_is_of_type (MonoObject *obj, MonoType *t)
6324 MonoClass *klass = obj->vtable->klass;
6325 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
6326 if (mono_class_is_transparent_proxy (klass)) {
6327 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
6328 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
6338 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
6341 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6347 gpointer iter = NULL;
6351 is_enum = decode_byte (buf, &buf, limit);
6352 /* Enums are sent as a normal vtype */
6354 return ERR_NOT_IMPLEMENTED;
6355 klass = decode_typeid (buf, &buf, limit, &d, &err);
6356 if (err != ERR_NONE)
6359 if (t && klass != mono_class_from_mono_type (t)) {
6360 char *name = mono_type_full_name (t);
6361 char *name2 = mono_type_full_name (&klass->byval_arg);
6362 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got %s.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, name2);
6365 return ERR_INVALID_ARGUMENT;
6368 nfields = decode_int (buf, &buf, limit);
6369 while ((f = mono_class_get_fields (klass, &iter))) {
6370 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6372 if (mono_field_is_deleted (f))
6374 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
6375 if (err != ERR_NONE)
6379 g_assert (nfields == 0);
6387 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6391 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
6392 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
6393 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
6394 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
6395 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE) &&
6396 !(t->type == MONO_TYPE_VALUETYPE && type == MONO_TYPE_OBJECT)) {
6397 char *name = mono_type_full_name (t);
6398 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
6400 return ERR_INVALID_ARGUMENT;
6404 case MONO_TYPE_BOOLEAN:
6405 *(guint8*)addr = decode_int (buf, &buf, limit);
6407 case MONO_TYPE_CHAR:
6408 *(gunichar2*)addr = decode_int (buf, &buf, limit);
6411 *(gint8*)addr = decode_int (buf, &buf, limit);
6414 *(guint8*)addr = decode_int (buf, &buf, limit);
6417 *(gint16*)addr = decode_int (buf, &buf, limit);
6420 *(guint16*)addr = decode_int (buf, &buf, limit);
6423 *(gint32*)addr = decode_int (buf, &buf, limit);
6426 *(guint32*)addr = decode_int (buf, &buf, limit);
6429 *(gint64*)addr = decode_long (buf, &buf, limit);
6432 *(guint64*)addr = decode_long (buf, &buf, limit);
6435 *(guint32*)addr = decode_int (buf, &buf, limit);
6438 *(guint64*)addr = decode_long (buf, &buf, limit);
6441 /* We send these as I8, so we get them back as such */
6442 g_assert (type == MONO_TYPE_I8);
6443 *(gssize*)addr = decode_long (buf, &buf, limit);
6445 case MONO_TYPE_GENERICINST:
6446 if (MONO_TYPE_ISSTRUCT (t)) {
6447 /* The client sends these as a valuetype */
6455 /* We send these as vtypes, so we get them back as such */
6456 g_assert (type == MONO_TYPE_VALUETYPE);
6459 case MONO_TYPE_VALUETYPE:
6460 if (type == MONO_TYPE_OBJECT) {
6462 int objid = decode_objid (buf, &buf, limit);
6466 err = get_object (objid, (MonoObject**)&obj);
6467 if (err != ERR_NONE)
6470 return ERR_INVALID_ARGUMENT;
6471 if (obj->vtable->klass != mono_class_from_mono_type (t)) {
6472 DEBUG_PRINTF (1, "Expected type '%s', got object '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6473 return ERR_INVALID_ARGUMENT;
6475 memcpy (addr, mono_object_unbox (obj), mono_class_value_size (obj->vtable->klass, NULL));
6477 err = decode_vtype (t, domain, addr, buf, &buf, limit);
6478 if (err != ERR_NONE)
6484 if (MONO_TYPE_IS_REFERENCE (t)) {
6485 if (type == MONO_TYPE_OBJECT) {
6486 int objid = decode_objid (buf, &buf, limit);
6490 err = get_object (objid, (MonoObject**)&obj);
6491 if (err != ERR_NONE)
6495 if (!obj_is_of_type (obj, t)) {
6496 DEBUG_PRINTF (1, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6497 return ERR_INVALID_ARGUMENT;
6500 if (obj && obj->vtable->domain != domain)
6501 return ERR_INVALID_ARGUMENT;
6503 mono_gc_wbarrier_generic_store (addr, obj);
6504 } else if (type == VALUE_TYPE_ID_NULL) {
6505 *(MonoObject**)addr = NULL;
6506 } else if (type == MONO_TYPE_VALUETYPE) {
6515 /* This can happen when round-tripping boxed vtypes */
6517 * Obtain vtype class.
6518 * Same as the beginning of the handle_vtype case above.
6521 is_enum = decode_byte (buf, &buf, limit);
6523 return ERR_NOT_IMPLEMENTED;
6524 klass = decode_typeid (buf, &buf, limit, &d, &err);
6525 if (err != ERR_NONE)
6528 /* Decode the vtype into a temporary buffer, then box it. */
6529 vtype_buf_size = mono_class_value_size (klass, NULL);
6530 vtype_buf = (guint8 *)g_malloc0 (vtype_buf_size);
6531 g_assert (vtype_buf);
6534 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
6535 if (err != ERR_NONE) {
6539 *(MonoObject**)addr = mono_value_box_checked (d, klass, vtype_buf, &error);
6540 mono_error_cleanup (&error);
6543 char *name = mono_type_full_name (t);
6544 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
6546 return ERR_INVALID_ARGUMENT;
6560 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6564 int type = decode_byte (buf, &buf, limit);
6566 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
6567 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
6568 guint8 *nullable_buf;
6571 * First try decoding it as a Nullable`1
6573 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6574 if (err == ERR_NONE)
6578 * Then try decoding as a primitive value or null.
6580 if (targ->type == type) {
6581 nullable_buf = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
6582 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
6583 if (err != ERR_NONE) {
6584 g_free (nullable_buf);
6587 MonoObject *boxed = mono_value_box_checked (domain, mono_class_from_mono_type (targ), nullable_buf, &error);
6588 if (!is_ok (&error)) {
6589 mono_error_cleanup (&error);
6590 return ERR_INVALID_OBJECT;
6592 mono_nullable_init (addr, boxed, mono_class_from_mono_type (t));
6593 g_free (nullable_buf);
6596 } else if (type == VALUE_TYPE_ID_NULL) {
6597 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
6603 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6607 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
6611 guint8 *addr, *gaddr;
6614 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6615 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6618 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
6619 reg_val = mono_arch_context_get_int_reg (ctx, reg);
6621 buffer_add_value_full (buf, t, ®_val, domain, as_vtype, NULL);
6623 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6624 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6625 addr += (gint32)var->offset;
6627 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6629 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6631 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6634 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6635 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
6636 /* Same as regoffset, but with an indirection */
6637 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6638 addr += (gint32)var->offset;
6640 gaddr = (guint8 *)*(gpointer*)addr;
6642 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL);
6644 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
6645 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
6646 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
6647 MonoGSharedVtMethodRuntimeInfo *info;
6653 g_assert (info_var);
6654 g_assert (locals_var);
6656 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6657 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6658 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6659 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6660 addr += (gint32)info_var->offset;
6661 info = (MonoGSharedVtMethodRuntimeInfo *)*(gpointer*)addr;
6662 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6663 info = (MonoGSharedVtMethodRuntimeInfo *)mono_arch_context_get_int_reg (ctx, reg);
6665 g_assert_not_reached ();
6669 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6670 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6671 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6672 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6673 addr += (gint32)locals_var->offset;
6674 locals = (guint8 *)*(gpointer*)addr;
6675 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6676 locals = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6678 g_assert_not_reached ();
6682 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6684 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6689 g_assert_not_reached ();
6694 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
6698 guint8 *addr, *gaddr;
6700 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6701 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6703 if (MONO_TYPE_IS_REFERENCE (t))
6704 size = sizeof (gpointer);
6706 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6709 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6710 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6712 gboolean is_signed = FALSE;
6715 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6718 // FIXME: Write barriers
6719 mono_gc_memmove_atomic (addr, val, size);
6724 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6729 v = is_signed ? *(gint8*)val : *(guint8*)val;
6732 v = is_signed ? *(gint16*)val : *(guint16*)val;
6735 v = is_signed ? *(gint32*)val : *(guint32*)val;
6738 v = is_signed ? *(gint64*)val : *(guint64*)val;
6741 g_assert_not_reached ();
6744 /* Set value on the stack or in the return ctx */
6745 if (reg_locations [reg]) {
6746 /* Saved on the stack */
6747 DEBUG_PRINTF (1, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v);
6748 *(reg_locations [reg]) = v;
6751 DEBUG_PRINTF (1, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v);
6752 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6755 // FIXME: Move these to mono-context.h/c.
6756 mono_arch_context_set_int_reg (ctx, reg, v);
6758 // FIXME: Can't set registers, so we disable linears
6763 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6764 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6765 addr += (gint32)var->offset;
6767 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6770 addr = *(guint8**)addr;
6776 // FIXME: Write barriers
6777 mono_gc_memmove_atomic (addr, val, size);
6779 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6780 /* Same as regoffset, but with an indirection */
6781 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6782 addr += (gint32)var->offset;
6784 gaddr = (guint8 *)*(gpointer*)addr;
6786 // FIXME: Write barriers
6787 mono_gc_memmove_atomic (gaddr, val, size);
6789 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6793 g_assert_not_reached ();
6798 set_interp_var (MonoType *t, gpointer addr, guint8 *val_buf)
6803 addr = *(gpointer*)addr;
6807 if (MONO_TYPE_IS_REFERENCE (t))
6808 size = sizeof (gpointer);
6810 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6812 memcpy (addr, val_buf, size);
6816 clear_event_request (int req_id, int etype)
6820 mono_loader_lock ();
6821 for (i = 0; i < event_requests->len; ++i) {
6822 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6824 if (req->id == req_id && req->event_kind == etype) {
6825 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6826 clear_breakpoint ((MonoBreakpoint *)req->info);
6827 if (req->event_kind == EVENT_KIND_STEP)
6828 ss_destroy ((SingleStepReq *)req->info);
6829 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6830 clear_breakpoint ((MonoBreakpoint *)req->info);
6831 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6832 clear_breakpoint ((MonoBreakpoint *)req->info);
6833 g_ptr_array_remove_index_fast (event_requests, i);
6838 mono_loader_unlock ();
6842 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
6846 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6847 m->kind = MOD_KIND_NONE;
6848 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6849 int count = 0, match_count = 0, pos;
6850 MonoAssembly **newassemblies;
6852 for (i = 0; m->data.assemblies [i]; ++i) {
6854 if (m->data.assemblies [i] == assembly)
6859 // +1 because we don't know length and we use last element to check for end
6860 newassemblies = g_new0 (MonoAssembly*, count - match_count + 1);
6863 for (i = 0; i < count; ++i)
6864 if (m->data.assemblies [i] != assembly)
6865 newassemblies [pos ++] = m->data.assemblies [i];
6866 g_assert (pos == count - match_count);
6867 g_free (m->data.assemblies);
6868 m->data.assemblies = newassemblies;
6874 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
6878 for (i = 0; i < req->nmodifiers; ++i) {
6879 Modifier *m = &req->modifiers [i];
6881 clear_assembly_from_modifier (req, m, assembly);
6886 * clear_event_requests_for_assembly:
6888 * Clear all events requests which reference ASSEMBLY.
6891 clear_event_requests_for_assembly (MonoAssembly *assembly)
6896 mono_loader_lock ();
6900 for (i = 0; i < event_requests->len; ++i) {
6901 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6903 clear_assembly_from_modifiers (req, assembly);
6905 if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly ((MonoBreakpoint *)req->info, assembly)) {
6906 clear_event_request (req->id, req->event_kind);
6911 if (req->event_kind == EVENT_KIND_STEP)
6912 ss_clear_for_assembly ((SingleStepReq *)req->info, assembly);
6915 mono_loader_unlock ();
6919 * type_comes_from_assembly:
6921 * GHRFunc that returns TRUE if klass comes from assembly
6924 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6926 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6930 * clear_types_for_assembly:
6932 * Clears types from loaded_classes for a given assembly
6935 clear_types_for_assembly (MonoAssembly *assembly)
6937 MonoDomain *domain = mono_domain_get ();
6938 AgentDomainInfo *info = NULL;
6940 if (!domain || !domain_jit_info (domain))
6941 /* Can happen during shutdown */
6944 info = get_agent_domain_info (domain);
6946 mono_loader_lock ();
6947 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6948 mono_loader_unlock ();
6952 add_thread (gpointer key, gpointer value, gpointer user_data)
6954 MonoInternalThread *thread = (MonoInternalThread *)value;
6955 Buffer *buf = (Buffer *)user_data;
6957 buffer_add_objid (buf, (MonoObject*)thread);
6961 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6964 guint8 *end = invoke->endp;
6968 MonoMethodSignature *sig;
6971 MonoObject *this_arg, *res, *exc;
6974 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6977 MonoStopwatch watch;
6979 if (invoke->method) {
6981 * Invoke this method directly, currently only Environment.Exit () is supported.
6984 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>");
6986 mono_runtime_try_invoke (invoke->method, NULL, invoke->args, &exc, &error);
6987 mono_error_assert_ok (&error);
6989 g_assert_not_reached ();
6992 m = decode_methodid (p, &p, end, &domain, &err);
6993 if (err != ERR_NONE)
6995 sig = mono_method_signature (m);
6997 if (m->klass->valuetype)
6998 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
7000 this_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
7001 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
7002 /* Should be null */
7003 int type = decode_byte (p, &p, end);
7004 if (type != VALUE_TYPE_ID_NULL) {
7005 DEBUG_PRINTF (1, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
7006 return ERR_INVALID_ARGUMENT;
7008 memset (this_buf, 0, mono_class_instance_size (m->klass));
7009 } else if (m->klass->valuetype && !strcmp (m->name, ".ctor")) {
7013 int type = decode_byte (p, &tmp_p, end);
7014 if (type == VALUE_TYPE_ID_NULL) {
7015 memset (this_buf, 0, mono_class_instance_size (m->klass));
7018 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
7019 if (err != ERR_NONE)
7023 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
7024 if (err != ERR_NONE)
7028 if (!m->klass->valuetype)
7029 this_arg = *(MonoObject**)this_buf;
7033 if (MONO_CLASS_IS_INTERFACE (m->klass)) {
7035 DEBUG_PRINTF (1, "[%p] Error: Interface method invoked without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
7036 return ERR_INVALID_ARGUMENT;
7038 m = mono_object_get_virtual_method (this_arg, m);
7039 /* Transform this to the format the rest of the code expects it to be */
7040 if (m->klass->valuetype) {
7041 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
7042 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
7044 } else if ((m->flags & METHOD_ATTRIBUTE_VIRTUAL) && !m->klass->valuetype && invoke->flags & INVOKE_FLAG_VIRTUAL) {
7046 DEBUG_PRINTF (1, "[%p] Error: invoke with INVOKE_FLAG_VIRTUAL flag set without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
7047 return ERR_INVALID_ARGUMENT;
7049 m = mono_object_get_virtual_method (this_arg, m);
7050 if (m->klass->valuetype) {
7051 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
7052 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
7056 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>");
7058 if (this_arg && this_arg->vtable->domain != domain)
7061 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this_arg) {
7062 if (!strcmp (m->name, ".ctor")) {
7063 if (mono_class_is_abstract (m->klass))
7064 return ERR_INVALID_ARGUMENT;
7067 this_arg = mono_object_new_checked (domain, m->klass, &error);
7068 mono_error_assert_ok (&error);
7071 return ERR_INVALID_ARGUMENT;
7075 if (this_arg && !obj_is_of_type (this_arg, &m->klass->byval_arg))
7076 return ERR_INVALID_ARGUMENT;
7078 nargs = decode_int (p, &p, end);
7079 if (nargs != sig->param_count)
7080 return ERR_INVALID_ARGUMENT;
7081 /* Use alloca to get gc tracking */
7082 arg_buf = (guint8 **)g_alloca (nargs * sizeof (gpointer));
7083 memset (arg_buf, 0, nargs * sizeof (gpointer));
7084 args = (gpointer *)g_alloca (nargs * sizeof (gpointer));
7085 for (i = 0; i < nargs; ++i) {
7086 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
7087 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
7088 if (err != ERR_NONE)
7090 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
7093 if (sig->params [i]->byref) {
7094 arg_buf [i] = (guint8 *)g_alloca (sizeof (mgreg_t));
7095 *(gpointer*)arg_buf [i] = args [i];
7096 args [i] = arg_buf [i];
7099 MonoClass *arg_class = mono_class_from_mono_type (sig->params [i]);
7100 arg_buf [i] = (guint8 *)g_alloca (mono_class_instance_size (arg_class));
7101 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
7102 if (err != ERR_NONE)
7104 if (mono_class_is_nullable (arg_class)) {
7105 args [i] = mono_nullable_box (arg_buf [i], arg_class, &error);
7106 mono_error_assert_ok (&error);
7108 args [i] = arg_buf [i];
7116 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
7117 tls->disable_breakpoints = TRUE;
7119 tls->disable_breakpoints = FALSE;
7122 * Add an LMF frame to link the stack frames on the invoke method with our caller.
7124 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
7125 if (invoke->has_ctx) {
7128 lmf_addr = mono_get_lmf_addr ();
7131 memset (&ext, 0, sizeof (ext));
7132 mono_arch_init_lmf_ext (&ext, *lmf_addr);
7134 ext.debugger_invoke = TRUE;
7135 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
7137 mono_set_lmf ((MonoLMF*)&ext);
7141 mono_stopwatch_start (&watch);
7142 res = mono_runtime_try_invoke (m, m->klass->valuetype ? (gpointer) this_buf : (gpointer) this_arg, args, &exc, &error);
7143 if (exc == NULL && !mono_error_ok (&error)) {
7144 exc = (MonoObject*) mono_error_convert_to_exception (&error);
7146 mono_error_cleanup (&error); /* FIXME report error */
7148 mono_stopwatch_stop (&watch);
7149 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));
7151 buffer_add_byte (buf, 0);
7152 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
7154 gboolean out_this = FALSE;
7155 gboolean out_args = FALSE;
7157 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_THIS) && CHECK_PROTOCOL_VERSION (2, 35))
7159 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_ARGS) && CHECK_PROTOCOL_VERSION (2, 35))
7161 buffer_add_byte (buf, 1 + (out_this ? 2 : 0) + (out_args ? 4 : 0));
7162 if (m->string_ctor) {
7163 buffer_add_value (buf, &mono_get_string_class ()->byval_arg, &res, domain);
7164 } else if (sig->ret->type == MONO_TYPE_VOID && !m->string_ctor) {
7165 if (!strcmp (m->name, ".ctor")) {
7166 if (!m->klass->valuetype)
7167 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this_arg, domain);
7169 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
7171 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
7173 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
7174 buffer_add_value (buf, sig->ret, &res, domain);
7175 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
7176 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
7177 MonoClass *k = mono_class_from_mono_type (sig->ret);
7178 guint8 *nullable_buf = (guint8 *)g_alloca (mono_class_value_size (k, NULL));
7180 g_assert (nullable_buf);
7181 mono_nullable_init (nullable_buf, res, k);
7182 buffer_add_value (buf, sig->ret, nullable_buf, domain);
7185 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
7191 /* Return the new value of the receiver after the call */
7192 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
7194 buffer_add_int (buf, nargs);
7195 for (i = 0; i < nargs; ++i) {
7196 if (MONO_TYPE_IS_REFERENCE (sig->params [i]))
7197 buffer_add_value (buf, sig->params [i], &args [i], domain);
7198 else if (sig->params [i]->byref)
7199 /* add_value () does an indirection */
7200 buffer_add_value (buf, sig->params [i], &arg_buf [i], domain);
7202 buffer_add_value (buf, sig->params [i], arg_buf [i], domain);
7207 tls->disable_breakpoints = FALSE;
7209 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
7210 if (invoke->has_ctx)
7211 mono_set_lmf ((MonoLMF *)(((gssize)ext.lmf.previous_lmf) & ~3));
7215 // FIXME: byref arguments
7223 * Invoke the method given by tls->pending_invoke in the current thread.
7226 invoke_method (void)
7228 DebuggerTlsData *tls;
7234 MonoContext restore_ctx;
7237 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
7241 * Store the `InvokeData *' in `tls->invoke' until we're done with
7242 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
7245 mono_loader_lock ();
7247 invoke = tls->pending_invoke;
7249 tls->pending_invoke = NULL;
7251 invoke->last_invoke = tls->invoke;
7252 tls->invoke = invoke;
7254 mono_loader_unlock ();
7256 tls->frames_up_to_date = FALSE;
7262 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
7263 buffer_init (&buf, 128);
7266 /* Fail the other invokes as well */
7268 err = do_invoke_method (tls, &buf, invoke, p, &p);
7271 if (tls->abort_requested) {
7272 if (CHECK_PROTOCOL_VERSION (2, 42))
7273 err = ERR_INVOKE_ABORTED;
7276 /* Start suspending before sending the reply */
7277 if (mindex == invoke->nmethods - 1) {
7278 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
7279 for (i = 0; i < invoke->suspend_count; ++i)
7284 send_reply_packet (id, err, &buf);
7289 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
7291 if (invoke->has_ctx)
7292 save_thread_context (&restore_ctx);
7294 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
7295 g_assert (tls->resume_count);
7296 tls->resume_count -= invoke->suspend_count;
7299 DEBUG_PRINTF (1, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer) (gsize) mono_native_thread_id_get (), err, tls->resume_count);
7302 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
7304 * It is possible that mono_thread_internal_abort () was called
7305 * after the mono_runtime_invoke_checked() already returned, but it doesn't matter
7306 * because we reset the abort here.
7309 mono_loader_lock ();
7311 if (tls->abort_requested)
7312 mono_thread_internal_reset_abort (tls->thread);
7314 tls->invoke = tls->invoke->last_invoke;
7315 tls->abort_requested = FALSE;
7317 mono_loader_unlock ();
7326 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
7328 MonoThread *thread = (MonoThread *)value;
7329 DebuggerTlsData *tls;
7332 mono_loader_lock ();
7333 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
7335 res = tls->really_suspended;
7336 mono_loader_unlock ();
7342 get_source_files_for_type (MonoClass *klass)
7344 gpointer iter = NULL;
7346 MonoDebugSourceInfo *sinfo;
7350 files = g_ptr_array_new ();
7352 while ((method = mono_class_get_methods (klass, &iter))) {
7353 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
7354 GPtrArray *source_file_list;
7357 mono_debug_get_seq_points (minfo, NULL, &source_file_list, NULL, NULL, NULL);
7358 for (j = 0; j < source_file_list->len; ++j) {
7359 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, j);
7360 for (i = 0; i < files->len; ++i)
7361 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
7363 if (i == files->len)
7364 g_ptr_array_add (files, g_strdup (sinfo->source_file));
7366 g_ptr_array_free (source_file_list, TRUE);
7374 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
7377 case CMD_VM_VERSION: {
7378 char *build_info, *version;
7380 build_info = mono_get_runtime_build_info ();
7381 version = g_strdup_printf ("mono %s", build_info);
7383 buffer_add_string (buf, version); /* vm version */
7384 buffer_add_int (buf, MAJOR_VERSION);
7385 buffer_add_int (buf, MINOR_VERSION);
7386 g_free (build_info);
7390 case CMD_VM_SET_PROTOCOL_VERSION: {
7391 major_version = decode_int (p, &p, end);
7392 minor_version = decode_int (p, &p, end);
7393 protocol_version_set = TRUE;
7394 DEBUG_PRINTF (1, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version);
7397 case CMD_VM_ALL_THREADS: {
7399 mono_loader_lock ();
7400 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
7401 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
7402 mono_loader_unlock ();
7405 case CMD_VM_SUSPEND:
7407 wait_for_suspend ();
7410 if (suspend_count == 0)
7411 return ERR_NOT_SUSPENDED;
7413 clear_suspended_objs ();
7415 case CMD_VM_DISPOSE:
7416 /* Clear all event requests */
7417 mono_loader_lock ();
7418 while (event_requests->len > 0) {
7419 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
7421 clear_event_request (req->id, req->event_kind);
7423 mono_loader_unlock ();
7425 while (suspend_count > 0)
7427 disconnected = TRUE;
7428 vm_start_event_sent = FALSE;
7431 MonoInternalThread *thread;
7432 DebuggerTlsData *tls;
7433 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7434 MonoClass *env_class;
7436 MonoMethod *exit_method = NULL;
7440 exit_code = decode_int (p, &p, end);
7442 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
7444 /* Have to send a reply before exiting */
7445 send_reply_packet (id, 0, buf);
7447 /* Clear all event requests */
7448 mono_loader_lock ();
7449 while (event_requests->len > 0) {
7450 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
7452 clear_event_request (req->id, req->event_kind);
7454 mono_loader_unlock ();
7457 * The JDWP documentation says that the shutdown is not orderly. It doesn't
7458 * specify whenever a VM_DEATH event is sent. We currently do an orderly
7459 * shutdown by hijacking a thread to execute Environment.Exit (). This is
7460 * better than doing the shutdown ourselves, since it avoids various races.
7464 wait_for_suspend ();
7466 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7467 env_class = mono_class_try_load_from_name (mono_defaults.corlib, "System", "Environment");
7469 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
7472 mono_loader_lock ();
7473 thread = (MonoInternalThread *)mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
7474 mono_loader_unlock ();
7476 if (thread && exit_method) {
7477 mono_loader_lock ();
7478 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
7479 mono_loader_unlock ();
7481 args = g_new0 (gpointer, 1);
7482 args [0] = g_malloc (sizeof (int));
7483 *(int*)(args [0]) = exit_code;
7485 tls->pending_invoke = g_new0 (InvokeData, 1);
7486 tls->pending_invoke->method = exit_method;
7487 tls->pending_invoke->args = args;
7488 tls->pending_invoke->nmethods = 1;
7490 while (suspend_count > 0)
7494 * No thread found, do it ourselves.
7495 * FIXME: This can race with normal shutdown etc.
7497 while (suspend_count > 0)
7500 if (!mono_runtime_try_shutdown ())
7503 mono_environment_exitcode_set (exit_code);
7505 /* Suspend all managed threads since the runtime is going away */
7506 DEBUG_PRINTF (1, "Suspending all threads...\n");
7507 mono_thread_suspend_all_other_threads ();
7508 DEBUG_PRINTF (1, "Shutting down the runtime...\n");
7509 mono_runtime_quit ();
7510 transport_close2 ();
7511 DEBUG_PRINTF (1, "Exiting...\n");
7517 case CMD_VM_INVOKE_METHOD:
7518 case CMD_VM_INVOKE_METHODS: {
7519 int objid = decode_objid (p, &p, end);
7521 DebuggerTlsData *tls;
7522 int i, count, flags, nmethods;
7525 err = get_object (objid, (MonoObject**)&thread);
7526 if (err != ERR_NONE)
7529 flags = decode_int (p, &p, end);
7531 if (command == CMD_VM_INVOKE_METHODS)
7532 nmethods = decode_int (p, &p, end);
7536 // Wait for suspending if it already started
7538 wait_for_suspend ();
7539 if (!is_suspended ())
7540 return ERR_NOT_SUSPENDED;
7542 mono_loader_lock ();
7543 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7544 mono_loader_unlock ();
7547 if (!tls->really_suspended)
7548 /* The thread is still running native code, can't do invokes */
7549 return ERR_NOT_SUSPENDED;
7552 * Store the invoke data into tls, the thread will execute it after it is
7555 if (tls->pending_invoke)
7556 return ERR_NOT_SUSPENDED;
7557 tls->pending_invoke = g_new0 (InvokeData, 1);
7558 tls->pending_invoke->id = id;
7559 tls->pending_invoke->flags = flags;
7560 tls->pending_invoke->p = (guint8 *)g_malloc (end - p);
7561 memcpy (tls->pending_invoke->p, p, end - p);
7562 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
7563 tls->pending_invoke->suspend_count = suspend_count;
7564 tls->pending_invoke->nmethods = nmethods;
7566 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
7567 resume_thread (THREAD_TO_INTERNAL (thread));
7570 count = suspend_count;
7571 for (i = 0; i < count; ++i)
7576 case CMD_VM_ABORT_INVOKE: {
7577 int objid = decode_objid (p, &p, end);
7579 DebuggerTlsData *tls;
7583 err = get_object (objid, (MonoObject**)&thread);
7584 if (err != ERR_NONE)
7587 invoke_id = decode_int (p, &p, end);
7589 mono_loader_lock ();
7590 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7593 if (tls->abort_requested) {
7594 DEBUG_PRINTF (1, "Abort already requested.\n");
7595 mono_loader_unlock ();
7600 * Check whether we're still inside the mono_runtime_invoke_checked() and that it's
7601 * actually the correct invocation.
7603 * Careful, we do not stop the thread that's doing the invocation, so we can't
7604 * inspect its stack. However, invoke_method() also acquires the loader lock
7605 * when it's done, so we're safe here.
7609 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
7610 mono_loader_unlock ();
7611 return ERR_NO_INVOCATION;
7614 tls->abort_requested = TRUE;
7616 mono_thread_internal_abort (THREAD_TO_INTERNAL (thread));
7617 mono_loader_unlock ();
7621 case CMD_VM_SET_KEEPALIVE: {
7622 int timeout = decode_int (p, &p, end);
7623 agent_config.keepalive = timeout;
7625 #ifndef DISABLE_SOCKET_TRANSPORT
7632 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
7633 GHashTableIter iter, kiter;
7638 char *fname, *basename;
7639 gboolean ignore_case;
7640 GSList *class_list, *l;
7641 GPtrArray *res_classes, *res_domains;
7643 fname = decode_string (p, &p, end);
7644 ignore_case = decode_byte (p, &p, end);
7646 basename = dbg_path_get_basename (fname);
7648 res_classes = g_ptr_array_new ();
7649 res_domains = g_ptr_array_new ();
7651 mono_loader_lock ();
7652 g_hash_table_iter_init (&iter, domains);
7653 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7654 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
7656 /* Update 'source_file_to_class' cache */
7657 g_hash_table_iter_init (&kiter, info->loaded_classes);
7658 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
7659 if (!g_hash_table_lookup (info->source_files, klass)) {
7660 files = get_source_files_for_type (klass);
7661 g_hash_table_insert (info->source_files, klass, files);
7663 for (i = 0; i < files->len; ++i) {
7664 char *s = (char *)g_ptr_array_index (files, i);
7665 char *s2 = dbg_path_get_basename (s);
7668 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, s2);
7670 class_list = g_slist_prepend (class_list, klass);
7671 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
7673 class_list = g_slist_prepend (class_list, klass);
7674 g_hash_table_insert (info->source_file_to_class, s2, class_list);
7677 /* The _ignorecase hash contains the lowercase path */
7678 s3 = strdup_tolower (s2);
7679 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
7681 class_list = g_slist_prepend (class_list, klass);
7682 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
7684 class_list = g_slist_prepend (class_list, klass);
7685 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
7697 s = strdup_tolower (basename);
7698 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
7701 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, basename);
7704 for (l = class_list; l; l = l->next) {
7705 klass = (MonoClass *)l->data;
7707 g_ptr_array_add (res_classes, klass);
7708 g_ptr_array_add (res_domains, domain);
7711 mono_loader_unlock ();
7716 buffer_add_int (buf, res_classes->len);
7717 for (i = 0; i < res_classes->len; ++i)
7718 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7719 g_ptr_array_free (res_classes, TRUE);
7720 g_ptr_array_free (res_domains, TRUE);
7723 case CMD_VM_GET_TYPES: {
7724 GHashTableIter iter;
7728 gboolean ignore_case;
7729 GPtrArray *res_classes, *res_domains;
7730 MonoTypeNameParse info;
7732 name = decode_string (p, &p, end);
7733 ignore_case = decode_byte (p, &p, end);
7735 if (!mono_reflection_parse_type (name, &info)) {
7737 mono_reflection_free_type_info (&info);
7738 return ERR_INVALID_ARGUMENT;
7741 res_classes = g_ptr_array_new ();
7742 res_domains = g_ptr_array_new ();
7744 mono_loader_lock ();
7745 g_hash_table_iter_init (&iter, domains);
7746 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7748 gboolean type_resolve;
7752 mono_domain_assemblies_lock (domain);
7753 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7754 ass = (MonoAssembly *)tmp->data;
7758 type_resolve = TRUE;
7759 /* FIXME really okay to call while holding locks? */
7760 t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignore_case, &type_resolve, &error);
7761 mono_error_cleanup (&error);
7763 g_ptr_array_add (res_classes, mono_type_get_class (t));
7764 g_ptr_array_add (res_domains, domain);
7768 mono_domain_assemblies_unlock (domain);
7770 mono_loader_unlock ();
7773 mono_reflection_free_type_info (&info);
7775 buffer_add_int (buf, res_classes->len);
7776 for (i = 0; i < res_classes->len; ++i)
7777 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7778 g_ptr_array_free (res_classes, TRUE);
7779 g_ptr_array_free (res_domains, TRUE);
7782 case CMD_VM_START_BUFFERING:
7783 case CMD_VM_STOP_BUFFERING:
7784 /* Handled in the main loop */
7787 return ERR_NOT_IMPLEMENTED;
7794 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7800 case CMD_EVENT_REQUEST_SET: {
7802 int i, event_kind, suspend_policy, nmodifiers;
7806 MonoThread *step_thread;
7807 int step_thread_id = 0;
7808 StepDepth depth = STEP_DEPTH_INTO;
7809 StepSize size = STEP_SIZE_MIN;
7810 StepFilter filter = STEP_FILTER_NONE;
7814 event_kind = decode_byte (p, &p, end);
7815 suspend_policy = decode_byte (p, &p, end);
7816 nmodifiers = decode_byte (p, &p, end);
7818 req = (EventRequest *)g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7819 req->id = InterlockedIncrement (&event_request_id);
7820 req->event_kind = event_kind;
7821 req->suspend_policy = suspend_policy;
7822 req->nmodifiers = nmodifiers;
7825 for (i = 0; i < nmodifiers; ++i) {
7826 mod = (ModifierKind)decode_byte (p, &p, end);
7828 req->modifiers [i].kind = mod;
7829 if (mod == MOD_KIND_COUNT) {
7830 req->modifiers [i].data.count = decode_int (p, &p, end);
7831 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7832 method = decode_methodid (p, &p, end, &domain, &err);
7833 if (err != ERR_NONE)
7835 location = decode_long (p, &p, end);
7836 } else if (mod == MOD_KIND_STEP) {
7837 step_thread_id = decode_id (p, &p, end);
7838 size = (StepSize)decode_int (p, &p, end);
7839 depth = (StepDepth)decode_int (p, &p, end);
7840 if (CHECK_PROTOCOL_VERSION (2, 16))
7841 filter = (StepFilter)decode_int (p, &p, end);
7842 req->modifiers [i].data.filter = filter;
7843 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7844 /* Treat STEP_THOUGH the same as HIDDEN */
7845 req->modifiers [i].data.filter = (StepFilter)(req->modifiers [i].data.filter | STEP_FILTER_DEBUGGER_STEP_THROUGH);
7846 } else if (mod == MOD_KIND_THREAD_ONLY) {
7847 int id = decode_id (p, &p, end);
7849 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7850 if (err != ERR_NONE) {
7854 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7855 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7857 if (err != ERR_NONE)
7859 req->modifiers [i].caught = decode_byte (p, &p, end);
7860 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7861 if (CHECK_PROTOCOL_VERSION (2, 25))
7862 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7864 req->modifiers [i].subclasses = TRUE;
7865 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" : "");
7867 req->modifiers [i].data.exc_class = exc_class;
7869 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
7871 return ERR_INVALID_ARGUMENT;
7874 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7875 int n = decode_int (p, &p, end);
7878 // +1 because we don't know length and we use last element to check for end
7879 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n + 1);
7880 for (j = 0; j < n; ++j) {
7881 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7882 if (err != ERR_NONE) {
7883 g_free (req->modifiers [i].data.assemblies);
7887 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7888 int n = decode_int (p, &p, end);
7891 modifier = &req->modifiers [i];
7892 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7893 for (j = 0; j < n; ++j) {
7894 char *s = decode_string (p, &p, end);
7898 s2 = strdup_tolower (s);
7899 g_hash_table_insert (modifier->data.source_files, s2, s2);
7903 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7904 int n = decode_int (p, &p, end);
7907 modifier = &req->modifiers [i];
7908 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7909 for (j = 0; j < n; ++j) {
7910 char *s = decode_string (p, &p, end);
7913 g_hash_table_insert (modifier->data.type_names, s, s);
7917 return ERR_NOT_IMPLEMENTED;
7921 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7924 req->info = set_breakpoint (method, location, req, &error);
7925 if (!mono_error_ok (&error)) {
7927 DEBUG_PRINTF (1, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error));
7928 mono_error_cleanup (&error);
7929 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7931 } else if (req->event_kind == EVENT_KIND_STEP) {
7932 g_assert (step_thread_id);
7934 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7935 if (err != ERR_NONE) {
7940 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, filter, req);
7941 if (err != ERR_NONE) {
7945 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7946 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7947 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7948 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7949 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7950 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7952 if (req->nmodifiers) {
7954 return ERR_NOT_IMPLEMENTED;
7958 mono_loader_lock ();
7959 g_ptr_array_add (event_requests, req);
7961 if (agent_config.defer) {
7962 /* Transmit cached data to the client on receipt of the event request */
7963 switch (req->event_kind) {
7964 case EVENT_KIND_APPDOMAIN_CREATE:
7965 /* Emit load events for currently loaded domains */
7966 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7968 case EVENT_KIND_ASSEMBLY_LOAD:
7969 /* Emit load events for currently loaded assemblies */
7970 mono_domain_foreach (send_assemblies_for_domain, NULL);
7972 case EVENT_KIND_THREAD_START:
7973 /* Emit start events for currently started threads */
7974 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7976 case EVENT_KIND_TYPE_LOAD:
7977 /* Emit type load events for currently loaded types */
7978 mono_domain_foreach (send_types_for_domain, NULL);
7984 mono_loader_unlock ();
7986 buffer_add_int (buf, req->id);
7989 case CMD_EVENT_REQUEST_CLEAR: {
7990 int etype = decode_byte (p, &p, end);
7991 int req_id = decode_int (p, &p, end);
7993 // FIXME: Make a faster mapping from req_id to request
7994 mono_loader_lock ();
7995 clear_event_request (req_id, etype);
7996 mono_loader_unlock ();
7999 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
8002 mono_loader_lock ();
8004 while (i < event_requests->len) {
8005 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
8007 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
8008 clear_breakpoint ((MonoBreakpoint *)req->info);
8010 g_ptr_array_remove_index_fast (event_requests, i);
8016 mono_loader_unlock ();
8020 return ERR_NOT_IMPLEMENTED;
8027 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8033 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
8034 buffer_add_domainid (buf, mono_get_root_domain ());
8037 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
8038 domain = decode_domainid (p, &p, end, NULL, &err);
8039 if (err != ERR_NONE)
8041 buffer_add_string (buf, domain->friendly_name);
8044 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
8049 domain = decode_domainid (p, &p, end, NULL, &err);
8050 if (err != ERR_NONE)
8052 mono_loader_lock ();
8054 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
8057 buffer_add_int (buf, count);
8058 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
8059 ass = (MonoAssembly *)tmp->data;
8060 buffer_add_assemblyid (buf, domain, ass);
8062 mono_loader_unlock ();
8065 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
8066 domain = decode_domainid (p, &p, end, NULL, &err);
8067 if (err != ERR_NONE)
8070 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
8073 case CMD_APPDOMAIN_GET_CORLIB: {
8074 domain = decode_domainid (p, &p, end, NULL, &err);
8075 if (err != ERR_NONE)
8078 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
8081 case CMD_APPDOMAIN_CREATE_STRING: {
8086 domain = decode_domainid (p, &p, end, NULL, &err);
8087 if (err != ERR_NONE)
8089 s = decode_string (p, &p, end);
8091 o = mono_string_new_checked (domain, s, &error);
8092 if (!is_ok (&error)) {
8093 DEBUG_PRINTF (1, "[dbg] Failed to allocate String object '%s': %s\n", s, mono_error_get_message (&error));
8094 mono_error_cleanup (&error);
8095 return ERR_INVALID_OBJECT;
8097 buffer_add_objid (buf, (MonoObject*)o);
8100 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
8103 MonoDomain *domain2;
8106 domain = decode_domainid (p, &p, end, NULL, &err);
8107 if (err != ERR_NONE)
8109 klass = decode_typeid (p, &p, end, &domain2, &err);
8110 if (err != ERR_NONE)
8114 g_assert (domain == domain2);
8116 o = mono_object_new_checked (domain, klass, &error);
8117 mono_error_assert_ok (&error);
8119 err = decode_value (&klass->byval_arg, domain, (guint8 *)mono_object_unbox (o), p, &p, end);
8120 if (err != ERR_NONE)
8123 buffer_add_objid (buf, o);
8127 return ERR_NOT_IMPLEMENTED;
8134 get_assembly_object_command (MonoDomain *domain, MonoAssembly *ass, Buffer *buf, MonoError *error)
8136 HANDLE_FUNCTION_ENTER();
8137 ErrorCode err = ERR_NONE;
8139 MonoReflectionAssemblyHandle o = mono_assembly_get_object_handle (domain, ass, error);
8140 if (MONO_HANDLE_IS_NULL (o)) {
8141 err = ERR_INVALID_OBJECT;
8144 buffer_add_objid (buf, MONO_HANDLE_RAW (MONO_HANDLE_CAST (MonoObject, o)));
8146 HANDLE_FUNCTION_RETURN_VAL (err);
8151 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8157 ass = decode_assemblyid (p, &p, end, &domain, &err);
8158 if (err != ERR_NONE)
8162 case CMD_ASSEMBLY_GET_LOCATION: {
8163 buffer_add_string (buf, mono_image_get_filename (ass->image));
8166 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
8170 if (ass->image->dynamic) {
8171 buffer_add_id (buf, 0);
8173 token = mono_image_get_entry_point (ass->image);
8175 buffer_add_id (buf, 0);
8178 m = mono_get_method_checked (ass->image, token, NULL, NULL, &error);
8180 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8181 buffer_add_methodid (buf, domain, m);
8186 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
8187 buffer_add_moduleid (buf, domain, ass->image);
8190 case CMD_ASSEMBLY_GET_OBJECT: {
8192 err = get_assembly_object_command (domain, ass, buf, &error);
8193 mono_error_cleanup (&error);
8196 case CMD_ASSEMBLY_GET_DOMAIN: {
8197 buffer_add_domainid (buf, domain);
8200 case CMD_ASSEMBLY_GET_TYPE: {
8202 char *s = decode_string (p, &p, end);
8203 gboolean ignorecase = decode_byte (p, &p, end);
8204 MonoTypeNameParse info;
8206 gboolean type_resolve, res;
8207 MonoDomain *d = mono_domain_get ();
8209 /* This is needed to be able to find referenced assemblies */
8210 res = mono_domain_set (domain, FALSE);
8213 if (!mono_reflection_parse_type (s, &info)) {
8216 if (info.assembly.name)
8218 t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignorecase, &type_resolve, &error);
8219 if (!is_ok (&error)) {
8220 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8221 mono_reflection_free_type_info (&info);
8223 return ERR_INVALID_ARGUMENT;
8226 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
8227 mono_reflection_free_type_info (&info);
8230 mono_domain_set (d, TRUE);
8234 case CMD_ASSEMBLY_GET_NAME: {
8236 MonoAssembly *mass = ass;
8238 name = g_strdup_printf (
8239 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
8241 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
8242 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
8243 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
8244 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
8246 buffer_add_string (buf, name);
8251 return ERR_NOT_IMPLEMENTED;
8258 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8264 case CMD_MODULE_GET_INFO: {
8265 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
8268 basename = g_path_get_basename (image->name);
8269 buffer_add_string (buf, basename); // name
8270 buffer_add_string (buf, image->module_name); // scopename
8271 buffer_add_string (buf, image->name); // fqname
8272 buffer_add_string (buf, mono_image_get_guid (image)); // guid
8273 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
8278 return ERR_NOT_IMPLEMENTED;
8285 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8291 case CMD_FIELD_GET_INFO: {
8292 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
8294 buffer_add_string (buf, f->name);
8295 buffer_add_typeid (buf, domain, f->parent);
8296 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
8297 buffer_add_int (buf, f->type->attrs);
8301 return ERR_NOT_IMPLEMENTED;
8308 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
8310 if (val && val->vtable->klass == mono_defaults.runtimetype_class) {
8311 /* Special case these so the client doesn't have to handle Type objects */
8313 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
8314 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
8315 } else if (MONO_TYPE_IS_REFERENCE (t))
8316 buffer_add_value (buf, t, &val, domain);
8318 buffer_add_value (buf, t, mono_object_unbox (val), domain);
8322 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
8328 buffer_add_int (buf, 0);
8332 for (i = 0; i < cinfo->num_attrs; ++i) {
8333 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
8336 buffer_add_int (buf, nattrs);
8338 for (i = 0; i < cinfo->num_attrs; ++i) {
8339 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
8340 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
8341 MonoArray *typed_args, *named_args;
8343 CattrNamedArg *arginfo = NULL;
8346 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
8347 if (!mono_error_ok (&error)) {
8348 DEBUG_PRINTF (2, "[dbg] mono_reflection_create_custom_attr_data_args () failed with: '%s'\n", mono_error_get_message (&error));
8349 mono_error_cleanup (&error);
8350 return ERR_LOADER_ERROR;
8353 buffer_add_methodid (buf, domain, attr->ctor);
8357 buffer_add_int (buf, mono_array_length (typed_args));
8358 for (j = 0; j < mono_array_length (typed_args); ++j) {
8359 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
8361 t = mono_method_signature (attr->ctor)->params [j];
8363 buffer_add_cattr_arg (buf, t, domain, val);
8366 buffer_add_int (buf, 0);
8371 buffer_add_int (buf, mono_array_length (named_args));
8373 for (j = 0; j < mono_array_length (named_args); ++j) {
8374 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
8376 if (arginfo [j].prop) {
8377 buffer_add_byte (buf, 0x54);
8378 buffer_add_propertyid (buf, domain, arginfo [j].prop);
8379 } else if (arginfo [j].field) {
8380 buffer_add_byte (buf, 0x53);
8381 buffer_add_fieldid (buf, domain, arginfo [j].field);
8383 g_assert_not_reached ();
8386 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
8389 buffer_add_int (buf, 0);
8398 /* FIXME: Code duplication with icall.c */
8400 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
8405 mono_class_setup_interfaces (klass, error);
8406 if (!mono_error_ok (error))
8409 for (i = 0; i < klass->interface_count; i++) {
8410 ic = klass->interfaces [i];
8411 g_hash_table_insert (ifaces, ic, ic);
8413 collect_interfaces (ic, ifaces, error);
8414 if (!mono_error_ok (error))
8420 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8432 case CMD_TYPE_GET_INFO: {
8433 buffer_add_string (buf, klass->name_space);
8434 buffer_add_string (buf, klass->name);
8436 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
8437 buffer_add_string (buf, name);
8439 buffer_add_assemblyid (buf, domain, klass->image->assembly);
8440 buffer_add_moduleid (buf, domain, klass->image);
8441 buffer_add_typeid (buf, domain, klass->parent);
8442 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
8443 buffer_add_typeid (buf, domain, klass->element_class);
8445 buffer_add_id (buf, 0);
8446 buffer_add_int (buf, klass->type_token);
8447 buffer_add_byte (buf, klass->rank);
8448 buffer_add_int (buf, mono_class_get_flags (klass));
8450 type = &klass->byval_arg;
8451 // FIXME: Can't decide whenever a class represents a byref type
8454 if (type->type == MONO_TYPE_PTR)
8456 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
8458 if (type->type == MONO_TYPE_VALUETYPE)
8460 if (klass->enumtype)
8462 if (mono_class_is_gtd (klass))
8464 if (mono_class_is_gtd (klass) || mono_class_is_ginst (klass))
8466 buffer_add_byte (buf, b);
8469 while ((nested = mono_class_get_nested_types (klass, &iter)))
8471 buffer_add_int (buf, nnested);
8473 while ((nested = mono_class_get_nested_types (klass, &iter)))
8474 buffer_add_typeid (buf, domain, nested);
8475 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8476 if (mono_class_is_gtd (klass))
8477 buffer_add_typeid (buf, domain, klass);
8478 else if (mono_class_is_ginst (klass))
8479 buffer_add_typeid (buf, domain, mono_class_get_generic_class (klass)->container_class);
8481 buffer_add_id (buf, 0);
8483 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8486 if (mono_class_is_ginst (klass)) {
8487 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
8489 count = inst->type_argc;
8490 buffer_add_int (buf, count);
8491 for (i = 0; i < count; i++)
8492 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8493 } else if (mono_class_is_gtd (klass)) {
8494 MonoGenericContainer *container = mono_class_get_generic_container (klass);
8497 count = container->type_argc;
8498 buffer_add_int (buf, count);
8499 for (i = 0; i < count; i++) {
8500 pklass = mono_class_from_generic_parameter_internal (mono_generic_container_get_param (container, i));
8501 buffer_add_typeid (buf, domain, pklass);
8504 buffer_add_int (buf, 0);
8509 case CMD_TYPE_GET_METHODS: {
8512 gpointer iter = NULL;
8515 mono_class_setup_methods (klass);
8517 nmethods = mono_class_num_methods (klass);
8519 buffer_add_int (buf, nmethods);
8521 while ((m = mono_class_get_methods (klass, &iter))) {
8522 buffer_add_methodid (buf, domain, m);
8525 g_assert (i == nmethods);
8528 case CMD_TYPE_GET_FIELDS: {
8531 gpointer iter = NULL;
8534 nfields = mono_class_num_fields (klass);
8536 buffer_add_int (buf, nfields);
8538 while ((f = mono_class_get_fields (klass, &iter))) {
8539 buffer_add_fieldid (buf, domain, f);
8540 buffer_add_string (buf, f->name);
8541 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
8542 buffer_add_int (buf, f->type->attrs);
8545 g_assert (i == nfields);
8548 case CMD_TYPE_GET_PROPERTIES: {
8551 gpointer iter = NULL;
8554 nprops = mono_class_num_properties (klass);
8556 buffer_add_int (buf, nprops);
8558 while ((p = mono_class_get_properties (klass, &iter))) {
8559 buffer_add_propertyid (buf, domain, p);
8560 buffer_add_string (buf, p->name);
8561 buffer_add_methodid (buf, domain, p->get);
8562 buffer_add_methodid (buf, domain, p->set);
8563 buffer_add_int (buf, p->attrs);
8566 g_assert (i == nprops);
8569 case CMD_TYPE_GET_CATTRS: {
8570 MonoClass *attr_klass;
8571 MonoCustomAttrInfo *cinfo;
8573 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8574 /* attr_klass can be NULL */
8575 if (err != ERR_NONE)
8578 cinfo = mono_custom_attrs_from_class_checked (klass, &error);
8579 if (!is_ok (&error)) {
8580 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8581 return ERR_LOADER_ERROR;
8584 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8585 if (err != ERR_NONE)
8589 case CMD_TYPE_GET_FIELD_CATTRS: {
8590 MonoClass *attr_klass;
8591 MonoCustomAttrInfo *cinfo;
8592 MonoClassField *field;
8594 field = decode_fieldid (p, &p, end, NULL, &err);
8595 if (err != ERR_NONE)
8597 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8598 if (err != ERR_NONE)
8601 cinfo = mono_custom_attrs_from_field_checked (klass, field, &error);
8602 if (!is_ok (&error)) {
8603 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8604 return ERR_LOADER_ERROR;
8607 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8608 if (err != ERR_NONE)
8612 case CMD_TYPE_GET_PROPERTY_CATTRS: {
8613 MonoClass *attr_klass;
8614 MonoCustomAttrInfo *cinfo;
8617 prop = decode_propertyid (p, &p, end, NULL, &err);
8618 if (err != ERR_NONE)
8620 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8621 if (err != ERR_NONE)
8624 cinfo = mono_custom_attrs_from_property_checked (klass, prop, &error);
8625 if (!is_ok (&error)) {
8626 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8627 return ERR_LOADER_ERROR;
8630 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8631 if (err != ERR_NONE)
8635 case CMD_TYPE_GET_VALUES:
8636 case CMD_TYPE_GET_VALUES_2: {
8643 MonoThread *thread_obj;
8644 MonoInternalThread *thread = NULL;
8645 guint32 special_static_type;
8647 if (command == CMD_TYPE_GET_VALUES_2) {
8648 int objid = decode_objid (p, &p, end);
8651 err = get_object (objid, (MonoObject**)&thread_obj);
8652 if (err != ERR_NONE)
8655 thread = THREAD_TO_INTERNAL (thread_obj);
8658 len = decode_int (p, &p, end);
8659 for (i = 0; i < len; ++i) {
8660 f = decode_fieldid (p, &p, end, NULL, &err);
8661 if (err != ERR_NONE)
8664 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8665 return ERR_INVALID_FIELDID;
8666 special_static_type = mono_class_field_get_special_static_type (f);
8667 if (special_static_type != SPECIAL_STATIC_NONE) {
8668 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
8669 return ERR_INVALID_FIELDID;
8672 /* Check that the field belongs to the object */
8674 for (k = klass; k; k = k->parent) {
8675 if (k == f->parent) {
8681 return ERR_INVALID_FIELDID;
8683 vtable = mono_class_vtable (domain, f->parent);
8684 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8685 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val, &error);
8686 if (!is_ok (&error))
8687 return ERR_INVALID_FIELDID;
8688 buffer_add_value (buf, f->type, val, domain);
8693 case CMD_TYPE_SET_VALUES: {
8701 len = decode_int (p, &p, end);
8702 for (i = 0; i < len; ++i) {
8703 f = decode_fieldid (p, &p, end, NULL, &err);
8704 if (err != ERR_NONE)
8707 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8708 return ERR_INVALID_FIELDID;
8709 if (mono_class_field_is_special_static (f))
8710 return ERR_INVALID_FIELDID;
8712 /* Check that the field belongs to the object */
8714 for (k = klass; k; k = k->parent) {
8715 if (k == f->parent) {
8721 return ERR_INVALID_FIELDID;
8723 // FIXME: Check for literal/const
8725 vtable = mono_class_vtable (domain, f->parent);
8726 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8727 err = decode_value (f->type, domain, val, p, &p, end);
8728 if (err != ERR_NONE) {
8732 if (MONO_TYPE_IS_REFERENCE (f->type))
8733 mono_field_static_set_value (vtable, f, *(gpointer*)val);
8735 mono_field_static_set_value (vtable, f, val);
8740 case CMD_TYPE_GET_OBJECT: {
8741 MonoObject *o = (MonoObject*)mono_type_get_object_checked (domain, &klass->byval_arg, &error);
8742 if (!mono_error_ok (&error)) {
8743 mono_error_cleanup (&error);
8744 return ERR_INVALID_OBJECT;
8746 buffer_add_objid (buf, o);
8749 case CMD_TYPE_GET_SOURCE_FILES:
8750 case CMD_TYPE_GET_SOURCE_FILES_2: {
8751 char *source_file, *base;
8755 files = get_source_files_for_type (klass);
8757 buffer_add_int (buf, files->len);
8758 for (i = 0; i < files->len; ++i) {
8759 source_file = (char *)g_ptr_array_index (files, i);
8760 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8761 buffer_add_string (buf, source_file);
8763 base = dbg_path_get_basename (source_file);
8764 buffer_add_string (buf, base);
8767 g_free (source_file);
8769 g_ptr_array_free (files, TRUE);
8772 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8773 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8775 if (err != ERR_NONE)
8777 if (mono_class_is_assignable_from (klass, oklass))
8778 buffer_add_byte (buf, 1);
8780 buffer_add_byte (buf, 0);
8783 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8784 char *name = decode_string (p, &p, end);
8785 int i, flags = decode_int (p, &p, end);
8789 error_init (&error);
8790 array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &error);
8791 if (!is_ok (&error)) {
8792 mono_error_cleanup (&error);
8793 return ERR_LOADER_ERROR;
8795 buffer_add_int (buf, array->len);
8796 for (i = 0; i < array->len; ++i) {
8797 MonoMethod *method = (MonoMethod *)g_ptr_array_index (array, i);
8798 buffer_add_methodid (buf, domain, method);
8801 g_ptr_array_free (array, TRUE);
8805 case CMD_TYPE_GET_INTERFACES: {
8807 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8808 MonoClass *tclass, *iface;
8809 GHashTableIter iter;
8813 for (parent = tclass; parent; parent = parent->parent) {
8814 mono_class_setup_interfaces (parent, &error);
8815 if (!mono_error_ok (&error))
8816 return ERR_LOADER_ERROR;
8817 collect_interfaces (parent, iface_hash, &error);
8818 if (!mono_error_ok (&error))
8819 return ERR_LOADER_ERROR;
8822 buffer_add_int (buf, g_hash_table_size (iface_hash));
8824 g_hash_table_iter_init (&iter, iface_hash);
8825 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8826 buffer_add_typeid (buf, domain, iface);
8827 g_hash_table_destroy (iface_hash);
8830 case CMD_TYPE_GET_INTERFACE_MAP: {
8831 int tindex, ioffset;
8832 gboolean variance_used;
8834 int len, nmethods, i;
8838 len = decode_int (p, &p, end);
8839 mono_class_setup_vtable (klass);
8841 for (tindex = 0; tindex < len; ++tindex) {
8842 iclass = decode_typeid (p, &p, end, NULL, &err);
8843 if (err != ERR_NONE)
8846 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8848 return ERR_INVALID_ARGUMENT;
8850 nmethods = mono_class_num_methods (iclass);
8851 buffer_add_int (buf, nmethods);
8854 while ((method = mono_class_get_methods (iclass, &iter))) {
8855 buffer_add_methodid (buf, domain, method);
8857 for (i = 0; i < nmethods; ++i)
8858 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
8862 case CMD_TYPE_IS_INITIALIZED: {
8863 MonoVTable *vtable = mono_class_vtable (domain, klass);
8866 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8868 buffer_add_int (buf, 0);
8871 case CMD_TYPE_CREATE_INSTANCE: {
8875 obj = mono_object_new_checked (domain, klass, &error);
8876 mono_error_assert_ok (&error);
8877 buffer_add_objid (buf, obj);
8881 return ERR_NOT_IMPLEMENTED;
8888 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8891 MonoDomain *old_domain;
8895 klass = decode_typeid (p, &p, end, &domain, &err);
8896 if (err != ERR_NONE)
8899 old_domain = mono_domain_get ();
8901 mono_domain_set (domain, TRUE);
8903 err = type_commands_internal (command, klass, domain, p, end, buf);
8905 mono_domain_set (old_domain, TRUE);
8911 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8913 MonoMethodHeader *header;
8917 case CMD_METHOD_GET_NAME: {
8918 buffer_add_string (buf, method->name);
8921 case CMD_METHOD_GET_DECLARING_TYPE: {
8922 buffer_add_typeid (buf, domain, method->klass);
8925 case CMD_METHOD_GET_DEBUG_INFO: {
8927 MonoDebugMethodInfo *minfo;
8929 int i, j, n_il_offsets;
8931 GPtrArray *source_file_list;
8932 MonoSymSeqPoint *sym_seq_points;
8934 header = mono_method_get_header_checked (method, &error);
8936 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8937 buffer_add_int (buf, 0);
8938 buffer_add_string (buf, "");
8939 buffer_add_int (buf, 0);
8943 minfo = mono_debug_lookup_method (method);
8945 buffer_add_int (buf, header->code_size);
8946 buffer_add_string (buf, "");
8947 buffer_add_int (buf, 0);
8948 mono_metadata_free_mh (header);
8952 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, &source_files, &sym_seq_points, &n_il_offsets);
8953 buffer_add_int (buf, header->code_size);
8954 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8955 buffer_add_int (buf, source_file_list->len);
8956 for (i = 0; i < source_file_list->len; ++i) {
8957 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
8958 buffer_add_string (buf, sinfo->source_file);
8959 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8960 for (j = 0; j < 16; ++j)
8961 buffer_add_byte (buf, sinfo->hash [j]);
8965 buffer_add_string (buf, source_file);
8967 buffer_add_int (buf, n_il_offsets);
8968 DEBUG_PRINTF (10, "Line number table for method %s:\n", mono_method_full_name (method, TRUE));
8969 for (i = 0; i < n_il_offsets; ++i) {
8970 MonoSymSeqPoint *sp = &sym_seq_points [i];
8971 const char *srcfile = "";
8973 if (source_files [i] != -1) {
8974 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, source_files [i]);
8975 srcfile = sinfo->source_file;
8977 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);
8978 buffer_add_int (buf, sp->il_offset);
8979 buffer_add_int (buf, sp->line);
8980 if (CHECK_PROTOCOL_VERSION (2, 13))
8981 buffer_add_int (buf, source_files [i]);
8982 if (CHECK_PROTOCOL_VERSION (2, 19))
8983 buffer_add_int (buf, sp->column);
8984 if (CHECK_PROTOCOL_VERSION (2, 32)) {
8985 buffer_add_int (buf, sp->end_line);
8986 buffer_add_int (buf, sp->end_column);
8989 g_free (source_file);
8990 g_free (source_files);
8991 g_free (sym_seq_points);
8992 g_ptr_array_free (source_file_list, TRUE);
8993 mono_metadata_free_mh (header);
8996 case CMD_METHOD_GET_PARAM_INFO: {
8997 MonoMethodSignature *sig = mono_method_signature (method);
9001 /* FIXME: mono_class_from_mono_type () and byrefs */
9003 /* FIXME: Use a smaller encoding */
9004 buffer_add_int (buf, sig->call_convention);
9005 buffer_add_int (buf, sig->param_count);
9006 buffer_add_int (buf, sig->generic_param_count);
9007 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
9008 for (i = 0; i < sig->param_count; ++i) {
9010 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
9013 /* Emit parameter names */
9014 names = g_new (char *, sig->param_count);
9015 mono_method_get_param_names (method, (const char **) names);
9016 for (i = 0; i < sig->param_count; ++i)
9017 buffer_add_string (buf, names [i]);
9022 case CMD_METHOD_GET_LOCALS_INFO: {
9025 MonoDebugLocalsInfo *locals;
9026 int *locals_map = NULL;
9028 header = mono_method_get_header_checked (method, &error);
9030 mono_error_cleanup (&error); /* FIXME don't swallow the error */
9031 return ERR_INVALID_ARGUMENT;
9034 locals = mono_debug_lookup_locals (method);
9036 if (CHECK_PROTOCOL_VERSION (2, 43)) {
9038 buffer_add_int (buf, 1);
9039 buffer_add_int (buf, 0);
9040 buffer_add_int (buf, header->code_size);
9042 buffer_add_int (buf, header->num_locals);
9044 for (i = 0; i < header->num_locals; ++i) {
9045 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
9048 for (i = 0; i < header->num_locals; ++i) {
9050 sprintf (lname, "V_%d", i);
9051 buffer_add_string (buf, lname);
9054 for (i = 0; i < header->num_locals; ++i) {
9055 buffer_add_int (buf, 0);
9056 buffer_add_int (buf, header->code_size);
9059 if (CHECK_PROTOCOL_VERSION (2, 43)) {
9061 buffer_add_int (buf, locals->num_blocks);
9063 for (i = 0; i < locals->num_blocks; ++i) {
9064 buffer_add_int (buf, locals->code_blocks [i].start_offset - last_start);
9065 buffer_add_int (buf, locals->code_blocks [i].end_offset - locals->code_blocks [i].start_offset);
9066 last_start = locals->code_blocks [i].start_offset;
9070 num_locals = locals->num_locals;
9071 buffer_add_int (buf, num_locals);
9074 for (i = 0; i < num_locals; ++i) {
9075 g_assert (locals->locals [i].index < header->num_locals);
9076 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [locals->locals [i].index]));
9079 for (i = 0; i < num_locals; ++i)
9080 buffer_add_string (buf, locals->locals [i].name);
9082 for (i = 0; i < num_locals; ++i) {
9083 if (locals->locals [i].block) {
9084 buffer_add_int (buf, locals->locals [i].block->start_offset);
9085 buffer_add_int (buf, locals->locals [i].block->end_offset);
9087 buffer_add_int (buf, 0);
9088 buffer_add_int (buf, header->code_size);
9092 mono_metadata_free_mh (header);
9095 mono_debug_free_locals (locals);
9096 g_free (locals_map);
9100 case CMD_METHOD_GET_INFO:
9101 buffer_add_int (buf, method->flags);
9102 buffer_add_int (buf, method->iflags);
9103 buffer_add_int (buf, method->token);
9104 if (CHECK_PROTOCOL_VERSION (2, 12)) {
9106 if (method->is_generic)
9108 if (mono_method_signature (method)->generic_param_count)
9110 buffer_add_byte (buf, attrs);
9111 if (method->is_generic || method->is_inflated) {
9114 if (method->is_generic) {
9117 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
9119 result = imethod->declaring;
9120 if (imethod->context.class_inst) {
9121 MonoClass *klass = ((MonoMethod *) imethod)->klass;
9122 /*Generic methods gets the context of the GTD.*/
9123 if (mono_class_get_context (klass)) {
9125 result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), &error);
9126 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9131 buffer_add_methodid (buf, domain, result);
9133 buffer_add_id (buf, 0);
9135 if (CHECK_PROTOCOL_VERSION (2, 15)) {
9136 if (mono_method_signature (method)->generic_param_count) {
9139 if (method->is_inflated) {
9140 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
9142 count = inst->type_argc;
9143 buffer_add_int (buf, count);
9145 for (i = 0; i < count; i++)
9146 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
9148 buffer_add_int (buf, 0);
9150 } else if (method->is_generic) {
9151 MonoGenericContainer *container = mono_method_get_generic_container (method);
9153 count = mono_method_signature (method)->generic_param_count;
9154 buffer_add_int (buf, count);
9155 for (i = 0; i < count; i++) {
9156 MonoGenericParam *param = mono_generic_container_get_param (container, i);
9157 MonoClass *pklass = mono_class_from_generic_parameter_internal (param);
9158 buffer_add_typeid (buf, domain, pklass);
9161 buffer_add_int (buf, 0);
9164 buffer_add_int (buf, 0);
9169 case CMD_METHOD_GET_BODY: {
9173 header = mono_method_get_header_checked (method, &error);
9175 mono_error_cleanup (&error); /* FIXME don't swallow the error */
9176 buffer_add_int (buf, 0);
9178 if (CHECK_PROTOCOL_VERSION (2, 18))
9179 buffer_add_int (buf, 0);
9181 buffer_add_int (buf, header->code_size);
9182 for (i = 0; i < header->code_size; ++i)
9183 buffer_add_byte (buf, header->code [i]);
9185 if (CHECK_PROTOCOL_VERSION (2, 18)) {
9186 buffer_add_int (buf, header->num_clauses);
9187 for (i = 0; i < header->num_clauses; ++i) {
9188 MonoExceptionClause *clause = &header->clauses [i];
9190 buffer_add_int (buf, clause->flags);
9191 buffer_add_int (buf, clause->try_offset);
9192 buffer_add_int (buf, clause->try_len);
9193 buffer_add_int (buf, clause->handler_offset);
9194 buffer_add_int (buf, clause->handler_len);
9195 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
9196 buffer_add_typeid (buf, domain, clause->data.catch_class);
9197 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
9198 buffer_add_int (buf, clause->data.filter_offset);
9202 mono_metadata_free_mh (header);
9207 case CMD_METHOD_RESOLVE_TOKEN: {
9208 guint32 token = decode_int (p, &p, end);
9211 switch (mono_metadata_token_code (token)) {
9212 case MONO_TOKEN_STRING: {
9217 s = mono_ldstr_checked (domain, method->klass->image, mono_metadata_token_index (token), &error);
9218 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
9220 s2 = mono_string_to_utf8_checked (s, &error);
9221 mono_error_assert_ok (&error);
9223 buffer_add_byte (buf, TOKEN_TYPE_STRING);
9224 buffer_add_string (buf, s2);
9231 MonoClass *handle_class;
9233 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
9234 val = mono_method_get_wrapper_data (method, token);
9235 handle_class = (MonoClass *)mono_method_get_wrapper_data (method, token + 1);
9237 if (handle_class == NULL) {
9238 // Can't figure out the token type
9239 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
9243 val = mono_ldtoken_checked (method->klass->image, token, &handle_class, NULL, &error);
9245 g_error ("Could not load token due to %s", mono_error_get_message (&error));
9248 if (handle_class == mono_defaults.typehandle_class) {
9249 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
9250 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
9251 buffer_add_typeid (buf, domain, (MonoClass *) val);
9253 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
9254 } else if (handle_class == mono_defaults.fieldhandle_class) {
9255 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
9256 buffer_add_fieldid (buf, domain, (MonoClassField *)val);
9257 } else if (handle_class == mono_defaults.methodhandle_class) {
9258 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
9259 buffer_add_methodid (buf, domain, (MonoMethod *)val);
9260 } else if (handle_class == mono_defaults.string_class) {
9263 s = mono_string_to_utf8_checked ((MonoString *)val, &error);
9264 mono_error_assert_ok (&error);
9265 buffer_add_byte (buf, TOKEN_TYPE_STRING);
9266 buffer_add_string (buf, s);
9269 g_assert_not_reached ();
9276 case CMD_METHOD_GET_CATTRS: {
9278 MonoClass *attr_klass;
9279 MonoCustomAttrInfo *cinfo;
9281 attr_klass = decode_typeid (p, &p, end, NULL, &err);
9282 /* attr_klass can be NULL */
9283 if (err != ERR_NONE)
9286 cinfo = mono_custom_attrs_from_method_checked (method, &error);
9287 if (!is_ok (&error)) {
9288 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
9289 return ERR_LOADER_ERROR;
9292 err = buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
9293 if (err != ERR_NONE)
9297 case CMD_METHOD_MAKE_GENERIC_METHOD: {
9299 MonoType **type_argv;
9303 MonoGenericInst *ginst;
9304 MonoGenericContext tmp_context;
9305 MonoMethod *inflated;
9307 type_argc = decode_int (p, &p, end);
9308 type_argv = g_new0 (MonoType*, type_argc);
9309 for (i = 0; i < type_argc; ++i) {
9310 klass = decode_typeid (p, &p, end, &d, &err);
9311 if (err != ERR_NONE) {
9317 return ERR_INVALID_ARGUMENT;
9319 type_argv [i] = &klass->byval_arg;
9321 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
9323 tmp_context.class_inst = mono_class_is_ginst (method->klass) ? mono_class_get_generic_class (method->klass)->context.class_inst : NULL;
9324 tmp_context.method_inst = ginst;
9326 inflated = mono_class_inflate_generic_method_checked (method, &tmp_context, &error);
9327 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9328 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
9329 return ERR_INVALID_ARGUMENT;
9330 buffer_add_methodid (buf, domain, inflated);
9334 return ERR_NOT_IMPLEMENTED;
9341 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9344 MonoDomain *old_domain;
9348 method = decode_methodid (p, &p, end, &domain, &err);
9349 if (err != ERR_NONE)
9352 old_domain = mono_domain_get ();
9354 mono_domain_set (domain, TRUE);
9356 err = method_commands_internal (command, method, domain, p, end, buf);
9358 mono_domain_set (old_domain, TRUE);
9364 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9366 int objid = decode_objid (p, &p, end);
9368 MonoThread *thread_obj;
9369 MonoInternalThread *thread;
9371 err = get_object (objid, (MonoObject**)&thread_obj);
9372 if (err != ERR_NONE)
9375 thread = THREAD_TO_INTERNAL (thread_obj);
9378 case CMD_THREAD_GET_NAME: {
9380 gunichar2 *s = mono_thread_get_name (thread, &name_len);
9383 buffer_add_int (buf, 0);
9388 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
9390 buffer_add_int (buf, len);
9391 buffer_add_data (buf, (guint8*)name, len);
9396 case CMD_THREAD_GET_FRAME_INFO: {
9397 DebuggerTlsData *tls;
9398 int i, start_frame, length;
9400 // Wait for suspending if it already started
9401 // FIXME: Races with suspend_count
9402 while (!is_suspended ()) {
9404 wait_for_suspend ();
9408 wait_for_suspend ();
9409 if (!is_suspended ())
9410 return ERR_NOT_SUSPENDED;
9413 start_frame = decode_int (p, &p, end);
9414 length = decode_int (p, &p, end);
9416 if (start_frame != 0 || length != -1)
9417 return ERR_NOT_IMPLEMENTED;
9419 mono_loader_lock ();
9420 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9421 mono_loader_unlock ();
9424 compute_frame_info (thread, tls);
9426 buffer_add_int (buf, tls->frame_count);
9427 for (i = 0; i < tls->frame_count; ++i) {
9428 buffer_add_int (buf, tls->frames [i]->id);
9429 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
9430 buffer_add_int (buf, tls->frames [i]->il_offset);
9432 * Instead of passing the frame type directly to the client, we associate
9433 * it with the previous frame using a set of flags. This avoids lots of
9434 * conditional code in the client, since a frame whose type isn't
9435 * FRAME_TYPE_MANAGED has no method, location, etc.
9437 buffer_add_byte (buf, tls->frames [i]->flags);
9442 case CMD_THREAD_GET_STATE:
9443 buffer_add_int (buf, thread->state);
9445 case CMD_THREAD_GET_INFO:
9446 buffer_add_byte (buf, thread->threadpool_thread);
9448 case CMD_THREAD_GET_ID:
9449 buffer_add_long (buf, (guint64)(gsize)thread);
9451 case CMD_THREAD_GET_TID:
9452 buffer_add_long (buf, (guint64)thread->tid);
9454 case CMD_THREAD_SET_IP: {
9455 DebuggerTlsData *tls;
9458 MonoSeqPointInfo *seq_points;
9463 method = decode_methodid (p, &p, end, &domain, &err);
9464 if (err != ERR_NONE)
9466 il_offset = decode_long (p, &p, end);
9468 while (!is_suspended ()) {
9470 wait_for_suspend ();
9473 mono_loader_lock ();
9474 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9475 mono_loader_unlock ();
9478 compute_frame_info (thread, tls);
9479 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
9480 return ERR_INVALID_ARGUMENT;
9482 found_sp = mono_find_seq_point (domain, method, il_offset, &seq_points, &sp);
9484 g_assert (seq_points);
9487 return ERR_INVALID_ARGUMENT;
9489 // FIXME: Check that the ip change is safe
9491 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);
9493 if (tls->frames [0]->ji->is_interp) {
9494 MonoJitTlsData *jit_data = ((MonoThreadInfo*)thread->thread_info)->jit_data;
9495 mono_interp_set_resume_state (jit_data, NULL, tls->frames [0]->interp_frame, (guint8*)tls->frames [0]->ji->code_start + sp.native_offset);
9497 MONO_CONTEXT_SET_IP (&tls->restore_state.ctx, (guint8*)tls->frames [0]->ji->code_start + sp.native_offset);
9502 return ERR_NOT_IMPLEMENTED;
9509 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9513 MonoThread *thread_obj;
9514 MonoInternalThread *thread;
9515 int pos, i, len, frame_idx;
9516 DebuggerTlsData *tls;
9518 MonoDebugMethodJitInfo *jit;
9519 MonoMethodSignature *sig;
9521 MonoMethodHeader *header;
9523 objid = decode_objid (p, &p, end);
9524 err = get_object (objid, (MonoObject**)&thread_obj);
9525 if (err != ERR_NONE)
9528 thread = THREAD_TO_INTERNAL (thread_obj);
9530 id = decode_id (p, &p, end);
9532 mono_loader_lock ();
9533 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9534 mono_loader_unlock ();
9537 for (i = 0; i < tls->frame_count; ++i) {
9538 if (tls->frames [i]->id == id)
9541 if (i == tls->frame_count)
9542 return ERR_INVALID_FRAMEID;
9545 frame = tls->frames [frame_idx];
9547 /* This is supported for frames without has_ctx etc. set */
9548 if (command == CMD_STACK_FRAME_GET_DOMAIN) {
9549 if (CHECK_PROTOCOL_VERSION (2, 38))
9550 buffer_add_domainid (buf, frame->domain);
9554 if (!frame->has_ctx)
9555 return ERR_ABSENT_INFORMATION;
9557 if (!ensure_jit (frame))
9558 return ERR_ABSENT_INFORMATION;
9562 sig = mono_method_signature (frame->actual_method);
9564 if (!(jit->has_var_info || frame->ji->is_interp) || !mono_get_seq_points (frame->domain, frame->actual_method))
9566 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
9568 return ERR_ABSENT_INFORMATION;
9571 case CMD_STACK_FRAME_GET_VALUES: {
9573 len = decode_int (p, &p, end);
9574 header = mono_method_get_header_checked (frame->actual_method, &error);
9575 mono_error_assert_ok (&error); /* FIXME report error */
9577 for (i = 0; i < len; ++i) {
9578 pos = decode_int (p, &p, end);
9583 DEBUG_PRINTF (4, "[dbg] send arg %d.\n", pos);
9585 if (frame->ji->is_interp) {
9588 addr = mono_interp_frame_get_arg (frame->interp_frame, pos);
9590 buffer_add_value_full (buf, sig->params [pos], addr, frame->domain, FALSE, NULL);
9592 g_assert (pos >= 0 && pos < jit->num_params);
9594 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
9597 MonoDebugLocalsInfo *locals;
9599 locals = mono_debug_lookup_locals (frame->method);
9601 g_assert (pos < locals->num_locals);
9602 pos = locals->locals [pos].index;
9603 mono_debug_free_locals (locals);
9606 DEBUG_PRINTF (4, "[dbg] send local %d.\n", pos);
9608 if (frame->ji->is_interp) {
9611 addr = mono_interp_frame_get_local (frame->interp_frame, pos);
9613 buffer_add_value_full (buf, header->locals [pos], addr, frame->domain, FALSE, NULL);
9615 g_assert (pos >= 0 && pos < jit->num_locals);
9617 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
9621 mono_metadata_free_mh (header);
9624 case CMD_STACK_FRAME_GET_THIS: {
9625 if (frame->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE)
9626 return ERR_ABSENT_INFORMATION;
9627 if (frame->api_method->klass->valuetype) {
9628 if (!sig->hasthis) {
9629 MonoObject *p = NULL;
9630 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
9632 if (frame->ji->is_interp) {
9635 addr = mono_interp_frame_get_this (frame->interp_frame);
9637 buffer_add_value_full (buf, &frame->actual_method->klass->this_arg, addr, frame->domain, FALSE, NULL);
9639 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9643 if (!sig->hasthis) {
9644 MonoObject *p = NULL;
9645 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
9647 if (frame->ji->is_interp) {
9650 addr = mono_interp_frame_get_this (frame->interp_frame);
9652 buffer_add_value_full (buf, &frame->api_method->klass->byval_arg, addr, frame->domain, FALSE, NULL);
9654 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9660 case CMD_STACK_FRAME_SET_VALUES: {
9664 MonoDebugVarInfo *var = NULL;
9665 gboolean is_arg = FALSE;
9667 len = decode_int (p, &p, end);
9668 header = mono_method_get_header_checked (frame->actual_method, &error);
9669 mono_error_assert_ok (&error); /* FIXME report error */
9671 for (i = 0; i < len; ++i) {
9672 pos = decode_int (p, &p, end);
9677 g_assert (pos >= 0 && pos < jit->num_params);
9679 t = sig->params [pos];
9680 var = &jit->params [pos];
9683 MonoDebugLocalsInfo *locals;
9685 locals = mono_debug_lookup_locals (frame->method);
9687 g_assert (pos < locals->num_locals);
9688 pos = locals->locals [pos].index;
9689 mono_debug_free_locals (locals);
9691 g_assert (pos >= 0 && pos < jit->num_locals);
9693 t = header->locals [pos];
9694 var = &jit->locals [pos];
9697 if (MONO_TYPE_IS_REFERENCE (t))
9698 val_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
9700 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9701 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9702 if (err != ERR_NONE)
9705 if (frame->ji->is_interp) {
9709 addr = mono_interp_frame_get_arg (frame->interp_frame, pos);
9711 addr = mono_interp_frame_get_local (frame->interp_frame, pos);
9712 set_interp_var (t, addr, val_buf);
9714 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9717 mono_metadata_free_mh (header);
9720 case CMD_STACK_FRAME_GET_DOMAIN: {
9721 if (CHECK_PROTOCOL_VERSION (2, 38))
9722 buffer_add_domainid (buf, frame->domain);
9725 case CMD_STACK_FRAME_SET_THIS: {
9728 MonoDebugVarInfo *var;
9730 t = &frame->actual_method->klass->byval_arg;
9731 /* Checked by the sender */
9732 g_assert (MONO_TYPE_ISSTRUCT (t));
9734 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9735 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9736 if (err != ERR_NONE)
9739 if (frame->ji->is_interp) {
9742 addr = mono_interp_frame_get_this (frame->interp_frame);
9743 set_interp_var (&frame->actual_method->klass->this_arg, addr, val_buf);
9745 var = jit->this_var;
9748 set_var (&frame->actual_method->klass->this_arg, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9753 return ERR_NOT_IMPLEMENTED;
9760 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9763 int objid, index, len, i, esize;
9767 objid = decode_objid (p, &p, end);
9768 err = get_object (objid, (MonoObject**)&arr);
9769 if (err != ERR_NONE)
9773 case CMD_ARRAY_REF_GET_LENGTH:
9774 buffer_add_int (buf, arr->obj.vtable->klass->rank);
9776 buffer_add_int (buf, arr->max_length);
9777 buffer_add_int (buf, 0);
9779 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
9780 buffer_add_int (buf, arr->bounds [i].length);
9781 buffer_add_int (buf, arr->bounds [i].lower_bound);
9785 case CMD_ARRAY_REF_GET_VALUES:
9786 index = decode_int (p, &p, end);
9787 len = decode_int (p, &p, end);
9789 g_assert (index >= 0 && len >= 0);
9790 // Reordered to avoid integer overflow
9791 g_assert (!(index > arr->max_length - len));
9793 esize = mono_array_element_size (arr->obj.vtable->klass);
9794 for (i = index; i < index + len; ++i) {
9795 elem = (gpointer*)((char*)arr->vector + (i * esize));
9796 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
9799 case CMD_ARRAY_REF_SET_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));
9811 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, (guint8 *)elem, p, &p, end);
9815 return ERR_NOT_IMPLEMENTED;
9822 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9828 int i, index, length;
9830 gboolean use_utf16 = FALSE;
9832 objid = decode_objid (p, &p, end);
9833 err = get_object (objid, (MonoObject**)&str);
9834 if (err != ERR_NONE)
9838 case CMD_STRING_REF_GET_VALUE:
9839 if (CHECK_PROTOCOL_VERSION (2, 41)) {
9840 for (i = 0; i < mono_string_length (str); ++i)
9841 if (mono_string_chars (str)[i] == 0)
9843 buffer_add_byte (buf, use_utf16 ? 1 : 0);
9846 buffer_add_int (buf, mono_string_length (str) * 2);
9847 buffer_add_data (buf, (guint8*)mono_string_chars (str), mono_string_length (str) * 2);
9850 s = mono_string_to_utf8_checked (str, &error);
9851 mono_error_assert_ok (&error);
9852 buffer_add_string (buf, s);
9856 case CMD_STRING_REF_GET_LENGTH:
9857 buffer_add_long (buf, mono_string_length (str));
9859 case CMD_STRING_REF_GET_CHARS:
9860 index = decode_long (p, &p, end);
9861 length = decode_long (p, &p, end);
9862 if (index > mono_string_length (str) - length)
9863 return ERR_INVALID_ARGUMENT;
9864 c = mono_string_chars (str) + index;
9865 for (i = 0; i < length; ++i)
9866 buffer_add_short (buf, c [i]);
9869 return ERR_NOT_IMPLEMENTED;
9876 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9887 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9888 objid = decode_objid (p, &p, end);
9889 err = get_object (objid, &obj);
9890 if (err != ERR_NONE)
9891 buffer_add_int (buf, 1);
9893 buffer_add_int (buf, 0);
9897 objid = decode_objid (p, &p, end);
9898 err = get_object (objid, &obj);
9899 if (err != ERR_NONE)
9902 MonoClass *obj_type;
9903 gboolean remote_obj = FALSE;
9905 obj_type = obj->vtable->klass;
9906 if (mono_class_is_transparent_proxy (obj_type)) {
9907 obj_type = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
9911 g_assert (obj_type);
9914 case CMD_OBJECT_REF_GET_TYPE:
9915 /* This handles transparent proxies too */
9916 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9918 case CMD_OBJECT_REF_GET_VALUES:
9919 len = decode_int (p, &p, end);
9921 for (i = 0; i < len; ++i) {
9922 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9923 if (err != ERR_NONE)
9926 /* Check that the field belongs to the object */
9928 for (k = obj_type; k; k = k->parent) {
9929 if (k == f->parent) {
9935 return ERR_INVALID_FIELDID;
9937 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9941 if (mono_class_field_is_special_static (f))
9942 return ERR_INVALID_FIELDID;
9944 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9945 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9946 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9947 mono_field_static_get_value_checked (vtable, f, val, &error);
9948 if (!is_ok (&error)) {
9949 mono_error_cleanup (&error); /* FIXME report the error */
9950 return ERR_INVALID_OBJECT;
9952 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9955 guint8 *field_value = NULL;
9958 #ifndef DISABLE_REMOTING
9959 void *field_storage = NULL;
9960 field_value = mono_load_remote_field_checked(obj, obj_type, f, &field_storage, &error);
9961 if (!is_ok (&error)) {
9962 mono_error_cleanup (&error); /* FIXME report the error */
9963 return ERR_INVALID_OBJECT;
9966 g_assert_not_reached ();
9969 field_value = (guint8*)obj + f->offset;
9971 buffer_add_value (buf, f->type, field_value, obj->vtable->domain);
9975 case CMD_OBJECT_REF_SET_VALUES:
9976 len = decode_int (p, &p, end);
9978 for (i = 0; i < len; ++i) {
9979 f = decode_fieldid (p, &p, end, NULL, &err);
9980 if (err != ERR_NONE)
9983 /* Check that the field belongs to the object */
9985 for (k = obj_type; k; k = k->parent) {
9986 if (k == f->parent) {
9992 return ERR_INVALID_FIELDID;
9994 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9998 if (mono_class_field_is_special_static (f))
9999 return ERR_INVALID_FIELDID;
10001 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
10002 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
10004 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
10005 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
10006 if (err != ERR_NONE) {
10010 mono_field_static_set_value (vtable, f, val);
10013 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
10014 if (err != ERR_NONE)
10019 case CMD_OBJECT_REF_GET_ADDRESS:
10020 buffer_add_long (buf, (gssize)obj);
10022 case CMD_OBJECT_REF_GET_DOMAIN:
10023 buffer_add_domainid (buf, obj->vtable->domain);
10025 case CMD_OBJECT_REF_GET_INFO:
10026 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
10027 buffer_add_domainid (buf, obj->vtable->domain);
10030 return ERR_NOT_IMPLEMENTED;
10037 command_set_to_string (CommandSet command_set)
10039 switch (command_set) {
10042 case CMD_SET_OBJECT_REF:
10043 return "OBJECT_REF";
10044 case CMD_SET_STRING_REF:
10045 return "STRING_REF";
10046 case CMD_SET_THREAD:
10048 case CMD_SET_ARRAY_REF:
10049 return "ARRAY_REF";
10050 case CMD_SET_EVENT_REQUEST:
10051 return "EVENT_REQUEST";
10052 case CMD_SET_STACK_FRAME:
10053 return "STACK_FRAME";
10054 case CMD_SET_APPDOMAIN:
10055 return "APPDOMAIN";
10056 case CMD_SET_ASSEMBLY:
10058 case CMD_SET_METHOD:
10062 case CMD_SET_MODULE:
10064 case CMD_SET_FIELD:
10066 case CMD_SET_EVENT:
10073 static const char* vm_cmds_str [] = {
10081 "SET_PROTOCOL_VERSION",
10084 "GET_TYPES_FOR_SOURCE_FILE",
10089 static const char* thread_cmds_str[] = {
10099 static const char* event_cmds_str[] = {
10102 "REQUEST_CLEAR_ALL_BREAKPOINTS"
10105 static const char* appdomain_cmds_str[] = {
10107 "GET_FRIENDLY_NAME",
10109 "GET_ENTRY_ASSEMBLY",
10112 "CREATE_BOXED_VALUE"
10115 static const char* assembly_cmds_str[] = {
10118 "GET_MANIFEST_MODULE",
10125 static const char* module_cmds_str[] = {
10129 static const char* field_cmds_str[] = {
10133 static const char* method_cmds_str[] = {
10135 "GET_DECLARING_TYPE",
10143 "MAKE_GENERIC_METHOD"
10146 static const char* type_cmds_str[] = {
10152 "GET_SOURCE_FILES",
10154 "IS_ASSIGNABLE_FROM",
10157 "GET_FIELD_CATTRS",
10158 "GET_PROPERTY_CATTRS",
10159 "GET_SOURCE_FILES_2",
10161 "GET_METHODS_BY_NAME_FLAGS",
10163 "GET_INTERFACE_MAP",
10167 static const char* stack_frame_cmds_str[] = {
10175 static const char* array_cmds_str[] = {
10181 static const char* string_cmds_str[] = {
10187 static const char* object_cmds_str[] = {
10198 cmd_to_string (CommandSet set, int command)
10205 cmds = vm_cmds_str;
10206 cmds_len = G_N_ELEMENTS (vm_cmds_str);
10208 case CMD_SET_OBJECT_REF:
10209 cmds = object_cmds_str;
10210 cmds_len = G_N_ELEMENTS (object_cmds_str);
10212 case CMD_SET_STRING_REF:
10213 cmds = string_cmds_str;
10214 cmds_len = G_N_ELEMENTS (string_cmds_str);
10216 case CMD_SET_THREAD:
10217 cmds = thread_cmds_str;
10218 cmds_len = G_N_ELEMENTS (thread_cmds_str);
10220 case CMD_SET_ARRAY_REF:
10221 cmds = array_cmds_str;
10222 cmds_len = G_N_ELEMENTS (array_cmds_str);
10224 case CMD_SET_EVENT_REQUEST:
10225 cmds = event_cmds_str;
10226 cmds_len = G_N_ELEMENTS (event_cmds_str);
10228 case CMD_SET_STACK_FRAME:
10229 cmds = stack_frame_cmds_str;
10230 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
10232 case CMD_SET_APPDOMAIN:
10233 cmds = appdomain_cmds_str;
10234 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
10236 case CMD_SET_ASSEMBLY:
10237 cmds = assembly_cmds_str;
10238 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
10240 case CMD_SET_METHOD:
10241 cmds = method_cmds_str;
10242 cmds_len = G_N_ELEMENTS (method_cmds_str);
10245 cmds = type_cmds_str;
10246 cmds_len = G_N_ELEMENTS (type_cmds_str);
10248 case CMD_SET_MODULE:
10249 cmds = module_cmds_str;
10250 cmds_len = G_N_ELEMENTS (module_cmds_str);
10252 case CMD_SET_FIELD:
10253 cmds = field_cmds_str;
10254 cmds_len = G_N_ELEMENTS (field_cmds_str);
10256 case CMD_SET_EVENT:
10257 cmds = event_cmds_str;
10258 cmds_len = G_N_ELEMENTS (event_cmds_str);
10263 if (command > 0 && command <= cmds_len)
10264 return cmds [command - 1];
10270 wait_for_attach (void)
10272 #ifndef DISABLE_SOCKET_TRANSPORT
10273 if (listen_fd == -1) {
10274 DEBUG_PRINTF (1, "[dbg] Invalid listening socket\n");
10278 /* Block and wait for client connection */
10279 conn_fd = socket_transport_accept (listen_fd);
10281 DEBUG_PRINTF (1, "Accepted connection on %d\n", conn_fd);
10282 if (conn_fd == -1) {
10283 DEBUG_PRINTF (1, "[dbg] Bad client connection\n");
10287 g_assert_not_reached ();
10291 disconnected = !transport_handshake ();
10292 if (disconnected) {
10293 DEBUG_PRINTF (1, "Transport handshake failed!\n");
10303 * This thread handles communication with the debugger client using a JDWP
10306 static gsize WINAPI
10307 debugger_thread (void *arg)
10310 int res, len, id, flags, command = 0;
10311 CommandSet command_set = (CommandSet)0;
10312 guint8 header [HEADER_LENGTH];
10313 guint8 *data, *p, *end;
10317 gboolean attach_failed = FALSE;
10319 DEBUG_PRINTF (1, "[dbg] Agent thread started, pid=%p\n", (gpointer) (gsize) mono_native_thread_id_get ());
10321 debugger_thread_id = mono_native_thread_id_get ();
10323 MonoInternalThread *internal = mono_thread_internal_current ();
10324 MonoString *str = mono_string_new_checked (mono_domain_get (), "Debugger agent", &error);
10325 mono_error_assert_ok (&error);
10326 mono_thread_set_name_internal (internal, str, TRUE, FALSE, &error);
10327 mono_error_assert_ok (&error);
10329 internal->state |= ThreadState_Background;
10330 internal->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
10332 if (agent_config.defer) {
10333 if (!wait_for_attach ()) {
10334 DEBUG_PRINTF (1, "[dbg] Can't attach, aborting debugger thread.\n");
10335 attach_failed = TRUE; // Don't abort process when we can't listen
10337 mono_set_is_debugger_attached (TRUE);
10338 /* Send start event to client */
10339 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
10342 mono_set_is_debugger_attached (TRUE);
10345 while (!attach_failed) {
10346 res = transport_recv (header, HEADER_LENGTH);
10348 /* This will break if the socket is closed during shutdown too */
10349 if (res != HEADER_LENGTH) {
10350 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH);
10355 end = header + HEADER_LENGTH;
10357 len = decode_int (p, &p, end);
10358 id = decode_int (p, &p, end);
10359 flags = decode_byte (p, &p, end);
10360 command_set = (CommandSet)decode_byte (p, &p, end);
10361 command = decode_byte (p, &p, end);
10363 g_assert (flags == 0);
10366 const char *cmd_str;
10367 char cmd_num [256];
10369 cmd_str = cmd_to_string (command_set, command);
10371 sprintf (cmd_num, "%d", command);
10375 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);
10378 data = (guint8 *)g_malloc (len - HEADER_LENGTH);
10379 if (len - HEADER_LENGTH > 0)
10381 res = transport_recv (data, len - HEADER_LENGTH);
10382 if (res != len - HEADER_LENGTH) {
10383 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH);
10389 end = data + (len - HEADER_LENGTH);
10391 buffer_init (&buf, 128);
10396 /* Process the request */
10397 switch (command_set) {
10399 err = vm_commands (command, id, p, end, &buf);
10400 if (err == ERR_NONE && command == CMD_VM_INVOKE_METHOD)
10401 /* Sent after the invoke is complete */
10404 case CMD_SET_EVENT_REQUEST:
10405 err = event_commands (command, p, end, &buf);
10407 case CMD_SET_APPDOMAIN:
10408 err = domain_commands (command, p, end, &buf);
10410 case CMD_SET_ASSEMBLY:
10411 err = assembly_commands (command, p, end, &buf);
10413 case CMD_SET_MODULE:
10414 err = module_commands (command, p, end, &buf);
10416 case CMD_SET_FIELD:
10417 err = field_commands (command, p, end, &buf);
10420 err = type_commands (command, p, end, &buf);
10422 case CMD_SET_METHOD:
10423 err = method_commands (command, p, end, &buf);
10425 case CMD_SET_THREAD:
10426 err = thread_commands (command, p, end, &buf);
10428 case CMD_SET_STACK_FRAME:
10429 err = frame_commands (command, p, end, &buf);
10431 case CMD_SET_ARRAY_REF:
10432 err = array_commands (command, p, end, &buf);
10434 case CMD_SET_STRING_REF:
10435 err = string_commands (command, p, end, &buf);
10437 case CMD_SET_OBJECT_REF:
10438 err = object_commands (command, p, end, &buf);
10441 err = ERR_NOT_IMPLEMENTED;
10444 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
10445 buffer_replies = TRUE;
10449 if (buffer_replies) {
10450 buffer_reply_packet (id, err, &buf);
10452 send_reply_packet (id, err, &buf);
10453 //DEBUG_PRINTF (1, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000);
10457 if (err == ERR_NONE && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
10458 send_buffered_reply_packets ();
10459 buffer_replies = FALSE;
10463 buffer_free (&buf);
10465 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
10469 mono_set_is_debugger_attached (FALSE);
10471 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
10472 debugger_thread_exited = TRUE;
10473 mono_coop_cond_signal (&debugger_thread_exited_cond);
10474 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
10476 DEBUG_PRINTF (1, "[dbg] Debugger thread exited.\n");
10478 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
10479 DEBUG_PRINTF (2, "[dbg] Detached - restarting clean debugger thread.\n");
10480 start_debugger_thread ();
10486 #else /* DISABLE_DEBUGGER_AGENT */
10489 mono_debugger_agent_parse_options (char *options)
10491 g_error ("This runtime is configured with the debugger agent disabled.");
10495 mono_debugger_agent_init (void)
10500 mono_debugger_agent_breakpoint_hit (void *sigctx)
10505 mono_debugger_agent_single_step_event (void *sigctx)
10510 mono_debugger_agent_free_domain_info (MonoDomain *domain)
10515 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
10516 MonoContext *catch_ctx)
10521 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
10526 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
10531 mono_debugger_agent_user_break (void)
10537 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
10542 mono_debugger_agent_debug_log_is_enabled (void)
10548 mono_debugger_agent_unhandled_exception (MonoException *exc)
10550 g_assert_not_reached ();
10554 debugger_agent_single_step_from_context (MonoContext *ctx)
10556 g_assert_not_reached ();
10560 debugger_agent_breakpoint_from_context (MonoContext *ctx)
10562 g_assert_not_reached ();