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/socket-io.h>
63 #include <mono/metadata/assembly.h>
64 #include <mono/metadata/runtime.h>
65 #include <mono/metadata/verify-internals.h>
66 #include <mono/metadata/reflection-internals.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 */
575 * Contains additional information for an event
578 /* For EVENT_KIND_EXCEPTION */
580 MonoContext catch_ctx;
582 /* For EVENT_KIND_USER_LOG */
584 char *category, *message;
585 /* For EVENT_KIND_TYPE_LOAD */
589 /* Dummy structure used for the profiler callbacks */
595 guint8 *buf, *p, *end;
598 typedef struct ReplyPacket {
604 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
606 #ifdef PLATFORM_ANDROID
607 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { g_print (__VA_ARGS__); } } while (0)
609 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { fprintf (log_file, __VA_ARGS__); fflush (log_file); } } while (0)
613 #define get_last_sock_error() WSAGetLastError()
614 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
615 #define MONO_EINTR WSAEINTR
617 #define get_last_sock_error() errno
618 #define MONO_EWOULDBLOCK EWOULDBLOCK
619 #define MONO_EINTR EINTR
622 #define CHECK_PROTOCOL_VERSION(major,minor) \
623 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
629 static AgentConfig agent_config;
632 * Whenever the agent is fully initialized.
633 * When using the onuncaught or onthrow options, only some parts of the agent are
634 * initialized on startup, and the full initialization which includes connection
635 * establishment and the startup of the agent thread is only done in response to
638 static gint32 inited;
640 #ifndef DISABLE_SOCKET_TRANSPORT
642 static int listen_fd;
645 static int packet_id = 0;
647 static int objref_id = 0;
649 static int event_request_id = 0;
651 static int frame_id = 0;
653 static GPtrArray *event_requests;
655 static MonoNativeTlsKey debugger_tls_id;
657 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
659 /* Maps MonoInternalThread -> DebuggerTlsData */
660 /* Protected by the loader lock */
661 static MonoGHashTable *thread_to_tls;
663 /* Maps tid -> MonoInternalThread */
664 /* Protected by the loader lock */
665 static MonoGHashTable *tid_to_thread;
667 /* Maps tid -> MonoThread (not MonoInternalThread) */
668 /* Protected by the loader lock */
669 static MonoGHashTable *tid_to_thread_obj;
671 static MonoNativeThreadId debugger_thread_id;
673 static MonoThreadHandle *debugger_thread_handle;
675 static int log_level;
677 static gboolean embedding;
679 static FILE *log_file;
681 /* Assemblies whose assembly load event has no been sent yet */
682 /* Protected by the dbg lock */
683 static GPtrArray *pending_assembly_loads;
685 /* Whenever the debugger thread has exited */
686 static gboolean debugger_thread_exited;
688 /* Cond variable used to wait for debugger_thread_exited becoming true */
689 static MonoCoopCond debugger_thread_exited_cond;
691 /* Mutex for the cond var above */
692 static MonoCoopMutex debugger_thread_exited_mutex;
694 static DebuggerProfiler debugger_profiler;
696 /* The single step request instance */
697 static SingleStepReq *ss_req;
699 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
700 /* Number of single stepping operations in progress */
704 /* The protocol version of the client */
705 static int major_version, minor_version;
707 /* Whenever the variables above are set by the client */
708 static gboolean protocol_version_set;
710 /* A hash table containing all active domains */
711 /* Protected by the loader lock */
712 static GHashTable *domains;
714 /* The number of times the runtime is suspended */
715 static gint32 suspend_count;
717 /* Whenever to buffer reply messages and send them together */
718 static gboolean buffer_replies;
720 /* Buffered reply packets */
721 static ReplyPacket reply_packets [128];
724 #define dbg_lock() mono_coop_mutex_lock (&debug_mutex)
725 #define dbg_unlock() mono_coop_mutex_unlock (&debug_mutex)
726 static MonoCoopMutex debug_mutex;
728 static void transport_init (void);
729 static void transport_connect (const char *address);
730 static gboolean transport_handshake (void);
731 static void register_transport (DebuggerTransport *trans);
733 static gsize WINAPI debugger_thread (void *arg);
735 static void runtime_initialized (MonoProfiler *prof);
737 static void runtime_shutdown (MonoProfiler *prof);
739 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
741 static void thread_end (MonoProfiler *prof, uintptr_t tid);
743 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
745 static void appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain);
747 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
749 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
751 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
753 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
755 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
757 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
759 static void emit_assembly_load (gpointer assembly, gpointer user_data);
761 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
763 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
765 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
767 static void start_single_stepping (void);
769 static void stop_single_stepping (void);
771 static void suspend_current (void);
773 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
775 static void clear_types_for_assembly (MonoAssembly *assembly);
777 static void clear_breakpoints_for_domain (MonoDomain *domain);
779 static void process_profiler_event (EventKind event, gpointer arg);
781 /* Submodule init/cleanup */
782 static void breakpoints_init (void);
783 static void breakpoints_cleanup (void);
785 static void objrefs_init (void);
786 static void objrefs_cleanup (void);
788 static void ids_init (void);
789 static void ids_cleanup (void);
791 static void suspend_init (void);
793 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch,
794 StackFrame **frames, int nframes);
795 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req);
796 static void ss_destroy (SingleStepReq *req);
798 static void start_debugger_thread (void);
799 static void stop_debugger_thread (void);
801 static void finish_agent_init (gboolean on_startup);
803 static void process_profiler_event (EventKind event, gpointer arg);
805 static void invalidate_frames (DebuggerTlsData *tls);
807 #ifndef DISABLE_SOCKET_TRANSPORT
809 register_socket_transport (void);
812 static inline gboolean
813 is_debugger_thread (void)
815 return mono_native_thread_id_equals (mono_native_thread_id_get (), debugger_thread_id);
819 parse_address (char *address, char **host, int *port)
821 char *pos = strchr (address, ':');
823 if (pos == NULL || pos == address)
826 *host = (char *)g_malloc (pos - address + 1);
827 strncpy (*host, address, pos - address);
828 (*host) [pos - address] = '\0';
830 *port = atoi (pos + 1);
838 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
839 fprintf (stderr, "Available options:\n");
840 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
841 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
842 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
843 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
844 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
845 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
846 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
847 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
848 fprintf (stderr, " setpgid=y/n\t\t\tWhether to call setpid(0, 0) after startup.\n");
849 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
853 parse_flag (const char *option, char *flag)
855 if (!strcmp (flag, "y"))
857 else if (!strcmp (flag, "n"))
860 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
867 mono_debugger_agent_parse_options (char *options)
874 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
875 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
879 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
881 options = g_strdup_printf ("%s,%s", options, extra);
883 agent_config.enabled = TRUE;
884 agent_config.suspend = TRUE;
885 agent_config.server = FALSE;
886 agent_config.defer = FALSE;
887 agent_config.address = NULL;
889 //agent_config.log_level = 10;
891 args = g_strsplit (options, ",", -1);
892 for (ptr = args; ptr && *ptr; ptr ++) {
895 if (strncmp (arg, "transport=", 10) == 0) {
896 agent_config.transport = g_strdup (arg + 10);
897 } else if (strncmp (arg, "address=", 8) == 0) {
898 agent_config.address = g_strdup (arg + 8);
899 } else if (strncmp (arg, "loglevel=", 9) == 0) {
900 agent_config.log_level = atoi (arg + 9);
901 } else if (strncmp (arg, "logfile=", 8) == 0) {
902 agent_config.log_file = g_strdup (arg + 8);
903 } else if (strncmp (arg, "suspend=", 8) == 0) {
904 agent_config.suspend = parse_flag ("suspend", arg + 8);
905 } else if (strncmp (arg, "server=", 7) == 0) {
906 agent_config.server = parse_flag ("server", arg + 7);
907 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
908 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
909 } else if (strncmp (arg, "onthrow=", 8) == 0) {
910 /* We support multiple onthrow= options */
911 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
912 } else if (strncmp (arg, "onthrow", 7) == 0) {
913 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
914 } else if (strncmp (arg, "help", 4) == 0) {
917 } else if (strncmp (arg, "timeout=", 8) == 0) {
918 agent_config.timeout = atoi (arg + 8);
919 } else if (strncmp (arg, "launch=", 7) == 0) {
920 agent_config.launch = g_strdup (arg + 7);
921 } else if (strncmp (arg, "embedding=", 10) == 0) {
922 agent_config.embedding = atoi (arg + 10) == 1;
923 } else if (strncmp (arg, "keepalive=", 10) == 0) {
924 agent_config.keepalive = atoi (arg + 10);
925 } else if (strncmp (arg, "setpgid=", 8) == 0) {
926 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
933 if (agent_config.server && !agent_config.suspend) {
934 /* Waiting for deferred attachment */
935 agent_config.defer = TRUE;
936 if (agent_config.address == NULL) {
937 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (mono_process_current_pid () % 1000));
941 //agent_config.log_level = 0;
943 if (agent_config.transport == NULL) {
944 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
948 if (agent_config.address == NULL && !agent_config.server) {
949 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
954 if (!strcmp (agent_config.transport, "dt_socket")) {
955 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
956 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
963 mono_debugger_agent_init (void)
965 mono_coop_mutex_init_recursive (&debug_mutex);
967 if (!agent_config.enabled)
972 /* Need to know whenever a thread has acquired the loader mutex */
973 mono_loader_lock_track_ownership (TRUE);
975 event_requests = g_ptr_array_new ();
977 mono_coop_mutex_init (&debugger_thread_exited_mutex);
978 mono_coop_cond_init (&debugger_thread_exited_cond);
980 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
981 mono_profiler_set_events ((MonoProfileFlags)(MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS));
982 mono_profiler_install_runtime_initialized (runtime_initialized);
983 mono_profiler_install_appdomain (NULL, appdomain_load, appdomain_start_unload, appdomain_unload);
984 mono_profiler_install_thread (thread_startup, thread_end);
985 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
986 mono_profiler_install_jit_end (jit_end);
988 mono_native_tls_alloc (&debugger_tls_id, NULL);
990 /* Needed by the hash_table_new_type () call below */
991 mono_gc_base_init ();
993 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_DEBUGGER, "thread-to-tls table");
994 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls, MONO_ROOT_SOURCE_DEBUGGER, "thread-to-tls table");
996 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread table");
997 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread table");
999 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");
1000 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread object table");
1002 pending_assembly_loads = g_ptr_array_new ();
1003 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
1005 log_level = agent_config.log_level;
1007 embedding = agent_config.embedding;
1008 disconnected = TRUE;
1010 if (agent_config.log_file) {
1011 log_file = fopen (agent_config.log_file, "w+");
1013 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
1022 breakpoints_init ();
1025 mini_get_debug_options ()->gen_sdb_seq_points = TRUE;
1027 * This is needed because currently we don't handle liveness info.
1029 mini_get_debug_options ()->mdb_optimizations = TRUE;
1031 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
1032 /* This is needed because we can't set local variables in registers yet */
1033 mono_disable_optimizations (MONO_OPT_LINEARS);
1037 * The stack walk done from thread_interrupt () needs to be signal safe, but it
1038 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
1039 * safe (#3411). So load AOT info eagerly when the debugger is running as a
1042 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
1045 if (agent_config.setpgid)
1049 if (!agent_config.onuncaught && !agent_config.onthrow)
1050 finish_agent_init (TRUE);
1054 * finish_agent_init:
1056 * Finish the initialization of the agent. This involves connecting the transport
1057 * and starting the agent thread. This is either done at startup, or
1058 * in response to some event like an unhandled exception.
1061 finish_agent_init (gboolean on_startup)
1065 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
1068 if (agent_config.launch) {
1071 // FIXME: Generated address
1072 // FIXME: Races with transport_connect ()
1074 argv [0] = agent_config.launch;
1075 argv [1] = agent_config.transport;
1076 argv [2] = agent_config.address;
1079 res = g_spawn_async_with_pipes (NULL, argv, NULL, (GSpawnFlags)0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1081 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1086 transport_connect (agent_config.address);
1089 /* Do some which is usually done after sending the VMStart () event */
1090 vm_start_event_sent = TRUE;
1091 start_debugger_thread ();
1096 mono_debugger_agent_cleanup (void)
1101 stop_debugger_thread ();
1103 breakpoints_cleanup ();
1112 #ifndef DISABLE_SOCKET_TRANSPORT
1117 * recv() + handle incomplete reads and EINTR
1120 socket_transport_recv (void *buf, int len)
1126 static gint64 last_keepalive;
1133 res = recv (fd, (char *) buf + total, len - total, flags);
1136 if (agent_config.keepalive) {
1137 gboolean need_keepalive = FALSE;
1138 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1139 need_keepalive = TRUE;
1140 } else if (res == -1) {
1141 /* This could happen if recv () is interrupted repeatedly */
1142 msecs = mono_msec_ticks ();
1143 if (msecs - last_keepalive >= agent_config.keepalive) {
1144 need_keepalive = TRUE;
1145 last_keepalive = msecs;
1148 if (need_keepalive) {
1149 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1153 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1161 set_keepalive (void)
1166 if (!agent_config.keepalive || !conn_fd)
1169 tv.tv_sec = agent_config.keepalive / 1000;
1170 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1172 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1173 g_assert (result >= 0);
1177 socket_transport_accept (int socket_fd)
1180 conn_fd = accept (socket_fd, NULL, NULL);
1183 if (conn_fd == -1) {
1184 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1186 DEBUG_PRINTF (1, "Accepted connection from client, connection fd=%d.\n", conn_fd);
1193 socket_transport_send (void *data, int len)
1200 res = send (conn_fd, data, len, 0);
1201 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1212 * socket_transport_connect:
1214 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1217 socket_transport_connect (const char *address)
1219 MonoAddressInfo *result;
1220 MonoAddressEntry *rp;
1221 int sfd = -1, s, res;
1225 if (agent_config.address) {
1226 res = parse_address (agent_config.address, &host, &port);
1227 g_assert (res == 0);
1238 mono_network_init ();
1240 /* Obtain address(es) matching host/port */
1241 s = mono_get_address_info (host, port, MONO_HINT_UNSPECIFIED, &result);
1243 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, s); // FIXME add portable error conversion functions
1248 if (agent_config.server) {
1249 /* Wait for a connection */
1251 struct sockaddr_in addr;
1254 /* No address, generate one */
1255 sfd = socket (AF_INET, SOCK_STREAM, 0);
1258 /* This will bind the socket to a random port */
1259 res = listen (sfd, 16);
1261 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1266 addrlen = sizeof (addr);
1267 memset (&addr, 0, sizeof (addr));
1268 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1269 g_assert (res == 0);
1271 host = (char*)"127.0.0.1";
1272 port = ntohs (addr.sin_port);
1274 /* Emit the address to stdout */
1275 /* FIXME: Should print another interface, not localhost */
1276 printf ("%s:%d\n", host, port);
1278 /* Listen on the provided address */
1279 for (rp = result->entries; rp != NULL; rp = rp->next) {
1280 MonoSocketAddress sockaddr;
1284 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1286 sfd = socket (rp->family, rp->socktype,
1291 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1294 res = bind (sfd, &sockaddr.addr, sock_len);
1298 res = listen (sfd, 16);
1305 mono_free_address_info (result);
1308 if (agent_config.defer)
1311 DEBUG_PRINTF (1, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout);
1313 if (agent_config.timeout) {
1318 tv.tv_usec = agent_config.timeout * 1000;
1320 FD_SET (sfd, &readfds);
1323 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1327 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1332 conn_fd = socket_transport_accept (sfd);
1336 DEBUG_PRINTF (1, "Accepted connection from client, socket fd=%d.\n", conn_fd);
1338 /* Connect to the specified address */
1339 /* FIXME: Respect the timeout */
1340 for (rp = result->entries; rp != NULL; rp = rp->next) {
1341 MonoSocketAddress sockaddr;
1344 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1346 sfd = socket (rp->family, rp->socktype,
1352 res = connect (sfd, &sockaddr.addr, sock_len);
1356 break; /* Success */
1364 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1370 mono_free_address_info (result);
1373 if (!transport_handshake ())
1378 socket_transport_close1 (void)
1380 /* This will interrupt the agent thread */
1381 /* Close the read part only so it can still send back replies */
1382 /* Also shut down the connection listener so that we can exit normally */
1384 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1385 shutdown (conn_fd, SD_BOTH);
1386 shutdown (listen_fd, SD_BOTH);
1387 closesocket (listen_fd);
1389 shutdown (conn_fd, SHUT_RD);
1390 shutdown (listen_fd, SHUT_RDWR);
1398 socket_transport_close2 (void)
1401 shutdown (conn_fd, SD_BOTH);
1403 shutdown (conn_fd, SHUT_RDWR);
1408 register_socket_transport (void)
1410 DebuggerTransport trans;
1412 trans.name = "dt_socket";
1413 trans.connect = socket_transport_connect;
1414 trans.close1 = socket_transport_close1;
1415 trans.close2 = socket_transport_close2;
1416 trans.send = socket_transport_send;
1417 trans.recv = socket_transport_recv;
1419 register_transport (&trans);
1423 * socket_fd_transport_connect:
1427 socket_fd_transport_connect (const char *address)
1431 res = sscanf (address, "%d", &conn_fd);
1433 fprintf (stderr, "debugger-agent: socket-fd transport address is invalid: '%s'\n", address);
1437 if (!transport_handshake ())
1442 register_socket_fd_transport (void)
1444 DebuggerTransport trans;
1446 /* This is the same as the 'dt_socket' transport, but receives an already connected socket fd */
1447 trans.name = "socket-fd";
1448 trans.connect = socket_fd_transport_connect;
1449 trans.close1 = socket_transport_close1;
1450 trans.close2 = socket_transport_close2;
1451 trans.send = socket_transport_send;
1452 trans.recv = socket_transport_recv;
1454 register_transport (&trans);
1457 #endif /* DISABLE_SOCKET_TRANSPORT */
1463 #define MAX_TRANSPORTS 16
1465 static DebuggerTransport *transport;
1467 static DebuggerTransport transports [MAX_TRANSPORTS];
1468 static int ntransports;
1471 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1474 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1476 register_transport (trans);
1480 register_transport (DebuggerTransport *trans)
1482 g_assert (ntransports < MAX_TRANSPORTS);
1484 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1489 transport_init (void)
1493 #ifndef DISABLE_SOCKET_TRANSPORT
1494 register_socket_transport ();
1495 register_socket_fd_transport ();
1498 for (i = 0; i < ntransports; ++i) {
1499 if (!strcmp (agent_config.transport, transports [i].name))
1502 if (i == ntransports) {
1503 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1504 for (i = 0; i < ntransports; ++i)
1505 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1506 fprintf (stderr, "\n");
1509 transport = &transports [i];
1513 transport_connect (const char *address)
1515 transport->connect (address);
1519 transport_close1 (void)
1521 transport->close1 ();
1525 transport_close2 (void)
1527 transport->close2 ();
1531 transport_send (void *buf, int len)
1533 return transport->send (buf, len);
1537 transport_recv (void *buf, int len)
1539 return transport->recv (buf, len);
1543 mono_debugger_agent_transport_handshake (void)
1545 return transport_handshake ();
1549 transport_handshake (void)
1551 char handshake_msg [128];
1555 disconnected = TRUE;
1557 /* Write handshake message */
1558 sprintf (handshake_msg, "DWP-Handshake");
1561 res = transport_send (handshake_msg, strlen (handshake_msg));
1562 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1564 g_assert (res != -1);
1567 res = transport_recv (buf, strlen (handshake_msg));
1568 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg)) != 0)) {
1569 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1574 * To support older clients, the client sends its protocol version after connecting
1575 * using a command. Until that is received, default to our protocol version.
1577 major_version = MAJOR_VERSION;
1578 minor_version = MINOR_VERSION;
1579 protocol_version_set = FALSE;
1581 #ifndef DISABLE_SOCKET_TRANSPORT
1582 // FIXME: Move this somewhere else
1584 * Set TCP_NODELAY on the socket so the client receives events/command
1585 * results immediately.
1589 int result = setsockopt (conn_fd,
1594 g_assert (result >= 0);
1600 disconnected = FALSE;
1605 stop_debugger_thread (void)
1610 transport_close1 ();
1613 * Wait for the thread to exit.
1615 * If we continue with the shutdown without waiting for it, then the client might
1616 * not receive an answer to its last command like a resume.
1618 if (!is_debugger_thread ()) {
1620 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
1621 if (!debugger_thread_exited)
1622 mono_coop_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1623 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
1624 } while (!debugger_thread_exited);
1627 transport_close2 ();
1631 start_debugger_thread (void)
1633 debugger_thread_handle = mono_threads_create_thread (debugger_thread, NULL, NULL, NULL);
1634 g_assert (debugger_thread_handle);
1638 * Functions to decode protocol data
1642 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1645 g_assert (*endbuf <= limit);
1650 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1653 g_assert (*endbuf <= limit);
1655 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1658 static inline gint64
1659 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1661 guint32 high = decode_int (buf, &buf, limit);
1662 guint32 low = decode_int (buf, &buf, limit);
1666 return ((((guint64)high) << 32) | ((guint64)low));
1670 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1672 return decode_int (buf, endbuf, limit);
1676 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1678 int len = decode_int (buf, &buf, limit);
1686 s = (char *)g_malloc (len + 1);
1689 memcpy (s, buf, len);
1698 * Functions to encode protocol data
1702 buffer_init (Buffer *buf, int size)
1704 buf->buf = (guint8 *)g_malloc (size);
1706 buf->end = buf->buf + size;
1710 buffer_len (Buffer *buf)
1712 return buf->p - buf->buf;
1716 buffer_make_room (Buffer *buf, int size)
1718 if (buf->end - buf->p < size) {
1719 int new_size = buf->end - buf->buf + size + 32;
1720 guint8 *p = (guint8 *)g_realloc (buf->buf, new_size);
1721 size = buf->p - buf->buf;
1724 buf->end = buf->buf + new_size;
1729 buffer_add_byte (Buffer *buf, guint8 val)
1731 buffer_make_room (buf, 1);
1737 buffer_add_short (Buffer *buf, guint32 val)
1739 buffer_make_room (buf, 2);
1740 buf->p [0] = (val >> 8) & 0xff;
1741 buf->p [1] = (val >> 0) & 0xff;
1746 buffer_add_int (Buffer *buf, guint32 val)
1748 buffer_make_room (buf, 4);
1749 buf->p [0] = (val >> 24) & 0xff;
1750 buf->p [1] = (val >> 16) & 0xff;
1751 buf->p [2] = (val >> 8) & 0xff;
1752 buf->p [3] = (val >> 0) & 0xff;
1757 buffer_add_long (Buffer *buf, guint64 l)
1759 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1760 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1764 buffer_add_id (Buffer *buf, int id)
1766 buffer_add_int (buf, (guint64)id);
1770 buffer_add_data (Buffer *buf, guint8 *data, int len)
1772 buffer_make_room (buf, len);
1773 memcpy (buf->p, data, len);
1778 buffer_add_string (Buffer *buf, const char *str)
1783 buffer_add_int (buf, 0);
1786 buffer_add_int (buf, len);
1787 buffer_add_data (buf, (guint8*)str, len);
1792 buffer_add_buffer (Buffer *buf, Buffer *data)
1794 buffer_add_data (buf, data->buf, buffer_len (data));
1798 buffer_free (Buffer *buf)
1804 send_packet (int command_set, int command, Buffer *data)
1810 id = InterlockedIncrement (&packet_id);
1812 len = data->p - data->buf + 11;
1813 buffer_init (&buf, len);
1814 buffer_add_int (&buf, len);
1815 buffer_add_int (&buf, id);
1816 buffer_add_byte (&buf, 0); /* flags */
1817 buffer_add_byte (&buf, command_set);
1818 buffer_add_byte (&buf, command);
1819 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1821 res = transport_send (buf.buf, len);
1829 send_reply_packets (int npackets, ReplyPacket *packets)
1836 for (i = 0; i < npackets; ++i)
1837 len += buffer_len (packets [i].data) + 11;
1838 buffer_init (&buf, len);
1839 for (i = 0; i < npackets; ++i) {
1840 buffer_add_int (&buf, buffer_len (packets [i].data) + 11);
1841 buffer_add_int (&buf, packets [i].id);
1842 buffer_add_byte (&buf, 0x80); /* flags */
1843 buffer_add_byte (&buf, (packets [i].error >> 8) & 0xff);
1844 buffer_add_byte (&buf, packets [i].error);
1845 buffer_add_buffer (&buf, packets [i].data);
1848 res = transport_send (buf.buf, len);
1856 send_reply_packet (int id, int error, Buffer *data)
1860 memset (&packet, 0, sizeof (ReplyPacket));
1862 packet.error = error;
1865 return send_reply_packets (1, &packet);
1869 send_buffered_reply_packets (void)
1873 send_reply_packets (nreply_packets, reply_packets);
1874 for (i = 0; i < nreply_packets; ++i)
1875 buffer_free (reply_packets [i].data);
1876 DEBUG_PRINTF (1, "[dbg] Sent %d buffered reply packets [at=%lx].\n", nreply_packets, (long)mono_100ns_ticks () / 10000);
1881 buffer_reply_packet (int id, int error, Buffer *data)
1885 if (nreply_packets == 128)
1886 send_buffered_reply_packets ();
1888 p = &reply_packets [nreply_packets];
1891 p->data = g_new0 (Buffer, 1);
1892 buffer_init (p->data, buffer_len (data));
1893 buffer_add_buffer (p->data, data);
1902 * Represents an object accessible by the debugger client.
1905 /* Unique id used in the wire protocol to refer to objects */
1908 * A weakref gc handle pointing to the object. The gc handle is used to
1909 * detect if the object was garbage collected.
1914 /* Maps objid -> ObjRef */
1915 /* Protected by the loader lock */
1916 static GHashTable *objrefs;
1917 /* Protected by the loader lock */
1918 static GHashTable *obj_to_objref;
1919 /* Protected by the dbg lock */
1920 static MonoGHashTable *suspended_objs;
1923 free_objref (gpointer value)
1925 ObjRef *o = (ObjRef *)value;
1927 mono_gchandle_free (o->handle);
1935 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1936 obj_to_objref = g_hash_table_new (NULL, NULL);
1937 suspended_objs = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_DEBUGGER, "suspended objects table");
1938 MONO_GC_REGISTER_ROOT_FIXED (suspended_objs, MONO_ROOT_SOURCE_DEBUGGER, "suspended objects table");
1942 objrefs_cleanup (void)
1944 g_hash_table_destroy (objrefs);
1949 * Return an ObjRef for OBJ.
1952 get_objref (MonoObject *obj)
1955 GSList *reflist = NULL, *l;
1961 if (suspend_count) {
1963 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1966 mono_g_hash_table_insert (suspended_objs, obj, NULL);
1970 mono_loader_lock ();
1972 /* FIXME: The tables can grow indefinitely */
1974 if (mono_gc_is_moving ()) {
1976 * Objects can move, so use a hash table mapping hash codes to lists of
1977 * ObjRef structures.
1979 hash = mono_object_hash (obj);
1981 reflist = (GSList *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1982 for (l = reflist; l; l = l->next) {
1983 ref = (ObjRef *)l->data;
1984 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1985 mono_loader_unlock ();
1990 /* Use a hash table with masked pointers to internalize object references */
1991 ref = (ObjRef *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1992 /* ref might refer to a different object with the same addr which was GCd */
1993 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1994 mono_loader_unlock ();
1999 ref = g_new0 (ObjRef, 1);
2000 ref->id = InterlockedIncrement (&objref_id);
2001 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
2003 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
2005 if (mono_gc_is_moving ()) {
2006 reflist = g_slist_append (reflist, ref);
2007 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
2009 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
2012 mono_loader_unlock ();
2018 true_pred (gpointer key, gpointer value, gpointer user_data)
2024 clear_suspended_objs (void)
2027 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
2032 get_objid (MonoObject *obj)
2037 return get_objref (obj)->id;
2041 * Set OBJ to the object identified by OBJID.
2042 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
2046 get_object_allow_null (int objid, MonoObject **obj)
2056 return ERR_INVALID_OBJECT;
2058 mono_loader_lock ();
2060 ref = (ObjRef *)g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
2063 *obj = mono_gchandle_get_target (ref->handle);
2064 mono_loader_unlock ();
2066 return ERR_INVALID_OBJECT;
2069 mono_loader_unlock ();
2070 return ERR_INVALID_OBJECT;
2075 get_object (int objid, MonoObject **obj)
2077 ErrorCode err = get_object_allow_null (objid, obj);
2079 if (err != ERR_NONE)
2082 return ERR_INVALID_OBJECT;
2087 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
2089 return decode_id (buf, endbuf, limit);
2093 buffer_add_objid (Buffer *buf, MonoObject *o)
2095 buffer_add_id (buf, get_objid (o));
2114 * Represents a runtime structure accessible to the debugger client
2117 /* Unique id used in the wire protocol */
2119 /* Domain of the runtime structure, NULL if the domain was unloaded */
2126 MonoAssembly *assembly;
2127 MonoClassField *field;
2129 MonoProperty *property;
2134 /* Maps runtime structure -> Id */
2135 /* Protected by the dbg lock */
2136 GHashTable *val_to_id [ID_NUM];
2137 /* Classes whose class load event has been sent */
2138 /* Protected by the loader lock */
2139 GHashTable *loaded_classes;
2140 /* Maps MonoClass->GPtrArray of file names */
2141 GHashTable *source_files;
2142 /* Maps source file basename -> GSList of classes */
2143 GHashTable *source_file_to_class;
2144 /* Same with ignore-case */
2145 GHashTable *source_file_to_class_ignorecase;
2149 /* Protected by the dbg lock */
2150 static GPtrArray *ids [ID_NUM];
2157 for (i = 0; i < ID_NUM; ++i)
2158 ids [i] = g_ptr_array_new ();
2166 for (i = 0; i < ID_NUM; ++i) {
2168 for (j = 0; j < ids [i]->len; ++j)
2169 g_free (g_ptr_array_index (ids [i], j));
2170 g_ptr_array_free (ids [i], TRUE);
2177 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2179 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2181 GHashTableIter iter;
2182 GPtrArray *file_names;
2187 for (i = 0; i < ID_NUM; ++i)
2188 if (info->val_to_id [i])
2189 g_hash_table_destroy (info->val_to_id [i]);
2190 g_hash_table_destroy (info->loaded_classes);
2192 g_hash_table_iter_init (&iter, info->source_files);
2193 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2194 for (i = 0; i < file_names->len; ++i)
2195 g_free (g_ptr_array_index (file_names, i));
2196 g_ptr_array_free (file_names, TRUE);
2199 g_hash_table_iter_init (&iter, info->source_file_to_class);
2200 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2205 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2206 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2214 domain_jit_info (domain)->agent_info = NULL;
2216 /* Clear ids referencing structures in the domain */
2218 for (i = 0; i < ID_NUM; ++i) {
2220 for (j = 0; j < ids [i]->len; ++j) {
2221 Id *id = (Id *)g_ptr_array_index (ids [i], j);
2222 if (id->domain == domain)
2229 mono_loader_lock ();
2230 g_hash_table_remove (domains, domain);
2231 mono_loader_unlock ();
2234 static AgentDomainInfo*
2235 get_agent_domain_info (MonoDomain *domain)
2237 AgentDomainInfo *info = NULL;
2239 mono_domain_lock (domain);
2241 info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2243 info = g_new0 (AgentDomainInfo, 1);
2244 domain_jit_info (domain)->agent_info = info;
2245 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2246 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2247 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2248 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2251 mono_domain_unlock (domain);
2257 get_id (MonoDomain *domain, IdType type, gpointer val)
2260 AgentDomainInfo *info;
2265 info = get_agent_domain_info (domain);
2269 if (info->val_to_id [type] == NULL)
2270 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2272 id = (Id *)g_hash_table_lookup (info->val_to_id [type], val);
2278 id = g_new0 (Id, 1);
2280 id->id = ids [type]->len + 1;
2281 id->domain = domain;
2284 g_hash_table_insert (info->val_to_id [type], val, id);
2285 g_ptr_array_add (ids [type], id);
2292 static inline gpointer
2293 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, ErrorCode *err)
2297 int id = decode_id (buf, endbuf, limit);
2306 // FIXME: error handling
2308 g_assert (id > 0 && id <= ids [type]->len);
2310 res = (Id *)g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2313 if (res->domain == NULL || res->domain->state == MONO_APPDOMAIN_UNLOADED) {
2314 DEBUG_PRINTF (1, "ERR_UNLOADED, id=%d, type=%d.\n", id, type);
2315 *err = ERR_UNLOADED;
2320 *domain = res->domain;
2322 return res->data.val;
2326 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2328 int id = get_id (domain, type, val);
2330 buffer_add_id (buf, id);
2334 static inline MonoClass*
2335 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2339 klass = (MonoClass *)decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2340 if (G_UNLIKELY (log_level >= 2) && klass) {
2343 s = mono_type_full_name (&klass->byval_arg);
2344 DEBUG_PRINTF (2, "[dbg] recv class [%s]\n", s);
2350 static inline MonoAssembly*
2351 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2353 return (MonoAssembly *)decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2356 static inline MonoImage*
2357 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2359 return (MonoImage *)decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2362 static inline MonoMethod*
2363 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2367 m = (MonoMethod *)decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2368 if (G_UNLIKELY (log_level >= 2) && m) {
2371 s = mono_method_full_name (m, TRUE);
2372 DEBUG_PRINTF (2, "[dbg] recv method [%s]\n", s);
2378 static inline MonoClassField*
2379 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2381 return (MonoClassField *)decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2384 static inline MonoDomain*
2385 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2387 return (MonoDomain *)decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2390 static inline MonoProperty*
2391 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2393 return (MonoProperty *)decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2397 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2399 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2400 if (G_UNLIKELY (log_level >= 2) && klass) {
2403 s = mono_type_full_name (&klass->byval_arg);
2404 if (is_debugger_thread ())
2405 DEBUG_PRINTF (2, "[dbg] send class [%s]\n", s);
2407 DEBUG_PRINTF (2, "[%p] send class [%s]\n", (gpointer) (gsize) mono_native_thread_id_get (), s);
2413 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2415 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2416 if (G_UNLIKELY (log_level >= 2) && method) {
2419 s = mono_method_full_name (method, 1);
2420 DEBUG_PRINTF (2, "[dbg] send method [%s]\n", s);
2426 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2430 id = buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2431 if (G_UNLIKELY (log_level >= 2) && assembly)
2432 DEBUG_PRINTF (2, "[dbg] send assembly [%s][%s][%d]\n", assembly->aname.name, domain->friendly_name, id);
2436 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2438 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2442 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2444 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2448 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2450 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2454 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2456 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2459 static void invoke_method (void);
2466 * save_thread_context:
2468 * Set CTX as the current threads context which is used for computing stack traces.
2469 * This function is signal-safe.
2472 save_thread_context (MonoContext *ctx)
2474 DebuggerTlsData *tls;
2476 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2480 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2482 mono_thread_state_init_from_current (&tls->context);
2485 /* Number of threads suspended */
2487 * If this is equal to the size of thread_to_tls, the runtime is considered
2490 static gint32 threads_suspend_count;
2492 static MonoCoopMutex suspend_mutex;
2494 /* Cond variable used to wait for suspend_count becoming 0 */
2495 static MonoCoopCond suspend_cond;
2497 /* Semaphore used to wait for a thread becoming suspended */
2498 static MonoCoopSem suspend_sem;
2503 mono_coop_mutex_init (&suspend_mutex);
2504 mono_coop_cond_init (&suspend_cond);
2505 mono_coop_sem_init (&suspend_sem, 0);
2510 StackFrameInfo last_frame;
2511 gboolean last_frame_set;
2515 } GetLastFrameUserData;
2518 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2520 GetLastFrameUserData *data = (GetLastFrameUserData *)user_data;
2522 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE || info->type == FRAME_TYPE_TRAMPOLINE)
2525 if (!data->last_frame_set) {
2526 /* Store the last frame */
2527 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2528 data->last_frame_set = TRUE;
2531 /* Store the context/lmf for the frame above the last frame */
2532 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2533 data->lmf = info->lmf;
2534 data->domain = info->domain;
2540 copy_unwind_state_from_frame_data (MonoThreadUnwindState *to, GetLastFrameUserData *data, gpointer jit_tls)
2542 memcpy (&to->ctx, &data->ctx, sizeof (MonoContext));
2544 to->unwind_data [MONO_UNWIND_DATA_DOMAIN] = data->domain;
2545 to->unwind_data [MONO_UNWIND_DATA_LMF] = data->lmf;
2546 to->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = jit_tls;
2553 * Process interruption of a thread. This should be signal safe.
2555 * This always runs in the debugger thread.
2558 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, MonoJitInfo *ji)
2561 MonoNativeThreadId tid;
2565 ip = MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx);
2566 tid = mono_thread_info_get_tid (info);
2568 // FIXME: Races when the thread leaves managed code before hitting a single step
2571 if (ji && !ji->is_trampoline) {
2572 /* Running managed code, will be suspended by the single step code */
2573 DEBUG_PRINTF (1, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip);
2576 * Running native code, will be suspended when it returns to/enters
2577 * managed code. Treat it as already suspended.
2578 * This might interrupt the code in process_single_step_inner (), we use the
2579 * tls->suspending flag to avoid races when that happens.
2581 if (!tls->suspended && !tls->suspending) {
2582 GetLastFrameUserData data;
2584 // FIXME: printf is not signal safe, but this is only used during
2585 // debugger debugging
2587 DEBUG_PRINTF (1, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip);
2588 //save_thread_context (&ctx);
2591 /* Already terminated */
2595 * We are in a difficult position: we want to be able to provide stack
2596 * traces for this thread, but we can't use the current ctx+lmf, since
2597 * the thread is still running, so it might return to managed code,
2598 * making these invalid.
2599 * So we start a stack walk and save the first frame, along with the
2600 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2601 * suspended when it returns to managed code, so the parent's ctx should
2604 data.last_frame_set = FALSE;
2605 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, mono_thread_info_get_suspend_state (info), MONO_UNWIND_SIGNAL_SAFE, &data);
2606 if (data.last_frame_set) {
2607 gpointer jit_tls = ((MonoThreadInfo*)tls->thread->thread_info)->jit_data;
2609 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2611 copy_unwind_state_from_frame_data (&tls->async_state, &data, jit_tls);
2612 copy_unwind_state_from_frame_data (&tls->context, &data, jit_tls);
2614 tls->async_state.valid = FALSE;
2617 mono_memory_barrier ();
2619 tls->suspended = TRUE;
2620 mono_coop_sem_post (&suspend_sem);
2626 * reset_native_thread_suspend_state:
2628 * Reset the suspended flag and state on native threads
2631 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2633 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2635 if (!tls->really_suspended && tls->suspended) {
2636 tls->suspended = FALSE;
2638 * The thread might still be running if it was executing native code, so the state won't be invalided by
2639 * suspend_current ().
2641 tls->context.valid = FALSE;
2642 tls->async_state.valid = FALSE;
2643 invalidate_frames (tls);
2648 DebuggerTlsData *tls;
2649 gboolean valid_info;
2652 static SuspendThreadResult
2653 debugger_interrupt_critical (MonoThreadInfo *info, gpointer user_data)
2655 InterruptData *data = (InterruptData *)user_data;
2658 data->valid_info = TRUE;
2659 ji = mono_jit_info_table_find_internal (
2660 (MonoDomain *)mono_thread_info_get_suspend_state (info)->unwind_data [MONO_UNWIND_DATA_DOMAIN],
2661 (char *)MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx),
2665 /* This is signal safe */
2666 thread_interrupt (data->tls, info, ji);
2667 return MonoResumeThread;
2673 * Notify a thread that it needs to suspend.
2676 notify_thread (gpointer key, gpointer value, gpointer user_data)
2678 MonoInternalThread *thread = (MonoInternalThread *)key;
2679 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2680 MonoNativeThreadId tid = MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid);
2682 if (mono_native_thread_id_equals (mono_native_thread_id_get (), tid) || tls->terminated)
2685 DEBUG_PRINTF (1, "[%p] Interrupting %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2687 /* This is _not_ equivalent to mono_thread_internal_abort () */
2688 InterruptData interrupt_data = { 0 };
2689 interrupt_data.tls = tls;
2691 mono_thread_info_safe_suspend_and_run ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE, debugger_interrupt_critical, &interrupt_data);
2692 if (!interrupt_data.valid_info) {
2693 DEBUG_PRINTF (1, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2695 * Attached thread which died without detaching.
2697 tls->terminated = TRUE;
2702 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2704 guint8 *ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
2708 if (mono_loader_lock_is_owned_by_self ()) {
2710 * Shortcut for the check in suspend_current (). This speeds up processing
2711 * when executing long running code inside the loader lock, i.e. assembly load
2717 if (is_debugger_thread ())
2720 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2721 if (suspend_count - tls->resume_count > 0)
2722 tls->suspending = TRUE;
2724 DEBUG_PRINTF (1, "[%p] Received single step event for suspending.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2726 if (suspend_count - tls->resume_count == 0) {
2728 * We are executing a single threaded invoke but the single step for
2729 * suspending is still active.
2730 * FIXME: This slows down single threaded invokes.
2732 DEBUG_PRINTF (1, "[%p] Ignored during single threaded invoke.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2736 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2738 /* Can't suspend in these methods */
2739 method = jinfo_get_method (ji);
2740 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2743 save_thread_context (ctx);
2751 * Increase the suspend count of the VM. While the suspend count is greater
2752 * than 0, runtime threads are suspended at certain points during execution.
2757 mono_loader_lock ();
2759 mono_coop_mutex_lock (&suspend_mutex);
2763 DEBUG_PRINTF (1, "[%p] Suspending vm...\n", (gpointer) (gsize) mono_native_thread_id_get ());
2765 if (suspend_count == 1) {
2766 // FIXME: Is it safe to call this inside the lock ?
2767 start_single_stepping ();
2768 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2771 mono_coop_mutex_unlock (&suspend_mutex);
2773 if (suspend_count == 1)
2775 * Suspend creation of new threadpool threads, since they cannot run
2777 mono_threadpool_suspend ();
2779 mono_loader_unlock ();
2785 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2791 g_assert (is_debugger_thread ());
2793 mono_loader_lock ();
2795 mono_coop_mutex_lock (&suspend_mutex);
2797 g_assert (suspend_count > 0);
2800 DEBUG_PRINTF (1, "[%p] Resuming vm, suspend count=%d...\n", (gpointer) (gsize) mono_native_thread_id_get (), suspend_count);
2802 if (suspend_count == 0) {
2803 // FIXME: Is it safe to call this inside the lock ?
2804 stop_single_stepping ();
2805 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2808 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2809 mono_coop_cond_broadcast (&suspend_cond);
2811 mono_coop_mutex_unlock (&suspend_mutex);
2812 //g_assert (err == 0);
2814 if (suspend_count == 0)
2815 mono_threadpool_resume ();
2817 mono_loader_unlock ();
2823 * Resume just one thread.
2826 resume_thread (MonoInternalThread *thread)
2828 DebuggerTlsData *tls;
2830 g_assert (is_debugger_thread ());
2832 mono_loader_lock ();
2834 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
2837 mono_coop_mutex_lock (&suspend_mutex);
2839 g_assert (suspend_count > 0);
2841 DEBUG_PRINTF (1, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid);
2843 tls->resume_count += suspend_count;
2846 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2847 * but only the one whose resume_count field is > 0 will be resumed.
2849 mono_coop_cond_broadcast (&suspend_cond);
2851 mono_coop_mutex_unlock (&suspend_mutex);
2852 //g_assert (err == 0);
2854 mono_loader_unlock ();
2858 free_frames (StackFrame **frames, int nframes)
2862 for (i = 0; i < nframes; ++i) {
2863 if (frames [i]->jit)
2864 mono_debug_free_method_jit_info (frames [i]->jit);
2865 g_free (frames [i]);
2871 invalidate_frames (DebuggerTlsData *tls)
2874 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2877 free_frames (tls->frames, tls->frame_count);
2878 tls->frame_count = 0;
2881 free_frames (tls->restore_frames, tls->restore_frame_count);
2882 tls->restore_frame_count = 0;
2883 tls->restore_frames = NULL;
2889 * Suspend the current thread until the runtime is resumed. If the thread has a
2890 * pending invoke, then the invoke is executed before this function returns.
2893 suspend_current (void)
2895 DebuggerTlsData *tls;
2897 g_assert (!is_debugger_thread ());
2899 if (mono_loader_lock_is_owned_by_self ()) {
2901 * If we own the loader mutex, can't suspend until we release it, since the
2902 * whole runtime can deadlock otherwise.
2907 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2910 mono_coop_mutex_lock (&suspend_mutex);
2912 tls->suspending = FALSE;
2913 tls->really_suspended = TRUE;
2915 if (!tls->suspended) {
2916 tls->suspended = TRUE;
2917 mono_coop_sem_post (&suspend_sem);
2920 DEBUG_PRINTF (1, "[%p] Suspended.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2922 while (suspend_count - tls->resume_count > 0) {
2923 mono_coop_cond_wait (&suspend_cond, &suspend_mutex);
2926 tls->suspended = FALSE;
2927 tls->really_suspended = FALSE;
2929 threads_suspend_count --;
2931 mono_coop_mutex_unlock (&suspend_mutex);
2933 DEBUG_PRINTF (1, "[%p] Resumed.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2935 if (tls->pending_invoke) {
2936 /* Save the original context */
2937 tls->pending_invoke->has_ctx = TRUE;
2938 tls->pending_invoke->ctx = tls->context.ctx;
2943 /* The frame info becomes invalid after a resume */
2944 tls->context.valid = FALSE;
2945 tls->async_state.valid = FALSE;
2946 invalidate_frames (tls);
2950 count_thread (gpointer key, gpointer value, gpointer user_data)
2952 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2954 if (!tls->suspended && !tls->terminated)
2955 *(int*)user_data = *(int*)user_data + 1;
2959 count_threads_to_wait_for (void)
2963 mono_loader_lock ();
2964 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2965 mono_loader_unlock ();
2973 * Wait until the runtime is completely suspended.
2976 wait_for_suspend (void)
2978 int nthreads, nwait, err;
2979 gboolean waited = FALSE;
2981 // FIXME: Threads starting/stopping ?
2982 mono_loader_lock ();
2983 nthreads = mono_g_hash_table_size (thread_to_tls);
2984 mono_loader_unlock ();
2987 nwait = count_threads_to_wait_for ();
2989 DEBUG_PRINTF (1, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads);
2990 err = mono_coop_sem_wait (&suspend_sem, MONO_SEM_FLAGS_NONE);
2991 g_assert (err == 0);
2999 DEBUG_PRINTF (1, "%d threads suspended.\n", nthreads);
3005 * Return whenever the runtime is suspended.
3010 return count_threads_to_wait_for () == 0;
3014 no_seq_points_found (MonoMethod *method, int offset)
3017 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3019 printf ("Unable to find seq points for method '%s', offset 0x%x.\n", mono_method_full_name (method, TRUE), offset);
3023 DebuggerTlsData *tls;
3025 } ComputeFramesUserData;
3028 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3030 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3032 MonoMethod *method, *actual_method, *api_method;
3036 if (info->type != FRAME_TYPE_MANAGED) {
3037 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3038 /* Mark the last frame as an invoke frame */
3040 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3046 method = jinfo_get_method (info->ji);
3048 method = info->method;
3049 actual_method = info->actual_method;
3050 api_method = method;
3055 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3058 if (info->il_offset == -1) {
3059 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3060 if (ud->frames == NULL) {
3061 if (mono_find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL, &sp))
3062 info->il_offset = sp.il_offset;
3064 if (info->il_offset == -1)
3065 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3068 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);
3070 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3071 if (!CHECK_PROTOCOL_VERSION (2, 17))
3072 /* Older clients can't handle this flag */
3074 api_method = mono_marshal_method_from_wrapper (method);
3077 actual_method = api_method;
3078 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3081 frame = g_new0 (StackFrame, 1);
3082 frame->method = method;
3083 frame->actual_method = actual_method;
3084 frame->api_method = api_method;
3085 frame->il_offset = info->il_offset;
3086 frame->native_offset = info->native_offset;
3087 frame->flags = flags;
3088 frame->ji = info->ji;
3089 if (info->reg_locations)
3090 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3093 frame->has_ctx = TRUE;
3095 frame->domain = info->domain;
3097 ud->frames = g_slist_append (ud->frames, frame);
3103 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3105 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3108 * 'tls->filter_ctx' is the location of the throw site.
3110 * mono_walk_stack() will never actually hit the throw site, but unwind
3111 * directly from the filter to the call site; we abort stack unwinding here
3112 * once this happens and resume from the throw site.
3115 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3118 return process_frame (info, ctx, user_data);
3122 * Return a malloc-ed list of StackFrame structures.
3125 compute_frame_info_from (MonoInternalThread *thread, DebuggerTlsData *tls, MonoThreadUnwindState *state, int *out_nframes)
3127 ComputeFramesUserData user_data;
3128 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3133 user_data.tls = tls;
3134 user_data.frames = NULL;
3136 mono_walk_stack_with_state (process_frame, state, opts, &user_data);
3138 nframes = g_slist_length (user_data.frames);
3139 res = g_new0 (StackFrame*, nframes);
3140 l = user_data.frames;
3141 for (i = 0; i < nframes; ++i) {
3142 res [i] = (StackFrame *)l->data;
3145 *out_nframes = nframes;
3151 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3153 ComputeFramesUserData user_data;
3155 int i, findex, new_frame_count;
3156 StackFrame **new_frames, *f;
3157 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3159 // FIXME: Locking on tls
3160 if (tls->frames && tls->frames_up_to_date)
3163 DEBUG_PRINTF (1, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid);
3165 user_data.tls = tls;
3166 user_data.frames = NULL;
3167 if (tls->terminated) {
3168 tls->frame_count = 0;
3170 } if (!tls->really_suspended && tls->async_state.valid) {
3171 /* Have to use the state saved by the signal handler */
3172 process_frame (&tls->async_last_frame, NULL, &user_data);
3173 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3174 } else if (tls->filter_state.valid) {
3176 * We are inside an exception filter.
3178 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3180 if (tls->context.valid)
3181 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3183 * After that, we resume unwinding from the location where the exception has been thrown.
3185 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3186 } else if (tls->context.valid) {
3187 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3190 tls->frame_count = 0;
3194 new_frame_count = g_slist_length (user_data.frames);
3195 new_frames = g_new0 (StackFrame*, new_frame_count);
3197 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3198 f = (StackFrame *)tmp->data;
3201 * Reuse the id for already existing stack frames, so invokes don't invalidate
3202 * the still valid stack frames.
3204 for (i = 0; i < tls->frame_count; ++i) {
3205 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3206 f->id = tls->frames [i]->id;
3211 if (i >= tls->frame_count)
3212 f->id = InterlockedIncrement (&frame_id);
3214 new_frames [findex ++] = f;
3217 g_slist_free (user_data.frames);
3219 invalidate_frames (tls);
3221 tls->frames = new_frames;
3222 tls->frame_count = new_frame_count;
3223 tls->frames_up_to_date = TRUE;
3227 * GHFunc to emit an appdomain creation event
3228 * @param key Don't care
3229 * @param value A loaded appdomain
3230 * @param user_data Don't care
3233 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3235 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3236 g_hash_table_foreach (get_agent_domain_info ((MonoDomain *)value)->loaded_classes, emit_type_load, NULL);
3240 * GHFunc to emit a thread start event
3241 * @param key A thread id
3242 * @param value A thread object
3243 * @param user_data Don't care
3246 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3248 if (!mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (GPOINTER_TO_UINT (key)), debugger_thread_id))
3249 process_profiler_event (EVENT_KIND_THREAD_START, value);
3253 * GFunc to emit an assembly load event
3254 * @param value A loaded assembly
3255 * @param user_data Don't care
3258 emit_assembly_load (gpointer value, gpointer user_data)
3260 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3264 * GFunc to emit a type load event
3265 * @param value A loaded type
3266 * @param user_data Don't care
3269 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3271 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3275 strdup_tolower (char *s)
3280 for (p = s2; *p; ++p)
3286 * Same as g_path_get_basename () but handles windows paths as well,
3287 * which can occur in .mdb files created by pdb2mdb.
3290 dbg_path_get_basename (const char *filename)
3294 if (!filename || strchr (filename, '/') || !strchr (filename, '\\'))
3295 return g_path_get_basename (filename);
3299 /* No separator -> filename */
3300 r = strrchr (filename, '\\');
3302 return g_strdup (filename);
3304 /* Trailing slash, remove component */
3306 char *copy = g_strdup (filename);
3307 copy [r-filename] = 0;
3308 r = strrchr (copy, '\\');
3312 return g_strdup ("/");
3314 r = g_strdup (&r[1]);
3319 return g_strdup (&r[1]);
3323 init_jit_info_dbg_attrs (MonoJitInfo *ji)
3325 static MonoClass *hidden_klass, *step_through_klass, *non_user_klass;
3327 MonoCustomAttrInfo *ainfo;
3329 if (ji->dbg_attrs_inited)
3333 hidden_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3335 if (!step_through_klass)
3336 step_through_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3338 if (!non_user_klass)
3339 non_user_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute");
3341 ainfo = mono_custom_attrs_from_method_checked (jinfo_get_method (ji), &error);
3342 mono_error_cleanup (&error); /* FIXME don't swallow the error? */
3344 if (mono_custom_attrs_has_attr (ainfo, hidden_klass))
3345 ji->dbg_hidden = TRUE;
3346 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3347 ji->dbg_step_through = TRUE;
3348 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3349 ji->dbg_non_user_code = TRUE;
3350 mono_custom_attrs_free (ainfo);
3353 ainfo = mono_custom_attrs_from_class_checked (jinfo_get_method (ji)->klass, &error);
3354 mono_error_cleanup (&error); /* FIXME don't swallow the error? */
3356 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3357 ji->dbg_step_through = TRUE;
3358 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3359 ji->dbg_non_user_code = TRUE;
3360 mono_custom_attrs_free (ainfo);
3363 mono_memory_barrier ();
3364 ji->dbg_attrs_inited = TRUE;
3372 * create_event_list:
3374 * Return a list of event request ids matching EVENT, starting from REQS, which
3375 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3377 * We return request ids, instead of requests, to simplify threading, since
3378 * requests could be deleted anytime when the loader lock is not held.
3379 * LOCKING: Assumes the loader lock is held.
3382 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3385 GSList *events = NULL;
3387 *suspend_policy = SUSPEND_POLICY_NONE;
3390 reqs = event_requests;
3395 for (i = 0; i < reqs->len; ++i) {
3396 EventRequest *req = (EventRequest *)g_ptr_array_index (reqs, i);
3397 if (req->event_kind == event) {
3398 gboolean filtered = FALSE;
3401 for (j = 0; j < req->nmodifiers; ++j) {
3402 Modifier *mod = &req->modifiers [j];
3404 if (mod->kind == MOD_KIND_COUNT) {
3406 if (mod->data.count > 0) {
3407 if (mod->data.count > 0) {
3409 if (mod->data.count == 0)
3413 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3414 if (mod->data.thread != mono_thread_internal_current ())
3416 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3417 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3419 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3421 if (ei->caught && !mod->caught)
3423 if (!ei->caught && !mod->uncaught)
3425 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3427 gboolean found = FALSE;
3428 MonoAssembly **assemblies = mod->data.assemblies;
3431 for (k = 0; assemblies [k]; ++k)
3432 if (assemblies [k] == jinfo_get_method (ji)->klass->image->assembly)
3437 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3438 gpointer iter = NULL;
3440 MonoDebugSourceInfo *sinfo;
3441 char *source_file, *s;
3442 gboolean found = FALSE;
3444 GPtrArray *source_file_list;
3446 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3447 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3450 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, NULL, NULL, NULL);
3451 for (i = 0; i < source_file_list->len; ++i) {
3452 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
3454 * Do a case-insesitive match by converting the file name to
3457 s = strdup_tolower (sinfo->source_file);
3458 if (g_hash_table_lookup (mod->data.source_files, s))
3461 char *s2 = dbg_path_get_basename (sinfo->source_file);
3462 char *s3 = strdup_tolower (s2);
3464 if (g_hash_table_lookup (mod->data.source_files, s3))
3471 g_ptr_array_free (source_file_list, TRUE);
3476 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3479 s = mono_type_full_name (&ei->klass->byval_arg);
3480 if (!g_hash_table_lookup (mod->data.type_names, s))
3483 } else if (mod->kind == MOD_KIND_STEP) {
3484 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3485 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3486 !strcmp (jinfo_get_method (ji)->name, ".cctor") &&
3487 (jinfo_get_method (ji) != ((SingleStepReq*)req->info)->start_method))
3489 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3490 init_jit_info_dbg_attrs (ji);
3494 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3495 init_jit_info_dbg_attrs (ji);
3496 if (ji->dbg_step_through)
3499 if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3500 init_jit_info_dbg_attrs (ji);
3501 if (ji->dbg_non_user_code)
3508 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3509 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3514 /* Send a VM START/DEATH event by default */
3515 if (event == EVENT_KIND_VM_START)
3516 events = g_slist_append (events, GINT_TO_POINTER (0));
3517 if (event == EVENT_KIND_VM_DEATH)
3518 events = g_slist_append (events, GINT_TO_POINTER (0));
3523 static G_GNUC_UNUSED const char*
3524 event_to_string (EventKind event)
3527 case EVENT_KIND_VM_START: return "VM_START";
3528 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3529 case EVENT_KIND_THREAD_START: return "THREAD_START";
3530 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3531 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3532 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3533 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3534 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3535 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3536 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3537 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3538 case EVENT_KIND_STEP: return "STEP";
3539 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3540 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3541 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3542 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3543 case EVENT_KIND_USER_LOG: return "USER_LOG";
3545 g_assert_not_reached ();
3553 * Send an event to the client, suspending the vm if needed.
3554 * LOCKING: Since this can suspend the calling thread, no locks should be held
3556 * The EVENTS list is freed by this function.
3559 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3563 MonoDomain *domain = mono_domain_get ();
3564 MonoThread *thread = NULL;
3565 MonoObject *keepalive_obj = NULL;
3566 gboolean send_success = FALSE;
3571 DEBUG_PRINTF (2, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event));
3575 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3576 // FIXME: We miss those events
3577 DEBUG_PRINTF (2, "VM start event not sent yet: dropping %s\n", event_to_string (event));
3581 if (vm_death_event_sent) {
3582 DEBUG_PRINTF (2, "VM death event has been sent: dropping %s\n", event_to_string (event));
3586 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3587 DEBUG_PRINTF (2, "Mono runtime is shutting down: dropping %s\n", event_to_string (event));
3592 DEBUG_PRINTF (2, "Debugger client is not connected: dropping %s\n", event_to_string (event));
3596 if (event == EVENT_KIND_KEEPALIVE)
3597 suspend_policy = SUSPEND_POLICY_NONE;
3602 if (agent_config.defer) {
3603 /* Make sure the thread id is always set when doing deferred debugging */
3604 if (is_debugger_thread ()) {
3605 /* Don't suspend on events from the debugger thread */
3606 suspend_policy = SUSPEND_POLICY_NONE;
3607 thread = mono_thread_get_main ();
3609 else thread = mono_thread_current ();
3611 if (is_debugger_thread () && event != EVENT_KIND_VM_DEATH)
3612 // FIXME: Send these with a NULL thread, don't suspend the current thread
3617 nevents = g_slist_length (events);
3618 buffer_init (&buf, 128);
3619 buffer_add_byte (&buf, suspend_policy);
3620 buffer_add_int (&buf, nevents);
3622 for (l = events; l; l = l->next) {
3623 buffer_add_byte (&buf, event); // event kind
3624 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3628 if (event == EVENT_KIND_VM_DEATH) {
3632 thread = mono_thread_current ();
3634 if (event == EVENT_KIND_VM_START && arg != NULL)
3635 thread = (MonoThread *)arg;
3638 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3641 case EVENT_KIND_THREAD_START:
3642 case EVENT_KIND_THREAD_DEATH:
3644 case EVENT_KIND_APPDOMAIN_CREATE:
3645 case EVENT_KIND_APPDOMAIN_UNLOAD:
3646 buffer_add_domainid (&buf, (MonoDomain *)arg);
3648 case EVENT_KIND_METHOD_ENTRY:
3649 case EVENT_KIND_METHOD_EXIT:
3650 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3652 case EVENT_KIND_ASSEMBLY_LOAD:
3653 buffer_add_assemblyid (&buf, domain, (MonoAssembly *)arg);
3655 case EVENT_KIND_ASSEMBLY_UNLOAD: {
3656 DebuggerTlsData *tls;
3658 /* The domain the assembly belonged to is not equal to the current domain */
3659 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3661 g_assert (tls->domain_unloading);
3663 buffer_add_assemblyid (&buf, tls->domain_unloading, (MonoAssembly *)arg);
3666 case EVENT_KIND_TYPE_LOAD:
3667 buffer_add_typeid (&buf, domain, (MonoClass *)arg);
3669 case EVENT_KIND_BREAKPOINT:
3670 case EVENT_KIND_STEP:
3671 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3672 buffer_add_long (&buf, il_offset);
3674 case EVENT_KIND_VM_START:
3675 buffer_add_domainid (&buf, mono_get_root_domain ());
3677 case EVENT_KIND_VM_DEATH:
3678 if (CHECK_PROTOCOL_VERSION (2, 27))
3679 buffer_add_int (&buf, mono_environment_exitcode_get ());
3681 case EVENT_KIND_EXCEPTION: {
3682 EventInfo *ei = (EventInfo *)arg;
3683 buffer_add_objid (&buf, ei->exc);
3685 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3686 * later after the suspension. (#12494).
3688 keepalive_obj = ei->exc;
3691 case EVENT_KIND_USER_BREAK:
3693 case EVENT_KIND_USER_LOG: {
3694 EventInfo *ei = (EventInfo *)arg;
3695 buffer_add_int (&buf, ei->level);
3696 buffer_add_string (&buf, ei->category ? ei->category : "");
3697 buffer_add_string (&buf, ei->message ? ei->message : "");
3700 case EVENT_KIND_KEEPALIVE:
3701 suspend_policy = SUSPEND_POLICY_NONE;
3704 g_assert_not_reached ();
3708 if (event == EVENT_KIND_VM_START) {
3709 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3710 if (!agent_config.defer)
3711 start_debugger_thread ();
3714 if (event == EVENT_KIND_VM_DEATH) {
3715 vm_death_event_sent = TRUE;
3716 suspend_policy = SUSPEND_POLICY_NONE;
3719 if (mono_runtime_is_shutting_down ())
3720 suspend_policy = SUSPEND_POLICY_NONE;
3722 if (suspend_policy != SUSPEND_POLICY_NONE) {
3724 * Save the thread context and start suspending before sending the packet,
3725 * since we could be receiving the resume request before send_packet ()
3728 save_thread_context (ctx);
3732 /* This will keep this object alive */
3733 get_objref (keepalive_obj);
3736 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3740 g_slist_free (events);
3743 if (!send_success) {
3744 DEBUG_PRINTF (2, "Sending command %s failed.\n", event_to_string (event));
3748 if (event == EVENT_KIND_VM_START) {
3749 vm_start_event_sent = TRUE;
3752 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);
3754 switch (suspend_policy) {
3755 case SUSPEND_POLICY_NONE:
3757 case SUSPEND_POLICY_ALL:
3760 case SUSPEND_POLICY_EVENT_THREAD:
3764 g_assert_not_reached ();
3769 process_profiler_event (EventKind event, gpointer arg)
3773 EventInfo ei, *ei_arg = NULL;
3775 if (event == EVENT_KIND_TYPE_LOAD) {
3776 ei.klass = (MonoClass *)arg;
3780 mono_loader_lock ();
3781 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3782 mono_loader_unlock ();
3784 process_event (event, arg, 0, NULL, events, suspend_policy);
3788 runtime_initialized (MonoProfiler *prof)
3790 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3791 if (agent_config.defer)
3792 start_debugger_thread ();
3796 runtime_shutdown (MonoProfiler *prof)
3798 process_profiler_event (EVENT_KIND_VM_DEATH, NULL);
3800 mono_debugger_agent_cleanup ();
3804 thread_startup (MonoProfiler *prof, uintptr_t tid)
3806 MonoInternalThread *thread = mono_thread_internal_current ();
3807 MonoInternalThread *old_thread;
3808 DebuggerTlsData *tls;
3810 if (mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (tid), debugger_thread_id))
3813 g_assert (mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (tid), MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid)));
3815 mono_loader_lock ();
3816 old_thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3817 mono_loader_unlock ();
3819 if (thread == old_thread) {
3821 * For some reason, thread_startup () might be called for the same thread
3822 * multiple times (attach ?).
3824 DEBUG_PRINTF (1, "[%p] thread_start () called multiple times for %p, ignored.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3828 * thread_end () might not be called for some threads, and the tid could
3831 DEBUG_PRINTF (1, "[%p] Removing stale data for tid %p.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3832 mono_loader_lock ();
3833 mono_g_hash_table_remove (thread_to_tls, old_thread);
3834 mono_g_hash_table_remove (tid_to_thread, GUINT_TO_POINTER (tid));
3835 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3836 mono_loader_unlock ();
3840 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3842 // FIXME: Free this somewhere
3843 tls = g_new0 (DebuggerTlsData, 1);
3844 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread, MONO_ROOT_SOURCE_DEBUGGER, "debugger thread reference");
3845 tls->thread = thread;
3846 mono_native_tls_set_value (debugger_tls_id, tls);
3848 DEBUG_PRINTF (1, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3850 mono_loader_lock ();
3851 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3852 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3853 mono_g_hash_table_insert (tid_to_thread_obj, GUINT_TO_POINTER (tid), mono_thread_current ());
3854 mono_loader_unlock ();
3856 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3859 * suspend_vm () could have missed this thread, so wait for a resume.
3865 thread_end (MonoProfiler *prof, uintptr_t tid)
3867 MonoInternalThread *thread;
3868 DebuggerTlsData *tls = NULL;
3870 mono_loader_lock ();
3871 thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3873 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3874 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
3876 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3877 tls->terminated = TRUE;
3878 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3879 MONO_GC_UNREGISTER_ROOT (tls->thread);
3883 mono_loader_unlock ();
3885 /* We might be called for threads started before we registered the start callback */
3887 DEBUG_PRINTF (1, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3889 if (mono_native_thread_id_equals (mono_native_thread_id_get (), MONO_UINT_TO_NATIVE_THREAD_ID (tid))
3890 && !mono_native_tls_get_value (debugger_tls_id)
3893 * This can happen on darwin since we deregister threads using pthread dtors.
3894 * process_profiler_event () and the code it calls cannot handle a null TLS value.
3899 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3904 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3906 mono_loader_lock ();
3907 g_hash_table_insert (domains, domain, domain);
3908 mono_loader_unlock ();
3910 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3914 appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain)
3916 DebuggerTlsData *tls;
3918 /* This might be called during shutdown on the debugger thread from the CMD_VM_EXIT code */
3919 if (is_debugger_thread ())
3923 * Remember the currently unloading appdomain as it is needed to generate
3924 * proper ids for unloading assemblies.
3926 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3928 tls->domain_unloading = domain;
3932 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3934 DebuggerTlsData *tls;
3936 if (is_debugger_thread ())
3939 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3941 tls->domain_unloading = NULL;
3943 clear_breakpoints_for_domain (domain);
3945 mono_loader_lock ();
3946 /* Invalidate each thread's frame stack */
3947 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3948 mono_loader_unlock ();
3950 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3954 * invalidate_each_thread:
3956 * A GHFunc to invalidate frames.
3957 * value must be a DebuggerTlsData*
3960 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3962 invalidate_frames ((DebuggerTlsData *)value);
3966 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3968 /* Sent later in jit_end () */
3970 g_ptr_array_add (pending_assembly_loads, assembly);
3975 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3977 if (is_debugger_thread ())
3980 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3982 clear_event_requests_for_assembly (assembly);
3983 clear_types_for_assembly (assembly);
3987 send_type_load (MonoClass *klass)
3989 gboolean type_load = FALSE;
3990 MonoDomain *domain = mono_domain_get ();
3991 AgentDomainInfo *info = NULL;
3993 info = get_agent_domain_info (domain);
3995 mono_loader_lock ();
3997 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
3999 g_hash_table_insert (info->loaded_classes, klass, klass);
4002 mono_loader_unlock ();
4005 emit_type_load (klass, klass, NULL);
4009 * Emit load events for all types currently loaded in the domain.
4010 * Takes the loader and domain locks.
4011 * user_data is unused.
4014 send_types_for_domain (MonoDomain *domain, void *user_data)
4016 AgentDomainInfo *info = NULL;
4018 info = get_agent_domain_info (domain);
4021 mono_loader_lock ();
4022 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4023 mono_loader_unlock ();
4027 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
4030 * We emit type load events when the first method of the type is JITted,
4031 * since the class load profiler callbacks might be called with the
4032 * loader lock held. They could also occur in the debugger thread.
4033 * Same for assembly load events.
4036 MonoAssembly *assembly = NULL;
4038 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4040 if (pending_assembly_loads->len > 0) {
4041 assembly = (MonoAssembly *)g_ptr_array_index (pending_assembly_loads, 0);
4042 g_ptr_array_remove_index (pending_assembly_loads, 0);
4047 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4053 send_type_load (method->klass);
4056 add_pending_breakpoints (method, jinfo);
4060 * BREAKPOINTS/SINGLE STEPPING
4064 * Contains information about an inserted breakpoint.
4067 long il_offset, native_offset;
4071 } BreakpointInstance;
4074 * Contains generic information about a breakpoint.
4078 * The method where the breakpoint is placed. Can be NULL in which case it
4079 * is inserted into every method. This is used to implement method entry/
4080 * exit events. Can be a generic method definition, in which case the
4081 * breakpoint is inserted into every instance.
4087 * A list of BreakpointInstance structures describing where the breakpoint
4088 * was inserted. There could be more than one because of
4089 * generics/appdomains/method entry/exit.
4091 GPtrArray *children;
4094 /* List of breakpoints */
4095 /* Protected by the loader lock */
4096 static GPtrArray *breakpoints;
4097 /* Maps breakpoint locations to the number of breakpoints at that location */
4098 static GHashTable *bp_locs;
4101 breakpoints_init (void)
4103 breakpoints = g_ptr_array_new ();
4104 bp_locs = g_hash_table_new (NULL, NULL);
4108 * insert_breakpoint:
4110 * Insert the breakpoint described by BP into the method described by
4114 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4117 BreakpointInstance *inst;
4118 SeqPointIterator it;
4119 gboolean it_has_sp = FALSE;
4122 mono_error_init (error);
4124 mono_seq_point_iterator_init (&it, seq_points);
4125 while (mono_seq_point_iterator_next (&it)) {
4126 if (it.seq_point.il_offset == bp->il_offset) {
4134 * The set of IL offsets with seq points doesn't completely match the
4135 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4137 mono_seq_point_iterator_init (&it, seq_points);
4138 while (mono_seq_point_iterator_next (&it)) {
4139 if (it.seq_point.il_offset != METHOD_ENTRY_IL_OFFSET &&
4140 it.seq_point.il_offset != METHOD_EXIT_IL_OFFSET &&
4141 it.seq_point.il_offset + 1 == bp->il_offset) {
4149 char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d", mono_method_full_name (jinfo_get_method (ji), TRUE), bp->il_offset);
4151 mono_seq_point_iterator_init (&it, seq_points);
4152 while (mono_seq_point_iterator_next (&it))
4153 DEBUG_PRINTF (1, "%d\n", it.seq_point.il_offset);
4156 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4157 g_warning ("%s", s);
4161 g_warning ("%s", s);
4167 inst = g_new0 (BreakpointInstance, 1);
4168 inst->il_offset = it.seq_point.il_offset;
4169 inst->native_offset = it.seq_point.native_offset;
4170 inst->ip = (guint8*)ji->code_start + it.seq_point.native_offset;
4172 inst->domain = domain;
4174 mono_loader_lock ();
4176 g_ptr_array_add (bp->children, inst);
4178 mono_loader_unlock ();
4181 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4182 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4185 if (it.seq_point.native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4186 DEBUG_PRINTF (1, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset);
4187 } else if (count == 0) {
4188 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4189 mono_arch_set_breakpoint (ji, inst->ip);
4195 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);
4199 remove_breakpoint (BreakpointInstance *inst)
4201 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4203 MonoJitInfo *ji = inst->ji;
4204 guint8 *ip = inst->ip;
4207 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4208 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4211 g_assert (count > 0);
4213 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4214 mono_arch_clear_breakpoint (ji, ip);
4215 DEBUG_PRINTF (1, "[dbg] Clear breakpoint at %s [%p].\n", mono_method_full_name (jinfo_get_method (ji), TRUE), ip);
4223 * This doesn't take any locks.
4225 static inline gboolean
4226 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4232 if (method == bp->method)
4234 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4237 if (bp->method->is_inflated && method->is_inflated) {
4238 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4239 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4241 /* Open generic methods should match closed generic methods of the same class */
4242 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4243 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4244 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4246 /* FIXME: Handle !mvar */
4247 if (t1->type != MONO_TYPE_MVAR)
4258 * add_pending_breakpoints:
4260 * Insert pending breakpoints into the newly JITted method METHOD.
4263 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4266 MonoSeqPointInfo *seq_points;
4268 MonoMethod *jmethod;
4273 domain = mono_domain_get ();
4275 mono_loader_lock ();
4277 for (i = 0; i < breakpoints->len; ++i) {
4278 MonoBreakpoint *bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4279 gboolean found = FALSE;
4281 if (!bp_matches_method (bp, method))
4284 for (j = 0; j < bp->children->len; ++j) {
4285 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4292 MonoMethod *declaring = NULL;
4294 jmethod = jinfo_get_method (ji);
4295 if (jmethod->is_inflated)
4296 declaring = mono_method_get_declaring_generic_method (jmethod);
4298 mono_domain_lock (domain);
4299 seq_points = (MonoSeqPointInfo *)g_hash_table_lookup (domain_jit_info (domain)->seq_points, jmethod);
4300 if (!seq_points && declaring)
4301 seq_points = (MonoSeqPointInfo *)g_hash_table_lookup (domain_jit_info (domain)->seq_points, declaring);
4302 mono_domain_unlock (domain);
4304 /* Could be AOT code */
4306 g_assert (seq_points);
4308 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4312 mono_loader_unlock ();
4316 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4322 mono_error_init (error);
4324 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4328 /* Might be AOTed code */
4329 mono_class_init (method->klass);
4330 code = mono_aot_get_method_checked (domain, method, &oerror);
4332 mono_error_assert_ok (&oerror);
4333 ji = mono_jit_info_table_find (domain, (char *)code);
4338 insert_breakpoint (seq_points, domain, ji, bp, error);
4342 clear_breakpoint (MonoBreakpoint *bp);
4347 * Set a breakpoint at IL_OFFSET in METHOD.
4348 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4349 * METHOD can also be a generic method definition, in which case a breakpoint
4350 * is placed in all instances of the method.
4351 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4354 static MonoBreakpoint*
4355 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4358 GHashTableIter iter, iter2;
4361 MonoSeqPointInfo *seq_points;
4363 GPtrArray *method_domains;
4364 GPtrArray *method_seq_points;
4368 mono_error_init (error);
4371 // - suspend/resume the vm to prevent code patching problems
4372 // - multiple breakpoints on the same location
4373 // - dynamic methods
4376 bp = g_new0 (MonoBreakpoint, 1);
4377 bp->method = method;
4378 bp->il_offset = il_offset;
4380 bp->children = g_ptr_array_new ();
4382 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);
4384 methods = g_ptr_array_new ();
4385 method_domains = g_ptr_array_new ();
4386 method_seq_points = g_ptr_array_new ();
4388 mono_loader_lock ();
4389 g_hash_table_iter_init (&iter, domains);
4390 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4391 mono_domain_lock (domain);
4392 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4393 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4394 if (bp_matches_method (bp, m)) {
4395 /* Save the info locally to simplify the code inside the domain lock */
4396 g_ptr_array_add (methods, m);
4397 g_ptr_array_add (method_domains, domain);
4398 g_ptr_array_add (method_seq_points, seq_points);
4401 mono_domain_unlock (domain);
4404 for (i = 0; i < methods->len; ++i) {
4405 m = (MonoMethod *)g_ptr_array_index (methods, i);
4406 domain = (MonoDomain *)g_ptr_array_index (method_domains, i);
4407 seq_points = (MonoSeqPointInfo *)g_ptr_array_index (method_seq_points, i);
4408 set_bp_in_method (domain, m, seq_points, bp, error);
4411 g_ptr_array_add (breakpoints, bp);
4412 mono_loader_unlock ();
4414 g_ptr_array_free (methods, TRUE);
4415 g_ptr_array_free (method_domains, TRUE);
4416 g_ptr_array_free (method_seq_points, TRUE);
4418 if (error && !mono_error_ok (error)) {
4419 clear_breakpoint (bp);
4427 clear_breakpoint (MonoBreakpoint *bp)
4431 // FIXME: locking, races
4432 for (i = 0; i < bp->children->len; ++i) {
4433 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, i);
4435 remove_breakpoint (inst);
4440 mono_loader_lock ();
4441 g_ptr_array_remove (breakpoints, bp);
4442 mono_loader_unlock ();
4444 g_ptr_array_free (bp->children, TRUE);
4449 breakpoints_cleanup (void)
4453 mono_loader_lock ();
4455 while (i < event_requests->len) {
4456 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
4458 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4459 clear_breakpoint ((MonoBreakpoint *)req->info);
4460 g_ptr_array_remove_index_fast (event_requests, i);
4467 for (i = 0; i < breakpoints->len; ++i)
4468 g_free (g_ptr_array_index (breakpoints, i));
4470 g_ptr_array_free (breakpoints, TRUE);
4471 g_hash_table_destroy (bp_locs);
4476 mono_loader_unlock ();
4480 * clear_breakpoints_for_domain:
4482 * Clear breakpoint instances which reference DOMAIN.
4485 clear_breakpoints_for_domain (MonoDomain *domain)
4489 /* This could be called after shutdown */
4493 mono_loader_lock ();
4494 for (i = 0; i < breakpoints->len; ++i) {
4495 MonoBreakpoint *bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4498 while (j < bp->children->len) {
4499 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4501 if (inst->domain == domain) {
4502 remove_breakpoint (inst);
4506 g_ptr_array_remove_index_fast (bp->children, j);
4512 mono_loader_unlock ();
4516 * ss_calculate_framecount:
4518 * Ensure DebuggerTlsData fields are filled out.
4520 static void ss_calculate_framecount (DebuggerTlsData *tls, MonoContext *ctx)
4522 if (!tls->context.valid)
4523 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4524 compute_frame_info (tls->thread, tls);
4530 * Return FALSE if single stepping needs to continue.
4533 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp, DebuggerTlsData *tls, MonoContext *ctx)
4535 MonoDebugMethodInfo *minfo;
4536 MonoDebugSourceLocation *loc = NULL;
4537 gboolean hit = TRUE;
4540 if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK)) {
4542 * These seq points are inserted by the JIT after calls, step over needs to skip them.
4544 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);
4548 if ((req->depth == STEP_DEPTH_OVER || req->depth == STEP_DEPTH_OUT) && hit) {
4549 gboolean is_step_out = req->depth == STEP_DEPTH_OUT;
4551 ss_calculate_framecount (tls, ctx);
4553 // Because functions can call themselves recursively, we need to make sure we're stopping at the right stack depth.
4554 // In case of step out, the target is the frame *enclosing* the one where the request was made.
4555 int target_frames = req->nframes + (is_step_out ? -1 : 0);
4556 if (req->nframes > 0 && tls->frame_count > 0 && tls->frame_count > target_frames) {
4557 /* Hit the breakpoint in a recursive call, don't halt */
4558 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");
4563 if (req->depth == STEP_DEPTH_INTO && req->size == STEP_SIZE_MIN && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) && ss_req->start_method){
4564 method = jinfo_get_method (ji);
4565 ss_calculate_framecount (tls, ctx);
4566 if (ss_req->start_method == method && req->nframes && tls->frame_count == req->nframes) {//Check also frame count(could be recursion)
4567 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);
4572 if (req->size != STEP_SIZE_LINE)
4575 /* Have to check whenever a different source line was reached */
4576 method = jinfo_get_method (ji);
4577 minfo = mono_debug_lookup_method (method);
4580 loc = mono_debug_method_lookup_location (minfo, sp->il_offset);
4583 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);
4584 ss_req->last_method = method;
4586 } else if (loc && method == ss_req->last_method && loc->row == ss_req->last_line) {
4587 ss_calculate_framecount (tls, ctx);
4588 if (tls->frame_count == req->nframes) { // If the frame has changed we're clearly not on the same source line.
4589 DEBUG_PRINTF (1, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer) (gsize) mono_native_thread_id_get (), loc->row);
4595 ss_req->last_method = method;
4596 ss_req->last_line = loc->row;
4597 mono_debug_free_source_location (loc);
4604 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4606 return bp->method && bp->method->klass->image->assembly == assembly;
4610 process_breakpoint_inner (DebuggerTlsData *tls, gboolean from_signal)
4614 int i, j, suspend_policy;
4615 guint32 native_offset;
4617 BreakpointInstance *inst;
4618 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4619 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4620 EventKind kind = EVENT_KIND_BREAKPOINT;
4621 MonoContext *ctx = &tls->restore_state.ctx;
4623 MonoSeqPointInfo *info;
4627 // FIXME: Speed this up
4629 ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
4630 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4631 g_assert (ji && !ji->is_trampoline);
4632 method = jinfo_get_method (ji);
4634 /* Compute the native offset of the breakpoint from the ip */
4635 native_offset = ip - (guint8*)ji->code_start;
4638 * Skip the instruction causing the breakpoint signal.
4641 mono_arch_skip_breakpoint (ctx, ji);
4643 if (method->wrapper_type || tls->disable_breakpoints)
4646 bp_reqs = g_ptr_array_new ();
4647 ss_reqs = g_ptr_array_new ();
4648 ss_reqs_orig = g_ptr_array_new ();
4650 mono_loader_lock ();
4653 * The ip points to the instruction causing the breakpoint event, which is after
4654 * the offset recorded in the seq point map, so find the prev seq point before ip.
4656 found_sp = mono_find_prev_seq_point_for_native_offset (mono_domain_get (), method, native_offset, &info, &sp);
4659 no_seq_points_found (method, native_offset);
4661 g_assert (found_sp);
4663 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);
4666 for (i = 0; i < breakpoints->len; ++i) {
4667 bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4672 for (j = 0; j < bp->children->len; ++j) {
4673 inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4674 if (inst->ji == ji && inst->il_offset == sp.il_offset && inst->native_offset == sp.native_offset) {
4675 if (bp->req->event_kind == EVENT_KIND_STEP) {
4676 g_ptr_array_add (ss_reqs_orig, bp->req);
4678 g_ptr_array_add (bp_reqs, bp->req);
4683 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4684 /* Maybe a method entry/exit event */
4685 if (sp.il_offset == METHOD_ENTRY_IL_OFFSET)
4686 kind = EVENT_KIND_METHOD_ENTRY;
4687 else if (sp.il_offset == METHOD_EXIT_IL_OFFSET)
4688 kind = EVENT_KIND_METHOD_EXIT;
4691 /* Process single step requests */
4692 for (i = 0; i < ss_reqs_orig->len; ++i) {
4693 EventRequest *req = (EventRequest *)g_ptr_array_index (ss_reqs_orig, i);
4694 SingleStepReq *ss_req = (SingleStepReq *)req->info;
4697 if (mono_thread_internal_current () != ss_req->thread)
4700 hit = ss_update (ss_req, ji, &sp, tls, ctx);
4702 g_ptr_array_add (ss_reqs, req);
4704 /* Start single stepping again from the current sequence point */
4705 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
4708 if (ss_reqs->len > 0)
4709 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4710 if (bp_reqs->len > 0)
4711 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4712 if (kind != EVENT_KIND_BREAKPOINT)
4713 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4715 mono_loader_unlock ();
4717 g_ptr_array_free (bp_reqs, TRUE);
4718 g_ptr_array_free (ss_reqs, TRUE);
4721 * FIXME: The first event will suspend, so the second will only be sent after the
4725 process_event (EVENT_KIND_STEP, method, 0, ctx, ss_events, suspend_policy);
4727 process_event (kind, method, 0, ctx, bp_events, suspend_policy);
4728 if (enter_leave_events)
4729 process_event (kind, method, 0, ctx, enter_leave_events, suspend_policy);
4732 /* Process a breakpoint/single step event after resuming from a signal handler */
4734 process_signal_event (void (*func) (DebuggerTlsData*, gboolean))
4736 DebuggerTlsData *tls;
4737 MonoThreadUnwindState orig_restore_state;
4740 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4741 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4742 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4743 mono_thread_state_init_from_monoctx (&tls->restore_state, &tls->handler_ctx);
4747 /* This is called when resuming from a signal handler, so it shouldn't return */
4748 memcpy (&ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4749 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4750 mono_restore_context (&ctx);
4751 g_assert_not_reached ();
4755 process_breakpoint (void)
4757 process_signal_event (process_breakpoint_inner);
4761 resume_from_signal_handler (void *sigctx, void *func)
4763 DebuggerTlsData *tls;
4766 /* Save the original context in TLS */
4767 // FIXME: This might not work on an altstack ?
4768 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4770 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer) (gsize) mono_native_thread_id_get ());
4773 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4774 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4775 // clob:c could be added to op_seq_point.
4777 mono_sigctx_to_monoctx (sigctx, &ctx);
4778 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4779 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4780 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4782 MONO_CONTEXT_SET_IP (&ctx, func);
4784 mono_monoctx_to_sigctx (&ctx, sigctx);
4786 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4787 mono_ppc_set_func_into_sigctx (sigctx, func);
4792 mono_debugger_agent_breakpoint_hit (void *sigctx)
4795 * We are called from a signal handler, and running code there causes all kinds of
4796 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4797 * So set up the signal context to return to the real breakpoint handler function.
4799 resume_from_signal_handler (sigctx, process_breakpoint);
4803 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4805 if (frame->managed) {
4806 *(MonoContext*)data = *ctx;
4815 * Called by System.Diagnostics.Debugger:Break ().
4818 mono_debugger_agent_user_break (void)
4820 if (agent_config.enabled) {
4825 /* Obtain a context */
4826 MONO_CONTEXT_SET_IP (&ctx, NULL);
4827 mono_walk_stack_with_ctx (user_break_cb, NULL, (MonoUnwindOptions)0, &ctx);
4828 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4830 mono_loader_lock ();
4831 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4832 mono_loader_unlock ();
4834 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4835 } else if (debug_options.native_debugger_break) {
4841 ss_depth_to_string (StepDepth depth)
4844 case STEP_DEPTH_OVER:
4846 case STEP_DEPTH_OUT:
4848 case STEP_DEPTH_INTO:
4851 g_assert_not_reached ();
4857 process_single_step_inner (DebuggerTlsData *tls, gboolean from_signal)
4862 int il_offset, suspend_policy;
4865 MonoContext *ctx = &tls->restore_state.ctx;
4868 MonoSeqPointInfo *info;
4870 ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
4872 /* Skip the instruction causing the single step */
4874 mono_arch_skip_single_step (ctx);
4876 if (suspend_count > 0) {
4877 /* Fastpath during invokes, see in process_suspend () */
4878 if (suspend_count - tls->resume_count == 0)
4880 process_suspend (tls, ctx);
4885 // FIXME: A suspend race
4888 if (mono_thread_internal_current () != ss_req->thread)
4891 if (log_level > 0) {
4892 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4894 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);
4897 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4898 g_assert (ji && !ji->is_trampoline);
4899 method = jinfo_get_method (ji);
4902 if (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4907 * Stopping in memset makes half-initialized vtypes visible.
4908 * Stopping in memcpy makes half-copied vtypes visible.
4910 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
4914 * The ip points to the instruction causing the single step event, which is before
4915 * the offset recorded in the seq point map, so find the next seq point after ip.
4917 if (!mono_find_next_seq_point_for_native_offset (domain, method, (guint8*)ip - (guint8*)ji->code_start, &info, &sp))
4920 il_offset = sp.il_offset;
4922 if (!ss_update (ss_req, ji, &sp, tls, ctx))
4925 /* Start single stepping again from the current sequence point */
4926 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
4928 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
4929 (method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4930 !strcmp (method->name, ".cctor"))
4933 // FIXME: Has to lock earlier
4935 reqs = g_ptr_array_new ();
4937 mono_loader_lock ();
4939 g_ptr_array_add (reqs, ss_req->req);
4941 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4943 g_ptr_array_free (reqs, TRUE);
4945 mono_loader_unlock ();
4947 process_event (EVENT_KIND_STEP, jinfo_get_method (ji), il_offset, ctx, events, suspend_policy);
4951 process_single_step (void)
4953 process_signal_event (process_single_step_inner);
4957 * mono_debugger_agent_single_step_event:
4959 * Called from a signal handler to handle a single step event.
4962 mono_debugger_agent_single_step_event (void *sigctx)
4964 /* Resume to process_single_step through the signal context */
4966 // FIXME: Since step out/over is implemented using step in, the step in case should
4967 // be as fast as possible. Move the relevant code from process_single_step_inner ()
4970 if (is_debugger_thread ()) {
4972 * This could happen despite our best effors when the runtime calls
4973 * assembly/type resolve hooks.
4974 * FIXME: Breakpoints too.
4978 mono_sigctx_to_monoctx (sigctx, &ctx);
4979 mono_arch_skip_single_step (&ctx);
4980 mono_monoctx_to_sigctx (&ctx, sigctx);
4984 resume_from_signal_handler (sigctx, process_single_step);
4988 debugger_agent_single_step_from_context (MonoContext *ctx)
4990 DebuggerTlsData *tls;
4991 MonoThreadUnwindState orig_restore_state;
4993 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4994 /* Fastpath during invokes, see in process_suspend () */
4995 if (tls && suspend_count && suspend_count - tls->resume_count == 0)
4998 if (is_debugger_thread ())
5003 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
5004 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5005 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5006 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5008 process_single_step_inner (tls, FALSE);
5010 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5011 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5015 debugger_agent_breakpoint_from_context (MonoContext *ctx)
5017 DebuggerTlsData *tls;
5018 MonoThreadUnwindState orig_restore_state;
5021 if (is_debugger_thread ())
5024 orig_ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
5025 MONO_CONTEXT_SET_IP (ctx, orig_ip - 1);
5027 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5029 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5030 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5031 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5033 process_breakpoint_inner (tls, FALSE);
5035 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5036 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5037 if (MONO_CONTEXT_GET_IP (ctx) == orig_ip - 1)
5038 MONO_CONTEXT_SET_IP (ctx, orig_ip);
5042 * start_single_stepping:
5044 * Turn on single stepping. Can be called multiple times, for example,
5045 * by a single step event request + a suspend.
5048 start_single_stepping (void)
5050 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5051 int val = InterlockedIncrement (&ss_count);
5054 mono_arch_start_single_stepping ();
5056 g_assert_not_reached ();
5061 stop_single_stepping (void)
5063 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5064 int val = InterlockedDecrement (&ss_count);
5067 mono_arch_stop_single_stepping ();
5069 g_assert_not_reached ();
5076 * Stop the single stepping operation given by SS_REQ.
5079 ss_stop (SingleStepReq *ss_req)
5084 for (l = ss_req->bps; l; l = l->next) {
5085 clear_breakpoint ((MonoBreakpoint *)l->data);
5087 g_slist_free (ss_req->bps);
5091 if (ss_req->global) {
5092 stop_single_stepping ();
5093 ss_req->global = FALSE;
5100 * Reject breakpoint if it is a duplicate of one already in list or hash table.
5103 ss_bp_is_unique (GSList *bps, GHashTable *ss_req_bp_cache, MonoMethod *method, guint32 il_offset)
5105 if (ss_req_bp_cache) {
5106 MonoBreakpoint dummy = {method, il_offset, NULL, NULL};
5107 return !g_hash_table_lookup (ss_req_bp_cache, &dummy);
5109 for (GSList *l = bps; l; l = l->next) {
5110 MonoBreakpoint *bp = (MonoBreakpoint *)l->data;
5111 if (bp->method == method && bp->il_offset == il_offset)
5120 * GHashTable equality for a MonoBreakpoint (only care about method and il_offset fields)
5123 ss_bp_eq (gconstpointer ka, gconstpointer kb)
5125 const MonoBreakpoint *s1 = (const MonoBreakpoint *)ka;
5126 const MonoBreakpoint *s2 = (const MonoBreakpoint *)kb;
5127 return (s1->method == s2->method && s1->il_offset == s2->il_offset) ? 1 : 0;
5133 * GHashTable hash for a MonoBreakpoint (only care about method and il_offset fields)
5136 ss_bp_hash (gconstpointer data)
5138 const MonoBreakpoint *s = (const MonoBreakpoint *)data;
5139 guint hash = (guint) (uintptr_t) s->method;
5140 hash ^= ((guint)s->il_offset) << 16; // Assume low bits are more interesting
5141 hash ^= ((guint)s->il_offset) >> 16;
5145 #define MAX_LINEAR_SCAN_BPS 7
5150 * Create a new breakpoint and add it to a step request.
5151 * Will adjust the bp count and cache used by ss_start.
5154 ss_bp_add_one (SingleStepReq *ss_req, int *ss_req_bp_count, GHashTable **ss_req_bp_cache,
5155 MonoMethod *method, guint32 il_offset)
5157 // This list is getting too long, switch to using the hash table
5158 if (!*ss_req_bp_cache && *ss_req_bp_count > MAX_LINEAR_SCAN_BPS) {
5159 *ss_req_bp_cache = g_hash_table_new (ss_bp_hash, ss_bp_eq);
5160 for (GSList *l = ss_req->bps; l; l = l->next)
5161 g_hash_table_insert (*ss_req_bp_cache, l->data, l->data);
5164 if (ss_bp_is_unique (ss_req->bps, *ss_req_bp_cache, method, il_offset)) {
5165 // Create and add breakpoint
5166 MonoBreakpoint *bp = set_breakpoint (method, il_offset, ss_req->req, NULL);
5167 ss_req->bps = g_slist_append (ss_req->bps, bp);
5168 if (*ss_req_bp_cache)
5169 g_hash_table_insert (*ss_req_bp_cache, bp, bp);
5170 (*ss_req_bp_count)++;
5172 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);
5179 * Start the single stepping operation given by SS_REQ from the sequence point SP.
5180 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
5181 * belong to the same thread as CTX.
5182 * If FRAMES is not-null, use that instead of tls->frames for placing breakpoints etc.
5185 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint* sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls,
5186 gboolean step_to_catch, StackFrame **frames, int nframes)
5188 int i, j, frame_index;
5189 SeqPoint *next_sp, *parent_sp = NULL;
5190 SeqPoint local_sp, local_parent_sp;
5192 MonoSeqPointInfo *parent_info;
5193 MonoMethod *parent_sp_method = NULL;
5194 gboolean enable_global = FALSE;
5196 // When 8 or more entries are in bps, we build a hash table to serve as a set of breakpoints.
5197 // Recreating this on each pass is a little wasteful but at least keeps behavior linear.
5198 int ss_req_bp_count = g_slist_length (ss_req->bps);
5199 GHashTable *ss_req_bp_cache = NULL;
5201 /* Stop the previous operation */
5205 * Implement single stepping using breakpoints if possible.
5207 if (step_to_catch) {
5208 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, sp->il_offset);
5212 if (ctx && !frames) {
5213 /* Need parent frames */
5214 if (!tls->context.valid)
5215 mono_thread_state_init_from_monoctx (&tls->context, ctx);
5216 compute_frame_info (tls->thread, tls);
5217 frames = tls->frames;
5218 nframes = tls->frame_count;
5222 * Find the first sequence point in the current or in a previous frame which
5223 * is not the last in its method.
5225 if (ss_req->depth == STEP_DEPTH_OUT) {
5226 /* Ignore seq points in current method */
5227 while (frame_index < nframes) {
5228 StackFrame *frame = frames [frame_index];
5230 method = frame->method;
5231 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5232 sp = (found_sp)? &local_sp : NULL;
5234 if (sp && sp->next_len != 0)
5237 // There could be method calls before the next seq point in the caller when using nested calls
5238 //enable_global = TRUE;
5240 if (sp && sp->next_len == 0) {
5242 while (frame_index < nframes) {
5243 StackFrame *frame = frames [frame_index];
5245 method = frame->method;
5246 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5247 sp = (found_sp)? &local_sp : NULL;
5248 if (sp && sp->next_len != 0)
5254 /* Have to put a breakpoint into a parent frame since the seq points might not cover all control flow out of the method */
5255 while (frame_index < nframes) {
5256 StackFrame *frame = frames [frame_index];
5258 parent_sp_method = frame->method;
5259 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &parent_info, &local_parent_sp);
5260 parent_sp = found_sp ? &local_parent_sp : NULL;
5261 if (found_sp && parent_sp->next_len != 0)
5269 if (sp && sp->next_len > 0) {
5270 SeqPoint* next = g_new(SeqPoint, sp->next_len);
5272 mono_seq_point_init_next (info, *sp, next);
5273 for (i = 0; i < sp->next_len; i++) {
5276 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, next_sp->il_offset);
5282 SeqPoint* next = g_new(SeqPoint, parent_sp->next_len);
5284 mono_seq_point_init_next (parent_info, *parent_sp, next);
5285 for (i = 0; i < parent_sp->next_len; i++) {
5288 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, parent_sp_method, next_sp->il_offset);
5293 if (ss_req->nframes == 0)
5294 ss_req->nframes = nframes;
5296 if ((ss_req->depth == STEP_DEPTH_OVER) && (!sp && !parent_sp)) {
5297 DEBUG_PRINTF (1, "[dbg] No parent frame for step over, transition to step into.\n");
5299 * This is needed since if we leave managed code, and later return to it, step over
5300 * is not going to stop.
5301 * This approach is a bit ugly, since we change the step depth, but it only affects
5302 * clients who reuse the same step request, and only in this special case.
5304 ss_req->depth = STEP_DEPTH_INTO;
5307 if (ss_req->depth == STEP_DEPTH_OVER) {
5308 /* Need to stop in catch clauses as well */
5309 for (i = 0; i < nframes; ++i) {
5310 StackFrame *frame = frames [i];
5313 MonoJitInfo *jinfo = frame->ji;
5314 for (j = 0; j < jinfo->num_clauses; ++j) {
5315 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5317 found_sp = mono_find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL, &local_sp);
5318 sp = (found_sp)? &local_sp : NULL;
5321 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, frame->method, sp->il_offset);
5327 if (ss_req->depth == STEP_DEPTH_INTO) {
5328 /* Enable global stepping so we stop at method entry too */
5329 enable_global = TRUE;
5333 * The ctx/frame info computed above will become invalid when we continue.
5335 tls->context.valid = FALSE;
5336 tls->async_state.valid = FALSE;
5337 invalidate_frames (tls);
5340 if (enable_global) {
5341 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5342 ss_req->global = TRUE;
5343 start_single_stepping ();
5344 } else if (!ss_req->bps) {
5345 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5346 ss_req->global = TRUE;
5347 start_single_stepping ();
5349 ss_req->global = FALSE;
5352 if (ss_req_bp_cache)
5353 g_hash_table_destroy (ss_req_bp_cache);
5357 * Start single stepping of thread THREAD
5360 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req)
5362 DebuggerTlsData *tls;
5363 MonoSeqPointInfo *info = NULL;
5364 SeqPoint *sp = NULL;
5367 MonoMethod *method = NULL;
5368 MonoDebugMethodInfo *minfo;
5369 gboolean step_to_catch = FALSE;
5370 gboolean set_ip = FALSE;
5371 StackFrame **frames = NULL;
5374 if (suspend_count == 0)
5375 return ERR_NOT_SUSPENDED;
5377 wait_for_suspend ();
5379 // FIXME: Multiple requests
5381 DEBUG_PRINTF (0, "Received a single step request while the previous one was still active.\n");
5382 return ERR_NOT_IMPLEMENTED;
5385 DEBUG_PRINTF (1, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth));
5387 ss_req = g_new0 (SingleStepReq, 1);
5389 ss_req->thread = thread;
5390 ss_req->size = size;
5391 ss_req->depth = depth;
5392 ss_req->filter = filter;
5395 mono_loader_lock ();
5396 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5397 mono_loader_unlock ();
5399 if (!tls->context.valid) {
5400 DEBUG_PRINTF (1, "Received a single step request on a thread with no managed frames.");
5401 return ERR_INVALID_ARGUMENT;
5404 if (tls->restore_state.valid && MONO_CONTEXT_GET_IP (&tls->context.ctx) != MONO_CONTEXT_GET_IP (&tls->restore_state.ctx)) {
5406 * Need to start single stepping from restore_state and not from the current state
5409 frames = compute_frame_info_from (thread, tls, &tls->restore_state, &nframes);
5412 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5414 if (tls->catch_state.valid) {
5416 StackFrameInfo frame;
5417 MonoContext new_ctx;
5418 MonoLMF *lmf = NULL;
5421 * We are stopped at a throw site. Stepping should go to the catch site.
5424 /* Find the the jit info for the catch context */
5425 res = mono_find_jit_info_ext (
5426 (MonoDomain *)tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN],
5427 (MonoJitTlsData *)((MonoThreadInfo*)thread->thread_info)->jit_data,
5428 NULL, &tls->catch_state.ctx, &new_ctx, NULL, &lmf, NULL, &frame);
5430 g_assert (frame.type == FRAME_TYPE_MANAGED);
5433 * Find the seq point corresponding to the landing site ip, which is the first seq
5436 found_sp = mono_find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info, &local_sp);
5437 sp = (found_sp)? &local_sp : NULL;
5439 no_seq_points_found (frame.method, frame.native_offset);
5442 method = frame.method;
5444 step_to_catch = TRUE;
5445 /* This make sure the seq point is not skipped by process_single_step () */
5446 ss_req->last_sp = NULL;
5449 if (!step_to_catch) {
5450 StackFrame *frame = NULL;
5453 if (frames && nframes)
5456 compute_frame_info (thread, tls);
5458 if (tls->frame_count)
5459 frame = tls->frames [0];
5462 if (ss_req->size == STEP_SIZE_LINE) {
5464 ss_req->last_method = frame->method;
5465 ss_req->last_line = -1;
5467 minfo = mono_debug_lookup_method (frame->method);
5468 if (minfo && frame->il_offset != -1) {
5469 MonoDebugSourceLocation *loc = mono_debug_method_lookup_location (minfo, frame->il_offset);
5472 ss_req->last_line = loc->row;
5480 if (!method && frame->il_offset != -1) {
5481 /* FIXME: Sort the table and use a binary search */
5482 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5483 sp = (found_sp)? &local_sp : NULL;
5485 no_seq_points_found (frame->method, frame->native_offset);
5487 method = frame->method;
5492 ss_req->start_method = method;
5494 ss_start (ss_req, method, sp, info, set_ip ? &tls->restore_state.ctx : &tls->context.ctx, tls, step_to_catch, frames, nframes);
5497 free_frames (frames, nframes);
5503 ss_destroy (SingleStepReq *req)
5506 g_assert (ss_req == req);
5515 ss_clear_for_assembly (SingleStepReq *req, MonoAssembly *assembly)
5518 gboolean found = TRUE;
5522 for (l = ss_req->bps; l; l = l->next) {
5523 if (breakpoint_matches_assembly ((MonoBreakpoint *)l->data, assembly)) {
5524 clear_breakpoint ((MonoBreakpoint *)l->data);
5525 ss_req->bps = g_slist_delete_link (ss_req->bps, l);
5534 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5537 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5544 if (!agent_config.enabled)
5547 mono_loader_lock ();
5548 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5549 mono_loader_unlock ();
5554 ei.category = mono_string_to_utf8_checked (category, &error);
5555 mono_error_cleanup (&error);
5559 ei.message = mono_string_to_utf8_checked (message, &error);
5560 mono_error_cleanup (&error);
5563 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5565 g_free (ei.category);
5566 g_free (ei.message);
5570 mono_debugger_agent_debug_log_is_enabled (void)
5572 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5573 return agent_config.enabled;
5576 #if defined(PLATFORM_ANDROID) || defined(TARGET_ANDROID)
5578 mono_debugger_agent_unhandled_exception (MonoException *exc)
5587 memset (&ei, 0, sizeof (EventInfo));
5588 ei.exc = (MonoObject*)exc;
5590 mono_loader_lock ();
5591 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5592 mono_loader_unlock ();
5594 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5599 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5600 MonoContext *catch_ctx)
5602 int i, j, suspend_policy;
5604 MonoJitInfo *ji, *catch_ji;
5606 DebuggerTlsData *tls = NULL;
5608 if (thread_to_tls != NULL) {
5609 MonoInternalThread *thread = mono_thread_internal_current ();
5611 mono_loader_lock ();
5612 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5613 mono_loader_unlock ();
5615 if (tls && tls->abort_requested)
5617 if (tls && tls->disable_breakpoints)
5621 memset (&ei, 0, sizeof (EventInfo));
5623 /* Just-In-Time debugging */
5625 if (agent_config.onuncaught && !inited) {
5626 finish_agent_init (FALSE);
5629 * Send an unsolicited EXCEPTION event with a dummy request id.
5631 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5632 ei.exc = (MonoObject*)exc;
5633 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5636 } else if (agent_config.onthrow && !inited) {
5638 gboolean found = FALSE;
5640 for (l = agent_config.onthrow; l; l = l->next) {
5641 char *ex_type = (char *)l->data;
5642 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5644 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5651 finish_agent_init (FALSE);
5654 * Send an unsolicited EXCEPTION event with a dummy request id.
5656 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5657 ei.exc = (MonoObject*)exc;
5658 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5666 ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5668 catch_ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5672 ei.exc = (MonoObject*)exc;
5673 ei.caught = catch_ctx != NULL;
5675 mono_loader_lock ();
5677 /* Treat exceptions which are caught in non-user code as unhandled */
5678 for (i = 0; i < event_requests->len; ++i) {
5679 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
5680 if (req->event_kind != EVENT_KIND_EXCEPTION)
5683 for (j = 0; j < req->nmodifiers; ++j) {
5684 Modifier *mod = &req->modifiers [j];
5686 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5688 gboolean found = FALSE;
5689 MonoAssembly **assemblies = mod->data.assemblies;
5692 for (k = 0; assemblies [k]; ++k)
5693 if (assemblies [k] == jinfo_get_method (catch_ji)->klass->image->assembly)
5702 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5703 mono_loader_unlock ();
5705 if (tls && ei.caught && catch_ctx) {
5706 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5707 tls->catch_state.ctx = *catch_ctx;
5708 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5709 tls->catch_state.valid = TRUE;
5712 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5715 tls->catch_state.valid = FALSE;
5719 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5721 DebuggerTlsData *tls;
5726 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5731 * We're about to invoke an exception filter during the first pass of exception handling.
5733 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5734 * 'orig_ctx' is the context where the exception has been thrown.
5737 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5739 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5740 * the call site (line 37) and then continue to Main(), but it would never
5741 * include the throw site (line 32).
5743 * Since exception filters are invoked during the first pass of exception handling,
5744 * the stack frames of the throw site are still intact, so we should include them
5747 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5749 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5750 * but report the location of the 'throw' to the user.
5754 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5758 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5760 DebuggerTlsData *tls;
5765 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5769 tls->filter_state.valid = FALSE;
5773 * buffer_add_value_full:
5775 * Add the encoding of the value at ADDR described by T to the buffer.
5776 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5780 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5781 gboolean as_vtype, GHashTable *parent_vtypes)
5784 gboolean boxed_vtype = FALSE;
5787 if (!(*(void**)addr)) {
5788 /* This can happen with compiler generated locals */
5789 //printf ("%s\n", mono_type_full_name (t));
5790 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5793 g_assert (*(void**)addr);
5794 addr = *(void**)addr;
5799 case MONO_TYPE_BOOLEAN:
5802 case MONO_TYPE_CHAR:
5822 case MONO_TYPE_VOID:
5823 buffer_add_byte (buf, t->type);
5825 case MONO_TYPE_BOOLEAN:
5828 buffer_add_byte (buf, t->type);
5829 buffer_add_int (buf, *(gint8*)addr);
5831 case MONO_TYPE_CHAR:
5834 buffer_add_byte (buf, t->type);
5835 buffer_add_int (buf, *(gint16*)addr);
5840 buffer_add_byte (buf, t->type);
5841 buffer_add_int (buf, *(gint32*)addr);
5846 buffer_add_byte (buf, t->type);
5847 buffer_add_long (buf, *(gint64*)addr);
5851 /* Treat it as a vtype */
5853 case MONO_TYPE_PTR: {
5854 gssize val = *(gssize*)addr;
5856 buffer_add_byte (buf, t->type);
5857 buffer_add_long (buf, val);
5861 case MONO_TYPE_STRING:
5862 case MONO_TYPE_SZARRAY:
5863 case MONO_TYPE_OBJECT:
5864 case MONO_TYPE_CLASS:
5865 case MONO_TYPE_ARRAY:
5866 obj = *(MonoObject**)addr;
5869 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5871 if (obj->vtable->klass->valuetype) {
5872 t = &obj->vtable->klass->byval_arg;
5873 addr = mono_object_unbox (obj);
5876 } else if (obj->vtable->klass->rank) {
5877 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5878 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5879 buffer_add_byte (buf, MONO_TYPE_CLASS);
5881 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5883 buffer_add_objid (buf, obj);
5887 case MONO_TYPE_VALUETYPE:
5888 case MONO_TYPE_TYPEDBYREF: {
5892 MonoClass *klass = mono_class_from_mono_type (t);
5897 * Handle boxed vtypes recursively referencing themselves using fields.
5900 parent_vtypes = g_hash_table_new (NULL, NULL);
5901 vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
5903 if (CHECK_PROTOCOL_VERSION (2, 33)) {
5904 buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
5905 buffer_add_int (buf, vtype_index - 1);
5907 /* The client can't handle PARENT_VTYPE */
5908 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5912 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
5916 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5917 buffer_add_byte (buf, klass->enumtype);
5918 buffer_add_typeid (buf, domain, klass);
5922 while ((f = mono_class_get_fields (klass, &iter))) {
5923 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5925 if (mono_field_is_deleted (f))
5929 buffer_add_int (buf, nfields);
5932 while ((f = mono_class_get_fields (klass, &iter))) {
5933 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5935 if (mono_field_is_deleted (f))
5937 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE, parent_vtypes);
5941 g_hash_table_remove (parent_vtypes, addr);
5942 if (g_hash_table_size (parent_vtypes) == 0) {
5943 g_hash_table_destroy (parent_vtypes);
5944 parent_vtypes = NULL;
5949 case MONO_TYPE_GENERICINST:
5950 if (mono_type_generic_inst_is_valuetype (t)) {
5962 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5964 buffer_add_value_full (buf, t, addr, domain, FALSE, NULL);
5968 obj_is_of_type (MonoObject *obj, MonoType *t)
5970 MonoClass *klass = obj->vtable->klass;
5971 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5972 if (mono_class_is_transparent_proxy (klass)) {
5973 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5974 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5984 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5987 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5993 gpointer iter = NULL;
5997 is_enum = decode_byte (buf, &buf, limit);
5998 /* Enums are sent as a normal vtype */
6000 return ERR_NOT_IMPLEMENTED;
6001 klass = decode_typeid (buf, &buf, limit, &d, &err);
6002 if (err != ERR_NONE)
6005 if (t && klass != mono_class_from_mono_type (t)) {
6006 char *name = mono_type_full_name (t);
6007 char *name2 = mono_type_full_name (&klass->byval_arg);
6008 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got %s.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, name2);
6011 return ERR_INVALID_ARGUMENT;
6014 nfields = decode_int (buf, &buf, limit);
6015 while ((f = mono_class_get_fields (klass, &iter))) {
6016 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6018 if (mono_field_is_deleted (f))
6020 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
6021 if (err != ERR_NONE)
6025 g_assert (nfields == 0);
6033 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6037 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
6038 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
6039 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
6040 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
6041 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE) &&
6042 !(t->type == MONO_TYPE_VALUETYPE && type == MONO_TYPE_OBJECT)) {
6043 char *name = mono_type_full_name (t);
6044 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
6046 return ERR_INVALID_ARGUMENT;
6050 case MONO_TYPE_BOOLEAN:
6051 *(guint8*)addr = decode_int (buf, &buf, limit);
6053 case MONO_TYPE_CHAR:
6054 *(gunichar2*)addr = decode_int (buf, &buf, limit);
6057 *(gint8*)addr = decode_int (buf, &buf, limit);
6060 *(guint8*)addr = decode_int (buf, &buf, limit);
6063 *(gint16*)addr = decode_int (buf, &buf, limit);
6066 *(guint16*)addr = decode_int (buf, &buf, limit);
6069 *(gint32*)addr = decode_int (buf, &buf, limit);
6072 *(guint32*)addr = decode_int (buf, &buf, limit);
6075 *(gint64*)addr = decode_long (buf, &buf, limit);
6078 *(guint64*)addr = decode_long (buf, &buf, limit);
6081 *(guint32*)addr = decode_int (buf, &buf, limit);
6084 *(guint64*)addr = decode_long (buf, &buf, limit);
6087 /* We send these as I8, so we get them back as such */
6088 g_assert (type == MONO_TYPE_I8);
6089 *(gssize*)addr = decode_long (buf, &buf, limit);
6091 case MONO_TYPE_GENERICINST:
6092 if (MONO_TYPE_ISSTRUCT (t)) {
6093 /* The client sends these as a valuetype */
6101 /* We send these as vtypes, so we get them back as such */
6102 g_assert (type == MONO_TYPE_VALUETYPE);
6105 case MONO_TYPE_VALUETYPE:
6106 if (type == MONO_TYPE_OBJECT) {
6108 int objid = decode_objid (buf, &buf, limit);
6112 err = get_object (objid, (MonoObject**)&obj);
6113 if (err != ERR_NONE)
6116 return ERR_INVALID_ARGUMENT;
6117 if (obj->vtable->klass != mono_class_from_mono_type (t)) {
6118 DEBUG_PRINTF (1, "Expected type '%s', got object '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6119 return ERR_INVALID_ARGUMENT;
6121 memcpy (addr, mono_object_unbox (obj), mono_class_value_size (obj->vtable->klass, NULL));
6123 err = decode_vtype (t, domain, addr, buf, &buf, limit);
6124 if (err != ERR_NONE)
6130 if (MONO_TYPE_IS_REFERENCE (t)) {
6131 if (type == MONO_TYPE_OBJECT) {
6132 int objid = decode_objid (buf, &buf, limit);
6136 err = get_object (objid, (MonoObject**)&obj);
6137 if (err != ERR_NONE)
6141 if (!obj_is_of_type (obj, t)) {
6142 DEBUG_PRINTF (1, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6143 return ERR_INVALID_ARGUMENT;
6146 if (obj && obj->vtable->domain != domain)
6147 return ERR_INVALID_ARGUMENT;
6149 mono_gc_wbarrier_generic_store (addr, obj);
6150 } else if (type == VALUE_TYPE_ID_NULL) {
6151 *(MonoObject**)addr = NULL;
6152 } else if (type == MONO_TYPE_VALUETYPE) {
6161 /* This can happen when round-tripping boxed vtypes */
6163 * Obtain vtype class.
6164 * Same as the beginning of the handle_vtype case above.
6167 is_enum = decode_byte (buf, &buf, limit);
6169 return ERR_NOT_IMPLEMENTED;
6170 klass = decode_typeid (buf, &buf, limit, &d, &err);
6171 if (err != ERR_NONE)
6174 /* Decode the vtype into a temporary buffer, then box it. */
6175 vtype_buf_size = mono_class_value_size (klass, NULL);
6176 vtype_buf = (guint8 *)g_malloc0 (vtype_buf_size);
6177 g_assert (vtype_buf);
6180 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
6181 if (err != ERR_NONE) {
6185 *(MonoObject**)addr = mono_value_box_checked (d, klass, vtype_buf, &error);
6186 mono_error_cleanup (&error);
6189 char *name = mono_type_full_name (t);
6190 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
6192 return ERR_INVALID_ARGUMENT;
6206 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6210 int type = decode_byte (buf, &buf, limit);
6212 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
6213 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
6214 guint8 *nullable_buf;
6217 * First try decoding it as a Nullable`1
6219 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6220 if (err == ERR_NONE)
6224 * Then try decoding as a primitive value or null.
6226 if (targ->type == type) {
6227 nullable_buf = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
6228 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
6229 if (err != ERR_NONE) {
6230 g_free (nullable_buf);
6233 MonoObject *boxed = mono_value_box_checked (domain, mono_class_from_mono_type (targ), nullable_buf, &error);
6234 if (!is_ok (&error)) {
6235 mono_error_cleanup (&error);
6236 return ERR_INVALID_OBJECT;
6238 mono_nullable_init (addr, boxed, mono_class_from_mono_type (t));
6239 g_free (nullable_buf);
6242 } else if (type == VALUE_TYPE_ID_NULL) {
6243 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
6249 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6253 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
6257 guint8 *addr, *gaddr;
6260 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6261 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6264 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
6265 reg_val = mono_arch_context_get_int_reg (ctx, reg);
6267 buffer_add_value_full (buf, t, ®_val, domain, as_vtype, NULL);
6269 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6270 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6271 addr += (gint32)var->offset;
6273 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6275 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6277 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6280 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6281 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
6282 /* Same as regoffset, but with an indirection */
6283 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6284 addr += (gint32)var->offset;
6286 gaddr = (guint8 *)*(gpointer*)addr;
6288 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL);
6290 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
6291 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
6292 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
6293 MonoGSharedVtMethodRuntimeInfo *info;
6299 g_assert (info_var);
6300 g_assert (locals_var);
6302 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6303 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6304 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6305 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6306 addr += (gint32)info_var->offset;
6307 info = (MonoGSharedVtMethodRuntimeInfo *)*(gpointer*)addr;
6308 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6309 info = (MonoGSharedVtMethodRuntimeInfo *)mono_arch_context_get_int_reg (ctx, reg);
6311 g_assert_not_reached ();
6315 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6316 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6317 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6318 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6319 addr += (gint32)locals_var->offset;
6320 locals = (guint8 *)*(gpointer*)addr;
6321 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6322 locals = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6324 g_assert_not_reached ();
6328 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6330 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6335 g_assert_not_reached ();
6340 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
6344 guint8 *addr, *gaddr;
6346 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6347 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6349 if (MONO_TYPE_IS_REFERENCE (t))
6350 size = sizeof (gpointer);
6352 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6355 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6356 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6358 gboolean is_signed = FALSE;
6361 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6364 // FIXME: Write barriers
6365 mono_gc_memmove_atomic (addr, val, size);
6370 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6375 v = is_signed ? *(gint8*)val : *(guint8*)val;
6378 v = is_signed ? *(gint16*)val : *(guint16*)val;
6381 v = is_signed ? *(gint32*)val : *(guint32*)val;
6384 v = is_signed ? *(gint64*)val : *(guint64*)val;
6387 g_assert_not_reached ();
6390 /* Set value on the stack or in the return ctx */
6391 if (reg_locations [reg]) {
6392 /* Saved on the stack */
6393 DEBUG_PRINTF (1, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v);
6394 *(reg_locations [reg]) = v;
6397 DEBUG_PRINTF (1, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v);
6398 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6401 // FIXME: Move these to mono-context.h/c.
6402 mono_arch_context_set_int_reg (ctx, reg, v);
6404 // FIXME: Can't set registers, so we disable linears
6409 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6410 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6411 addr += (gint32)var->offset;
6413 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6416 addr = *(guint8**)addr;
6422 // FIXME: Write barriers
6423 mono_gc_memmove_atomic (addr, val, size);
6425 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6426 /* Same as regoffset, but with an indirection */
6427 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6428 addr += (gint32)var->offset;
6430 gaddr = (guint8 *)*(gpointer*)addr;
6432 // FIXME: Write barriers
6433 mono_gc_memmove_atomic (gaddr, val, size);
6435 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6439 g_assert_not_reached ();
6444 clear_event_request (int req_id, int etype)
6448 mono_loader_lock ();
6449 for (i = 0; i < event_requests->len; ++i) {
6450 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6452 if (req->id == req_id && req->event_kind == etype) {
6453 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6454 clear_breakpoint ((MonoBreakpoint *)req->info);
6455 if (req->event_kind == EVENT_KIND_STEP)
6456 ss_destroy ((SingleStepReq *)req->info);
6457 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6458 clear_breakpoint ((MonoBreakpoint *)req->info);
6459 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6460 clear_breakpoint ((MonoBreakpoint *)req->info);
6461 g_ptr_array_remove_index_fast (event_requests, i);
6466 mono_loader_unlock ();
6470 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
6474 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6475 m->kind = MOD_KIND_NONE;
6476 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6477 int count = 0, match_count = 0, pos;
6478 MonoAssembly **newassemblies;
6480 for (i = 0; m->data.assemblies [i]; ++i) {
6482 if (m->data.assemblies [i] == assembly)
6487 newassemblies = g_new0 (MonoAssembly*, count - match_count);
6490 for (i = 0; i < count; ++i)
6491 if (m->data.assemblies [i] != assembly)
6492 newassemblies [pos ++] = m->data.assemblies [i];
6493 g_assert (pos == count - match_count);
6494 g_free (m->data.assemblies);
6495 m->data.assemblies = newassemblies;
6501 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
6505 for (i = 0; i < req->nmodifiers; ++i) {
6506 Modifier *m = &req->modifiers [i];
6508 clear_assembly_from_modifier (req, m, assembly);
6513 * clear_event_requests_for_assembly:
6515 * Clear all events requests which reference ASSEMBLY.
6518 clear_event_requests_for_assembly (MonoAssembly *assembly)
6523 mono_loader_lock ();
6527 for (i = 0; i < event_requests->len; ++i) {
6528 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6530 clear_assembly_from_modifiers (req, assembly);
6532 if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly ((MonoBreakpoint *)req->info, assembly)) {
6533 clear_event_request (req->id, req->event_kind);
6538 if (req->event_kind == EVENT_KIND_STEP)
6539 ss_clear_for_assembly ((SingleStepReq *)req->info, assembly);
6542 mono_loader_unlock ();
6546 * type_comes_from_assembly:
6548 * GHRFunc that returns TRUE if klass comes from assembly
6551 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6553 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6557 * clear_types_for_assembly:
6559 * Clears types from loaded_classes for a given assembly
6562 clear_types_for_assembly (MonoAssembly *assembly)
6564 MonoDomain *domain = mono_domain_get ();
6565 AgentDomainInfo *info = NULL;
6567 if (!domain || !domain_jit_info (domain))
6568 /* Can happen during shutdown */
6571 info = get_agent_domain_info (domain);
6573 mono_loader_lock ();
6574 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6575 mono_loader_unlock ();
6579 add_thread (gpointer key, gpointer value, gpointer user_data)
6581 MonoInternalThread *thread = (MonoInternalThread *)value;
6582 Buffer *buf = (Buffer *)user_data;
6584 buffer_add_objid (buf, (MonoObject*)thread);
6588 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6591 guint8 *end = invoke->endp;
6595 MonoMethodSignature *sig;
6598 MonoObject *this_arg, *res, *exc;
6601 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6604 MonoStopwatch watch;
6606 if (invoke->method) {
6608 * Invoke this method directly, currently only Environment.Exit () is supported.
6611 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>");
6613 mono_runtime_try_invoke (invoke->method, NULL, invoke->args, &exc, &error);
6614 mono_error_assert_ok (&error);
6616 g_assert_not_reached ();
6619 m = decode_methodid (p, &p, end, &domain, &err);
6620 if (err != ERR_NONE)
6622 sig = mono_method_signature (m);
6624 if (m->klass->valuetype)
6625 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6627 this_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
6628 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6629 /* Should be null */
6630 int type = decode_byte (p, &p, end);
6631 if (type != VALUE_TYPE_ID_NULL) {
6632 DEBUG_PRINTF (1, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6633 return ERR_INVALID_ARGUMENT;
6635 memset (this_buf, 0, mono_class_instance_size (m->klass));
6636 } else if (m->klass->valuetype && !strcmp (m->name, ".ctor")) {
6640 int type = decode_byte (p, &tmp_p, end);
6641 if (type == VALUE_TYPE_ID_NULL) {
6642 memset (this_buf, 0, mono_class_instance_size (m->klass));
6645 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6646 if (err != ERR_NONE)
6650 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6651 if (err != ERR_NONE)
6655 if (!m->klass->valuetype)
6656 this_arg = *(MonoObject**)this_buf;
6660 if (MONO_CLASS_IS_INTERFACE (m->klass)) {
6662 DEBUG_PRINTF (1, "[%p] Error: Interface method invoked without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6663 return ERR_INVALID_ARGUMENT;
6665 m = mono_object_get_virtual_method (this_arg, m);
6666 /* Transform this to the format the rest of the code expects it to be */
6667 if (m->klass->valuetype) {
6668 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6669 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
6671 } else if ((m->flags & METHOD_ATTRIBUTE_VIRTUAL) && !m->klass->valuetype && invoke->flags & INVOKE_FLAG_VIRTUAL) {
6673 DEBUG_PRINTF (1, "[%p] Error: invoke with INVOKE_FLAG_VIRTUAL flag set without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6674 return ERR_INVALID_ARGUMENT;
6676 m = mono_object_get_virtual_method (this_arg, m);
6677 if (m->klass->valuetype) {
6678 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6679 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
6683 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>");
6685 if (this_arg && this_arg->vtable->domain != domain)
6688 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this_arg) {
6689 if (!strcmp (m->name, ".ctor")) {
6690 if (mono_class_is_abstract (m->klass))
6691 return ERR_INVALID_ARGUMENT;
6694 this_arg = mono_object_new_checked (domain, m->klass, &error);
6695 mono_error_assert_ok (&error);
6698 return ERR_INVALID_ARGUMENT;
6702 if (this_arg && !obj_is_of_type (this_arg, &m->klass->byval_arg))
6703 return ERR_INVALID_ARGUMENT;
6705 nargs = decode_int (p, &p, end);
6706 if (nargs != sig->param_count)
6707 return ERR_INVALID_ARGUMENT;
6708 /* Use alloca to get gc tracking */
6709 arg_buf = (guint8 **)g_alloca (nargs * sizeof (gpointer));
6710 memset (arg_buf, 0, nargs * sizeof (gpointer));
6711 args = (gpointer *)g_alloca (nargs * sizeof (gpointer));
6712 for (i = 0; i < nargs; ++i) {
6713 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6714 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6715 if (err != ERR_NONE)
6717 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6720 if (sig->params [i]->byref) {
6721 arg_buf [i] = (guint8 *)g_alloca (sizeof (mgreg_t));
6722 *(gpointer*)arg_buf [i] = args [i];
6723 args [i] = arg_buf [i];
6726 arg_buf [i] = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6727 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6728 if (err != ERR_NONE)
6730 args [i] = arg_buf [i];
6737 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6738 tls->disable_breakpoints = TRUE;
6740 tls->disable_breakpoints = FALSE;
6743 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6745 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6746 if (invoke->has_ctx) {
6749 lmf_addr = mono_get_lmf_addr ();
6752 memset (&ext, 0, sizeof (ext));
6753 mono_arch_init_lmf_ext (&ext, *lmf_addr);
6755 ext.debugger_invoke = TRUE;
6756 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6758 mono_set_lmf ((MonoLMF*)&ext);
6762 mono_stopwatch_start (&watch);
6763 res = mono_runtime_try_invoke (m, m->klass->valuetype ? (gpointer) this_buf : (gpointer) this_arg, args, &exc, &error);
6764 if (exc == NULL && !mono_error_ok (&error)) {
6765 exc = (MonoObject*) mono_error_convert_to_exception (&error);
6767 mono_error_cleanup (&error); /* FIXME report error */
6769 mono_stopwatch_stop (&watch);
6770 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));
6772 buffer_add_byte (buf, 0);
6773 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6775 gboolean out_this = FALSE;
6776 gboolean out_args = FALSE;
6778 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_THIS) && CHECK_PROTOCOL_VERSION (2, 35))
6780 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_ARGS) && CHECK_PROTOCOL_VERSION (2, 35))
6782 buffer_add_byte (buf, 1 + (out_this ? 2 : 0) + (out_args ? 4 : 0));
6783 if (sig->ret->type == MONO_TYPE_VOID) {
6784 if (!strcmp (m->name, ".ctor")) {
6785 if (!m->klass->valuetype)
6786 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this_arg, domain);
6788 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
6790 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6792 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6793 buffer_add_value (buf, sig->ret, &res, domain);
6794 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6795 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6796 MonoClass *k = mono_class_from_mono_type (sig->ret);
6797 guint8 *nullable_buf = (guint8 *)g_alloca (mono_class_value_size (k, NULL));
6799 g_assert (nullable_buf);
6800 mono_nullable_init (nullable_buf, res, k);
6801 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6804 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6810 /* Return the new value of the receiver after the call */
6811 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
6813 buffer_add_int (buf, nargs);
6814 for (i = 0; i < nargs; ++i) {
6815 if (MONO_TYPE_IS_REFERENCE (sig->params [i]))
6816 buffer_add_value (buf, sig->params [i], &args [i], domain);
6817 else if (sig->params [i]->byref)
6818 /* add_value () does an indirection */
6819 buffer_add_value (buf, sig->params [i], &arg_buf [i], domain);
6821 buffer_add_value (buf, sig->params [i], arg_buf [i], domain);
6826 tls->disable_breakpoints = FALSE;
6828 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6829 if (invoke->has_ctx)
6830 mono_set_lmf ((MonoLMF *)(((gssize)ext.lmf.previous_lmf) & ~3));
6834 // FIXME: byref arguments
6842 * Invoke the method given by tls->pending_invoke in the current thread.
6845 invoke_method (void)
6847 DebuggerTlsData *tls;
6853 MonoContext restore_ctx;
6856 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
6860 * Store the `InvokeData *' in `tls->invoke' until we're done with
6861 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6864 mono_loader_lock ();
6866 invoke = tls->pending_invoke;
6868 tls->pending_invoke = NULL;
6870 invoke->last_invoke = tls->invoke;
6871 tls->invoke = invoke;
6873 mono_loader_unlock ();
6875 tls->frames_up_to_date = FALSE;
6881 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6882 buffer_init (&buf, 128);
6885 /* Fail the other invokes as well */
6887 err = do_invoke_method (tls, &buf, invoke, p, &p);
6890 if (tls->abort_requested) {
6891 if (CHECK_PROTOCOL_VERSION (2, 42))
6892 err = ERR_INVOKE_ABORTED;
6895 /* Start suspending before sending the reply */
6896 if (mindex == invoke->nmethods - 1) {
6897 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6898 for (i = 0; i < invoke->suspend_count; ++i)
6903 send_reply_packet (id, err, &buf);
6908 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6910 if (invoke->has_ctx)
6911 save_thread_context (&restore_ctx);
6913 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6914 g_assert (tls->resume_count);
6915 tls->resume_count -= invoke->suspend_count;
6918 DEBUG_PRINTF (1, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer) (gsize) mono_native_thread_id_get (), err, tls->resume_count);
6921 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6923 * It is possible that mono_thread_internal_abort () was called
6924 * after the mono_runtime_invoke_checked() already returned, but it doesn't matter
6925 * because we reset the abort here.
6928 mono_loader_lock ();
6930 if (tls->abort_requested)
6931 mono_thread_internal_reset_abort (tls->thread);
6933 tls->invoke = tls->invoke->last_invoke;
6934 tls->abort_requested = FALSE;
6936 mono_loader_unlock ();
6945 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6947 MonoThread *thread = (MonoThread *)value;
6948 DebuggerTlsData *tls;
6951 mono_loader_lock ();
6952 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
6954 res = tls->really_suspended;
6955 mono_loader_unlock ();
6961 get_source_files_for_type (MonoClass *klass)
6963 gpointer iter = NULL;
6965 MonoDebugSourceInfo *sinfo;
6969 files = g_ptr_array_new ();
6971 while ((method = mono_class_get_methods (klass, &iter))) {
6972 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6973 GPtrArray *source_file_list;
6976 mono_debug_get_seq_points (minfo, NULL, &source_file_list, NULL, NULL, NULL);
6977 for (j = 0; j < source_file_list->len; ++j) {
6978 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, j);
6979 for (i = 0; i < files->len; ++i)
6980 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6982 if (i == files->len)
6983 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6985 g_ptr_array_free (source_file_list, TRUE);
6993 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6996 case CMD_VM_VERSION: {
6997 char *build_info, *version;
6999 build_info = mono_get_runtime_build_info ();
7000 version = g_strdup_printf ("mono %s", build_info);
7002 buffer_add_string (buf, version); /* vm version */
7003 buffer_add_int (buf, MAJOR_VERSION);
7004 buffer_add_int (buf, MINOR_VERSION);
7005 g_free (build_info);
7009 case CMD_VM_SET_PROTOCOL_VERSION: {
7010 major_version = decode_int (p, &p, end);
7011 minor_version = decode_int (p, &p, end);
7012 protocol_version_set = TRUE;
7013 DEBUG_PRINTF (1, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version);
7016 case CMD_VM_ALL_THREADS: {
7018 mono_loader_lock ();
7019 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
7020 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
7021 mono_loader_unlock ();
7024 case CMD_VM_SUSPEND:
7026 wait_for_suspend ();
7029 if (suspend_count == 0)
7030 return ERR_NOT_SUSPENDED;
7032 clear_suspended_objs ();
7034 case CMD_VM_DISPOSE:
7035 /* Clear all event requests */
7036 mono_loader_lock ();
7037 while (event_requests->len > 0) {
7038 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
7040 clear_event_request (req->id, req->event_kind);
7042 mono_loader_unlock ();
7044 while (suspend_count > 0)
7046 disconnected = TRUE;
7047 vm_start_event_sent = FALSE;
7050 MonoInternalThread *thread;
7051 DebuggerTlsData *tls;
7052 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7053 MonoClass *env_class;
7055 MonoMethod *exit_method = NULL;
7059 exit_code = decode_int (p, &p, end);
7061 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
7063 /* Have to send a reply before exiting */
7064 send_reply_packet (id, 0, buf);
7066 /* Clear all event requests */
7067 mono_loader_lock ();
7068 while (event_requests->len > 0) {
7069 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
7071 clear_event_request (req->id, req->event_kind);
7073 mono_loader_unlock ();
7076 * The JDWP documentation says that the shutdown is not orderly. It doesn't
7077 * specify whenever a VM_DEATH event is sent. We currently do an orderly
7078 * shutdown by hijacking a thread to execute Environment.Exit (). This is
7079 * better than doing the shutdown ourselves, since it avoids various races.
7083 wait_for_suspend ();
7085 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7086 env_class = mono_class_try_load_from_name (mono_defaults.corlib, "System", "Environment");
7088 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
7091 mono_loader_lock ();
7092 thread = (MonoInternalThread *)mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
7093 mono_loader_unlock ();
7095 if (thread && exit_method) {
7096 mono_loader_lock ();
7097 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
7098 mono_loader_unlock ();
7100 args = g_new0 (gpointer, 1);
7101 args [0] = g_malloc (sizeof (int));
7102 *(int*)(args [0]) = exit_code;
7104 tls->pending_invoke = g_new0 (InvokeData, 1);
7105 tls->pending_invoke->method = exit_method;
7106 tls->pending_invoke->args = args;
7107 tls->pending_invoke->nmethods = 1;
7109 while (suspend_count > 0)
7113 * No thread found, do it ourselves.
7114 * FIXME: This can race with normal shutdown etc.
7116 while (suspend_count > 0)
7119 if (!mono_runtime_try_shutdown ())
7122 mono_environment_exitcode_set (exit_code);
7124 /* Suspend all managed threads since the runtime is going away */
7125 DEBUG_PRINTF (1, "Suspending all threads...\n");
7126 mono_thread_suspend_all_other_threads ();
7127 DEBUG_PRINTF (1, "Shutting down the runtime...\n");
7128 mono_runtime_quit ();
7129 transport_close2 ();
7130 DEBUG_PRINTF (1, "Exiting...\n");
7136 case CMD_VM_INVOKE_METHOD:
7137 case CMD_VM_INVOKE_METHODS: {
7138 int objid = decode_objid (p, &p, end);
7140 DebuggerTlsData *tls;
7141 int i, count, flags, nmethods;
7144 err = get_object (objid, (MonoObject**)&thread);
7145 if (err != ERR_NONE)
7148 flags = decode_int (p, &p, end);
7150 if (command == CMD_VM_INVOKE_METHODS)
7151 nmethods = decode_int (p, &p, end);
7155 // Wait for suspending if it already started
7157 wait_for_suspend ();
7158 if (!is_suspended ())
7159 return ERR_NOT_SUSPENDED;
7161 mono_loader_lock ();
7162 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7163 mono_loader_unlock ();
7166 if (!tls->really_suspended)
7167 /* The thread is still running native code, can't do invokes */
7168 return ERR_NOT_SUSPENDED;
7171 * Store the invoke data into tls, the thread will execute it after it is
7174 if (tls->pending_invoke)
7175 return ERR_NOT_SUSPENDED;
7176 tls->pending_invoke = g_new0 (InvokeData, 1);
7177 tls->pending_invoke->id = id;
7178 tls->pending_invoke->flags = flags;
7179 tls->pending_invoke->p = (guint8 *)g_malloc (end - p);
7180 memcpy (tls->pending_invoke->p, p, end - p);
7181 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
7182 tls->pending_invoke->suspend_count = suspend_count;
7183 tls->pending_invoke->nmethods = nmethods;
7185 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
7186 resume_thread (THREAD_TO_INTERNAL (thread));
7189 count = suspend_count;
7190 for (i = 0; i < count; ++i)
7195 case CMD_VM_ABORT_INVOKE: {
7196 int objid = decode_objid (p, &p, end);
7198 DebuggerTlsData *tls;
7202 err = get_object (objid, (MonoObject**)&thread);
7203 if (err != ERR_NONE)
7206 invoke_id = decode_int (p, &p, end);
7208 mono_loader_lock ();
7209 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7212 if (tls->abort_requested) {
7213 DEBUG_PRINTF (1, "Abort already requested.\n");
7214 mono_loader_unlock ();
7219 * Check whether we're still inside the mono_runtime_invoke_checked() and that it's
7220 * actually the correct invocation.
7222 * Careful, we do not stop the thread that's doing the invocation, so we can't
7223 * inspect its stack. However, invoke_method() also acquires the loader lock
7224 * when it's done, so we're safe here.
7228 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
7229 mono_loader_unlock ();
7230 return ERR_NO_INVOCATION;
7233 tls->abort_requested = TRUE;
7235 mono_thread_internal_abort (THREAD_TO_INTERNAL (thread));
7236 mono_loader_unlock ();
7240 case CMD_VM_SET_KEEPALIVE: {
7241 int timeout = decode_int (p, &p, end);
7242 agent_config.keepalive = timeout;
7244 #ifndef DISABLE_SOCKET_TRANSPORT
7251 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
7252 GHashTableIter iter, kiter;
7257 char *fname, *basename;
7258 gboolean ignore_case;
7259 GSList *class_list, *l;
7260 GPtrArray *res_classes, *res_domains;
7262 fname = decode_string (p, &p, end);
7263 ignore_case = decode_byte (p, &p, end);
7265 basename = dbg_path_get_basename (fname);
7267 res_classes = g_ptr_array_new ();
7268 res_domains = g_ptr_array_new ();
7270 mono_loader_lock ();
7271 g_hash_table_iter_init (&iter, domains);
7272 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7273 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
7275 /* Update 'source_file_to_class' cache */
7276 g_hash_table_iter_init (&kiter, info->loaded_classes);
7277 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
7278 if (!g_hash_table_lookup (info->source_files, klass)) {
7279 files = get_source_files_for_type (klass);
7280 g_hash_table_insert (info->source_files, klass, files);
7282 for (i = 0; i < files->len; ++i) {
7283 char *s = (char *)g_ptr_array_index (files, i);
7284 char *s2 = dbg_path_get_basename (s);
7287 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, s2);
7289 class_list = g_slist_prepend (class_list, klass);
7290 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
7292 class_list = g_slist_prepend (class_list, klass);
7293 g_hash_table_insert (info->source_file_to_class, s2, class_list);
7296 /* The _ignorecase hash contains the lowercase path */
7297 s3 = strdup_tolower (s2);
7298 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
7300 class_list = g_slist_prepend (class_list, klass);
7301 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
7303 class_list = g_slist_prepend (class_list, klass);
7304 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
7316 s = strdup_tolower (basename);
7317 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
7320 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, basename);
7323 for (l = class_list; l; l = l->next) {
7324 klass = (MonoClass *)l->data;
7326 g_ptr_array_add (res_classes, klass);
7327 g_ptr_array_add (res_domains, domain);
7330 mono_loader_unlock ();
7335 buffer_add_int (buf, res_classes->len);
7336 for (i = 0; i < res_classes->len; ++i)
7337 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7338 g_ptr_array_free (res_classes, TRUE);
7339 g_ptr_array_free (res_domains, TRUE);
7342 case CMD_VM_GET_TYPES: {
7343 GHashTableIter iter;
7347 gboolean ignore_case;
7348 GPtrArray *res_classes, *res_domains;
7349 MonoTypeNameParse info;
7351 name = decode_string (p, &p, end);
7352 ignore_case = decode_byte (p, &p, end);
7354 if (!mono_reflection_parse_type (name, &info)) {
7356 mono_reflection_free_type_info (&info);
7357 return ERR_INVALID_ARGUMENT;
7360 res_classes = g_ptr_array_new ();
7361 res_domains = g_ptr_array_new ();
7363 mono_loader_lock ();
7364 g_hash_table_iter_init (&iter, domains);
7365 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7367 gboolean type_resolve;
7371 mono_domain_assemblies_lock (domain);
7372 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7373 ass = (MonoAssembly *)tmp->data;
7377 type_resolve = TRUE;
7378 /* FIXME really okay to call while holding locks? */
7379 t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignore_case, &type_resolve, &error);
7380 mono_error_cleanup (&error);
7382 g_ptr_array_add (res_classes, mono_type_get_class (t));
7383 g_ptr_array_add (res_domains, domain);
7387 mono_domain_assemblies_unlock (domain);
7389 mono_loader_unlock ();
7392 mono_reflection_free_type_info (&info);
7394 buffer_add_int (buf, res_classes->len);
7395 for (i = 0; i < res_classes->len; ++i)
7396 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7397 g_ptr_array_free (res_classes, TRUE);
7398 g_ptr_array_free (res_domains, TRUE);
7401 case CMD_VM_START_BUFFERING:
7402 case CMD_VM_STOP_BUFFERING:
7403 /* Handled in the main loop */
7406 return ERR_NOT_IMPLEMENTED;
7413 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7419 case CMD_EVENT_REQUEST_SET: {
7421 int i, event_kind, suspend_policy, nmodifiers;
7425 MonoThread *step_thread;
7426 int step_thread_id = 0;
7427 StepDepth depth = STEP_DEPTH_INTO;
7428 StepSize size = STEP_SIZE_MIN;
7429 StepFilter filter = STEP_FILTER_NONE;
7433 event_kind = decode_byte (p, &p, end);
7434 suspend_policy = decode_byte (p, &p, end);
7435 nmodifiers = decode_byte (p, &p, end);
7437 req = (EventRequest *)g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7438 req->id = InterlockedIncrement (&event_request_id);
7439 req->event_kind = event_kind;
7440 req->suspend_policy = suspend_policy;
7441 req->nmodifiers = nmodifiers;
7444 for (i = 0; i < nmodifiers; ++i) {
7445 mod = (ModifierKind)decode_byte (p, &p, end);
7447 req->modifiers [i].kind = mod;
7448 if (mod == MOD_KIND_COUNT) {
7449 req->modifiers [i].data.count = decode_int (p, &p, end);
7450 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7451 method = decode_methodid (p, &p, end, &domain, &err);
7452 if (err != ERR_NONE)
7454 location = decode_long (p, &p, end);
7455 } else if (mod == MOD_KIND_STEP) {
7456 step_thread_id = decode_id (p, &p, end);
7457 size = (StepSize)decode_int (p, &p, end);
7458 depth = (StepDepth)decode_int (p, &p, end);
7459 if (CHECK_PROTOCOL_VERSION (2, 16))
7460 filter = (StepFilter)decode_int (p, &p, end);
7461 req->modifiers [i].data.filter = filter;
7462 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7463 /* Treat STEP_THOUGH the same as HIDDEN */
7464 req->modifiers [i].data.filter = (StepFilter)(req->modifiers [i].data.filter | STEP_FILTER_DEBUGGER_STEP_THROUGH);
7465 } else if (mod == MOD_KIND_THREAD_ONLY) {
7466 int id = decode_id (p, &p, end);
7468 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7469 if (err != ERR_NONE) {
7473 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7474 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7476 if (err != ERR_NONE)
7478 req->modifiers [i].caught = decode_byte (p, &p, end);
7479 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7480 if (CHECK_PROTOCOL_VERSION (2, 25))
7481 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7483 req->modifiers [i].subclasses = TRUE;
7484 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" : "");
7486 req->modifiers [i].data.exc_class = exc_class;
7488 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
7490 return ERR_INVALID_ARGUMENT;
7493 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7494 int n = decode_int (p, &p, end);
7497 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
7498 for (j = 0; j < n; ++j) {
7499 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7500 if (err != ERR_NONE) {
7501 g_free (req->modifiers [i].data.assemblies);
7505 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7506 int n = decode_int (p, &p, end);
7509 modifier = &req->modifiers [i];
7510 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7511 for (j = 0; j < n; ++j) {
7512 char *s = decode_string (p, &p, end);
7516 s2 = strdup_tolower (s);
7517 g_hash_table_insert (modifier->data.source_files, s2, s2);
7521 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7522 int n = decode_int (p, &p, end);
7525 modifier = &req->modifiers [i];
7526 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7527 for (j = 0; j < n; ++j) {
7528 char *s = decode_string (p, &p, end);
7531 g_hash_table_insert (modifier->data.type_names, s, s);
7535 return ERR_NOT_IMPLEMENTED;
7539 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7542 req->info = set_breakpoint (method, location, req, &error);
7543 if (!mono_error_ok (&error)) {
7545 DEBUG_PRINTF (1, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error));
7546 mono_error_cleanup (&error);
7547 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7549 } else if (req->event_kind == EVENT_KIND_STEP) {
7550 g_assert (step_thread_id);
7552 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7553 if (err != ERR_NONE) {
7558 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, filter, req);
7559 if (err != ERR_NONE) {
7563 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7564 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7565 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7566 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7567 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7568 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7570 if (req->nmodifiers) {
7572 return ERR_NOT_IMPLEMENTED;
7576 mono_loader_lock ();
7577 g_ptr_array_add (event_requests, req);
7579 if (agent_config.defer) {
7580 /* Transmit cached data to the client on receipt of the event request */
7581 switch (req->event_kind) {
7582 case EVENT_KIND_APPDOMAIN_CREATE:
7583 /* Emit load events for currently loaded domains */
7584 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7586 case EVENT_KIND_ASSEMBLY_LOAD:
7587 /* Emit load events for currently loaded assemblies */
7588 mono_assembly_foreach (emit_assembly_load, NULL);
7590 case EVENT_KIND_THREAD_START:
7591 /* Emit start events for currently started threads */
7592 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7594 case EVENT_KIND_TYPE_LOAD:
7595 /* Emit type load events for currently loaded types */
7596 mono_domain_foreach (send_types_for_domain, NULL);
7602 mono_loader_unlock ();
7604 buffer_add_int (buf, req->id);
7607 case CMD_EVENT_REQUEST_CLEAR: {
7608 int etype = decode_byte (p, &p, end);
7609 int req_id = decode_int (p, &p, end);
7611 // FIXME: Make a faster mapping from req_id to request
7612 mono_loader_lock ();
7613 clear_event_request (req_id, etype);
7614 mono_loader_unlock ();
7617 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7620 mono_loader_lock ();
7622 while (i < event_requests->len) {
7623 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
7625 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7626 clear_breakpoint ((MonoBreakpoint *)req->info);
7628 g_ptr_array_remove_index_fast (event_requests, i);
7634 mono_loader_unlock ();
7638 return ERR_NOT_IMPLEMENTED;
7645 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7651 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7652 buffer_add_domainid (buf, mono_get_root_domain ());
7655 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7656 domain = decode_domainid (p, &p, end, NULL, &err);
7657 if (err != ERR_NONE)
7659 buffer_add_string (buf, domain->friendly_name);
7662 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7667 domain = decode_domainid (p, &p, end, NULL, &err);
7668 if (err != ERR_NONE)
7670 mono_loader_lock ();
7672 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7675 buffer_add_int (buf, count);
7676 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7677 ass = (MonoAssembly *)tmp->data;
7678 buffer_add_assemblyid (buf, domain, ass);
7680 mono_loader_unlock ();
7683 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7684 domain = decode_domainid (p, &p, end, NULL, &err);
7685 if (err != ERR_NONE)
7688 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7691 case CMD_APPDOMAIN_GET_CORLIB: {
7692 domain = decode_domainid (p, &p, end, NULL, &err);
7693 if (err != ERR_NONE)
7696 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7699 case CMD_APPDOMAIN_CREATE_STRING: {
7703 domain = decode_domainid (p, &p, end, NULL, &err);
7704 if (err != ERR_NONE)
7706 s = decode_string (p, &p, end);
7708 o = mono_string_new (domain, s);
7709 buffer_add_objid (buf, (MonoObject*)o);
7712 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7715 MonoDomain *domain2;
7718 domain = decode_domainid (p, &p, end, NULL, &err);
7719 if (err != ERR_NONE)
7721 klass = decode_typeid (p, &p, end, &domain2, &err);
7722 if (err != ERR_NONE)
7726 g_assert (domain == domain2);
7728 o = mono_object_new_checked (domain, klass, &error);
7729 mono_error_assert_ok (&error);
7731 err = decode_value (&klass->byval_arg, domain, (guint8 *)mono_object_unbox (o), p, &p, end);
7732 if (err != ERR_NONE)
7735 buffer_add_objid (buf, o);
7739 return ERR_NOT_IMPLEMENTED;
7746 get_assembly_object_command (MonoDomain *domain, MonoAssembly *ass, Buffer *buf, MonoError *error)
7748 HANDLE_FUNCTION_ENTER();
7749 ErrorCode err = ERR_NONE;
7750 mono_error_init (error);
7751 MonoReflectionAssemblyHandle o = mono_assembly_get_object_handle (domain, ass, error);
7752 if (MONO_HANDLE_IS_NULL (o)) {
7753 err = ERR_INVALID_OBJECT;
7756 buffer_add_objid (buf, MONO_HANDLE_RAW (MONO_HANDLE_CAST (MonoObject, o)));
7758 HANDLE_FUNCTION_RETURN_VAL (err);
7763 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7769 ass = decode_assemblyid (p, &p, end, &domain, &err);
7770 if (err != ERR_NONE)
7774 case CMD_ASSEMBLY_GET_LOCATION: {
7775 buffer_add_string (buf, mono_image_get_filename (ass->image));
7778 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7782 if (ass->image->dynamic) {
7783 buffer_add_id (buf, 0);
7785 token = mono_image_get_entry_point (ass->image);
7787 buffer_add_id (buf, 0);
7790 m = mono_get_method_checked (ass->image, token, NULL, NULL, &error);
7792 mono_error_cleanup (&error); /* FIXME don't swallow the error */
7793 buffer_add_methodid (buf, domain, m);
7798 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7799 buffer_add_moduleid (buf, domain, ass->image);
7802 case CMD_ASSEMBLY_GET_OBJECT: {
7804 err = get_assembly_object_command (domain, ass, buf, &error);
7805 mono_error_cleanup (&error);
7808 case CMD_ASSEMBLY_GET_TYPE: {
7810 char *s = decode_string (p, &p, end);
7811 gboolean ignorecase = decode_byte (p, &p, end);
7812 MonoTypeNameParse info;
7814 gboolean type_resolve, res;
7815 MonoDomain *d = mono_domain_get ();
7817 /* This is needed to be able to find referenced assemblies */
7818 res = mono_domain_set (domain, FALSE);
7821 if (!mono_reflection_parse_type (s, &info)) {
7824 if (info.assembly.name)
7826 t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignorecase, &type_resolve, &error);
7827 if (!is_ok (&error)) {
7828 mono_error_cleanup (&error); /* FIXME don't swallow the error */
7829 mono_reflection_free_type_info (&info);
7831 return ERR_INVALID_ARGUMENT;
7834 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
7835 mono_reflection_free_type_info (&info);
7838 mono_domain_set (d, TRUE);
7842 case CMD_ASSEMBLY_GET_NAME: {
7844 MonoAssembly *mass = ass;
7846 name = g_strdup_printf (
7847 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7849 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7850 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7851 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7852 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7854 buffer_add_string (buf, name);
7859 return ERR_NOT_IMPLEMENTED;
7866 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7872 case CMD_MODULE_GET_INFO: {
7873 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7876 basename = g_path_get_basename (image->name);
7877 buffer_add_string (buf, basename); // name
7878 buffer_add_string (buf, image->module_name); // scopename
7879 buffer_add_string (buf, image->name); // fqname
7880 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7881 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7886 return ERR_NOT_IMPLEMENTED;
7893 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7899 case CMD_FIELD_GET_INFO: {
7900 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
7902 buffer_add_string (buf, f->name);
7903 buffer_add_typeid (buf, domain, f->parent);
7904 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7905 buffer_add_int (buf, f->type->attrs);
7909 return ERR_NOT_IMPLEMENTED;
7916 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7918 if (val && val->vtable->klass == mono_defaults.runtimetype_class) {
7919 /* Special case these so the client doesn't have to handle Type objects */
7921 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7922 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7923 } else if (MONO_TYPE_IS_REFERENCE (t))
7924 buffer_add_value (buf, t, &val, domain);
7926 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7930 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7936 buffer_add_int (buf, 0);
7940 for (i = 0; i < cinfo->num_attrs; ++i) {
7941 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7944 buffer_add_int (buf, nattrs);
7946 for (i = 0; i < cinfo->num_attrs; ++i) {
7947 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7948 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7949 MonoArray *typed_args, *named_args;
7951 CattrNamedArg *arginfo = NULL;
7954 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
7955 if (!mono_error_ok (&error)) {
7956 DEBUG_PRINTF (2, "[dbg] mono_reflection_create_custom_attr_data_args () failed with: '%s'\n", mono_error_get_message (&error));
7957 mono_error_cleanup (&error);
7958 return ERR_LOADER_ERROR;
7961 buffer_add_methodid (buf, domain, attr->ctor);
7965 buffer_add_int (buf, mono_array_length (typed_args));
7966 for (j = 0; j < mono_array_length (typed_args); ++j) {
7967 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7969 t = mono_method_signature (attr->ctor)->params [j];
7971 buffer_add_cattr_arg (buf, t, domain, val);
7974 buffer_add_int (buf, 0);
7979 buffer_add_int (buf, mono_array_length (named_args));
7981 for (j = 0; j < mono_array_length (named_args); ++j) {
7982 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7984 if (arginfo [j].prop) {
7985 buffer_add_byte (buf, 0x54);
7986 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7987 } else if (arginfo [j].field) {
7988 buffer_add_byte (buf, 0x53);
7989 buffer_add_fieldid (buf, domain, arginfo [j].field);
7991 g_assert_not_reached ();
7994 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7997 buffer_add_int (buf, 0);
8006 /* FIXME: Code duplication with icall.c */
8008 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
8013 mono_class_setup_interfaces (klass, error);
8014 if (!mono_error_ok (error))
8017 for (i = 0; i < klass->interface_count; i++) {
8018 ic = klass->interfaces [i];
8019 g_hash_table_insert (ifaces, ic, ic);
8021 collect_interfaces (ic, ifaces, error);
8022 if (!mono_error_ok (error))
8028 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8040 case CMD_TYPE_GET_INFO: {
8041 buffer_add_string (buf, klass->name_space);
8042 buffer_add_string (buf, klass->name);
8044 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
8045 buffer_add_string (buf, name);
8047 buffer_add_assemblyid (buf, domain, klass->image->assembly);
8048 buffer_add_moduleid (buf, domain, klass->image);
8049 buffer_add_typeid (buf, domain, klass->parent);
8050 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
8051 buffer_add_typeid (buf, domain, klass->element_class);
8053 buffer_add_id (buf, 0);
8054 buffer_add_int (buf, klass->type_token);
8055 buffer_add_byte (buf, klass->rank);
8056 buffer_add_int (buf, mono_class_get_flags (klass));
8058 type = &klass->byval_arg;
8059 // FIXME: Can't decide whenever a class represents a byref type
8062 if (type->type == MONO_TYPE_PTR)
8064 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
8066 if (type->type == MONO_TYPE_VALUETYPE)
8068 if (klass->enumtype)
8070 if (mono_class_is_gtd (klass))
8072 if (mono_class_is_gtd (klass) || mono_class_is_ginst (klass))
8074 buffer_add_byte (buf, b);
8077 while ((nested = mono_class_get_nested_types (klass, &iter)))
8079 buffer_add_int (buf, nnested);
8081 while ((nested = mono_class_get_nested_types (klass, &iter)))
8082 buffer_add_typeid (buf, domain, nested);
8083 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8084 if (mono_class_is_gtd (klass))
8085 buffer_add_typeid (buf, domain, klass);
8086 else if (mono_class_is_ginst (klass))
8087 buffer_add_typeid (buf, domain, mono_class_get_generic_class (klass)->container_class);
8089 buffer_add_id (buf, 0);
8091 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8094 if (mono_class_is_ginst (klass)) {
8095 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
8097 count = inst->type_argc;
8098 buffer_add_int (buf, count);
8099 for (i = 0; i < count; i++)
8100 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8101 } else if (mono_class_is_gtd (klass)) {
8102 MonoGenericContainer *container = mono_class_get_generic_container (klass);
8105 count = container->type_argc;
8106 buffer_add_int (buf, count);
8107 for (i = 0; i < count; i++) {
8108 pklass = mono_class_from_generic_parameter_internal (mono_generic_container_get_param (container, i));
8109 buffer_add_typeid (buf, domain, pklass);
8112 buffer_add_int (buf, 0);
8117 case CMD_TYPE_GET_METHODS: {
8120 gpointer iter = NULL;
8123 mono_class_setup_methods (klass);
8125 nmethods = mono_class_num_methods (klass);
8127 buffer_add_int (buf, nmethods);
8129 while ((m = mono_class_get_methods (klass, &iter))) {
8130 buffer_add_methodid (buf, domain, m);
8133 g_assert (i == nmethods);
8136 case CMD_TYPE_GET_FIELDS: {
8139 gpointer iter = NULL;
8142 nfields = mono_class_num_fields (klass);
8144 buffer_add_int (buf, nfields);
8146 while ((f = mono_class_get_fields (klass, &iter))) {
8147 buffer_add_fieldid (buf, domain, f);
8148 buffer_add_string (buf, f->name);
8149 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
8150 buffer_add_int (buf, f->type->attrs);
8153 g_assert (i == nfields);
8156 case CMD_TYPE_GET_PROPERTIES: {
8159 gpointer iter = NULL;
8162 nprops = mono_class_num_properties (klass);
8164 buffer_add_int (buf, nprops);
8166 while ((p = mono_class_get_properties (klass, &iter))) {
8167 buffer_add_propertyid (buf, domain, p);
8168 buffer_add_string (buf, p->name);
8169 buffer_add_methodid (buf, domain, p->get);
8170 buffer_add_methodid (buf, domain, p->set);
8171 buffer_add_int (buf, p->attrs);
8174 g_assert (i == nprops);
8177 case CMD_TYPE_GET_CATTRS: {
8178 MonoClass *attr_klass;
8179 MonoCustomAttrInfo *cinfo;
8181 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8182 /* attr_klass can be NULL */
8183 if (err != ERR_NONE)
8186 cinfo = mono_custom_attrs_from_class_checked (klass, &error);
8187 if (!is_ok (&error)) {
8188 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8189 return ERR_LOADER_ERROR;
8192 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8193 if (err != ERR_NONE)
8197 case CMD_TYPE_GET_FIELD_CATTRS: {
8198 MonoClass *attr_klass;
8199 MonoCustomAttrInfo *cinfo;
8200 MonoClassField *field;
8202 field = decode_fieldid (p, &p, end, NULL, &err);
8203 if (err != ERR_NONE)
8205 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8206 if (err != ERR_NONE)
8209 cinfo = mono_custom_attrs_from_field_checked (klass, field, &error);
8210 if (!is_ok (&error)) {
8211 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8212 return ERR_LOADER_ERROR;
8215 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8216 if (err != ERR_NONE)
8220 case CMD_TYPE_GET_PROPERTY_CATTRS: {
8221 MonoClass *attr_klass;
8222 MonoCustomAttrInfo *cinfo;
8225 prop = decode_propertyid (p, &p, end, NULL, &err);
8226 if (err != ERR_NONE)
8228 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8229 if (err != ERR_NONE)
8232 cinfo = mono_custom_attrs_from_property_checked (klass, prop, &error);
8233 if (!is_ok (&error)) {
8234 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8235 return ERR_LOADER_ERROR;
8238 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8239 if (err != ERR_NONE)
8243 case CMD_TYPE_GET_VALUES:
8244 case CMD_TYPE_GET_VALUES_2: {
8251 MonoThread *thread_obj;
8252 MonoInternalThread *thread = NULL;
8253 guint32 special_static_type;
8255 if (command == CMD_TYPE_GET_VALUES_2) {
8256 int objid = decode_objid (p, &p, end);
8259 err = get_object (objid, (MonoObject**)&thread_obj);
8260 if (err != ERR_NONE)
8263 thread = THREAD_TO_INTERNAL (thread_obj);
8266 len = decode_int (p, &p, end);
8267 for (i = 0; i < len; ++i) {
8268 f = decode_fieldid (p, &p, end, NULL, &err);
8269 if (err != ERR_NONE)
8272 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8273 return ERR_INVALID_FIELDID;
8274 special_static_type = mono_class_field_get_special_static_type (f);
8275 if (special_static_type != SPECIAL_STATIC_NONE) {
8276 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
8277 return ERR_INVALID_FIELDID;
8280 /* Check that the field belongs to the object */
8282 for (k = klass; k; k = k->parent) {
8283 if (k == f->parent) {
8289 return ERR_INVALID_FIELDID;
8291 vtable = mono_class_vtable (domain, f->parent);
8292 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8293 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val, &error);
8294 if (!is_ok (&error))
8295 return ERR_INVALID_FIELDID;
8296 buffer_add_value (buf, f->type, val, domain);
8301 case CMD_TYPE_SET_VALUES: {
8309 len = decode_int (p, &p, end);
8310 for (i = 0; i < len; ++i) {
8311 f = decode_fieldid (p, &p, end, NULL, &err);
8312 if (err != ERR_NONE)
8315 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8316 return ERR_INVALID_FIELDID;
8317 if (mono_class_field_is_special_static (f))
8318 return ERR_INVALID_FIELDID;
8320 /* Check that the field belongs to the object */
8322 for (k = klass; k; k = k->parent) {
8323 if (k == f->parent) {
8329 return ERR_INVALID_FIELDID;
8331 // FIXME: Check for literal/const
8333 vtable = mono_class_vtable (domain, f->parent);
8334 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8335 err = decode_value (f->type, domain, val, p, &p, end);
8336 if (err != ERR_NONE) {
8340 if (MONO_TYPE_IS_REFERENCE (f->type))
8341 mono_field_static_set_value (vtable, f, *(gpointer*)val);
8343 mono_field_static_set_value (vtable, f, val);
8348 case CMD_TYPE_GET_OBJECT: {
8349 MonoObject *o = (MonoObject*)mono_type_get_object_checked (domain, &klass->byval_arg, &error);
8350 if (!mono_error_ok (&error)) {
8351 mono_error_cleanup (&error);
8352 return ERR_INVALID_OBJECT;
8354 buffer_add_objid (buf, o);
8357 case CMD_TYPE_GET_SOURCE_FILES:
8358 case CMD_TYPE_GET_SOURCE_FILES_2: {
8359 char *source_file, *base;
8363 files = get_source_files_for_type (klass);
8365 buffer_add_int (buf, files->len);
8366 for (i = 0; i < files->len; ++i) {
8367 source_file = (char *)g_ptr_array_index (files, i);
8368 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8369 buffer_add_string (buf, source_file);
8371 base = dbg_path_get_basename (source_file);
8372 buffer_add_string (buf, base);
8375 g_free (source_file);
8377 g_ptr_array_free (files, TRUE);
8380 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8381 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8383 if (err != ERR_NONE)
8385 if (mono_class_is_assignable_from (klass, oklass))
8386 buffer_add_byte (buf, 1);
8388 buffer_add_byte (buf, 0);
8391 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8392 char *name = decode_string (p, &p, end);
8393 int i, flags = decode_int (p, &p, end);
8397 mono_error_init (&error);
8398 array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &error);
8399 if (!is_ok (&error)) {
8400 mono_error_cleanup (&error);
8401 return ERR_LOADER_ERROR;
8403 buffer_add_int (buf, array->len);
8404 for (i = 0; i < array->len; ++i) {
8405 MonoMethod *method = (MonoMethod *)g_ptr_array_index (array, i);
8406 buffer_add_methodid (buf, domain, method);
8409 g_ptr_array_free (array, TRUE);
8413 case CMD_TYPE_GET_INTERFACES: {
8415 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8416 MonoClass *tclass, *iface;
8417 GHashTableIter iter;
8421 for (parent = tclass; parent; parent = parent->parent) {
8422 mono_class_setup_interfaces (parent, &error);
8423 if (!mono_error_ok (&error))
8424 return ERR_LOADER_ERROR;
8425 collect_interfaces (parent, iface_hash, &error);
8426 if (!mono_error_ok (&error))
8427 return ERR_LOADER_ERROR;
8430 buffer_add_int (buf, g_hash_table_size (iface_hash));
8432 g_hash_table_iter_init (&iter, iface_hash);
8433 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8434 buffer_add_typeid (buf, domain, iface);
8435 g_hash_table_destroy (iface_hash);
8438 case CMD_TYPE_GET_INTERFACE_MAP: {
8439 int tindex, ioffset;
8440 gboolean variance_used;
8442 int len, nmethods, i;
8446 len = decode_int (p, &p, end);
8447 mono_class_setup_vtable (klass);
8449 for (tindex = 0; tindex < len; ++tindex) {
8450 iclass = decode_typeid (p, &p, end, NULL, &err);
8451 if (err != ERR_NONE)
8454 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8456 return ERR_INVALID_ARGUMENT;
8458 nmethods = mono_class_num_methods (iclass);
8459 buffer_add_int (buf, nmethods);
8462 while ((method = mono_class_get_methods (iclass, &iter))) {
8463 buffer_add_methodid (buf, domain, method);
8465 for (i = 0; i < nmethods; ++i)
8466 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
8470 case CMD_TYPE_IS_INITIALIZED: {
8471 MonoVTable *vtable = mono_class_vtable (domain, klass);
8474 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8476 buffer_add_int (buf, 0);
8479 case CMD_TYPE_CREATE_INSTANCE: {
8483 obj = mono_object_new_checked (domain, klass, &error);
8484 mono_error_assert_ok (&error);
8485 buffer_add_objid (buf, obj);
8489 return ERR_NOT_IMPLEMENTED;
8496 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8499 MonoDomain *old_domain;
8503 klass = decode_typeid (p, &p, end, &domain, &err);
8504 if (err != ERR_NONE)
8507 old_domain = mono_domain_get ();
8509 mono_domain_set (domain, TRUE);
8511 err = type_commands_internal (command, klass, domain, p, end, buf);
8513 mono_domain_set (old_domain, TRUE);
8519 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8521 MonoMethodHeader *header;
8525 case CMD_METHOD_GET_NAME: {
8526 buffer_add_string (buf, method->name);
8529 case CMD_METHOD_GET_DECLARING_TYPE: {
8530 buffer_add_typeid (buf, domain, method->klass);
8533 case CMD_METHOD_GET_DEBUG_INFO: {
8535 MonoDebugMethodInfo *minfo;
8537 int i, j, n_il_offsets;
8539 GPtrArray *source_file_list;
8540 MonoSymSeqPoint *sym_seq_points;
8542 header = mono_method_get_header_checked (method, &error);
8544 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8545 buffer_add_int (buf, 0);
8546 buffer_add_string (buf, "");
8547 buffer_add_int (buf, 0);
8551 minfo = mono_debug_lookup_method (method);
8553 buffer_add_int (buf, header->code_size);
8554 buffer_add_string (buf, "");
8555 buffer_add_int (buf, 0);
8556 mono_metadata_free_mh (header);
8560 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, &source_files, &sym_seq_points, &n_il_offsets);
8561 buffer_add_int (buf, header->code_size);
8562 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8563 buffer_add_int (buf, source_file_list->len);
8564 for (i = 0; i < source_file_list->len; ++i) {
8565 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
8566 buffer_add_string (buf, sinfo->source_file);
8567 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8568 for (j = 0; j < 16; ++j)
8569 buffer_add_byte (buf, sinfo->hash [j]);
8573 buffer_add_string (buf, source_file);
8575 buffer_add_int (buf, n_il_offsets);
8576 DEBUG_PRINTF (10, "Line number table for method %s:\n", mono_method_full_name (method, TRUE));
8577 for (i = 0; i < n_il_offsets; ++i) {
8578 MonoSymSeqPoint *sp = &sym_seq_points [i];
8579 const char *srcfile = "";
8581 if (source_files [i] != -1) {
8582 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, source_files [i]);
8583 srcfile = sinfo->source_file;
8585 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);
8586 buffer_add_int (buf, sp->il_offset);
8587 buffer_add_int (buf, sp->line);
8588 if (CHECK_PROTOCOL_VERSION (2, 13))
8589 buffer_add_int (buf, source_files [i]);
8590 if (CHECK_PROTOCOL_VERSION (2, 19))
8591 buffer_add_int (buf, sp->column);
8592 if (CHECK_PROTOCOL_VERSION (2, 32)) {
8593 buffer_add_int (buf, sp->end_line);
8594 buffer_add_int (buf, sp->end_column);
8597 g_free (source_file);
8598 g_free (source_files);
8599 g_free (sym_seq_points);
8600 g_ptr_array_free (source_file_list, TRUE);
8601 mono_metadata_free_mh (header);
8604 case CMD_METHOD_GET_PARAM_INFO: {
8605 MonoMethodSignature *sig = mono_method_signature (method);
8609 /* FIXME: mono_class_from_mono_type () and byrefs */
8611 /* FIXME: Use a smaller encoding */
8612 buffer_add_int (buf, sig->call_convention);
8613 buffer_add_int (buf, sig->param_count);
8614 buffer_add_int (buf, sig->generic_param_count);
8615 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
8616 for (i = 0; i < sig->param_count; ++i) {
8618 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
8621 /* Emit parameter names */
8622 names = g_new (char *, sig->param_count);
8623 mono_method_get_param_names (method, (const char **) names);
8624 for (i = 0; i < sig->param_count; ++i)
8625 buffer_add_string (buf, names [i]);
8630 case CMD_METHOD_GET_LOCALS_INFO: {
8633 MonoDebugLocalsInfo *locals;
8634 int *locals_map = NULL;
8636 header = mono_method_get_header_checked (method, &error);
8638 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8639 return ERR_INVALID_ARGUMENT;
8642 locals = mono_debug_lookup_locals (method);
8644 if (CHECK_PROTOCOL_VERSION (2, 43)) {
8646 buffer_add_int (buf, 1);
8647 buffer_add_int (buf, 0);
8648 buffer_add_int (buf, header->code_size);
8650 buffer_add_int (buf, header->num_locals);
8652 for (i = 0; i < header->num_locals; ++i) {
8653 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
8656 for (i = 0; i < header->num_locals; ++i) {
8658 sprintf (lname, "V_%d", i);
8659 buffer_add_string (buf, lname);
8662 for (i = 0; i < header->num_locals; ++i) {
8663 buffer_add_int (buf, 0);
8664 buffer_add_int (buf, header->code_size);
8667 if (CHECK_PROTOCOL_VERSION (2, 43)) {
8669 buffer_add_int (buf, locals->num_blocks);
8671 for (i = 0; i < locals->num_blocks; ++i) {
8672 buffer_add_int (buf, locals->code_blocks [i].start_offset - last_start);
8673 buffer_add_int (buf, locals->code_blocks [i].end_offset - locals->code_blocks [i].start_offset);
8674 last_start = locals->code_blocks [i].start_offset;
8678 num_locals = locals->num_locals;
8679 buffer_add_int (buf, num_locals);
8682 for (i = 0; i < num_locals; ++i) {
8683 g_assert (locals->locals [i].index < header->num_locals);
8684 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [locals->locals [i].index]));
8687 for (i = 0; i < num_locals; ++i)
8688 buffer_add_string (buf, locals->locals [i].name);
8690 for (i = 0; i < num_locals; ++i) {
8691 if (locals->locals [i].block) {
8692 buffer_add_int (buf, locals->locals [i].block->start_offset);
8693 buffer_add_int (buf, locals->locals [i].block->end_offset);
8695 buffer_add_int (buf, 0);
8696 buffer_add_int (buf, header->code_size);
8700 mono_metadata_free_mh (header);
8703 mono_debug_free_locals (locals);
8704 g_free (locals_map);
8708 case CMD_METHOD_GET_INFO:
8709 buffer_add_int (buf, method->flags);
8710 buffer_add_int (buf, method->iflags);
8711 buffer_add_int (buf, method->token);
8712 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8714 if (method->is_generic)
8716 if (mono_method_signature (method)->generic_param_count)
8718 buffer_add_byte (buf, attrs);
8719 if (method->is_generic || method->is_inflated) {
8722 if (method->is_generic) {
8725 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8727 result = imethod->declaring;
8728 if (imethod->context.class_inst) {
8729 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8730 /*Generic methods gets the context of the GTD.*/
8731 if (mono_class_get_context (klass)) {
8733 result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), &error);
8734 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8739 buffer_add_methodid (buf, domain, result);
8741 buffer_add_id (buf, 0);
8743 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8744 if (mono_method_signature (method)->generic_param_count) {
8747 if (method->is_inflated) {
8748 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
8750 count = inst->type_argc;
8751 buffer_add_int (buf, count);
8753 for (i = 0; i < count; i++)
8754 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8756 buffer_add_int (buf, 0);
8758 } else if (method->is_generic) {
8759 MonoGenericContainer *container = mono_method_get_generic_container (method);
8761 count = mono_method_signature (method)->generic_param_count;
8762 buffer_add_int (buf, count);
8763 for (i = 0; i < count; i++) {
8764 MonoGenericParam *param = mono_generic_container_get_param (container, i);
8765 MonoClass *pklass = mono_class_from_generic_parameter_internal (param);
8766 buffer_add_typeid (buf, domain, pklass);
8769 buffer_add_int (buf, 0);
8772 buffer_add_int (buf, 0);
8777 case CMD_METHOD_GET_BODY: {
8781 header = mono_method_get_header_checked (method, &error);
8783 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8784 buffer_add_int (buf, 0);
8786 if (CHECK_PROTOCOL_VERSION (2, 18))
8787 buffer_add_int (buf, 0);
8789 buffer_add_int (buf, header->code_size);
8790 for (i = 0; i < header->code_size; ++i)
8791 buffer_add_byte (buf, header->code [i]);
8793 if (CHECK_PROTOCOL_VERSION (2, 18)) {
8794 buffer_add_int (buf, header->num_clauses);
8795 for (i = 0; i < header->num_clauses; ++i) {
8796 MonoExceptionClause *clause = &header->clauses [i];
8798 buffer_add_int (buf, clause->flags);
8799 buffer_add_int (buf, clause->try_offset);
8800 buffer_add_int (buf, clause->try_len);
8801 buffer_add_int (buf, clause->handler_offset);
8802 buffer_add_int (buf, clause->handler_len);
8803 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
8804 buffer_add_typeid (buf, domain, clause->data.catch_class);
8805 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8806 buffer_add_int (buf, clause->data.filter_offset);
8810 mono_metadata_free_mh (header);
8815 case CMD_METHOD_RESOLVE_TOKEN: {
8816 guint32 token = decode_int (p, &p, end);
8819 switch (mono_metadata_token_code (token)) {
8820 case MONO_TOKEN_STRING: {
8825 s = mono_ldstr_checked (domain, method->klass->image, mono_metadata_token_index (token), &error);
8826 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
8828 s2 = mono_string_to_utf8_checked (s, &error);
8829 mono_error_assert_ok (&error);
8831 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8832 buffer_add_string (buf, s2);
8839 MonoClass *handle_class;
8841 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8842 val = mono_method_get_wrapper_data (method, token);
8843 handle_class = (MonoClass *)mono_method_get_wrapper_data (method, token + 1);
8845 if (handle_class == NULL) {
8846 // Can't figure out the token type
8847 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8851 val = mono_ldtoken_checked (method->klass->image, token, &handle_class, NULL, &error);
8853 g_error ("Could not load token due to %s", mono_error_get_message (&error));
8856 if (handle_class == mono_defaults.typehandle_class) {
8857 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8858 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8859 buffer_add_typeid (buf, domain, (MonoClass *) val);
8861 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
8862 } else if (handle_class == mono_defaults.fieldhandle_class) {
8863 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8864 buffer_add_fieldid (buf, domain, (MonoClassField *)val);
8865 } else if (handle_class == mono_defaults.methodhandle_class) {
8866 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8867 buffer_add_methodid (buf, domain, (MonoMethod *)val);
8868 } else if (handle_class == mono_defaults.string_class) {
8871 s = mono_string_to_utf8_checked ((MonoString *)val, &error);
8872 mono_error_assert_ok (&error);
8873 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8874 buffer_add_string (buf, s);
8877 g_assert_not_reached ();
8884 case CMD_METHOD_GET_CATTRS: {
8886 MonoClass *attr_klass;
8887 MonoCustomAttrInfo *cinfo;
8889 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8890 /* attr_klass can be NULL */
8891 if (err != ERR_NONE)
8894 cinfo = mono_custom_attrs_from_method_checked (method, &error);
8895 if (!is_ok (&error)) {
8896 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8897 return ERR_LOADER_ERROR;
8900 err = buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
8901 if (err != ERR_NONE)
8905 case CMD_METHOD_MAKE_GENERIC_METHOD: {
8907 MonoType **type_argv;
8911 MonoGenericInst *ginst;
8912 MonoGenericContext tmp_context;
8913 MonoMethod *inflated;
8915 type_argc = decode_int (p, &p, end);
8916 type_argv = g_new0 (MonoType*, type_argc);
8917 for (i = 0; i < type_argc; ++i) {
8918 klass = decode_typeid (p, &p, end, &d, &err);
8919 if (err != ERR_NONE) {
8925 return ERR_INVALID_ARGUMENT;
8927 type_argv [i] = &klass->byval_arg;
8929 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
8931 tmp_context.class_inst = mono_class_is_ginst (method->klass) ? mono_class_get_generic_class (method->klass)->context.class_inst : NULL;
8932 tmp_context.method_inst = ginst;
8934 inflated = mono_class_inflate_generic_method_checked (method, &tmp_context, &error);
8935 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
8936 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
8937 return ERR_INVALID_ARGUMENT;
8938 buffer_add_methodid (buf, domain, inflated);
8942 return ERR_NOT_IMPLEMENTED;
8949 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8952 MonoDomain *old_domain;
8956 method = decode_methodid (p, &p, end, &domain, &err);
8957 if (err != ERR_NONE)
8960 old_domain = mono_domain_get ();
8962 mono_domain_set (domain, TRUE);
8964 err = method_commands_internal (command, method, domain, p, end, buf);
8966 mono_domain_set (old_domain, TRUE);
8972 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8974 int objid = decode_objid (p, &p, end);
8976 MonoThread *thread_obj;
8977 MonoInternalThread *thread;
8979 err = get_object (objid, (MonoObject**)&thread_obj);
8980 if (err != ERR_NONE)
8983 thread = THREAD_TO_INTERNAL (thread_obj);
8986 case CMD_THREAD_GET_NAME: {
8988 gunichar2 *s = mono_thread_get_name (thread, &name_len);
8991 buffer_add_int (buf, 0);
8996 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
8998 buffer_add_int (buf, len);
8999 buffer_add_data (buf, (guint8*)name, len);
9004 case CMD_THREAD_GET_FRAME_INFO: {
9005 DebuggerTlsData *tls;
9006 int i, start_frame, length;
9008 // Wait for suspending if it already started
9009 // FIXME: Races with suspend_count
9010 while (!is_suspended ()) {
9012 wait_for_suspend ();
9016 wait_for_suspend ();
9017 if (!is_suspended ())
9018 return ERR_NOT_SUSPENDED;
9021 start_frame = decode_int (p, &p, end);
9022 length = decode_int (p, &p, end);
9024 if (start_frame != 0 || length != -1)
9025 return ERR_NOT_IMPLEMENTED;
9027 mono_loader_lock ();
9028 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9029 mono_loader_unlock ();
9032 compute_frame_info (thread, tls);
9034 buffer_add_int (buf, tls->frame_count);
9035 for (i = 0; i < tls->frame_count; ++i) {
9036 buffer_add_int (buf, tls->frames [i]->id);
9037 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
9038 buffer_add_int (buf, tls->frames [i]->il_offset);
9040 * Instead of passing the frame type directly to the client, we associate
9041 * it with the previous frame using a set of flags. This avoids lots of
9042 * conditional code in the client, since a frame whose type isn't
9043 * FRAME_TYPE_MANAGED has no method, location, etc.
9045 buffer_add_byte (buf, tls->frames [i]->flags);
9050 case CMD_THREAD_GET_STATE:
9051 buffer_add_int (buf, thread->state);
9053 case CMD_THREAD_GET_INFO:
9054 buffer_add_byte (buf, thread->threadpool_thread);
9056 case CMD_THREAD_GET_ID:
9057 buffer_add_long (buf, (guint64)(gsize)thread);
9059 case CMD_THREAD_GET_TID:
9060 buffer_add_long (buf, (guint64)thread->tid);
9062 case CMD_THREAD_SET_IP: {
9063 DebuggerTlsData *tls;
9066 MonoSeqPointInfo *seq_points;
9071 method = decode_methodid (p, &p, end, &domain, &err);
9072 if (err != ERR_NONE)
9074 il_offset = decode_long (p, &p, end);
9076 while (!is_suspended ()) {
9078 wait_for_suspend ();
9081 mono_loader_lock ();
9082 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9083 mono_loader_unlock ();
9086 compute_frame_info (thread, tls);
9087 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
9088 return ERR_INVALID_ARGUMENT;
9090 found_sp = mono_find_seq_point (domain, method, il_offset, &seq_points, &sp);
9092 g_assert (seq_points);
9095 return ERR_INVALID_ARGUMENT;
9097 // FIXME: Check that the ip change is safe
9099 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);
9100 MONO_CONTEXT_SET_IP (&tls->restore_state.ctx, (guint8*)tls->frames [0]->ji->code_start + sp.native_offset);
9104 return ERR_NOT_IMPLEMENTED;
9111 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9115 MonoThread *thread_obj;
9116 MonoInternalThread *thread;
9117 int pos, i, len, frame_idx;
9118 DebuggerTlsData *tls;
9120 MonoDebugMethodJitInfo *jit;
9121 MonoMethodSignature *sig;
9123 MonoMethodHeader *header;
9125 objid = decode_objid (p, &p, end);
9126 err = get_object (objid, (MonoObject**)&thread_obj);
9127 if (err != ERR_NONE)
9130 thread = THREAD_TO_INTERNAL (thread_obj);
9132 id = decode_id (p, &p, end);
9134 mono_loader_lock ();
9135 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9136 mono_loader_unlock ();
9139 for (i = 0; i < tls->frame_count; ++i) {
9140 if (tls->frames [i]->id == id)
9143 if (i == tls->frame_count)
9144 return ERR_INVALID_FRAMEID;
9147 frame = tls->frames [frame_idx];
9149 /* This is supported for frames without has_ctx etc. set */
9150 if (command == CMD_STACK_FRAME_GET_DOMAIN) {
9151 if (CHECK_PROTOCOL_VERSION (2, 38))
9152 buffer_add_domainid (buf, frame->domain);
9156 if (!frame->has_ctx)
9157 return ERR_ABSENT_INFORMATION;
9160 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
9161 if (!frame->jit && frame->api_method->is_inflated)
9162 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
9166 /* This could happen for aot images with no jit debug info */
9167 s = mono_method_full_name (frame->api_method, TRUE);
9168 DEBUG_PRINTF (1, "[dbg] No debug information found for '%s'.\n", s);
9170 return ERR_ABSENT_INFORMATION;
9175 sig = mono_method_signature (frame->actual_method);
9177 if (!jit->has_var_info || !mono_get_seq_points (frame->domain, frame->actual_method))
9179 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
9181 return ERR_ABSENT_INFORMATION;
9184 case CMD_STACK_FRAME_GET_VALUES: {
9186 len = decode_int (p, &p, end);
9187 header = mono_method_get_header_checked (frame->actual_method, &error);
9188 mono_error_assert_ok (&error); /* FIXME report error */
9190 for (i = 0; i < len; ++i) {
9191 pos = decode_int (p, &p, end);
9196 DEBUG_PRINTF (4, "[dbg] send arg %d.\n", pos);
9198 g_assert (pos >= 0 && pos < jit->num_params);
9200 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
9202 MonoDebugLocalsInfo *locals;
9204 locals = mono_debug_lookup_locals (frame->method);
9206 g_assert (pos < locals->num_locals);
9207 pos = locals->locals [pos].index;
9208 mono_debug_free_locals (locals);
9210 g_assert (pos >= 0 && pos < jit->num_locals);
9212 DEBUG_PRINTF (4, "[dbg] send local %d.\n", pos);
9214 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
9217 mono_metadata_free_mh (header);
9220 case CMD_STACK_FRAME_GET_THIS: {
9221 if (frame->api_method->klass->valuetype) {
9222 if (!sig->hasthis) {
9223 MonoObject *p = NULL;
9224 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
9226 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9229 if (!sig->hasthis) {
9230 MonoObject *p = NULL;
9231 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
9233 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9238 case CMD_STACK_FRAME_SET_VALUES: {
9242 MonoDebugVarInfo *var;
9244 len = decode_int (p, &p, end);
9245 header = mono_method_get_header_checked (frame->actual_method, &error);
9246 mono_error_assert_ok (&error); /* FIXME report error */
9248 for (i = 0; i < len; ++i) {
9249 pos = decode_int (p, &p, end);
9254 g_assert (pos >= 0 && pos < jit->num_params);
9256 t = sig->params [pos];
9257 var = &jit->params [pos];
9259 MonoDebugLocalsInfo *locals;
9261 locals = mono_debug_lookup_locals (frame->method);
9263 g_assert (pos < locals->num_locals);
9264 pos = locals->locals [pos].index;
9265 mono_debug_free_locals (locals);
9267 g_assert (pos >= 0 && pos < jit->num_locals);
9269 t = header->locals [pos];
9270 var = &jit->locals [pos];
9273 if (MONO_TYPE_IS_REFERENCE (t))
9274 val_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
9276 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9277 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9278 if (err != ERR_NONE)
9281 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9283 mono_metadata_free_mh (header);
9286 case CMD_STACK_FRAME_GET_DOMAIN: {
9287 if (CHECK_PROTOCOL_VERSION (2, 38))
9288 buffer_add_domainid (buf, frame->domain);
9291 case CMD_STACK_FRAME_SET_THIS: {
9294 MonoDebugVarInfo *var;
9296 t = &frame->actual_method->klass->byval_arg;
9297 /* Checked by the sender */
9298 g_assert (MONO_TYPE_ISSTRUCT (t));
9299 var = jit->this_var;
9302 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9303 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9304 if (err != ERR_NONE)
9307 set_var (&frame->actual_method->klass->this_arg, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9311 return ERR_NOT_IMPLEMENTED;
9318 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9321 int objid, index, len, i, esize;
9325 objid = decode_objid (p, &p, end);
9326 err = get_object (objid, (MonoObject**)&arr);
9327 if (err != ERR_NONE)
9331 case CMD_ARRAY_REF_GET_LENGTH:
9332 buffer_add_int (buf, arr->obj.vtable->klass->rank);
9334 buffer_add_int (buf, arr->max_length);
9335 buffer_add_int (buf, 0);
9337 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
9338 buffer_add_int (buf, arr->bounds [i].length);
9339 buffer_add_int (buf, arr->bounds [i].lower_bound);
9343 case CMD_ARRAY_REF_GET_VALUES:
9344 index = decode_int (p, &p, end);
9345 len = decode_int (p, &p, end);
9347 g_assert (index >= 0 && len >= 0);
9348 // Reordered to avoid integer overflow
9349 g_assert (!(index > arr->max_length - len));
9351 esize = mono_array_element_size (arr->obj.vtable->klass);
9352 for (i = index; i < index + len; ++i) {
9353 elem = (gpointer*)((char*)arr->vector + (i * esize));
9354 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
9357 case CMD_ARRAY_REF_SET_VALUES:
9358 index = decode_int (p, &p, end);
9359 len = decode_int (p, &p, end);
9361 g_assert (index >= 0 && len >= 0);
9362 // Reordered to avoid integer overflow
9363 g_assert (!(index > arr->max_length - len));
9365 esize = mono_array_element_size (arr->obj.vtable->klass);
9366 for (i = index; i < index + len; ++i) {
9367 elem = (gpointer*)((char*)arr->vector + (i * esize));
9369 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, (guint8 *)elem, p, &p, end);
9373 return ERR_NOT_IMPLEMENTED;
9380 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9386 int i, index, length;
9388 gboolean use_utf16 = FALSE;
9390 objid = decode_objid (p, &p, end);
9391 err = get_object (objid, (MonoObject**)&str);
9392 if (err != ERR_NONE)
9396 case CMD_STRING_REF_GET_VALUE:
9397 if (CHECK_PROTOCOL_VERSION (2, 41)) {
9398 for (i = 0; i < mono_string_length (str); ++i)
9399 if (mono_string_chars (str)[i] == 0)
9401 buffer_add_byte (buf, use_utf16 ? 1 : 0);
9404 buffer_add_int (buf, mono_string_length (str) * 2);
9405 buffer_add_data (buf, (guint8*)mono_string_chars (str), mono_string_length (str) * 2);
9408 s = mono_string_to_utf8_checked (str, &error);
9409 mono_error_assert_ok (&error);
9410 buffer_add_string (buf, s);
9414 case CMD_STRING_REF_GET_LENGTH:
9415 buffer_add_long (buf, mono_string_length (str));
9417 case CMD_STRING_REF_GET_CHARS:
9418 index = decode_long (p, &p, end);
9419 length = decode_long (p, &p, end);
9420 if (index > mono_string_length (str) - length)
9421 return ERR_INVALID_ARGUMENT;
9422 c = mono_string_chars (str) + index;
9423 for (i = 0; i < length; ++i)
9424 buffer_add_short (buf, c [i]);
9427 return ERR_NOT_IMPLEMENTED;
9434 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9445 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9446 objid = decode_objid (p, &p, end);
9447 err = get_object (objid, &obj);
9448 if (err != ERR_NONE)
9449 buffer_add_int (buf, 1);
9451 buffer_add_int (buf, 0);
9455 objid = decode_objid (p, &p, end);
9456 err = get_object (objid, &obj);
9457 if (err != ERR_NONE)
9460 MonoClass *obj_type;
9461 gboolean remote_obj = FALSE;
9463 obj_type = obj->vtable->klass;
9464 if (mono_class_is_transparent_proxy (obj_type)) {
9465 obj_type = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
9469 g_assert (obj_type);
9472 case CMD_OBJECT_REF_GET_TYPE:
9473 /* This handles transparent proxies too */
9474 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9476 case CMD_OBJECT_REF_GET_VALUES:
9477 len = decode_int (p, &p, end);
9479 for (i = 0; i < len; ++i) {
9480 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9481 if (err != ERR_NONE)
9484 /* Check that the field belongs to the object */
9486 for (k = obj_type; k; k = k->parent) {
9487 if (k == f->parent) {
9493 return ERR_INVALID_FIELDID;
9495 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9499 if (mono_class_field_is_special_static (f))
9500 return ERR_INVALID_FIELDID;
9502 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9503 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9504 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9505 mono_field_static_get_value_checked (vtable, f, val, &error);
9506 if (!is_ok (&error)) {
9507 mono_error_cleanup (&error); /* FIXME report the error */
9508 return ERR_INVALID_OBJECT;
9510 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9513 guint8 *field_value = NULL;
9516 #ifndef DISABLE_REMOTING
9517 void *field_storage = NULL;
9518 field_value = mono_load_remote_field_checked(obj, obj_type, f, &field_storage, &error);
9519 if (!is_ok (&error)) {
9520 mono_error_cleanup (&error); /* FIXME report the error */
9521 return ERR_INVALID_OBJECT;
9524 g_assert_not_reached ();
9527 field_value = (guint8*)obj + f->offset;
9529 buffer_add_value (buf, f->type, field_value, obj->vtable->domain);
9533 case CMD_OBJECT_REF_SET_VALUES:
9534 len = decode_int (p, &p, end);
9536 for (i = 0; i < len; ++i) {
9537 f = decode_fieldid (p, &p, end, NULL, &err);
9538 if (err != ERR_NONE)
9541 /* Check that the field belongs to the object */
9543 for (k = obj_type; k; k = k->parent) {
9544 if (k == f->parent) {
9550 return ERR_INVALID_FIELDID;
9552 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9556 if (mono_class_field_is_special_static (f))
9557 return ERR_INVALID_FIELDID;
9559 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9560 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9562 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9563 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
9564 if (err != ERR_NONE) {
9568 mono_field_static_set_value (vtable, f, val);
9571 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
9572 if (err != ERR_NONE)
9577 case CMD_OBJECT_REF_GET_ADDRESS:
9578 buffer_add_long (buf, (gssize)obj);
9580 case CMD_OBJECT_REF_GET_DOMAIN:
9581 buffer_add_domainid (buf, obj->vtable->domain);
9583 case CMD_OBJECT_REF_GET_INFO:
9584 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9585 buffer_add_domainid (buf, obj->vtable->domain);
9588 return ERR_NOT_IMPLEMENTED;
9595 command_set_to_string (CommandSet command_set)
9597 switch (command_set) {
9600 case CMD_SET_OBJECT_REF:
9601 return "OBJECT_REF";
9602 case CMD_SET_STRING_REF:
9603 return "STRING_REF";
9604 case CMD_SET_THREAD:
9606 case CMD_SET_ARRAY_REF:
9608 case CMD_SET_EVENT_REQUEST:
9609 return "EVENT_REQUEST";
9610 case CMD_SET_STACK_FRAME:
9611 return "STACK_FRAME";
9612 case CMD_SET_APPDOMAIN:
9614 case CMD_SET_ASSEMBLY:
9616 case CMD_SET_METHOD:
9620 case CMD_SET_MODULE:
9631 static const char* vm_cmds_str [] = {
9639 "SET_PROTOCOL_VERSION",
9642 "GET_TYPES_FOR_SOURCE_FILE",
9647 static const char* thread_cmds_str[] = {
9657 static const char* event_cmds_str[] = {
9660 "REQUEST_CLEAR_ALL_BREAKPOINTS"
9663 static const char* appdomain_cmds_str[] = {
9665 "GET_FRIENDLY_NAME",
9667 "GET_ENTRY_ASSEMBLY",
9670 "CREATE_BOXED_VALUE"
9673 static const char* assembly_cmds_str[] = {
9676 "GET_MANIFEST_MODULE",
9682 static const char* module_cmds_str[] = {
9686 static const char* field_cmds_str[] = {
9690 static const char* method_cmds_str[] = {
9692 "GET_DECLARING_TYPE",
9700 "MAKE_GENERIC_METHOD"
9703 static const char* type_cmds_str[] = {
9711 "IS_ASSIGNABLE_FROM",
9715 "GET_PROPERTY_CATTRS",
9716 "GET_SOURCE_FILES_2",
9718 "GET_METHODS_BY_NAME_FLAGS",
9720 "GET_INTERFACE_MAP",
9724 static const char* stack_frame_cmds_str[] = {
9732 static const char* array_cmds_str[] = {
9738 static const char* string_cmds_str[] = {
9744 static const char* object_cmds_str[] = {
9755 cmd_to_string (CommandSet set, int command)
9763 cmds_len = G_N_ELEMENTS (vm_cmds_str);
9765 case CMD_SET_OBJECT_REF:
9766 cmds = object_cmds_str;
9767 cmds_len = G_N_ELEMENTS (object_cmds_str);
9769 case CMD_SET_STRING_REF:
9770 cmds = string_cmds_str;
9771 cmds_len = G_N_ELEMENTS (string_cmds_str);
9773 case CMD_SET_THREAD:
9774 cmds = thread_cmds_str;
9775 cmds_len = G_N_ELEMENTS (thread_cmds_str);
9777 case CMD_SET_ARRAY_REF:
9778 cmds = array_cmds_str;
9779 cmds_len = G_N_ELEMENTS (array_cmds_str);
9781 case CMD_SET_EVENT_REQUEST:
9782 cmds = event_cmds_str;
9783 cmds_len = G_N_ELEMENTS (event_cmds_str);
9785 case CMD_SET_STACK_FRAME:
9786 cmds = stack_frame_cmds_str;
9787 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
9789 case CMD_SET_APPDOMAIN:
9790 cmds = appdomain_cmds_str;
9791 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
9793 case CMD_SET_ASSEMBLY:
9794 cmds = assembly_cmds_str;
9795 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
9797 case CMD_SET_METHOD:
9798 cmds = method_cmds_str;
9799 cmds_len = G_N_ELEMENTS (method_cmds_str);
9802 cmds = type_cmds_str;
9803 cmds_len = G_N_ELEMENTS (type_cmds_str);
9805 case CMD_SET_MODULE:
9806 cmds = module_cmds_str;
9807 cmds_len = G_N_ELEMENTS (module_cmds_str);
9810 cmds = field_cmds_str;
9811 cmds_len = G_N_ELEMENTS (field_cmds_str);
9814 cmds = event_cmds_str;
9815 cmds_len = G_N_ELEMENTS (event_cmds_str);
9820 if (command > 0 && command <= cmds_len)
9821 return cmds [command - 1];
9827 wait_for_attach (void)
9829 #ifndef DISABLE_SOCKET_TRANSPORT
9830 if (listen_fd == -1) {
9831 DEBUG_PRINTF (1, "[dbg] Invalid listening socket\n");
9835 /* Block and wait for client connection */
9836 conn_fd = socket_transport_accept (listen_fd);
9838 DEBUG_PRINTF (1, "Accepted connection on %d\n", conn_fd);
9839 if (conn_fd == -1) {
9840 DEBUG_PRINTF (1, "[dbg] Bad client connection\n");
9844 g_assert_not_reached ();
9848 disconnected = !transport_handshake ();
9850 DEBUG_PRINTF (1, "Transport handshake failed!\n");
9860 * This thread handles communication with the debugger client using a JDWP
9864 debugger_thread (void *arg)
9867 int res, len, id, flags, command = 0;
9868 CommandSet command_set = (CommandSet)0;
9869 guint8 header [HEADER_LENGTH];
9870 guint8 *data, *p, *end;
9874 gboolean attach_failed = FALSE;
9876 DEBUG_PRINTF (1, "[dbg] Agent thread started, pid=%p\n", (gpointer) (gsize) mono_native_thread_id_get ());
9878 debugger_thread_id = mono_native_thread_id_get ();
9880 MonoThread *thread = mono_thread_attach (mono_get_root_domain ());
9881 mono_thread_set_name_internal (thread->internal_thread, mono_string_new (mono_get_root_domain (), "Debugger agent"), TRUE, &error);
9882 mono_error_assert_ok (&error);
9884 thread->internal_thread->state |= ThreadState_Background;
9885 thread->internal_thread->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
9887 if (agent_config.defer) {
9888 if (!wait_for_attach ()) {
9889 DEBUG_PRINTF (1, "[dbg] Can't attach, aborting debugger thread.\n");
9890 attach_failed = TRUE; // Don't abort process when we can't listen
9892 mono_set_is_debugger_attached (TRUE);
9893 /* Send start event to client */
9894 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
9897 mono_set_is_debugger_attached (TRUE);
9900 while (!attach_failed) {
9901 res = transport_recv (header, HEADER_LENGTH);
9903 /* This will break if the socket is closed during shutdown too */
9904 if (res != HEADER_LENGTH) {
9905 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH);
9910 end = header + HEADER_LENGTH;
9912 len = decode_int (p, &p, end);
9913 id = decode_int (p, &p, end);
9914 flags = decode_byte (p, &p, end);
9915 command_set = (CommandSet)decode_byte (p, &p, end);
9916 command = decode_byte (p, &p, end);
9918 g_assert (flags == 0);
9921 const char *cmd_str;
9924 cmd_str = cmd_to_string (command_set, command);
9926 sprintf (cmd_num, "%d", command);
9930 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);
9933 data = (guint8 *)g_malloc (len - HEADER_LENGTH);
9934 if (len - HEADER_LENGTH > 0)
9936 res = transport_recv (data, len - HEADER_LENGTH);
9937 if (res != len - HEADER_LENGTH) {
9938 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH);
9944 end = data + (len - HEADER_LENGTH);
9946 buffer_init (&buf, 128);
9951 /* Process the request */
9952 switch (command_set) {
9954 err = vm_commands (command, id, p, end, &buf);
9955 if (err == ERR_NONE && command == CMD_VM_INVOKE_METHOD)
9956 /* Sent after the invoke is complete */
9959 case CMD_SET_EVENT_REQUEST:
9960 err = event_commands (command, p, end, &buf);
9962 case CMD_SET_APPDOMAIN:
9963 err = domain_commands (command, p, end, &buf);
9965 case CMD_SET_ASSEMBLY:
9966 err = assembly_commands (command, p, end, &buf);
9968 case CMD_SET_MODULE:
9969 err = module_commands (command, p, end, &buf);
9972 err = field_commands (command, p, end, &buf);
9975 err = type_commands (command, p, end, &buf);
9977 case CMD_SET_METHOD:
9978 err = method_commands (command, p, end, &buf);
9980 case CMD_SET_THREAD:
9981 err = thread_commands (command, p, end, &buf);
9983 case CMD_SET_STACK_FRAME:
9984 err = frame_commands (command, p, end, &buf);
9986 case CMD_SET_ARRAY_REF:
9987 err = array_commands (command, p, end, &buf);
9989 case CMD_SET_STRING_REF:
9990 err = string_commands (command, p, end, &buf);
9992 case CMD_SET_OBJECT_REF:
9993 err = object_commands (command, p, end, &buf);
9996 err = ERR_NOT_IMPLEMENTED;
9999 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
10000 buffer_replies = TRUE;
10004 if (buffer_replies) {
10005 buffer_reply_packet (id, err, &buf);
10007 send_reply_packet (id, err, &buf);
10008 //DEBUG_PRINTF (1, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000);
10012 if (err == ERR_NONE && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
10013 send_buffered_reply_packets ();
10014 buffer_replies = FALSE;
10018 buffer_free (&buf);
10020 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
10024 mono_set_is_debugger_attached (FALSE);
10026 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
10027 debugger_thread_exited = TRUE;
10028 mono_coop_cond_signal (&debugger_thread_exited_cond);
10029 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
10031 DEBUG_PRINTF (1, "[dbg] Debugger thread exited.\n");
10033 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
10034 DEBUG_PRINTF (2, "[dbg] Detached - restarting clean debugger thread.\n");
10035 start_debugger_thread ();
10041 #else /* DISABLE_DEBUGGER_AGENT */
10044 mono_debugger_agent_parse_options (char *options)
10046 g_error ("This runtime is configured with the debugger agent disabled.");
10050 mono_debugger_agent_init (void)
10055 mono_debugger_agent_breakpoint_hit (void *sigctx)
10060 mono_debugger_agent_single_step_event (void *sigctx)
10065 mono_debugger_agent_free_domain_info (MonoDomain *domain)
10070 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
10071 MonoContext *catch_ctx)
10076 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
10081 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
10086 mono_debugger_agent_user_break (void)
10092 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
10097 mono_debugger_agent_debug_log_is_enabled (void)
10103 mono_debugger_agent_unhandled_exception (MonoException *exc)
10105 g_assert_not_reached ();
10109 debugger_agent_single_step_from_context (MonoContext *ctx)
10111 g_assert_not_reached ();
10115 debugger_agent_breakpoint_from_context (MonoContext *ctx)
10117 g_assert_not_reached ();