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);
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);
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_done (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo);
774 static void jit_failed (MonoProfiler *prof, MonoMethod *method);
776 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo);
778 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
780 static void start_single_stepping (void);
782 static void stop_single_stepping (void);
784 static void suspend_current (void);
786 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
788 static void clear_types_for_assembly (MonoAssembly *assembly);
790 static void clear_breakpoints_for_domain (MonoDomain *domain);
792 static void process_profiler_event (EventKind event, gpointer arg);
794 /* Submodule init/cleanup */
795 static void breakpoints_init (void);
796 static void breakpoints_cleanup (void);
798 static void objrefs_init (void);
799 static void objrefs_cleanup (void);
801 static void ids_init (void);
802 static void ids_cleanup (void);
804 static void suspend_init (void);
806 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch,
807 StackFrame **frames, int nframes);
808 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req);
809 static void ss_destroy (SingleStepReq *req);
811 static void start_debugger_thread (void);
812 static void stop_debugger_thread (void);
814 static void finish_agent_init (gboolean on_startup);
816 static void process_profiler_event (EventKind event, gpointer arg);
818 static void invalidate_frames (DebuggerTlsData *tls);
820 #ifndef DISABLE_SOCKET_TRANSPORT
822 register_socket_transport (void);
825 static inline gboolean
826 is_debugger_thread (void)
828 MonoInternalThread *internal;
830 internal = mono_thread_internal_current ();
834 return internal->debugger_thread;
838 parse_address (char *address, char **host, int *port)
840 char *pos = strchr (address, ':');
842 if (pos == NULL || pos == address)
845 size_t len = pos - address;
846 *host = (char *)g_malloc (len + 1);
847 memcpy (*host, address, len);
848 (*host) [len] = '\0';
850 *port = atoi (pos + 1);
858 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
859 fprintf (stderr, "Available options:\n");
860 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
861 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
862 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
863 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
864 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
865 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
866 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
867 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
868 fprintf (stderr, " setpgid=y/n\t\t\tWhether to call setpid(0, 0) after startup.\n");
869 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
873 parse_flag (const char *option, char *flag)
875 if (!strcmp (flag, "y"))
877 else if (!strcmp (flag, "n"))
880 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
887 mono_debugger_agent_parse_options (char *options)
894 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
895 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
899 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
901 options = g_strdup_printf ("%s,%s", options, extra);
905 agent_config.enabled = TRUE;
906 agent_config.suspend = TRUE;
907 agent_config.server = FALSE;
908 agent_config.defer = FALSE;
909 agent_config.address = NULL;
911 //agent_config.log_level = 10;
913 args = g_strsplit (options, ",", -1);
914 for (ptr = args; ptr && *ptr; ptr ++) {
917 if (strncmp (arg, "transport=", 10) == 0) {
918 agent_config.transport = g_strdup (arg + 10);
919 } else if (strncmp (arg, "address=", 8) == 0) {
920 agent_config.address = g_strdup (arg + 8);
921 } else if (strncmp (arg, "loglevel=", 9) == 0) {
922 agent_config.log_level = atoi (arg + 9);
923 } else if (strncmp (arg, "logfile=", 8) == 0) {
924 agent_config.log_file = g_strdup (arg + 8);
925 } else if (strncmp (arg, "suspend=", 8) == 0) {
926 agent_config.suspend = parse_flag ("suspend", arg + 8);
927 } else if (strncmp (arg, "server=", 7) == 0) {
928 agent_config.server = parse_flag ("server", arg + 7);
929 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
930 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
931 } else if (strncmp (arg, "onthrow=", 8) == 0) {
932 /* We support multiple onthrow= options */
933 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
934 } else if (strncmp (arg, "onthrow", 7) == 0) {
935 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
936 } else if (strncmp (arg, "help", 4) == 0) {
939 } else if (strncmp (arg, "timeout=", 8) == 0) {
940 agent_config.timeout = atoi (arg + 8);
941 } else if (strncmp (arg, "launch=", 7) == 0) {
942 agent_config.launch = g_strdup (arg + 7);
943 } else if (strncmp (arg, "embedding=", 10) == 0) {
944 agent_config.embedding = atoi (arg + 10) == 1;
945 } else if (strncmp (arg, "keepalive=", 10) == 0) {
946 agent_config.keepalive = atoi (arg + 10);
947 } else if (strncmp (arg, "setpgid=", 8) == 0) {
948 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
955 if (agent_config.server && !agent_config.suspend) {
956 /* Waiting for deferred attachment */
957 agent_config.defer = TRUE;
958 if (agent_config.address == NULL) {
959 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (mono_process_current_pid () % 1000));
963 //agent_config.log_level = 0;
965 if (agent_config.transport == NULL) {
966 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
970 if (agent_config.address == NULL && !agent_config.server) {
971 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
976 if (!strcmp (agent_config.transport, "dt_socket")) {
977 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
978 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
985 mono_debugger_agent_init (void)
987 mono_coop_mutex_init_recursive (&debug_mutex);
989 if (!agent_config.enabled)
994 /* Need to know whenever a thread has acquired the loader mutex */
995 mono_loader_lock_track_ownership (TRUE);
997 event_requests = g_ptr_array_new ();
999 mono_coop_mutex_init (&debugger_thread_exited_mutex);
1000 mono_coop_cond_init (&debugger_thread_exited_cond);
1002 MonoProfilerHandle prof = mono_profiler_install ((MonoProfiler*)&debugger_profiler);
1003 mono_profiler_set_runtime_shutdown_end_callback (prof, runtime_shutdown);
1004 mono_profiler_set_runtime_initialized_callback (prof, runtime_initialized);
1005 mono_profiler_set_domain_loaded_callback (prof, appdomain_load);
1006 mono_profiler_set_domain_unloading_callback (prof, appdomain_start_unload);
1007 mono_profiler_set_domain_unloaded_callback (prof, appdomain_unload);
1008 mono_profiler_set_thread_started_callback (prof, thread_startup);
1009 mono_profiler_set_thread_stopped_callback (prof, thread_end);
1010 mono_profiler_set_assembly_loaded_callback (prof, assembly_load);
1011 mono_profiler_set_assembly_unloading_callback (prof, assembly_unload);
1012 mono_profiler_set_jit_done_callback (prof, jit_done);
1013 mono_profiler_set_jit_failed_callback (prof, jit_failed);
1015 mono_native_tls_alloc (&debugger_tls_id, NULL);
1017 /* Needed by the hash_table_new_type () call below */
1018 mono_gc_base_init ();
1020 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");
1022 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread table");
1024 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");
1026 pending_assembly_loads = g_ptr_array_new ();
1027 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
1029 log_level = agent_config.log_level;
1031 embedding = agent_config.embedding;
1032 disconnected = TRUE;
1034 if (agent_config.log_file) {
1035 log_file = fopen (agent_config.log_file, "w+");
1037 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
1046 breakpoints_init ();
1049 mini_get_debug_options ()->gen_sdb_seq_points = TRUE;
1051 * This is needed because currently we don't handle liveness info.
1053 mini_get_debug_options ()->mdb_optimizations = TRUE;
1055 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
1056 /* This is needed because we can't set local variables in registers yet */
1057 mono_disable_optimizations (MONO_OPT_LINEARS);
1061 * The stack walk done from thread_interrupt () needs to be signal safe, but it
1062 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
1063 * safe (#3411). So load AOT info eagerly when the debugger is running as a
1066 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
1069 if (agent_config.setpgid)
1073 if (!agent_config.onuncaught && !agent_config.onthrow)
1074 finish_agent_init (TRUE);
1078 * finish_agent_init:
1080 * Finish the initialization of the agent. This involves connecting the transport
1081 * and starting the agent thread. This is either done at startup, or
1082 * in response to some event like an unhandled exception.
1085 finish_agent_init (gboolean on_startup)
1089 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
1092 if (agent_config.launch) {
1095 // FIXME: Generated address
1096 // FIXME: Races with transport_connect ()
1098 argv [0] = agent_config.launch;
1099 argv [1] = agent_config.transport;
1100 argv [2] = agent_config.address;
1103 res = g_spawn_async_with_pipes (NULL, argv, NULL, (GSpawnFlags)0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1105 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1110 transport_connect (agent_config.address);
1113 /* Do some which is usually done after sending the VMStart () event */
1114 vm_start_event_sent = TRUE;
1115 start_debugger_thread ();
1120 mono_debugger_agent_cleanup (void)
1125 stop_debugger_thread ();
1127 breakpoints_cleanup ();
1136 #ifndef DISABLE_SOCKET_TRANSPORT
1141 * recv() + handle incomplete reads and EINTR
1144 socket_transport_recv (void *buf, int len)
1150 static gint64 last_keepalive;
1157 res = recv (fd, (char *) buf + total, len - total, flags);
1160 if (agent_config.keepalive) {
1161 gboolean need_keepalive = FALSE;
1162 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1163 need_keepalive = TRUE;
1164 } else if (res == -1) {
1165 /* This could happen if recv () is interrupted repeatedly */
1166 msecs = mono_msec_ticks ();
1167 if (msecs - last_keepalive >= agent_config.keepalive) {
1168 need_keepalive = TRUE;
1169 last_keepalive = msecs;
1172 if (need_keepalive) {
1173 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1177 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1185 set_keepalive (void)
1190 if (!agent_config.keepalive || !conn_fd)
1193 tv.tv_sec = agent_config.keepalive / 1000;
1194 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1196 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1197 g_assert (result >= 0);
1201 socket_transport_accept (int socket_fd)
1204 conn_fd = accept (socket_fd, NULL, NULL);
1207 if (conn_fd == -1) {
1208 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1210 DEBUG_PRINTF (1, "Accepted connection from client, connection fd=%d.\n", conn_fd);
1217 socket_transport_send (void *data, int len)
1224 res = send (conn_fd, data, len, 0);
1225 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1236 * socket_transport_connect:
1238 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1241 socket_transport_connect (const char *address)
1243 MonoAddressInfo *result;
1244 MonoAddressEntry *rp;
1245 int sfd = -1, s, res;
1249 if (agent_config.address) {
1250 res = parse_address (agent_config.address, &host, &port);
1251 g_assert (res == 0);
1262 mono_network_init ();
1264 /* Obtain address(es) matching host/port */
1265 s = mono_get_address_info (host, port, MONO_HINT_UNSPECIFIED, &result);
1267 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, s); // FIXME add portable error conversion functions
1272 if (agent_config.server) {
1273 /* Wait for a connection */
1275 struct sockaddr_in addr;
1278 /* No address, generate one */
1279 sfd = socket (AF_INET, SOCK_STREAM, 0);
1282 /* This will bind the socket to a random port */
1283 res = listen (sfd, 16);
1285 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1290 addrlen = sizeof (addr);
1291 memset (&addr, 0, sizeof (addr));
1292 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1293 g_assert (res == 0);
1295 host = (char*)"127.0.0.1";
1296 port = ntohs (addr.sin_port);
1298 /* Emit the address to stdout */
1299 /* FIXME: Should print another interface, not localhost */
1300 printf ("%s:%d\n", host, port);
1302 /* Listen on the provided address */
1303 for (rp = result->entries; rp != NULL; rp = rp->next) {
1304 MonoSocketAddress sockaddr;
1308 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1310 sfd = socket (rp->family, rp->socktype,
1315 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1318 res = bind (sfd, &sockaddr.addr, sock_len);
1322 res = listen (sfd, 16);
1329 mono_free_address_info (result);
1332 if (agent_config.defer)
1335 DEBUG_PRINTF (1, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout);
1337 if (agent_config.timeout) {
1342 tv.tv_usec = agent_config.timeout * 1000;
1344 FD_SET (sfd, &readfds);
1347 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1351 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1356 conn_fd = socket_transport_accept (sfd);
1360 DEBUG_PRINTF (1, "Accepted connection from client, socket fd=%d.\n", conn_fd);
1362 /* Connect to the specified address */
1363 /* FIXME: Respect the timeout */
1364 for (rp = result->entries; rp != NULL; rp = rp->next) {
1365 MonoSocketAddress sockaddr;
1368 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1370 sfd = socket (rp->family, rp->socktype,
1376 res = connect (sfd, &sockaddr.addr, sock_len);
1380 break; /* Success */
1388 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1394 mono_free_address_info (result);
1397 if (!transport_handshake ())
1402 socket_transport_close1 (void)
1404 /* This will interrupt the agent thread */
1405 /* Close the read part only so it can still send back replies */
1406 /* Also shut down the connection listener so that we can exit normally */
1408 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1409 shutdown (conn_fd, SD_BOTH);
1410 shutdown (listen_fd, SD_BOTH);
1411 closesocket (listen_fd);
1413 shutdown (conn_fd, SHUT_RD);
1414 shutdown (listen_fd, SHUT_RDWR);
1422 socket_transport_close2 (void)
1425 shutdown (conn_fd, SD_BOTH);
1427 shutdown (conn_fd, SHUT_RDWR);
1432 register_socket_transport (void)
1434 DebuggerTransport trans;
1436 trans.name = "dt_socket";
1437 trans.connect = socket_transport_connect;
1438 trans.close1 = socket_transport_close1;
1439 trans.close2 = socket_transport_close2;
1440 trans.send = socket_transport_send;
1441 trans.recv = socket_transport_recv;
1443 register_transport (&trans);
1447 * socket_fd_transport_connect:
1451 socket_fd_transport_connect (const char *address)
1455 res = sscanf (address, "%d", &conn_fd);
1457 fprintf (stderr, "debugger-agent: socket-fd transport address is invalid: '%s'\n", address);
1461 if (!transport_handshake ())
1466 register_socket_fd_transport (void)
1468 DebuggerTransport trans;
1470 /* This is the same as the 'dt_socket' transport, but receives an already connected socket fd */
1471 trans.name = "socket-fd";
1472 trans.connect = socket_fd_transport_connect;
1473 trans.close1 = socket_transport_close1;
1474 trans.close2 = socket_transport_close2;
1475 trans.send = socket_transport_send;
1476 trans.recv = socket_transport_recv;
1478 register_transport (&trans);
1481 #endif /* DISABLE_SOCKET_TRANSPORT */
1487 #define MAX_TRANSPORTS 16
1489 static DebuggerTransport *transport;
1491 static DebuggerTransport transports [MAX_TRANSPORTS];
1492 static int ntransports;
1495 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1498 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1500 register_transport (trans);
1504 register_transport (DebuggerTransport *trans)
1506 g_assert (ntransports < MAX_TRANSPORTS);
1508 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1513 transport_init (void)
1517 #ifndef DISABLE_SOCKET_TRANSPORT
1518 register_socket_transport ();
1519 register_socket_fd_transport ();
1522 for (i = 0; i < ntransports; ++i) {
1523 if (!strcmp (agent_config.transport, transports [i].name))
1526 if (i == ntransports) {
1527 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1528 for (i = 0; i < ntransports; ++i)
1529 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1530 fprintf (stderr, "\n");
1533 transport = &transports [i];
1537 transport_connect (const char *address)
1539 transport->connect (address);
1543 transport_close1 (void)
1545 transport->close1 ();
1549 transport_close2 (void)
1551 transport->close2 ();
1555 transport_send (void *buf, int len)
1557 return transport->send (buf, len);
1561 transport_recv (void *buf, int len)
1563 return transport->recv (buf, len);
1567 mono_debugger_agent_transport_handshake (void)
1569 return transport_handshake ();
1573 transport_handshake (void)
1575 char handshake_msg [128];
1579 disconnected = TRUE;
1581 /* Write handshake message */
1582 sprintf (handshake_msg, "DWP-Handshake");
1585 res = transport_send (handshake_msg, strlen (handshake_msg));
1586 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1588 g_assert (res != -1);
1591 res = transport_recv (buf, strlen (handshake_msg));
1592 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg)) != 0)) {
1593 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1598 * To support older clients, the client sends its protocol version after connecting
1599 * using a command. Until that is received, default to our protocol version.
1601 major_version = MAJOR_VERSION;
1602 minor_version = MINOR_VERSION;
1603 protocol_version_set = FALSE;
1605 #ifndef DISABLE_SOCKET_TRANSPORT
1606 // FIXME: Move this somewhere else
1608 * Set TCP_NODELAY on the socket so the client receives events/command
1609 * results immediately.
1613 int result = setsockopt (conn_fd,
1618 g_assert (result >= 0);
1624 disconnected = FALSE;
1629 stop_debugger_thread (void)
1634 transport_close1 ();
1637 * Wait for the thread to exit.
1639 * If we continue with the shutdown without waiting for it, then the client might
1640 * not receive an answer to its last command like a resume.
1642 if (!is_debugger_thread ()) {
1644 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
1645 if (!debugger_thread_exited)
1646 mono_coop_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1647 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
1648 } while (!debugger_thread_exited);
1651 transport_close2 ();
1655 start_debugger_thread (void)
1658 MonoInternalThread *thread;
1660 thread = mono_thread_create_internal (mono_get_root_domain (), debugger_thread, NULL, MONO_THREAD_CREATE_FLAGS_DEBUGGER, &error);
1661 mono_error_assert_ok (&error);
1663 debugger_thread_handle = mono_threads_open_thread_handle (thread->handle);
1664 g_assert (debugger_thread_handle);
1668 * Functions to decode protocol data
1672 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1675 g_assert (*endbuf <= limit);
1680 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1683 g_assert (*endbuf <= limit);
1685 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1688 static inline gint64
1689 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1691 guint32 high = decode_int (buf, &buf, limit);
1692 guint32 low = decode_int (buf, &buf, limit);
1696 return ((((guint64)high) << 32) | ((guint64)low));
1700 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1702 return decode_int (buf, endbuf, limit);
1706 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1708 int len = decode_int (buf, &buf, limit);
1716 s = (char *)g_malloc (len + 1);
1719 memcpy (s, buf, len);
1728 * Functions to encode protocol data
1732 buffer_init (Buffer *buf, int size)
1734 buf->buf = (guint8 *)g_malloc (size);
1736 buf->end = buf->buf + size;
1740 buffer_len (Buffer *buf)
1742 return buf->p - buf->buf;
1746 buffer_make_room (Buffer *buf, int size)
1748 if (buf->end - buf->p < size) {
1749 int new_size = buf->end - buf->buf + size + 32;
1750 guint8 *p = (guint8 *)g_realloc (buf->buf, new_size);
1751 size = buf->p - buf->buf;
1754 buf->end = buf->buf + new_size;
1759 buffer_add_byte (Buffer *buf, guint8 val)
1761 buffer_make_room (buf, 1);
1767 buffer_add_short (Buffer *buf, guint32 val)
1769 buffer_make_room (buf, 2);
1770 buf->p [0] = (val >> 8) & 0xff;
1771 buf->p [1] = (val >> 0) & 0xff;
1776 buffer_add_int (Buffer *buf, guint32 val)
1778 buffer_make_room (buf, 4);
1779 buf->p [0] = (val >> 24) & 0xff;
1780 buf->p [1] = (val >> 16) & 0xff;
1781 buf->p [2] = (val >> 8) & 0xff;
1782 buf->p [3] = (val >> 0) & 0xff;
1787 buffer_add_long (Buffer *buf, guint64 l)
1789 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1790 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1794 buffer_add_id (Buffer *buf, int id)
1796 buffer_add_int (buf, (guint64)id);
1800 buffer_add_data (Buffer *buf, guint8 *data, int len)
1802 buffer_make_room (buf, len);
1803 memcpy (buf->p, data, len);
1808 buffer_add_string (Buffer *buf, const char *str)
1813 buffer_add_int (buf, 0);
1816 buffer_add_int (buf, len);
1817 buffer_add_data (buf, (guint8*)str, len);
1822 buffer_add_buffer (Buffer *buf, Buffer *data)
1824 buffer_add_data (buf, data->buf, buffer_len (data));
1828 buffer_free (Buffer *buf)
1834 send_packet (int command_set, int command, Buffer *data)
1840 id = InterlockedIncrement (&packet_id);
1842 len = data->p - data->buf + 11;
1843 buffer_init (&buf, len);
1844 buffer_add_int (&buf, len);
1845 buffer_add_int (&buf, id);
1846 buffer_add_byte (&buf, 0); /* flags */
1847 buffer_add_byte (&buf, command_set);
1848 buffer_add_byte (&buf, command);
1849 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1851 res = transport_send (buf.buf, len);
1859 send_reply_packets (int npackets, ReplyPacket *packets)
1866 for (i = 0; i < npackets; ++i)
1867 len += buffer_len (packets [i].data) + 11;
1868 buffer_init (&buf, len);
1869 for (i = 0; i < npackets; ++i) {
1870 buffer_add_int (&buf, buffer_len (packets [i].data) + 11);
1871 buffer_add_int (&buf, packets [i].id);
1872 buffer_add_byte (&buf, 0x80); /* flags */
1873 buffer_add_byte (&buf, (packets [i].error >> 8) & 0xff);
1874 buffer_add_byte (&buf, packets [i].error);
1875 buffer_add_buffer (&buf, packets [i].data);
1878 res = transport_send (buf.buf, len);
1886 send_reply_packet (int id, int error, Buffer *data)
1890 memset (&packet, 0, sizeof (ReplyPacket));
1892 packet.error = error;
1895 return send_reply_packets (1, &packet);
1899 send_buffered_reply_packets (void)
1903 send_reply_packets (nreply_packets, reply_packets);
1904 for (i = 0; i < nreply_packets; ++i)
1905 buffer_free (reply_packets [i].data);
1906 DEBUG_PRINTF (1, "[dbg] Sent %d buffered reply packets [at=%lx].\n", nreply_packets, (long)mono_100ns_ticks () / 10000);
1911 buffer_reply_packet (int id, int error, Buffer *data)
1915 if (nreply_packets == 128)
1916 send_buffered_reply_packets ();
1918 p = &reply_packets [nreply_packets];
1921 p->data = g_new0 (Buffer, 1);
1922 buffer_init (p->data, buffer_len (data));
1923 buffer_add_buffer (p->data, data);
1932 * Represents an object accessible by the debugger client.
1935 /* Unique id used in the wire protocol to refer to objects */
1938 * A weakref gc handle pointing to the object. The gc handle is used to
1939 * detect if the object was garbage collected.
1944 /* Maps objid -> ObjRef */
1945 /* Protected by the loader lock */
1946 static GHashTable *objrefs;
1947 /* Protected by the loader lock */
1948 static GHashTable *obj_to_objref;
1949 /* Protected by the dbg lock */
1950 static MonoGHashTable *suspended_objs;
1953 free_objref (gpointer value)
1955 ObjRef *o = (ObjRef *)value;
1957 mono_gchandle_free (o->handle);
1965 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1966 obj_to_objref = g_hash_table_new (NULL, NULL);
1967 suspended_objs = mono_g_hash_table_new_type ((GHashFunc)mono_object_hash, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_DEBUGGER, "suspended objects table");
1971 objrefs_cleanup (void)
1973 g_hash_table_destroy (objrefs);
1978 * Return an ObjRef for OBJ.
1981 get_objref (MonoObject *obj)
1984 GSList *reflist = NULL, *l;
1990 if (suspend_count) {
1992 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1995 mono_g_hash_table_insert (suspended_objs, obj, NULL);
1999 mono_loader_lock ();
2001 /* FIXME: The tables can grow indefinitely */
2003 if (mono_gc_is_moving ()) {
2005 * Objects can move, so use a hash table mapping hash codes to lists of
2006 * ObjRef structures.
2008 hash = mono_object_hash (obj);
2010 reflist = (GSList *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
2011 for (l = reflist; l; l = l->next) {
2012 ref = (ObjRef *)l->data;
2013 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
2014 mono_loader_unlock ();
2019 /* Use a hash table with masked pointers to internalize object references */
2020 ref = (ObjRef *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
2021 /* ref might refer to a different object with the same addr which was GCd */
2022 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
2023 mono_loader_unlock ();
2028 ref = g_new0 (ObjRef, 1);
2029 ref->id = InterlockedIncrement (&objref_id);
2030 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
2032 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
2034 if (mono_gc_is_moving ()) {
2035 reflist = g_slist_append (reflist, ref);
2036 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
2038 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
2041 mono_loader_unlock ();
2047 true_pred (gpointer key, gpointer value, gpointer user_data)
2053 clear_suspended_objs (void)
2056 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
2061 get_objid (MonoObject *obj)
2066 return get_objref (obj)->id;
2070 * Set OBJ to the object identified by OBJID.
2071 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
2075 get_object_allow_null (int objid, MonoObject **obj)
2085 return ERR_INVALID_OBJECT;
2087 mono_loader_lock ();
2089 ref = (ObjRef *)g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
2092 *obj = mono_gchandle_get_target (ref->handle);
2093 mono_loader_unlock ();
2095 return ERR_INVALID_OBJECT;
2098 mono_loader_unlock ();
2099 return ERR_INVALID_OBJECT;
2104 get_object (int objid, MonoObject **obj)
2106 ErrorCode err = get_object_allow_null (objid, obj);
2108 if (err != ERR_NONE)
2111 return ERR_INVALID_OBJECT;
2116 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
2118 return decode_id (buf, endbuf, limit);
2122 buffer_add_objid (Buffer *buf, MonoObject *o)
2124 buffer_add_id (buf, get_objid (o));
2143 * Represents a runtime structure accessible to the debugger client
2146 /* Unique id used in the wire protocol */
2148 /* Domain of the runtime structure, NULL if the domain was unloaded */
2155 MonoAssembly *assembly;
2156 MonoClassField *field;
2158 MonoProperty *property;
2163 /* Maps runtime structure -> Id */
2164 /* Protected by the dbg lock */
2165 GHashTable *val_to_id [ID_NUM];
2166 /* Classes whose class load event has been sent */
2167 /* Protected by the loader lock */
2168 GHashTable *loaded_classes;
2169 /* Maps MonoClass->GPtrArray of file names */
2170 GHashTable *source_files;
2171 /* Maps source file basename -> GSList of classes */
2172 GHashTable *source_file_to_class;
2173 /* Same with ignore-case */
2174 GHashTable *source_file_to_class_ignorecase;
2178 /* Protected by the dbg lock */
2179 static GPtrArray *ids [ID_NUM];
2186 for (i = 0; i < ID_NUM; ++i)
2187 ids [i] = g_ptr_array_new ();
2195 for (i = 0; i < ID_NUM; ++i) {
2197 for (j = 0; j < ids [i]->len; ++j)
2198 g_free (g_ptr_array_index (ids [i], j));
2199 g_ptr_array_free (ids [i], TRUE);
2206 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2208 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2210 GHashTableIter iter;
2211 GPtrArray *file_names;
2216 for (i = 0; i < ID_NUM; ++i)
2217 if (info->val_to_id [i])
2218 g_hash_table_destroy (info->val_to_id [i]);
2219 g_hash_table_destroy (info->loaded_classes);
2221 g_hash_table_iter_init (&iter, info->source_files);
2222 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2223 for (i = 0; i < file_names->len; ++i)
2224 g_free (g_ptr_array_index (file_names, i));
2225 g_ptr_array_free (file_names, TRUE);
2228 g_hash_table_iter_init (&iter, info->source_file_to_class);
2229 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2234 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2235 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2243 domain_jit_info (domain)->agent_info = NULL;
2245 /* Clear ids referencing structures in the domain */
2247 for (i = 0; i < ID_NUM; ++i) {
2249 for (j = 0; j < ids [i]->len; ++j) {
2250 Id *id = (Id *)g_ptr_array_index (ids [i], j);
2251 if (id->domain == domain)
2258 mono_loader_lock ();
2259 g_hash_table_remove (domains, domain);
2260 mono_loader_unlock ();
2263 static AgentDomainInfo*
2264 get_agent_domain_info (MonoDomain *domain)
2266 AgentDomainInfo *info = NULL;
2268 mono_domain_lock (domain);
2270 info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2272 info = g_new0 (AgentDomainInfo, 1);
2273 domain_jit_info (domain)->agent_info = info;
2274 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2275 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2276 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2277 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2280 mono_domain_unlock (domain);
2286 get_id (MonoDomain *domain, IdType type, gpointer val)
2289 AgentDomainInfo *info;
2294 info = get_agent_domain_info (domain);
2298 if (info->val_to_id [type] == NULL)
2299 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2301 id = (Id *)g_hash_table_lookup (info->val_to_id [type], val);
2307 id = g_new0 (Id, 1);
2309 id->id = ids [type]->len + 1;
2310 id->domain = domain;
2313 g_hash_table_insert (info->val_to_id [type], val, id);
2314 g_ptr_array_add (ids [type], id);
2321 static inline gpointer
2322 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, ErrorCode *err)
2326 int id = decode_id (buf, endbuf, limit);
2335 // FIXME: error handling
2337 g_assert (id > 0 && id <= ids [type]->len);
2339 res = (Id *)g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2342 if (res->domain == NULL || res->domain->state == MONO_APPDOMAIN_UNLOADED) {
2343 DEBUG_PRINTF (1, "ERR_UNLOADED, id=%d, type=%d.\n", id, type);
2344 *err = ERR_UNLOADED;
2349 *domain = res->domain;
2351 return res->data.val;
2355 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2357 int id = get_id (domain, type, val);
2359 buffer_add_id (buf, id);
2363 static inline MonoClass*
2364 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2368 klass = (MonoClass *)decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2369 if (G_UNLIKELY (log_level >= 2) && klass) {
2372 s = mono_type_full_name (&klass->byval_arg);
2373 DEBUG_PRINTF (2, "[dbg] recv class [%s]\n", s);
2379 static inline MonoAssembly*
2380 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2382 return (MonoAssembly *)decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2385 static inline MonoImage*
2386 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2388 return (MonoImage *)decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2391 static inline MonoMethod*
2392 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2396 m = (MonoMethod *)decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2397 if (G_UNLIKELY (log_level >= 2) && m) {
2400 s = mono_method_full_name (m, TRUE);
2401 DEBUG_PRINTF (2, "[dbg] recv method [%s]\n", s);
2407 static inline MonoClassField*
2408 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2410 return (MonoClassField *)decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2413 static inline MonoDomain*
2414 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2416 return (MonoDomain *)decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2419 static inline MonoProperty*
2420 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2422 return (MonoProperty *)decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2426 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2428 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2429 if (G_UNLIKELY (log_level >= 2) && klass) {
2432 s = mono_type_full_name (&klass->byval_arg);
2433 if (is_debugger_thread ())
2434 DEBUG_PRINTF (2, "[dbg] send class [%s]\n", s);
2436 DEBUG_PRINTF (2, "[%p] send class [%s]\n", (gpointer) (gsize) mono_native_thread_id_get (), s);
2442 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2444 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2445 if (G_UNLIKELY (log_level >= 2) && method) {
2448 s = mono_method_full_name (method, 1);
2449 DEBUG_PRINTF (2, "[dbg] send method [%s]\n", s);
2455 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2459 id = buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2460 if (G_UNLIKELY (log_level >= 2) && assembly)
2461 DEBUG_PRINTF (2, "[dbg] send assembly [%s][%s][%d]\n", assembly->aname.name, domain->friendly_name, id);
2465 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2467 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2471 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2473 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2477 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2479 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2483 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2485 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2488 static void invoke_method (void);
2495 get_top_method_ji (gpointer ip, MonoDomain **domain, gpointer *out_ip)
2502 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, domain);
2504 /* Could be an interpreter method */
2506 MonoLMF *lmf = mono_get_lmf ();
2507 MonoInterpFrameHandle *frame;
2509 g_assert (((guint64)lmf->previous_lmf) & 2);
2510 MonoLMFExt *ext = (MonoLMFExt*)lmf;
2512 g_assert (ext->interp_exit);
2513 frame = ext->interp_exit_data;
2514 ji = mono_interp_frame_get_jit_info (frame);
2516 *domain = mono_domain_get ();
2518 *out_ip = mono_interp_frame_get_ip (frame);
2524 * save_thread_context:
2526 * Set CTX as the current threads context which is used for computing stack traces.
2527 * This function is signal-safe.
2530 save_thread_context (MonoContext *ctx)
2532 DebuggerTlsData *tls;
2534 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2538 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2540 mono_thread_state_init_from_current (&tls->context);
2543 /* Number of threads suspended */
2545 * If this is equal to the size of thread_to_tls, the runtime is considered
2548 static gint32 threads_suspend_count;
2550 static MonoCoopMutex suspend_mutex;
2552 /* Cond variable used to wait for suspend_count becoming 0 */
2553 static MonoCoopCond suspend_cond;
2555 /* Semaphore used to wait for a thread becoming suspended */
2556 static MonoCoopSem suspend_sem;
2561 mono_coop_mutex_init (&suspend_mutex);
2562 mono_coop_cond_init (&suspend_cond);
2563 mono_coop_sem_init (&suspend_sem, 0);
2568 StackFrameInfo last_frame;
2569 gboolean last_frame_set;
2573 } GetLastFrameUserData;
2576 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2578 GetLastFrameUserData *data = (GetLastFrameUserData *)user_data;
2580 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE || info->type == FRAME_TYPE_TRAMPOLINE)
2583 if (!data->last_frame_set) {
2584 /* Store the last frame */
2585 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2586 data->last_frame_set = TRUE;
2589 /* Store the context/lmf for the frame above the last frame */
2590 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2591 data->lmf = info->lmf;
2592 data->domain = info->domain;
2598 copy_unwind_state_from_frame_data (MonoThreadUnwindState *to, GetLastFrameUserData *data, gpointer jit_tls)
2600 memcpy (&to->ctx, &data->ctx, sizeof (MonoContext));
2602 to->unwind_data [MONO_UNWIND_DATA_DOMAIN] = data->domain;
2603 to->unwind_data [MONO_UNWIND_DATA_LMF] = data->lmf;
2604 to->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = jit_tls;
2611 * Process interruption of a thread. This should be signal safe.
2613 * This always runs in the debugger thread.
2616 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, MonoJitInfo *ji)
2619 MonoNativeThreadId tid;
2623 ip = MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx);
2624 tid = mono_thread_info_get_tid (info);
2626 // FIXME: Races when the thread leaves managed code before hitting a single step
2629 if (ji && !ji->is_trampoline) {
2630 /* Running managed code, will be suspended by the single step code */
2631 DEBUG_PRINTF (1, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip);
2634 * Running native code, will be suspended when it returns to/enters
2635 * managed code. Treat it as already suspended.
2636 * This might interrupt the code in process_single_step_inner (), we use the
2637 * tls->suspending flag to avoid races when that happens.
2639 if (!tls->suspended && !tls->suspending) {
2640 GetLastFrameUserData data;
2642 // FIXME: printf is not signal safe, but this is only used during
2643 // debugger debugging
2645 DEBUG_PRINTF (1, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip);
2646 //save_thread_context (&ctx);
2649 /* Already terminated */
2653 * We are in a difficult position: we want to be able to provide stack
2654 * traces for this thread, but we can't use the current ctx+lmf, since
2655 * the thread is still running, so it might return to managed code,
2656 * making these invalid.
2657 * So we start a stack walk and save the first frame, along with the
2658 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2659 * suspended when it returns to managed code, so the parent's ctx should
2662 MonoThreadUnwindState *state = mono_thread_info_get_suspend_state (info);
2664 data.last_frame_set = FALSE;
2665 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, state, MONO_UNWIND_SIGNAL_SAFE, &data);
2666 if (data.last_frame_set) {
2667 gpointer jit_tls = ((MonoThreadInfo*)tls->thread->thread_info)->jit_data;
2669 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2671 if (data.last_frame.type == FRAME_TYPE_INTERP_TO_MANAGED) {
2673 * Store the current lmf instead of the parent one, since that
2674 * contains the interp exit data.
2676 data.lmf = state->unwind_data [MONO_UNWIND_DATA_LMF];
2679 copy_unwind_state_from_frame_data (&tls->async_state, &data, jit_tls);
2680 copy_unwind_state_from_frame_data (&tls->context, &data, jit_tls);
2682 tls->async_state.valid = FALSE;
2685 mono_memory_barrier ();
2687 tls->suspended = TRUE;
2688 mono_coop_sem_post (&suspend_sem);
2694 * reset_native_thread_suspend_state:
2696 * Reset the suspended flag and state on native threads
2699 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2701 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2703 if (!tls->really_suspended && tls->suspended) {
2704 tls->suspended = FALSE;
2706 * The thread might still be running if it was executing native code, so the state won't be invalided by
2707 * suspend_current ().
2709 tls->context.valid = FALSE;
2710 tls->async_state.valid = FALSE;
2711 invalidate_frames (tls);
2716 DebuggerTlsData *tls;
2717 gboolean valid_info;
2720 static SuspendThreadResult
2721 debugger_interrupt_critical (MonoThreadInfo *info, gpointer user_data)
2723 InterruptData *data = (InterruptData *)user_data;
2726 data->valid_info = TRUE;
2727 ji = mono_jit_info_table_find_internal (
2728 (MonoDomain *)mono_thread_info_get_suspend_state (info)->unwind_data [MONO_UNWIND_DATA_DOMAIN],
2729 (char *)MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx),
2733 /* This is signal safe */
2734 thread_interrupt (data->tls, info, ji);
2735 return MonoResumeThread;
2741 * Notify a thread that it needs to suspend.
2744 notify_thread (gpointer key, gpointer value, gpointer user_data)
2746 MonoInternalThread *thread = (MonoInternalThread *)key;
2747 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2748 MonoNativeThreadId tid = MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid);
2750 if (mono_thread_internal_is_current (thread) || tls->terminated)
2753 DEBUG_PRINTF (1, "[%p] Interrupting %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2755 /* This is _not_ equivalent to mono_thread_internal_abort () */
2756 InterruptData interrupt_data = { 0 };
2757 interrupt_data.tls = tls;
2759 mono_thread_info_safe_suspend_and_run ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE, debugger_interrupt_critical, &interrupt_data);
2760 if (!interrupt_data.valid_info) {
2761 DEBUG_PRINTF (1, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2763 * Attached thread which died without detaching.
2765 tls->terminated = TRUE;
2770 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2772 guint8 *ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
2776 if (mono_loader_lock_is_owned_by_self ()) {
2778 * Shortcut for the check in suspend_current (). This speeds up processing
2779 * when executing long running code inside the loader lock, i.e. assembly load
2785 if (is_debugger_thread ())
2788 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2789 if (suspend_count - tls->resume_count > 0)
2790 tls->suspending = TRUE;
2792 DEBUG_PRINTF (1, "[%p] Received single step event for suspending.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2794 if (suspend_count - tls->resume_count == 0) {
2796 * We are executing a single threaded invoke but the single step for
2797 * suspending is still active.
2798 * FIXME: This slows down single threaded invokes.
2800 DEBUG_PRINTF (1, "[%p] Ignored during single threaded invoke.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2804 ji = get_top_method_ji (ip, NULL, NULL);
2806 /* Can't suspend in these methods */
2807 method = jinfo_get_method (ji);
2808 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2811 save_thread_context (ctx);
2819 * Increase the suspend count of the VM. While the suspend count is greater
2820 * than 0, runtime threads are suspended at certain points during execution.
2825 mono_loader_lock ();
2827 mono_coop_mutex_lock (&suspend_mutex);
2831 DEBUG_PRINTF (1, "[%p] Suspending vm...\n", (gpointer) (gsize) mono_native_thread_id_get ());
2833 if (suspend_count == 1) {
2834 // FIXME: Is it safe to call this inside the lock ?
2835 start_single_stepping ();
2836 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2839 mono_coop_mutex_unlock (&suspend_mutex);
2841 if (suspend_count == 1)
2843 * Suspend creation of new threadpool threads, since they cannot run
2845 mono_threadpool_suspend ();
2847 mono_loader_unlock ();
2853 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2859 g_assert (is_debugger_thread ());
2861 mono_loader_lock ();
2863 mono_coop_mutex_lock (&suspend_mutex);
2865 g_assert (suspend_count > 0);
2868 DEBUG_PRINTF (1, "[%p] Resuming vm, suspend count=%d...\n", (gpointer) (gsize) mono_native_thread_id_get (), suspend_count);
2870 if (suspend_count == 0) {
2871 // FIXME: Is it safe to call this inside the lock ?
2872 stop_single_stepping ();
2873 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2876 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2877 mono_coop_cond_broadcast (&suspend_cond);
2879 mono_coop_mutex_unlock (&suspend_mutex);
2880 //g_assert (err == 0);
2882 if (suspend_count == 0)
2883 mono_threadpool_resume ();
2885 mono_loader_unlock ();
2891 * Resume just one thread.
2894 resume_thread (MonoInternalThread *thread)
2896 DebuggerTlsData *tls;
2898 g_assert (is_debugger_thread ());
2900 mono_loader_lock ();
2902 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
2905 mono_coop_mutex_lock (&suspend_mutex);
2907 g_assert (suspend_count > 0);
2909 DEBUG_PRINTF (1, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid);
2911 tls->resume_count += suspend_count;
2914 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2915 * but only the one whose resume_count field is > 0 will be resumed.
2917 mono_coop_cond_broadcast (&suspend_cond);
2919 mono_coop_mutex_unlock (&suspend_mutex);
2920 //g_assert (err == 0);
2922 mono_loader_unlock ();
2926 free_frames (StackFrame **frames, int nframes)
2930 for (i = 0; i < nframes; ++i) {
2931 if (frames [i]->jit)
2932 mono_debug_free_method_jit_info (frames [i]->jit);
2933 g_free (frames [i]);
2939 invalidate_frames (DebuggerTlsData *tls)
2942 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2945 free_frames (tls->frames, tls->frame_count);
2946 tls->frame_count = 0;
2949 free_frames (tls->restore_frames, tls->restore_frame_count);
2950 tls->restore_frame_count = 0;
2951 tls->restore_frames = NULL;
2957 * Suspend the current thread until the runtime is resumed. If the thread has a
2958 * pending invoke, then the invoke is executed before this function returns.
2961 suspend_current (void)
2963 DebuggerTlsData *tls;
2965 g_assert (!is_debugger_thread ());
2967 if (mono_loader_lock_is_owned_by_self ()) {
2969 * If we own the loader mutex, can't suspend until we release it, since the
2970 * whole runtime can deadlock otherwise.
2975 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2978 mono_coop_mutex_lock (&suspend_mutex);
2980 tls->suspending = FALSE;
2981 tls->really_suspended = TRUE;
2983 if (!tls->suspended) {
2984 tls->suspended = TRUE;
2985 mono_coop_sem_post (&suspend_sem);
2988 DEBUG_PRINTF (1, "[%p] Suspended.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2990 while (suspend_count - tls->resume_count > 0) {
2991 mono_coop_cond_wait (&suspend_cond, &suspend_mutex);
2994 tls->suspended = FALSE;
2995 tls->really_suspended = FALSE;
2997 threads_suspend_count --;
2999 mono_coop_mutex_unlock (&suspend_mutex);
3001 DEBUG_PRINTF (1, "[%p] Resumed.\n", (gpointer) (gsize) mono_native_thread_id_get ());
3003 if (tls->pending_invoke) {
3004 /* Save the original context */
3005 tls->pending_invoke->has_ctx = TRUE;
3006 tls->pending_invoke->ctx = tls->context.ctx;
3011 /* The frame info becomes invalid after a resume */
3012 tls->context.valid = FALSE;
3013 tls->async_state.valid = FALSE;
3014 invalidate_frames (tls);
3018 count_thread (gpointer key, gpointer value, gpointer user_data)
3020 DebuggerTlsData *tls = (DebuggerTlsData *)value;
3022 if (!tls->suspended && !tls->terminated && !mono_thread_internal_is_current (tls->thread))
3023 *(int*)user_data = *(int*)user_data + 1;
3027 count_threads_to_wait_for (void)
3031 mono_loader_lock ();
3032 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
3033 mono_loader_unlock ();
3041 * Wait until the runtime is completely suspended.
3044 wait_for_suspend (void)
3046 int nthreads, nwait, err;
3047 gboolean waited = FALSE;
3049 // FIXME: Threads starting/stopping ?
3050 mono_loader_lock ();
3051 nthreads = mono_g_hash_table_size (thread_to_tls);
3052 mono_loader_unlock ();
3055 nwait = count_threads_to_wait_for ();
3057 DEBUG_PRINTF (1, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads);
3058 err = mono_coop_sem_wait (&suspend_sem, MONO_SEM_FLAGS_NONE);
3059 g_assert (err == 0);
3067 DEBUG_PRINTF (1, "%d threads suspended.\n", nthreads);
3073 * Return whenever the runtime is suspended.
3078 return count_threads_to_wait_for () == 0;
3082 no_seq_points_found (MonoMethod *method, int offset)
3085 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3087 printf ("Unable to find seq points for method '%s', offset 0x%x.\n", mono_method_full_name (method, TRUE), offset);
3091 DebuggerTlsData *tls;
3093 } ComputeFramesUserData;
3096 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3098 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3100 MonoMethod *method, *actual_method, *api_method;
3104 if (info->type != FRAME_TYPE_MANAGED && info->type != FRAME_TYPE_INTERP) {
3105 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3106 /* Mark the last frame as an invoke frame */
3108 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3114 method = jinfo_get_method (info->ji);
3116 method = info->method;
3117 actual_method = info->actual_method;
3118 api_method = method;
3123 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3126 if (info->il_offset == -1) {
3127 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3128 if (ud->frames == NULL) {
3129 if (mono_find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL, &sp))
3130 info->il_offset = sp.il_offset;
3132 if (info->il_offset == -1)
3133 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3136 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);
3138 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3139 if (!CHECK_PROTOCOL_VERSION (2, 17))
3140 /* Older clients can't handle this flag */
3142 api_method = mono_marshal_method_from_wrapper (method);
3145 actual_method = api_method;
3146 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3149 frame = g_new0 (StackFrame, 1);
3150 frame->method = method;
3151 frame->actual_method = actual_method;
3152 frame->api_method = api_method;
3153 frame->il_offset = info->il_offset;
3154 frame->native_offset = info->native_offset;
3155 frame->flags = flags;
3156 frame->ji = info->ji;
3157 frame->interp_frame = info->interp_frame;
3158 if (info->reg_locations)
3159 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3162 frame->has_ctx = TRUE;
3164 frame->domain = info->domain;
3166 ud->frames = g_slist_append (ud->frames, frame);
3172 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3174 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3177 * 'tls->filter_ctx' is the location of the throw site.
3179 * mono_walk_stack() will never actually hit the throw site, but unwind
3180 * directly from the filter to the call site; we abort stack unwinding here
3181 * once this happens and resume from the throw site.
3184 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3187 return process_frame (info, ctx, user_data);
3191 * Return a malloc-ed list of StackFrame structures.
3194 compute_frame_info_from (MonoInternalThread *thread, DebuggerTlsData *tls, MonoThreadUnwindState *state, int *out_nframes)
3196 ComputeFramesUserData user_data;
3197 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3202 user_data.tls = tls;
3203 user_data.frames = NULL;
3205 mono_walk_stack_with_state (process_frame, state, opts, &user_data);
3207 nframes = g_slist_length (user_data.frames);
3208 res = g_new0 (StackFrame*, nframes);
3209 l = user_data.frames;
3210 for (i = 0; i < nframes; ++i) {
3211 res [i] = (StackFrame *)l->data;
3214 *out_nframes = nframes;
3220 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3222 ComputeFramesUserData user_data;
3224 int i, findex, new_frame_count;
3225 StackFrame **new_frames, *f;
3226 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3228 // FIXME: Locking on tls
3229 if (tls->frames && tls->frames_up_to_date)
3232 DEBUG_PRINTF (1, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid);
3234 user_data.tls = tls;
3235 user_data.frames = NULL;
3236 if (tls->terminated) {
3237 tls->frame_count = 0;
3239 } if (!tls->really_suspended && tls->async_state.valid) {
3240 /* Have to use the state saved by the signal handler */
3241 process_frame (&tls->async_last_frame, NULL, &user_data);
3242 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3243 } else if (tls->filter_state.valid) {
3245 * We are inside an exception filter.
3247 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3249 if (tls->context.valid)
3250 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3252 * After that, we resume unwinding from the location where the exception has been thrown.
3254 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3255 } else if (tls->context.valid) {
3256 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3259 tls->frame_count = 0;
3263 new_frame_count = g_slist_length (user_data.frames);
3264 new_frames = g_new0 (StackFrame*, new_frame_count);
3266 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3267 f = (StackFrame *)tmp->data;
3270 * Reuse the id for already existing stack frames, so invokes don't invalidate
3271 * the still valid stack frames.
3273 for (i = 0; i < tls->frame_count; ++i) {
3274 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3275 f->id = tls->frames [i]->id;
3280 if (i >= tls->frame_count)
3281 f->id = InterlockedIncrement (&frame_id);
3283 new_frames [findex ++] = f;
3286 g_slist_free (user_data.frames);
3288 invalidate_frames (tls);
3290 tls->frames = new_frames;
3291 tls->frame_count = new_frame_count;
3292 tls->frames_up_to_date = TRUE;
3296 * GHFunc to emit an appdomain creation event
3297 * @param key Don't care
3298 * @param value A loaded appdomain
3299 * @param user_data Don't care
3302 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3304 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3305 g_hash_table_foreach (get_agent_domain_info ((MonoDomain *)value)->loaded_classes, emit_type_load, NULL);
3309 * GHFunc to emit a thread start event
3310 * @param key A thread id
3311 * @param value A thread object
3312 * @param user_data Don't care
3315 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3317 g_assert (!mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (GPOINTER_TO_UINT (key)), debugger_thread_id));
3318 process_profiler_event (EVENT_KIND_THREAD_START, value);
3322 * GFunc to emit an assembly load event
3323 * @param value A loaded assembly
3324 * @param user_data Don't care
3327 emit_assembly_load (gpointer value, gpointer user_data)
3329 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3333 * GFunc to emit a type load event
3334 * @param value A loaded type
3335 * @param user_data Don't care
3338 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3340 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3344 strdup_tolower (char *s)
3349 for (p = s2; *p; ++p)
3355 * Same as g_path_get_basename () but handles windows paths as well,
3356 * which can occur in .mdb files created by pdb2mdb.
3359 dbg_path_get_basename (const char *filename)
3363 if (!filename || strchr (filename, '/') || !strchr (filename, '\\'))
3364 return g_path_get_basename (filename);
3368 /* No separator -> filename */
3369 r = strrchr (filename, '\\');
3371 return g_strdup (filename);
3373 /* Trailing slash, remove component */
3375 char *copy = g_strdup (filename);
3376 copy [r-filename] = 0;
3377 r = strrchr (copy, '\\');
3381 return g_strdup ("/");
3383 r = g_strdup (&r[1]);
3388 return g_strdup (&r[1]);
3392 init_jit_info_dbg_attrs (MonoJitInfo *ji)
3394 static MonoClass *hidden_klass, *step_through_klass, *non_user_klass;
3396 MonoCustomAttrInfo *ainfo;
3398 if (ji->dbg_attrs_inited)
3402 hidden_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3404 if (!step_through_klass)
3405 step_through_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3407 if (!non_user_klass)
3408 non_user_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute");
3410 ainfo = mono_custom_attrs_from_method_checked (jinfo_get_method (ji), &error);
3411 mono_error_cleanup (&error); /* FIXME don't swallow the error? */
3413 if (mono_custom_attrs_has_attr (ainfo, hidden_klass))
3414 ji->dbg_hidden = TRUE;
3415 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3416 ji->dbg_step_through = TRUE;
3417 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3418 ji->dbg_non_user_code = TRUE;
3419 mono_custom_attrs_free (ainfo);
3422 ainfo = mono_custom_attrs_from_class_checked (jinfo_get_method (ji)->klass, &error);
3423 mono_error_cleanup (&error); /* FIXME don't swallow the error? */
3425 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3426 ji->dbg_step_through = TRUE;
3427 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3428 ji->dbg_non_user_code = TRUE;
3429 mono_custom_attrs_free (ainfo);
3432 mono_memory_barrier ();
3433 ji->dbg_attrs_inited = TRUE;
3441 * create_event_list:
3443 * Return a list of event request ids matching EVENT, starting from REQS, which
3444 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3446 * We return request ids, instead of requests, to simplify threading, since
3447 * requests could be deleted anytime when the loader lock is not held.
3448 * LOCKING: Assumes the loader lock is held.
3451 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3454 GSList *events = NULL;
3456 *suspend_policy = SUSPEND_POLICY_NONE;
3459 reqs = event_requests;
3464 for (i = 0; i < reqs->len; ++i) {
3465 EventRequest *req = (EventRequest *)g_ptr_array_index (reqs, i);
3466 if (req->event_kind == event) {
3467 gboolean filtered = FALSE;
3470 for (j = 0; j < req->nmodifiers; ++j) {
3471 Modifier *mod = &req->modifiers [j];
3473 if (mod->kind == MOD_KIND_COUNT) {
3475 if (mod->data.count > 0) {
3476 if (mod->data.count > 0) {
3478 if (mod->data.count == 0)
3482 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3483 if (mod->data.thread != mono_thread_internal_current ())
3485 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3486 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3488 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3490 if (ei->caught && !mod->caught)
3492 if (!ei->caught && !mod->uncaught)
3494 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3496 gboolean found = FALSE;
3497 MonoAssembly **assemblies = mod->data.assemblies;
3500 for (k = 0; assemblies [k]; ++k)
3501 if (assemblies [k] == jinfo_get_method (ji)->klass->image->assembly)
3506 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3507 gpointer iter = NULL;
3509 MonoDebugSourceInfo *sinfo;
3510 char *source_file, *s;
3511 gboolean found = FALSE;
3513 GPtrArray *source_file_list;
3515 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3516 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3519 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, NULL, NULL, NULL);
3520 for (i = 0; i < source_file_list->len; ++i) {
3521 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
3523 * Do a case-insesitive match by converting the file name to
3526 s = strdup_tolower (sinfo->source_file);
3527 if (g_hash_table_lookup (mod->data.source_files, s))
3530 char *s2 = dbg_path_get_basename (sinfo->source_file);
3531 char *s3 = strdup_tolower (s2);
3533 if (g_hash_table_lookup (mod->data.source_files, s3))
3540 g_ptr_array_free (source_file_list, TRUE);
3545 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3548 s = mono_type_full_name (&ei->klass->byval_arg);
3549 if (!g_hash_table_lookup (mod->data.type_names, s))
3552 } else if (mod->kind == MOD_KIND_STEP) {
3553 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3554 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3555 !strcmp (jinfo_get_method (ji)->name, ".cctor") &&
3556 (jinfo_get_method (ji) != ((SingleStepReq*)req->info)->start_method))
3558 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3559 init_jit_info_dbg_attrs (ji);
3563 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3564 init_jit_info_dbg_attrs (ji);
3565 if (ji->dbg_step_through)
3568 if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3569 init_jit_info_dbg_attrs (ji);
3570 if (ji->dbg_non_user_code)
3577 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3578 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3583 /* Send a VM START/DEATH event by default */
3584 if (event == EVENT_KIND_VM_START)
3585 events = g_slist_append (events, GINT_TO_POINTER (0));
3586 if (event == EVENT_KIND_VM_DEATH)
3587 events = g_slist_append (events, GINT_TO_POINTER (0));
3592 static G_GNUC_UNUSED const char*
3593 event_to_string (EventKind event)
3596 case EVENT_KIND_VM_START: return "VM_START";
3597 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3598 case EVENT_KIND_THREAD_START: return "THREAD_START";
3599 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3600 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3601 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3602 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3603 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3604 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3605 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3606 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3607 case EVENT_KIND_STEP: return "STEP";
3608 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3609 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3610 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3611 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3612 case EVENT_KIND_USER_LOG: return "USER_LOG";
3614 g_assert_not_reached ();
3622 * Send an event to the client, suspending the vm if needed.
3623 * LOCKING: Since this can suspend the calling thread, no locks should be held
3625 * The EVENTS list is freed by this function.
3628 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3632 MonoDomain *domain = mono_domain_get ();
3633 MonoThread *thread = NULL;
3634 MonoObject *keepalive_obj = NULL;
3635 gboolean send_success = FALSE;
3640 DEBUG_PRINTF (2, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event));
3644 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3645 // FIXME: We miss those events
3646 DEBUG_PRINTF (2, "VM start event not sent yet: dropping %s\n", event_to_string (event));
3650 if (vm_death_event_sent) {
3651 DEBUG_PRINTF (2, "VM death event has been sent: dropping %s\n", event_to_string (event));
3655 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3656 DEBUG_PRINTF (2, "Mono runtime is shutting down: dropping %s\n", event_to_string (event));
3661 DEBUG_PRINTF (2, "Debugger client is not connected: dropping %s\n", event_to_string (event));
3665 if (event == EVENT_KIND_KEEPALIVE)
3666 suspend_policy = SUSPEND_POLICY_NONE;
3671 if (agent_config.defer) {
3672 /* Make sure the thread id is always set when doing deferred debugging */
3673 if (is_debugger_thread ()) {
3674 /* Don't suspend on events from the debugger thread */
3675 suspend_policy = SUSPEND_POLICY_NONE;
3676 thread = mono_thread_get_main ();
3678 else thread = mono_thread_current ();
3680 if (is_debugger_thread () && event != EVENT_KIND_VM_DEATH)
3681 // FIXME: Send these with a NULL thread, don't suspend the current thread
3686 nevents = g_slist_length (events);
3687 buffer_init (&buf, 128);
3688 buffer_add_byte (&buf, suspend_policy);
3689 buffer_add_int (&buf, nevents);
3691 for (l = events; l; l = l->next) {
3692 buffer_add_byte (&buf, event); // event kind
3693 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3697 if (event == EVENT_KIND_VM_DEATH) {
3701 thread = mono_thread_current ();
3703 if (event == EVENT_KIND_VM_START && arg != NULL)
3704 thread = (MonoThread *)arg;
3707 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3710 case EVENT_KIND_THREAD_START:
3711 case EVENT_KIND_THREAD_DEATH:
3713 case EVENT_KIND_APPDOMAIN_CREATE:
3714 case EVENT_KIND_APPDOMAIN_UNLOAD:
3715 buffer_add_domainid (&buf, (MonoDomain *)arg);
3717 case EVENT_KIND_METHOD_ENTRY:
3718 case EVENT_KIND_METHOD_EXIT:
3719 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3721 case EVENT_KIND_ASSEMBLY_LOAD:
3722 buffer_add_assemblyid (&buf, domain, (MonoAssembly *)arg);
3724 case EVENT_KIND_ASSEMBLY_UNLOAD: {
3725 DebuggerTlsData *tls;
3727 /* The domain the assembly belonged to is not equal to the current domain */
3728 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3730 g_assert (tls->domain_unloading);
3732 buffer_add_assemblyid (&buf, tls->domain_unloading, (MonoAssembly *)arg);
3735 case EVENT_KIND_TYPE_LOAD:
3736 buffer_add_typeid (&buf, domain, (MonoClass *)arg);
3738 case EVENT_KIND_BREAKPOINT:
3739 case EVENT_KIND_STEP:
3740 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3741 buffer_add_long (&buf, il_offset);
3743 case EVENT_KIND_VM_START:
3744 buffer_add_domainid (&buf, mono_get_root_domain ());
3746 case EVENT_KIND_VM_DEATH:
3747 if (CHECK_PROTOCOL_VERSION (2, 27))
3748 buffer_add_int (&buf, mono_environment_exitcode_get ());
3750 case EVENT_KIND_EXCEPTION: {
3751 EventInfo *ei = (EventInfo *)arg;
3752 buffer_add_objid (&buf, ei->exc);
3754 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3755 * later after the suspension. (#12494).
3757 keepalive_obj = ei->exc;
3760 case EVENT_KIND_USER_BREAK:
3762 case EVENT_KIND_USER_LOG: {
3763 EventInfo *ei = (EventInfo *)arg;
3764 buffer_add_int (&buf, ei->level);
3765 buffer_add_string (&buf, ei->category ? ei->category : "");
3766 buffer_add_string (&buf, ei->message ? ei->message : "");
3769 case EVENT_KIND_KEEPALIVE:
3770 suspend_policy = SUSPEND_POLICY_NONE;
3773 g_assert_not_reached ();
3777 if (event == EVENT_KIND_VM_START) {
3778 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3779 if (!agent_config.defer)
3780 start_debugger_thread ();
3783 if (event == EVENT_KIND_VM_DEATH) {
3784 vm_death_event_sent = TRUE;
3785 suspend_policy = SUSPEND_POLICY_NONE;
3788 if (mono_runtime_is_shutting_down ())
3789 suspend_policy = SUSPEND_POLICY_NONE;
3791 if (suspend_policy != SUSPEND_POLICY_NONE) {
3793 * Save the thread context and start suspending before sending the packet,
3794 * since we could be receiving the resume request before send_packet ()
3797 save_thread_context (ctx);
3801 /* This will keep this object alive */
3802 get_objref (keepalive_obj);
3805 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3809 g_slist_free (events);
3812 if (!send_success) {
3813 DEBUG_PRINTF (2, "Sending command %s failed.\n", event_to_string (event));
3817 if (event == EVENT_KIND_VM_START) {
3818 vm_start_event_sent = TRUE;
3821 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);
3823 switch (suspend_policy) {
3824 case SUSPEND_POLICY_NONE:
3826 case SUSPEND_POLICY_ALL:
3829 case SUSPEND_POLICY_EVENT_THREAD:
3833 g_assert_not_reached ();
3838 process_profiler_event (EventKind event, gpointer arg)
3842 EventInfo ei, *ei_arg = NULL;
3844 if (event == EVENT_KIND_TYPE_LOAD) {
3845 ei.klass = (MonoClass *)arg;
3849 mono_loader_lock ();
3850 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3851 mono_loader_unlock ();
3853 process_event (event, arg, 0, NULL, events, suspend_policy);
3857 runtime_initialized (MonoProfiler *prof)
3859 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3860 if (agent_config.defer)
3861 start_debugger_thread ();
3865 runtime_shutdown (MonoProfiler *prof)
3867 process_profiler_event (EVENT_KIND_VM_DEATH, NULL);
3869 mono_debugger_agent_cleanup ();
3873 thread_startup (MonoProfiler *prof, uintptr_t tid)
3875 MonoInternalThread *thread = mono_thread_internal_current ();
3876 MonoInternalThread *old_thread;
3877 DebuggerTlsData *tls;
3879 if (is_debugger_thread ())
3882 g_assert (mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (tid), MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid)));
3884 mono_loader_lock ();
3885 old_thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3886 mono_loader_unlock ();
3888 if (thread == old_thread) {
3890 * For some reason, thread_startup () might be called for the same thread
3891 * multiple times (attach ?).
3893 DEBUG_PRINTF (1, "[%p] thread_start () called multiple times for %p, ignored.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3897 * thread_end () might not be called for some threads, and the tid could
3900 DEBUG_PRINTF (1, "[%p] Removing stale data for tid %p.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3901 mono_loader_lock ();
3902 mono_g_hash_table_remove (thread_to_tls, old_thread);
3903 mono_g_hash_table_remove (tid_to_thread, GUINT_TO_POINTER (tid));
3904 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3905 mono_loader_unlock ();
3909 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3911 // FIXME: Free this somewhere
3912 tls = g_new0 (DebuggerTlsData, 1);
3913 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread, MONO_ROOT_SOURCE_DEBUGGER, "debugger thread reference");
3914 tls->thread = thread;
3915 mono_native_tls_set_value (debugger_tls_id, tls);
3917 DEBUG_PRINTF (1, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3919 mono_loader_lock ();
3920 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3921 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3922 mono_g_hash_table_insert (tid_to_thread_obj, GUINT_TO_POINTER (tid), mono_thread_current ());
3923 mono_loader_unlock ();
3925 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3928 * suspend_vm () could have missed this thread, so wait for a resume.
3934 thread_end (MonoProfiler *prof, uintptr_t tid)
3936 MonoInternalThread *thread;
3937 DebuggerTlsData *tls = NULL;
3939 mono_loader_lock ();
3940 thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3942 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3943 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
3945 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3946 tls->terminated = TRUE;
3947 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3948 MONO_GC_UNREGISTER_ROOT (tls->thread);
3952 mono_loader_unlock ();
3954 /* We might be called for threads started before we registered the start callback */
3956 DEBUG_PRINTF (1, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3958 if (mono_thread_internal_is_current (thread) && !mono_native_tls_get_value (debugger_tls_id)
3961 * This can happen on darwin since we deregister threads using pthread dtors.
3962 * process_profiler_event () and the code it calls cannot handle a null TLS value.
3967 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3972 appdomain_load (MonoProfiler *prof, MonoDomain *domain)
3974 mono_loader_lock ();
3975 g_hash_table_insert (domains, domain, domain);
3976 mono_loader_unlock ();
3978 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3982 appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain)
3984 DebuggerTlsData *tls;
3986 /* This might be called during shutdown on the debugger thread from the CMD_VM_EXIT code */
3987 if (is_debugger_thread ())
3991 * Remember the currently unloading appdomain as it is needed to generate
3992 * proper ids for unloading assemblies.
3994 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3996 tls->domain_unloading = domain;
4000 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
4002 DebuggerTlsData *tls;
4004 if (is_debugger_thread ())
4007 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4009 tls->domain_unloading = NULL;
4011 clear_breakpoints_for_domain (domain);
4013 mono_loader_lock ();
4014 /* Invalidate each thread's frame stack */
4015 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
4016 mono_loader_unlock ();
4018 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
4022 * invalidate_each_thread:
4024 * A GHFunc to invalidate frames.
4025 * value must be a DebuggerTlsData*
4028 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
4030 invalidate_frames ((DebuggerTlsData *)value);
4034 assembly_load (MonoProfiler *prof, MonoAssembly *assembly)
4036 /* Sent later in jit_end () */
4038 g_ptr_array_add (pending_assembly_loads, assembly);
4043 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
4045 if (is_debugger_thread ())
4048 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
4050 clear_event_requests_for_assembly (assembly);
4051 clear_types_for_assembly (assembly);
4055 send_type_load (MonoClass *klass)
4057 gboolean type_load = FALSE;
4058 MonoDomain *domain = mono_domain_get ();
4059 AgentDomainInfo *info = NULL;
4061 info = get_agent_domain_info (domain);
4063 mono_loader_lock ();
4065 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
4067 g_hash_table_insert (info->loaded_classes, klass, klass);
4070 mono_loader_unlock ();
4073 emit_type_load (klass, klass, NULL);
4077 * Emit load events for all types currently loaded in the domain.
4078 * Takes the loader and domain locks.
4079 * user_data is unused.
4082 send_types_for_domain (MonoDomain *domain, void *user_data)
4084 MonoDomain* old_domain;
4085 AgentDomainInfo *info = NULL;
4087 info = get_agent_domain_info (domain);
4090 old_domain = mono_domain_get ();
4092 mono_domain_set (domain, TRUE);
4094 mono_loader_lock ();
4095 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4096 mono_loader_unlock ();
4098 mono_domain_set (old_domain, TRUE);
4102 send_assemblies_for_domain (MonoDomain *domain, void *user_data)
4105 MonoDomain* old_domain;
4107 old_domain = mono_domain_get ();
4109 mono_domain_set (domain, TRUE);
4111 mono_domain_assemblies_lock (domain);
4112 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
4113 MonoAssembly* ass = (MonoAssembly *)tmp->data;
4114 emit_assembly_load (ass, NULL);
4116 mono_domain_assemblies_unlock (domain);
4118 mono_domain_set (old_domain, TRUE);
4122 jit_done (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo)
4124 jit_end (prof, method, jinfo);
4128 jit_failed (MonoProfiler *prof, MonoMethod *method)
4130 jit_end (prof, method, NULL);
4134 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo)
4137 * We emit type load events when the first method of the type is JITted,
4138 * since the class load profiler callbacks might be called with the
4139 * loader lock held. They could also occur in the debugger thread.
4140 * Same for assembly load events.
4143 MonoAssembly *assembly = NULL;
4145 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4147 if (pending_assembly_loads->len > 0) {
4148 assembly = (MonoAssembly *)g_ptr_array_index (pending_assembly_loads, 0);
4149 g_ptr_array_remove_index (pending_assembly_loads, 0);
4154 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4160 send_type_load (method->klass);
4163 add_pending_breakpoints (method, jinfo);
4167 * BREAKPOINTS/SINGLE STEPPING
4171 * Contains information about an inserted breakpoint.
4174 long il_offset, native_offset;
4178 } BreakpointInstance;
4181 * Contains generic information about a breakpoint.
4185 * The method where the breakpoint is placed. Can be NULL in which case it
4186 * is inserted into every method. This is used to implement method entry/
4187 * exit events. Can be a generic method definition, in which case the
4188 * breakpoint is inserted into every instance.
4194 * A list of BreakpointInstance structures describing where the breakpoint
4195 * was inserted. There could be more than one because of
4196 * generics/appdomains/method entry/exit.
4198 GPtrArray *children;
4201 /* List of breakpoints */
4202 /* Protected by the loader lock */
4203 static GPtrArray *breakpoints;
4204 /* Maps breakpoint locations to the number of breakpoints at that location */
4205 static GHashTable *bp_locs;
4208 breakpoints_init (void)
4210 breakpoints = g_ptr_array_new ();
4211 bp_locs = g_hash_table_new (NULL, NULL);
4215 * insert_breakpoint:
4217 * Insert the breakpoint described by BP into the method described by
4221 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4224 BreakpointInstance *inst;
4225 SeqPointIterator it;
4226 gboolean it_has_sp = FALSE;
4231 mono_seq_point_iterator_init (&it, seq_points);
4232 while (mono_seq_point_iterator_next (&it)) {
4233 if (it.seq_point.il_offset == bp->il_offset) {
4241 * The set of IL offsets with seq points doesn't completely match the
4242 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4244 mono_seq_point_iterator_init (&it, seq_points);
4245 while (mono_seq_point_iterator_next (&it)) {
4246 if (it.seq_point.il_offset != METHOD_ENTRY_IL_OFFSET &&
4247 it.seq_point.il_offset != METHOD_EXIT_IL_OFFSET &&
4248 it.seq_point.il_offset + 1 == bp->il_offset) {
4256 char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d", mono_method_full_name (jinfo_get_method (ji), TRUE), bp->il_offset);
4258 mono_seq_point_iterator_init (&it, seq_points);
4259 while (mono_seq_point_iterator_next (&it))
4260 DEBUG_PRINTF (1, "%d\n", it.seq_point.il_offset);
4263 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4264 g_warning ("%s", s);
4268 g_warning ("%s", s);
4274 inst = g_new0 (BreakpointInstance, 1);
4275 inst->il_offset = it.seq_point.il_offset;
4276 inst->native_offset = it.seq_point.native_offset;
4277 inst->ip = (guint8*)ji->code_start + it.seq_point.native_offset;
4279 inst->domain = domain;
4281 mono_loader_lock ();
4283 g_ptr_array_add (bp->children, inst);
4285 mono_loader_unlock ();
4288 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4289 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4292 if (it.seq_point.native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4293 DEBUG_PRINTF (1, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset);
4294 } else if (count == 0) {
4295 if (ji->is_interp) {
4296 mono_interp_set_breakpoint (ji, inst->ip);
4298 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4299 mono_arch_set_breakpoint (ji, inst->ip);
4306 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);
4310 remove_breakpoint (BreakpointInstance *inst)
4312 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4314 MonoJitInfo *ji = inst->ji;
4315 guint8 *ip = inst->ip;
4318 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4319 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4322 g_assert (count > 0);
4324 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4326 mono_interp_clear_breakpoint (ji, ip);
4328 mono_arch_clear_breakpoint (ji, ip);
4329 DEBUG_PRINTF (1, "[dbg] Clear breakpoint at %s [%p].\n", mono_method_full_name (jinfo_get_method (ji), TRUE), ip);
4337 * This doesn't take any locks.
4339 static inline gboolean
4340 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4346 if (method == bp->method)
4348 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4351 if (bp->method->is_inflated && method->is_inflated) {
4352 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4353 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4355 /* Open generic methods should match closed generic methods of the same class */
4356 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4357 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4358 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4360 /* FIXME: Handle !mvar */
4361 if (t1->type != MONO_TYPE_MVAR)
4372 * add_pending_breakpoints:
4374 * Insert pending breakpoints into the newly JITted method METHOD.
4377 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4380 MonoSeqPointInfo *seq_points;
4382 MonoMethod *jmethod;
4387 domain = mono_domain_get ();
4389 mono_loader_lock ();
4391 for (i = 0; i < breakpoints->len; ++i) {
4392 MonoBreakpoint *bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4393 gboolean found = FALSE;
4395 if (!bp_matches_method (bp, method))
4398 for (j = 0; j < bp->children->len; ++j) {
4399 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4406 MonoMethod *declaring = NULL;
4408 jmethod = jinfo_get_method (ji);
4409 if (jmethod->is_inflated)
4410 declaring = mono_method_get_declaring_generic_method (jmethod);
4412 mono_domain_lock (domain);
4413 seq_points = (MonoSeqPointInfo *)g_hash_table_lookup (domain_jit_info (domain)->seq_points, jmethod);
4414 if (!seq_points && declaring)
4415 seq_points = (MonoSeqPointInfo *)g_hash_table_lookup (domain_jit_info (domain)->seq_points, declaring);
4416 mono_domain_unlock (domain);
4418 /* Could be AOT code */
4420 g_assert (seq_points);
4422 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4426 mono_loader_unlock ();
4430 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4438 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4442 /* Might be AOTed code */
4443 mono_class_init (method->klass);
4444 code = mono_aot_get_method_checked (domain, method, &oerror);
4446 mono_error_assert_ok (&oerror);
4447 ji = mono_jit_info_table_find (domain, (char *)code);
4449 /* Might be interpreted */
4450 ji = mono_interp_find_jit_info (domain, method);
4455 insert_breakpoint (seq_points, domain, ji, bp, error);
4459 clear_breakpoint (MonoBreakpoint *bp);
4464 * Set a breakpoint at IL_OFFSET in METHOD.
4465 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4466 * METHOD can also be a generic method definition, in which case a breakpoint
4467 * is placed in all instances of the method.
4468 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4471 static MonoBreakpoint*
4472 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4475 GHashTableIter iter, iter2;
4478 MonoSeqPointInfo *seq_points;
4480 GPtrArray *method_domains;
4481 GPtrArray *method_seq_points;
4488 // - suspend/resume the vm to prevent code patching problems
4489 // - multiple breakpoints on the same location
4490 // - dynamic methods
4493 bp = g_new0 (MonoBreakpoint, 1);
4494 bp->method = method;
4495 bp->il_offset = il_offset;
4497 bp->children = g_ptr_array_new ();
4499 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);
4501 methods = g_ptr_array_new ();
4502 method_domains = g_ptr_array_new ();
4503 method_seq_points = g_ptr_array_new ();
4505 mono_loader_lock ();
4506 g_hash_table_iter_init (&iter, domains);
4507 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4508 mono_domain_lock (domain);
4509 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4510 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4511 if (bp_matches_method (bp, m)) {
4512 /* Save the info locally to simplify the code inside the domain lock */
4513 g_ptr_array_add (methods, m);
4514 g_ptr_array_add (method_domains, domain);
4515 g_ptr_array_add (method_seq_points, seq_points);
4518 mono_domain_unlock (domain);
4521 for (i = 0; i < methods->len; ++i) {
4522 m = (MonoMethod *)g_ptr_array_index (methods, i);
4523 domain = (MonoDomain *)g_ptr_array_index (method_domains, i);
4524 seq_points = (MonoSeqPointInfo *)g_ptr_array_index (method_seq_points, i);
4525 set_bp_in_method (domain, m, seq_points, bp, error);
4528 g_ptr_array_add (breakpoints, bp);
4529 mono_loader_unlock ();
4531 g_ptr_array_free (methods, TRUE);
4532 g_ptr_array_free (method_domains, TRUE);
4533 g_ptr_array_free (method_seq_points, TRUE);
4535 if (error && !mono_error_ok (error)) {
4536 clear_breakpoint (bp);
4544 clear_breakpoint (MonoBreakpoint *bp)
4548 // FIXME: locking, races
4549 for (i = 0; i < bp->children->len; ++i) {
4550 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, i);
4552 remove_breakpoint (inst);
4557 mono_loader_lock ();
4558 g_ptr_array_remove (breakpoints, bp);
4559 mono_loader_unlock ();
4561 g_ptr_array_free (bp->children, TRUE);
4566 breakpoints_cleanup (void)
4570 mono_loader_lock ();
4572 while (i < event_requests->len) {
4573 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
4575 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4576 clear_breakpoint ((MonoBreakpoint *)req->info);
4577 g_ptr_array_remove_index_fast (event_requests, i);
4584 for (i = 0; i < breakpoints->len; ++i)
4585 g_free (g_ptr_array_index (breakpoints, i));
4587 g_ptr_array_free (breakpoints, TRUE);
4588 g_hash_table_destroy (bp_locs);
4593 mono_loader_unlock ();
4597 * clear_breakpoints_for_domain:
4599 * Clear breakpoint instances which reference DOMAIN.
4602 clear_breakpoints_for_domain (MonoDomain *domain)
4606 /* This could be called after shutdown */
4610 mono_loader_lock ();
4611 for (i = 0; i < breakpoints->len; ++i) {
4612 MonoBreakpoint *bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4615 while (j < bp->children->len) {
4616 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4618 if (inst->domain == domain) {
4619 remove_breakpoint (inst);
4623 g_ptr_array_remove_index_fast (bp->children, j);
4629 mono_loader_unlock ();
4633 * ss_calculate_framecount:
4635 * Ensure DebuggerTlsData fields are filled out.
4637 static void ss_calculate_framecount (DebuggerTlsData *tls, MonoContext *ctx)
4639 if (!tls->context.valid)
4640 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4641 compute_frame_info (tls->thread, tls);
4645 ensure_jit (StackFrame* frame)
4648 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
4649 if (!frame->jit && frame->api_method->is_inflated)
4650 frame->jit = mono_debug_find_method(mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
4654 /* This could happen for aot images with no jit debug info */
4655 s = mono_method_full_name (frame->api_method, TRUE);
4656 DEBUG_PRINTF(1, "[dbg] No debug information found for '%s'.\n", s);
4667 * Return FALSE if single stepping needs to continue.
4670 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp, DebuggerTlsData *tls, MonoContext *ctx, MonoMethod* method)
4672 MonoDebugMethodInfo *minfo;
4673 MonoDebugSourceLocation *loc = NULL;
4674 gboolean hit = TRUE;
4676 if (req->async_stepout_method == method) {
4677 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);
4681 if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK)) {
4683 * These seq points are inserted by the JIT after calls, step over needs to skip them.
4685 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);
4689 if ((req->depth == STEP_DEPTH_OVER || req->depth == STEP_DEPTH_OUT) && hit && !req->async_stepout_method) {
4690 gboolean is_step_out = req->depth == STEP_DEPTH_OUT;
4692 ss_calculate_framecount (tls, ctx);
4694 // Because functions can call themselves recursively, we need to make sure we're stopping at the right stack depth.
4695 // In case of step out, the target is the frame *enclosing* the one where the request was made.
4696 int target_frames = req->nframes + (is_step_out ? -1 : 0);
4697 if (req->nframes > 0 && tls->frame_count > 0 && tls->frame_count > target_frames) {
4698 /* Hit the breakpoint in a recursive call, don't halt */
4699 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");
4704 if (req->depth == STEP_DEPTH_INTO && req->size == STEP_SIZE_MIN && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) && ss_req->start_method){
4705 ss_calculate_framecount (tls, ctx);
4706 if (ss_req->start_method == method && req->nframes && tls->frame_count == req->nframes) {//Check also frame count(could be recursion)
4707 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);
4712 MonoDebugMethodAsyncInfo* async_method = mono_debug_lookup_method_async_debug_info (method);
4714 for (int i = 0; i < async_method->num_awaits; i++) {
4715 if (async_method->yield_offsets[i] == sp->il_offset || async_method->resume_offsets[i] == sp->il_offset) {
4716 mono_debug_free_method_async_debug_info (async_method);
4720 mono_debug_free_method_async_debug_info (async_method);
4723 if (req->size != STEP_SIZE_LINE)
4726 /* Have to check whenever a different source line was reached */
4727 minfo = mono_debug_lookup_method (method);
4730 loc = mono_debug_method_lookup_location (minfo, sp->il_offset);
4733 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);
4734 ss_req->last_method = method;
4736 } else if (loc && method == ss_req->last_method && loc->row == ss_req->last_line) {
4737 ss_calculate_framecount (tls, ctx);
4738 if (tls->frame_count == req->nframes) { // If the frame has changed we're clearly not on the same source line.
4739 DEBUG_PRINTF (1, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer) (gsize) mono_native_thread_id_get (), loc->row);
4745 ss_req->last_method = method;
4746 ss_req->last_line = loc->row;
4747 mono_debug_free_source_location (loc);
4754 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4756 return bp->method && bp->method->klass->image->assembly == assembly;
4760 get_this (StackFrame *frame)
4762 //Logic inspiered by "add_var" method and took out path that happens in async method for getting this
4763 MonoDebugVarInfo *var = frame->jit->this_var;
4764 if ((var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS) != MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET)
4767 guint8 * addr = (guint8 *)mono_arch_context_get_int_reg (&frame->ctx, var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS);
4768 addr += (gint32)var->offset;
4769 return *(MonoObject**)addr;
4772 //This ID is used to figure out if breakpoint hit on resumeOffset belongs to us or not
4773 //since thread probably changed...
4775 get_this_async_id (StackFrame *frame)
4777 return get_objid (get_this (frame));
4781 get_set_notification_method (MonoClass* async_builder_class)
4784 GPtrArray* array = mono_class_get_methods_by_name (async_builder_class, "SetNotificationForWaitCompletion", 0x24, FALSE, FALSE, &error);
4785 mono_error_assert_ok (&error);
4786 g_assert (array->len == 1);
4787 MonoMethod* set_notification_method = (MonoMethod *)g_ptr_array_index (array, 0);
4788 g_ptr_array_free (array, TRUE);
4789 return set_notification_method;
4793 set_set_notification_for_wait_completion_flag (StackFrame *frame)
4795 MonoObject* obj = get_this (frame);
4797 MonoClassField *builder_field = mono_class_get_field_from_name (obj->vtable->klass, "<>t__builder");
4798 g_assert (builder_field);
4799 MonoObject* builder;
4801 builder = mono_field_get_value_object_checked (frame->domain, builder_field, obj, &error);
4802 mono_error_assert_ok (&error);
4806 gboolean arg = TRUE;
4808 mono_runtime_invoke_checked (get_set_notification_method (builder->vtable->klass), mono_object_unbox (builder), args, &error);
4809 mono_error_assert_ok (&error);
4810 mono_field_set_value (obj, builder_field, mono_object_unbox (builder));
4813 static MonoMethod* notify_debugger_of_wait_completion_method_cache = NULL;
4816 get_notify_debugger_of_wait_completion_method (void)
4818 if (notify_debugger_of_wait_completion_method_cache != NULL)
4819 return notify_debugger_of_wait_completion_method_cache;
4821 MonoClass* task_class = mono_class_load_from_name (mono_defaults.corlib, "System.Threading.Tasks", "Task");
4822 GPtrArray* array = mono_class_get_methods_by_name (task_class, "NotifyDebuggerOfWaitCompletion", 0x24, FALSE, FALSE, &error);
4823 mono_error_assert_ok (&error);
4824 g_assert (array->len == 1);
4825 notify_debugger_of_wait_completion_method_cache = (MonoMethod *)g_ptr_array_index (array, 0);
4826 g_ptr_array_free (array, TRUE);
4827 return notify_debugger_of_wait_completion_method_cache;
4831 process_breakpoint (DebuggerTlsData *tls, gboolean from_signal)
4835 int i, j, suspend_policy;
4836 guint32 native_offset;
4838 BreakpointInstance *inst;
4839 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4840 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4841 EventKind kind = EVENT_KIND_BREAKPOINT;
4842 MonoContext *ctx = &tls->restore_state.ctx;
4844 MonoSeqPointInfo *info;
4848 // FIXME: Speed this up
4850 ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
4851 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4855 // FIXME: Pass a flag instead to detect this
4856 MonoLMF *lmf = mono_get_lmf ();
4857 MonoInterpFrameHandle *frame;
4859 g_assert (((guint64)lmf->previous_lmf) & 2);
4860 MonoLMFExt *ext = (MonoLMFExt*)lmf;
4862 g_assert (ext->interp_exit);
4863 frame = ext->interp_exit_data;
4864 ji = mono_interp_frame_get_jit_info (frame);
4865 ip = mono_interp_frame_get_ip (frame);
4868 g_assert (ji && !ji->is_trampoline);
4869 method = jinfo_get_method (ji);
4871 /* Compute the native offset of the breakpoint from the ip */
4872 native_offset = ip - (guint8*)ji->code_start;
4875 * Skip the instruction causing the breakpoint signal.
4878 mono_arch_skip_breakpoint (ctx, ji);
4880 if (method->wrapper_type || tls->disable_breakpoints)
4883 bp_reqs = g_ptr_array_new ();
4884 ss_reqs = g_ptr_array_new ();
4885 ss_reqs_orig = g_ptr_array_new ();
4887 mono_loader_lock ();
4890 * The ip points to the instruction causing the breakpoint event, which is after
4891 * the offset recorded in the seq point map, so find the prev seq point before ip.
4893 found_sp = mono_find_prev_seq_point_for_native_offset (mono_domain_get (), method, native_offset, &info, &sp);
4896 no_seq_points_found (method, native_offset);
4898 g_assert (found_sp);
4900 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);
4903 for (i = 0; i < breakpoints->len; ++i) {
4904 bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4909 for (j = 0; j < bp->children->len; ++j) {
4910 inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4911 if (inst->ji == ji && inst->il_offset == sp.il_offset && inst->native_offset == sp.native_offset) {
4912 if (bp->req->event_kind == EVENT_KIND_STEP) {
4913 g_ptr_array_add (ss_reqs_orig, bp->req);
4915 g_ptr_array_add (bp_reqs, bp->req);
4920 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4921 /* Maybe a method entry/exit event */
4922 if (sp.il_offset == METHOD_ENTRY_IL_OFFSET)
4923 kind = EVENT_KIND_METHOD_ENTRY;
4924 else if (sp.il_offset == METHOD_EXIT_IL_OFFSET)
4925 kind = EVENT_KIND_METHOD_EXIT;
4928 /* Process single step requests */
4929 for (i = 0; i < ss_reqs_orig->len; ++i) {
4930 EventRequest *req = (EventRequest *)g_ptr_array_index (ss_reqs_orig, i);
4931 SingleStepReq *ss_req = (SingleStepReq *)req->info;
4934 //if we hit async_stepout_method, it's our no matter which thread
4935 if ((ss_req->async_stepout_method != method) && (ss_req->async_id || mono_thread_internal_current () != ss_req->thread)) {
4936 //We have different thread and we don't have async stepping in progress
4937 //it's breakpoint in parallel thread, ignore it
4938 if (ss_req->async_id == 0)
4941 tls->context.valid = FALSE;
4942 tls->async_state.valid = FALSE;
4943 invalidate_frames (tls);
4944 ss_calculate_framecount(tls, ctx);
4945 //make sure we have enough data to get current async method instance id
4946 if (tls->frame_count == 0 || !ensure_jit (tls->frames [0]))
4949 //Check method is async before calling get_this_async_id
4950 MonoDebugMethodAsyncInfo* asyncMethod = mono_debug_lookup_method_async_debug_info (method);
4954 mono_debug_free_method_async_debug_info (asyncMethod);
4956 //breakpoint was hit in parallelly executing async method, ignore it
4957 if (ss_req->async_id != get_this_async_id (tls->frames [0]))
4961 //Update stepping request to new thread/frame_count that we are continuing on
4962 //so continuing with normal stepping works as expected
4963 if (ss_req->async_stepout_method || ss_req->async_id) {
4964 tls->context.valid = FALSE;
4965 tls->async_state.valid = FALSE;
4966 invalidate_frames (tls);
4967 ss_calculate_framecount (tls, ctx);
4968 ss_req->thread = mono_thread_internal_current ();
4969 ss_req->nframes = tls->frame_count;
4972 hit = ss_update (ss_req, ji, &sp, tls, ctx, method);
4974 g_ptr_array_add (ss_reqs, req);
4976 /* Start single stepping again from the current sequence point */
4977 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
4980 if (ss_reqs->len > 0)
4981 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4982 if (bp_reqs->len > 0)
4983 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4984 if (kind != EVENT_KIND_BREAKPOINT)
4985 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4987 mono_loader_unlock ();
4989 g_ptr_array_free (bp_reqs, TRUE);
4990 g_ptr_array_free (ss_reqs, TRUE);
4993 * FIXME: The first event will suspend, so the second will only be sent after the
4997 process_event (EVENT_KIND_STEP, method, 0, ctx, ss_events, suspend_policy);
4999 process_event (kind, method, 0, ctx, bp_events, suspend_policy);
5000 if (enter_leave_events)
5001 process_event (kind, method, 0, ctx, enter_leave_events, suspend_policy);
5004 /* Process a breakpoint/single step event after resuming from a signal handler */
5006 process_signal_event (void (*func) (DebuggerTlsData*, gboolean))
5008 DebuggerTlsData *tls;
5009 MonoThreadUnwindState orig_restore_state;
5012 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5013 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
5014 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5015 mono_thread_state_init_from_monoctx (&tls->restore_state, &tls->handler_ctx);
5019 /* This is called when resuming from a signal handler, so it shouldn't return */
5020 memcpy (&ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5021 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5022 mono_restore_context (&ctx);
5023 g_assert_not_reached ();
5027 process_breakpoint_from_signal (void)
5029 process_signal_event (process_breakpoint);
5033 resume_from_signal_handler (void *sigctx, void *func)
5035 DebuggerTlsData *tls;
5038 /* Save the original context in TLS */
5039 // FIXME: This might not work on an altstack ?
5040 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5042 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer) (gsize) mono_native_thread_id_get ());
5045 // FIXME: MonoContext usually doesn't include the fp registers, so these are
5046 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
5047 // clob:c could be added to op_seq_point.
5049 mono_sigctx_to_monoctx (sigctx, &ctx);
5050 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
5051 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
5052 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
5054 MONO_CONTEXT_SET_IP (&ctx, func);
5056 mono_monoctx_to_sigctx (&ctx, sigctx);
5058 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
5059 mono_ppc_set_func_into_sigctx (sigctx, func);
5064 mono_debugger_agent_breakpoint_hit (void *sigctx)
5067 * We are called from a signal handler, and running code there causes all kinds of
5068 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
5069 * So set up the signal context to return to the real breakpoint handler function.
5071 resume_from_signal_handler (sigctx, process_breakpoint_from_signal);
5080 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer user_data)
5082 UserBreakCbData *data = user_data;
5084 if (frame->type == FRAME_TYPE_INTERP_TO_MANAGED) {
5088 if (frame->managed) {
5098 * Called by System.Diagnostics.Debugger:Break ().
5101 mono_debugger_agent_user_break (void)
5103 if (agent_config.enabled) {
5107 UserBreakCbData data;
5109 memset (&data, 0, sizeof (UserBreakCbData));
5112 /* Obtain a context */
5113 MONO_CONTEXT_SET_IP (&ctx, NULL);
5114 mono_walk_stack_with_ctx (user_break_cb, NULL, (MonoUnwindOptions)0, &data);
5115 g_assert (data.found);
5117 mono_loader_lock ();
5118 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
5119 mono_loader_unlock ();
5121 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
5122 } else if (debug_options.native_debugger_break) {
5128 ss_depth_to_string (StepDepth depth)
5131 case STEP_DEPTH_OVER:
5133 case STEP_DEPTH_OUT:
5135 case STEP_DEPTH_INTO:
5138 g_assert_not_reached ();
5144 process_single_step_inner (DebuggerTlsData *tls, gboolean from_signal)
5149 int il_offset, suspend_policy;
5152 MonoContext *ctx = &tls->restore_state.ctx;
5155 MonoSeqPointInfo *info;
5157 /* Skip the instruction causing the single step */
5159 mono_arch_skip_single_step (ctx);
5161 if (suspend_count > 0) {
5162 /* Fastpath during invokes, see in process_suspend () */
5163 if (suspend_count - tls->resume_count == 0)
5165 process_suspend (tls, ctx);
5170 // FIXME: A suspend race
5173 if (mono_thread_internal_current () != ss_req->thread)
5176 ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
5178 ji = get_top_method_ji (ip, &domain, (gpointer*)&ip);
5179 g_assert (ji && !ji->is_trampoline);
5181 if (log_level > 0) {
5182 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);
5185 method = jinfo_get_method (ji);
5188 if (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
5193 * Stopping in memset makes half-initialized vtypes visible.
5194 * Stopping in memcpy makes half-copied vtypes visible.
5196 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
5200 * This could be in ss_update method, but mono_find_next_seq_point_for_native_offset is pretty expensive method,
5201 * hence we prefer this check here.
5203 if (ss_req->user_assemblies) {
5204 gboolean found = FALSE;
5205 for (int k = 0; ss_req->user_assemblies[k]; k++)
5206 if (ss_req->user_assemblies[k] == method->klass->image->assembly) {
5216 * The ip points to the instruction causing the single step event, which is before
5217 * the offset recorded in the seq point map, so find the next seq point after ip.
5219 if (!mono_find_next_seq_point_for_native_offset (domain, method, (guint8*)ip - (guint8*)ji->code_start, &info, &sp)) {
5220 g_assert_not_reached ();
5224 il_offset = sp.il_offset;
5226 if (!ss_update (ss_req, ji, &sp, tls, ctx, method))
5229 /* Start single stepping again from the current sequence point */
5230 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
5232 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
5233 (method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
5234 !strcmp (method->name, ".cctor"))
5237 // FIXME: Has to lock earlier
5239 reqs = g_ptr_array_new ();
5241 mono_loader_lock ();
5243 g_ptr_array_add (reqs, ss_req->req);
5245 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
5247 g_ptr_array_free (reqs, TRUE);
5249 mono_loader_unlock ();
5251 process_event (EVENT_KIND_STEP, jinfo_get_method (ji), il_offset, ctx, events, suspend_policy);
5255 process_single_step (void)
5257 process_signal_event (process_single_step_inner);
5261 * mono_debugger_agent_single_step_event:
5263 * Called from a signal handler to handle a single step event.
5266 mono_debugger_agent_single_step_event (void *sigctx)
5268 /* Resume to process_single_step through the signal context */
5270 // FIXME: Since step out/over is implemented using step in, the step in case should
5271 // be as fast as possible. Move the relevant code from process_single_step_inner ()
5274 if (is_debugger_thread ()) {
5276 * This could happen despite our best effors when the runtime calls
5277 * assembly/type resolve hooks.
5278 * FIXME: Breakpoints too.
5282 mono_sigctx_to_monoctx (sigctx, &ctx);
5283 mono_arch_skip_single_step (&ctx);
5284 mono_monoctx_to_sigctx (&ctx, sigctx);
5288 resume_from_signal_handler (sigctx, process_single_step);
5292 debugger_agent_single_step_from_context (MonoContext *ctx)
5294 DebuggerTlsData *tls;
5295 MonoThreadUnwindState orig_restore_state;
5297 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5298 /* Fastpath during invokes, see in process_suspend () */
5299 if (tls && suspend_count && suspend_count - tls->resume_count == 0)
5302 if (is_debugger_thread ())
5307 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
5308 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5309 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5310 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5312 process_single_step_inner (tls, FALSE);
5314 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5315 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5319 debugger_agent_breakpoint_from_context (MonoContext *ctx)
5321 DebuggerTlsData *tls;
5322 MonoThreadUnwindState orig_restore_state;
5325 if (is_debugger_thread ())
5328 orig_ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
5329 MONO_CONTEXT_SET_IP (ctx, orig_ip - 1);
5331 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5333 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5334 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5335 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5337 process_breakpoint (tls, FALSE);
5339 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5340 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5341 if (MONO_CONTEXT_GET_IP (ctx) == orig_ip - 1)
5342 MONO_CONTEXT_SET_IP (ctx, orig_ip);
5346 * start_single_stepping:
5348 * Turn on single stepping. Can be called multiple times, for example,
5349 * by a single step event request + a suspend.
5352 start_single_stepping (void)
5354 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5355 int val = InterlockedIncrement (&ss_count);
5358 mono_arch_start_single_stepping ();
5359 mono_interp_start_single_stepping ();
5362 g_assert_not_reached ();
5367 stop_single_stepping (void)
5369 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5370 int val = InterlockedDecrement (&ss_count);
5373 mono_arch_stop_single_stepping ();
5374 mono_interp_stop_single_stepping ();
5377 g_assert_not_reached ();
5384 * Stop the single stepping operation given by SS_REQ.
5387 ss_stop (SingleStepReq *ss_req)
5392 for (l = ss_req->bps; l; l = l->next) {
5393 clear_breakpoint ((MonoBreakpoint *)l->data);
5395 g_slist_free (ss_req->bps);
5399 ss_req->async_id = 0;
5400 ss_req->async_stepout_method = NULL;
5401 if (ss_req->global) {
5402 stop_single_stepping ();
5403 ss_req->global = FALSE;
5410 * Reject breakpoint if it is a duplicate of one already in list or hash table.
5413 ss_bp_is_unique (GSList *bps, GHashTable *ss_req_bp_cache, MonoMethod *method, guint32 il_offset)
5415 if (ss_req_bp_cache) {
5416 MonoBreakpoint dummy = {method, il_offset, NULL, NULL};
5417 return !g_hash_table_lookup (ss_req_bp_cache, &dummy);
5419 for (GSList *l = bps; l; l = l->next) {
5420 MonoBreakpoint *bp = (MonoBreakpoint *)l->data;
5421 if (bp->method == method && bp->il_offset == il_offset)
5430 * GHashTable equality for a MonoBreakpoint (only care about method and il_offset fields)
5433 ss_bp_eq (gconstpointer ka, gconstpointer kb)
5435 const MonoBreakpoint *s1 = (const MonoBreakpoint *)ka;
5436 const MonoBreakpoint *s2 = (const MonoBreakpoint *)kb;
5437 return (s1->method == s2->method && s1->il_offset == s2->il_offset) ? 1 : 0;
5443 * GHashTable hash for a MonoBreakpoint (only care about method and il_offset fields)
5446 ss_bp_hash (gconstpointer data)
5448 const MonoBreakpoint *s = (const MonoBreakpoint *)data;
5449 guint hash = (guint) (uintptr_t) s->method;
5450 hash ^= ((guint)s->il_offset) << 16; // Assume low bits are more interesting
5451 hash ^= ((guint)s->il_offset) >> 16;
5455 #define MAX_LINEAR_SCAN_BPS 7
5460 * Create a new breakpoint and add it to a step request.
5461 * Will adjust the bp count and cache used by ss_start.
5464 ss_bp_add_one (SingleStepReq *ss_req, int *ss_req_bp_count, GHashTable **ss_req_bp_cache,
5465 MonoMethod *method, guint32 il_offset)
5467 // This list is getting too long, switch to using the hash table
5468 if (!*ss_req_bp_cache && *ss_req_bp_count > MAX_LINEAR_SCAN_BPS) {
5469 *ss_req_bp_cache = g_hash_table_new (ss_bp_hash, ss_bp_eq);
5470 for (GSList *l = ss_req->bps; l; l = l->next)
5471 g_hash_table_insert (*ss_req_bp_cache, l->data, l->data);
5474 if (ss_bp_is_unique (ss_req->bps, *ss_req_bp_cache, method, il_offset)) {
5475 // Create and add breakpoint
5476 MonoBreakpoint *bp = set_breakpoint (method, il_offset, ss_req->req, NULL);
5477 ss_req->bps = g_slist_append (ss_req->bps, bp);
5478 if (*ss_req_bp_cache)
5479 g_hash_table_insert (*ss_req_bp_cache, bp, bp);
5480 (*ss_req_bp_count)++;
5482 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);
5487 is_last_non_empty (SeqPoint* sp, MonoSeqPointInfo *info)
5491 SeqPoint* next = g_new (SeqPoint, sp->next_len);
5492 mono_seq_point_init_next (info, *sp, next);
5493 for (int i = 0; i < sp->next_len; i++) {
5494 if (next [i].flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) {
5495 if (!is_last_non_empty (&next [i], info)) {
5511 * Start the single stepping operation given by SS_REQ from the sequence point SP.
5512 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
5513 * belong to the same thread as CTX.
5514 * If FRAMES is not-null, use that instead of tls->frames for placing breakpoints etc.
5517 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint* sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls,
5518 gboolean step_to_catch, StackFrame **frames, int nframes)
5520 int i, j, frame_index;
5521 SeqPoint *next_sp, *parent_sp = NULL;
5522 SeqPoint local_sp, local_parent_sp;
5524 MonoSeqPointInfo *parent_info;
5525 MonoMethod *parent_sp_method = NULL;
5526 gboolean enable_global = FALSE;
5528 // When 8 or more entries are in bps, we build a hash table to serve as a set of breakpoints.
5529 // Recreating this on each pass is a little wasteful but at least keeps behavior linear.
5530 int ss_req_bp_count = g_slist_length (ss_req->bps);
5531 GHashTable *ss_req_bp_cache = NULL;
5533 /* Stop the previous operation */
5537 * Implement single stepping using breakpoints if possible.
5539 if (step_to_catch) {
5540 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, sp->il_offset);
5544 if (ctx && !frames) {
5545 /* Need parent frames */
5546 if (!tls->context.valid)
5547 mono_thread_state_init_from_monoctx (&tls->context, ctx);
5548 compute_frame_info (tls->thread, tls);
5549 frames = tls->frames;
5550 nframes = tls->frame_count;
5553 MonoDebugMethodAsyncInfo* asyncMethod = mono_debug_lookup_method_async_debug_info (method);
5555 /* Need to stop in catch clauses as well */
5556 for (i = ss_req->depth == STEP_DEPTH_OUT ? 1 : 0; i < nframes; ++i) {
5557 StackFrame *frame = frames [i];
5560 MonoJitInfo *jinfo = frame->ji;
5561 for (j = 0; j < jinfo->num_clauses; ++j) {
5562 // In case of async method we don't want to place breakpoint on last catch handler(which state machine added for whole method)
5563 if (asyncMethod && asyncMethod->num_awaits && i == 0 && j + 1 == jinfo->num_clauses)
5565 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5567 if (mono_find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL, &local_sp))
5568 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, frame->method, local_sp.il_offset);
5573 if (asyncMethod && asyncMethod->num_awaits && nframes && ensure_jit (frames [0])) {
5574 //asyncMethod has value and num_awaits > 0, this means we are inside async method with awaits
5576 // Check if we hit yield_offset during normal stepping, because if we did...
5577 // Go into special async stepping mode which places breakpoint on resumeOffset
5578 // of this await call and sets async_id so we can distinguish it from parallel executions
5579 for (i = 0; i < asyncMethod->num_awaits; i++) {
5580 if (sp->il_offset == asyncMethod->yield_offsets [i]) {
5581 ss_req->async_id = get_this_async_id (frames [0]);
5582 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, asyncMethod->resume_offsets [i]);
5583 if (ss_req_bp_cache)
5584 g_hash_table_destroy (ss_req_bp_cache);
5585 mono_debug_free_method_async_debug_info (asyncMethod);
5589 //If we are at end of async method and doing step-in or step-over...
5590 //Switch to step-out, so whole NotifyDebuggerOfWaitCompletion magic happens...
5591 if (is_last_non_empty (sp, info)) {
5592 ss_req->depth = STEP_DEPTH_OUT;//setting depth to step-out is important, don't inline IF, because code later depends on this
5594 if (ss_req->depth == STEP_DEPTH_OUT) {
5595 set_set_notification_for_wait_completion_flag (frames [0]);
5596 ss_req->async_id = get_this_async_id (frames [0]);
5597 ss_req->async_stepout_method = get_notify_debugger_of_wait_completion_method ();
5598 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, ss_req->async_stepout_method, 0);
5599 if (ss_req_bp_cache)
5600 g_hash_table_destroy (ss_req_bp_cache);
5601 mono_debug_free_method_async_debug_info (asyncMethod);
5607 mono_debug_free_method_async_debug_info (asyncMethod);
5610 * Find the first sequence point in the current or in a previous frame which
5611 * is not the last in its method.
5613 if (ss_req->depth == STEP_DEPTH_OUT) {
5614 /* Ignore seq points in current method */
5615 while (frame_index < nframes) {
5616 StackFrame *frame = frames [frame_index];
5618 method = frame->method;
5619 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5620 sp = (found_sp)? &local_sp : NULL;
5622 if (sp && sp->next_len != 0)
5625 // There could be method calls before the next seq point in the caller when using nested calls
5626 //enable_global = TRUE;
5628 if (sp && sp->next_len == 0) {
5630 while (frame_index < nframes) {
5631 StackFrame *frame = frames [frame_index];
5633 method = frame->method;
5634 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5635 sp = (found_sp)? &local_sp : NULL;
5636 if (sp && sp->next_len != 0)
5642 /* Have to put a breakpoint into a parent frame since the seq points might not cover all control flow out of the method */
5643 while (frame_index < nframes) {
5644 StackFrame *frame = frames [frame_index];
5646 parent_sp_method = frame->method;
5647 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &parent_info, &local_parent_sp);
5648 parent_sp = found_sp ? &local_parent_sp : NULL;
5649 if (found_sp && parent_sp->next_len != 0)
5657 if (sp && sp->next_len > 0) {
5658 SeqPoint* next = g_new(SeqPoint, sp->next_len);
5660 mono_seq_point_init_next (info, *sp, next);
5661 for (i = 0; i < sp->next_len; i++) {
5664 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, next_sp->il_offset);
5670 SeqPoint* next = g_new(SeqPoint, parent_sp->next_len);
5672 mono_seq_point_init_next (parent_info, *parent_sp, next);
5673 for (i = 0; i < parent_sp->next_len; i++) {
5676 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, parent_sp_method, next_sp->il_offset);
5681 if (ss_req->nframes == 0)
5682 ss_req->nframes = nframes;
5684 if ((ss_req->depth == STEP_DEPTH_OVER) && (!sp && !parent_sp)) {
5685 DEBUG_PRINTF (1, "[dbg] No parent frame for step over, transition to step into.\n");
5687 * This is needed since if we leave managed code, and later return to it, step over
5688 * is not going to stop.
5689 * This approach is a bit ugly, since we change the step depth, but it only affects
5690 * clients who reuse the same step request, and only in this special case.
5692 ss_req->depth = STEP_DEPTH_INTO;
5695 if (ss_req->depth == STEP_DEPTH_INTO) {
5696 /* Enable global stepping so we stop at method entry too */
5697 enable_global = TRUE;
5701 * The ctx/frame info computed above will become invalid when we continue.
5703 tls->context.valid = FALSE;
5704 tls->async_state.valid = FALSE;
5705 invalidate_frames (tls);
5708 if (enable_global) {
5709 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5710 ss_req->global = TRUE;
5711 start_single_stepping ();
5712 } else if (!ss_req->bps) {
5713 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5714 ss_req->global = TRUE;
5715 start_single_stepping ();
5717 ss_req->global = FALSE;
5720 if (ss_req_bp_cache)
5721 g_hash_table_destroy (ss_req_bp_cache);
5725 * Start single stepping of thread THREAD
5728 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req)
5730 DebuggerTlsData *tls;
5731 MonoSeqPointInfo *info = NULL;
5732 SeqPoint *sp = NULL;
5735 MonoMethod *method = NULL;
5736 MonoDebugMethodInfo *minfo;
5737 gboolean step_to_catch = FALSE;
5738 gboolean set_ip = FALSE;
5739 StackFrame **frames = NULL;
5742 if (suspend_count == 0)
5743 return ERR_NOT_SUSPENDED;
5745 wait_for_suspend ();
5747 // FIXME: Multiple requests
5749 DEBUG_PRINTF (0, "Received a single step request while the previous one was still active.\n");
5750 return ERR_NOT_IMPLEMENTED;
5753 DEBUG_PRINTF (1, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth));
5755 ss_req = g_new0 (SingleStepReq, 1);
5757 ss_req->thread = thread;
5758 ss_req->size = size;
5759 ss_req->depth = depth;
5760 ss_req->filter = filter;
5763 for (int i = 0; i < req->nmodifiers; i++) {
5764 if (req->modifiers[i].kind == MOD_KIND_ASSEMBLY_ONLY) {
5765 ss_req->user_assemblies = req->modifiers[i].data.assemblies;
5770 mono_loader_lock ();
5771 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5772 mono_loader_unlock ();
5774 if (!tls->context.valid) {
5775 DEBUG_PRINTF (1, "Received a single step request on a thread with no managed frames.");
5776 return ERR_INVALID_ARGUMENT;
5779 if (tls->restore_state.valid && MONO_CONTEXT_GET_IP (&tls->context.ctx) != MONO_CONTEXT_GET_IP (&tls->restore_state.ctx)) {
5781 * Need to start single stepping from restore_state and not from the current state
5784 frames = compute_frame_info_from (thread, tls, &tls->restore_state, &nframes);
5787 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5789 if (tls->catch_state.valid) {
5791 StackFrameInfo frame;
5792 MonoContext new_ctx;
5793 MonoLMF *lmf = NULL;
5796 * We are stopped at a throw site. Stepping should go to the catch site.
5799 /* Find the the jit info for the catch context */
5800 res = mono_find_jit_info_ext (
5801 (MonoDomain *)tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN],
5802 (MonoJitTlsData *)((MonoThreadInfo*)thread->thread_info)->jit_data,
5803 NULL, &tls->catch_state.ctx, &new_ctx, NULL, &lmf, NULL, &frame);
5805 g_assert (frame.type == FRAME_TYPE_MANAGED);
5808 * Find the seq point corresponding to the landing site ip, which is the first seq
5811 found_sp = mono_find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info, &local_sp);
5812 sp = (found_sp)? &local_sp : NULL;
5814 no_seq_points_found (frame.method, frame.native_offset);
5817 method = frame.method;
5819 step_to_catch = TRUE;
5820 /* This make sure the seq point is not skipped by process_single_step () */
5821 ss_req->last_sp = NULL;
5824 if (!step_to_catch) {
5825 StackFrame *frame = NULL;
5828 if (frames && nframes)
5831 compute_frame_info (thread, tls);
5833 if (tls->frame_count)
5834 frame = tls->frames [0];
5837 if (ss_req->size == STEP_SIZE_LINE) {
5839 ss_req->last_method = frame->method;
5840 ss_req->last_line = -1;
5842 minfo = mono_debug_lookup_method (frame->method);
5843 if (minfo && frame->il_offset != -1) {
5844 MonoDebugSourceLocation *loc = mono_debug_method_lookup_location (minfo, frame->il_offset);
5847 ss_req->last_line = loc->row;
5855 if (!method && frame->il_offset != -1) {
5856 /* FIXME: Sort the table and use a binary search */
5857 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5858 sp = (found_sp)? &local_sp : NULL;
5860 no_seq_points_found (frame->method, frame->native_offset);
5862 method = frame->method;
5867 ss_req->start_method = method;
5869 ss_start (ss_req, method, sp, info, set_ip ? &tls->restore_state.ctx : &tls->context.ctx, tls, step_to_catch, frames, nframes);
5872 free_frames (frames, nframes);
5878 ss_destroy (SingleStepReq *req)
5881 g_assert (ss_req == req);
5890 ss_clear_for_assembly (SingleStepReq *req, MonoAssembly *assembly)
5893 gboolean found = TRUE;
5897 for (l = ss_req->bps; l; l = l->next) {
5898 if (breakpoint_matches_assembly ((MonoBreakpoint *)l->data, assembly)) {
5899 clear_breakpoint ((MonoBreakpoint *)l->data);
5900 ss_req->bps = g_slist_delete_link (ss_req->bps, l);
5909 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5912 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5919 if (!agent_config.enabled)
5922 mono_loader_lock ();
5923 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5924 mono_loader_unlock ();
5929 ei.category = mono_string_to_utf8_checked (category, &error);
5930 mono_error_cleanup (&error);
5934 ei.message = mono_string_to_utf8_checked (message, &error);
5935 mono_error_cleanup (&error);
5938 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5940 g_free (ei.category);
5941 g_free (ei.message);
5945 mono_debugger_agent_debug_log_is_enabled (void)
5947 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5948 return agent_config.enabled;
5951 #if defined(PLATFORM_ANDROID) || defined(TARGET_ANDROID)
5953 mono_debugger_agent_unhandled_exception (MonoException *exc)
5962 memset (&ei, 0, sizeof (EventInfo));
5963 ei.exc = (MonoObject*)exc;
5965 mono_loader_lock ();
5966 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5967 mono_loader_unlock ();
5969 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5974 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5975 MonoContext *catch_ctx)
5977 int i, j, suspend_policy;
5979 MonoJitInfo *ji, *catch_ji;
5981 DebuggerTlsData *tls = NULL;
5983 if (thread_to_tls != NULL) {
5984 MonoInternalThread *thread = mono_thread_internal_current ();
5986 mono_loader_lock ();
5987 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5988 mono_loader_unlock ();
5990 if (tls && tls->abort_requested)
5992 if (tls && tls->disable_breakpoints)
5996 memset (&ei, 0, sizeof (EventInfo));
5998 /* Just-In-Time debugging */
6000 if (agent_config.onuncaught && !inited) {
6001 finish_agent_init (FALSE);
6004 * Send an unsolicited EXCEPTION event with a dummy request id.
6006 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
6007 ei.exc = (MonoObject*)exc;
6008 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
6011 } else if (agent_config.onthrow && !inited) {
6013 gboolean found = FALSE;
6015 for (l = agent_config.onthrow; l; l = l->next) {
6016 char *ex_type = (char *)l->data;
6017 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
6019 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
6026 finish_agent_init (FALSE);
6029 * Send an unsolicited EXCEPTION event with a dummy request id.
6031 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
6032 ei.exc = (MonoObject*)exc;
6033 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
6041 ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (throw_ctx), NULL);
6043 catch_ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (catch_ctx), NULL);
6047 ei.exc = (MonoObject*)exc;
6048 ei.caught = catch_ctx != NULL;
6050 mono_loader_lock ();
6052 /* Treat exceptions which are caught in non-user code as unhandled */
6053 for (i = 0; i < event_requests->len; ++i) {
6054 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6055 if (req->event_kind != EVENT_KIND_EXCEPTION)
6058 for (j = 0; j < req->nmodifiers; ++j) {
6059 Modifier *mod = &req->modifiers [j];
6061 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
6063 gboolean found = FALSE;
6064 MonoAssembly **assemblies = mod->data.assemblies;
6067 for (k = 0; assemblies [k]; ++k)
6068 if (assemblies [k] == jinfo_get_method (catch_ji)->klass->image->assembly)
6077 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
6078 mono_loader_unlock ();
6080 if (tls && ei.caught && catch_ctx) {
6081 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
6082 tls->catch_state.ctx = *catch_ctx;
6083 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
6084 tls->catch_state.valid = TRUE;
6087 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
6090 tls->catch_state.valid = FALSE;
6094 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
6096 DebuggerTlsData *tls;
6101 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
6106 * We're about to invoke an exception filter during the first pass of exception handling.
6108 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
6109 * 'orig_ctx' is the context where the exception has been thrown.
6112 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
6114 * If we're stopped in Filter(), normal stack unwinding would first unwind to
6115 * the call site (line 37) and then continue to Main(), but it would never
6116 * include the throw site (line 32).
6118 * Since exception filters are invoked during the first pass of exception handling,
6119 * the stack frames of the throw site are still intact, so we should include them
6122 * We do this here by saving the context of the throw site in 'tls->filter_state'.
6124 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
6125 * but report the location of the 'throw' to the user.
6129 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
6133 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
6135 DebuggerTlsData *tls;
6140 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
6144 tls->filter_state.valid = FALSE;
6148 * buffer_add_value_full:
6150 * Add the encoding of the value at ADDR described by T to the buffer.
6151 * AS_VTYPE determines whenever to treat primitive types as primitive types or
6155 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
6156 gboolean as_vtype, GHashTable *parent_vtypes)
6159 gboolean boxed_vtype = FALSE;
6162 if (!(*(void**)addr)) {
6163 /* This can happen with compiler generated locals */
6164 //printf ("%s\n", mono_type_full_name (t));
6165 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
6168 g_assert (*(void**)addr);
6169 addr = *(void**)addr;
6174 case MONO_TYPE_BOOLEAN:
6177 case MONO_TYPE_CHAR:
6197 case MONO_TYPE_VOID:
6198 buffer_add_byte (buf, t->type);
6200 case MONO_TYPE_BOOLEAN:
6203 buffer_add_byte (buf, t->type);
6204 buffer_add_int (buf, *(gint8*)addr);
6206 case MONO_TYPE_CHAR:
6209 buffer_add_byte (buf, t->type);
6210 buffer_add_int (buf, *(gint16*)addr);
6215 buffer_add_byte (buf, t->type);
6216 buffer_add_int (buf, *(gint32*)addr);
6221 buffer_add_byte (buf, t->type);
6222 buffer_add_long (buf, *(gint64*)addr);
6226 /* Treat it as a vtype */
6228 case MONO_TYPE_PTR: {
6229 gssize val = *(gssize*)addr;
6231 buffer_add_byte (buf, t->type);
6232 buffer_add_long (buf, val);
6236 case MONO_TYPE_STRING:
6237 case MONO_TYPE_SZARRAY:
6238 case MONO_TYPE_OBJECT:
6239 case MONO_TYPE_CLASS:
6240 case MONO_TYPE_ARRAY:
6241 obj = *(MonoObject**)addr;
6244 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
6246 if (obj->vtable->klass->valuetype) {
6247 t = &obj->vtable->klass->byval_arg;
6248 addr = mono_object_unbox (obj);
6251 } else if (obj->vtable->klass->rank) {
6252 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
6253 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
6254 buffer_add_byte (buf, MONO_TYPE_CLASS);
6256 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
6258 buffer_add_objid (buf, obj);
6262 case MONO_TYPE_VALUETYPE:
6263 case MONO_TYPE_TYPEDBYREF: {
6267 MonoClass *klass = mono_class_from_mono_type (t);
6272 * Handle boxed vtypes recursively referencing themselves using fields.
6275 parent_vtypes = g_hash_table_new (NULL, NULL);
6276 vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
6278 if (CHECK_PROTOCOL_VERSION (2, 33)) {
6279 buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
6280 buffer_add_int (buf, vtype_index - 1);
6282 /* The client can't handle PARENT_VTYPE */
6283 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
6287 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
6291 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
6292 buffer_add_byte (buf, klass->enumtype);
6293 buffer_add_typeid (buf, domain, klass);
6297 while ((f = mono_class_get_fields (klass, &iter))) {
6298 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6300 if (mono_field_is_deleted (f))
6304 buffer_add_int (buf, nfields);
6307 while ((f = mono_class_get_fields (klass, &iter))) {
6308 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6310 if (mono_field_is_deleted (f))
6312 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE, parent_vtypes);
6316 g_hash_table_remove (parent_vtypes, addr);
6317 if (g_hash_table_size (parent_vtypes) == 0) {
6318 g_hash_table_destroy (parent_vtypes);
6319 parent_vtypes = NULL;
6324 case MONO_TYPE_GENERICINST:
6325 if (mono_type_generic_inst_is_valuetype (t)) {
6337 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
6339 buffer_add_value_full (buf, t, addr, domain, FALSE, NULL);
6343 obj_is_of_type (MonoObject *obj, MonoType *t)
6345 MonoClass *klass = obj->vtable->klass;
6346 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
6347 if (mono_class_is_transparent_proxy (klass)) {
6348 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
6349 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
6359 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
6362 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6368 gpointer iter = NULL;
6372 is_enum = decode_byte (buf, &buf, limit);
6373 /* Enums are sent as a normal vtype */
6375 return ERR_NOT_IMPLEMENTED;
6376 klass = decode_typeid (buf, &buf, limit, &d, &err);
6377 if (err != ERR_NONE)
6380 if (t && klass != mono_class_from_mono_type (t)) {
6381 char *name = mono_type_full_name (t);
6382 char *name2 = mono_type_full_name (&klass->byval_arg);
6383 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got %s.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, name2);
6386 return ERR_INVALID_ARGUMENT;
6389 nfields = decode_int (buf, &buf, limit);
6390 while ((f = mono_class_get_fields (klass, &iter))) {
6391 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6393 if (mono_field_is_deleted (f))
6395 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
6396 if (err != ERR_NONE)
6400 g_assert (nfields == 0);
6408 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6412 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
6413 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
6414 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
6415 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
6416 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE) &&
6417 !(t->type == MONO_TYPE_VALUETYPE && type == MONO_TYPE_OBJECT)) {
6418 char *name = mono_type_full_name (t);
6419 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
6421 return ERR_INVALID_ARGUMENT;
6425 case MONO_TYPE_BOOLEAN:
6426 *(guint8*)addr = decode_int (buf, &buf, limit);
6428 case MONO_TYPE_CHAR:
6429 *(gunichar2*)addr = decode_int (buf, &buf, limit);
6432 *(gint8*)addr = decode_int (buf, &buf, limit);
6435 *(guint8*)addr = decode_int (buf, &buf, limit);
6438 *(gint16*)addr = decode_int (buf, &buf, limit);
6441 *(guint16*)addr = decode_int (buf, &buf, limit);
6444 *(gint32*)addr = decode_int (buf, &buf, limit);
6447 *(guint32*)addr = decode_int (buf, &buf, limit);
6450 *(gint64*)addr = decode_long (buf, &buf, limit);
6453 *(guint64*)addr = decode_long (buf, &buf, limit);
6456 *(guint32*)addr = decode_int (buf, &buf, limit);
6459 *(guint64*)addr = decode_long (buf, &buf, limit);
6462 /* We send these as I8, so we get them back as such */
6463 g_assert (type == MONO_TYPE_I8);
6464 *(gssize*)addr = decode_long (buf, &buf, limit);
6466 case MONO_TYPE_GENERICINST:
6467 if (MONO_TYPE_ISSTRUCT (t)) {
6468 /* The client sends these as a valuetype */
6476 /* We send these as vtypes, so we get them back as such */
6477 g_assert (type == MONO_TYPE_VALUETYPE);
6480 case MONO_TYPE_VALUETYPE:
6481 if (type == MONO_TYPE_OBJECT) {
6483 int objid = decode_objid (buf, &buf, limit);
6487 err = get_object (objid, (MonoObject**)&obj);
6488 if (err != ERR_NONE)
6491 return ERR_INVALID_ARGUMENT;
6492 if (obj->vtable->klass != mono_class_from_mono_type (t)) {
6493 DEBUG_PRINTF (1, "Expected type '%s', got object '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6494 return ERR_INVALID_ARGUMENT;
6496 memcpy (addr, mono_object_unbox (obj), mono_class_value_size (obj->vtable->klass, NULL));
6498 err = decode_vtype (t, domain, addr, buf, &buf, limit);
6499 if (err != ERR_NONE)
6505 if (MONO_TYPE_IS_REFERENCE (t)) {
6506 if (type == MONO_TYPE_OBJECT) {
6507 int objid = decode_objid (buf, &buf, limit);
6511 err = get_object (objid, (MonoObject**)&obj);
6512 if (err != ERR_NONE)
6516 if (!obj_is_of_type (obj, t)) {
6517 DEBUG_PRINTF (1, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6518 return ERR_INVALID_ARGUMENT;
6521 if (obj && obj->vtable->domain != domain)
6522 return ERR_INVALID_ARGUMENT;
6524 mono_gc_wbarrier_generic_store (addr, obj);
6525 } else if (type == VALUE_TYPE_ID_NULL) {
6526 *(MonoObject**)addr = NULL;
6527 } else if (type == MONO_TYPE_VALUETYPE) {
6536 /* This can happen when round-tripping boxed vtypes */
6538 * Obtain vtype class.
6539 * Same as the beginning of the handle_vtype case above.
6542 is_enum = decode_byte (buf, &buf, limit);
6544 return ERR_NOT_IMPLEMENTED;
6545 klass = decode_typeid (buf, &buf, limit, &d, &err);
6546 if (err != ERR_NONE)
6549 /* Decode the vtype into a temporary buffer, then box it. */
6550 vtype_buf_size = mono_class_value_size (klass, NULL);
6551 vtype_buf = (guint8 *)g_malloc0 (vtype_buf_size);
6552 g_assert (vtype_buf);
6555 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
6556 if (err != ERR_NONE) {
6560 *(MonoObject**)addr = mono_value_box_checked (d, klass, vtype_buf, &error);
6561 mono_error_cleanup (&error);
6564 char *name = mono_type_full_name (t);
6565 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
6567 return ERR_INVALID_ARGUMENT;
6581 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6585 int type = decode_byte (buf, &buf, limit);
6587 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
6588 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
6589 guint8 *nullable_buf;
6592 * First try decoding it as a Nullable`1
6594 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6595 if (err == ERR_NONE)
6599 * Then try decoding as a primitive value or null.
6601 if (targ->type == type) {
6602 nullable_buf = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
6603 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
6604 if (err != ERR_NONE) {
6605 g_free (nullable_buf);
6608 MonoObject *boxed = mono_value_box_checked (domain, mono_class_from_mono_type (targ), nullable_buf, &error);
6609 if (!is_ok (&error)) {
6610 mono_error_cleanup (&error);
6611 return ERR_INVALID_OBJECT;
6613 mono_nullable_init (addr, boxed, mono_class_from_mono_type (t));
6614 g_free (nullable_buf);
6617 } else if (type == VALUE_TYPE_ID_NULL) {
6618 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
6624 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6628 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
6632 guint8 *addr, *gaddr;
6635 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6636 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6639 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
6640 reg_val = mono_arch_context_get_int_reg (ctx, reg);
6642 buffer_add_value_full (buf, t, ®_val, domain, as_vtype, NULL);
6644 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6645 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6646 addr += (gint32)var->offset;
6648 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6650 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6652 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6655 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6656 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
6657 /* Same as regoffset, but with an indirection */
6658 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6659 addr += (gint32)var->offset;
6661 gaddr = (guint8 *)*(gpointer*)addr;
6663 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL);
6665 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
6666 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
6667 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
6668 MonoGSharedVtMethodRuntimeInfo *info;
6674 g_assert (info_var);
6675 g_assert (locals_var);
6677 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6678 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6679 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6680 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6681 addr += (gint32)info_var->offset;
6682 info = (MonoGSharedVtMethodRuntimeInfo *)*(gpointer*)addr;
6683 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6684 info = (MonoGSharedVtMethodRuntimeInfo *)mono_arch_context_get_int_reg (ctx, reg);
6686 g_assert_not_reached ();
6690 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6691 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6692 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6693 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6694 addr += (gint32)locals_var->offset;
6695 locals = (guint8 *)*(gpointer*)addr;
6696 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6697 locals = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6699 g_assert_not_reached ();
6703 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6705 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6710 g_assert_not_reached ();
6715 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
6719 guint8 *addr, *gaddr;
6721 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6722 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6724 if (MONO_TYPE_IS_REFERENCE (t))
6725 size = sizeof (gpointer);
6727 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6730 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6731 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6733 gboolean is_signed = FALSE;
6736 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6739 // FIXME: Write barriers
6740 mono_gc_memmove_atomic (addr, val, size);
6745 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6750 v = is_signed ? *(gint8*)val : *(guint8*)val;
6753 v = is_signed ? *(gint16*)val : *(guint16*)val;
6756 v = is_signed ? *(gint32*)val : *(guint32*)val;
6759 v = is_signed ? *(gint64*)val : *(guint64*)val;
6762 g_assert_not_reached ();
6765 /* Set value on the stack or in the return ctx */
6766 if (reg_locations [reg]) {
6767 /* Saved on the stack */
6768 DEBUG_PRINTF (1, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v);
6769 *(reg_locations [reg]) = v;
6772 DEBUG_PRINTF (1, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v);
6773 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6776 // FIXME: Move these to mono-context.h/c.
6777 mono_arch_context_set_int_reg (ctx, reg, v);
6779 // FIXME: Can't set registers, so we disable linears
6784 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6785 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6786 addr += (gint32)var->offset;
6788 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6791 addr = *(guint8**)addr;
6797 // FIXME: Write barriers
6798 mono_gc_memmove_atomic (addr, val, size);
6800 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6801 /* Same as regoffset, but with an indirection */
6802 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6803 addr += (gint32)var->offset;
6805 gaddr = (guint8 *)*(gpointer*)addr;
6807 // FIXME: Write barriers
6808 mono_gc_memmove_atomic (gaddr, val, size);
6810 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6814 g_assert_not_reached ();
6819 set_interp_var (MonoType *t, gpointer addr, guint8 *val_buf)
6824 addr = *(gpointer*)addr;
6828 if (MONO_TYPE_IS_REFERENCE (t))
6829 size = sizeof (gpointer);
6831 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6833 memcpy (addr, val_buf, size);
6837 clear_event_request (int req_id, int etype)
6841 mono_loader_lock ();
6842 for (i = 0; i < event_requests->len; ++i) {
6843 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6845 if (req->id == req_id && req->event_kind == etype) {
6846 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6847 clear_breakpoint ((MonoBreakpoint *)req->info);
6848 if (req->event_kind == EVENT_KIND_STEP)
6849 ss_destroy ((SingleStepReq *)req->info);
6850 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6851 clear_breakpoint ((MonoBreakpoint *)req->info);
6852 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6853 clear_breakpoint ((MonoBreakpoint *)req->info);
6854 g_ptr_array_remove_index_fast (event_requests, i);
6859 mono_loader_unlock ();
6863 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
6867 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6868 m->kind = MOD_KIND_NONE;
6869 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6870 int count = 0, match_count = 0, pos;
6871 MonoAssembly **newassemblies;
6873 for (i = 0; m->data.assemblies [i]; ++i) {
6875 if (m->data.assemblies [i] == assembly)
6880 // +1 because we don't know length and we use last element to check for end
6881 newassemblies = g_new0 (MonoAssembly*, count - match_count + 1);
6884 for (i = 0; i < count; ++i)
6885 if (m->data.assemblies [i] != assembly)
6886 newassemblies [pos ++] = m->data.assemblies [i];
6887 g_assert (pos == count - match_count);
6888 g_free (m->data.assemblies);
6889 m->data.assemblies = newassemblies;
6895 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
6899 for (i = 0; i < req->nmodifiers; ++i) {
6900 Modifier *m = &req->modifiers [i];
6902 clear_assembly_from_modifier (req, m, assembly);
6907 * clear_event_requests_for_assembly:
6909 * Clear all events requests which reference ASSEMBLY.
6912 clear_event_requests_for_assembly (MonoAssembly *assembly)
6917 mono_loader_lock ();
6921 for (i = 0; i < event_requests->len; ++i) {
6922 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6924 clear_assembly_from_modifiers (req, assembly);
6926 if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly ((MonoBreakpoint *)req->info, assembly)) {
6927 clear_event_request (req->id, req->event_kind);
6932 if (req->event_kind == EVENT_KIND_STEP)
6933 ss_clear_for_assembly ((SingleStepReq *)req->info, assembly);
6936 mono_loader_unlock ();
6940 * type_comes_from_assembly:
6942 * GHRFunc that returns TRUE if klass comes from assembly
6945 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6947 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6951 * clear_types_for_assembly:
6953 * Clears types from loaded_classes for a given assembly
6956 clear_types_for_assembly (MonoAssembly *assembly)
6958 MonoDomain *domain = mono_domain_get ();
6959 AgentDomainInfo *info = NULL;
6961 if (!domain || !domain_jit_info (domain))
6962 /* Can happen during shutdown */
6965 info = get_agent_domain_info (domain);
6967 mono_loader_lock ();
6968 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6969 mono_loader_unlock ();
6973 add_thread (gpointer key, gpointer value, gpointer user_data)
6975 MonoInternalThread *thread = (MonoInternalThread *)value;
6976 Buffer *buf = (Buffer *)user_data;
6978 buffer_add_objid (buf, (MonoObject*)thread);
6982 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6985 guint8 *end = invoke->endp;
6989 MonoMethodSignature *sig;
6992 MonoObject *this_arg, *res, *exc;
6995 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6998 MonoStopwatch watch;
7000 if (invoke->method) {
7002 * Invoke this method directly, currently only Environment.Exit () is supported.
7005 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>");
7007 mono_runtime_try_invoke (invoke->method, NULL, invoke->args, &exc, &error);
7008 mono_error_assert_ok (&error);
7010 g_assert_not_reached ();
7013 m = decode_methodid (p, &p, end, &domain, &err);
7014 if (err != ERR_NONE)
7016 sig = mono_method_signature (m);
7018 if (m->klass->valuetype)
7019 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
7021 this_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
7022 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
7023 /* Should be null */
7024 int type = decode_byte (p, &p, end);
7025 if (type != VALUE_TYPE_ID_NULL) {
7026 DEBUG_PRINTF (1, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
7027 return ERR_INVALID_ARGUMENT;
7029 memset (this_buf, 0, mono_class_instance_size (m->klass));
7030 } else if (m->klass->valuetype && !strcmp (m->name, ".ctor")) {
7034 int type = decode_byte (p, &tmp_p, end);
7035 if (type == VALUE_TYPE_ID_NULL) {
7036 memset (this_buf, 0, mono_class_instance_size (m->klass));
7039 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
7040 if (err != ERR_NONE)
7044 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
7045 if (err != ERR_NONE)
7049 if (!m->klass->valuetype)
7050 this_arg = *(MonoObject**)this_buf;
7054 if (MONO_CLASS_IS_INTERFACE (m->klass)) {
7056 DEBUG_PRINTF (1, "[%p] Error: Interface method invoked without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
7057 return ERR_INVALID_ARGUMENT;
7059 m = mono_object_get_virtual_method (this_arg, m);
7060 /* Transform this to the format the rest of the code expects it to be */
7061 if (m->klass->valuetype) {
7062 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
7063 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
7065 } else if ((m->flags & METHOD_ATTRIBUTE_VIRTUAL) && !m->klass->valuetype && invoke->flags & INVOKE_FLAG_VIRTUAL) {
7067 DEBUG_PRINTF (1, "[%p] Error: invoke with INVOKE_FLAG_VIRTUAL flag set without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
7068 return ERR_INVALID_ARGUMENT;
7070 m = mono_object_get_virtual_method (this_arg, m);
7071 if (m->klass->valuetype) {
7072 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
7073 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
7077 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>");
7079 if (this_arg && this_arg->vtable->domain != domain)
7082 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this_arg) {
7083 if (!strcmp (m->name, ".ctor")) {
7084 if (mono_class_is_abstract (m->klass))
7085 return ERR_INVALID_ARGUMENT;
7088 this_arg = mono_object_new_checked (domain, m->klass, &error);
7089 mono_error_assert_ok (&error);
7092 return ERR_INVALID_ARGUMENT;
7096 if (this_arg && !obj_is_of_type (this_arg, &m->klass->byval_arg))
7097 return ERR_INVALID_ARGUMENT;
7099 nargs = decode_int (p, &p, end);
7100 if (nargs != sig->param_count)
7101 return ERR_INVALID_ARGUMENT;
7102 /* Use alloca to get gc tracking */
7103 arg_buf = (guint8 **)g_alloca (nargs * sizeof (gpointer));
7104 memset (arg_buf, 0, nargs * sizeof (gpointer));
7105 args = (gpointer *)g_alloca (nargs * sizeof (gpointer));
7106 for (i = 0; i < nargs; ++i) {
7107 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
7108 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
7109 if (err != ERR_NONE)
7111 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
7114 if (sig->params [i]->byref) {
7115 arg_buf [i] = (guint8 *)g_alloca (sizeof (mgreg_t));
7116 *(gpointer*)arg_buf [i] = args [i];
7117 args [i] = arg_buf [i];
7120 MonoClass *arg_class = mono_class_from_mono_type (sig->params [i]);
7121 arg_buf [i] = (guint8 *)g_alloca (mono_class_instance_size (arg_class));
7122 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
7123 if (err != ERR_NONE)
7125 if (mono_class_is_nullable (arg_class)) {
7126 args [i] = mono_nullable_box (arg_buf [i], arg_class, &error);
7127 mono_error_assert_ok (&error);
7129 args [i] = arg_buf [i];
7137 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
7138 tls->disable_breakpoints = TRUE;
7140 tls->disable_breakpoints = FALSE;
7143 * Add an LMF frame to link the stack frames on the invoke method with our caller.
7145 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
7146 if (invoke->has_ctx) {
7149 lmf_addr = mono_get_lmf_addr ();
7152 memset (&ext, 0, sizeof (ext));
7153 mono_arch_init_lmf_ext (&ext, *lmf_addr);
7155 ext.debugger_invoke = TRUE;
7156 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
7158 mono_set_lmf ((MonoLMF*)&ext);
7162 mono_stopwatch_start (&watch);
7163 res = mono_runtime_try_invoke (m, m->klass->valuetype ? (gpointer) this_buf : (gpointer) this_arg, args, &exc, &error);
7164 if (exc == NULL && !mono_error_ok (&error)) {
7165 exc = (MonoObject*) mono_error_convert_to_exception (&error);
7167 mono_error_cleanup (&error); /* FIXME report error */
7169 mono_stopwatch_stop (&watch);
7170 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));
7172 buffer_add_byte (buf, 0);
7173 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
7175 gboolean out_this = FALSE;
7176 gboolean out_args = FALSE;
7178 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_THIS) && CHECK_PROTOCOL_VERSION (2, 35))
7180 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_ARGS) && CHECK_PROTOCOL_VERSION (2, 35))
7182 buffer_add_byte (buf, 1 + (out_this ? 2 : 0) + (out_args ? 4 : 0));
7183 if (m->string_ctor) {
7184 buffer_add_value (buf, &mono_get_string_class ()->byval_arg, &res, domain);
7185 } else if (sig->ret->type == MONO_TYPE_VOID && !m->string_ctor) {
7186 if (!strcmp (m->name, ".ctor")) {
7187 if (!m->klass->valuetype)
7188 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this_arg, domain);
7190 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
7192 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
7194 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
7195 buffer_add_value (buf, sig->ret, &res, domain);
7196 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
7197 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
7198 MonoClass *k = mono_class_from_mono_type (sig->ret);
7199 guint8 *nullable_buf = (guint8 *)g_alloca (mono_class_value_size (k, NULL));
7201 g_assert (nullable_buf);
7202 mono_nullable_init (nullable_buf, res, k);
7203 buffer_add_value (buf, sig->ret, nullable_buf, domain);
7206 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
7212 /* Return the new value of the receiver after the call */
7213 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
7215 buffer_add_int (buf, nargs);
7216 for (i = 0; i < nargs; ++i) {
7217 if (MONO_TYPE_IS_REFERENCE (sig->params [i]))
7218 buffer_add_value (buf, sig->params [i], &args [i], domain);
7219 else if (sig->params [i]->byref)
7220 /* add_value () does an indirection */
7221 buffer_add_value (buf, sig->params [i], &arg_buf [i], domain);
7223 buffer_add_value (buf, sig->params [i], arg_buf [i], domain);
7228 tls->disable_breakpoints = FALSE;
7230 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
7231 if (invoke->has_ctx)
7232 mono_set_lmf ((MonoLMF *)(((gssize)ext.lmf.previous_lmf) & ~3));
7236 // FIXME: byref arguments
7244 * Invoke the method given by tls->pending_invoke in the current thread.
7247 invoke_method (void)
7249 DebuggerTlsData *tls;
7255 MonoContext restore_ctx;
7258 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
7262 * Store the `InvokeData *' in `tls->invoke' until we're done with
7263 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
7266 mono_loader_lock ();
7268 invoke = tls->pending_invoke;
7270 tls->pending_invoke = NULL;
7272 invoke->last_invoke = tls->invoke;
7273 tls->invoke = invoke;
7275 mono_loader_unlock ();
7277 tls->frames_up_to_date = FALSE;
7283 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
7284 buffer_init (&buf, 128);
7287 /* Fail the other invokes as well */
7289 err = do_invoke_method (tls, &buf, invoke, p, &p);
7292 if (tls->abort_requested) {
7293 if (CHECK_PROTOCOL_VERSION (2, 42))
7294 err = ERR_INVOKE_ABORTED;
7297 /* Start suspending before sending the reply */
7298 if (mindex == invoke->nmethods - 1) {
7299 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
7300 for (i = 0; i < invoke->suspend_count; ++i)
7305 send_reply_packet (id, err, &buf);
7310 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
7312 if (invoke->has_ctx)
7313 save_thread_context (&restore_ctx);
7315 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
7316 g_assert (tls->resume_count);
7317 tls->resume_count -= invoke->suspend_count;
7320 DEBUG_PRINTF (1, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer) (gsize) mono_native_thread_id_get (), err, tls->resume_count);
7323 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
7325 * It is possible that mono_thread_internal_abort () was called
7326 * after the mono_runtime_invoke_checked() already returned, but it doesn't matter
7327 * because we reset the abort here.
7330 mono_loader_lock ();
7332 if (tls->abort_requested)
7333 mono_thread_internal_reset_abort (tls->thread);
7335 tls->invoke = tls->invoke->last_invoke;
7336 tls->abort_requested = FALSE;
7338 mono_loader_unlock ();
7347 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
7349 MonoThread *thread = (MonoThread *)value;
7350 DebuggerTlsData *tls;
7353 mono_loader_lock ();
7354 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
7356 res = tls->really_suspended;
7357 mono_loader_unlock ();
7363 get_source_files_for_type (MonoClass *klass)
7365 gpointer iter = NULL;
7367 MonoDebugSourceInfo *sinfo;
7371 files = g_ptr_array_new ();
7373 while ((method = mono_class_get_methods (klass, &iter))) {
7374 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
7375 GPtrArray *source_file_list;
7378 mono_debug_get_seq_points (minfo, NULL, &source_file_list, NULL, NULL, NULL);
7379 for (j = 0; j < source_file_list->len; ++j) {
7380 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, j);
7381 for (i = 0; i < files->len; ++i)
7382 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
7384 if (i == files->len)
7385 g_ptr_array_add (files, g_strdup (sinfo->source_file));
7387 g_ptr_array_free (source_file_list, TRUE);
7395 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
7398 case CMD_VM_VERSION: {
7399 char *build_info, *version;
7401 build_info = mono_get_runtime_build_info ();
7402 version = g_strdup_printf ("mono %s", build_info);
7404 buffer_add_string (buf, version); /* vm version */
7405 buffer_add_int (buf, MAJOR_VERSION);
7406 buffer_add_int (buf, MINOR_VERSION);
7407 g_free (build_info);
7411 case CMD_VM_SET_PROTOCOL_VERSION: {
7412 major_version = decode_int (p, &p, end);
7413 minor_version = decode_int (p, &p, end);
7414 protocol_version_set = TRUE;
7415 DEBUG_PRINTF (1, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version);
7418 case CMD_VM_ALL_THREADS: {
7420 mono_loader_lock ();
7421 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
7422 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
7423 mono_loader_unlock ();
7426 case CMD_VM_SUSPEND:
7428 wait_for_suspend ();
7431 if (suspend_count == 0)
7432 return ERR_NOT_SUSPENDED;
7434 clear_suspended_objs ();
7436 case CMD_VM_DISPOSE:
7437 /* Clear all event requests */
7438 mono_loader_lock ();
7439 while (event_requests->len > 0) {
7440 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
7442 clear_event_request (req->id, req->event_kind);
7444 mono_loader_unlock ();
7446 while (suspend_count > 0)
7448 disconnected = TRUE;
7449 vm_start_event_sent = FALSE;
7452 MonoInternalThread *thread;
7453 DebuggerTlsData *tls;
7454 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7455 MonoClass *env_class;
7457 MonoMethod *exit_method = NULL;
7461 exit_code = decode_int (p, &p, end);
7463 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
7465 /* Have to send a reply before exiting */
7466 send_reply_packet (id, 0, buf);
7468 /* Clear all event requests */
7469 mono_loader_lock ();
7470 while (event_requests->len > 0) {
7471 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
7473 clear_event_request (req->id, req->event_kind);
7475 mono_loader_unlock ();
7478 * The JDWP documentation says that the shutdown is not orderly. It doesn't
7479 * specify whenever a VM_DEATH event is sent. We currently do an orderly
7480 * shutdown by hijacking a thread to execute Environment.Exit (). This is
7481 * better than doing the shutdown ourselves, since it avoids various races.
7485 wait_for_suspend ();
7487 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7488 env_class = mono_class_try_load_from_name (mono_defaults.corlib, "System", "Environment");
7490 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
7493 mono_loader_lock ();
7494 thread = (MonoInternalThread *)mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
7495 mono_loader_unlock ();
7497 if (thread && exit_method) {
7498 mono_loader_lock ();
7499 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
7500 mono_loader_unlock ();
7502 args = g_new0 (gpointer, 1);
7503 args [0] = g_malloc (sizeof (int));
7504 *(int*)(args [0]) = exit_code;
7506 tls->pending_invoke = g_new0 (InvokeData, 1);
7507 tls->pending_invoke->method = exit_method;
7508 tls->pending_invoke->args = args;
7509 tls->pending_invoke->nmethods = 1;
7511 while (suspend_count > 0)
7515 * No thread found, do it ourselves.
7516 * FIXME: This can race with normal shutdown etc.
7518 while (suspend_count > 0)
7521 if (!mono_runtime_try_shutdown ())
7524 mono_environment_exitcode_set (exit_code);
7526 /* Suspend all managed threads since the runtime is going away */
7527 DEBUG_PRINTF (1, "Suspending all threads...\n");
7528 mono_thread_suspend_all_other_threads ();
7529 DEBUG_PRINTF (1, "Shutting down the runtime...\n");
7530 mono_runtime_quit ();
7531 transport_close2 ();
7532 DEBUG_PRINTF (1, "Exiting...\n");
7538 case CMD_VM_INVOKE_METHOD:
7539 case CMD_VM_INVOKE_METHODS: {
7540 int objid = decode_objid (p, &p, end);
7542 DebuggerTlsData *tls;
7543 int i, count, flags, nmethods;
7546 err = get_object (objid, (MonoObject**)&thread);
7547 if (err != ERR_NONE)
7550 flags = decode_int (p, &p, end);
7552 if (command == CMD_VM_INVOKE_METHODS)
7553 nmethods = decode_int (p, &p, end);
7557 // Wait for suspending if it already started
7559 wait_for_suspend ();
7560 if (!is_suspended ())
7561 return ERR_NOT_SUSPENDED;
7563 mono_loader_lock ();
7564 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7565 mono_loader_unlock ();
7568 if (!tls->really_suspended)
7569 /* The thread is still running native code, can't do invokes */
7570 return ERR_NOT_SUSPENDED;
7573 * Store the invoke data into tls, the thread will execute it after it is
7576 if (tls->pending_invoke)
7577 return ERR_NOT_SUSPENDED;
7578 tls->pending_invoke = g_new0 (InvokeData, 1);
7579 tls->pending_invoke->id = id;
7580 tls->pending_invoke->flags = flags;
7581 tls->pending_invoke->p = (guint8 *)g_malloc (end - p);
7582 memcpy (tls->pending_invoke->p, p, end - p);
7583 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
7584 tls->pending_invoke->suspend_count = suspend_count;
7585 tls->pending_invoke->nmethods = nmethods;
7587 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
7588 resume_thread (THREAD_TO_INTERNAL (thread));
7591 count = suspend_count;
7592 for (i = 0; i < count; ++i)
7597 case CMD_VM_ABORT_INVOKE: {
7598 int objid = decode_objid (p, &p, end);
7600 DebuggerTlsData *tls;
7604 err = get_object (objid, (MonoObject**)&thread);
7605 if (err != ERR_NONE)
7608 invoke_id = decode_int (p, &p, end);
7610 mono_loader_lock ();
7611 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7614 if (tls->abort_requested) {
7615 DEBUG_PRINTF (1, "Abort already requested.\n");
7616 mono_loader_unlock ();
7621 * Check whether we're still inside the mono_runtime_invoke_checked() and that it's
7622 * actually the correct invocation.
7624 * Careful, we do not stop the thread that's doing the invocation, so we can't
7625 * inspect its stack. However, invoke_method() also acquires the loader lock
7626 * when it's done, so we're safe here.
7630 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
7631 mono_loader_unlock ();
7632 return ERR_NO_INVOCATION;
7635 tls->abort_requested = TRUE;
7637 mono_thread_internal_abort (THREAD_TO_INTERNAL (thread));
7638 mono_loader_unlock ();
7642 case CMD_VM_SET_KEEPALIVE: {
7643 int timeout = decode_int (p, &p, end);
7644 agent_config.keepalive = timeout;
7646 #ifndef DISABLE_SOCKET_TRANSPORT
7653 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
7654 GHashTableIter iter, kiter;
7659 char *fname, *basename;
7660 gboolean ignore_case;
7661 GSList *class_list, *l;
7662 GPtrArray *res_classes, *res_domains;
7664 fname = decode_string (p, &p, end);
7665 ignore_case = decode_byte (p, &p, end);
7667 basename = dbg_path_get_basename (fname);
7669 res_classes = g_ptr_array_new ();
7670 res_domains = g_ptr_array_new ();
7672 mono_loader_lock ();
7673 g_hash_table_iter_init (&iter, domains);
7674 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7675 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
7677 /* Update 'source_file_to_class' cache */
7678 g_hash_table_iter_init (&kiter, info->loaded_classes);
7679 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
7680 if (!g_hash_table_lookup (info->source_files, klass)) {
7681 files = get_source_files_for_type (klass);
7682 g_hash_table_insert (info->source_files, klass, files);
7684 for (i = 0; i < files->len; ++i) {
7685 char *s = (char *)g_ptr_array_index (files, i);
7686 char *s2 = dbg_path_get_basename (s);
7689 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, s2);
7691 class_list = g_slist_prepend (class_list, klass);
7692 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
7694 class_list = g_slist_prepend (class_list, klass);
7695 g_hash_table_insert (info->source_file_to_class, s2, class_list);
7698 /* The _ignorecase hash contains the lowercase path */
7699 s3 = strdup_tolower (s2);
7700 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
7702 class_list = g_slist_prepend (class_list, klass);
7703 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
7705 class_list = g_slist_prepend (class_list, klass);
7706 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
7718 s = strdup_tolower (basename);
7719 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
7722 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, basename);
7725 for (l = class_list; l; l = l->next) {
7726 klass = (MonoClass *)l->data;
7728 g_ptr_array_add (res_classes, klass);
7729 g_ptr_array_add (res_domains, domain);
7732 mono_loader_unlock ();
7737 buffer_add_int (buf, res_classes->len);
7738 for (i = 0; i < res_classes->len; ++i)
7739 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7740 g_ptr_array_free (res_classes, TRUE);
7741 g_ptr_array_free (res_domains, TRUE);
7744 case CMD_VM_GET_TYPES: {
7745 GHashTableIter iter;
7749 gboolean ignore_case;
7750 GPtrArray *res_classes, *res_domains;
7751 MonoTypeNameParse info;
7753 name = decode_string (p, &p, end);
7754 ignore_case = decode_byte (p, &p, end);
7756 if (!mono_reflection_parse_type (name, &info)) {
7758 mono_reflection_free_type_info (&info);
7759 return ERR_INVALID_ARGUMENT;
7762 res_classes = g_ptr_array_new ();
7763 res_domains = g_ptr_array_new ();
7765 mono_loader_lock ();
7766 g_hash_table_iter_init (&iter, domains);
7767 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7769 gboolean type_resolve;
7773 mono_domain_assemblies_lock (domain);
7774 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7775 ass = (MonoAssembly *)tmp->data;
7779 type_resolve = TRUE;
7780 /* FIXME really okay to call while holding locks? */
7781 t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignore_case, &type_resolve, &error);
7782 mono_error_cleanup (&error);
7784 g_ptr_array_add (res_classes, mono_type_get_class (t));
7785 g_ptr_array_add (res_domains, domain);
7789 mono_domain_assemblies_unlock (domain);
7791 mono_loader_unlock ();
7794 mono_reflection_free_type_info (&info);
7796 buffer_add_int (buf, res_classes->len);
7797 for (i = 0; i < res_classes->len; ++i)
7798 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7799 g_ptr_array_free (res_classes, TRUE);
7800 g_ptr_array_free (res_domains, TRUE);
7803 case CMD_VM_START_BUFFERING:
7804 case CMD_VM_STOP_BUFFERING:
7805 /* Handled in the main loop */
7808 return ERR_NOT_IMPLEMENTED;
7815 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7821 case CMD_EVENT_REQUEST_SET: {
7823 int i, event_kind, suspend_policy, nmodifiers;
7827 MonoThread *step_thread;
7828 int step_thread_id = 0;
7829 StepDepth depth = STEP_DEPTH_INTO;
7830 StepSize size = STEP_SIZE_MIN;
7831 StepFilter filter = STEP_FILTER_NONE;
7835 event_kind = decode_byte (p, &p, end);
7836 suspend_policy = decode_byte (p, &p, end);
7837 nmodifiers = decode_byte (p, &p, end);
7839 req = (EventRequest *)g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7840 req->id = InterlockedIncrement (&event_request_id);
7841 req->event_kind = event_kind;
7842 req->suspend_policy = suspend_policy;
7843 req->nmodifiers = nmodifiers;
7846 for (i = 0; i < nmodifiers; ++i) {
7847 mod = (ModifierKind)decode_byte (p, &p, end);
7849 req->modifiers [i].kind = mod;
7850 if (mod == MOD_KIND_COUNT) {
7851 req->modifiers [i].data.count = decode_int (p, &p, end);
7852 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7853 method = decode_methodid (p, &p, end, &domain, &err);
7854 if (err != ERR_NONE)
7856 location = decode_long (p, &p, end);
7857 } else if (mod == MOD_KIND_STEP) {
7858 step_thread_id = decode_id (p, &p, end);
7859 size = (StepSize)decode_int (p, &p, end);
7860 depth = (StepDepth)decode_int (p, &p, end);
7861 if (CHECK_PROTOCOL_VERSION (2, 16))
7862 filter = (StepFilter)decode_int (p, &p, end);
7863 req->modifiers [i].data.filter = filter;
7864 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7865 /* Treat STEP_THOUGH the same as HIDDEN */
7866 req->modifiers [i].data.filter = (StepFilter)(req->modifiers [i].data.filter | STEP_FILTER_DEBUGGER_STEP_THROUGH);
7867 } else if (mod == MOD_KIND_THREAD_ONLY) {
7868 int id = decode_id (p, &p, end);
7870 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7871 if (err != ERR_NONE) {
7875 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7876 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7878 if (err != ERR_NONE)
7880 req->modifiers [i].caught = decode_byte (p, &p, end);
7881 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7882 if (CHECK_PROTOCOL_VERSION (2, 25))
7883 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7885 req->modifiers [i].subclasses = TRUE;
7886 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" : "");
7888 req->modifiers [i].data.exc_class = exc_class;
7890 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
7892 return ERR_INVALID_ARGUMENT;
7895 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7896 int n = decode_int (p, &p, end);
7899 // +1 because we don't know length and we use last element to check for end
7900 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n + 1);
7901 for (j = 0; j < n; ++j) {
7902 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7903 if (err != ERR_NONE) {
7904 g_free (req->modifiers [i].data.assemblies);
7908 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7909 int n = decode_int (p, &p, end);
7912 modifier = &req->modifiers [i];
7913 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7914 for (j = 0; j < n; ++j) {
7915 char *s = decode_string (p, &p, end);
7919 s2 = strdup_tolower (s);
7920 g_hash_table_insert (modifier->data.source_files, s2, s2);
7924 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7925 int n = decode_int (p, &p, end);
7928 modifier = &req->modifiers [i];
7929 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7930 for (j = 0; j < n; ++j) {
7931 char *s = decode_string (p, &p, end);
7934 g_hash_table_insert (modifier->data.type_names, s, s);
7938 return ERR_NOT_IMPLEMENTED;
7942 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7945 req->info = set_breakpoint (method, location, req, &error);
7946 if (!mono_error_ok (&error)) {
7948 DEBUG_PRINTF (1, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error));
7949 mono_error_cleanup (&error);
7950 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7952 } else if (req->event_kind == EVENT_KIND_STEP) {
7953 g_assert (step_thread_id);
7955 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7956 if (err != ERR_NONE) {
7961 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, filter, req);
7962 if (err != ERR_NONE) {
7966 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7967 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7968 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7969 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7970 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7971 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7973 if (req->nmodifiers) {
7975 return ERR_NOT_IMPLEMENTED;
7979 mono_loader_lock ();
7980 g_ptr_array_add (event_requests, req);
7982 if (agent_config.defer) {
7983 /* Transmit cached data to the client on receipt of the event request */
7984 switch (req->event_kind) {
7985 case EVENT_KIND_APPDOMAIN_CREATE:
7986 /* Emit load events for currently loaded domains */
7987 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7989 case EVENT_KIND_ASSEMBLY_LOAD:
7990 /* Emit load events for currently loaded assemblies */
7991 mono_domain_foreach (send_assemblies_for_domain, NULL);
7993 case EVENT_KIND_THREAD_START:
7994 /* Emit start events for currently started threads */
7995 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7997 case EVENT_KIND_TYPE_LOAD:
7998 /* Emit type load events for currently loaded types */
7999 mono_domain_foreach (send_types_for_domain, NULL);
8005 mono_loader_unlock ();
8007 buffer_add_int (buf, req->id);
8010 case CMD_EVENT_REQUEST_CLEAR: {
8011 int etype = decode_byte (p, &p, end);
8012 int req_id = decode_int (p, &p, end);
8014 // FIXME: Make a faster mapping from req_id to request
8015 mono_loader_lock ();
8016 clear_event_request (req_id, etype);
8017 mono_loader_unlock ();
8020 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
8023 mono_loader_lock ();
8025 while (i < event_requests->len) {
8026 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
8028 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
8029 clear_breakpoint ((MonoBreakpoint *)req->info);
8031 g_ptr_array_remove_index_fast (event_requests, i);
8037 mono_loader_unlock ();
8041 return ERR_NOT_IMPLEMENTED;
8048 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8054 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
8055 buffer_add_domainid (buf, mono_get_root_domain ());
8058 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
8059 domain = decode_domainid (p, &p, end, NULL, &err);
8060 if (err != ERR_NONE)
8062 buffer_add_string (buf, domain->friendly_name);
8065 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
8070 domain = decode_domainid (p, &p, end, NULL, &err);
8071 if (err != ERR_NONE)
8073 mono_loader_lock ();
8075 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
8078 buffer_add_int (buf, count);
8079 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
8080 ass = (MonoAssembly *)tmp->data;
8081 buffer_add_assemblyid (buf, domain, ass);
8083 mono_loader_unlock ();
8086 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
8087 domain = decode_domainid (p, &p, end, NULL, &err);
8088 if (err != ERR_NONE)
8091 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
8094 case CMD_APPDOMAIN_GET_CORLIB: {
8095 domain = decode_domainid (p, &p, end, NULL, &err);
8096 if (err != ERR_NONE)
8099 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
8102 case CMD_APPDOMAIN_CREATE_STRING: {
8107 domain = decode_domainid (p, &p, end, NULL, &err);
8108 if (err != ERR_NONE)
8110 s = decode_string (p, &p, end);
8112 o = mono_string_new_checked (domain, s, &error);
8113 if (!is_ok (&error)) {
8114 DEBUG_PRINTF (1, "[dbg] Failed to allocate String object '%s': %s\n", s, mono_error_get_message (&error));
8115 mono_error_cleanup (&error);
8116 return ERR_INVALID_OBJECT;
8118 buffer_add_objid (buf, (MonoObject*)o);
8121 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
8124 MonoDomain *domain2;
8127 domain = decode_domainid (p, &p, end, NULL, &err);
8128 if (err != ERR_NONE)
8130 klass = decode_typeid (p, &p, end, &domain2, &err);
8131 if (err != ERR_NONE)
8135 g_assert (domain == domain2);
8137 o = mono_object_new_checked (domain, klass, &error);
8138 mono_error_assert_ok (&error);
8140 err = decode_value (&klass->byval_arg, domain, (guint8 *)mono_object_unbox (o), p, &p, end);
8141 if (err != ERR_NONE)
8144 buffer_add_objid (buf, o);
8148 return ERR_NOT_IMPLEMENTED;
8155 get_assembly_object_command (MonoDomain *domain, MonoAssembly *ass, Buffer *buf, MonoError *error)
8157 HANDLE_FUNCTION_ENTER();
8158 ErrorCode err = ERR_NONE;
8160 MonoReflectionAssemblyHandle o = mono_assembly_get_object_handle (domain, ass, error);
8161 if (MONO_HANDLE_IS_NULL (o)) {
8162 err = ERR_INVALID_OBJECT;
8165 buffer_add_objid (buf, MONO_HANDLE_RAW (MONO_HANDLE_CAST (MonoObject, o)));
8167 HANDLE_FUNCTION_RETURN_VAL (err);
8172 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8178 ass = decode_assemblyid (p, &p, end, &domain, &err);
8179 if (err != ERR_NONE)
8183 case CMD_ASSEMBLY_GET_LOCATION: {
8184 buffer_add_string (buf, mono_image_get_filename (ass->image));
8187 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
8191 if (ass->image->dynamic) {
8192 buffer_add_id (buf, 0);
8194 token = mono_image_get_entry_point (ass->image);
8196 buffer_add_id (buf, 0);
8199 m = mono_get_method_checked (ass->image, token, NULL, NULL, &error);
8201 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8202 buffer_add_methodid (buf, domain, m);
8207 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
8208 buffer_add_moduleid (buf, domain, ass->image);
8211 case CMD_ASSEMBLY_GET_OBJECT: {
8213 err = get_assembly_object_command (domain, ass, buf, &error);
8214 mono_error_cleanup (&error);
8217 case CMD_ASSEMBLY_GET_DOMAIN: {
8218 buffer_add_domainid (buf, domain);
8221 case CMD_ASSEMBLY_GET_TYPE: {
8223 char *s = decode_string (p, &p, end);
8224 gboolean ignorecase = decode_byte (p, &p, end);
8225 MonoTypeNameParse info;
8227 gboolean type_resolve, res;
8228 MonoDomain *d = mono_domain_get ();
8230 /* This is needed to be able to find referenced assemblies */
8231 res = mono_domain_set (domain, FALSE);
8234 if (!mono_reflection_parse_type (s, &info)) {
8237 if (info.assembly.name)
8239 t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignorecase, &type_resolve, &error);
8240 if (!is_ok (&error)) {
8241 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8242 mono_reflection_free_type_info (&info);
8244 return ERR_INVALID_ARGUMENT;
8247 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
8248 mono_reflection_free_type_info (&info);
8251 mono_domain_set (d, TRUE);
8255 case CMD_ASSEMBLY_GET_NAME: {
8257 MonoAssembly *mass = ass;
8259 name = g_strdup_printf (
8260 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
8262 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
8263 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
8264 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
8265 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
8267 buffer_add_string (buf, name);
8272 return ERR_NOT_IMPLEMENTED;
8279 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8285 case CMD_MODULE_GET_INFO: {
8286 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
8289 basename = g_path_get_basename (image->name);
8290 buffer_add_string (buf, basename); // name
8291 buffer_add_string (buf, image->module_name); // scopename
8292 buffer_add_string (buf, image->name); // fqname
8293 buffer_add_string (buf, mono_image_get_guid (image)); // guid
8294 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
8299 return ERR_NOT_IMPLEMENTED;
8306 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8312 case CMD_FIELD_GET_INFO: {
8313 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
8315 buffer_add_string (buf, f->name);
8316 buffer_add_typeid (buf, domain, f->parent);
8317 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
8318 buffer_add_int (buf, f->type->attrs);
8322 return ERR_NOT_IMPLEMENTED;
8329 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
8331 if (val && val->vtable->klass == mono_defaults.runtimetype_class) {
8332 /* Special case these so the client doesn't have to handle Type objects */
8334 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
8335 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
8336 } else if (MONO_TYPE_IS_REFERENCE (t))
8337 buffer_add_value (buf, t, &val, domain);
8339 buffer_add_value (buf, t, mono_object_unbox (val), domain);
8343 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
8349 buffer_add_int (buf, 0);
8353 for (i = 0; i < cinfo->num_attrs; ++i) {
8354 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
8357 buffer_add_int (buf, nattrs);
8359 for (i = 0; i < cinfo->num_attrs; ++i) {
8360 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
8361 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
8362 MonoArray *typed_args, *named_args;
8364 CattrNamedArg *arginfo = NULL;
8367 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
8368 if (!mono_error_ok (&error)) {
8369 DEBUG_PRINTF (2, "[dbg] mono_reflection_create_custom_attr_data_args () failed with: '%s'\n", mono_error_get_message (&error));
8370 mono_error_cleanup (&error);
8371 return ERR_LOADER_ERROR;
8374 buffer_add_methodid (buf, domain, attr->ctor);
8378 buffer_add_int (buf, mono_array_length (typed_args));
8379 for (j = 0; j < mono_array_length (typed_args); ++j) {
8380 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
8382 t = mono_method_signature (attr->ctor)->params [j];
8384 buffer_add_cattr_arg (buf, t, domain, val);
8387 buffer_add_int (buf, 0);
8392 buffer_add_int (buf, mono_array_length (named_args));
8394 for (j = 0; j < mono_array_length (named_args); ++j) {
8395 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
8397 if (arginfo [j].prop) {
8398 buffer_add_byte (buf, 0x54);
8399 buffer_add_propertyid (buf, domain, arginfo [j].prop);
8400 } else if (arginfo [j].field) {
8401 buffer_add_byte (buf, 0x53);
8402 buffer_add_fieldid (buf, domain, arginfo [j].field);
8404 g_assert_not_reached ();
8407 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
8410 buffer_add_int (buf, 0);
8419 /* FIXME: Code duplication with icall.c */
8421 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
8426 mono_class_setup_interfaces (klass, error);
8427 if (!mono_error_ok (error))
8430 for (i = 0; i < klass->interface_count; i++) {
8431 ic = klass->interfaces [i];
8432 g_hash_table_insert (ifaces, ic, ic);
8434 collect_interfaces (ic, ifaces, error);
8435 if (!mono_error_ok (error))
8441 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8453 case CMD_TYPE_GET_INFO: {
8454 buffer_add_string (buf, klass->name_space);
8455 buffer_add_string (buf, klass->name);
8457 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
8458 buffer_add_string (buf, name);
8460 buffer_add_assemblyid (buf, domain, klass->image->assembly);
8461 buffer_add_moduleid (buf, domain, klass->image);
8462 buffer_add_typeid (buf, domain, klass->parent);
8463 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
8464 buffer_add_typeid (buf, domain, klass->element_class);
8466 buffer_add_id (buf, 0);
8467 buffer_add_int (buf, klass->type_token);
8468 buffer_add_byte (buf, klass->rank);
8469 buffer_add_int (buf, mono_class_get_flags (klass));
8471 type = &klass->byval_arg;
8472 // FIXME: Can't decide whenever a class represents a byref type
8475 if (type->type == MONO_TYPE_PTR)
8477 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
8479 if (type->type == MONO_TYPE_VALUETYPE)
8481 if (klass->enumtype)
8483 if (mono_class_is_gtd (klass))
8485 if (mono_class_is_gtd (klass) || mono_class_is_ginst (klass))
8487 buffer_add_byte (buf, b);
8490 while ((nested = mono_class_get_nested_types (klass, &iter)))
8492 buffer_add_int (buf, nnested);
8494 while ((nested = mono_class_get_nested_types (klass, &iter)))
8495 buffer_add_typeid (buf, domain, nested);
8496 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8497 if (mono_class_is_gtd (klass))
8498 buffer_add_typeid (buf, domain, klass);
8499 else if (mono_class_is_ginst (klass))
8500 buffer_add_typeid (buf, domain, mono_class_get_generic_class (klass)->container_class);
8502 buffer_add_id (buf, 0);
8504 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8507 if (mono_class_is_ginst (klass)) {
8508 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
8510 count = inst->type_argc;
8511 buffer_add_int (buf, count);
8512 for (i = 0; i < count; i++)
8513 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8514 } else if (mono_class_is_gtd (klass)) {
8515 MonoGenericContainer *container = mono_class_get_generic_container (klass);
8518 count = container->type_argc;
8519 buffer_add_int (buf, count);
8520 for (i = 0; i < count; i++) {
8521 pklass = mono_class_from_generic_parameter_internal (mono_generic_container_get_param (container, i));
8522 buffer_add_typeid (buf, domain, pklass);
8525 buffer_add_int (buf, 0);
8530 case CMD_TYPE_GET_METHODS: {
8533 gpointer iter = NULL;
8536 mono_class_setup_methods (klass);
8538 nmethods = mono_class_num_methods (klass);
8540 buffer_add_int (buf, nmethods);
8542 while ((m = mono_class_get_methods (klass, &iter))) {
8543 buffer_add_methodid (buf, domain, m);
8546 g_assert (i == nmethods);
8549 case CMD_TYPE_GET_FIELDS: {
8552 gpointer iter = NULL;
8555 nfields = mono_class_num_fields (klass);
8557 buffer_add_int (buf, nfields);
8559 while ((f = mono_class_get_fields (klass, &iter))) {
8560 buffer_add_fieldid (buf, domain, f);
8561 buffer_add_string (buf, f->name);
8562 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
8563 buffer_add_int (buf, f->type->attrs);
8566 g_assert (i == nfields);
8569 case CMD_TYPE_GET_PROPERTIES: {
8572 gpointer iter = NULL;
8575 nprops = mono_class_num_properties (klass);
8577 buffer_add_int (buf, nprops);
8579 while ((p = mono_class_get_properties (klass, &iter))) {
8580 buffer_add_propertyid (buf, domain, p);
8581 buffer_add_string (buf, p->name);
8582 buffer_add_methodid (buf, domain, p->get);
8583 buffer_add_methodid (buf, domain, p->set);
8584 buffer_add_int (buf, p->attrs);
8587 g_assert (i == nprops);
8590 case CMD_TYPE_GET_CATTRS: {
8591 MonoClass *attr_klass;
8592 MonoCustomAttrInfo *cinfo;
8594 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8595 /* attr_klass can be NULL */
8596 if (err != ERR_NONE)
8599 cinfo = mono_custom_attrs_from_class_checked (klass, &error);
8600 if (!is_ok (&error)) {
8601 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8602 return ERR_LOADER_ERROR;
8605 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8606 if (err != ERR_NONE)
8610 case CMD_TYPE_GET_FIELD_CATTRS: {
8611 MonoClass *attr_klass;
8612 MonoCustomAttrInfo *cinfo;
8613 MonoClassField *field;
8615 field = decode_fieldid (p, &p, end, NULL, &err);
8616 if (err != ERR_NONE)
8618 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8619 if (err != ERR_NONE)
8622 cinfo = mono_custom_attrs_from_field_checked (klass, field, &error);
8623 if (!is_ok (&error)) {
8624 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8625 return ERR_LOADER_ERROR;
8628 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8629 if (err != ERR_NONE)
8633 case CMD_TYPE_GET_PROPERTY_CATTRS: {
8634 MonoClass *attr_klass;
8635 MonoCustomAttrInfo *cinfo;
8638 prop = decode_propertyid (p, &p, end, NULL, &err);
8639 if (err != ERR_NONE)
8641 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8642 if (err != ERR_NONE)
8645 cinfo = mono_custom_attrs_from_property_checked (klass, prop, &error);
8646 if (!is_ok (&error)) {
8647 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8648 return ERR_LOADER_ERROR;
8651 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8652 if (err != ERR_NONE)
8656 case CMD_TYPE_GET_VALUES:
8657 case CMD_TYPE_GET_VALUES_2: {
8664 MonoThread *thread_obj;
8665 MonoInternalThread *thread = NULL;
8666 guint32 special_static_type;
8668 if (command == CMD_TYPE_GET_VALUES_2) {
8669 int objid = decode_objid (p, &p, end);
8672 err = get_object (objid, (MonoObject**)&thread_obj);
8673 if (err != ERR_NONE)
8676 thread = THREAD_TO_INTERNAL (thread_obj);
8679 len = decode_int (p, &p, end);
8680 for (i = 0; i < len; ++i) {
8681 f = decode_fieldid (p, &p, end, NULL, &err);
8682 if (err != ERR_NONE)
8685 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8686 return ERR_INVALID_FIELDID;
8687 special_static_type = mono_class_field_get_special_static_type (f);
8688 if (special_static_type != SPECIAL_STATIC_NONE) {
8689 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
8690 return ERR_INVALID_FIELDID;
8693 /* Check that the field belongs to the object */
8695 for (k = klass; k; k = k->parent) {
8696 if (k == f->parent) {
8702 return ERR_INVALID_FIELDID;
8704 vtable = mono_class_vtable (domain, f->parent);
8705 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8706 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val, &error);
8707 if (!is_ok (&error))
8708 return ERR_INVALID_FIELDID;
8709 buffer_add_value (buf, f->type, val, domain);
8714 case CMD_TYPE_SET_VALUES: {
8722 len = decode_int (p, &p, end);
8723 for (i = 0; i < len; ++i) {
8724 f = decode_fieldid (p, &p, end, NULL, &err);
8725 if (err != ERR_NONE)
8728 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8729 return ERR_INVALID_FIELDID;
8730 if (mono_class_field_is_special_static (f))
8731 return ERR_INVALID_FIELDID;
8733 /* Check that the field belongs to the object */
8735 for (k = klass; k; k = k->parent) {
8736 if (k == f->parent) {
8742 return ERR_INVALID_FIELDID;
8744 // FIXME: Check for literal/const
8746 vtable = mono_class_vtable (domain, f->parent);
8747 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8748 err = decode_value (f->type, domain, val, p, &p, end);
8749 if (err != ERR_NONE) {
8753 if (MONO_TYPE_IS_REFERENCE (f->type))
8754 mono_field_static_set_value (vtable, f, *(gpointer*)val);
8756 mono_field_static_set_value (vtable, f, val);
8761 case CMD_TYPE_GET_OBJECT: {
8762 MonoObject *o = (MonoObject*)mono_type_get_object_checked (domain, &klass->byval_arg, &error);
8763 if (!mono_error_ok (&error)) {
8764 mono_error_cleanup (&error);
8765 return ERR_INVALID_OBJECT;
8767 buffer_add_objid (buf, o);
8770 case CMD_TYPE_GET_SOURCE_FILES:
8771 case CMD_TYPE_GET_SOURCE_FILES_2: {
8772 char *source_file, *base;
8776 files = get_source_files_for_type (klass);
8778 buffer_add_int (buf, files->len);
8779 for (i = 0; i < files->len; ++i) {
8780 source_file = (char *)g_ptr_array_index (files, i);
8781 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8782 buffer_add_string (buf, source_file);
8784 base = dbg_path_get_basename (source_file);
8785 buffer_add_string (buf, base);
8788 g_free (source_file);
8790 g_ptr_array_free (files, TRUE);
8793 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8794 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8796 if (err != ERR_NONE)
8798 if (mono_class_is_assignable_from (klass, oklass))
8799 buffer_add_byte (buf, 1);
8801 buffer_add_byte (buf, 0);
8804 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8805 char *name = decode_string (p, &p, end);
8806 int i, flags = decode_int (p, &p, end);
8810 error_init (&error);
8811 array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &error);
8812 if (!is_ok (&error)) {
8813 mono_error_cleanup (&error);
8814 return ERR_LOADER_ERROR;
8816 buffer_add_int (buf, array->len);
8817 for (i = 0; i < array->len; ++i) {
8818 MonoMethod *method = (MonoMethod *)g_ptr_array_index (array, i);
8819 buffer_add_methodid (buf, domain, method);
8822 g_ptr_array_free (array, TRUE);
8826 case CMD_TYPE_GET_INTERFACES: {
8828 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8829 MonoClass *tclass, *iface;
8830 GHashTableIter iter;
8834 for (parent = tclass; parent; parent = parent->parent) {
8835 mono_class_setup_interfaces (parent, &error);
8836 if (!mono_error_ok (&error))
8837 return ERR_LOADER_ERROR;
8838 collect_interfaces (parent, iface_hash, &error);
8839 if (!mono_error_ok (&error))
8840 return ERR_LOADER_ERROR;
8843 buffer_add_int (buf, g_hash_table_size (iface_hash));
8845 g_hash_table_iter_init (&iter, iface_hash);
8846 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8847 buffer_add_typeid (buf, domain, iface);
8848 g_hash_table_destroy (iface_hash);
8851 case CMD_TYPE_GET_INTERFACE_MAP: {
8852 int tindex, ioffset;
8853 gboolean variance_used;
8855 int len, nmethods, i;
8859 len = decode_int (p, &p, end);
8860 mono_class_setup_vtable (klass);
8862 for (tindex = 0; tindex < len; ++tindex) {
8863 iclass = decode_typeid (p, &p, end, NULL, &err);
8864 if (err != ERR_NONE)
8867 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8869 return ERR_INVALID_ARGUMENT;
8871 nmethods = mono_class_num_methods (iclass);
8872 buffer_add_int (buf, nmethods);
8875 while ((method = mono_class_get_methods (iclass, &iter))) {
8876 buffer_add_methodid (buf, domain, method);
8878 for (i = 0; i < nmethods; ++i)
8879 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
8883 case CMD_TYPE_IS_INITIALIZED: {
8884 MonoVTable *vtable = mono_class_vtable (domain, klass);
8887 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8889 buffer_add_int (buf, 0);
8892 case CMD_TYPE_CREATE_INSTANCE: {
8896 obj = mono_object_new_checked (domain, klass, &error);
8897 mono_error_assert_ok (&error);
8898 buffer_add_objid (buf, obj);
8902 return ERR_NOT_IMPLEMENTED;
8909 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8912 MonoDomain *old_domain;
8916 klass = decode_typeid (p, &p, end, &domain, &err);
8917 if (err != ERR_NONE)
8920 old_domain = mono_domain_get ();
8922 mono_domain_set (domain, TRUE);
8924 err = type_commands_internal (command, klass, domain, p, end, buf);
8926 mono_domain_set (old_domain, TRUE);
8932 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8934 MonoMethodHeader *header;
8938 case CMD_METHOD_GET_NAME: {
8939 buffer_add_string (buf, method->name);
8942 case CMD_METHOD_GET_DECLARING_TYPE: {
8943 buffer_add_typeid (buf, domain, method->klass);
8946 case CMD_METHOD_GET_DEBUG_INFO: {
8948 MonoDebugMethodInfo *minfo;
8950 int i, j, n_il_offsets;
8952 GPtrArray *source_file_list;
8953 MonoSymSeqPoint *sym_seq_points;
8955 header = mono_method_get_header_checked (method, &error);
8957 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8958 buffer_add_int (buf, 0);
8959 buffer_add_string (buf, "");
8960 buffer_add_int (buf, 0);
8964 minfo = mono_debug_lookup_method (method);
8966 buffer_add_int (buf, header->code_size);
8967 buffer_add_string (buf, "");
8968 buffer_add_int (buf, 0);
8969 mono_metadata_free_mh (header);
8973 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, &source_files, &sym_seq_points, &n_il_offsets);
8974 buffer_add_int (buf, header->code_size);
8975 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8976 buffer_add_int (buf, source_file_list->len);
8977 for (i = 0; i < source_file_list->len; ++i) {
8978 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
8979 buffer_add_string (buf, sinfo->source_file);
8980 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8981 for (j = 0; j < 16; ++j)
8982 buffer_add_byte (buf, sinfo->hash [j]);
8986 buffer_add_string (buf, source_file);
8988 buffer_add_int (buf, n_il_offsets);
8989 DEBUG_PRINTF (10, "Line number table for method %s:\n", mono_method_full_name (method, TRUE));
8990 for (i = 0; i < n_il_offsets; ++i) {
8991 MonoSymSeqPoint *sp = &sym_seq_points [i];
8992 const char *srcfile = "";
8994 if (source_files [i] != -1) {
8995 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, source_files [i]);
8996 srcfile = sinfo->source_file;
8998 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);
8999 buffer_add_int (buf, sp->il_offset);
9000 buffer_add_int (buf, sp->line);
9001 if (CHECK_PROTOCOL_VERSION (2, 13))
9002 buffer_add_int (buf, source_files [i]);
9003 if (CHECK_PROTOCOL_VERSION (2, 19))
9004 buffer_add_int (buf, sp->column);
9005 if (CHECK_PROTOCOL_VERSION (2, 32)) {
9006 buffer_add_int (buf, sp->end_line);
9007 buffer_add_int (buf, sp->end_column);
9010 g_free (source_file);
9011 g_free (source_files);
9012 g_free (sym_seq_points);
9013 g_ptr_array_free (source_file_list, TRUE);
9014 mono_metadata_free_mh (header);
9017 case CMD_METHOD_GET_PARAM_INFO: {
9018 MonoMethodSignature *sig = mono_method_signature (method);
9022 /* FIXME: mono_class_from_mono_type () and byrefs */
9024 /* FIXME: Use a smaller encoding */
9025 buffer_add_int (buf, sig->call_convention);
9026 buffer_add_int (buf, sig->param_count);
9027 buffer_add_int (buf, sig->generic_param_count);
9028 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
9029 for (i = 0; i < sig->param_count; ++i) {
9031 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
9034 /* Emit parameter names */
9035 names = g_new (char *, sig->param_count);
9036 mono_method_get_param_names (method, (const char **) names);
9037 for (i = 0; i < sig->param_count; ++i)
9038 buffer_add_string (buf, names [i]);
9043 case CMD_METHOD_GET_LOCALS_INFO: {
9046 MonoDebugLocalsInfo *locals;
9047 int *locals_map = NULL;
9049 header = mono_method_get_header_checked (method, &error);
9051 mono_error_cleanup (&error); /* FIXME don't swallow the error */
9052 return ERR_INVALID_ARGUMENT;
9055 locals = mono_debug_lookup_locals (method);
9057 if (CHECK_PROTOCOL_VERSION (2, 43)) {
9059 buffer_add_int (buf, 1);
9060 buffer_add_int (buf, 0);
9061 buffer_add_int (buf, header->code_size);
9063 buffer_add_int (buf, header->num_locals);
9065 for (i = 0; i < header->num_locals; ++i) {
9066 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
9069 for (i = 0; i < header->num_locals; ++i) {
9071 sprintf (lname, "V_%d", i);
9072 buffer_add_string (buf, lname);
9075 for (i = 0; i < header->num_locals; ++i) {
9076 buffer_add_int (buf, 0);
9077 buffer_add_int (buf, header->code_size);
9080 if (CHECK_PROTOCOL_VERSION (2, 43)) {
9082 buffer_add_int (buf, locals->num_blocks);
9084 for (i = 0; i < locals->num_blocks; ++i) {
9085 buffer_add_int (buf, locals->code_blocks [i].start_offset - last_start);
9086 buffer_add_int (buf, locals->code_blocks [i].end_offset - locals->code_blocks [i].start_offset);
9087 last_start = locals->code_blocks [i].start_offset;
9091 num_locals = locals->num_locals;
9092 buffer_add_int (buf, num_locals);
9095 for (i = 0; i < num_locals; ++i) {
9096 g_assert (locals->locals [i].index < header->num_locals);
9097 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [locals->locals [i].index]));
9100 for (i = 0; i < num_locals; ++i)
9101 buffer_add_string (buf, locals->locals [i].name);
9103 for (i = 0; i < num_locals; ++i) {
9104 if (locals->locals [i].block) {
9105 buffer_add_int (buf, locals->locals [i].block->start_offset);
9106 buffer_add_int (buf, locals->locals [i].block->end_offset);
9108 buffer_add_int (buf, 0);
9109 buffer_add_int (buf, header->code_size);
9113 mono_metadata_free_mh (header);
9116 mono_debug_free_locals (locals);
9117 g_free (locals_map);
9121 case CMD_METHOD_GET_INFO:
9122 buffer_add_int (buf, method->flags);
9123 buffer_add_int (buf, method->iflags);
9124 buffer_add_int (buf, method->token);
9125 if (CHECK_PROTOCOL_VERSION (2, 12)) {
9127 if (method->is_generic)
9129 if (mono_method_signature (method)->generic_param_count)
9131 buffer_add_byte (buf, attrs);
9132 if (method->is_generic || method->is_inflated) {
9135 if (method->is_generic) {
9138 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
9140 result = imethod->declaring;
9141 if (imethod->context.class_inst) {
9142 MonoClass *klass = ((MonoMethod *) imethod)->klass;
9143 /*Generic methods gets the context of the GTD.*/
9144 if (mono_class_get_context (klass)) {
9146 result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), &error);
9147 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9152 buffer_add_methodid (buf, domain, result);
9154 buffer_add_id (buf, 0);
9156 if (CHECK_PROTOCOL_VERSION (2, 15)) {
9157 if (mono_method_signature (method)->generic_param_count) {
9160 if (method->is_inflated) {
9161 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
9163 count = inst->type_argc;
9164 buffer_add_int (buf, count);
9166 for (i = 0; i < count; i++)
9167 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
9169 buffer_add_int (buf, 0);
9171 } else if (method->is_generic) {
9172 MonoGenericContainer *container = mono_method_get_generic_container (method);
9174 count = mono_method_signature (method)->generic_param_count;
9175 buffer_add_int (buf, count);
9176 for (i = 0; i < count; i++) {
9177 MonoGenericParam *param = mono_generic_container_get_param (container, i);
9178 MonoClass *pklass = mono_class_from_generic_parameter_internal (param);
9179 buffer_add_typeid (buf, domain, pklass);
9182 buffer_add_int (buf, 0);
9185 buffer_add_int (buf, 0);
9190 case CMD_METHOD_GET_BODY: {
9194 header = mono_method_get_header_checked (method, &error);
9196 mono_error_cleanup (&error); /* FIXME don't swallow the error */
9197 buffer_add_int (buf, 0);
9199 if (CHECK_PROTOCOL_VERSION (2, 18))
9200 buffer_add_int (buf, 0);
9202 buffer_add_int (buf, header->code_size);
9203 for (i = 0; i < header->code_size; ++i)
9204 buffer_add_byte (buf, header->code [i]);
9206 if (CHECK_PROTOCOL_VERSION (2, 18)) {
9207 buffer_add_int (buf, header->num_clauses);
9208 for (i = 0; i < header->num_clauses; ++i) {
9209 MonoExceptionClause *clause = &header->clauses [i];
9211 buffer_add_int (buf, clause->flags);
9212 buffer_add_int (buf, clause->try_offset);
9213 buffer_add_int (buf, clause->try_len);
9214 buffer_add_int (buf, clause->handler_offset);
9215 buffer_add_int (buf, clause->handler_len);
9216 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
9217 buffer_add_typeid (buf, domain, clause->data.catch_class);
9218 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
9219 buffer_add_int (buf, clause->data.filter_offset);
9223 mono_metadata_free_mh (header);
9228 case CMD_METHOD_RESOLVE_TOKEN: {
9229 guint32 token = decode_int (p, &p, end);
9232 switch (mono_metadata_token_code (token)) {
9233 case MONO_TOKEN_STRING: {
9238 s = mono_ldstr_checked (domain, method->klass->image, mono_metadata_token_index (token), &error);
9239 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
9241 s2 = mono_string_to_utf8_checked (s, &error);
9242 mono_error_assert_ok (&error);
9244 buffer_add_byte (buf, TOKEN_TYPE_STRING);
9245 buffer_add_string (buf, s2);
9252 MonoClass *handle_class;
9254 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
9255 val = mono_method_get_wrapper_data (method, token);
9256 handle_class = (MonoClass *)mono_method_get_wrapper_data (method, token + 1);
9258 if (handle_class == NULL) {
9259 // Can't figure out the token type
9260 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
9264 val = mono_ldtoken_checked (method->klass->image, token, &handle_class, NULL, &error);
9266 g_error ("Could not load token due to %s", mono_error_get_message (&error));
9269 if (handle_class == mono_defaults.typehandle_class) {
9270 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
9271 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
9272 buffer_add_typeid (buf, domain, (MonoClass *) val);
9274 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
9275 } else if (handle_class == mono_defaults.fieldhandle_class) {
9276 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
9277 buffer_add_fieldid (buf, domain, (MonoClassField *)val);
9278 } else if (handle_class == mono_defaults.methodhandle_class) {
9279 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
9280 buffer_add_methodid (buf, domain, (MonoMethod *)val);
9281 } else if (handle_class == mono_defaults.string_class) {
9284 s = mono_string_to_utf8_checked ((MonoString *)val, &error);
9285 mono_error_assert_ok (&error);
9286 buffer_add_byte (buf, TOKEN_TYPE_STRING);
9287 buffer_add_string (buf, s);
9290 g_assert_not_reached ();
9297 case CMD_METHOD_GET_CATTRS: {
9299 MonoClass *attr_klass;
9300 MonoCustomAttrInfo *cinfo;
9302 attr_klass = decode_typeid (p, &p, end, NULL, &err);
9303 /* attr_klass can be NULL */
9304 if (err != ERR_NONE)
9307 cinfo = mono_custom_attrs_from_method_checked (method, &error);
9308 if (!is_ok (&error)) {
9309 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
9310 return ERR_LOADER_ERROR;
9313 err = buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
9314 if (err != ERR_NONE)
9318 case CMD_METHOD_MAKE_GENERIC_METHOD: {
9320 MonoType **type_argv;
9324 MonoGenericInst *ginst;
9325 MonoGenericContext tmp_context;
9326 MonoMethod *inflated;
9328 type_argc = decode_int (p, &p, end);
9329 type_argv = g_new0 (MonoType*, type_argc);
9330 for (i = 0; i < type_argc; ++i) {
9331 klass = decode_typeid (p, &p, end, &d, &err);
9332 if (err != ERR_NONE) {
9338 return ERR_INVALID_ARGUMENT;
9340 type_argv [i] = &klass->byval_arg;
9342 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
9344 tmp_context.class_inst = mono_class_is_ginst (method->klass) ? mono_class_get_generic_class (method->klass)->context.class_inst : NULL;
9345 tmp_context.method_inst = ginst;
9347 inflated = mono_class_inflate_generic_method_checked (method, &tmp_context, &error);
9348 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9349 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
9350 return ERR_INVALID_ARGUMENT;
9351 buffer_add_methodid (buf, domain, inflated);
9355 return ERR_NOT_IMPLEMENTED;
9362 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9365 MonoDomain *old_domain;
9369 method = decode_methodid (p, &p, end, &domain, &err);
9370 if (err != ERR_NONE)
9373 old_domain = mono_domain_get ();
9375 mono_domain_set (domain, TRUE);
9377 err = method_commands_internal (command, method, domain, p, end, buf);
9379 mono_domain_set (old_domain, TRUE);
9385 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9387 int objid = decode_objid (p, &p, end);
9389 MonoThread *thread_obj;
9390 MonoInternalThread *thread;
9392 err = get_object (objid, (MonoObject**)&thread_obj);
9393 if (err != ERR_NONE)
9396 thread = THREAD_TO_INTERNAL (thread_obj);
9399 case CMD_THREAD_GET_NAME: {
9401 gunichar2 *s = mono_thread_get_name (thread, &name_len);
9404 buffer_add_int (buf, 0);
9409 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
9411 buffer_add_int (buf, len);
9412 buffer_add_data (buf, (guint8*)name, len);
9417 case CMD_THREAD_GET_FRAME_INFO: {
9418 DebuggerTlsData *tls;
9419 int i, start_frame, length;
9421 // Wait for suspending if it already started
9422 // FIXME: Races with suspend_count
9423 while (!is_suspended ()) {
9425 wait_for_suspend ();
9429 wait_for_suspend ();
9430 if (!is_suspended ())
9431 return ERR_NOT_SUSPENDED;
9434 start_frame = decode_int (p, &p, end);
9435 length = decode_int (p, &p, end);
9437 if (start_frame != 0 || length != -1)
9438 return ERR_NOT_IMPLEMENTED;
9440 mono_loader_lock ();
9441 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9442 mono_loader_unlock ();
9445 compute_frame_info (thread, tls);
9447 buffer_add_int (buf, tls->frame_count);
9448 for (i = 0; i < tls->frame_count; ++i) {
9449 buffer_add_int (buf, tls->frames [i]->id);
9450 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
9451 buffer_add_int (buf, tls->frames [i]->il_offset);
9453 * Instead of passing the frame type directly to the client, we associate
9454 * it with the previous frame using a set of flags. This avoids lots of
9455 * conditional code in the client, since a frame whose type isn't
9456 * FRAME_TYPE_MANAGED has no method, location, etc.
9458 buffer_add_byte (buf, tls->frames [i]->flags);
9463 case CMD_THREAD_GET_STATE:
9464 buffer_add_int (buf, thread->state);
9466 case CMD_THREAD_GET_INFO:
9467 buffer_add_byte (buf, thread->threadpool_thread);
9469 case CMD_THREAD_GET_ID:
9470 buffer_add_long (buf, (guint64)(gsize)thread);
9472 case CMD_THREAD_GET_TID:
9473 buffer_add_long (buf, (guint64)thread->tid);
9475 case CMD_THREAD_SET_IP: {
9476 DebuggerTlsData *tls;
9479 MonoSeqPointInfo *seq_points;
9484 method = decode_methodid (p, &p, end, &domain, &err);
9485 if (err != ERR_NONE)
9487 il_offset = decode_long (p, &p, end);
9489 while (!is_suspended ()) {
9491 wait_for_suspend ();
9494 mono_loader_lock ();
9495 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9496 mono_loader_unlock ();
9499 compute_frame_info (thread, tls);
9500 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
9501 return ERR_INVALID_ARGUMENT;
9503 found_sp = mono_find_seq_point (domain, method, il_offset, &seq_points, &sp);
9505 g_assert (seq_points);
9508 return ERR_INVALID_ARGUMENT;
9510 // FIXME: Check that the ip change is safe
9512 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);
9514 if (tls->frames [0]->ji->is_interp) {
9515 MonoJitTlsData *jit_data = ((MonoThreadInfo*)thread->thread_info)->jit_data;
9516 mono_interp_set_resume_state (jit_data, NULL, tls->frames [0]->interp_frame, (guint8*)tls->frames [0]->ji->code_start + sp.native_offset);
9518 MONO_CONTEXT_SET_IP (&tls->restore_state.ctx, (guint8*)tls->frames [0]->ji->code_start + sp.native_offset);
9523 return ERR_NOT_IMPLEMENTED;
9530 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9534 MonoThread *thread_obj;
9535 MonoInternalThread *thread;
9536 int pos, i, len, frame_idx;
9537 DebuggerTlsData *tls;
9539 MonoDebugMethodJitInfo *jit;
9540 MonoMethodSignature *sig;
9542 MonoMethodHeader *header;
9544 objid = decode_objid (p, &p, end);
9545 err = get_object (objid, (MonoObject**)&thread_obj);
9546 if (err != ERR_NONE)
9549 thread = THREAD_TO_INTERNAL (thread_obj);
9551 id = decode_id (p, &p, end);
9553 mono_loader_lock ();
9554 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9555 mono_loader_unlock ();
9558 for (i = 0; i < tls->frame_count; ++i) {
9559 if (tls->frames [i]->id == id)
9562 if (i == tls->frame_count)
9563 return ERR_INVALID_FRAMEID;
9566 frame = tls->frames [frame_idx];
9568 /* This is supported for frames without has_ctx etc. set */
9569 if (command == CMD_STACK_FRAME_GET_DOMAIN) {
9570 if (CHECK_PROTOCOL_VERSION (2, 38))
9571 buffer_add_domainid (buf, frame->domain);
9575 if (!frame->has_ctx)
9576 return ERR_ABSENT_INFORMATION;
9578 if (!ensure_jit (frame))
9579 return ERR_ABSENT_INFORMATION;
9583 sig = mono_method_signature (frame->actual_method);
9585 if (!(jit->has_var_info || frame->ji->is_interp) || !mono_get_seq_points (frame->domain, frame->actual_method))
9587 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
9589 return ERR_ABSENT_INFORMATION;
9592 case CMD_STACK_FRAME_GET_VALUES: {
9594 len = decode_int (p, &p, end);
9595 header = mono_method_get_header_checked (frame->actual_method, &error);
9596 mono_error_assert_ok (&error); /* FIXME report error */
9598 for (i = 0; i < len; ++i) {
9599 pos = decode_int (p, &p, end);
9604 DEBUG_PRINTF (4, "[dbg] send arg %d.\n", pos);
9606 if (frame->ji->is_interp) {
9609 addr = mono_interp_frame_get_arg (frame->interp_frame, pos);
9611 buffer_add_value_full (buf, sig->params [pos], addr, frame->domain, FALSE, NULL);
9613 g_assert (pos >= 0 && pos < jit->num_params);
9615 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
9618 MonoDebugLocalsInfo *locals;
9620 locals = mono_debug_lookup_locals (frame->method);
9622 g_assert (pos < locals->num_locals);
9623 pos = locals->locals [pos].index;
9624 mono_debug_free_locals (locals);
9627 DEBUG_PRINTF (4, "[dbg] send local %d.\n", pos);
9629 if (frame->ji->is_interp) {
9632 addr = mono_interp_frame_get_local (frame->interp_frame, pos);
9634 buffer_add_value_full (buf, header->locals [pos], addr, frame->domain, FALSE, NULL);
9636 g_assert (pos >= 0 && pos < jit->num_locals);
9638 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
9642 mono_metadata_free_mh (header);
9645 case CMD_STACK_FRAME_GET_THIS: {
9646 if (frame->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE)
9647 return ERR_ABSENT_INFORMATION;
9648 if (frame->api_method->klass->valuetype) {
9649 if (!sig->hasthis) {
9650 MonoObject *p = NULL;
9651 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
9653 if (frame->ji->is_interp) {
9656 addr = mono_interp_frame_get_this (frame->interp_frame);
9658 buffer_add_value_full (buf, &frame->actual_method->klass->this_arg, addr, frame->domain, FALSE, NULL);
9660 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9664 if (!sig->hasthis) {
9665 MonoObject *p = NULL;
9666 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
9668 if (frame->ji->is_interp) {
9671 addr = mono_interp_frame_get_this (frame->interp_frame);
9673 buffer_add_value_full (buf, &frame->api_method->klass->byval_arg, addr, frame->domain, FALSE, NULL);
9675 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9681 case CMD_STACK_FRAME_SET_VALUES: {
9685 MonoDebugVarInfo *var = NULL;
9686 gboolean is_arg = FALSE;
9688 len = decode_int (p, &p, end);
9689 header = mono_method_get_header_checked (frame->actual_method, &error);
9690 mono_error_assert_ok (&error); /* FIXME report error */
9692 for (i = 0; i < len; ++i) {
9693 pos = decode_int (p, &p, end);
9698 g_assert (pos >= 0 && pos < jit->num_params);
9700 t = sig->params [pos];
9701 var = &jit->params [pos];
9704 MonoDebugLocalsInfo *locals;
9706 locals = mono_debug_lookup_locals (frame->method);
9708 g_assert (pos < locals->num_locals);
9709 pos = locals->locals [pos].index;
9710 mono_debug_free_locals (locals);
9712 g_assert (pos >= 0 && pos < jit->num_locals);
9714 t = header->locals [pos];
9715 var = &jit->locals [pos];
9718 if (MONO_TYPE_IS_REFERENCE (t))
9719 val_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
9721 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9722 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9723 if (err != ERR_NONE)
9726 if (frame->ji->is_interp) {
9730 addr = mono_interp_frame_get_arg (frame->interp_frame, pos);
9732 addr = mono_interp_frame_get_local (frame->interp_frame, pos);
9733 set_interp_var (t, addr, val_buf);
9735 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9738 mono_metadata_free_mh (header);
9741 case CMD_STACK_FRAME_GET_DOMAIN: {
9742 if (CHECK_PROTOCOL_VERSION (2, 38))
9743 buffer_add_domainid (buf, frame->domain);
9746 case CMD_STACK_FRAME_SET_THIS: {
9749 MonoDebugVarInfo *var;
9751 t = &frame->actual_method->klass->byval_arg;
9752 /* Checked by the sender */
9753 g_assert (MONO_TYPE_ISSTRUCT (t));
9755 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9756 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9757 if (err != ERR_NONE)
9760 if (frame->ji->is_interp) {
9763 addr = mono_interp_frame_get_this (frame->interp_frame);
9764 set_interp_var (&frame->actual_method->klass->this_arg, addr, val_buf);
9766 var = jit->this_var;
9769 set_var (&frame->actual_method->klass->this_arg, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9774 return ERR_NOT_IMPLEMENTED;
9781 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9784 int objid, index, len, i, esize;
9788 objid = decode_objid (p, &p, end);
9789 err = get_object (objid, (MonoObject**)&arr);
9790 if (err != ERR_NONE)
9794 case CMD_ARRAY_REF_GET_LENGTH:
9795 buffer_add_int (buf, arr->obj.vtable->klass->rank);
9797 buffer_add_int (buf, arr->max_length);
9798 buffer_add_int (buf, 0);
9800 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
9801 buffer_add_int (buf, arr->bounds [i].length);
9802 buffer_add_int (buf, arr->bounds [i].lower_bound);
9806 case CMD_ARRAY_REF_GET_VALUES:
9807 index = decode_int (p, &p, end);
9808 len = decode_int (p, &p, end);
9810 g_assert (index >= 0 && len >= 0);
9811 // Reordered to avoid integer overflow
9812 g_assert (!(index > arr->max_length - len));
9814 esize = mono_array_element_size (arr->obj.vtable->klass);
9815 for (i = index; i < index + len; ++i) {
9816 elem = (gpointer*)((char*)arr->vector + (i * esize));
9817 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
9820 case CMD_ARRAY_REF_SET_VALUES:
9821 index = decode_int (p, &p, end);
9822 len = decode_int (p, &p, end);
9824 g_assert (index >= 0 && len >= 0);
9825 // Reordered to avoid integer overflow
9826 g_assert (!(index > arr->max_length - len));
9828 esize = mono_array_element_size (arr->obj.vtable->klass);
9829 for (i = index; i < index + len; ++i) {
9830 elem = (gpointer*)((char*)arr->vector + (i * esize));
9832 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, (guint8 *)elem, p, &p, end);
9836 return ERR_NOT_IMPLEMENTED;
9843 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9849 int i, index, length;
9851 gboolean use_utf16 = FALSE;
9853 objid = decode_objid (p, &p, end);
9854 err = get_object (objid, (MonoObject**)&str);
9855 if (err != ERR_NONE)
9859 case CMD_STRING_REF_GET_VALUE:
9860 if (CHECK_PROTOCOL_VERSION (2, 41)) {
9861 for (i = 0; i < mono_string_length (str); ++i)
9862 if (mono_string_chars (str)[i] == 0)
9864 buffer_add_byte (buf, use_utf16 ? 1 : 0);
9867 buffer_add_int (buf, mono_string_length (str) * 2);
9868 buffer_add_data (buf, (guint8*)mono_string_chars (str), mono_string_length (str) * 2);
9871 s = mono_string_to_utf8_checked (str, &error);
9872 mono_error_assert_ok (&error);
9873 buffer_add_string (buf, s);
9877 case CMD_STRING_REF_GET_LENGTH:
9878 buffer_add_long (buf, mono_string_length (str));
9880 case CMD_STRING_REF_GET_CHARS:
9881 index = decode_long (p, &p, end);
9882 length = decode_long (p, &p, end);
9883 if (index > mono_string_length (str) - length)
9884 return ERR_INVALID_ARGUMENT;
9885 c = mono_string_chars (str) + index;
9886 for (i = 0; i < length; ++i)
9887 buffer_add_short (buf, c [i]);
9890 return ERR_NOT_IMPLEMENTED;
9897 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9908 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9909 objid = decode_objid (p, &p, end);
9910 err = get_object (objid, &obj);
9911 if (err != ERR_NONE)
9912 buffer_add_int (buf, 1);
9914 buffer_add_int (buf, 0);
9918 objid = decode_objid (p, &p, end);
9919 err = get_object (objid, &obj);
9920 if (err != ERR_NONE)
9923 MonoClass *obj_type;
9924 gboolean remote_obj = FALSE;
9926 obj_type = obj->vtable->klass;
9927 if (mono_class_is_transparent_proxy (obj_type)) {
9928 obj_type = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
9932 g_assert (obj_type);
9935 case CMD_OBJECT_REF_GET_TYPE:
9936 /* This handles transparent proxies too */
9937 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9939 case CMD_OBJECT_REF_GET_VALUES:
9940 len = decode_int (p, &p, end);
9942 for (i = 0; i < len; ++i) {
9943 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9944 if (err != ERR_NONE)
9947 /* Check that the field belongs to the object */
9949 for (k = obj_type; k; k = k->parent) {
9950 if (k == f->parent) {
9956 return ERR_INVALID_FIELDID;
9958 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9962 if (mono_class_field_is_special_static (f))
9963 return ERR_INVALID_FIELDID;
9965 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9966 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9967 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9968 mono_field_static_get_value_checked (vtable, f, val, &error);
9969 if (!is_ok (&error)) {
9970 mono_error_cleanup (&error); /* FIXME report the error */
9971 return ERR_INVALID_OBJECT;
9973 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9976 guint8 *field_value = NULL;
9979 #ifndef DISABLE_REMOTING
9980 void *field_storage = NULL;
9981 field_value = mono_load_remote_field_checked(obj, obj_type, f, &field_storage, &error);
9982 if (!is_ok (&error)) {
9983 mono_error_cleanup (&error); /* FIXME report the error */
9984 return ERR_INVALID_OBJECT;
9987 g_assert_not_reached ();
9990 field_value = (guint8*)obj + f->offset;
9992 buffer_add_value (buf, f->type, field_value, obj->vtable->domain);
9996 case CMD_OBJECT_REF_SET_VALUES:
9997 len = decode_int (p, &p, end);
9999 for (i = 0; i < len; ++i) {
10000 f = decode_fieldid (p, &p, end, NULL, &err);
10001 if (err != ERR_NONE)
10004 /* Check that the field belongs to the object */
10006 for (k = obj_type; k; k = k->parent) {
10007 if (k == f->parent) {
10013 return ERR_INVALID_FIELDID;
10015 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
10017 MonoVTable *vtable;
10019 if (mono_class_field_is_special_static (f))
10020 return ERR_INVALID_FIELDID;
10022 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
10023 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
10025 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
10026 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
10027 if (err != ERR_NONE) {
10031 mono_field_static_set_value (vtable, f, val);
10034 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
10035 if (err != ERR_NONE)
10040 case CMD_OBJECT_REF_GET_ADDRESS:
10041 buffer_add_long (buf, (gssize)obj);
10043 case CMD_OBJECT_REF_GET_DOMAIN:
10044 buffer_add_domainid (buf, obj->vtable->domain);
10046 case CMD_OBJECT_REF_GET_INFO:
10047 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
10048 buffer_add_domainid (buf, obj->vtable->domain);
10051 return ERR_NOT_IMPLEMENTED;
10058 command_set_to_string (CommandSet command_set)
10060 switch (command_set) {
10063 case CMD_SET_OBJECT_REF:
10064 return "OBJECT_REF";
10065 case CMD_SET_STRING_REF:
10066 return "STRING_REF";
10067 case CMD_SET_THREAD:
10069 case CMD_SET_ARRAY_REF:
10070 return "ARRAY_REF";
10071 case CMD_SET_EVENT_REQUEST:
10072 return "EVENT_REQUEST";
10073 case CMD_SET_STACK_FRAME:
10074 return "STACK_FRAME";
10075 case CMD_SET_APPDOMAIN:
10076 return "APPDOMAIN";
10077 case CMD_SET_ASSEMBLY:
10079 case CMD_SET_METHOD:
10083 case CMD_SET_MODULE:
10085 case CMD_SET_FIELD:
10087 case CMD_SET_EVENT:
10094 static const char* vm_cmds_str [] = {
10102 "SET_PROTOCOL_VERSION",
10105 "GET_TYPES_FOR_SOURCE_FILE",
10110 static const char* thread_cmds_str[] = {
10120 static const char* event_cmds_str[] = {
10123 "REQUEST_CLEAR_ALL_BREAKPOINTS"
10126 static const char* appdomain_cmds_str[] = {
10128 "GET_FRIENDLY_NAME",
10130 "GET_ENTRY_ASSEMBLY",
10133 "CREATE_BOXED_VALUE"
10136 static const char* assembly_cmds_str[] = {
10139 "GET_MANIFEST_MODULE",
10146 static const char* module_cmds_str[] = {
10150 static const char* field_cmds_str[] = {
10154 static const char* method_cmds_str[] = {
10156 "GET_DECLARING_TYPE",
10164 "MAKE_GENERIC_METHOD"
10167 static const char* type_cmds_str[] = {
10173 "GET_SOURCE_FILES",
10175 "IS_ASSIGNABLE_FROM",
10178 "GET_FIELD_CATTRS",
10179 "GET_PROPERTY_CATTRS",
10180 "GET_SOURCE_FILES_2",
10182 "GET_METHODS_BY_NAME_FLAGS",
10184 "GET_INTERFACE_MAP",
10188 static const char* stack_frame_cmds_str[] = {
10196 static const char* array_cmds_str[] = {
10202 static const char* string_cmds_str[] = {
10208 static const char* object_cmds_str[] = {
10219 cmd_to_string (CommandSet set, int command)
10226 cmds = vm_cmds_str;
10227 cmds_len = G_N_ELEMENTS (vm_cmds_str);
10229 case CMD_SET_OBJECT_REF:
10230 cmds = object_cmds_str;
10231 cmds_len = G_N_ELEMENTS (object_cmds_str);
10233 case CMD_SET_STRING_REF:
10234 cmds = string_cmds_str;
10235 cmds_len = G_N_ELEMENTS (string_cmds_str);
10237 case CMD_SET_THREAD:
10238 cmds = thread_cmds_str;
10239 cmds_len = G_N_ELEMENTS (thread_cmds_str);
10241 case CMD_SET_ARRAY_REF:
10242 cmds = array_cmds_str;
10243 cmds_len = G_N_ELEMENTS (array_cmds_str);
10245 case CMD_SET_EVENT_REQUEST:
10246 cmds = event_cmds_str;
10247 cmds_len = G_N_ELEMENTS (event_cmds_str);
10249 case CMD_SET_STACK_FRAME:
10250 cmds = stack_frame_cmds_str;
10251 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
10253 case CMD_SET_APPDOMAIN:
10254 cmds = appdomain_cmds_str;
10255 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
10257 case CMD_SET_ASSEMBLY:
10258 cmds = assembly_cmds_str;
10259 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
10261 case CMD_SET_METHOD:
10262 cmds = method_cmds_str;
10263 cmds_len = G_N_ELEMENTS (method_cmds_str);
10266 cmds = type_cmds_str;
10267 cmds_len = G_N_ELEMENTS (type_cmds_str);
10269 case CMD_SET_MODULE:
10270 cmds = module_cmds_str;
10271 cmds_len = G_N_ELEMENTS (module_cmds_str);
10273 case CMD_SET_FIELD:
10274 cmds = field_cmds_str;
10275 cmds_len = G_N_ELEMENTS (field_cmds_str);
10277 case CMD_SET_EVENT:
10278 cmds = event_cmds_str;
10279 cmds_len = G_N_ELEMENTS (event_cmds_str);
10284 if (command > 0 && command <= cmds_len)
10285 return cmds [command - 1];
10291 wait_for_attach (void)
10293 #ifndef DISABLE_SOCKET_TRANSPORT
10294 if (listen_fd == -1) {
10295 DEBUG_PRINTF (1, "[dbg] Invalid listening socket\n");
10299 /* Block and wait for client connection */
10300 conn_fd = socket_transport_accept (listen_fd);
10302 DEBUG_PRINTF (1, "Accepted connection on %d\n", conn_fd);
10303 if (conn_fd == -1) {
10304 DEBUG_PRINTF (1, "[dbg] Bad client connection\n");
10308 g_assert_not_reached ();
10312 disconnected = !transport_handshake ();
10313 if (disconnected) {
10314 DEBUG_PRINTF (1, "Transport handshake failed!\n");
10324 * This thread handles communication with the debugger client using a JDWP
10327 static gsize WINAPI
10328 debugger_thread (void *arg)
10331 int res, len, id, flags, command = 0;
10332 CommandSet command_set = (CommandSet)0;
10333 guint8 header [HEADER_LENGTH];
10334 guint8 *data, *p, *end;
10338 gboolean attach_failed = FALSE;
10340 DEBUG_PRINTF (1, "[dbg] Agent thread started, pid=%p\n", (gpointer) (gsize) mono_native_thread_id_get ());
10342 debugger_thread_id = mono_native_thread_id_get ();
10344 MonoInternalThread *internal = mono_thread_internal_current ();
10345 MonoString *str = mono_string_new_checked (mono_domain_get (), "Debugger agent", &error);
10346 mono_error_assert_ok (&error);
10347 mono_thread_set_name_internal (internal, str, TRUE, FALSE, &error);
10348 mono_error_assert_ok (&error);
10350 internal->state |= ThreadState_Background;
10351 internal->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
10353 if (agent_config.defer) {
10354 if (!wait_for_attach ()) {
10355 DEBUG_PRINTF (1, "[dbg] Can't attach, aborting debugger thread.\n");
10356 attach_failed = TRUE; // Don't abort process when we can't listen
10358 mono_set_is_debugger_attached (TRUE);
10359 /* Send start event to client */
10360 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
10363 mono_set_is_debugger_attached (TRUE);
10366 while (!attach_failed) {
10367 res = transport_recv (header, HEADER_LENGTH);
10369 /* This will break if the socket is closed during shutdown too */
10370 if (res != HEADER_LENGTH) {
10371 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH);
10376 end = header + HEADER_LENGTH;
10378 len = decode_int (p, &p, end);
10379 id = decode_int (p, &p, end);
10380 flags = decode_byte (p, &p, end);
10381 command_set = (CommandSet)decode_byte (p, &p, end);
10382 command = decode_byte (p, &p, end);
10384 g_assert (flags == 0);
10387 const char *cmd_str;
10388 char cmd_num [256];
10390 cmd_str = cmd_to_string (command_set, command);
10392 sprintf (cmd_num, "%d", command);
10396 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);
10399 data = (guint8 *)g_malloc (len - HEADER_LENGTH);
10400 if (len - HEADER_LENGTH > 0)
10402 res = transport_recv (data, len - HEADER_LENGTH);
10403 if (res != len - HEADER_LENGTH) {
10404 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH);
10410 end = data + (len - HEADER_LENGTH);
10412 buffer_init (&buf, 128);
10417 /* Process the request */
10418 switch (command_set) {
10420 err = vm_commands (command, id, p, end, &buf);
10421 if (err == ERR_NONE && command == CMD_VM_INVOKE_METHOD)
10422 /* Sent after the invoke is complete */
10425 case CMD_SET_EVENT_REQUEST:
10426 err = event_commands (command, p, end, &buf);
10428 case CMD_SET_APPDOMAIN:
10429 err = domain_commands (command, p, end, &buf);
10431 case CMD_SET_ASSEMBLY:
10432 err = assembly_commands (command, p, end, &buf);
10434 case CMD_SET_MODULE:
10435 err = module_commands (command, p, end, &buf);
10437 case CMD_SET_FIELD:
10438 err = field_commands (command, p, end, &buf);
10441 err = type_commands (command, p, end, &buf);
10443 case CMD_SET_METHOD:
10444 err = method_commands (command, p, end, &buf);
10446 case CMD_SET_THREAD:
10447 err = thread_commands (command, p, end, &buf);
10449 case CMD_SET_STACK_FRAME:
10450 err = frame_commands (command, p, end, &buf);
10452 case CMD_SET_ARRAY_REF:
10453 err = array_commands (command, p, end, &buf);
10455 case CMD_SET_STRING_REF:
10456 err = string_commands (command, p, end, &buf);
10458 case CMD_SET_OBJECT_REF:
10459 err = object_commands (command, p, end, &buf);
10462 err = ERR_NOT_IMPLEMENTED;
10465 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
10466 buffer_replies = TRUE;
10470 if (buffer_replies) {
10471 buffer_reply_packet (id, err, &buf);
10473 send_reply_packet (id, err, &buf);
10474 //DEBUG_PRINTF (1, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000);
10478 if (err == ERR_NONE && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
10479 send_buffered_reply_packets ();
10480 buffer_replies = FALSE;
10484 buffer_free (&buf);
10486 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
10490 mono_set_is_debugger_attached (FALSE);
10492 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
10493 debugger_thread_exited = TRUE;
10494 mono_coop_cond_signal (&debugger_thread_exited_cond);
10495 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
10497 DEBUG_PRINTF (1, "[dbg] Debugger thread exited.\n");
10499 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
10500 DEBUG_PRINTF (2, "[dbg] Detached - restarting clean debugger thread.\n");
10501 start_debugger_thread ();
10507 #else /* DISABLE_DEBUGGER_AGENT */
10510 mono_debugger_agent_parse_options (char *options)
10512 g_error ("This runtime is configured with the debugger agent disabled.");
10516 mono_debugger_agent_init (void)
10521 mono_debugger_agent_breakpoint_hit (void *sigctx)
10526 mono_debugger_agent_single_step_event (void *sigctx)
10531 mono_debugger_agent_free_domain_info (MonoDomain *domain)
10536 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
10537 MonoContext *catch_ctx)
10542 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
10547 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
10552 mono_debugger_agent_user_break (void)
10558 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
10563 mono_debugger_agent_debug_log_is_enabled (void)
10569 mono_debugger_agent_unhandled_exception (MonoException *exc)
10571 g_assert_not_reached ();
10575 debugger_agent_single_step_from_context (MonoContext *ctx)
10577 g_assert_not_reached ();
10581 debugger_agent_breakpoint_from_context (MonoContext *ctx)
10583 g_assert_not_reached ();