2 * debugger-agent.c: Soft Debugger back-end module
5 * Zoltan Varga (vargaz@gmail.com)
7 * Copyright 2009-2010 Novell, Inc.
8 * Copyright 2011 Xamarin Inc.
9 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
16 #ifdef HAVE_SYS_TYPES_H
17 #include <sys/types.h>
19 #ifdef HAVE_SYS_SELECT_H
20 #include <sys/select.h>
22 #ifdef HAVE_SYS_SOCKET_H
23 #include <sys/socket.h>
25 #ifdef HAVE_NETINET_TCP_H
26 #include <netinet/tcp.h>
28 #ifdef HAVE_NETINET_IN_H
29 #include <netinet/in.h>
49 #ifdef PLATFORM_ANDROID
51 #include <linux/tcp.h>
52 #include <sys/endian.h>
55 #include <mono/metadata/mono-debug.h>
56 #include <mono/metadata/mono-debug-debugger.h>
57 #include <mono/metadata/debug-mono-symfile.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 "debugger-agent.h"
77 #include "seq-points.h"
78 #include <mono/io-layer/io-layer.h>
81 * On iOS we can't use System.Environment.Exit () as it will do the wrong
84 #if !defined (TARGET_IOS)
85 #define TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
89 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
90 #define DISABLE_DEBUGGER_AGENT 1
93 #ifdef DISABLE_SOFT_DEBUG
94 #define DISABLE_DEBUGGER_AGENT 1
97 #ifndef DISABLE_DEBUGGER_AGENT
99 #include <mono/utils/mono-os-mutex.h>
101 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
124 guint32 il_offset, native_offset;
128 * If method is gshared, this is the actual instance, otherwise this is equal to
131 MonoMethod *actual_method;
133 * This is the method which is visible to debugger clients. Same as method,
134 * except for native-to-managed wrappers.
136 MonoMethod *api_method;
138 MonoDebugMethodJitInfo *jit;
141 mgreg_t *reg_locations [MONO_MAX_IREGS];
143 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
144 * the frame can become invalid.
149 typedef struct _InvokeData InvokeData;
157 /* This is the context which needs to be restored after the invoke */
161 * If this is set, invoke this method with the arguments given by ARGS.
165 guint32 suspend_count;
168 InvokeData *last_invoke;
172 MonoThreadUnwindState context;
174 /* This is computed on demand when it is requested using the wire protocol */
175 /* It is freed up when the thread is resumed */
179 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
182 gboolean frames_up_to_date;
184 * Points to data about a pending invoke which needs to be executed after the thread
187 InvokeData *pending_invoke;
189 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
194 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
195 * within a finite amount of time.
199 * Set to TRUE if this thread is suspended in suspend_current ().
201 gboolean really_suspended;
202 /* Used to pass the context to the breakpoint/single step handler */
203 MonoContext handler_ctx;
204 /* Whenever thread_stop () was called for this thread */
207 /* Whenever to disable breakpoints (used during invokes) */
208 gboolean disable_breakpoints;
211 * Number of times this thread has been resumed using resume_thread ().
213 guint32 resume_count;
215 MonoInternalThread *thread;
218 * Information about the frame which transitioned to native code for running
221 StackFrameInfo async_last_frame;
224 * The context where the stack walk can be started for running threads.
226 MonoThreadUnwindState async_state;
229 * The context used for filter clauses
231 MonoThreadUnwindState filter_state;
233 gboolean abort_requested;
236 * The current mono_runtime_invoke_checked invocation.
241 * The context where single stepping should resume while the thread is suspended because
242 * of an EXCEPTION event.
244 MonoThreadUnwindState catch_state;
247 * The context which needs to be restored after handling a single step/breakpoint
248 * event. This is the same as the ctx at step/breakpoint site, but includes changes
249 * to caller saved registers done by set_var ().
251 MonoThreadUnwindState restore_state;
252 /* Frames computed from restore_state */
253 int restore_frame_count;
254 StackFrame **restore_frames;
256 /* The currently unloading appdomain */
257 MonoDomain *domain_unloading;
262 void (*connect) (const char *address);
263 void (*close1) (void);
264 void (*close2) (void);
265 gboolean (*send) (void *buf, int len);
266 int (*recv) (void *buf, int len);
270 * Wire Protocol definitions
273 #define HEADER_LENGTH 11
275 #define MAJOR_VERSION 2
276 #define MINOR_VERSION 44
280 CMD_SET_OBJECT_REF = 9,
281 CMD_SET_STRING_REF = 10,
283 CMD_SET_ARRAY_REF = 13,
284 CMD_SET_EVENT_REQUEST = 15,
285 CMD_SET_STACK_FRAME = 16,
286 CMD_SET_APPDOMAIN = 20,
287 CMD_SET_ASSEMBLY = 21,
296 EVENT_KIND_VM_START = 0,
297 EVENT_KIND_VM_DEATH = 1,
298 EVENT_KIND_THREAD_START = 2,
299 EVENT_KIND_THREAD_DEATH = 3,
300 EVENT_KIND_APPDOMAIN_CREATE = 4,
301 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
302 EVENT_KIND_METHOD_ENTRY = 6,
303 EVENT_KIND_METHOD_EXIT = 7,
304 EVENT_KIND_ASSEMBLY_LOAD = 8,
305 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
306 EVENT_KIND_BREAKPOINT = 10,
307 EVENT_KIND_STEP = 11,
308 EVENT_KIND_TYPE_LOAD = 12,
309 EVENT_KIND_EXCEPTION = 13,
310 EVENT_KIND_KEEPALIVE = 14,
311 EVENT_KIND_USER_BREAK = 15,
312 EVENT_KIND_USER_LOG = 16
316 SUSPEND_POLICY_NONE = 0,
317 SUSPEND_POLICY_EVENT_THREAD = 1,
318 SUSPEND_POLICY_ALL = 2
323 ERR_INVALID_OBJECT = 20,
324 ERR_INVALID_FIELDID = 25,
325 ERR_INVALID_FRAMEID = 30,
326 ERR_NOT_IMPLEMENTED = 100,
327 ERR_NOT_SUSPENDED = 101,
328 ERR_INVALID_ARGUMENT = 102,
330 ERR_NO_INVOCATION = 104,
331 ERR_ABSENT_INFORMATION = 105,
332 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
333 ERR_INVOKE_ABORTED = 107,
334 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
339 MOD_KIND_THREAD_ONLY = 3,
340 MOD_KIND_LOCATION_ONLY = 7,
341 MOD_KIND_EXCEPTION_ONLY = 8,
343 MOD_KIND_ASSEMBLY_ONLY = 11,
344 MOD_KIND_SOURCE_FILE_ONLY = 12,
345 MOD_KIND_TYPE_NAME_ONLY = 13,
361 STEP_FILTER_NONE = 0,
362 STEP_FILTER_STATIC_CTOR = 1,
363 STEP_FILTER_DEBUGGER_HIDDEN = 2,
364 STEP_FILTER_DEBUGGER_STEP_THROUGH = 4,
365 STEP_FILTER_DEBUGGER_NON_USER_CODE = 8
369 TOKEN_TYPE_STRING = 0,
371 TOKEN_TYPE_FIELD = 2,
372 TOKEN_TYPE_METHOD = 3,
373 TOKEN_TYPE_UNKNOWN = 4
377 VALUE_TYPE_ID_NULL = 0xf0,
378 VALUE_TYPE_ID_TYPE = 0xf1,
379 VALUE_TYPE_ID_PARENT_VTYPE = 0xf2
383 FRAME_FLAG_DEBUGGER_INVOKE = 1,
384 FRAME_FLAG_NATIVE_TRANSITION = 2
388 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
389 INVOKE_FLAG_SINGLE_THREADED = 2,
390 INVOKE_FLAG_RETURN_OUT_THIS = 4,
391 INVOKE_FLAG_RETURN_OUT_ARGS = 8,
392 INVOKE_FLAG_VIRTUAL = 16
396 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
397 } BindingFlagsExtensions;
401 CMD_VM_ALL_THREADS = 2,
406 CMD_VM_INVOKE_METHOD = 7,
407 CMD_VM_SET_PROTOCOL_VERSION = 8,
408 CMD_VM_ABORT_INVOKE = 9,
409 CMD_VM_SET_KEEPALIVE = 10,
410 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
411 CMD_VM_GET_TYPES = 12,
412 CMD_VM_INVOKE_METHODS = 13,
413 CMD_VM_START_BUFFERING = 14,
414 CMD_VM_STOP_BUFFERING = 15
418 CMD_THREAD_GET_FRAME_INFO = 1,
419 CMD_THREAD_GET_NAME = 2,
420 CMD_THREAD_GET_STATE = 3,
421 CMD_THREAD_GET_INFO = 4,
422 CMD_THREAD_GET_ID = 5,
423 CMD_THREAD_GET_TID = 6,
424 CMD_THREAD_SET_IP = 7
428 CMD_EVENT_REQUEST_SET = 1,
429 CMD_EVENT_REQUEST_CLEAR = 2,
430 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
438 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
439 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
440 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
441 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
442 CMD_APPDOMAIN_CREATE_STRING = 5,
443 CMD_APPDOMAIN_GET_CORLIB = 6,
444 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
448 CMD_ASSEMBLY_GET_LOCATION = 1,
449 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
450 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
451 CMD_ASSEMBLY_GET_OBJECT = 4,
452 CMD_ASSEMBLY_GET_TYPE = 5,
453 CMD_ASSEMBLY_GET_NAME = 6
457 CMD_MODULE_GET_INFO = 1,
461 CMD_FIELD_GET_INFO = 1,
465 CMD_METHOD_GET_NAME = 1,
466 CMD_METHOD_GET_DECLARING_TYPE = 2,
467 CMD_METHOD_GET_DEBUG_INFO = 3,
468 CMD_METHOD_GET_PARAM_INFO = 4,
469 CMD_METHOD_GET_LOCALS_INFO = 5,
470 CMD_METHOD_GET_INFO = 6,
471 CMD_METHOD_GET_BODY = 7,
472 CMD_METHOD_RESOLVE_TOKEN = 8,
473 CMD_METHOD_GET_CATTRS = 9,
474 CMD_METHOD_MAKE_GENERIC_METHOD = 10
478 CMD_TYPE_GET_INFO = 1,
479 CMD_TYPE_GET_METHODS = 2,
480 CMD_TYPE_GET_FIELDS = 3,
481 CMD_TYPE_GET_VALUES = 4,
482 CMD_TYPE_GET_OBJECT = 5,
483 CMD_TYPE_GET_SOURCE_FILES = 6,
484 CMD_TYPE_SET_VALUES = 7,
485 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
486 CMD_TYPE_GET_PROPERTIES = 9,
487 CMD_TYPE_GET_CATTRS = 10,
488 CMD_TYPE_GET_FIELD_CATTRS = 11,
489 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
490 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
491 CMD_TYPE_GET_VALUES_2 = 14,
492 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
493 CMD_TYPE_GET_INTERFACES = 16,
494 CMD_TYPE_GET_INTERFACE_MAP = 17,
495 CMD_TYPE_IS_INITIALIZED = 18,
496 CMD_TYPE_CREATE_INSTANCE = 19
500 CMD_STACK_FRAME_GET_VALUES = 1,
501 CMD_STACK_FRAME_GET_THIS = 2,
502 CMD_STACK_FRAME_SET_VALUES = 3,
503 CMD_STACK_FRAME_GET_DOMAIN = 4,
504 CMD_STACK_FRAME_SET_THIS = 5,
508 CMD_ARRAY_REF_GET_LENGTH = 1,
509 CMD_ARRAY_REF_GET_VALUES = 2,
510 CMD_ARRAY_REF_SET_VALUES = 3,
514 CMD_STRING_REF_GET_VALUE = 1,
515 CMD_STRING_REF_GET_LENGTH = 2,
516 CMD_STRING_REF_GET_CHARS = 3
520 CMD_OBJECT_REF_GET_TYPE = 1,
521 CMD_OBJECT_REF_GET_VALUES = 2,
522 CMD_OBJECT_REF_IS_COLLECTED = 3,
523 CMD_OBJECT_REF_GET_ADDRESS = 4,
524 CMD_OBJECT_REF_GET_DOMAIN = 5,
525 CMD_OBJECT_REF_SET_VALUES = 6,
526 CMD_OBJECT_REF_GET_INFO = 7,
532 int count; /* For kind == MOD_KIND_COUNT */
533 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
534 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
535 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
536 GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
537 GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
538 StepFilter filter; /* For kind == MOD_KIND_STEP */
540 gboolean caught, uncaught, subclasses; /* For kind == MOD_KIND_EXCEPTION_ONLY */
549 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
553 * Describes a single step request.
557 MonoInternalThread *thread;
563 MonoMethod *start_method;
564 MonoMethod *last_method;
566 /* Whenever single stepping is performed using start/stop_single_stepping () */
568 /* The list of breakpoints used to implement step-over */
570 /* The number of frames at the start of a step-over */
572 /* If set, don't stop in methods that are not part of user assemblies */
573 MonoAssembly** user_assemblies;
577 * Contains additional information for an event
580 /* For EVENT_KIND_EXCEPTION */
582 MonoContext catch_ctx;
584 /* For EVENT_KIND_USER_LOG */
586 char *category, *message;
587 /* For EVENT_KIND_TYPE_LOAD */
591 /* Dummy structure used for the profiler callbacks */
597 guint8 *buf, *p, *end;
600 typedef struct ReplyPacket {
606 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
608 #ifdef PLATFORM_ANDROID
609 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { g_print (__VA_ARGS__); } } while (0)
611 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { fprintf (log_file, __VA_ARGS__); fflush (log_file); } } while (0)
615 #define get_last_sock_error() WSAGetLastError()
616 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
617 #define MONO_EINTR WSAEINTR
619 #define get_last_sock_error() errno
620 #define MONO_EWOULDBLOCK EWOULDBLOCK
621 #define MONO_EINTR EINTR
624 #define CHECK_PROTOCOL_VERSION(major,minor) \
625 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
631 static AgentConfig agent_config;
634 * Whenever the agent is fully initialized.
635 * When using the onuncaught or onthrow options, only some parts of the agent are
636 * initialized on startup, and the full initialization which includes connection
637 * establishment and the startup of the agent thread is only done in response to
640 static gint32 inited;
642 #ifndef DISABLE_SOCKET_TRANSPORT
644 static int listen_fd;
647 static int packet_id = 0;
649 static int objref_id = 0;
651 static int event_request_id = 0;
653 static int frame_id = 0;
655 static GPtrArray *event_requests;
657 static MonoNativeTlsKey debugger_tls_id;
659 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
661 /* Maps MonoInternalThread -> DebuggerTlsData */
662 /* Protected by the loader lock */
663 static MonoGHashTable *thread_to_tls;
665 /* Maps tid -> MonoInternalThread */
666 /* Protected by the loader lock */
667 static MonoGHashTable *tid_to_thread;
669 /* Maps tid -> MonoThread (not MonoInternalThread) */
670 /* Protected by the loader lock */
671 static MonoGHashTable *tid_to_thread_obj;
673 static MonoNativeThreadId debugger_thread_id;
675 static MonoThreadHandle *debugger_thread_handle;
677 static int log_level;
679 static gboolean embedding;
681 static FILE *log_file;
683 /* Assemblies whose assembly load event has no been sent yet */
684 /* Protected by the dbg lock */
685 static GPtrArray *pending_assembly_loads;
687 /* Whenever the debugger thread has exited */
688 static gboolean debugger_thread_exited;
690 /* Cond variable used to wait for debugger_thread_exited becoming true */
691 static MonoCoopCond debugger_thread_exited_cond;
693 /* Mutex for the cond var above */
694 static MonoCoopMutex debugger_thread_exited_mutex;
696 static DebuggerProfiler debugger_profiler;
698 /* The single step request instance */
699 static SingleStepReq *ss_req;
701 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
702 /* Number of single stepping operations in progress */
706 /* The protocol version of the client */
707 static int major_version, minor_version;
709 /* Whenever the variables above are set by the client */
710 static gboolean protocol_version_set;
712 /* A hash table containing all active domains */
713 /* Protected by the loader lock */
714 static GHashTable *domains;
716 /* The number of times the runtime is suspended */
717 static gint32 suspend_count;
719 /* Whenever to buffer reply messages and send them together */
720 static gboolean buffer_replies;
722 /* Buffered reply packets */
723 static ReplyPacket reply_packets [128];
726 #define dbg_lock() mono_coop_mutex_lock (&debug_mutex)
727 #define dbg_unlock() mono_coop_mutex_unlock (&debug_mutex)
728 static MonoCoopMutex debug_mutex;
730 static void transport_init (void);
731 static void transport_connect (const char *address);
732 static gboolean transport_handshake (void);
733 static void register_transport (DebuggerTransport *trans);
735 static gsize WINAPI debugger_thread (void *arg);
737 static void runtime_initialized (MonoProfiler *prof);
739 static void runtime_shutdown (MonoProfiler *prof);
741 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
743 static void thread_end (MonoProfiler *prof, uintptr_t tid);
745 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
747 static void appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain);
749 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
751 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
753 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
755 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
757 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
759 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
761 static void emit_assembly_load (gpointer assembly, gpointer user_data);
763 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
765 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
767 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
769 static void start_single_stepping (void);
771 static void stop_single_stepping (void);
773 static void suspend_current (void);
775 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
777 static void clear_types_for_assembly (MonoAssembly *assembly);
779 static void clear_breakpoints_for_domain (MonoDomain *domain);
781 static void process_profiler_event (EventKind event, gpointer arg);
783 /* Submodule init/cleanup */
784 static void breakpoints_init (void);
785 static void breakpoints_cleanup (void);
787 static void objrefs_init (void);
788 static void objrefs_cleanup (void);
790 static void ids_init (void);
791 static void ids_cleanup (void);
793 static void suspend_init (void);
795 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch,
796 StackFrame **frames, int nframes);
797 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req);
798 static void ss_destroy (SingleStepReq *req);
800 static void start_debugger_thread (void);
801 static void stop_debugger_thread (void);
803 static void finish_agent_init (gboolean on_startup);
805 static void process_profiler_event (EventKind event, gpointer arg);
807 static void invalidate_frames (DebuggerTlsData *tls);
809 #ifndef DISABLE_SOCKET_TRANSPORT
811 register_socket_transport (void);
814 static inline gboolean
815 is_debugger_thread (void)
817 return mono_native_thread_id_equals (mono_native_thread_id_get (), debugger_thread_id);
821 parse_address (char *address, char **host, int *port)
823 char *pos = strchr (address, ':');
825 if (pos == NULL || pos == address)
828 *host = (char *)g_malloc (pos - address + 1);
829 strncpy (*host, address, pos - address);
830 (*host) [pos - address] = '\0';
832 *port = atoi (pos + 1);
840 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
841 fprintf (stderr, "Available options:\n");
842 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
843 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
844 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
845 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
846 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
847 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
848 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
849 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
850 fprintf (stderr, " setpgid=y/n\t\t\tWhether to call setpid(0, 0) after startup.\n");
851 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
855 parse_flag (const char *option, char *flag)
857 if (!strcmp (flag, "y"))
859 else if (!strcmp (flag, "n"))
862 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
869 mono_debugger_agent_parse_options (char *options)
876 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
877 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
881 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
883 options = g_strdup_printf ("%s,%s", options, extra);
885 agent_config.enabled = TRUE;
886 agent_config.suspend = TRUE;
887 agent_config.server = FALSE;
888 agent_config.defer = FALSE;
889 agent_config.address = NULL;
891 //agent_config.log_level = 10;
893 args = g_strsplit (options, ",", -1);
894 for (ptr = args; ptr && *ptr; ptr ++) {
897 if (strncmp (arg, "transport=", 10) == 0) {
898 agent_config.transport = g_strdup (arg + 10);
899 } else if (strncmp (arg, "address=", 8) == 0) {
900 agent_config.address = g_strdup (arg + 8);
901 } else if (strncmp (arg, "loglevel=", 9) == 0) {
902 agent_config.log_level = atoi (arg + 9);
903 } else if (strncmp (arg, "logfile=", 8) == 0) {
904 agent_config.log_file = g_strdup (arg + 8);
905 } else if (strncmp (arg, "suspend=", 8) == 0) {
906 agent_config.suspend = parse_flag ("suspend", arg + 8);
907 } else if (strncmp (arg, "server=", 7) == 0) {
908 agent_config.server = parse_flag ("server", arg + 7);
909 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
910 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
911 } else if (strncmp (arg, "onthrow=", 8) == 0) {
912 /* We support multiple onthrow= options */
913 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
914 } else if (strncmp (arg, "onthrow", 7) == 0) {
915 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
916 } else if (strncmp (arg, "help", 4) == 0) {
919 } else if (strncmp (arg, "timeout=", 8) == 0) {
920 agent_config.timeout = atoi (arg + 8);
921 } else if (strncmp (arg, "launch=", 7) == 0) {
922 agent_config.launch = g_strdup (arg + 7);
923 } else if (strncmp (arg, "embedding=", 10) == 0) {
924 agent_config.embedding = atoi (arg + 10) == 1;
925 } else if (strncmp (arg, "keepalive=", 10) == 0) {
926 agent_config.keepalive = atoi (arg + 10);
927 } else if (strncmp (arg, "setpgid=", 8) == 0) {
928 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
935 if (agent_config.server && !agent_config.suspend) {
936 /* Waiting for deferred attachment */
937 agent_config.defer = TRUE;
938 if (agent_config.address == NULL) {
939 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (mono_process_current_pid () % 1000));
943 //agent_config.log_level = 0;
945 if (agent_config.transport == NULL) {
946 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
950 if (agent_config.address == NULL && !agent_config.server) {
951 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
956 if (!strcmp (agent_config.transport, "dt_socket")) {
957 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
958 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
965 mono_debugger_agent_init (void)
967 mono_coop_mutex_init_recursive (&debug_mutex);
969 if (!agent_config.enabled)
974 /* Need to know whenever a thread has acquired the loader mutex */
975 mono_loader_lock_track_ownership (TRUE);
977 event_requests = g_ptr_array_new ();
979 mono_coop_mutex_init (&debugger_thread_exited_mutex);
980 mono_coop_cond_init (&debugger_thread_exited_cond);
982 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
983 mono_profiler_set_events ((MonoProfileFlags)(MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS));
984 mono_profiler_install_runtime_initialized (runtime_initialized);
985 mono_profiler_install_appdomain (NULL, appdomain_load, appdomain_start_unload, appdomain_unload);
986 mono_profiler_install_thread (thread_startup, thread_end);
987 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
988 mono_profiler_install_jit_end (jit_end);
990 mono_native_tls_alloc (&debugger_tls_id, NULL);
992 /* Needed by the hash_table_new_type () call below */
993 mono_gc_base_init ();
995 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_DEBUGGER, "thread-to-tls table");
996 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls, MONO_ROOT_SOURCE_DEBUGGER, "thread-to-tls table");
998 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread table");
999 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread table");
1001 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");
1002 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread object table");
1004 pending_assembly_loads = g_ptr_array_new ();
1005 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
1007 log_level = agent_config.log_level;
1009 embedding = agent_config.embedding;
1010 disconnected = TRUE;
1012 if (agent_config.log_file) {
1013 log_file = fopen (agent_config.log_file, "w+");
1015 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
1024 breakpoints_init ();
1027 mini_get_debug_options ()->gen_sdb_seq_points = TRUE;
1029 * This is needed because currently we don't handle liveness info.
1031 mini_get_debug_options ()->mdb_optimizations = TRUE;
1033 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
1034 /* This is needed because we can't set local variables in registers yet */
1035 mono_disable_optimizations (MONO_OPT_LINEARS);
1039 * The stack walk done from thread_interrupt () needs to be signal safe, but it
1040 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
1041 * safe (#3411). So load AOT info eagerly when the debugger is running as a
1044 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
1047 if (agent_config.setpgid)
1051 if (!agent_config.onuncaught && !agent_config.onthrow)
1052 finish_agent_init (TRUE);
1056 * finish_agent_init:
1058 * Finish the initialization of the agent. This involves connecting the transport
1059 * and starting the agent thread. This is either done at startup, or
1060 * in response to some event like an unhandled exception.
1063 finish_agent_init (gboolean on_startup)
1067 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
1070 if (agent_config.launch) {
1073 // FIXME: Generated address
1074 // FIXME: Races with transport_connect ()
1076 argv [0] = agent_config.launch;
1077 argv [1] = agent_config.transport;
1078 argv [2] = agent_config.address;
1081 res = g_spawn_async_with_pipes (NULL, argv, NULL, (GSpawnFlags)0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1083 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1088 transport_connect (agent_config.address);
1091 /* Do some which is usually done after sending the VMStart () event */
1092 vm_start_event_sent = TRUE;
1093 start_debugger_thread ();
1098 mono_debugger_agent_cleanup (void)
1103 stop_debugger_thread ();
1105 breakpoints_cleanup ();
1114 #ifndef DISABLE_SOCKET_TRANSPORT
1119 * recv() + handle incomplete reads and EINTR
1122 socket_transport_recv (void *buf, int len)
1128 static gint64 last_keepalive;
1135 res = recv (fd, (char *) buf + total, len - total, flags);
1138 if (agent_config.keepalive) {
1139 gboolean need_keepalive = FALSE;
1140 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1141 need_keepalive = TRUE;
1142 } else if (res == -1) {
1143 /* This could happen if recv () is interrupted repeatedly */
1144 msecs = mono_msec_ticks ();
1145 if (msecs - last_keepalive >= agent_config.keepalive) {
1146 need_keepalive = TRUE;
1147 last_keepalive = msecs;
1150 if (need_keepalive) {
1151 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1155 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1163 set_keepalive (void)
1168 if (!agent_config.keepalive || !conn_fd)
1171 tv.tv_sec = agent_config.keepalive / 1000;
1172 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1174 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1175 g_assert (result >= 0);
1179 socket_transport_accept (int socket_fd)
1182 conn_fd = accept (socket_fd, NULL, NULL);
1185 if (conn_fd == -1) {
1186 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1188 DEBUG_PRINTF (1, "Accepted connection from client, connection fd=%d.\n", conn_fd);
1195 socket_transport_send (void *data, int len)
1202 res = send (conn_fd, data, len, 0);
1203 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1214 * socket_transport_connect:
1216 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1219 socket_transport_connect (const char *address)
1221 MonoAddressInfo *result;
1222 MonoAddressEntry *rp;
1223 int sfd = -1, s, res;
1227 if (agent_config.address) {
1228 res = parse_address (agent_config.address, &host, &port);
1229 g_assert (res == 0);
1240 mono_network_init ();
1242 /* Obtain address(es) matching host/port */
1243 s = mono_get_address_info (host, port, MONO_HINT_UNSPECIFIED, &result);
1245 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, s); // FIXME add portable error conversion functions
1250 if (agent_config.server) {
1251 /* Wait for a connection */
1253 struct sockaddr_in addr;
1256 /* No address, generate one */
1257 sfd = socket (AF_INET, SOCK_STREAM, 0);
1260 /* This will bind the socket to a random port */
1261 res = listen (sfd, 16);
1263 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1268 addrlen = sizeof (addr);
1269 memset (&addr, 0, sizeof (addr));
1270 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1271 g_assert (res == 0);
1273 host = (char*)"127.0.0.1";
1274 port = ntohs (addr.sin_port);
1276 /* Emit the address to stdout */
1277 /* FIXME: Should print another interface, not localhost */
1278 printf ("%s:%d\n", host, port);
1280 /* Listen on the provided address */
1281 for (rp = result->entries; rp != NULL; rp = rp->next) {
1282 MonoSocketAddress sockaddr;
1286 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1288 sfd = socket (rp->family, rp->socktype,
1293 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1296 res = bind (sfd, &sockaddr.addr, sock_len);
1300 res = listen (sfd, 16);
1307 mono_free_address_info (result);
1310 if (agent_config.defer)
1313 DEBUG_PRINTF (1, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout);
1315 if (agent_config.timeout) {
1320 tv.tv_usec = agent_config.timeout * 1000;
1322 FD_SET (sfd, &readfds);
1325 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1329 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1334 conn_fd = socket_transport_accept (sfd);
1338 DEBUG_PRINTF (1, "Accepted connection from client, socket fd=%d.\n", conn_fd);
1340 /* Connect to the specified address */
1341 /* FIXME: Respect the timeout */
1342 for (rp = result->entries; rp != NULL; rp = rp->next) {
1343 MonoSocketAddress sockaddr;
1346 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1348 sfd = socket (rp->family, rp->socktype,
1354 res = connect (sfd, &sockaddr.addr, sock_len);
1358 break; /* Success */
1366 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1372 mono_free_address_info (result);
1375 if (!transport_handshake ())
1380 socket_transport_close1 (void)
1382 /* This will interrupt the agent thread */
1383 /* Close the read part only so it can still send back replies */
1384 /* Also shut down the connection listener so that we can exit normally */
1386 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1387 shutdown (conn_fd, SD_BOTH);
1388 shutdown (listen_fd, SD_BOTH);
1389 closesocket (listen_fd);
1391 shutdown (conn_fd, SHUT_RD);
1392 shutdown (listen_fd, SHUT_RDWR);
1400 socket_transport_close2 (void)
1403 shutdown (conn_fd, SD_BOTH);
1405 shutdown (conn_fd, SHUT_RDWR);
1410 register_socket_transport (void)
1412 DebuggerTransport trans;
1414 trans.name = "dt_socket";
1415 trans.connect = socket_transport_connect;
1416 trans.close1 = socket_transport_close1;
1417 trans.close2 = socket_transport_close2;
1418 trans.send = socket_transport_send;
1419 trans.recv = socket_transport_recv;
1421 register_transport (&trans);
1425 * socket_fd_transport_connect:
1429 socket_fd_transport_connect (const char *address)
1433 res = sscanf (address, "%d", &conn_fd);
1435 fprintf (stderr, "debugger-agent: socket-fd transport address is invalid: '%s'\n", address);
1439 if (!transport_handshake ())
1444 register_socket_fd_transport (void)
1446 DebuggerTransport trans;
1448 /* This is the same as the 'dt_socket' transport, but receives an already connected socket fd */
1449 trans.name = "socket-fd";
1450 trans.connect = socket_fd_transport_connect;
1451 trans.close1 = socket_transport_close1;
1452 trans.close2 = socket_transport_close2;
1453 trans.send = socket_transport_send;
1454 trans.recv = socket_transport_recv;
1456 register_transport (&trans);
1459 #endif /* DISABLE_SOCKET_TRANSPORT */
1465 #define MAX_TRANSPORTS 16
1467 static DebuggerTransport *transport;
1469 static DebuggerTransport transports [MAX_TRANSPORTS];
1470 static int ntransports;
1473 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1476 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1478 register_transport (trans);
1482 register_transport (DebuggerTransport *trans)
1484 g_assert (ntransports < MAX_TRANSPORTS);
1486 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1491 transport_init (void)
1495 #ifndef DISABLE_SOCKET_TRANSPORT
1496 register_socket_transport ();
1497 register_socket_fd_transport ();
1500 for (i = 0; i < ntransports; ++i) {
1501 if (!strcmp (agent_config.transport, transports [i].name))
1504 if (i == ntransports) {
1505 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1506 for (i = 0; i < ntransports; ++i)
1507 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1508 fprintf (stderr, "\n");
1511 transport = &transports [i];
1515 transport_connect (const char *address)
1517 transport->connect (address);
1521 transport_close1 (void)
1523 transport->close1 ();
1527 transport_close2 (void)
1529 transport->close2 ();
1533 transport_send (void *buf, int len)
1535 return transport->send (buf, len);
1539 transport_recv (void *buf, int len)
1541 return transport->recv (buf, len);
1545 mono_debugger_agent_transport_handshake (void)
1547 return transport_handshake ();
1551 transport_handshake (void)
1553 char handshake_msg [128];
1557 disconnected = TRUE;
1559 /* Write handshake message */
1560 sprintf (handshake_msg, "DWP-Handshake");
1563 res = transport_send (handshake_msg, strlen (handshake_msg));
1564 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1566 g_assert (res != -1);
1569 res = transport_recv (buf, strlen (handshake_msg));
1570 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg)) != 0)) {
1571 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1576 * To support older clients, the client sends its protocol version after connecting
1577 * using a command. Until that is received, default to our protocol version.
1579 major_version = MAJOR_VERSION;
1580 minor_version = MINOR_VERSION;
1581 protocol_version_set = FALSE;
1583 #ifndef DISABLE_SOCKET_TRANSPORT
1584 // FIXME: Move this somewhere else
1586 * Set TCP_NODELAY on the socket so the client receives events/command
1587 * results immediately.
1591 int result = setsockopt (conn_fd,
1596 g_assert (result >= 0);
1602 disconnected = FALSE;
1607 stop_debugger_thread (void)
1612 transport_close1 ();
1615 * Wait for the thread to exit.
1617 * If we continue with the shutdown without waiting for it, then the client might
1618 * not receive an answer to its last command like a resume.
1620 if (!is_debugger_thread ()) {
1622 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
1623 if (!debugger_thread_exited)
1624 mono_coop_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1625 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
1626 } while (!debugger_thread_exited);
1629 transport_close2 ();
1633 start_debugger_thread (void)
1635 debugger_thread_handle = mono_threads_create_thread (debugger_thread, NULL, NULL, NULL);
1636 g_assert (debugger_thread_handle);
1640 * Functions to decode protocol data
1644 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1647 g_assert (*endbuf <= limit);
1652 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1655 g_assert (*endbuf <= limit);
1657 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1660 static inline gint64
1661 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1663 guint32 high = decode_int (buf, &buf, limit);
1664 guint32 low = decode_int (buf, &buf, limit);
1668 return ((((guint64)high) << 32) | ((guint64)low));
1672 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1674 return decode_int (buf, endbuf, limit);
1678 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1680 int len = decode_int (buf, &buf, limit);
1688 s = (char *)g_malloc (len + 1);
1691 memcpy (s, buf, len);
1700 * Functions to encode protocol data
1704 buffer_init (Buffer *buf, int size)
1706 buf->buf = (guint8 *)g_malloc (size);
1708 buf->end = buf->buf + size;
1712 buffer_len (Buffer *buf)
1714 return buf->p - buf->buf;
1718 buffer_make_room (Buffer *buf, int size)
1720 if (buf->end - buf->p < size) {
1721 int new_size = buf->end - buf->buf + size + 32;
1722 guint8 *p = (guint8 *)g_realloc (buf->buf, new_size);
1723 size = buf->p - buf->buf;
1726 buf->end = buf->buf + new_size;
1731 buffer_add_byte (Buffer *buf, guint8 val)
1733 buffer_make_room (buf, 1);
1739 buffer_add_short (Buffer *buf, guint32 val)
1741 buffer_make_room (buf, 2);
1742 buf->p [0] = (val >> 8) & 0xff;
1743 buf->p [1] = (val >> 0) & 0xff;
1748 buffer_add_int (Buffer *buf, guint32 val)
1750 buffer_make_room (buf, 4);
1751 buf->p [0] = (val >> 24) & 0xff;
1752 buf->p [1] = (val >> 16) & 0xff;
1753 buf->p [2] = (val >> 8) & 0xff;
1754 buf->p [3] = (val >> 0) & 0xff;
1759 buffer_add_long (Buffer *buf, guint64 l)
1761 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1762 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1766 buffer_add_id (Buffer *buf, int id)
1768 buffer_add_int (buf, (guint64)id);
1772 buffer_add_data (Buffer *buf, guint8 *data, int len)
1774 buffer_make_room (buf, len);
1775 memcpy (buf->p, data, len);
1780 buffer_add_string (Buffer *buf, const char *str)
1785 buffer_add_int (buf, 0);
1788 buffer_add_int (buf, len);
1789 buffer_add_data (buf, (guint8*)str, len);
1794 buffer_add_buffer (Buffer *buf, Buffer *data)
1796 buffer_add_data (buf, data->buf, buffer_len (data));
1800 buffer_free (Buffer *buf)
1806 send_packet (int command_set, int command, Buffer *data)
1812 id = InterlockedIncrement (&packet_id);
1814 len = data->p - data->buf + 11;
1815 buffer_init (&buf, len);
1816 buffer_add_int (&buf, len);
1817 buffer_add_int (&buf, id);
1818 buffer_add_byte (&buf, 0); /* flags */
1819 buffer_add_byte (&buf, command_set);
1820 buffer_add_byte (&buf, command);
1821 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1823 res = transport_send (buf.buf, len);
1831 send_reply_packets (int npackets, ReplyPacket *packets)
1838 for (i = 0; i < npackets; ++i)
1839 len += buffer_len (packets [i].data) + 11;
1840 buffer_init (&buf, len);
1841 for (i = 0; i < npackets; ++i) {
1842 buffer_add_int (&buf, buffer_len (packets [i].data) + 11);
1843 buffer_add_int (&buf, packets [i].id);
1844 buffer_add_byte (&buf, 0x80); /* flags */
1845 buffer_add_byte (&buf, (packets [i].error >> 8) & 0xff);
1846 buffer_add_byte (&buf, packets [i].error);
1847 buffer_add_buffer (&buf, packets [i].data);
1850 res = transport_send (buf.buf, len);
1858 send_reply_packet (int id, int error, Buffer *data)
1862 memset (&packet, 0, sizeof (ReplyPacket));
1864 packet.error = error;
1867 return send_reply_packets (1, &packet);
1871 send_buffered_reply_packets (void)
1875 send_reply_packets (nreply_packets, reply_packets);
1876 for (i = 0; i < nreply_packets; ++i)
1877 buffer_free (reply_packets [i].data);
1878 DEBUG_PRINTF (1, "[dbg] Sent %d buffered reply packets [at=%lx].\n", nreply_packets, (long)mono_100ns_ticks () / 10000);
1883 buffer_reply_packet (int id, int error, Buffer *data)
1887 if (nreply_packets == 128)
1888 send_buffered_reply_packets ();
1890 p = &reply_packets [nreply_packets];
1893 p->data = g_new0 (Buffer, 1);
1894 buffer_init (p->data, buffer_len (data));
1895 buffer_add_buffer (p->data, data);
1904 * Represents an object accessible by the debugger client.
1907 /* Unique id used in the wire protocol to refer to objects */
1910 * A weakref gc handle pointing to the object. The gc handle is used to
1911 * detect if the object was garbage collected.
1916 /* Maps objid -> ObjRef */
1917 /* Protected by the loader lock */
1918 static GHashTable *objrefs;
1919 /* Protected by the loader lock */
1920 static GHashTable *obj_to_objref;
1921 /* Protected by the dbg lock */
1922 static MonoGHashTable *suspended_objs;
1925 free_objref (gpointer value)
1927 ObjRef *o = (ObjRef *)value;
1929 mono_gchandle_free (o->handle);
1937 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1938 obj_to_objref = g_hash_table_new (NULL, NULL);
1939 suspended_objs = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_DEBUGGER, "suspended objects table");
1940 MONO_GC_REGISTER_ROOT_FIXED (suspended_objs, MONO_ROOT_SOURCE_DEBUGGER, "suspended objects table");
1944 objrefs_cleanup (void)
1946 g_hash_table_destroy (objrefs);
1951 * Return an ObjRef for OBJ.
1954 get_objref (MonoObject *obj)
1957 GSList *reflist = NULL, *l;
1963 if (suspend_count) {
1965 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1968 mono_g_hash_table_insert (suspended_objs, obj, NULL);
1972 mono_loader_lock ();
1974 /* FIXME: The tables can grow indefinitely */
1976 if (mono_gc_is_moving ()) {
1978 * Objects can move, so use a hash table mapping hash codes to lists of
1979 * ObjRef structures.
1981 hash = mono_object_hash (obj);
1983 reflist = (GSList *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1984 for (l = reflist; l; l = l->next) {
1985 ref = (ObjRef *)l->data;
1986 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1987 mono_loader_unlock ();
1992 /* Use a hash table with masked pointers to internalize object references */
1993 ref = (ObjRef *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1994 /* ref might refer to a different object with the same addr which was GCd */
1995 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1996 mono_loader_unlock ();
2001 ref = g_new0 (ObjRef, 1);
2002 ref->id = InterlockedIncrement (&objref_id);
2003 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
2005 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
2007 if (mono_gc_is_moving ()) {
2008 reflist = g_slist_append (reflist, ref);
2009 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
2011 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
2014 mono_loader_unlock ();
2020 true_pred (gpointer key, gpointer value, gpointer user_data)
2026 clear_suspended_objs (void)
2029 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
2034 get_objid (MonoObject *obj)
2039 return get_objref (obj)->id;
2043 * Set OBJ to the object identified by OBJID.
2044 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
2048 get_object_allow_null (int objid, MonoObject **obj)
2058 return ERR_INVALID_OBJECT;
2060 mono_loader_lock ();
2062 ref = (ObjRef *)g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
2065 *obj = mono_gchandle_get_target (ref->handle);
2066 mono_loader_unlock ();
2068 return ERR_INVALID_OBJECT;
2071 mono_loader_unlock ();
2072 return ERR_INVALID_OBJECT;
2077 get_object (int objid, MonoObject **obj)
2079 ErrorCode err = get_object_allow_null (objid, obj);
2081 if (err != ERR_NONE)
2084 return ERR_INVALID_OBJECT;
2089 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
2091 return decode_id (buf, endbuf, limit);
2095 buffer_add_objid (Buffer *buf, MonoObject *o)
2097 buffer_add_id (buf, get_objid (o));
2116 * Represents a runtime structure accessible to the debugger client
2119 /* Unique id used in the wire protocol */
2121 /* Domain of the runtime structure, NULL if the domain was unloaded */
2128 MonoAssembly *assembly;
2129 MonoClassField *field;
2131 MonoProperty *property;
2136 /* Maps runtime structure -> Id */
2137 /* Protected by the dbg lock */
2138 GHashTable *val_to_id [ID_NUM];
2139 /* Classes whose class load event has been sent */
2140 /* Protected by the loader lock */
2141 GHashTable *loaded_classes;
2142 /* Maps MonoClass->GPtrArray of file names */
2143 GHashTable *source_files;
2144 /* Maps source file basename -> GSList of classes */
2145 GHashTable *source_file_to_class;
2146 /* Same with ignore-case */
2147 GHashTable *source_file_to_class_ignorecase;
2151 /* Protected by the dbg lock */
2152 static GPtrArray *ids [ID_NUM];
2159 for (i = 0; i < ID_NUM; ++i)
2160 ids [i] = g_ptr_array_new ();
2168 for (i = 0; i < ID_NUM; ++i) {
2170 for (j = 0; j < ids [i]->len; ++j)
2171 g_free (g_ptr_array_index (ids [i], j));
2172 g_ptr_array_free (ids [i], TRUE);
2179 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2181 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2183 GHashTableIter iter;
2184 GPtrArray *file_names;
2189 for (i = 0; i < ID_NUM; ++i)
2190 if (info->val_to_id [i])
2191 g_hash_table_destroy (info->val_to_id [i]);
2192 g_hash_table_destroy (info->loaded_classes);
2194 g_hash_table_iter_init (&iter, info->source_files);
2195 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2196 for (i = 0; i < file_names->len; ++i)
2197 g_free (g_ptr_array_index (file_names, i));
2198 g_ptr_array_free (file_names, TRUE);
2201 g_hash_table_iter_init (&iter, info->source_file_to_class);
2202 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2207 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2208 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2216 domain_jit_info (domain)->agent_info = NULL;
2218 /* Clear ids referencing structures in the domain */
2220 for (i = 0; i < ID_NUM; ++i) {
2222 for (j = 0; j < ids [i]->len; ++j) {
2223 Id *id = (Id *)g_ptr_array_index (ids [i], j);
2224 if (id->domain == domain)
2231 mono_loader_lock ();
2232 g_hash_table_remove (domains, domain);
2233 mono_loader_unlock ();
2236 static AgentDomainInfo*
2237 get_agent_domain_info (MonoDomain *domain)
2239 AgentDomainInfo *info = NULL;
2241 mono_domain_lock (domain);
2243 info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2245 info = g_new0 (AgentDomainInfo, 1);
2246 domain_jit_info (domain)->agent_info = info;
2247 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2248 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2249 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2250 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2253 mono_domain_unlock (domain);
2259 get_id (MonoDomain *domain, IdType type, gpointer val)
2262 AgentDomainInfo *info;
2267 info = get_agent_domain_info (domain);
2271 if (info->val_to_id [type] == NULL)
2272 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2274 id = (Id *)g_hash_table_lookup (info->val_to_id [type], val);
2280 id = g_new0 (Id, 1);
2282 id->id = ids [type]->len + 1;
2283 id->domain = domain;
2286 g_hash_table_insert (info->val_to_id [type], val, id);
2287 g_ptr_array_add (ids [type], id);
2294 static inline gpointer
2295 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, ErrorCode *err)
2299 int id = decode_id (buf, endbuf, limit);
2308 // FIXME: error handling
2310 g_assert (id > 0 && id <= ids [type]->len);
2312 res = (Id *)g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2315 if (res->domain == NULL || res->domain->state == MONO_APPDOMAIN_UNLOADED) {
2316 DEBUG_PRINTF (1, "ERR_UNLOADED, id=%d, type=%d.\n", id, type);
2317 *err = ERR_UNLOADED;
2322 *domain = res->domain;
2324 return res->data.val;
2328 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2330 int id = get_id (domain, type, val);
2332 buffer_add_id (buf, id);
2336 static inline MonoClass*
2337 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2341 klass = (MonoClass *)decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2342 if (G_UNLIKELY (log_level >= 2) && klass) {
2345 s = mono_type_full_name (&klass->byval_arg);
2346 DEBUG_PRINTF (2, "[dbg] recv class [%s]\n", s);
2352 static inline MonoAssembly*
2353 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2355 return (MonoAssembly *)decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2358 static inline MonoImage*
2359 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2361 return (MonoImage *)decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2364 static inline MonoMethod*
2365 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2369 m = (MonoMethod *)decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2370 if (G_UNLIKELY (log_level >= 2) && m) {
2373 s = mono_method_full_name (m, TRUE);
2374 DEBUG_PRINTF (2, "[dbg] recv method [%s]\n", s);
2380 static inline MonoClassField*
2381 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2383 return (MonoClassField *)decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2386 static inline MonoDomain*
2387 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2389 return (MonoDomain *)decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2392 static inline MonoProperty*
2393 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2395 return (MonoProperty *)decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2399 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2401 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2402 if (G_UNLIKELY (log_level >= 2) && klass) {
2405 s = mono_type_full_name (&klass->byval_arg);
2406 if (is_debugger_thread ())
2407 DEBUG_PRINTF (2, "[dbg] send class [%s]\n", s);
2409 DEBUG_PRINTF (2, "[%p] send class [%s]\n", (gpointer) (gsize) mono_native_thread_id_get (), s);
2415 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2417 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2418 if (G_UNLIKELY (log_level >= 2) && method) {
2421 s = mono_method_full_name (method, 1);
2422 DEBUG_PRINTF (2, "[dbg] send method [%s]\n", s);
2428 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2432 id = buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2433 if (G_UNLIKELY (log_level >= 2) && assembly)
2434 DEBUG_PRINTF (2, "[dbg] send assembly [%s][%s][%d]\n", assembly->aname.name, domain->friendly_name, id);
2438 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2440 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2444 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2446 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2450 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2452 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2456 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2458 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2461 static void invoke_method (void);
2468 * save_thread_context:
2470 * Set CTX as the current threads context which is used for computing stack traces.
2471 * This function is signal-safe.
2474 save_thread_context (MonoContext *ctx)
2476 DebuggerTlsData *tls;
2478 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2482 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2484 mono_thread_state_init_from_current (&tls->context);
2487 /* Number of threads suspended */
2489 * If this is equal to the size of thread_to_tls, the runtime is considered
2492 static gint32 threads_suspend_count;
2494 static MonoCoopMutex suspend_mutex;
2496 /* Cond variable used to wait for suspend_count becoming 0 */
2497 static MonoCoopCond suspend_cond;
2499 /* Semaphore used to wait for a thread becoming suspended */
2500 static MonoCoopSem suspend_sem;
2505 mono_coop_mutex_init (&suspend_mutex);
2506 mono_coop_cond_init (&suspend_cond);
2507 mono_coop_sem_init (&suspend_sem, 0);
2512 StackFrameInfo last_frame;
2513 gboolean last_frame_set;
2517 } GetLastFrameUserData;
2520 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2522 GetLastFrameUserData *data = (GetLastFrameUserData *)user_data;
2524 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE || info->type == FRAME_TYPE_TRAMPOLINE)
2527 if (!data->last_frame_set) {
2528 /* Store the last frame */
2529 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2530 data->last_frame_set = TRUE;
2533 /* Store the context/lmf for the frame above the last frame */
2534 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2535 data->lmf = info->lmf;
2536 data->domain = info->domain;
2542 copy_unwind_state_from_frame_data (MonoThreadUnwindState *to, GetLastFrameUserData *data, gpointer jit_tls)
2544 memcpy (&to->ctx, &data->ctx, sizeof (MonoContext));
2546 to->unwind_data [MONO_UNWIND_DATA_DOMAIN] = data->domain;
2547 to->unwind_data [MONO_UNWIND_DATA_LMF] = data->lmf;
2548 to->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = jit_tls;
2555 * Process interruption of a thread. This should be signal safe.
2557 * This always runs in the debugger thread.
2560 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, MonoJitInfo *ji)
2563 MonoNativeThreadId tid;
2567 ip = MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx);
2568 tid = mono_thread_info_get_tid (info);
2570 // FIXME: Races when the thread leaves managed code before hitting a single step
2573 if (ji && !ji->is_trampoline) {
2574 /* Running managed code, will be suspended by the single step code */
2575 DEBUG_PRINTF (1, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip);
2578 * Running native code, will be suspended when it returns to/enters
2579 * managed code. Treat it as already suspended.
2580 * This might interrupt the code in process_single_step_inner (), we use the
2581 * tls->suspending flag to avoid races when that happens.
2583 if (!tls->suspended && !tls->suspending) {
2584 GetLastFrameUserData data;
2586 // FIXME: printf is not signal safe, but this is only used during
2587 // debugger debugging
2589 DEBUG_PRINTF (1, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip);
2590 //save_thread_context (&ctx);
2593 /* Already terminated */
2597 * We are in a difficult position: we want to be able to provide stack
2598 * traces for this thread, but we can't use the current ctx+lmf, since
2599 * the thread is still running, so it might return to managed code,
2600 * making these invalid.
2601 * So we start a stack walk and save the first frame, along with the
2602 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2603 * suspended when it returns to managed code, so the parent's ctx should
2606 data.last_frame_set = FALSE;
2607 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, mono_thread_info_get_suspend_state (info), MONO_UNWIND_SIGNAL_SAFE, &data);
2608 if (data.last_frame_set) {
2609 gpointer jit_tls = ((MonoThreadInfo*)tls->thread->thread_info)->jit_data;
2611 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2613 copy_unwind_state_from_frame_data (&tls->async_state, &data, jit_tls);
2614 copy_unwind_state_from_frame_data (&tls->context, &data, jit_tls);
2616 tls->async_state.valid = FALSE;
2619 mono_memory_barrier ();
2621 tls->suspended = TRUE;
2622 mono_coop_sem_post (&suspend_sem);
2628 * reset_native_thread_suspend_state:
2630 * Reset the suspended flag and state on native threads
2633 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2635 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2637 if (!tls->really_suspended && tls->suspended) {
2638 tls->suspended = FALSE;
2640 * The thread might still be running if it was executing native code, so the state won't be invalided by
2641 * suspend_current ().
2643 tls->context.valid = FALSE;
2644 tls->async_state.valid = FALSE;
2645 invalidate_frames (tls);
2650 DebuggerTlsData *tls;
2651 gboolean valid_info;
2654 static SuspendThreadResult
2655 debugger_interrupt_critical (MonoThreadInfo *info, gpointer user_data)
2657 InterruptData *data = (InterruptData *)user_data;
2660 data->valid_info = TRUE;
2661 ji = mono_jit_info_table_find_internal (
2662 (MonoDomain *)mono_thread_info_get_suspend_state (info)->unwind_data [MONO_UNWIND_DATA_DOMAIN],
2663 (char *)MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx),
2667 /* This is signal safe */
2668 thread_interrupt (data->tls, info, ji);
2669 return MonoResumeThread;
2675 * Notify a thread that it needs to suspend.
2678 notify_thread (gpointer key, gpointer value, gpointer user_data)
2680 MonoInternalThread *thread = (MonoInternalThread *)key;
2681 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2682 MonoNativeThreadId tid = MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid);
2684 if (mono_native_thread_id_equals (mono_native_thread_id_get (), tid) || tls->terminated)
2687 DEBUG_PRINTF (1, "[%p] Interrupting %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2689 /* This is _not_ equivalent to mono_thread_internal_abort () */
2690 InterruptData interrupt_data = { 0 };
2691 interrupt_data.tls = tls;
2693 mono_thread_info_safe_suspend_and_run ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE, debugger_interrupt_critical, &interrupt_data);
2694 if (!interrupt_data.valid_info) {
2695 DEBUG_PRINTF (1, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2697 * Attached thread which died without detaching.
2699 tls->terminated = TRUE;
2704 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2706 guint8 *ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
2710 if (mono_loader_lock_is_owned_by_self ()) {
2712 * Shortcut for the check in suspend_current (). This speeds up processing
2713 * when executing long running code inside the loader lock, i.e. assembly load
2719 if (is_debugger_thread ())
2722 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2723 if (suspend_count - tls->resume_count > 0)
2724 tls->suspending = TRUE;
2726 DEBUG_PRINTF (1, "[%p] Received single step event for suspending.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2728 if (suspend_count - tls->resume_count == 0) {
2730 * We are executing a single threaded invoke but the single step for
2731 * suspending is still active.
2732 * FIXME: This slows down single threaded invokes.
2734 DEBUG_PRINTF (1, "[%p] Ignored during single threaded invoke.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2738 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2740 /* Can't suspend in these methods */
2741 method = jinfo_get_method (ji);
2742 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2745 save_thread_context (ctx);
2753 * Increase the suspend count of the VM. While the suspend count is greater
2754 * than 0, runtime threads are suspended at certain points during execution.
2759 mono_loader_lock ();
2761 mono_coop_mutex_lock (&suspend_mutex);
2765 DEBUG_PRINTF (1, "[%p] Suspending vm...\n", (gpointer) (gsize) mono_native_thread_id_get ());
2767 if (suspend_count == 1) {
2768 // FIXME: Is it safe to call this inside the lock ?
2769 start_single_stepping ();
2770 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2773 mono_coop_mutex_unlock (&suspend_mutex);
2775 if (suspend_count == 1)
2777 * Suspend creation of new threadpool threads, since they cannot run
2779 mono_threadpool_suspend ();
2781 mono_loader_unlock ();
2787 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2793 g_assert (is_debugger_thread ());
2795 mono_loader_lock ();
2797 mono_coop_mutex_lock (&suspend_mutex);
2799 g_assert (suspend_count > 0);
2802 DEBUG_PRINTF (1, "[%p] Resuming vm, suspend count=%d...\n", (gpointer) (gsize) mono_native_thread_id_get (), suspend_count);
2804 if (suspend_count == 0) {
2805 // FIXME: Is it safe to call this inside the lock ?
2806 stop_single_stepping ();
2807 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2810 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2811 mono_coop_cond_broadcast (&suspend_cond);
2813 mono_coop_mutex_unlock (&suspend_mutex);
2814 //g_assert (err == 0);
2816 if (suspend_count == 0)
2817 mono_threadpool_resume ();
2819 mono_loader_unlock ();
2825 * Resume just one thread.
2828 resume_thread (MonoInternalThread *thread)
2830 DebuggerTlsData *tls;
2832 g_assert (is_debugger_thread ());
2834 mono_loader_lock ();
2836 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
2839 mono_coop_mutex_lock (&suspend_mutex);
2841 g_assert (suspend_count > 0);
2843 DEBUG_PRINTF (1, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid);
2845 tls->resume_count += suspend_count;
2848 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2849 * but only the one whose resume_count field is > 0 will be resumed.
2851 mono_coop_cond_broadcast (&suspend_cond);
2853 mono_coop_mutex_unlock (&suspend_mutex);
2854 //g_assert (err == 0);
2856 mono_loader_unlock ();
2860 free_frames (StackFrame **frames, int nframes)
2864 for (i = 0; i < nframes; ++i) {
2865 if (frames [i]->jit)
2866 mono_debug_free_method_jit_info (frames [i]->jit);
2867 g_free (frames [i]);
2873 invalidate_frames (DebuggerTlsData *tls)
2876 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2879 free_frames (tls->frames, tls->frame_count);
2880 tls->frame_count = 0;
2883 free_frames (tls->restore_frames, tls->restore_frame_count);
2884 tls->restore_frame_count = 0;
2885 tls->restore_frames = NULL;
2891 * Suspend the current thread until the runtime is resumed. If the thread has a
2892 * pending invoke, then the invoke is executed before this function returns.
2895 suspend_current (void)
2897 DebuggerTlsData *tls;
2899 g_assert (!is_debugger_thread ());
2901 if (mono_loader_lock_is_owned_by_self ()) {
2903 * If we own the loader mutex, can't suspend until we release it, since the
2904 * whole runtime can deadlock otherwise.
2909 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2912 mono_coop_mutex_lock (&suspend_mutex);
2914 tls->suspending = FALSE;
2915 tls->really_suspended = TRUE;
2917 if (!tls->suspended) {
2918 tls->suspended = TRUE;
2919 mono_coop_sem_post (&suspend_sem);
2922 DEBUG_PRINTF (1, "[%p] Suspended.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2924 while (suspend_count - tls->resume_count > 0) {
2925 mono_coop_cond_wait (&suspend_cond, &suspend_mutex);
2928 tls->suspended = FALSE;
2929 tls->really_suspended = FALSE;
2931 threads_suspend_count --;
2933 mono_coop_mutex_unlock (&suspend_mutex);
2935 DEBUG_PRINTF (1, "[%p] Resumed.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2937 if (tls->pending_invoke) {
2938 /* Save the original context */
2939 tls->pending_invoke->has_ctx = TRUE;
2940 tls->pending_invoke->ctx = tls->context.ctx;
2945 /* The frame info becomes invalid after a resume */
2946 tls->context.valid = FALSE;
2947 tls->async_state.valid = FALSE;
2948 invalidate_frames (tls);
2952 count_thread (gpointer key, gpointer value, gpointer user_data)
2954 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2956 if (!tls->suspended && !tls->terminated)
2957 *(int*)user_data = *(int*)user_data + 1;
2961 count_threads_to_wait_for (void)
2965 mono_loader_lock ();
2966 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2967 mono_loader_unlock ();
2975 * Wait until the runtime is completely suspended.
2978 wait_for_suspend (void)
2980 int nthreads, nwait, err;
2981 gboolean waited = FALSE;
2983 // FIXME: Threads starting/stopping ?
2984 mono_loader_lock ();
2985 nthreads = mono_g_hash_table_size (thread_to_tls);
2986 mono_loader_unlock ();
2989 nwait = count_threads_to_wait_for ();
2991 DEBUG_PRINTF (1, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads);
2992 err = mono_coop_sem_wait (&suspend_sem, MONO_SEM_FLAGS_NONE);
2993 g_assert (err == 0);
3001 DEBUG_PRINTF (1, "%d threads suspended.\n", nthreads);
3007 * Return whenever the runtime is suspended.
3012 return count_threads_to_wait_for () == 0;
3016 no_seq_points_found (MonoMethod *method, int offset)
3019 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3021 printf ("Unable to find seq points for method '%s', offset 0x%x.\n", mono_method_full_name (method, TRUE), offset);
3025 DebuggerTlsData *tls;
3027 } ComputeFramesUserData;
3030 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3032 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3034 MonoMethod *method, *actual_method, *api_method;
3038 if (info->type != FRAME_TYPE_MANAGED) {
3039 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3040 /* Mark the last frame as an invoke frame */
3042 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3048 method = jinfo_get_method (info->ji);
3050 method = info->method;
3051 actual_method = info->actual_method;
3052 api_method = method;
3057 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3060 if (info->il_offset == -1) {
3061 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3062 if (ud->frames == NULL) {
3063 if (mono_find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL, &sp))
3064 info->il_offset = sp.il_offset;
3066 if (info->il_offset == -1)
3067 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3070 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);
3072 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3073 if (!CHECK_PROTOCOL_VERSION (2, 17))
3074 /* Older clients can't handle this flag */
3076 api_method = mono_marshal_method_from_wrapper (method);
3079 actual_method = api_method;
3080 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3083 frame = g_new0 (StackFrame, 1);
3084 frame->method = method;
3085 frame->actual_method = actual_method;
3086 frame->api_method = api_method;
3087 frame->il_offset = info->il_offset;
3088 frame->native_offset = info->native_offset;
3089 frame->flags = flags;
3090 frame->ji = info->ji;
3091 if (info->reg_locations)
3092 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3095 frame->has_ctx = TRUE;
3097 frame->domain = info->domain;
3099 ud->frames = g_slist_append (ud->frames, frame);
3105 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3107 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3110 * 'tls->filter_ctx' is the location of the throw site.
3112 * mono_walk_stack() will never actually hit the throw site, but unwind
3113 * directly from the filter to the call site; we abort stack unwinding here
3114 * once this happens and resume from the throw site.
3117 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3120 return process_frame (info, ctx, user_data);
3124 * Return a malloc-ed list of StackFrame structures.
3127 compute_frame_info_from (MonoInternalThread *thread, DebuggerTlsData *tls, MonoThreadUnwindState *state, int *out_nframes)
3129 ComputeFramesUserData user_data;
3130 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3135 user_data.tls = tls;
3136 user_data.frames = NULL;
3138 mono_walk_stack_with_state (process_frame, state, opts, &user_data);
3140 nframes = g_slist_length (user_data.frames);
3141 res = g_new0 (StackFrame*, nframes);
3142 l = user_data.frames;
3143 for (i = 0; i < nframes; ++i) {
3144 res [i] = (StackFrame *)l->data;
3147 *out_nframes = nframes;
3153 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3155 ComputeFramesUserData user_data;
3157 int i, findex, new_frame_count;
3158 StackFrame **new_frames, *f;
3159 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3161 // FIXME: Locking on tls
3162 if (tls->frames && tls->frames_up_to_date)
3165 DEBUG_PRINTF (1, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid);
3167 user_data.tls = tls;
3168 user_data.frames = NULL;
3169 if (tls->terminated) {
3170 tls->frame_count = 0;
3172 } if (!tls->really_suspended && tls->async_state.valid) {
3173 /* Have to use the state saved by the signal handler */
3174 process_frame (&tls->async_last_frame, NULL, &user_data);
3175 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3176 } else if (tls->filter_state.valid) {
3178 * We are inside an exception filter.
3180 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3182 if (tls->context.valid)
3183 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3185 * After that, we resume unwinding from the location where the exception has been thrown.
3187 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3188 } else if (tls->context.valid) {
3189 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3192 tls->frame_count = 0;
3196 new_frame_count = g_slist_length (user_data.frames);
3197 new_frames = g_new0 (StackFrame*, new_frame_count);
3199 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3200 f = (StackFrame *)tmp->data;
3203 * Reuse the id for already existing stack frames, so invokes don't invalidate
3204 * the still valid stack frames.
3206 for (i = 0; i < tls->frame_count; ++i) {
3207 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3208 f->id = tls->frames [i]->id;
3213 if (i >= tls->frame_count)
3214 f->id = InterlockedIncrement (&frame_id);
3216 new_frames [findex ++] = f;
3219 g_slist_free (user_data.frames);
3221 invalidate_frames (tls);
3223 tls->frames = new_frames;
3224 tls->frame_count = new_frame_count;
3225 tls->frames_up_to_date = TRUE;
3229 * GHFunc to emit an appdomain creation event
3230 * @param key Don't care
3231 * @param value A loaded appdomain
3232 * @param user_data Don't care
3235 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3237 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3238 g_hash_table_foreach (get_agent_domain_info ((MonoDomain *)value)->loaded_classes, emit_type_load, NULL);
3242 * GHFunc to emit a thread start event
3243 * @param key A thread id
3244 * @param value A thread object
3245 * @param user_data Don't care
3248 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3250 if (!mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (GPOINTER_TO_UINT (key)), debugger_thread_id))
3251 process_profiler_event (EVENT_KIND_THREAD_START, value);
3255 * GFunc to emit an assembly load event
3256 * @param value A loaded assembly
3257 * @param user_data Don't care
3260 emit_assembly_load (gpointer value, gpointer user_data)
3262 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3266 * GFunc to emit a type load event
3267 * @param value A loaded type
3268 * @param user_data Don't care
3271 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3273 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3277 strdup_tolower (char *s)
3282 for (p = s2; *p; ++p)
3288 * Same as g_path_get_basename () but handles windows paths as well,
3289 * which can occur in .mdb files created by pdb2mdb.
3292 dbg_path_get_basename (const char *filename)
3296 if (!filename || strchr (filename, '/') || !strchr (filename, '\\'))
3297 return g_path_get_basename (filename);
3301 /* No separator -> filename */
3302 r = strrchr (filename, '\\');
3304 return g_strdup (filename);
3306 /* Trailing slash, remove component */
3308 char *copy = g_strdup (filename);
3309 copy [r-filename] = 0;
3310 r = strrchr (copy, '\\');
3314 return g_strdup ("/");
3316 r = g_strdup (&r[1]);
3321 return g_strdup (&r[1]);
3325 init_jit_info_dbg_attrs (MonoJitInfo *ji)
3327 static MonoClass *hidden_klass, *step_through_klass, *non_user_klass;
3329 MonoCustomAttrInfo *ainfo;
3331 if (ji->dbg_attrs_inited)
3335 hidden_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3337 if (!step_through_klass)
3338 step_through_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3340 if (!non_user_klass)
3341 non_user_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute");
3343 ainfo = mono_custom_attrs_from_method_checked (jinfo_get_method (ji), &error);
3344 mono_error_cleanup (&error); /* FIXME don't swallow the error? */
3346 if (mono_custom_attrs_has_attr (ainfo, hidden_klass))
3347 ji->dbg_hidden = TRUE;
3348 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3349 ji->dbg_step_through = TRUE;
3350 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3351 ji->dbg_non_user_code = TRUE;
3352 mono_custom_attrs_free (ainfo);
3355 ainfo = mono_custom_attrs_from_class_checked (jinfo_get_method (ji)->klass, &error);
3356 mono_error_cleanup (&error); /* FIXME don't swallow the error? */
3358 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3359 ji->dbg_step_through = TRUE;
3360 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3361 ji->dbg_non_user_code = TRUE;
3362 mono_custom_attrs_free (ainfo);
3365 mono_memory_barrier ();
3366 ji->dbg_attrs_inited = TRUE;
3374 * create_event_list:
3376 * Return a list of event request ids matching EVENT, starting from REQS, which
3377 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3379 * We return request ids, instead of requests, to simplify threading, since
3380 * requests could be deleted anytime when the loader lock is not held.
3381 * LOCKING: Assumes the loader lock is held.
3384 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3387 GSList *events = NULL;
3389 *suspend_policy = SUSPEND_POLICY_NONE;
3392 reqs = event_requests;
3397 for (i = 0; i < reqs->len; ++i) {
3398 EventRequest *req = (EventRequest *)g_ptr_array_index (reqs, i);
3399 if (req->event_kind == event) {
3400 gboolean filtered = FALSE;
3403 for (j = 0; j < req->nmodifiers; ++j) {
3404 Modifier *mod = &req->modifiers [j];
3406 if (mod->kind == MOD_KIND_COUNT) {
3408 if (mod->data.count > 0) {
3409 if (mod->data.count > 0) {
3411 if (mod->data.count == 0)
3415 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3416 if (mod->data.thread != mono_thread_internal_current ())
3418 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3419 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3421 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3423 if (ei->caught && !mod->caught)
3425 if (!ei->caught && !mod->uncaught)
3427 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3429 gboolean found = FALSE;
3430 MonoAssembly **assemblies = mod->data.assemblies;
3433 for (k = 0; assemblies [k]; ++k)
3434 if (assemblies [k] == jinfo_get_method (ji)->klass->image->assembly)
3439 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3440 gpointer iter = NULL;
3442 MonoDebugSourceInfo *sinfo;
3443 char *source_file, *s;
3444 gboolean found = FALSE;
3446 GPtrArray *source_file_list;
3448 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3449 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3452 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, NULL, NULL, NULL);
3453 for (i = 0; i < source_file_list->len; ++i) {
3454 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
3456 * Do a case-insesitive match by converting the file name to
3459 s = strdup_tolower (sinfo->source_file);
3460 if (g_hash_table_lookup (mod->data.source_files, s))
3463 char *s2 = dbg_path_get_basename (sinfo->source_file);
3464 char *s3 = strdup_tolower (s2);
3466 if (g_hash_table_lookup (mod->data.source_files, s3))
3473 g_ptr_array_free (source_file_list, TRUE);
3478 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3481 s = mono_type_full_name (&ei->klass->byval_arg);
3482 if (!g_hash_table_lookup (mod->data.type_names, s))
3485 } else if (mod->kind == MOD_KIND_STEP) {
3486 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3487 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3488 !strcmp (jinfo_get_method (ji)->name, ".cctor") &&
3489 (jinfo_get_method (ji) != ((SingleStepReq*)req->info)->start_method))
3491 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3492 init_jit_info_dbg_attrs (ji);
3496 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3497 init_jit_info_dbg_attrs (ji);
3498 if (ji->dbg_step_through)
3501 if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3502 init_jit_info_dbg_attrs (ji);
3503 if (ji->dbg_non_user_code)
3510 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3511 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3516 /* Send a VM START/DEATH event by default */
3517 if (event == EVENT_KIND_VM_START)
3518 events = g_slist_append (events, GINT_TO_POINTER (0));
3519 if (event == EVENT_KIND_VM_DEATH)
3520 events = g_slist_append (events, GINT_TO_POINTER (0));
3525 static G_GNUC_UNUSED const char*
3526 event_to_string (EventKind event)
3529 case EVENT_KIND_VM_START: return "VM_START";
3530 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3531 case EVENT_KIND_THREAD_START: return "THREAD_START";
3532 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3533 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3534 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3535 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3536 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3537 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3538 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3539 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3540 case EVENT_KIND_STEP: return "STEP";
3541 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3542 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3543 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3544 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3545 case EVENT_KIND_USER_LOG: return "USER_LOG";
3547 g_assert_not_reached ();
3555 * Send an event to the client, suspending the vm if needed.
3556 * LOCKING: Since this can suspend the calling thread, no locks should be held
3558 * The EVENTS list is freed by this function.
3561 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3565 MonoDomain *domain = mono_domain_get ();
3566 MonoThread *thread = NULL;
3567 MonoObject *keepalive_obj = NULL;
3568 gboolean send_success = FALSE;
3573 DEBUG_PRINTF (2, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event));
3577 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3578 // FIXME: We miss those events
3579 DEBUG_PRINTF (2, "VM start event not sent yet: dropping %s\n", event_to_string (event));
3583 if (vm_death_event_sent) {
3584 DEBUG_PRINTF (2, "VM death event has been sent: dropping %s\n", event_to_string (event));
3588 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3589 DEBUG_PRINTF (2, "Mono runtime is shutting down: dropping %s\n", event_to_string (event));
3594 DEBUG_PRINTF (2, "Debugger client is not connected: dropping %s\n", event_to_string (event));
3598 if (event == EVENT_KIND_KEEPALIVE)
3599 suspend_policy = SUSPEND_POLICY_NONE;
3604 if (agent_config.defer) {
3605 /* Make sure the thread id is always set when doing deferred debugging */
3606 if (is_debugger_thread ()) {
3607 /* Don't suspend on events from the debugger thread */
3608 suspend_policy = SUSPEND_POLICY_NONE;
3609 thread = mono_thread_get_main ();
3611 else thread = mono_thread_current ();
3613 if (is_debugger_thread () && event != EVENT_KIND_VM_DEATH)
3614 // FIXME: Send these with a NULL thread, don't suspend the current thread
3619 nevents = g_slist_length (events);
3620 buffer_init (&buf, 128);
3621 buffer_add_byte (&buf, suspend_policy);
3622 buffer_add_int (&buf, nevents);
3624 for (l = events; l; l = l->next) {
3625 buffer_add_byte (&buf, event); // event kind
3626 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3630 if (event == EVENT_KIND_VM_DEATH) {
3634 thread = mono_thread_current ();
3636 if (event == EVENT_KIND_VM_START && arg != NULL)
3637 thread = (MonoThread *)arg;
3640 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3643 case EVENT_KIND_THREAD_START:
3644 case EVENT_KIND_THREAD_DEATH:
3646 case EVENT_KIND_APPDOMAIN_CREATE:
3647 case EVENT_KIND_APPDOMAIN_UNLOAD:
3648 buffer_add_domainid (&buf, (MonoDomain *)arg);
3650 case EVENT_KIND_METHOD_ENTRY:
3651 case EVENT_KIND_METHOD_EXIT:
3652 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3654 case EVENT_KIND_ASSEMBLY_LOAD:
3655 buffer_add_assemblyid (&buf, domain, (MonoAssembly *)arg);
3657 case EVENT_KIND_ASSEMBLY_UNLOAD: {
3658 DebuggerTlsData *tls;
3660 /* The domain the assembly belonged to is not equal to the current domain */
3661 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3663 g_assert (tls->domain_unloading);
3665 buffer_add_assemblyid (&buf, tls->domain_unloading, (MonoAssembly *)arg);
3668 case EVENT_KIND_TYPE_LOAD:
3669 buffer_add_typeid (&buf, domain, (MonoClass *)arg);
3671 case EVENT_KIND_BREAKPOINT:
3672 case EVENT_KIND_STEP:
3673 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3674 buffer_add_long (&buf, il_offset);
3676 case EVENT_KIND_VM_START:
3677 buffer_add_domainid (&buf, mono_get_root_domain ());
3679 case EVENT_KIND_VM_DEATH:
3680 if (CHECK_PROTOCOL_VERSION (2, 27))
3681 buffer_add_int (&buf, mono_environment_exitcode_get ());
3683 case EVENT_KIND_EXCEPTION: {
3684 EventInfo *ei = (EventInfo *)arg;
3685 buffer_add_objid (&buf, ei->exc);
3687 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3688 * later after the suspension. (#12494).
3690 keepalive_obj = ei->exc;
3693 case EVENT_KIND_USER_BREAK:
3695 case EVENT_KIND_USER_LOG: {
3696 EventInfo *ei = (EventInfo *)arg;
3697 buffer_add_int (&buf, ei->level);
3698 buffer_add_string (&buf, ei->category ? ei->category : "");
3699 buffer_add_string (&buf, ei->message ? ei->message : "");
3702 case EVENT_KIND_KEEPALIVE:
3703 suspend_policy = SUSPEND_POLICY_NONE;
3706 g_assert_not_reached ();
3710 if (event == EVENT_KIND_VM_START) {
3711 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3712 if (!agent_config.defer)
3713 start_debugger_thread ();
3716 if (event == EVENT_KIND_VM_DEATH) {
3717 vm_death_event_sent = TRUE;
3718 suspend_policy = SUSPEND_POLICY_NONE;
3721 if (mono_runtime_is_shutting_down ())
3722 suspend_policy = SUSPEND_POLICY_NONE;
3724 if (suspend_policy != SUSPEND_POLICY_NONE) {
3726 * Save the thread context and start suspending before sending the packet,
3727 * since we could be receiving the resume request before send_packet ()
3730 save_thread_context (ctx);
3734 /* This will keep this object alive */
3735 get_objref (keepalive_obj);
3738 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3742 g_slist_free (events);
3745 if (!send_success) {
3746 DEBUG_PRINTF (2, "Sending command %s failed.\n", event_to_string (event));
3750 if (event == EVENT_KIND_VM_START) {
3751 vm_start_event_sent = TRUE;
3754 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);
3756 switch (suspend_policy) {
3757 case SUSPEND_POLICY_NONE:
3759 case SUSPEND_POLICY_ALL:
3762 case SUSPEND_POLICY_EVENT_THREAD:
3766 g_assert_not_reached ();
3771 process_profiler_event (EventKind event, gpointer arg)
3775 EventInfo ei, *ei_arg = NULL;
3777 if (event == EVENT_KIND_TYPE_LOAD) {
3778 ei.klass = (MonoClass *)arg;
3782 mono_loader_lock ();
3783 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3784 mono_loader_unlock ();
3786 process_event (event, arg, 0, NULL, events, suspend_policy);
3790 runtime_initialized (MonoProfiler *prof)
3792 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3793 if (agent_config.defer)
3794 start_debugger_thread ();
3798 runtime_shutdown (MonoProfiler *prof)
3800 process_profiler_event (EVENT_KIND_VM_DEATH, NULL);
3802 mono_debugger_agent_cleanup ();
3806 thread_startup (MonoProfiler *prof, uintptr_t tid)
3808 MonoInternalThread *thread = mono_thread_internal_current ();
3809 MonoInternalThread *old_thread;
3810 DebuggerTlsData *tls;
3812 if (mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (tid), debugger_thread_id))
3815 g_assert (mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (tid), MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid)));
3817 mono_loader_lock ();
3818 old_thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3819 mono_loader_unlock ();
3821 if (thread == old_thread) {
3823 * For some reason, thread_startup () might be called for the same thread
3824 * multiple times (attach ?).
3826 DEBUG_PRINTF (1, "[%p] thread_start () called multiple times for %p, ignored.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3830 * thread_end () might not be called for some threads, and the tid could
3833 DEBUG_PRINTF (1, "[%p] Removing stale data for tid %p.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3834 mono_loader_lock ();
3835 mono_g_hash_table_remove (thread_to_tls, old_thread);
3836 mono_g_hash_table_remove (tid_to_thread, GUINT_TO_POINTER (tid));
3837 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3838 mono_loader_unlock ();
3842 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3844 // FIXME: Free this somewhere
3845 tls = g_new0 (DebuggerTlsData, 1);
3846 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread, MONO_ROOT_SOURCE_DEBUGGER, "debugger thread reference");
3847 tls->thread = thread;
3848 mono_native_tls_set_value (debugger_tls_id, tls);
3850 DEBUG_PRINTF (1, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3852 mono_loader_lock ();
3853 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3854 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3855 mono_g_hash_table_insert (tid_to_thread_obj, GUINT_TO_POINTER (tid), mono_thread_current ());
3856 mono_loader_unlock ();
3858 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3861 * suspend_vm () could have missed this thread, so wait for a resume.
3867 thread_end (MonoProfiler *prof, uintptr_t tid)
3869 MonoInternalThread *thread;
3870 DebuggerTlsData *tls = NULL;
3872 mono_loader_lock ();
3873 thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3875 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3876 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
3878 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3879 tls->terminated = TRUE;
3880 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3881 MONO_GC_UNREGISTER_ROOT (tls->thread);
3885 mono_loader_unlock ();
3887 /* We might be called for threads started before we registered the start callback */
3889 DEBUG_PRINTF (1, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3891 if (mono_native_thread_id_equals (mono_native_thread_id_get (), MONO_UINT_TO_NATIVE_THREAD_ID (tid))
3892 && !mono_native_tls_get_value (debugger_tls_id)
3895 * This can happen on darwin since we deregister threads using pthread dtors.
3896 * process_profiler_event () and the code it calls cannot handle a null TLS value.
3901 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3906 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3908 mono_loader_lock ();
3909 g_hash_table_insert (domains, domain, domain);
3910 mono_loader_unlock ();
3912 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3916 appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain)
3918 DebuggerTlsData *tls;
3920 /* This might be called during shutdown on the debugger thread from the CMD_VM_EXIT code */
3921 if (is_debugger_thread ())
3925 * Remember the currently unloading appdomain as it is needed to generate
3926 * proper ids for unloading assemblies.
3928 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3930 tls->domain_unloading = domain;
3934 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3936 DebuggerTlsData *tls;
3938 if (is_debugger_thread ())
3941 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3943 tls->domain_unloading = NULL;
3945 clear_breakpoints_for_domain (domain);
3947 mono_loader_lock ();
3948 /* Invalidate each thread's frame stack */
3949 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3950 mono_loader_unlock ();
3952 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3956 * invalidate_each_thread:
3958 * A GHFunc to invalidate frames.
3959 * value must be a DebuggerTlsData*
3962 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3964 invalidate_frames ((DebuggerTlsData *)value);
3968 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3970 /* Sent later in jit_end () */
3972 g_ptr_array_add (pending_assembly_loads, assembly);
3977 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3979 if (is_debugger_thread ())
3982 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3984 clear_event_requests_for_assembly (assembly);
3985 clear_types_for_assembly (assembly);
3989 send_type_load (MonoClass *klass)
3991 gboolean type_load = FALSE;
3992 MonoDomain *domain = mono_domain_get ();
3993 AgentDomainInfo *info = NULL;
3995 info = get_agent_domain_info (domain);
3997 mono_loader_lock ();
3999 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
4001 g_hash_table_insert (info->loaded_classes, klass, klass);
4004 mono_loader_unlock ();
4007 emit_type_load (klass, klass, NULL);
4011 * Emit load events for all types currently loaded in the domain.
4012 * Takes the loader and domain locks.
4013 * user_data is unused.
4016 send_types_for_domain (MonoDomain *domain, void *user_data)
4018 AgentDomainInfo *info = NULL;
4020 info = get_agent_domain_info (domain);
4023 mono_loader_lock ();
4024 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4025 mono_loader_unlock ();
4029 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
4032 * We emit type load events when the first method of the type is JITted,
4033 * since the class load profiler callbacks might be called with the
4034 * loader lock held. They could also occur in the debugger thread.
4035 * Same for assembly load events.
4038 MonoAssembly *assembly = NULL;
4040 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4042 if (pending_assembly_loads->len > 0) {
4043 assembly = (MonoAssembly *)g_ptr_array_index (pending_assembly_loads, 0);
4044 g_ptr_array_remove_index (pending_assembly_loads, 0);
4049 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4055 send_type_load (method->klass);
4058 add_pending_breakpoints (method, jinfo);
4062 * BREAKPOINTS/SINGLE STEPPING
4066 * Contains information about an inserted breakpoint.
4069 long il_offset, native_offset;
4073 } BreakpointInstance;
4076 * Contains generic information about a breakpoint.
4080 * The method where the breakpoint is placed. Can be NULL in which case it
4081 * is inserted into every method. This is used to implement method entry/
4082 * exit events. Can be a generic method definition, in which case the
4083 * breakpoint is inserted into every instance.
4089 * A list of BreakpointInstance structures describing where the breakpoint
4090 * was inserted. There could be more than one because of
4091 * generics/appdomains/method entry/exit.
4093 GPtrArray *children;
4096 /* List of breakpoints */
4097 /* Protected by the loader lock */
4098 static GPtrArray *breakpoints;
4099 /* Maps breakpoint locations to the number of breakpoints at that location */
4100 static GHashTable *bp_locs;
4103 breakpoints_init (void)
4105 breakpoints = g_ptr_array_new ();
4106 bp_locs = g_hash_table_new (NULL, NULL);
4110 * insert_breakpoint:
4112 * Insert the breakpoint described by BP into the method described by
4116 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4119 BreakpointInstance *inst;
4120 SeqPointIterator it;
4121 gboolean it_has_sp = FALSE;
4124 mono_error_init (error);
4126 mono_seq_point_iterator_init (&it, seq_points);
4127 while (mono_seq_point_iterator_next (&it)) {
4128 if (it.seq_point.il_offset == bp->il_offset) {
4136 * The set of IL offsets with seq points doesn't completely match the
4137 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4139 mono_seq_point_iterator_init (&it, seq_points);
4140 while (mono_seq_point_iterator_next (&it)) {
4141 if (it.seq_point.il_offset != METHOD_ENTRY_IL_OFFSET &&
4142 it.seq_point.il_offset != METHOD_EXIT_IL_OFFSET &&
4143 it.seq_point.il_offset + 1 == bp->il_offset) {
4151 char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d", mono_method_full_name (jinfo_get_method (ji), TRUE), bp->il_offset);
4153 mono_seq_point_iterator_init (&it, seq_points);
4154 while (mono_seq_point_iterator_next (&it))
4155 DEBUG_PRINTF (1, "%d\n", it.seq_point.il_offset);
4158 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4159 g_warning ("%s", s);
4163 g_warning ("%s", s);
4169 inst = g_new0 (BreakpointInstance, 1);
4170 inst->il_offset = it.seq_point.il_offset;
4171 inst->native_offset = it.seq_point.native_offset;
4172 inst->ip = (guint8*)ji->code_start + it.seq_point.native_offset;
4174 inst->domain = domain;
4176 mono_loader_lock ();
4178 g_ptr_array_add (bp->children, inst);
4180 mono_loader_unlock ();
4183 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4184 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4187 if (it.seq_point.native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4188 DEBUG_PRINTF (1, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset);
4189 } else if (count == 0) {
4190 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4191 mono_arch_set_breakpoint (ji, inst->ip);
4197 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);
4201 remove_breakpoint (BreakpointInstance *inst)
4203 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4205 MonoJitInfo *ji = inst->ji;
4206 guint8 *ip = inst->ip;
4209 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4210 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4213 g_assert (count > 0);
4215 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4216 mono_arch_clear_breakpoint (ji, ip);
4217 DEBUG_PRINTF (1, "[dbg] Clear breakpoint at %s [%p].\n", mono_method_full_name (jinfo_get_method (ji), TRUE), ip);
4225 * This doesn't take any locks.
4227 static inline gboolean
4228 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4234 if (method == bp->method)
4236 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4239 if (bp->method->is_inflated && method->is_inflated) {
4240 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4241 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4243 /* Open generic methods should match closed generic methods of the same class */
4244 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4245 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4246 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4248 /* FIXME: Handle !mvar */
4249 if (t1->type != MONO_TYPE_MVAR)
4260 * add_pending_breakpoints:
4262 * Insert pending breakpoints into the newly JITted method METHOD.
4265 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4268 MonoSeqPointInfo *seq_points;
4270 MonoMethod *jmethod;
4275 domain = mono_domain_get ();
4277 mono_loader_lock ();
4279 for (i = 0; i < breakpoints->len; ++i) {
4280 MonoBreakpoint *bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4281 gboolean found = FALSE;
4283 if (!bp_matches_method (bp, method))
4286 for (j = 0; j < bp->children->len; ++j) {
4287 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4294 MonoMethod *declaring = NULL;
4296 jmethod = jinfo_get_method (ji);
4297 if (jmethod->is_inflated)
4298 declaring = mono_method_get_declaring_generic_method (jmethod);
4300 mono_domain_lock (domain);
4301 seq_points = (MonoSeqPointInfo *)g_hash_table_lookup (domain_jit_info (domain)->seq_points, jmethod);
4302 if (!seq_points && declaring)
4303 seq_points = (MonoSeqPointInfo *)g_hash_table_lookup (domain_jit_info (domain)->seq_points, declaring);
4304 mono_domain_unlock (domain);
4306 /* Could be AOT code */
4308 g_assert (seq_points);
4310 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4314 mono_loader_unlock ();
4318 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4324 mono_error_init (error);
4326 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4330 /* Might be AOTed code */
4331 mono_class_init (method->klass);
4332 code = mono_aot_get_method_checked (domain, method, &oerror);
4334 mono_error_assert_ok (&oerror);
4335 ji = mono_jit_info_table_find (domain, (char *)code);
4340 insert_breakpoint (seq_points, domain, ji, bp, error);
4344 clear_breakpoint (MonoBreakpoint *bp);
4349 * Set a breakpoint at IL_OFFSET in METHOD.
4350 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4351 * METHOD can also be a generic method definition, in which case a breakpoint
4352 * is placed in all instances of the method.
4353 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4356 static MonoBreakpoint*
4357 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4360 GHashTableIter iter, iter2;
4363 MonoSeqPointInfo *seq_points;
4365 GPtrArray *method_domains;
4366 GPtrArray *method_seq_points;
4370 mono_error_init (error);
4373 // - suspend/resume the vm to prevent code patching problems
4374 // - multiple breakpoints on the same location
4375 // - dynamic methods
4378 bp = g_new0 (MonoBreakpoint, 1);
4379 bp->method = method;
4380 bp->il_offset = il_offset;
4382 bp->children = g_ptr_array_new ();
4384 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);
4386 methods = g_ptr_array_new ();
4387 method_domains = g_ptr_array_new ();
4388 method_seq_points = g_ptr_array_new ();
4390 mono_loader_lock ();
4391 g_hash_table_iter_init (&iter, domains);
4392 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4393 mono_domain_lock (domain);
4394 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4395 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4396 if (bp_matches_method (bp, m)) {
4397 /* Save the info locally to simplify the code inside the domain lock */
4398 g_ptr_array_add (methods, m);
4399 g_ptr_array_add (method_domains, domain);
4400 g_ptr_array_add (method_seq_points, seq_points);
4403 mono_domain_unlock (domain);
4406 for (i = 0; i < methods->len; ++i) {
4407 m = (MonoMethod *)g_ptr_array_index (methods, i);
4408 domain = (MonoDomain *)g_ptr_array_index (method_domains, i);
4409 seq_points = (MonoSeqPointInfo *)g_ptr_array_index (method_seq_points, i);
4410 set_bp_in_method (domain, m, seq_points, bp, error);
4413 g_ptr_array_add (breakpoints, bp);
4414 mono_loader_unlock ();
4416 g_ptr_array_free (methods, TRUE);
4417 g_ptr_array_free (method_domains, TRUE);
4418 g_ptr_array_free (method_seq_points, TRUE);
4420 if (error && !mono_error_ok (error)) {
4421 clear_breakpoint (bp);
4429 clear_breakpoint (MonoBreakpoint *bp)
4433 // FIXME: locking, races
4434 for (i = 0; i < bp->children->len; ++i) {
4435 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, i);
4437 remove_breakpoint (inst);
4442 mono_loader_lock ();
4443 g_ptr_array_remove (breakpoints, bp);
4444 mono_loader_unlock ();
4446 g_ptr_array_free (bp->children, TRUE);
4451 breakpoints_cleanup (void)
4455 mono_loader_lock ();
4457 while (i < event_requests->len) {
4458 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
4460 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4461 clear_breakpoint ((MonoBreakpoint *)req->info);
4462 g_ptr_array_remove_index_fast (event_requests, i);
4469 for (i = 0; i < breakpoints->len; ++i)
4470 g_free (g_ptr_array_index (breakpoints, i));
4472 g_ptr_array_free (breakpoints, TRUE);
4473 g_hash_table_destroy (bp_locs);
4478 mono_loader_unlock ();
4482 * clear_breakpoints_for_domain:
4484 * Clear breakpoint instances which reference DOMAIN.
4487 clear_breakpoints_for_domain (MonoDomain *domain)
4491 /* This could be called after shutdown */
4495 mono_loader_lock ();
4496 for (i = 0; i < breakpoints->len; ++i) {
4497 MonoBreakpoint *bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4500 while (j < bp->children->len) {
4501 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4503 if (inst->domain == domain) {
4504 remove_breakpoint (inst);
4508 g_ptr_array_remove_index_fast (bp->children, j);
4514 mono_loader_unlock ();
4518 * ss_calculate_framecount:
4520 * Ensure DebuggerTlsData fields are filled out.
4522 static void ss_calculate_framecount (DebuggerTlsData *tls, MonoContext *ctx)
4524 if (!tls->context.valid)
4525 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4526 compute_frame_info (tls->thread, tls);
4532 * Return FALSE if single stepping needs to continue.
4535 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp, DebuggerTlsData *tls, MonoContext *ctx)
4537 MonoDebugMethodInfo *minfo;
4538 MonoDebugSourceLocation *loc = NULL;
4539 gboolean hit = TRUE;
4542 if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK)) {
4544 * These seq points are inserted by the JIT after calls, step over needs to skip them.
4546 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);
4550 if ((req->depth == STEP_DEPTH_OVER || req->depth == STEP_DEPTH_OUT) && hit) {
4551 gboolean is_step_out = req->depth == STEP_DEPTH_OUT;
4553 ss_calculate_framecount (tls, ctx);
4555 // Because functions can call themselves recursively, we need to make sure we're stopping at the right stack depth.
4556 // In case of step out, the target is the frame *enclosing* the one where the request was made.
4557 int target_frames = req->nframes + (is_step_out ? -1 : 0);
4558 if (req->nframes > 0 && tls->frame_count > 0 && tls->frame_count > target_frames) {
4559 /* Hit the breakpoint in a recursive call, don't halt */
4560 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");
4565 if (req->depth == STEP_DEPTH_INTO && req->size == STEP_SIZE_MIN && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) && ss_req->start_method){
4566 method = jinfo_get_method (ji);
4567 ss_calculate_framecount (tls, ctx);
4568 if (ss_req->start_method == method && req->nframes && tls->frame_count == req->nframes) {//Check also frame count(could be recursion)
4569 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);
4574 if (req->size != STEP_SIZE_LINE)
4577 /* Have to check whenever a different source line was reached */
4578 method = jinfo_get_method (ji);
4579 minfo = mono_debug_lookup_method (method);
4582 loc = mono_debug_method_lookup_location (minfo, sp->il_offset);
4585 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);
4586 ss_req->last_method = method;
4588 } else if (loc && method == ss_req->last_method && loc->row == ss_req->last_line) {
4589 ss_calculate_framecount (tls, ctx);
4590 if (tls->frame_count == req->nframes) { // If the frame has changed we're clearly not on the same source line.
4591 DEBUG_PRINTF (1, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer) (gsize) mono_native_thread_id_get (), loc->row);
4597 ss_req->last_method = method;
4598 ss_req->last_line = loc->row;
4599 mono_debug_free_source_location (loc);
4606 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4608 return bp->method && bp->method->klass->image->assembly == assembly;
4612 process_breakpoint_inner (DebuggerTlsData *tls, gboolean from_signal)
4616 int i, j, suspend_policy;
4617 guint32 native_offset;
4619 BreakpointInstance *inst;
4620 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4621 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4622 EventKind kind = EVENT_KIND_BREAKPOINT;
4623 MonoContext *ctx = &tls->restore_state.ctx;
4625 MonoSeqPointInfo *info;
4629 // FIXME: Speed this up
4631 ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
4632 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4633 g_assert (ji && !ji->is_trampoline);
4634 method = jinfo_get_method (ji);
4636 /* Compute the native offset of the breakpoint from the ip */
4637 native_offset = ip - (guint8*)ji->code_start;
4640 * Skip the instruction causing the breakpoint signal.
4643 mono_arch_skip_breakpoint (ctx, ji);
4645 if (method->wrapper_type || tls->disable_breakpoints)
4648 bp_reqs = g_ptr_array_new ();
4649 ss_reqs = g_ptr_array_new ();
4650 ss_reqs_orig = g_ptr_array_new ();
4652 mono_loader_lock ();
4655 * The ip points to the instruction causing the breakpoint event, which is after
4656 * the offset recorded in the seq point map, so find the prev seq point before ip.
4658 found_sp = mono_find_prev_seq_point_for_native_offset (mono_domain_get (), method, native_offset, &info, &sp);
4661 no_seq_points_found (method, native_offset);
4663 g_assert (found_sp);
4665 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);
4668 for (i = 0; i < breakpoints->len; ++i) {
4669 bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4674 for (j = 0; j < bp->children->len; ++j) {
4675 inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4676 if (inst->ji == ji && inst->il_offset == sp.il_offset && inst->native_offset == sp.native_offset) {
4677 if (bp->req->event_kind == EVENT_KIND_STEP) {
4678 g_ptr_array_add (ss_reqs_orig, bp->req);
4680 g_ptr_array_add (bp_reqs, bp->req);
4685 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4686 /* Maybe a method entry/exit event */
4687 if (sp.il_offset == METHOD_ENTRY_IL_OFFSET)
4688 kind = EVENT_KIND_METHOD_ENTRY;
4689 else if (sp.il_offset == METHOD_EXIT_IL_OFFSET)
4690 kind = EVENT_KIND_METHOD_EXIT;
4693 /* Process single step requests */
4694 for (i = 0; i < ss_reqs_orig->len; ++i) {
4695 EventRequest *req = (EventRequest *)g_ptr_array_index (ss_reqs_orig, i);
4696 SingleStepReq *ss_req = (SingleStepReq *)req->info;
4699 if (mono_thread_internal_current () != ss_req->thread)
4702 hit = ss_update (ss_req, ji, &sp, tls, ctx);
4704 g_ptr_array_add (ss_reqs, req);
4706 /* Start single stepping again from the current sequence point */
4707 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
4710 if (ss_reqs->len > 0)
4711 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4712 if (bp_reqs->len > 0)
4713 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4714 if (kind != EVENT_KIND_BREAKPOINT)
4715 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4717 mono_loader_unlock ();
4719 g_ptr_array_free (bp_reqs, TRUE);
4720 g_ptr_array_free (ss_reqs, TRUE);
4723 * FIXME: The first event will suspend, so the second will only be sent after the
4727 process_event (EVENT_KIND_STEP, method, 0, ctx, ss_events, suspend_policy);
4729 process_event (kind, method, 0, ctx, bp_events, suspend_policy);
4730 if (enter_leave_events)
4731 process_event (kind, method, 0, ctx, enter_leave_events, suspend_policy);
4734 /* Process a breakpoint/single step event after resuming from a signal handler */
4736 process_signal_event (void (*func) (DebuggerTlsData*, gboolean))
4738 DebuggerTlsData *tls;
4739 MonoThreadUnwindState orig_restore_state;
4742 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4743 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4744 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4745 mono_thread_state_init_from_monoctx (&tls->restore_state, &tls->handler_ctx);
4749 /* This is called when resuming from a signal handler, so it shouldn't return */
4750 memcpy (&ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4751 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4752 mono_restore_context (&ctx);
4753 g_assert_not_reached ();
4757 process_breakpoint (void)
4759 process_signal_event (process_breakpoint_inner);
4763 resume_from_signal_handler (void *sigctx, void *func)
4765 DebuggerTlsData *tls;
4768 /* Save the original context in TLS */
4769 // FIXME: This might not work on an altstack ?
4770 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4772 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer) (gsize) mono_native_thread_id_get ());
4775 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4776 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4777 // clob:c could be added to op_seq_point.
4779 mono_sigctx_to_monoctx (sigctx, &ctx);
4780 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4781 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4782 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4784 MONO_CONTEXT_SET_IP (&ctx, func);
4786 mono_monoctx_to_sigctx (&ctx, sigctx);
4788 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4789 mono_ppc_set_func_into_sigctx (sigctx, func);
4794 mono_debugger_agent_breakpoint_hit (void *sigctx)
4797 * We are called from a signal handler, and running code there causes all kinds of
4798 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4799 * So set up the signal context to return to the real breakpoint handler function.
4801 resume_from_signal_handler (sigctx, process_breakpoint);
4805 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4807 if (frame->managed) {
4808 *(MonoContext*)data = *ctx;
4817 * Called by System.Diagnostics.Debugger:Break ().
4820 mono_debugger_agent_user_break (void)
4822 if (agent_config.enabled) {
4827 /* Obtain a context */
4828 MONO_CONTEXT_SET_IP (&ctx, NULL);
4829 mono_walk_stack_with_ctx (user_break_cb, NULL, (MonoUnwindOptions)0, &ctx);
4830 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4832 mono_loader_lock ();
4833 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4834 mono_loader_unlock ();
4836 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4837 } else if (debug_options.native_debugger_break) {
4843 ss_depth_to_string (StepDepth depth)
4846 case STEP_DEPTH_OVER:
4848 case STEP_DEPTH_OUT:
4850 case STEP_DEPTH_INTO:
4853 g_assert_not_reached ();
4859 process_single_step_inner (DebuggerTlsData *tls, gboolean from_signal)
4864 int il_offset, suspend_policy;
4867 MonoContext *ctx = &tls->restore_state.ctx;
4870 MonoSeqPointInfo *info;
4872 ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
4874 /* Skip the instruction causing the single step */
4876 mono_arch_skip_single_step (ctx);
4878 if (suspend_count > 0) {
4879 /* Fastpath during invokes, see in process_suspend () */
4880 if (suspend_count - tls->resume_count == 0)
4882 process_suspend (tls, ctx);
4887 // FIXME: A suspend race
4890 if (mono_thread_internal_current () != ss_req->thread)
4893 if (log_level > 0) {
4894 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4896 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);
4899 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4900 g_assert (ji && !ji->is_trampoline);
4901 method = jinfo_get_method (ji);
4904 if (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4909 * Stopping in memset makes half-initialized vtypes visible.
4910 * Stopping in memcpy makes half-copied vtypes visible.
4912 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
4916 * This could be in ss_update method, but mono_find_next_seq_point_for_native_offset is pretty expensive method,
4917 * hence we prefer this check here.
4919 if (ss_req->user_assemblies) {
4920 gboolean found = FALSE;
4921 for (int k = 0; ss_req->user_assemblies[k]; k++)
4922 if (ss_req->user_assemblies[k] == method->klass->image->assembly) {
4932 * The ip points to the instruction causing the single step event, which is before
4933 * the offset recorded in the seq point map, so find the next seq point after ip.
4935 if (!mono_find_next_seq_point_for_native_offset (domain, method, (guint8*)ip - (guint8*)ji->code_start, &info, &sp))
4938 il_offset = sp.il_offset;
4940 if (!ss_update (ss_req, ji, &sp, tls, ctx))
4943 /* Start single stepping again from the current sequence point */
4944 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
4946 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
4947 (method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4948 !strcmp (method->name, ".cctor"))
4951 // FIXME: Has to lock earlier
4953 reqs = g_ptr_array_new ();
4955 mono_loader_lock ();
4957 g_ptr_array_add (reqs, ss_req->req);
4959 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4961 g_ptr_array_free (reqs, TRUE);
4963 mono_loader_unlock ();
4965 process_event (EVENT_KIND_STEP, jinfo_get_method (ji), il_offset, ctx, events, suspend_policy);
4969 process_single_step (void)
4971 process_signal_event (process_single_step_inner);
4975 * mono_debugger_agent_single_step_event:
4977 * Called from a signal handler to handle a single step event.
4980 mono_debugger_agent_single_step_event (void *sigctx)
4982 /* Resume to process_single_step through the signal context */
4984 // FIXME: Since step out/over is implemented using step in, the step in case should
4985 // be as fast as possible. Move the relevant code from process_single_step_inner ()
4988 if (is_debugger_thread ()) {
4990 * This could happen despite our best effors when the runtime calls
4991 * assembly/type resolve hooks.
4992 * FIXME: Breakpoints too.
4996 mono_sigctx_to_monoctx (sigctx, &ctx);
4997 mono_arch_skip_single_step (&ctx);
4998 mono_monoctx_to_sigctx (&ctx, sigctx);
5002 resume_from_signal_handler (sigctx, process_single_step);
5006 debugger_agent_single_step_from_context (MonoContext *ctx)
5008 DebuggerTlsData *tls;
5009 MonoThreadUnwindState orig_restore_state;
5011 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5012 /* Fastpath during invokes, see in process_suspend () */
5013 if (tls && suspend_count && suspend_count - tls->resume_count == 0)
5016 if (is_debugger_thread ())
5021 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
5022 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5023 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5024 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5026 process_single_step_inner (tls, FALSE);
5028 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5029 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5033 debugger_agent_breakpoint_from_context (MonoContext *ctx)
5035 DebuggerTlsData *tls;
5036 MonoThreadUnwindState orig_restore_state;
5039 if (is_debugger_thread ())
5042 orig_ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
5043 MONO_CONTEXT_SET_IP (ctx, orig_ip - 1);
5045 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5047 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5048 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5049 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5051 process_breakpoint_inner (tls, FALSE);
5053 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5054 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5055 if (MONO_CONTEXT_GET_IP (ctx) == orig_ip - 1)
5056 MONO_CONTEXT_SET_IP (ctx, orig_ip);
5060 * start_single_stepping:
5062 * Turn on single stepping. Can be called multiple times, for example,
5063 * by a single step event request + a suspend.
5066 start_single_stepping (void)
5068 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5069 int val = InterlockedIncrement (&ss_count);
5072 mono_arch_start_single_stepping ();
5074 g_assert_not_reached ();
5079 stop_single_stepping (void)
5081 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5082 int val = InterlockedDecrement (&ss_count);
5085 mono_arch_stop_single_stepping ();
5087 g_assert_not_reached ();
5094 * Stop the single stepping operation given by SS_REQ.
5097 ss_stop (SingleStepReq *ss_req)
5102 for (l = ss_req->bps; l; l = l->next) {
5103 clear_breakpoint ((MonoBreakpoint *)l->data);
5105 g_slist_free (ss_req->bps);
5109 if (ss_req->global) {
5110 stop_single_stepping ();
5111 ss_req->global = FALSE;
5118 * Reject breakpoint if it is a duplicate of one already in list or hash table.
5121 ss_bp_is_unique (GSList *bps, GHashTable *ss_req_bp_cache, MonoMethod *method, guint32 il_offset)
5123 if (ss_req_bp_cache) {
5124 MonoBreakpoint dummy = {method, il_offset, NULL, NULL};
5125 return !g_hash_table_lookup (ss_req_bp_cache, &dummy);
5127 for (GSList *l = bps; l; l = l->next) {
5128 MonoBreakpoint *bp = (MonoBreakpoint *)l->data;
5129 if (bp->method == method && bp->il_offset == il_offset)
5138 * GHashTable equality for a MonoBreakpoint (only care about method and il_offset fields)
5141 ss_bp_eq (gconstpointer ka, gconstpointer kb)
5143 const MonoBreakpoint *s1 = (const MonoBreakpoint *)ka;
5144 const MonoBreakpoint *s2 = (const MonoBreakpoint *)kb;
5145 return (s1->method == s2->method && s1->il_offset == s2->il_offset) ? 1 : 0;
5151 * GHashTable hash for a MonoBreakpoint (only care about method and il_offset fields)
5154 ss_bp_hash (gconstpointer data)
5156 const MonoBreakpoint *s = (const MonoBreakpoint *)data;
5157 guint hash = (guint) (uintptr_t) s->method;
5158 hash ^= ((guint)s->il_offset) << 16; // Assume low bits are more interesting
5159 hash ^= ((guint)s->il_offset) >> 16;
5163 #define MAX_LINEAR_SCAN_BPS 7
5168 * Create a new breakpoint and add it to a step request.
5169 * Will adjust the bp count and cache used by ss_start.
5172 ss_bp_add_one (SingleStepReq *ss_req, int *ss_req_bp_count, GHashTable **ss_req_bp_cache,
5173 MonoMethod *method, guint32 il_offset)
5175 // This list is getting too long, switch to using the hash table
5176 if (!*ss_req_bp_cache && *ss_req_bp_count > MAX_LINEAR_SCAN_BPS) {
5177 *ss_req_bp_cache = g_hash_table_new (ss_bp_hash, ss_bp_eq);
5178 for (GSList *l = ss_req->bps; l; l = l->next)
5179 g_hash_table_insert (*ss_req_bp_cache, l->data, l->data);
5182 if (ss_bp_is_unique (ss_req->bps, *ss_req_bp_cache, method, il_offset)) {
5183 // Create and add breakpoint
5184 MonoBreakpoint *bp = set_breakpoint (method, il_offset, ss_req->req, NULL);
5185 ss_req->bps = g_slist_append (ss_req->bps, bp);
5186 if (*ss_req_bp_cache)
5187 g_hash_table_insert (*ss_req_bp_cache, bp, bp);
5188 (*ss_req_bp_count)++;
5190 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);
5197 * Start the single stepping operation given by SS_REQ from the sequence point SP.
5198 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
5199 * belong to the same thread as CTX.
5200 * If FRAMES is not-null, use that instead of tls->frames for placing breakpoints etc.
5203 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint* sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls,
5204 gboolean step_to_catch, StackFrame **frames, int nframes)
5206 int i, j, frame_index;
5207 SeqPoint *next_sp, *parent_sp = NULL;
5208 SeqPoint local_sp, local_parent_sp;
5210 MonoSeqPointInfo *parent_info;
5211 MonoMethod *parent_sp_method = NULL;
5212 gboolean enable_global = FALSE;
5214 // When 8 or more entries are in bps, we build a hash table to serve as a set of breakpoints.
5215 // Recreating this on each pass is a little wasteful but at least keeps behavior linear.
5216 int ss_req_bp_count = g_slist_length (ss_req->bps);
5217 GHashTable *ss_req_bp_cache = NULL;
5219 /* Stop the previous operation */
5223 * Implement single stepping using breakpoints if possible.
5225 if (step_to_catch) {
5226 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, sp->il_offset);
5230 if (ctx && !frames) {
5231 /* Need parent frames */
5232 if (!tls->context.valid)
5233 mono_thread_state_init_from_monoctx (&tls->context, ctx);
5234 compute_frame_info (tls->thread, tls);
5235 frames = tls->frames;
5236 nframes = tls->frame_count;
5239 /* Need to stop in catch clauses as well */
5240 for (i = ss_req->depth == STEP_DEPTH_OUT ? 1 : 0; i < nframes; ++i) {
5241 StackFrame *frame = frames [i];
5244 MonoJitInfo *jinfo = frame->ji;
5245 for (j = 0; j < jinfo->num_clauses; ++j) {
5246 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5248 if (mono_find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL, &local_sp))
5249 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, frame->method, local_sp.il_offset);
5255 * Find the first sequence point in the current or in a previous frame which
5256 * is not the last in its method.
5258 if (ss_req->depth == STEP_DEPTH_OUT) {
5259 /* Ignore seq points in current method */
5260 while (frame_index < nframes) {
5261 StackFrame *frame = frames [frame_index];
5263 method = frame->method;
5264 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5265 sp = (found_sp)? &local_sp : NULL;
5267 if (sp && sp->next_len != 0)
5270 // There could be method calls before the next seq point in the caller when using nested calls
5271 //enable_global = TRUE;
5273 if (sp && sp->next_len == 0) {
5275 while (frame_index < nframes) {
5276 StackFrame *frame = frames [frame_index];
5278 method = frame->method;
5279 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5280 sp = (found_sp)? &local_sp : NULL;
5281 if (sp && sp->next_len != 0)
5287 /* Have to put a breakpoint into a parent frame since the seq points might not cover all control flow out of the method */
5288 while (frame_index < nframes) {
5289 StackFrame *frame = frames [frame_index];
5291 parent_sp_method = frame->method;
5292 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &parent_info, &local_parent_sp);
5293 parent_sp = found_sp ? &local_parent_sp : NULL;
5294 if (found_sp && parent_sp->next_len != 0)
5302 if (sp && sp->next_len > 0) {
5303 SeqPoint* next = g_new(SeqPoint, sp->next_len);
5305 mono_seq_point_init_next (info, *sp, next);
5306 for (i = 0; i < sp->next_len; i++) {
5309 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, next_sp->il_offset);
5315 SeqPoint* next = g_new(SeqPoint, parent_sp->next_len);
5317 mono_seq_point_init_next (parent_info, *parent_sp, next);
5318 for (i = 0; i < parent_sp->next_len; i++) {
5321 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, parent_sp_method, next_sp->il_offset);
5326 if (ss_req->nframes == 0)
5327 ss_req->nframes = nframes;
5329 if ((ss_req->depth == STEP_DEPTH_OVER) && (!sp && !parent_sp)) {
5330 DEBUG_PRINTF (1, "[dbg] No parent frame for step over, transition to step into.\n");
5332 * This is needed since if we leave managed code, and later return to it, step over
5333 * is not going to stop.
5334 * This approach is a bit ugly, since we change the step depth, but it only affects
5335 * clients who reuse the same step request, and only in this special case.
5337 ss_req->depth = STEP_DEPTH_INTO;
5340 if (ss_req->depth == STEP_DEPTH_INTO) {
5341 /* Enable global stepping so we stop at method entry too */
5342 enable_global = TRUE;
5346 * The ctx/frame info computed above will become invalid when we continue.
5348 tls->context.valid = FALSE;
5349 tls->async_state.valid = FALSE;
5350 invalidate_frames (tls);
5353 if (enable_global) {
5354 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5355 ss_req->global = TRUE;
5356 start_single_stepping ();
5357 } else if (!ss_req->bps) {
5358 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5359 ss_req->global = TRUE;
5360 start_single_stepping ();
5362 ss_req->global = FALSE;
5365 if (ss_req_bp_cache)
5366 g_hash_table_destroy (ss_req_bp_cache);
5370 * Start single stepping of thread THREAD
5373 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req)
5375 DebuggerTlsData *tls;
5376 MonoSeqPointInfo *info = NULL;
5377 SeqPoint *sp = NULL;
5380 MonoMethod *method = NULL;
5381 MonoDebugMethodInfo *minfo;
5382 gboolean step_to_catch = FALSE;
5383 gboolean set_ip = FALSE;
5384 StackFrame **frames = NULL;
5387 if (suspend_count == 0)
5388 return ERR_NOT_SUSPENDED;
5390 wait_for_suspend ();
5392 // FIXME: Multiple requests
5394 DEBUG_PRINTF (0, "Received a single step request while the previous one was still active.\n");
5395 return ERR_NOT_IMPLEMENTED;
5398 DEBUG_PRINTF (1, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth));
5400 ss_req = g_new0 (SingleStepReq, 1);
5402 ss_req->thread = thread;
5403 ss_req->size = size;
5404 ss_req->depth = depth;
5405 ss_req->filter = filter;
5408 for (int i = 0; i < req->nmodifiers; i++) {
5409 if (req->modifiers[i].kind == MOD_KIND_ASSEMBLY_ONLY) {
5410 ss_req->user_assemblies = req->modifiers[i].data.assemblies;
5415 mono_loader_lock ();
5416 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5417 mono_loader_unlock ();
5419 if (!tls->context.valid) {
5420 DEBUG_PRINTF (1, "Received a single step request on a thread with no managed frames.");
5421 return ERR_INVALID_ARGUMENT;
5424 if (tls->restore_state.valid && MONO_CONTEXT_GET_IP (&tls->context.ctx) != MONO_CONTEXT_GET_IP (&tls->restore_state.ctx)) {
5426 * Need to start single stepping from restore_state and not from the current state
5429 frames = compute_frame_info_from (thread, tls, &tls->restore_state, &nframes);
5432 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5434 if (tls->catch_state.valid) {
5436 StackFrameInfo frame;
5437 MonoContext new_ctx;
5438 MonoLMF *lmf = NULL;
5441 * We are stopped at a throw site. Stepping should go to the catch site.
5444 /* Find the the jit info for the catch context */
5445 res = mono_find_jit_info_ext (
5446 (MonoDomain *)tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN],
5447 (MonoJitTlsData *)((MonoThreadInfo*)thread->thread_info)->jit_data,
5448 NULL, &tls->catch_state.ctx, &new_ctx, NULL, &lmf, NULL, &frame);
5450 g_assert (frame.type == FRAME_TYPE_MANAGED);
5453 * Find the seq point corresponding to the landing site ip, which is the first seq
5456 found_sp = mono_find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info, &local_sp);
5457 sp = (found_sp)? &local_sp : NULL;
5459 no_seq_points_found (frame.method, frame.native_offset);
5462 method = frame.method;
5464 step_to_catch = TRUE;
5465 /* This make sure the seq point is not skipped by process_single_step () */
5466 ss_req->last_sp = NULL;
5469 if (!step_to_catch) {
5470 StackFrame *frame = NULL;
5473 if (frames && nframes)
5476 compute_frame_info (thread, tls);
5478 if (tls->frame_count)
5479 frame = tls->frames [0];
5482 if (ss_req->size == STEP_SIZE_LINE) {
5484 ss_req->last_method = frame->method;
5485 ss_req->last_line = -1;
5487 minfo = mono_debug_lookup_method (frame->method);
5488 if (minfo && frame->il_offset != -1) {
5489 MonoDebugSourceLocation *loc = mono_debug_method_lookup_location (minfo, frame->il_offset);
5492 ss_req->last_line = loc->row;
5500 if (!method && frame->il_offset != -1) {
5501 /* FIXME: Sort the table and use a binary search */
5502 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5503 sp = (found_sp)? &local_sp : NULL;
5505 no_seq_points_found (frame->method, frame->native_offset);
5507 method = frame->method;
5512 ss_req->start_method = method;
5514 ss_start (ss_req, method, sp, info, set_ip ? &tls->restore_state.ctx : &tls->context.ctx, tls, step_to_catch, frames, nframes);
5517 free_frames (frames, nframes);
5523 ss_destroy (SingleStepReq *req)
5526 g_assert (ss_req == req);
5535 ss_clear_for_assembly (SingleStepReq *req, MonoAssembly *assembly)
5538 gboolean found = TRUE;
5542 for (l = ss_req->bps; l; l = l->next) {
5543 if (breakpoint_matches_assembly ((MonoBreakpoint *)l->data, assembly)) {
5544 clear_breakpoint ((MonoBreakpoint *)l->data);
5545 ss_req->bps = g_slist_delete_link (ss_req->bps, l);
5554 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5557 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5564 if (!agent_config.enabled)
5567 mono_loader_lock ();
5568 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5569 mono_loader_unlock ();
5574 ei.category = mono_string_to_utf8_checked (category, &error);
5575 mono_error_cleanup (&error);
5579 ei.message = mono_string_to_utf8_checked (message, &error);
5580 mono_error_cleanup (&error);
5583 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5585 g_free (ei.category);
5586 g_free (ei.message);
5590 mono_debugger_agent_debug_log_is_enabled (void)
5592 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5593 return agent_config.enabled;
5596 #if defined(PLATFORM_ANDROID) || defined(TARGET_ANDROID)
5598 mono_debugger_agent_unhandled_exception (MonoException *exc)
5607 memset (&ei, 0, sizeof (EventInfo));
5608 ei.exc = (MonoObject*)exc;
5610 mono_loader_lock ();
5611 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5612 mono_loader_unlock ();
5614 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5619 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5620 MonoContext *catch_ctx)
5622 int i, j, suspend_policy;
5624 MonoJitInfo *ji, *catch_ji;
5626 DebuggerTlsData *tls = NULL;
5628 if (thread_to_tls != NULL) {
5629 MonoInternalThread *thread = mono_thread_internal_current ();
5631 mono_loader_lock ();
5632 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5633 mono_loader_unlock ();
5635 if (tls && tls->abort_requested)
5637 if (tls && tls->disable_breakpoints)
5641 memset (&ei, 0, sizeof (EventInfo));
5643 /* Just-In-Time debugging */
5645 if (agent_config.onuncaught && !inited) {
5646 finish_agent_init (FALSE);
5649 * Send an unsolicited EXCEPTION event with a dummy request id.
5651 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5652 ei.exc = (MonoObject*)exc;
5653 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5656 } else if (agent_config.onthrow && !inited) {
5658 gboolean found = FALSE;
5660 for (l = agent_config.onthrow; l; l = l->next) {
5661 char *ex_type = (char *)l->data;
5662 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5664 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5671 finish_agent_init (FALSE);
5674 * Send an unsolicited EXCEPTION event with a dummy request id.
5676 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5677 ei.exc = (MonoObject*)exc;
5678 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5686 ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5688 catch_ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5692 ei.exc = (MonoObject*)exc;
5693 ei.caught = catch_ctx != NULL;
5695 mono_loader_lock ();
5697 /* Treat exceptions which are caught in non-user code as unhandled */
5698 for (i = 0; i < event_requests->len; ++i) {
5699 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
5700 if (req->event_kind != EVENT_KIND_EXCEPTION)
5703 for (j = 0; j < req->nmodifiers; ++j) {
5704 Modifier *mod = &req->modifiers [j];
5706 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5708 gboolean found = FALSE;
5709 MonoAssembly **assemblies = mod->data.assemblies;
5712 for (k = 0; assemblies [k]; ++k)
5713 if (assemblies [k] == jinfo_get_method (catch_ji)->klass->image->assembly)
5722 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5723 mono_loader_unlock ();
5725 if (tls && ei.caught && catch_ctx) {
5726 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5727 tls->catch_state.ctx = *catch_ctx;
5728 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5729 tls->catch_state.valid = TRUE;
5732 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5735 tls->catch_state.valid = FALSE;
5739 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5741 DebuggerTlsData *tls;
5746 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5751 * We're about to invoke an exception filter during the first pass of exception handling.
5753 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5754 * 'orig_ctx' is the context where the exception has been thrown.
5757 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5759 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5760 * the call site (line 37) and then continue to Main(), but it would never
5761 * include the throw site (line 32).
5763 * Since exception filters are invoked during the first pass of exception handling,
5764 * the stack frames of the throw site are still intact, so we should include them
5767 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5769 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5770 * but report the location of the 'throw' to the user.
5774 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5778 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5780 DebuggerTlsData *tls;
5785 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5789 tls->filter_state.valid = FALSE;
5793 * buffer_add_value_full:
5795 * Add the encoding of the value at ADDR described by T to the buffer.
5796 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5800 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5801 gboolean as_vtype, GHashTable *parent_vtypes)
5804 gboolean boxed_vtype = FALSE;
5807 if (!(*(void**)addr)) {
5808 /* This can happen with compiler generated locals */
5809 //printf ("%s\n", mono_type_full_name (t));
5810 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5813 g_assert (*(void**)addr);
5814 addr = *(void**)addr;
5819 case MONO_TYPE_BOOLEAN:
5822 case MONO_TYPE_CHAR:
5842 case MONO_TYPE_VOID:
5843 buffer_add_byte (buf, t->type);
5845 case MONO_TYPE_BOOLEAN:
5848 buffer_add_byte (buf, t->type);
5849 buffer_add_int (buf, *(gint8*)addr);
5851 case MONO_TYPE_CHAR:
5854 buffer_add_byte (buf, t->type);
5855 buffer_add_int (buf, *(gint16*)addr);
5860 buffer_add_byte (buf, t->type);
5861 buffer_add_int (buf, *(gint32*)addr);
5866 buffer_add_byte (buf, t->type);
5867 buffer_add_long (buf, *(gint64*)addr);
5871 /* Treat it as a vtype */
5873 case MONO_TYPE_PTR: {
5874 gssize val = *(gssize*)addr;
5876 buffer_add_byte (buf, t->type);
5877 buffer_add_long (buf, val);
5881 case MONO_TYPE_STRING:
5882 case MONO_TYPE_SZARRAY:
5883 case MONO_TYPE_OBJECT:
5884 case MONO_TYPE_CLASS:
5885 case MONO_TYPE_ARRAY:
5886 obj = *(MonoObject**)addr;
5889 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5891 if (obj->vtable->klass->valuetype) {
5892 t = &obj->vtable->klass->byval_arg;
5893 addr = mono_object_unbox (obj);
5896 } else if (obj->vtable->klass->rank) {
5897 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5898 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5899 buffer_add_byte (buf, MONO_TYPE_CLASS);
5901 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5903 buffer_add_objid (buf, obj);
5907 case MONO_TYPE_VALUETYPE:
5908 case MONO_TYPE_TYPEDBYREF: {
5912 MonoClass *klass = mono_class_from_mono_type (t);
5917 * Handle boxed vtypes recursively referencing themselves using fields.
5920 parent_vtypes = g_hash_table_new (NULL, NULL);
5921 vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
5923 if (CHECK_PROTOCOL_VERSION (2, 33)) {
5924 buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
5925 buffer_add_int (buf, vtype_index - 1);
5927 /* The client can't handle PARENT_VTYPE */
5928 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5932 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
5936 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5937 buffer_add_byte (buf, klass->enumtype);
5938 buffer_add_typeid (buf, domain, klass);
5942 while ((f = mono_class_get_fields (klass, &iter))) {
5943 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5945 if (mono_field_is_deleted (f))
5949 buffer_add_int (buf, nfields);
5952 while ((f = mono_class_get_fields (klass, &iter))) {
5953 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5955 if (mono_field_is_deleted (f))
5957 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE, parent_vtypes);
5961 g_hash_table_remove (parent_vtypes, addr);
5962 if (g_hash_table_size (parent_vtypes) == 0) {
5963 g_hash_table_destroy (parent_vtypes);
5964 parent_vtypes = NULL;
5969 case MONO_TYPE_GENERICINST:
5970 if (mono_type_generic_inst_is_valuetype (t)) {
5982 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5984 buffer_add_value_full (buf, t, addr, domain, FALSE, NULL);
5988 obj_is_of_type (MonoObject *obj, MonoType *t)
5990 MonoClass *klass = obj->vtable->klass;
5991 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5992 if (mono_class_is_transparent_proxy (klass)) {
5993 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5994 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
6004 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
6007 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6013 gpointer iter = NULL;
6017 is_enum = decode_byte (buf, &buf, limit);
6018 /* Enums are sent as a normal vtype */
6020 return ERR_NOT_IMPLEMENTED;
6021 klass = decode_typeid (buf, &buf, limit, &d, &err);
6022 if (err != ERR_NONE)
6025 if (t && klass != mono_class_from_mono_type (t)) {
6026 char *name = mono_type_full_name (t);
6027 char *name2 = mono_type_full_name (&klass->byval_arg);
6028 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got %s.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, name2);
6031 return ERR_INVALID_ARGUMENT;
6034 nfields = decode_int (buf, &buf, limit);
6035 while ((f = mono_class_get_fields (klass, &iter))) {
6036 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6038 if (mono_field_is_deleted (f))
6040 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
6041 if (err != ERR_NONE)
6045 g_assert (nfields == 0);
6053 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6057 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
6058 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
6059 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
6060 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
6061 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE) &&
6062 !(t->type == MONO_TYPE_VALUETYPE && type == MONO_TYPE_OBJECT)) {
6063 char *name = mono_type_full_name (t);
6064 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
6066 return ERR_INVALID_ARGUMENT;
6070 case MONO_TYPE_BOOLEAN:
6071 *(guint8*)addr = decode_int (buf, &buf, limit);
6073 case MONO_TYPE_CHAR:
6074 *(gunichar2*)addr = decode_int (buf, &buf, limit);
6077 *(gint8*)addr = decode_int (buf, &buf, limit);
6080 *(guint8*)addr = decode_int (buf, &buf, limit);
6083 *(gint16*)addr = decode_int (buf, &buf, limit);
6086 *(guint16*)addr = decode_int (buf, &buf, limit);
6089 *(gint32*)addr = decode_int (buf, &buf, limit);
6092 *(guint32*)addr = decode_int (buf, &buf, limit);
6095 *(gint64*)addr = decode_long (buf, &buf, limit);
6098 *(guint64*)addr = decode_long (buf, &buf, limit);
6101 *(guint32*)addr = decode_int (buf, &buf, limit);
6104 *(guint64*)addr = decode_long (buf, &buf, limit);
6107 /* We send these as I8, so we get them back as such */
6108 g_assert (type == MONO_TYPE_I8);
6109 *(gssize*)addr = decode_long (buf, &buf, limit);
6111 case MONO_TYPE_GENERICINST:
6112 if (MONO_TYPE_ISSTRUCT (t)) {
6113 /* The client sends these as a valuetype */
6121 /* We send these as vtypes, so we get them back as such */
6122 g_assert (type == MONO_TYPE_VALUETYPE);
6125 case MONO_TYPE_VALUETYPE:
6126 if (type == MONO_TYPE_OBJECT) {
6128 int objid = decode_objid (buf, &buf, limit);
6132 err = get_object (objid, (MonoObject**)&obj);
6133 if (err != ERR_NONE)
6136 return ERR_INVALID_ARGUMENT;
6137 if (obj->vtable->klass != mono_class_from_mono_type (t)) {
6138 DEBUG_PRINTF (1, "Expected type '%s', got object '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6139 return ERR_INVALID_ARGUMENT;
6141 memcpy (addr, mono_object_unbox (obj), mono_class_value_size (obj->vtable->klass, NULL));
6143 err = decode_vtype (t, domain, addr, buf, &buf, limit);
6144 if (err != ERR_NONE)
6150 if (MONO_TYPE_IS_REFERENCE (t)) {
6151 if (type == MONO_TYPE_OBJECT) {
6152 int objid = decode_objid (buf, &buf, limit);
6156 err = get_object (objid, (MonoObject**)&obj);
6157 if (err != ERR_NONE)
6161 if (!obj_is_of_type (obj, t)) {
6162 DEBUG_PRINTF (1, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6163 return ERR_INVALID_ARGUMENT;
6166 if (obj && obj->vtable->domain != domain)
6167 return ERR_INVALID_ARGUMENT;
6169 mono_gc_wbarrier_generic_store (addr, obj);
6170 } else if (type == VALUE_TYPE_ID_NULL) {
6171 *(MonoObject**)addr = NULL;
6172 } else if (type == MONO_TYPE_VALUETYPE) {
6181 /* This can happen when round-tripping boxed vtypes */
6183 * Obtain vtype class.
6184 * Same as the beginning of the handle_vtype case above.
6187 is_enum = decode_byte (buf, &buf, limit);
6189 return ERR_NOT_IMPLEMENTED;
6190 klass = decode_typeid (buf, &buf, limit, &d, &err);
6191 if (err != ERR_NONE)
6194 /* Decode the vtype into a temporary buffer, then box it. */
6195 vtype_buf_size = mono_class_value_size (klass, NULL);
6196 vtype_buf = (guint8 *)g_malloc0 (vtype_buf_size);
6197 g_assert (vtype_buf);
6200 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
6201 if (err != ERR_NONE) {
6205 *(MonoObject**)addr = mono_value_box_checked (d, klass, vtype_buf, &error);
6206 mono_error_cleanup (&error);
6209 char *name = mono_type_full_name (t);
6210 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
6212 return ERR_INVALID_ARGUMENT;
6226 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6230 int type = decode_byte (buf, &buf, limit);
6232 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
6233 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
6234 guint8 *nullable_buf;
6237 * First try decoding it as a Nullable`1
6239 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6240 if (err == ERR_NONE)
6244 * Then try decoding as a primitive value or null.
6246 if (targ->type == type) {
6247 nullable_buf = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
6248 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
6249 if (err != ERR_NONE) {
6250 g_free (nullable_buf);
6253 MonoObject *boxed = mono_value_box_checked (domain, mono_class_from_mono_type (targ), nullable_buf, &error);
6254 if (!is_ok (&error)) {
6255 mono_error_cleanup (&error);
6256 return ERR_INVALID_OBJECT;
6258 mono_nullable_init (addr, boxed, mono_class_from_mono_type (t));
6259 g_free (nullable_buf);
6262 } else if (type == VALUE_TYPE_ID_NULL) {
6263 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
6269 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6273 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
6277 guint8 *addr, *gaddr;
6280 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6281 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6284 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
6285 reg_val = mono_arch_context_get_int_reg (ctx, reg);
6287 buffer_add_value_full (buf, t, ®_val, domain, as_vtype, NULL);
6289 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6290 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6291 addr += (gint32)var->offset;
6293 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6295 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6297 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6300 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6301 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
6302 /* Same as regoffset, but with an indirection */
6303 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6304 addr += (gint32)var->offset;
6306 gaddr = (guint8 *)*(gpointer*)addr;
6308 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL);
6310 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
6311 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
6312 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
6313 MonoGSharedVtMethodRuntimeInfo *info;
6319 g_assert (info_var);
6320 g_assert (locals_var);
6322 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6323 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6324 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6325 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6326 addr += (gint32)info_var->offset;
6327 info = (MonoGSharedVtMethodRuntimeInfo *)*(gpointer*)addr;
6328 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6329 info = (MonoGSharedVtMethodRuntimeInfo *)mono_arch_context_get_int_reg (ctx, reg);
6331 g_assert_not_reached ();
6335 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6336 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6337 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6338 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6339 addr += (gint32)locals_var->offset;
6340 locals = (guint8 *)*(gpointer*)addr;
6341 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6342 locals = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6344 g_assert_not_reached ();
6348 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6350 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6355 g_assert_not_reached ();
6360 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
6364 guint8 *addr, *gaddr;
6366 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6367 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6369 if (MONO_TYPE_IS_REFERENCE (t))
6370 size = sizeof (gpointer);
6372 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6375 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6376 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6378 gboolean is_signed = FALSE;
6381 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6384 // FIXME: Write barriers
6385 mono_gc_memmove_atomic (addr, val, size);
6390 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6395 v = is_signed ? *(gint8*)val : *(guint8*)val;
6398 v = is_signed ? *(gint16*)val : *(guint16*)val;
6401 v = is_signed ? *(gint32*)val : *(guint32*)val;
6404 v = is_signed ? *(gint64*)val : *(guint64*)val;
6407 g_assert_not_reached ();
6410 /* Set value on the stack or in the return ctx */
6411 if (reg_locations [reg]) {
6412 /* Saved on the stack */
6413 DEBUG_PRINTF (1, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v);
6414 *(reg_locations [reg]) = v;
6417 DEBUG_PRINTF (1, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v);
6418 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6421 // FIXME: Move these to mono-context.h/c.
6422 mono_arch_context_set_int_reg (ctx, reg, v);
6424 // FIXME: Can't set registers, so we disable linears
6429 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6430 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6431 addr += (gint32)var->offset;
6433 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6436 addr = *(guint8**)addr;
6442 // FIXME: Write barriers
6443 mono_gc_memmove_atomic (addr, val, size);
6445 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6446 /* Same as regoffset, but with an indirection */
6447 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6448 addr += (gint32)var->offset;
6450 gaddr = (guint8 *)*(gpointer*)addr;
6452 // FIXME: Write barriers
6453 mono_gc_memmove_atomic (gaddr, val, size);
6455 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6459 g_assert_not_reached ();
6464 clear_event_request (int req_id, int etype)
6468 mono_loader_lock ();
6469 for (i = 0; i < event_requests->len; ++i) {
6470 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6472 if (req->id == req_id && req->event_kind == etype) {
6473 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6474 clear_breakpoint ((MonoBreakpoint *)req->info);
6475 if (req->event_kind == EVENT_KIND_STEP)
6476 ss_destroy ((SingleStepReq *)req->info);
6477 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6478 clear_breakpoint ((MonoBreakpoint *)req->info);
6479 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6480 clear_breakpoint ((MonoBreakpoint *)req->info);
6481 g_ptr_array_remove_index_fast (event_requests, i);
6486 mono_loader_unlock ();
6490 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
6494 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6495 m->kind = MOD_KIND_NONE;
6496 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6497 int count = 0, match_count = 0, pos;
6498 MonoAssembly **newassemblies;
6500 for (i = 0; m->data.assemblies [i]; ++i) {
6502 if (m->data.assemblies [i] == assembly)
6507 // +1 because we don't know length and we use last element to check for end
6508 newassemblies = g_new0 (MonoAssembly*, count - match_count + 1);
6511 for (i = 0; i < count; ++i)
6512 if (m->data.assemblies [i] != assembly)
6513 newassemblies [pos ++] = m->data.assemblies [i];
6514 g_assert (pos == count - match_count);
6515 g_free (m->data.assemblies);
6516 m->data.assemblies = newassemblies;
6522 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
6526 for (i = 0; i < req->nmodifiers; ++i) {
6527 Modifier *m = &req->modifiers [i];
6529 clear_assembly_from_modifier (req, m, assembly);
6534 * clear_event_requests_for_assembly:
6536 * Clear all events requests which reference ASSEMBLY.
6539 clear_event_requests_for_assembly (MonoAssembly *assembly)
6544 mono_loader_lock ();
6548 for (i = 0; i < event_requests->len; ++i) {
6549 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6551 clear_assembly_from_modifiers (req, assembly);
6553 if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly ((MonoBreakpoint *)req->info, assembly)) {
6554 clear_event_request (req->id, req->event_kind);
6559 if (req->event_kind == EVENT_KIND_STEP)
6560 ss_clear_for_assembly ((SingleStepReq *)req->info, assembly);
6563 mono_loader_unlock ();
6567 * type_comes_from_assembly:
6569 * GHRFunc that returns TRUE if klass comes from assembly
6572 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6574 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6578 * clear_types_for_assembly:
6580 * Clears types from loaded_classes for a given assembly
6583 clear_types_for_assembly (MonoAssembly *assembly)
6585 MonoDomain *domain = mono_domain_get ();
6586 AgentDomainInfo *info = NULL;
6588 if (!domain || !domain_jit_info (domain))
6589 /* Can happen during shutdown */
6592 info = get_agent_domain_info (domain);
6594 mono_loader_lock ();
6595 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6596 mono_loader_unlock ();
6600 add_thread (gpointer key, gpointer value, gpointer user_data)
6602 MonoInternalThread *thread = (MonoInternalThread *)value;
6603 Buffer *buf = (Buffer *)user_data;
6605 buffer_add_objid (buf, (MonoObject*)thread);
6609 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6612 guint8 *end = invoke->endp;
6616 MonoMethodSignature *sig;
6619 MonoObject *this_arg, *res, *exc;
6622 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6625 MonoStopwatch watch;
6627 if (invoke->method) {
6629 * Invoke this method directly, currently only Environment.Exit () is supported.
6632 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>");
6634 mono_runtime_try_invoke (invoke->method, NULL, invoke->args, &exc, &error);
6635 mono_error_assert_ok (&error);
6637 g_assert_not_reached ();
6640 m = decode_methodid (p, &p, end, &domain, &err);
6641 if (err != ERR_NONE)
6643 sig = mono_method_signature (m);
6645 if (m->klass->valuetype)
6646 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6648 this_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
6649 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6650 /* Should be null */
6651 int type = decode_byte (p, &p, end);
6652 if (type != VALUE_TYPE_ID_NULL) {
6653 DEBUG_PRINTF (1, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6654 return ERR_INVALID_ARGUMENT;
6656 memset (this_buf, 0, mono_class_instance_size (m->klass));
6657 } else if (m->klass->valuetype && !strcmp (m->name, ".ctor")) {
6661 int type = decode_byte (p, &tmp_p, end);
6662 if (type == VALUE_TYPE_ID_NULL) {
6663 memset (this_buf, 0, mono_class_instance_size (m->klass));
6666 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6667 if (err != ERR_NONE)
6671 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6672 if (err != ERR_NONE)
6676 if (!m->klass->valuetype)
6677 this_arg = *(MonoObject**)this_buf;
6681 if (MONO_CLASS_IS_INTERFACE (m->klass)) {
6683 DEBUG_PRINTF (1, "[%p] Error: Interface method invoked without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6684 return ERR_INVALID_ARGUMENT;
6686 m = mono_object_get_virtual_method (this_arg, m);
6687 /* Transform this to the format the rest of the code expects it to be */
6688 if (m->klass->valuetype) {
6689 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6690 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
6692 } else if ((m->flags & METHOD_ATTRIBUTE_VIRTUAL) && !m->klass->valuetype && invoke->flags & INVOKE_FLAG_VIRTUAL) {
6694 DEBUG_PRINTF (1, "[%p] Error: invoke with INVOKE_FLAG_VIRTUAL flag set without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6695 return ERR_INVALID_ARGUMENT;
6697 m = mono_object_get_virtual_method (this_arg, m);
6698 if (m->klass->valuetype) {
6699 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6700 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
6704 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>");
6706 if (this_arg && this_arg->vtable->domain != domain)
6709 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this_arg) {
6710 if (!strcmp (m->name, ".ctor")) {
6711 if (mono_class_is_abstract (m->klass))
6712 return ERR_INVALID_ARGUMENT;
6715 this_arg = mono_object_new_checked (domain, m->klass, &error);
6716 mono_error_assert_ok (&error);
6719 return ERR_INVALID_ARGUMENT;
6723 if (this_arg && !obj_is_of_type (this_arg, &m->klass->byval_arg))
6724 return ERR_INVALID_ARGUMENT;
6726 nargs = decode_int (p, &p, end);
6727 if (nargs != sig->param_count)
6728 return ERR_INVALID_ARGUMENT;
6729 /* Use alloca to get gc tracking */
6730 arg_buf = (guint8 **)g_alloca (nargs * sizeof (gpointer));
6731 memset (arg_buf, 0, nargs * sizeof (gpointer));
6732 args = (gpointer *)g_alloca (nargs * sizeof (gpointer));
6733 for (i = 0; i < nargs; ++i) {
6734 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6735 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6736 if (err != ERR_NONE)
6738 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6741 if (sig->params [i]->byref) {
6742 arg_buf [i] = (guint8 *)g_alloca (sizeof (mgreg_t));
6743 *(gpointer*)arg_buf [i] = args [i];
6744 args [i] = arg_buf [i];
6747 arg_buf [i] = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6748 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6749 if (err != ERR_NONE)
6751 args [i] = arg_buf [i];
6758 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6759 tls->disable_breakpoints = TRUE;
6761 tls->disable_breakpoints = FALSE;
6764 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6766 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6767 if (invoke->has_ctx) {
6770 lmf_addr = mono_get_lmf_addr ();
6773 memset (&ext, 0, sizeof (ext));
6774 mono_arch_init_lmf_ext (&ext, *lmf_addr);
6776 ext.debugger_invoke = TRUE;
6777 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6779 mono_set_lmf ((MonoLMF*)&ext);
6783 mono_stopwatch_start (&watch);
6784 res = mono_runtime_try_invoke (m, m->klass->valuetype ? (gpointer) this_buf : (gpointer) this_arg, args, &exc, &error);
6785 if (exc == NULL && !mono_error_ok (&error)) {
6786 exc = (MonoObject*) mono_error_convert_to_exception (&error);
6788 mono_error_cleanup (&error); /* FIXME report error */
6790 mono_stopwatch_stop (&watch);
6791 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));
6793 buffer_add_byte (buf, 0);
6794 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6796 gboolean out_this = FALSE;
6797 gboolean out_args = FALSE;
6799 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_THIS) && CHECK_PROTOCOL_VERSION (2, 35))
6801 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_ARGS) && CHECK_PROTOCOL_VERSION (2, 35))
6803 buffer_add_byte (buf, 1 + (out_this ? 2 : 0) + (out_args ? 4 : 0));
6804 if (sig->ret->type == MONO_TYPE_VOID) {
6805 if (!strcmp (m->name, ".ctor")) {
6806 if (!m->klass->valuetype)
6807 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this_arg, domain);
6809 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
6811 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6813 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6814 buffer_add_value (buf, sig->ret, &res, domain);
6815 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6816 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6817 MonoClass *k = mono_class_from_mono_type (sig->ret);
6818 guint8 *nullable_buf = (guint8 *)g_alloca (mono_class_value_size (k, NULL));
6820 g_assert (nullable_buf);
6821 mono_nullable_init (nullable_buf, res, k);
6822 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6825 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6831 /* Return the new value of the receiver after the call */
6832 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
6834 buffer_add_int (buf, nargs);
6835 for (i = 0; i < nargs; ++i) {
6836 if (MONO_TYPE_IS_REFERENCE (sig->params [i]))
6837 buffer_add_value (buf, sig->params [i], &args [i], domain);
6838 else if (sig->params [i]->byref)
6839 /* add_value () does an indirection */
6840 buffer_add_value (buf, sig->params [i], &arg_buf [i], domain);
6842 buffer_add_value (buf, sig->params [i], arg_buf [i], domain);
6847 tls->disable_breakpoints = FALSE;
6849 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6850 if (invoke->has_ctx)
6851 mono_set_lmf ((MonoLMF *)(((gssize)ext.lmf.previous_lmf) & ~3));
6855 // FIXME: byref arguments
6863 * Invoke the method given by tls->pending_invoke in the current thread.
6866 invoke_method (void)
6868 DebuggerTlsData *tls;
6874 MonoContext restore_ctx;
6877 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
6881 * Store the `InvokeData *' in `tls->invoke' until we're done with
6882 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6885 mono_loader_lock ();
6887 invoke = tls->pending_invoke;
6889 tls->pending_invoke = NULL;
6891 invoke->last_invoke = tls->invoke;
6892 tls->invoke = invoke;
6894 mono_loader_unlock ();
6896 tls->frames_up_to_date = FALSE;
6902 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6903 buffer_init (&buf, 128);
6906 /* Fail the other invokes as well */
6908 err = do_invoke_method (tls, &buf, invoke, p, &p);
6911 if (tls->abort_requested) {
6912 if (CHECK_PROTOCOL_VERSION (2, 42))
6913 err = ERR_INVOKE_ABORTED;
6916 /* Start suspending before sending the reply */
6917 if (mindex == invoke->nmethods - 1) {
6918 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6919 for (i = 0; i < invoke->suspend_count; ++i)
6924 send_reply_packet (id, err, &buf);
6929 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6931 if (invoke->has_ctx)
6932 save_thread_context (&restore_ctx);
6934 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6935 g_assert (tls->resume_count);
6936 tls->resume_count -= invoke->suspend_count;
6939 DEBUG_PRINTF (1, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer) (gsize) mono_native_thread_id_get (), err, tls->resume_count);
6942 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6944 * It is possible that mono_thread_internal_abort () was called
6945 * after the mono_runtime_invoke_checked() already returned, but it doesn't matter
6946 * because we reset the abort here.
6949 mono_loader_lock ();
6951 if (tls->abort_requested)
6952 mono_thread_internal_reset_abort (tls->thread);
6954 tls->invoke = tls->invoke->last_invoke;
6955 tls->abort_requested = FALSE;
6957 mono_loader_unlock ();
6966 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6968 MonoThread *thread = (MonoThread *)value;
6969 DebuggerTlsData *tls;
6972 mono_loader_lock ();
6973 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
6975 res = tls->really_suspended;
6976 mono_loader_unlock ();
6982 get_source_files_for_type (MonoClass *klass)
6984 gpointer iter = NULL;
6986 MonoDebugSourceInfo *sinfo;
6990 files = g_ptr_array_new ();
6992 while ((method = mono_class_get_methods (klass, &iter))) {
6993 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6994 GPtrArray *source_file_list;
6997 mono_debug_get_seq_points (minfo, NULL, &source_file_list, NULL, NULL, NULL);
6998 for (j = 0; j < source_file_list->len; ++j) {
6999 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, j);
7000 for (i = 0; i < files->len; ++i)
7001 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
7003 if (i == files->len)
7004 g_ptr_array_add (files, g_strdup (sinfo->source_file));
7006 g_ptr_array_free (source_file_list, TRUE);
7014 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
7017 case CMD_VM_VERSION: {
7018 char *build_info, *version;
7020 build_info = mono_get_runtime_build_info ();
7021 version = g_strdup_printf ("mono %s", build_info);
7023 buffer_add_string (buf, version); /* vm version */
7024 buffer_add_int (buf, MAJOR_VERSION);
7025 buffer_add_int (buf, MINOR_VERSION);
7026 g_free (build_info);
7030 case CMD_VM_SET_PROTOCOL_VERSION: {
7031 major_version = decode_int (p, &p, end);
7032 minor_version = decode_int (p, &p, end);
7033 protocol_version_set = TRUE;
7034 DEBUG_PRINTF (1, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version);
7037 case CMD_VM_ALL_THREADS: {
7039 mono_loader_lock ();
7040 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
7041 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
7042 mono_loader_unlock ();
7045 case CMD_VM_SUSPEND:
7047 wait_for_suspend ();
7050 if (suspend_count == 0)
7051 return ERR_NOT_SUSPENDED;
7053 clear_suspended_objs ();
7055 case CMD_VM_DISPOSE:
7056 /* Clear all event requests */
7057 mono_loader_lock ();
7058 while (event_requests->len > 0) {
7059 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
7061 clear_event_request (req->id, req->event_kind);
7063 mono_loader_unlock ();
7065 while (suspend_count > 0)
7067 disconnected = TRUE;
7068 vm_start_event_sent = FALSE;
7071 MonoInternalThread *thread;
7072 DebuggerTlsData *tls;
7073 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7074 MonoClass *env_class;
7076 MonoMethod *exit_method = NULL;
7080 exit_code = decode_int (p, &p, end);
7082 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
7084 /* Have to send a reply before exiting */
7085 send_reply_packet (id, 0, buf);
7087 /* Clear all event requests */
7088 mono_loader_lock ();
7089 while (event_requests->len > 0) {
7090 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
7092 clear_event_request (req->id, req->event_kind);
7094 mono_loader_unlock ();
7097 * The JDWP documentation says that the shutdown is not orderly. It doesn't
7098 * specify whenever a VM_DEATH event is sent. We currently do an orderly
7099 * shutdown by hijacking a thread to execute Environment.Exit (). This is
7100 * better than doing the shutdown ourselves, since it avoids various races.
7104 wait_for_suspend ();
7106 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7107 env_class = mono_class_try_load_from_name (mono_defaults.corlib, "System", "Environment");
7109 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
7112 mono_loader_lock ();
7113 thread = (MonoInternalThread *)mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
7114 mono_loader_unlock ();
7116 if (thread && exit_method) {
7117 mono_loader_lock ();
7118 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
7119 mono_loader_unlock ();
7121 args = g_new0 (gpointer, 1);
7122 args [0] = g_malloc (sizeof (int));
7123 *(int*)(args [0]) = exit_code;
7125 tls->pending_invoke = g_new0 (InvokeData, 1);
7126 tls->pending_invoke->method = exit_method;
7127 tls->pending_invoke->args = args;
7128 tls->pending_invoke->nmethods = 1;
7130 while (suspend_count > 0)
7134 * No thread found, do it ourselves.
7135 * FIXME: This can race with normal shutdown etc.
7137 while (suspend_count > 0)
7140 if (!mono_runtime_try_shutdown ())
7143 mono_environment_exitcode_set (exit_code);
7145 /* Suspend all managed threads since the runtime is going away */
7146 DEBUG_PRINTF (1, "Suspending all threads...\n");
7147 mono_thread_suspend_all_other_threads ();
7148 DEBUG_PRINTF (1, "Shutting down the runtime...\n");
7149 mono_runtime_quit ();
7150 transport_close2 ();
7151 DEBUG_PRINTF (1, "Exiting...\n");
7157 case CMD_VM_INVOKE_METHOD:
7158 case CMD_VM_INVOKE_METHODS: {
7159 int objid = decode_objid (p, &p, end);
7161 DebuggerTlsData *tls;
7162 int i, count, flags, nmethods;
7165 err = get_object (objid, (MonoObject**)&thread);
7166 if (err != ERR_NONE)
7169 flags = decode_int (p, &p, end);
7171 if (command == CMD_VM_INVOKE_METHODS)
7172 nmethods = decode_int (p, &p, end);
7176 // Wait for suspending if it already started
7178 wait_for_suspend ();
7179 if (!is_suspended ())
7180 return ERR_NOT_SUSPENDED;
7182 mono_loader_lock ();
7183 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7184 mono_loader_unlock ();
7187 if (!tls->really_suspended)
7188 /* The thread is still running native code, can't do invokes */
7189 return ERR_NOT_SUSPENDED;
7192 * Store the invoke data into tls, the thread will execute it after it is
7195 if (tls->pending_invoke)
7196 return ERR_NOT_SUSPENDED;
7197 tls->pending_invoke = g_new0 (InvokeData, 1);
7198 tls->pending_invoke->id = id;
7199 tls->pending_invoke->flags = flags;
7200 tls->pending_invoke->p = (guint8 *)g_malloc (end - p);
7201 memcpy (tls->pending_invoke->p, p, end - p);
7202 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
7203 tls->pending_invoke->suspend_count = suspend_count;
7204 tls->pending_invoke->nmethods = nmethods;
7206 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
7207 resume_thread (THREAD_TO_INTERNAL (thread));
7210 count = suspend_count;
7211 for (i = 0; i < count; ++i)
7216 case CMD_VM_ABORT_INVOKE: {
7217 int objid = decode_objid (p, &p, end);
7219 DebuggerTlsData *tls;
7223 err = get_object (objid, (MonoObject**)&thread);
7224 if (err != ERR_NONE)
7227 invoke_id = decode_int (p, &p, end);
7229 mono_loader_lock ();
7230 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7233 if (tls->abort_requested) {
7234 DEBUG_PRINTF (1, "Abort already requested.\n");
7235 mono_loader_unlock ();
7240 * Check whether we're still inside the mono_runtime_invoke_checked() and that it's
7241 * actually the correct invocation.
7243 * Careful, we do not stop the thread that's doing the invocation, so we can't
7244 * inspect its stack. However, invoke_method() also acquires the loader lock
7245 * when it's done, so we're safe here.
7249 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
7250 mono_loader_unlock ();
7251 return ERR_NO_INVOCATION;
7254 tls->abort_requested = TRUE;
7256 mono_thread_internal_abort (THREAD_TO_INTERNAL (thread));
7257 mono_loader_unlock ();
7261 case CMD_VM_SET_KEEPALIVE: {
7262 int timeout = decode_int (p, &p, end);
7263 agent_config.keepalive = timeout;
7265 #ifndef DISABLE_SOCKET_TRANSPORT
7272 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
7273 GHashTableIter iter, kiter;
7278 char *fname, *basename;
7279 gboolean ignore_case;
7280 GSList *class_list, *l;
7281 GPtrArray *res_classes, *res_domains;
7283 fname = decode_string (p, &p, end);
7284 ignore_case = decode_byte (p, &p, end);
7286 basename = dbg_path_get_basename (fname);
7288 res_classes = g_ptr_array_new ();
7289 res_domains = g_ptr_array_new ();
7291 mono_loader_lock ();
7292 g_hash_table_iter_init (&iter, domains);
7293 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7294 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
7296 /* Update 'source_file_to_class' cache */
7297 g_hash_table_iter_init (&kiter, info->loaded_classes);
7298 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
7299 if (!g_hash_table_lookup (info->source_files, klass)) {
7300 files = get_source_files_for_type (klass);
7301 g_hash_table_insert (info->source_files, klass, files);
7303 for (i = 0; i < files->len; ++i) {
7304 char *s = (char *)g_ptr_array_index (files, i);
7305 char *s2 = dbg_path_get_basename (s);
7308 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, s2);
7310 class_list = g_slist_prepend (class_list, klass);
7311 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
7313 class_list = g_slist_prepend (class_list, klass);
7314 g_hash_table_insert (info->source_file_to_class, s2, class_list);
7317 /* The _ignorecase hash contains the lowercase path */
7318 s3 = strdup_tolower (s2);
7319 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
7321 class_list = g_slist_prepend (class_list, klass);
7322 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
7324 class_list = g_slist_prepend (class_list, klass);
7325 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
7337 s = strdup_tolower (basename);
7338 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
7341 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, basename);
7344 for (l = class_list; l; l = l->next) {
7345 klass = (MonoClass *)l->data;
7347 g_ptr_array_add (res_classes, klass);
7348 g_ptr_array_add (res_domains, domain);
7351 mono_loader_unlock ();
7356 buffer_add_int (buf, res_classes->len);
7357 for (i = 0; i < res_classes->len; ++i)
7358 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7359 g_ptr_array_free (res_classes, TRUE);
7360 g_ptr_array_free (res_domains, TRUE);
7363 case CMD_VM_GET_TYPES: {
7364 GHashTableIter iter;
7368 gboolean ignore_case;
7369 GPtrArray *res_classes, *res_domains;
7370 MonoTypeNameParse info;
7372 name = decode_string (p, &p, end);
7373 ignore_case = decode_byte (p, &p, end);
7375 if (!mono_reflection_parse_type (name, &info)) {
7377 mono_reflection_free_type_info (&info);
7378 return ERR_INVALID_ARGUMENT;
7381 res_classes = g_ptr_array_new ();
7382 res_domains = g_ptr_array_new ();
7384 mono_loader_lock ();
7385 g_hash_table_iter_init (&iter, domains);
7386 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7388 gboolean type_resolve;
7392 mono_domain_assemblies_lock (domain);
7393 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7394 ass = (MonoAssembly *)tmp->data;
7398 type_resolve = TRUE;
7399 /* FIXME really okay to call while holding locks? */
7400 t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignore_case, &type_resolve, &error);
7401 mono_error_cleanup (&error);
7403 g_ptr_array_add (res_classes, mono_type_get_class (t));
7404 g_ptr_array_add (res_domains, domain);
7408 mono_domain_assemblies_unlock (domain);
7410 mono_loader_unlock ();
7413 mono_reflection_free_type_info (&info);
7415 buffer_add_int (buf, res_classes->len);
7416 for (i = 0; i < res_classes->len; ++i)
7417 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7418 g_ptr_array_free (res_classes, TRUE);
7419 g_ptr_array_free (res_domains, TRUE);
7422 case CMD_VM_START_BUFFERING:
7423 case CMD_VM_STOP_BUFFERING:
7424 /* Handled in the main loop */
7427 return ERR_NOT_IMPLEMENTED;
7434 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7440 case CMD_EVENT_REQUEST_SET: {
7442 int i, event_kind, suspend_policy, nmodifiers;
7446 MonoThread *step_thread;
7447 int step_thread_id = 0;
7448 StepDepth depth = STEP_DEPTH_INTO;
7449 StepSize size = STEP_SIZE_MIN;
7450 StepFilter filter = STEP_FILTER_NONE;
7454 event_kind = decode_byte (p, &p, end);
7455 suspend_policy = decode_byte (p, &p, end);
7456 nmodifiers = decode_byte (p, &p, end);
7458 req = (EventRequest *)g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7459 req->id = InterlockedIncrement (&event_request_id);
7460 req->event_kind = event_kind;
7461 req->suspend_policy = suspend_policy;
7462 req->nmodifiers = nmodifiers;
7465 for (i = 0; i < nmodifiers; ++i) {
7466 mod = (ModifierKind)decode_byte (p, &p, end);
7468 req->modifiers [i].kind = mod;
7469 if (mod == MOD_KIND_COUNT) {
7470 req->modifiers [i].data.count = decode_int (p, &p, end);
7471 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7472 method = decode_methodid (p, &p, end, &domain, &err);
7473 if (err != ERR_NONE)
7475 location = decode_long (p, &p, end);
7476 } else if (mod == MOD_KIND_STEP) {
7477 step_thread_id = decode_id (p, &p, end);
7478 size = (StepSize)decode_int (p, &p, end);
7479 depth = (StepDepth)decode_int (p, &p, end);
7480 if (CHECK_PROTOCOL_VERSION (2, 16))
7481 filter = (StepFilter)decode_int (p, &p, end);
7482 req->modifiers [i].data.filter = filter;
7483 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7484 /* Treat STEP_THOUGH the same as HIDDEN */
7485 req->modifiers [i].data.filter = (StepFilter)(req->modifiers [i].data.filter | STEP_FILTER_DEBUGGER_STEP_THROUGH);
7486 } else if (mod == MOD_KIND_THREAD_ONLY) {
7487 int id = decode_id (p, &p, end);
7489 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7490 if (err != ERR_NONE) {
7494 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7495 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7497 if (err != ERR_NONE)
7499 req->modifiers [i].caught = decode_byte (p, &p, end);
7500 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7501 if (CHECK_PROTOCOL_VERSION (2, 25))
7502 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7504 req->modifiers [i].subclasses = TRUE;
7505 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" : "");
7507 req->modifiers [i].data.exc_class = exc_class;
7509 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
7511 return ERR_INVALID_ARGUMENT;
7514 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7515 int n = decode_int (p, &p, end);
7518 // +1 because we don't know length and we use last element to check for end
7519 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n + 1);
7520 for (j = 0; j < n; ++j) {
7521 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7522 if (err != ERR_NONE) {
7523 g_free (req->modifiers [i].data.assemblies);
7527 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7528 int n = decode_int (p, &p, end);
7531 modifier = &req->modifiers [i];
7532 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7533 for (j = 0; j < n; ++j) {
7534 char *s = decode_string (p, &p, end);
7538 s2 = strdup_tolower (s);
7539 g_hash_table_insert (modifier->data.source_files, s2, s2);
7543 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7544 int n = decode_int (p, &p, end);
7547 modifier = &req->modifiers [i];
7548 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7549 for (j = 0; j < n; ++j) {
7550 char *s = decode_string (p, &p, end);
7553 g_hash_table_insert (modifier->data.type_names, s, s);
7557 return ERR_NOT_IMPLEMENTED;
7561 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7564 req->info = set_breakpoint (method, location, req, &error);
7565 if (!mono_error_ok (&error)) {
7567 DEBUG_PRINTF (1, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error));
7568 mono_error_cleanup (&error);
7569 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7571 } else if (req->event_kind == EVENT_KIND_STEP) {
7572 g_assert (step_thread_id);
7574 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7575 if (err != ERR_NONE) {
7580 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, filter, req);
7581 if (err != ERR_NONE) {
7585 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7586 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7587 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7588 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7589 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7590 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7592 if (req->nmodifiers) {
7594 return ERR_NOT_IMPLEMENTED;
7598 mono_loader_lock ();
7599 g_ptr_array_add (event_requests, req);
7601 if (agent_config.defer) {
7602 /* Transmit cached data to the client on receipt of the event request */
7603 switch (req->event_kind) {
7604 case EVENT_KIND_APPDOMAIN_CREATE:
7605 /* Emit load events for currently loaded domains */
7606 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7608 case EVENT_KIND_ASSEMBLY_LOAD:
7609 /* Emit load events for currently loaded assemblies */
7610 mono_assembly_foreach (emit_assembly_load, NULL);
7612 case EVENT_KIND_THREAD_START:
7613 /* Emit start events for currently started threads */
7614 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7616 case EVENT_KIND_TYPE_LOAD:
7617 /* Emit type load events for currently loaded types */
7618 mono_domain_foreach (send_types_for_domain, NULL);
7624 mono_loader_unlock ();
7626 buffer_add_int (buf, req->id);
7629 case CMD_EVENT_REQUEST_CLEAR: {
7630 int etype = decode_byte (p, &p, end);
7631 int req_id = decode_int (p, &p, end);
7633 // FIXME: Make a faster mapping from req_id to request
7634 mono_loader_lock ();
7635 clear_event_request (req_id, etype);
7636 mono_loader_unlock ();
7639 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7642 mono_loader_lock ();
7644 while (i < event_requests->len) {
7645 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
7647 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7648 clear_breakpoint ((MonoBreakpoint *)req->info);
7650 g_ptr_array_remove_index_fast (event_requests, i);
7656 mono_loader_unlock ();
7660 return ERR_NOT_IMPLEMENTED;
7667 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7673 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7674 buffer_add_domainid (buf, mono_get_root_domain ());
7677 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7678 domain = decode_domainid (p, &p, end, NULL, &err);
7679 if (err != ERR_NONE)
7681 buffer_add_string (buf, domain->friendly_name);
7684 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7689 domain = decode_domainid (p, &p, end, NULL, &err);
7690 if (err != ERR_NONE)
7692 mono_loader_lock ();
7694 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7697 buffer_add_int (buf, count);
7698 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7699 ass = (MonoAssembly *)tmp->data;
7700 buffer_add_assemblyid (buf, domain, ass);
7702 mono_loader_unlock ();
7705 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7706 domain = decode_domainid (p, &p, end, NULL, &err);
7707 if (err != ERR_NONE)
7710 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7713 case CMD_APPDOMAIN_GET_CORLIB: {
7714 domain = decode_domainid (p, &p, end, NULL, &err);
7715 if (err != ERR_NONE)
7718 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7721 case CMD_APPDOMAIN_CREATE_STRING: {
7725 domain = decode_domainid (p, &p, end, NULL, &err);
7726 if (err != ERR_NONE)
7728 s = decode_string (p, &p, end);
7730 o = mono_string_new (domain, s);
7731 buffer_add_objid (buf, (MonoObject*)o);
7734 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7737 MonoDomain *domain2;
7740 domain = decode_domainid (p, &p, end, NULL, &err);
7741 if (err != ERR_NONE)
7743 klass = decode_typeid (p, &p, end, &domain2, &err);
7744 if (err != ERR_NONE)
7748 g_assert (domain == domain2);
7750 o = mono_object_new_checked (domain, klass, &error);
7751 mono_error_assert_ok (&error);
7753 err = decode_value (&klass->byval_arg, domain, (guint8 *)mono_object_unbox (o), p, &p, end);
7754 if (err != ERR_NONE)
7757 buffer_add_objid (buf, o);
7761 return ERR_NOT_IMPLEMENTED;
7768 get_assembly_object_command (MonoDomain *domain, MonoAssembly *ass, Buffer *buf, MonoError *error)
7770 HANDLE_FUNCTION_ENTER();
7771 ErrorCode err = ERR_NONE;
7772 mono_error_init (error);
7773 MonoReflectionAssemblyHandle o = mono_assembly_get_object_handle (domain, ass, error);
7774 if (MONO_HANDLE_IS_NULL (o)) {
7775 err = ERR_INVALID_OBJECT;
7778 buffer_add_objid (buf, MONO_HANDLE_RAW (MONO_HANDLE_CAST (MonoObject, o)));
7780 HANDLE_FUNCTION_RETURN_VAL (err);
7785 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7791 ass = decode_assemblyid (p, &p, end, &domain, &err);
7792 if (err != ERR_NONE)
7796 case CMD_ASSEMBLY_GET_LOCATION: {
7797 buffer_add_string (buf, mono_image_get_filename (ass->image));
7800 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7804 if (ass->image->dynamic) {
7805 buffer_add_id (buf, 0);
7807 token = mono_image_get_entry_point (ass->image);
7809 buffer_add_id (buf, 0);
7812 m = mono_get_method_checked (ass->image, token, NULL, NULL, &error);
7814 mono_error_cleanup (&error); /* FIXME don't swallow the error */
7815 buffer_add_methodid (buf, domain, m);
7820 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7821 buffer_add_moduleid (buf, domain, ass->image);
7824 case CMD_ASSEMBLY_GET_OBJECT: {
7826 err = get_assembly_object_command (domain, ass, buf, &error);
7827 mono_error_cleanup (&error);
7830 case CMD_ASSEMBLY_GET_TYPE: {
7832 char *s = decode_string (p, &p, end);
7833 gboolean ignorecase = decode_byte (p, &p, end);
7834 MonoTypeNameParse info;
7836 gboolean type_resolve, res;
7837 MonoDomain *d = mono_domain_get ();
7839 /* This is needed to be able to find referenced assemblies */
7840 res = mono_domain_set (domain, FALSE);
7843 if (!mono_reflection_parse_type (s, &info)) {
7846 if (info.assembly.name)
7848 t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignorecase, &type_resolve, &error);
7849 if (!is_ok (&error)) {
7850 mono_error_cleanup (&error); /* FIXME don't swallow the error */
7851 mono_reflection_free_type_info (&info);
7853 return ERR_INVALID_ARGUMENT;
7856 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
7857 mono_reflection_free_type_info (&info);
7860 mono_domain_set (d, TRUE);
7864 case CMD_ASSEMBLY_GET_NAME: {
7866 MonoAssembly *mass = ass;
7868 name = g_strdup_printf (
7869 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7871 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7872 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7873 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7874 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7876 buffer_add_string (buf, name);
7881 return ERR_NOT_IMPLEMENTED;
7888 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7894 case CMD_MODULE_GET_INFO: {
7895 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7898 basename = g_path_get_basename (image->name);
7899 buffer_add_string (buf, basename); // name
7900 buffer_add_string (buf, image->module_name); // scopename
7901 buffer_add_string (buf, image->name); // fqname
7902 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7903 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7908 return ERR_NOT_IMPLEMENTED;
7915 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7921 case CMD_FIELD_GET_INFO: {
7922 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
7924 buffer_add_string (buf, f->name);
7925 buffer_add_typeid (buf, domain, f->parent);
7926 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7927 buffer_add_int (buf, f->type->attrs);
7931 return ERR_NOT_IMPLEMENTED;
7938 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7940 if (val && val->vtable->klass == mono_defaults.runtimetype_class) {
7941 /* Special case these so the client doesn't have to handle Type objects */
7943 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7944 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7945 } else if (MONO_TYPE_IS_REFERENCE (t))
7946 buffer_add_value (buf, t, &val, domain);
7948 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7952 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7958 buffer_add_int (buf, 0);
7962 for (i = 0; i < cinfo->num_attrs; ++i) {
7963 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7966 buffer_add_int (buf, nattrs);
7968 for (i = 0; i < cinfo->num_attrs; ++i) {
7969 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7970 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7971 MonoArray *typed_args, *named_args;
7973 CattrNamedArg *arginfo = NULL;
7976 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
7977 if (!mono_error_ok (&error)) {
7978 DEBUG_PRINTF (2, "[dbg] mono_reflection_create_custom_attr_data_args () failed with: '%s'\n", mono_error_get_message (&error));
7979 mono_error_cleanup (&error);
7980 return ERR_LOADER_ERROR;
7983 buffer_add_methodid (buf, domain, attr->ctor);
7987 buffer_add_int (buf, mono_array_length (typed_args));
7988 for (j = 0; j < mono_array_length (typed_args); ++j) {
7989 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7991 t = mono_method_signature (attr->ctor)->params [j];
7993 buffer_add_cattr_arg (buf, t, domain, val);
7996 buffer_add_int (buf, 0);
8001 buffer_add_int (buf, mono_array_length (named_args));
8003 for (j = 0; j < mono_array_length (named_args); ++j) {
8004 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
8006 if (arginfo [j].prop) {
8007 buffer_add_byte (buf, 0x54);
8008 buffer_add_propertyid (buf, domain, arginfo [j].prop);
8009 } else if (arginfo [j].field) {
8010 buffer_add_byte (buf, 0x53);
8011 buffer_add_fieldid (buf, domain, arginfo [j].field);
8013 g_assert_not_reached ();
8016 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
8019 buffer_add_int (buf, 0);
8028 /* FIXME: Code duplication with icall.c */
8030 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
8035 mono_class_setup_interfaces (klass, error);
8036 if (!mono_error_ok (error))
8039 for (i = 0; i < klass->interface_count; i++) {
8040 ic = klass->interfaces [i];
8041 g_hash_table_insert (ifaces, ic, ic);
8043 collect_interfaces (ic, ifaces, error);
8044 if (!mono_error_ok (error))
8050 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8062 case CMD_TYPE_GET_INFO: {
8063 buffer_add_string (buf, klass->name_space);
8064 buffer_add_string (buf, klass->name);
8066 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
8067 buffer_add_string (buf, name);
8069 buffer_add_assemblyid (buf, domain, klass->image->assembly);
8070 buffer_add_moduleid (buf, domain, klass->image);
8071 buffer_add_typeid (buf, domain, klass->parent);
8072 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
8073 buffer_add_typeid (buf, domain, klass->element_class);
8075 buffer_add_id (buf, 0);
8076 buffer_add_int (buf, klass->type_token);
8077 buffer_add_byte (buf, klass->rank);
8078 buffer_add_int (buf, mono_class_get_flags (klass));
8080 type = &klass->byval_arg;
8081 // FIXME: Can't decide whenever a class represents a byref type
8084 if (type->type == MONO_TYPE_PTR)
8086 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
8088 if (type->type == MONO_TYPE_VALUETYPE)
8090 if (klass->enumtype)
8092 if (mono_class_is_gtd (klass))
8094 if (mono_class_is_gtd (klass) || mono_class_is_ginst (klass))
8096 buffer_add_byte (buf, b);
8099 while ((nested = mono_class_get_nested_types (klass, &iter)))
8101 buffer_add_int (buf, nnested);
8103 while ((nested = mono_class_get_nested_types (klass, &iter)))
8104 buffer_add_typeid (buf, domain, nested);
8105 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8106 if (mono_class_is_gtd (klass))
8107 buffer_add_typeid (buf, domain, klass);
8108 else if (mono_class_is_ginst (klass))
8109 buffer_add_typeid (buf, domain, mono_class_get_generic_class (klass)->container_class);
8111 buffer_add_id (buf, 0);
8113 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8116 if (mono_class_is_ginst (klass)) {
8117 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
8119 count = inst->type_argc;
8120 buffer_add_int (buf, count);
8121 for (i = 0; i < count; i++)
8122 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8123 } else if (mono_class_is_gtd (klass)) {
8124 MonoGenericContainer *container = mono_class_get_generic_container (klass);
8127 count = container->type_argc;
8128 buffer_add_int (buf, count);
8129 for (i = 0; i < count; i++) {
8130 pklass = mono_class_from_generic_parameter_internal (mono_generic_container_get_param (container, i));
8131 buffer_add_typeid (buf, domain, pklass);
8134 buffer_add_int (buf, 0);
8139 case CMD_TYPE_GET_METHODS: {
8142 gpointer iter = NULL;
8145 mono_class_setup_methods (klass);
8147 nmethods = mono_class_num_methods (klass);
8149 buffer_add_int (buf, nmethods);
8151 while ((m = mono_class_get_methods (klass, &iter))) {
8152 buffer_add_methodid (buf, domain, m);
8155 g_assert (i == nmethods);
8158 case CMD_TYPE_GET_FIELDS: {
8161 gpointer iter = NULL;
8164 nfields = mono_class_num_fields (klass);
8166 buffer_add_int (buf, nfields);
8168 while ((f = mono_class_get_fields (klass, &iter))) {
8169 buffer_add_fieldid (buf, domain, f);
8170 buffer_add_string (buf, f->name);
8171 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
8172 buffer_add_int (buf, f->type->attrs);
8175 g_assert (i == nfields);
8178 case CMD_TYPE_GET_PROPERTIES: {
8181 gpointer iter = NULL;
8184 nprops = mono_class_num_properties (klass);
8186 buffer_add_int (buf, nprops);
8188 while ((p = mono_class_get_properties (klass, &iter))) {
8189 buffer_add_propertyid (buf, domain, p);
8190 buffer_add_string (buf, p->name);
8191 buffer_add_methodid (buf, domain, p->get);
8192 buffer_add_methodid (buf, domain, p->set);
8193 buffer_add_int (buf, p->attrs);
8196 g_assert (i == nprops);
8199 case CMD_TYPE_GET_CATTRS: {
8200 MonoClass *attr_klass;
8201 MonoCustomAttrInfo *cinfo;
8203 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8204 /* attr_klass can be NULL */
8205 if (err != ERR_NONE)
8208 cinfo = mono_custom_attrs_from_class_checked (klass, &error);
8209 if (!is_ok (&error)) {
8210 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8211 return ERR_LOADER_ERROR;
8214 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8215 if (err != ERR_NONE)
8219 case CMD_TYPE_GET_FIELD_CATTRS: {
8220 MonoClass *attr_klass;
8221 MonoCustomAttrInfo *cinfo;
8222 MonoClassField *field;
8224 field = decode_fieldid (p, &p, end, NULL, &err);
8225 if (err != ERR_NONE)
8227 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8228 if (err != ERR_NONE)
8231 cinfo = mono_custom_attrs_from_field_checked (klass, field, &error);
8232 if (!is_ok (&error)) {
8233 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8234 return ERR_LOADER_ERROR;
8237 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8238 if (err != ERR_NONE)
8242 case CMD_TYPE_GET_PROPERTY_CATTRS: {
8243 MonoClass *attr_klass;
8244 MonoCustomAttrInfo *cinfo;
8247 prop = decode_propertyid (p, &p, end, NULL, &err);
8248 if (err != ERR_NONE)
8250 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8251 if (err != ERR_NONE)
8254 cinfo = mono_custom_attrs_from_property_checked (klass, prop, &error);
8255 if (!is_ok (&error)) {
8256 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8257 return ERR_LOADER_ERROR;
8260 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8261 if (err != ERR_NONE)
8265 case CMD_TYPE_GET_VALUES:
8266 case CMD_TYPE_GET_VALUES_2: {
8273 MonoThread *thread_obj;
8274 MonoInternalThread *thread = NULL;
8275 guint32 special_static_type;
8277 if (command == CMD_TYPE_GET_VALUES_2) {
8278 int objid = decode_objid (p, &p, end);
8281 err = get_object (objid, (MonoObject**)&thread_obj);
8282 if (err != ERR_NONE)
8285 thread = THREAD_TO_INTERNAL (thread_obj);
8288 len = decode_int (p, &p, end);
8289 for (i = 0; i < len; ++i) {
8290 f = decode_fieldid (p, &p, end, NULL, &err);
8291 if (err != ERR_NONE)
8294 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8295 return ERR_INVALID_FIELDID;
8296 special_static_type = mono_class_field_get_special_static_type (f);
8297 if (special_static_type != SPECIAL_STATIC_NONE) {
8298 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
8299 return ERR_INVALID_FIELDID;
8302 /* Check that the field belongs to the object */
8304 for (k = klass; k; k = k->parent) {
8305 if (k == f->parent) {
8311 return ERR_INVALID_FIELDID;
8313 vtable = mono_class_vtable (domain, f->parent);
8314 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8315 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val, &error);
8316 if (!is_ok (&error))
8317 return ERR_INVALID_FIELDID;
8318 buffer_add_value (buf, f->type, val, domain);
8323 case CMD_TYPE_SET_VALUES: {
8331 len = decode_int (p, &p, end);
8332 for (i = 0; i < len; ++i) {
8333 f = decode_fieldid (p, &p, end, NULL, &err);
8334 if (err != ERR_NONE)
8337 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8338 return ERR_INVALID_FIELDID;
8339 if (mono_class_field_is_special_static (f))
8340 return ERR_INVALID_FIELDID;
8342 /* Check that the field belongs to the object */
8344 for (k = klass; k; k = k->parent) {
8345 if (k == f->parent) {
8351 return ERR_INVALID_FIELDID;
8353 // FIXME: Check for literal/const
8355 vtable = mono_class_vtable (domain, f->parent);
8356 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8357 err = decode_value (f->type, domain, val, p, &p, end);
8358 if (err != ERR_NONE) {
8362 if (MONO_TYPE_IS_REFERENCE (f->type))
8363 mono_field_static_set_value (vtable, f, *(gpointer*)val);
8365 mono_field_static_set_value (vtable, f, val);
8370 case CMD_TYPE_GET_OBJECT: {
8371 MonoObject *o = (MonoObject*)mono_type_get_object_checked (domain, &klass->byval_arg, &error);
8372 if (!mono_error_ok (&error)) {
8373 mono_error_cleanup (&error);
8374 return ERR_INVALID_OBJECT;
8376 buffer_add_objid (buf, o);
8379 case CMD_TYPE_GET_SOURCE_FILES:
8380 case CMD_TYPE_GET_SOURCE_FILES_2: {
8381 char *source_file, *base;
8385 files = get_source_files_for_type (klass);
8387 buffer_add_int (buf, files->len);
8388 for (i = 0; i < files->len; ++i) {
8389 source_file = (char *)g_ptr_array_index (files, i);
8390 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8391 buffer_add_string (buf, source_file);
8393 base = dbg_path_get_basename (source_file);
8394 buffer_add_string (buf, base);
8397 g_free (source_file);
8399 g_ptr_array_free (files, TRUE);
8402 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8403 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8405 if (err != ERR_NONE)
8407 if (mono_class_is_assignable_from (klass, oklass))
8408 buffer_add_byte (buf, 1);
8410 buffer_add_byte (buf, 0);
8413 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8414 char *name = decode_string (p, &p, end);
8415 int i, flags = decode_int (p, &p, end);
8419 mono_error_init (&error);
8420 array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &error);
8421 if (!is_ok (&error)) {
8422 mono_error_cleanup (&error);
8423 return ERR_LOADER_ERROR;
8425 buffer_add_int (buf, array->len);
8426 for (i = 0; i < array->len; ++i) {
8427 MonoMethod *method = (MonoMethod *)g_ptr_array_index (array, i);
8428 buffer_add_methodid (buf, domain, method);
8431 g_ptr_array_free (array, TRUE);
8435 case CMD_TYPE_GET_INTERFACES: {
8437 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8438 MonoClass *tclass, *iface;
8439 GHashTableIter iter;
8443 for (parent = tclass; parent; parent = parent->parent) {
8444 mono_class_setup_interfaces (parent, &error);
8445 if (!mono_error_ok (&error))
8446 return ERR_LOADER_ERROR;
8447 collect_interfaces (parent, iface_hash, &error);
8448 if (!mono_error_ok (&error))
8449 return ERR_LOADER_ERROR;
8452 buffer_add_int (buf, g_hash_table_size (iface_hash));
8454 g_hash_table_iter_init (&iter, iface_hash);
8455 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8456 buffer_add_typeid (buf, domain, iface);
8457 g_hash_table_destroy (iface_hash);
8460 case CMD_TYPE_GET_INTERFACE_MAP: {
8461 int tindex, ioffset;
8462 gboolean variance_used;
8464 int len, nmethods, i;
8468 len = decode_int (p, &p, end);
8469 mono_class_setup_vtable (klass);
8471 for (tindex = 0; tindex < len; ++tindex) {
8472 iclass = decode_typeid (p, &p, end, NULL, &err);
8473 if (err != ERR_NONE)
8476 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8478 return ERR_INVALID_ARGUMENT;
8480 nmethods = mono_class_num_methods (iclass);
8481 buffer_add_int (buf, nmethods);
8484 while ((method = mono_class_get_methods (iclass, &iter))) {
8485 buffer_add_methodid (buf, domain, method);
8487 for (i = 0; i < nmethods; ++i)
8488 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
8492 case CMD_TYPE_IS_INITIALIZED: {
8493 MonoVTable *vtable = mono_class_vtable (domain, klass);
8496 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8498 buffer_add_int (buf, 0);
8501 case CMD_TYPE_CREATE_INSTANCE: {
8505 obj = mono_object_new_checked (domain, klass, &error);
8506 mono_error_assert_ok (&error);
8507 buffer_add_objid (buf, obj);
8511 return ERR_NOT_IMPLEMENTED;
8518 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8521 MonoDomain *old_domain;
8525 klass = decode_typeid (p, &p, end, &domain, &err);
8526 if (err != ERR_NONE)
8529 old_domain = mono_domain_get ();
8531 mono_domain_set (domain, TRUE);
8533 err = type_commands_internal (command, klass, domain, p, end, buf);
8535 mono_domain_set (old_domain, TRUE);
8541 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8543 MonoMethodHeader *header;
8547 case CMD_METHOD_GET_NAME: {
8548 buffer_add_string (buf, method->name);
8551 case CMD_METHOD_GET_DECLARING_TYPE: {
8552 buffer_add_typeid (buf, domain, method->klass);
8555 case CMD_METHOD_GET_DEBUG_INFO: {
8557 MonoDebugMethodInfo *minfo;
8559 int i, j, n_il_offsets;
8561 GPtrArray *source_file_list;
8562 MonoSymSeqPoint *sym_seq_points;
8564 header = mono_method_get_header_checked (method, &error);
8566 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8567 buffer_add_int (buf, 0);
8568 buffer_add_string (buf, "");
8569 buffer_add_int (buf, 0);
8573 minfo = mono_debug_lookup_method (method);
8575 buffer_add_int (buf, header->code_size);
8576 buffer_add_string (buf, "");
8577 buffer_add_int (buf, 0);
8578 mono_metadata_free_mh (header);
8582 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, &source_files, &sym_seq_points, &n_il_offsets);
8583 buffer_add_int (buf, header->code_size);
8584 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8585 buffer_add_int (buf, source_file_list->len);
8586 for (i = 0; i < source_file_list->len; ++i) {
8587 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
8588 buffer_add_string (buf, sinfo->source_file);
8589 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8590 for (j = 0; j < 16; ++j)
8591 buffer_add_byte (buf, sinfo->hash [j]);
8595 buffer_add_string (buf, source_file);
8597 buffer_add_int (buf, n_il_offsets);
8598 DEBUG_PRINTF (10, "Line number table for method %s:\n", mono_method_full_name (method, TRUE));
8599 for (i = 0; i < n_il_offsets; ++i) {
8600 MonoSymSeqPoint *sp = &sym_seq_points [i];
8601 const char *srcfile = "";
8603 if (source_files [i] != -1) {
8604 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, source_files [i]);
8605 srcfile = sinfo->source_file;
8607 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);
8608 buffer_add_int (buf, sp->il_offset);
8609 buffer_add_int (buf, sp->line);
8610 if (CHECK_PROTOCOL_VERSION (2, 13))
8611 buffer_add_int (buf, source_files [i]);
8612 if (CHECK_PROTOCOL_VERSION (2, 19))
8613 buffer_add_int (buf, sp->column);
8614 if (CHECK_PROTOCOL_VERSION (2, 32)) {
8615 buffer_add_int (buf, sp->end_line);
8616 buffer_add_int (buf, sp->end_column);
8619 g_free (source_file);
8620 g_free (source_files);
8621 g_free (sym_seq_points);
8622 g_ptr_array_free (source_file_list, TRUE);
8623 mono_metadata_free_mh (header);
8626 case CMD_METHOD_GET_PARAM_INFO: {
8627 MonoMethodSignature *sig = mono_method_signature (method);
8631 /* FIXME: mono_class_from_mono_type () and byrefs */
8633 /* FIXME: Use a smaller encoding */
8634 buffer_add_int (buf, sig->call_convention);
8635 buffer_add_int (buf, sig->param_count);
8636 buffer_add_int (buf, sig->generic_param_count);
8637 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
8638 for (i = 0; i < sig->param_count; ++i) {
8640 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
8643 /* Emit parameter names */
8644 names = g_new (char *, sig->param_count);
8645 mono_method_get_param_names (method, (const char **) names);
8646 for (i = 0; i < sig->param_count; ++i)
8647 buffer_add_string (buf, names [i]);
8652 case CMD_METHOD_GET_LOCALS_INFO: {
8655 MonoDebugLocalsInfo *locals;
8656 int *locals_map = NULL;
8658 header = mono_method_get_header_checked (method, &error);
8660 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8661 return ERR_INVALID_ARGUMENT;
8664 locals = mono_debug_lookup_locals (method);
8666 if (CHECK_PROTOCOL_VERSION (2, 43)) {
8668 buffer_add_int (buf, 1);
8669 buffer_add_int (buf, 0);
8670 buffer_add_int (buf, header->code_size);
8672 buffer_add_int (buf, header->num_locals);
8674 for (i = 0; i < header->num_locals; ++i) {
8675 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
8678 for (i = 0; i < header->num_locals; ++i) {
8680 sprintf (lname, "V_%d", i);
8681 buffer_add_string (buf, lname);
8684 for (i = 0; i < header->num_locals; ++i) {
8685 buffer_add_int (buf, 0);
8686 buffer_add_int (buf, header->code_size);
8689 if (CHECK_PROTOCOL_VERSION (2, 43)) {
8691 buffer_add_int (buf, locals->num_blocks);
8693 for (i = 0; i < locals->num_blocks; ++i) {
8694 buffer_add_int (buf, locals->code_blocks [i].start_offset - last_start);
8695 buffer_add_int (buf, locals->code_blocks [i].end_offset - locals->code_blocks [i].start_offset);
8696 last_start = locals->code_blocks [i].start_offset;
8700 num_locals = locals->num_locals;
8701 buffer_add_int (buf, num_locals);
8704 for (i = 0; i < num_locals; ++i) {
8705 g_assert (locals->locals [i].index < header->num_locals);
8706 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [locals->locals [i].index]));
8709 for (i = 0; i < num_locals; ++i)
8710 buffer_add_string (buf, locals->locals [i].name);
8712 for (i = 0; i < num_locals; ++i) {
8713 if (locals->locals [i].block) {
8714 buffer_add_int (buf, locals->locals [i].block->start_offset);
8715 buffer_add_int (buf, locals->locals [i].block->end_offset);
8717 buffer_add_int (buf, 0);
8718 buffer_add_int (buf, header->code_size);
8722 mono_metadata_free_mh (header);
8725 mono_debug_free_locals (locals);
8726 g_free (locals_map);
8730 case CMD_METHOD_GET_INFO:
8731 buffer_add_int (buf, method->flags);
8732 buffer_add_int (buf, method->iflags);
8733 buffer_add_int (buf, method->token);
8734 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8736 if (method->is_generic)
8738 if (mono_method_signature (method)->generic_param_count)
8740 buffer_add_byte (buf, attrs);
8741 if (method->is_generic || method->is_inflated) {
8744 if (method->is_generic) {
8747 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8749 result = imethod->declaring;
8750 if (imethod->context.class_inst) {
8751 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8752 /*Generic methods gets the context of the GTD.*/
8753 if (mono_class_get_context (klass)) {
8755 result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), &error);
8756 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8761 buffer_add_methodid (buf, domain, result);
8763 buffer_add_id (buf, 0);
8765 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8766 if (mono_method_signature (method)->generic_param_count) {
8769 if (method->is_inflated) {
8770 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
8772 count = inst->type_argc;
8773 buffer_add_int (buf, count);
8775 for (i = 0; i < count; i++)
8776 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8778 buffer_add_int (buf, 0);
8780 } else if (method->is_generic) {
8781 MonoGenericContainer *container = mono_method_get_generic_container (method);
8783 count = mono_method_signature (method)->generic_param_count;
8784 buffer_add_int (buf, count);
8785 for (i = 0; i < count; i++) {
8786 MonoGenericParam *param = mono_generic_container_get_param (container, i);
8787 MonoClass *pklass = mono_class_from_generic_parameter_internal (param);
8788 buffer_add_typeid (buf, domain, pklass);
8791 buffer_add_int (buf, 0);
8794 buffer_add_int (buf, 0);
8799 case CMD_METHOD_GET_BODY: {
8803 header = mono_method_get_header_checked (method, &error);
8805 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8806 buffer_add_int (buf, 0);
8808 if (CHECK_PROTOCOL_VERSION (2, 18))
8809 buffer_add_int (buf, 0);
8811 buffer_add_int (buf, header->code_size);
8812 for (i = 0; i < header->code_size; ++i)
8813 buffer_add_byte (buf, header->code [i]);
8815 if (CHECK_PROTOCOL_VERSION (2, 18)) {
8816 buffer_add_int (buf, header->num_clauses);
8817 for (i = 0; i < header->num_clauses; ++i) {
8818 MonoExceptionClause *clause = &header->clauses [i];
8820 buffer_add_int (buf, clause->flags);
8821 buffer_add_int (buf, clause->try_offset);
8822 buffer_add_int (buf, clause->try_len);
8823 buffer_add_int (buf, clause->handler_offset);
8824 buffer_add_int (buf, clause->handler_len);
8825 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
8826 buffer_add_typeid (buf, domain, clause->data.catch_class);
8827 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8828 buffer_add_int (buf, clause->data.filter_offset);
8832 mono_metadata_free_mh (header);
8837 case CMD_METHOD_RESOLVE_TOKEN: {
8838 guint32 token = decode_int (p, &p, end);
8841 switch (mono_metadata_token_code (token)) {
8842 case MONO_TOKEN_STRING: {
8847 s = mono_ldstr_checked (domain, method->klass->image, mono_metadata_token_index (token), &error);
8848 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
8850 s2 = mono_string_to_utf8_checked (s, &error);
8851 mono_error_assert_ok (&error);
8853 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8854 buffer_add_string (buf, s2);
8861 MonoClass *handle_class;
8863 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8864 val = mono_method_get_wrapper_data (method, token);
8865 handle_class = (MonoClass *)mono_method_get_wrapper_data (method, token + 1);
8867 if (handle_class == NULL) {
8868 // Can't figure out the token type
8869 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8873 val = mono_ldtoken_checked (method->klass->image, token, &handle_class, NULL, &error);
8875 g_error ("Could not load token due to %s", mono_error_get_message (&error));
8878 if (handle_class == mono_defaults.typehandle_class) {
8879 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8880 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8881 buffer_add_typeid (buf, domain, (MonoClass *) val);
8883 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
8884 } else if (handle_class == mono_defaults.fieldhandle_class) {
8885 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8886 buffer_add_fieldid (buf, domain, (MonoClassField *)val);
8887 } else if (handle_class == mono_defaults.methodhandle_class) {
8888 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8889 buffer_add_methodid (buf, domain, (MonoMethod *)val);
8890 } else if (handle_class == mono_defaults.string_class) {
8893 s = mono_string_to_utf8_checked ((MonoString *)val, &error);
8894 mono_error_assert_ok (&error);
8895 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8896 buffer_add_string (buf, s);
8899 g_assert_not_reached ();
8906 case CMD_METHOD_GET_CATTRS: {
8908 MonoClass *attr_klass;
8909 MonoCustomAttrInfo *cinfo;
8911 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8912 /* attr_klass can be NULL */
8913 if (err != ERR_NONE)
8916 cinfo = mono_custom_attrs_from_method_checked (method, &error);
8917 if (!is_ok (&error)) {
8918 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8919 return ERR_LOADER_ERROR;
8922 err = buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
8923 if (err != ERR_NONE)
8927 case CMD_METHOD_MAKE_GENERIC_METHOD: {
8929 MonoType **type_argv;
8933 MonoGenericInst *ginst;
8934 MonoGenericContext tmp_context;
8935 MonoMethod *inflated;
8937 type_argc = decode_int (p, &p, end);
8938 type_argv = g_new0 (MonoType*, type_argc);
8939 for (i = 0; i < type_argc; ++i) {
8940 klass = decode_typeid (p, &p, end, &d, &err);
8941 if (err != ERR_NONE) {
8947 return ERR_INVALID_ARGUMENT;
8949 type_argv [i] = &klass->byval_arg;
8951 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
8953 tmp_context.class_inst = mono_class_is_ginst (method->klass) ? mono_class_get_generic_class (method->klass)->context.class_inst : NULL;
8954 tmp_context.method_inst = ginst;
8956 inflated = mono_class_inflate_generic_method_checked (method, &tmp_context, &error);
8957 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8958 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
8959 return ERR_INVALID_ARGUMENT;
8960 buffer_add_methodid (buf, domain, inflated);
8964 return ERR_NOT_IMPLEMENTED;
8971 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8974 MonoDomain *old_domain;
8978 method = decode_methodid (p, &p, end, &domain, &err);
8979 if (err != ERR_NONE)
8982 old_domain = mono_domain_get ();
8984 mono_domain_set (domain, TRUE);
8986 err = method_commands_internal (command, method, domain, p, end, buf);
8988 mono_domain_set (old_domain, TRUE);
8994 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8996 int objid = decode_objid (p, &p, end);
8998 MonoThread *thread_obj;
8999 MonoInternalThread *thread;
9001 err = get_object (objid, (MonoObject**)&thread_obj);
9002 if (err != ERR_NONE)
9005 thread = THREAD_TO_INTERNAL (thread_obj);
9008 case CMD_THREAD_GET_NAME: {
9010 gunichar2 *s = mono_thread_get_name (thread, &name_len);
9013 buffer_add_int (buf, 0);
9018 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
9020 buffer_add_int (buf, len);
9021 buffer_add_data (buf, (guint8*)name, len);
9026 case CMD_THREAD_GET_FRAME_INFO: {
9027 DebuggerTlsData *tls;
9028 int i, start_frame, length;
9030 // Wait for suspending if it already started
9031 // FIXME: Races with suspend_count
9032 while (!is_suspended ()) {
9034 wait_for_suspend ();
9038 wait_for_suspend ();
9039 if (!is_suspended ())
9040 return ERR_NOT_SUSPENDED;
9043 start_frame = decode_int (p, &p, end);
9044 length = decode_int (p, &p, end);
9046 if (start_frame != 0 || length != -1)
9047 return ERR_NOT_IMPLEMENTED;
9049 mono_loader_lock ();
9050 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9051 mono_loader_unlock ();
9054 compute_frame_info (thread, tls);
9056 buffer_add_int (buf, tls->frame_count);
9057 for (i = 0; i < tls->frame_count; ++i) {
9058 buffer_add_int (buf, tls->frames [i]->id);
9059 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
9060 buffer_add_int (buf, tls->frames [i]->il_offset);
9062 * Instead of passing the frame type directly to the client, we associate
9063 * it with the previous frame using a set of flags. This avoids lots of
9064 * conditional code in the client, since a frame whose type isn't
9065 * FRAME_TYPE_MANAGED has no method, location, etc.
9067 buffer_add_byte (buf, tls->frames [i]->flags);
9072 case CMD_THREAD_GET_STATE:
9073 buffer_add_int (buf, thread->state);
9075 case CMD_THREAD_GET_INFO:
9076 buffer_add_byte (buf, thread->threadpool_thread);
9078 case CMD_THREAD_GET_ID:
9079 buffer_add_long (buf, (guint64)(gsize)thread);
9081 case CMD_THREAD_GET_TID:
9082 buffer_add_long (buf, (guint64)thread->tid);
9084 case CMD_THREAD_SET_IP: {
9085 DebuggerTlsData *tls;
9088 MonoSeqPointInfo *seq_points;
9093 method = decode_methodid (p, &p, end, &domain, &err);
9094 if (err != ERR_NONE)
9096 il_offset = decode_long (p, &p, end);
9098 while (!is_suspended ()) {
9100 wait_for_suspend ();
9103 mono_loader_lock ();
9104 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9105 mono_loader_unlock ();
9108 compute_frame_info (thread, tls);
9109 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
9110 return ERR_INVALID_ARGUMENT;
9112 found_sp = mono_find_seq_point (domain, method, il_offset, &seq_points, &sp);
9114 g_assert (seq_points);
9117 return ERR_INVALID_ARGUMENT;
9119 // FIXME: Check that the ip change is safe
9121 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);
9122 MONO_CONTEXT_SET_IP (&tls->restore_state.ctx, (guint8*)tls->frames [0]->ji->code_start + sp.native_offset);
9126 return ERR_NOT_IMPLEMENTED;
9133 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9137 MonoThread *thread_obj;
9138 MonoInternalThread *thread;
9139 int pos, i, len, frame_idx;
9140 DebuggerTlsData *tls;
9142 MonoDebugMethodJitInfo *jit;
9143 MonoMethodSignature *sig;
9145 MonoMethodHeader *header;
9147 objid = decode_objid (p, &p, end);
9148 err = get_object (objid, (MonoObject**)&thread_obj);
9149 if (err != ERR_NONE)
9152 thread = THREAD_TO_INTERNAL (thread_obj);
9154 id = decode_id (p, &p, end);
9156 mono_loader_lock ();
9157 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9158 mono_loader_unlock ();
9161 for (i = 0; i < tls->frame_count; ++i) {
9162 if (tls->frames [i]->id == id)
9165 if (i == tls->frame_count)
9166 return ERR_INVALID_FRAMEID;
9169 frame = tls->frames [frame_idx];
9171 /* This is supported for frames without has_ctx etc. set */
9172 if (command == CMD_STACK_FRAME_GET_DOMAIN) {
9173 if (CHECK_PROTOCOL_VERSION (2, 38))
9174 buffer_add_domainid (buf, frame->domain);
9178 if (!frame->has_ctx)
9179 return ERR_ABSENT_INFORMATION;
9182 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
9183 if (!frame->jit && frame->api_method->is_inflated)
9184 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
9188 /* This could happen for aot images with no jit debug info */
9189 s = mono_method_full_name (frame->api_method, TRUE);
9190 DEBUG_PRINTF (1, "[dbg] No debug information found for '%s'.\n", s);
9192 return ERR_ABSENT_INFORMATION;
9197 sig = mono_method_signature (frame->actual_method);
9199 if (!jit->has_var_info || !mono_get_seq_points (frame->domain, frame->actual_method))
9201 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
9203 return ERR_ABSENT_INFORMATION;
9206 case CMD_STACK_FRAME_GET_VALUES: {
9208 len = decode_int (p, &p, end);
9209 header = mono_method_get_header_checked (frame->actual_method, &error);
9210 mono_error_assert_ok (&error); /* FIXME report error */
9212 for (i = 0; i < len; ++i) {
9213 pos = decode_int (p, &p, end);
9218 DEBUG_PRINTF (4, "[dbg] send arg %d.\n", pos);
9220 g_assert (pos >= 0 && pos < jit->num_params);
9222 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
9224 MonoDebugLocalsInfo *locals;
9226 locals = mono_debug_lookup_locals (frame->method);
9228 g_assert (pos < locals->num_locals);
9229 pos = locals->locals [pos].index;
9230 mono_debug_free_locals (locals);
9232 g_assert (pos >= 0 && pos < jit->num_locals);
9234 DEBUG_PRINTF (4, "[dbg] send local %d.\n", pos);
9236 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
9239 mono_metadata_free_mh (header);
9242 case CMD_STACK_FRAME_GET_THIS: {
9243 if (frame->api_method->klass->valuetype) {
9244 if (!sig->hasthis) {
9245 MonoObject *p = NULL;
9246 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
9248 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9251 if (!sig->hasthis) {
9252 MonoObject *p = NULL;
9253 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
9255 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9260 case CMD_STACK_FRAME_SET_VALUES: {
9264 MonoDebugVarInfo *var;
9266 len = decode_int (p, &p, end);
9267 header = mono_method_get_header_checked (frame->actual_method, &error);
9268 mono_error_assert_ok (&error); /* FIXME report error */
9270 for (i = 0; i < len; ++i) {
9271 pos = decode_int (p, &p, end);
9276 g_assert (pos >= 0 && pos < jit->num_params);
9278 t = sig->params [pos];
9279 var = &jit->params [pos];
9281 MonoDebugLocalsInfo *locals;
9283 locals = mono_debug_lookup_locals (frame->method);
9285 g_assert (pos < locals->num_locals);
9286 pos = locals->locals [pos].index;
9287 mono_debug_free_locals (locals);
9289 g_assert (pos >= 0 && pos < jit->num_locals);
9291 t = header->locals [pos];
9292 var = &jit->locals [pos];
9295 if (MONO_TYPE_IS_REFERENCE (t))
9296 val_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
9298 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9299 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9300 if (err != ERR_NONE)
9303 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9305 mono_metadata_free_mh (header);
9308 case CMD_STACK_FRAME_GET_DOMAIN: {
9309 if (CHECK_PROTOCOL_VERSION (2, 38))
9310 buffer_add_domainid (buf, frame->domain);
9313 case CMD_STACK_FRAME_SET_THIS: {
9316 MonoDebugVarInfo *var;
9318 t = &frame->actual_method->klass->byval_arg;
9319 /* Checked by the sender */
9320 g_assert (MONO_TYPE_ISSTRUCT (t));
9321 var = jit->this_var;
9324 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9325 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9326 if (err != ERR_NONE)
9329 set_var (&frame->actual_method->klass->this_arg, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9333 return ERR_NOT_IMPLEMENTED;
9340 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9343 int objid, index, len, i, esize;
9347 objid = decode_objid (p, &p, end);
9348 err = get_object (objid, (MonoObject**)&arr);
9349 if (err != ERR_NONE)
9353 case CMD_ARRAY_REF_GET_LENGTH:
9354 buffer_add_int (buf, arr->obj.vtable->klass->rank);
9356 buffer_add_int (buf, arr->max_length);
9357 buffer_add_int (buf, 0);
9359 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
9360 buffer_add_int (buf, arr->bounds [i].length);
9361 buffer_add_int (buf, arr->bounds [i].lower_bound);
9365 case CMD_ARRAY_REF_GET_VALUES:
9366 index = decode_int (p, &p, end);
9367 len = decode_int (p, &p, end);
9369 g_assert (index >= 0 && len >= 0);
9370 // Reordered to avoid integer overflow
9371 g_assert (!(index > arr->max_length - len));
9373 esize = mono_array_element_size (arr->obj.vtable->klass);
9374 for (i = index; i < index + len; ++i) {
9375 elem = (gpointer*)((char*)arr->vector + (i * esize));
9376 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
9379 case CMD_ARRAY_REF_SET_VALUES:
9380 index = decode_int (p, &p, end);
9381 len = decode_int (p, &p, end);
9383 g_assert (index >= 0 && len >= 0);
9384 // Reordered to avoid integer overflow
9385 g_assert (!(index > arr->max_length - len));
9387 esize = mono_array_element_size (arr->obj.vtable->klass);
9388 for (i = index; i < index + len; ++i) {
9389 elem = (gpointer*)((char*)arr->vector + (i * esize));
9391 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, (guint8 *)elem, p, &p, end);
9395 return ERR_NOT_IMPLEMENTED;
9402 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9408 int i, index, length;
9410 gboolean use_utf16 = FALSE;
9412 objid = decode_objid (p, &p, end);
9413 err = get_object (objid, (MonoObject**)&str);
9414 if (err != ERR_NONE)
9418 case CMD_STRING_REF_GET_VALUE:
9419 if (CHECK_PROTOCOL_VERSION (2, 41)) {
9420 for (i = 0; i < mono_string_length (str); ++i)
9421 if (mono_string_chars (str)[i] == 0)
9423 buffer_add_byte (buf, use_utf16 ? 1 : 0);
9426 buffer_add_int (buf, mono_string_length (str) * 2);
9427 buffer_add_data (buf, (guint8*)mono_string_chars (str), mono_string_length (str) * 2);
9430 s = mono_string_to_utf8_checked (str, &error);
9431 mono_error_assert_ok (&error);
9432 buffer_add_string (buf, s);
9436 case CMD_STRING_REF_GET_LENGTH:
9437 buffer_add_long (buf, mono_string_length (str));
9439 case CMD_STRING_REF_GET_CHARS:
9440 index = decode_long (p, &p, end);
9441 length = decode_long (p, &p, end);
9442 if (index > mono_string_length (str) - length)
9443 return ERR_INVALID_ARGUMENT;
9444 c = mono_string_chars (str) + index;
9445 for (i = 0; i < length; ++i)
9446 buffer_add_short (buf, c [i]);
9449 return ERR_NOT_IMPLEMENTED;
9456 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9467 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9468 objid = decode_objid (p, &p, end);
9469 err = get_object (objid, &obj);
9470 if (err != ERR_NONE)
9471 buffer_add_int (buf, 1);
9473 buffer_add_int (buf, 0);
9477 objid = decode_objid (p, &p, end);
9478 err = get_object (objid, &obj);
9479 if (err != ERR_NONE)
9482 MonoClass *obj_type;
9483 gboolean remote_obj = FALSE;
9485 obj_type = obj->vtable->klass;
9486 if (mono_class_is_transparent_proxy (obj_type)) {
9487 obj_type = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
9491 g_assert (obj_type);
9494 case CMD_OBJECT_REF_GET_TYPE:
9495 /* This handles transparent proxies too */
9496 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9498 case CMD_OBJECT_REF_GET_VALUES:
9499 len = decode_int (p, &p, end);
9501 for (i = 0; i < len; ++i) {
9502 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9503 if (err != ERR_NONE)
9506 /* Check that the field belongs to the object */
9508 for (k = obj_type; k; k = k->parent) {
9509 if (k == f->parent) {
9515 return ERR_INVALID_FIELDID;
9517 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9521 if (mono_class_field_is_special_static (f))
9522 return ERR_INVALID_FIELDID;
9524 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9525 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9526 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9527 mono_field_static_get_value_checked (vtable, f, val, &error);
9528 if (!is_ok (&error)) {
9529 mono_error_cleanup (&error); /* FIXME report the error */
9530 return ERR_INVALID_OBJECT;
9532 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9535 guint8 *field_value = NULL;
9538 #ifndef DISABLE_REMOTING
9539 void *field_storage = NULL;
9540 field_value = mono_load_remote_field_checked(obj, obj_type, f, &field_storage, &error);
9541 if (!is_ok (&error)) {
9542 mono_error_cleanup (&error); /* FIXME report the error */
9543 return ERR_INVALID_OBJECT;
9546 g_assert_not_reached ();
9549 field_value = (guint8*)obj + f->offset;
9551 buffer_add_value (buf, f->type, field_value, obj->vtable->domain);
9555 case CMD_OBJECT_REF_SET_VALUES:
9556 len = decode_int (p, &p, end);
9558 for (i = 0; i < len; ++i) {
9559 f = decode_fieldid (p, &p, end, NULL, &err);
9560 if (err != ERR_NONE)
9563 /* Check that the field belongs to the object */
9565 for (k = obj_type; k; k = k->parent) {
9566 if (k == f->parent) {
9572 return ERR_INVALID_FIELDID;
9574 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9578 if (mono_class_field_is_special_static (f))
9579 return ERR_INVALID_FIELDID;
9581 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9582 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9584 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9585 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
9586 if (err != ERR_NONE) {
9590 mono_field_static_set_value (vtable, f, val);
9593 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
9594 if (err != ERR_NONE)
9599 case CMD_OBJECT_REF_GET_ADDRESS:
9600 buffer_add_long (buf, (gssize)obj);
9602 case CMD_OBJECT_REF_GET_DOMAIN:
9603 buffer_add_domainid (buf, obj->vtable->domain);
9605 case CMD_OBJECT_REF_GET_INFO:
9606 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9607 buffer_add_domainid (buf, obj->vtable->domain);
9610 return ERR_NOT_IMPLEMENTED;
9617 command_set_to_string (CommandSet command_set)
9619 switch (command_set) {
9622 case CMD_SET_OBJECT_REF:
9623 return "OBJECT_REF";
9624 case CMD_SET_STRING_REF:
9625 return "STRING_REF";
9626 case CMD_SET_THREAD:
9628 case CMD_SET_ARRAY_REF:
9630 case CMD_SET_EVENT_REQUEST:
9631 return "EVENT_REQUEST";
9632 case CMD_SET_STACK_FRAME:
9633 return "STACK_FRAME";
9634 case CMD_SET_APPDOMAIN:
9636 case CMD_SET_ASSEMBLY:
9638 case CMD_SET_METHOD:
9642 case CMD_SET_MODULE:
9653 static const char* vm_cmds_str [] = {
9661 "SET_PROTOCOL_VERSION",
9664 "GET_TYPES_FOR_SOURCE_FILE",
9669 static const char* thread_cmds_str[] = {
9679 static const char* event_cmds_str[] = {
9682 "REQUEST_CLEAR_ALL_BREAKPOINTS"
9685 static const char* appdomain_cmds_str[] = {
9687 "GET_FRIENDLY_NAME",
9689 "GET_ENTRY_ASSEMBLY",
9692 "CREATE_BOXED_VALUE"
9695 static const char* assembly_cmds_str[] = {
9698 "GET_MANIFEST_MODULE",
9704 static const char* module_cmds_str[] = {
9708 static const char* field_cmds_str[] = {
9712 static const char* method_cmds_str[] = {
9714 "GET_DECLARING_TYPE",
9722 "MAKE_GENERIC_METHOD"
9725 static const char* type_cmds_str[] = {
9733 "IS_ASSIGNABLE_FROM",
9737 "GET_PROPERTY_CATTRS",
9738 "GET_SOURCE_FILES_2",
9740 "GET_METHODS_BY_NAME_FLAGS",
9742 "GET_INTERFACE_MAP",
9746 static const char* stack_frame_cmds_str[] = {
9754 static const char* array_cmds_str[] = {
9760 static const char* string_cmds_str[] = {
9766 static const char* object_cmds_str[] = {
9777 cmd_to_string (CommandSet set, int command)
9785 cmds_len = G_N_ELEMENTS (vm_cmds_str);
9787 case CMD_SET_OBJECT_REF:
9788 cmds = object_cmds_str;
9789 cmds_len = G_N_ELEMENTS (object_cmds_str);
9791 case CMD_SET_STRING_REF:
9792 cmds = string_cmds_str;
9793 cmds_len = G_N_ELEMENTS (string_cmds_str);
9795 case CMD_SET_THREAD:
9796 cmds = thread_cmds_str;
9797 cmds_len = G_N_ELEMENTS (thread_cmds_str);
9799 case CMD_SET_ARRAY_REF:
9800 cmds = array_cmds_str;
9801 cmds_len = G_N_ELEMENTS (array_cmds_str);
9803 case CMD_SET_EVENT_REQUEST:
9804 cmds = event_cmds_str;
9805 cmds_len = G_N_ELEMENTS (event_cmds_str);
9807 case CMD_SET_STACK_FRAME:
9808 cmds = stack_frame_cmds_str;
9809 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
9811 case CMD_SET_APPDOMAIN:
9812 cmds = appdomain_cmds_str;
9813 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
9815 case CMD_SET_ASSEMBLY:
9816 cmds = assembly_cmds_str;
9817 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
9819 case CMD_SET_METHOD:
9820 cmds = method_cmds_str;
9821 cmds_len = G_N_ELEMENTS (method_cmds_str);
9824 cmds = type_cmds_str;
9825 cmds_len = G_N_ELEMENTS (type_cmds_str);
9827 case CMD_SET_MODULE:
9828 cmds = module_cmds_str;
9829 cmds_len = G_N_ELEMENTS (module_cmds_str);
9832 cmds = field_cmds_str;
9833 cmds_len = G_N_ELEMENTS (field_cmds_str);
9836 cmds = event_cmds_str;
9837 cmds_len = G_N_ELEMENTS (event_cmds_str);
9842 if (command > 0 && command <= cmds_len)
9843 return cmds [command - 1];
9849 wait_for_attach (void)
9851 #ifndef DISABLE_SOCKET_TRANSPORT
9852 if (listen_fd == -1) {
9853 DEBUG_PRINTF (1, "[dbg] Invalid listening socket\n");
9857 /* Block and wait for client connection */
9858 conn_fd = socket_transport_accept (listen_fd);
9860 DEBUG_PRINTF (1, "Accepted connection on %d\n", conn_fd);
9861 if (conn_fd == -1) {
9862 DEBUG_PRINTF (1, "[dbg] Bad client connection\n");
9866 g_assert_not_reached ();
9870 disconnected = !transport_handshake ();
9872 DEBUG_PRINTF (1, "Transport handshake failed!\n");
9882 * This thread handles communication with the debugger client using a JDWP
9886 debugger_thread (void *arg)
9889 int res, len, id, flags, command = 0;
9890 CommandSet command_set = (CommandSet)0;
9891 guint8 header [HEADER_LENGTH];
9892 guint8 *data, *p, *end;
9896 gboolean attach_failed = FALSE;
9898 DEBUG_PRINTF (1, "[dbg] Agent thread started, pid=%p\n", (gpointer) (gsize) mono_native_thread_id_get ());
9900 debugger_thread_id = mono_native_thread_id_get ();
9902 MonoThread *thread = mono_thread_attach (mono_get_root_domain ());
9903 mono_thread_set_name_internal (thread->internal_thread, mono_string_new (mono_get_root_domain (), "Debugger agent"), TRUE, &error);
9904 mono_error_assert_ok (&error);
9906 thread->internal_thread->state |= ThreadState_Background;
9907 thread->internal_thread->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
9909 if (agent_config.defer) {
9910 if (!wait_for_attach ()) {
9911 DEBUG_PRINTF (1, "[dbg] Can't attach, aborting debugger thread.\n");
9912 attach_failed = TRUE; // Don't abort process when we can't listen
9914 mono_set_is_debugger_attached (TRUE);
9915 /* Send start event to client */
9916 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
9919 mono_set_is_debugger_attached (TRUE);
9922 while (!attach_failed) {
9923 res = transport_recv (header, HEADER_LENGTH);
9925 /* This will break if the socket is closed during shutdown too */
9926 if (res != HEADER_LENGTH) {
9927 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH);
9932 end = header + HEADER_LENGTH;
9934 len = decode_int (p, &p, end);
9935 id = decode_int (p, &p, end);
9936 flags = decode_byte (p, &p, end);
9937 command_set = (CommandSet)decode_byte (p, &p, end);
9938 command = decode_byte (p, &p, end);
9940 g_assert (flags == 0);
9943 const char *cmd_str;
9946 cmd_str = cmd_to_string (command_set, command);
9948 sprintf (cmd_num, "%d", command);
9952 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);
9955 data = (guint8 *)g_malloc (len - HEADER_LENGTH);
9956 if (len - HEADER_LENGTH > 0)
9958 res = transport_recv (data, len - HEADER_LENGTH);
9959 if (res != len - HEADER_LENGTH) {
9960 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH);
9966 end = data + (len - HEADER_LENGTH);
9968 buffer_init (&buf, 128);
9973 /* Process the request */
9974 switch (command_set) {
9976 err = vm_commands (command, id, p, end, &buf);
9977 if (err == ERR_NONE && command == CMD_VM_INVOKE_METHOD)
9978 /* Sent after the invoke is complete */
9981 case CMD_SET_EVENT_REQUEST:
9982 err = event_commands (command, p, end, &buf);
9984 case CMD_SET_APPDOMAIN:
9985 err = domain_commands (command, p, end, &buf);
9987 case CMD_SET_ASSEMBLY:
9988 err = assembly_commands (command, p, end, &buf);
9990 case CMD_SET_MODULE:
9991 err = module_commands (command, p, end, &buf);
9994 err = field_commands (command, p, end, &buf);
9997 err = type_commands (command, p, end, &buf);
9999 case CMD_SET_METHOD:
10000 err = method_commands (command, p, end, &buf);
10002 case CMD_SET_THREAD:
10003 err = thread_commands (command, p, end, &buf);
10005 case CMD_SET_STACK_FRAME:
10006 err = frame_commands (command, p, end, &buf);
10008 case CMD_SET_ARRAY_REF:
10009 err = array_commands (command, p, end, &buf);
10011 case CMD_SET_STRING_REF:
10012 err = string_commands (command, p, end, &buf);
10014 case CMD_SET_OBJECT_REF:
10015 err = object_commands (command, p, end, &buf);
10018 err = ERR_NOT_IMPLEMENTED;
10021 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
10022 buffer_replies = TRUE;
10026 if (buffer_replies) {
10027 buffer_reply_packet (id, err, &buf);
10029 send_reply_packet (id, err, &buf);
10030 //DEBUG_PRINTF (1, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000);
10034 if (err == ERR_NONE && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
10035 send_buffered_reply_packets ();
10036 buffer_replies = FALSE;
10040 buffer_free (&buf);
10042 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
10046 mono_set_is_debugger_attached (FALSE);
10048 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
10049 debugger_thread_exited = TRUE;
10050 mono_coop_cond_signal (&debugger_thread_exited_cond);
10051 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
10053 DEBUG_PRINTF (1, "[dbg] Debugger thread exited.\n");
10055 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
10056 DEBUG_PRINTF (2, "[dbg] Detached - restarting clean debugger thread.\n");
10057 start_debugger_thread ();
10063 #else /* DISABLE_DEBUGGER_AGENT */
10066 mono_debugger_agent_parse_options (char *options)
10068 g_error ("This runtime is configured with the debugger agent disabled.");
10072 mono_debugger_agent_init (void)
10077 mono_debugger_agent_breakpoint_hit (void *sigctx)
10082 mono_debugger_agent_single_step_event (void *sigctx)
10087 mono_debugger_agent_free_domain_info (MonoDomain *domain)
10092 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
10093 MonoContext *catch_ctx)
10098 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
10103 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
10108 mono_debugger_agent_user_break (void)
10114 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
10119 mono_debugger_agent_debug_log_is_enabled (void)
10125 mono_debugger_agent_unhandled_exception (MonoException *exc)
10127 g_assert_not_reached ();
10131 debugger_agent_single_step_from_context (MonoContext *ctx)
10133 g_assert_not_reached ();
10137 debugger_agent_breakpoint_from_context (MonoContext *ctx)
10139 g_assert_not_reached ();