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.
15 #ifdef HAVE_SYS_TYPES_H
16 #include <sys/types.h>
18 #ifdef HAVE_SYS_SELECT_H
19 #include <sys/select.h>
21 #ifdef HAVE_SYS_SOCKET_H
22 #include <sys/socket.h>
24 #ifdef HAVE_NETINET_TCP_H
25 #include <netinet/tcp.h>
27 #ifdef HAVE_NETINET_IN_H
28 #include <netinet/in.h>
43 #ifdef HAVE_UCONTEXT_H
53 /* cygwin's headers do not seem to define these */
54 void WSAAPI freeaddrinfo (struct addrinfo*);
55 int WSAAPI getaddrinfo (const char*,const char*,const struct addrinfo*,
57 int WSAAPI getnameinfo(const struct sockaddr*,socklen_t,char*,DWORD,
62 #ifdef PLATFORM_ANDROID
64 #include <linux/tcp.h>
65 #include <sys/endian.h>
68 #include <mono/metadata/mono-debug.h>
69 #include <mono/metadata/mono-debug-debugger.h>
70 #include <mono/metadata/debug-mono-symfile.h>
71 #include <mono/metadata/gc-internal.h>
72 #include <mono/metadata/environment.h>
73 #include <mono/metadata/threads-types.h>
74 #include <mono/metadata/socket-io.h>
75 #include <mono/metadata/assembly.h>
76 #include <mono/metadata/runtime.h>
77 #include <mono/metadata/threadpool.h>
78 #include <mono/metadata/verify-internals.h>
79 #include <mono/utils/mono-semaphore.h>
80 #include <mono/utils/mono-error-internals.h>
81 #include <mono/utils/mono-stack-unwinding.h>
82 #include <mono/utils/mono-time.h>
83 #include <mono/utils/mono-threads.h>
84 #include "debugger-agent.h"
88 On iOS we can't use System.Environment.Exit () as it will do the wrong
91 #if !defined (TARGET_IOS)
92 #define TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
96 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
97 #define DISABLE_DEBUGGER_AGENT 1
100 #ifdef DISABLE_SOFT_DEBUG
101 #define DISABLE_DEBUGGER_AGENT 1
104 #ifndef DISABLE_DEBUGGER_AGENT
106 #include <mono/utils/mono-mutex.h>
108 /* Definitions to make backporting to 2.6 easier */
109 //#define MonoInternalThread MonoThread
110 //#define mono_thread_internal_current mono_thread_current
111 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
134 guint32 il_offset, native_offset;
138 * If method is gshared, this is the actual instance, otherwise this is equal to
141 MonoMethod *actual_method;
143 * This is the method which is visible to debugger clients. Same as method,
144 * except for native-to-managed wrappers.
146 MonoMethod *api_method;
148 MonoDebugMethodJitInfo *jit;
151 mgreg_t *reg_locations [MONO_MAX_IREGS];
153 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
154 * the frame can become invalid.
159 typedef struct _InvokeData InvokeData;
167 /* This is the context which needs to be restored after the invoke */
171 * If this is set, invoke this method with the arguments given by ARGS.
175 guint32 suspend_count;
178 InvokeData *last_invoke;
182 MonoThreadUnwindState context;
184 /* This is computed on demand when it is requested using the wire protocol */
185 /* It is freed up when the thread is resumed */
189 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
192 gboolean frames_up_to_date;
194 * Points to data about a pending invoke which needs to be executed after the thread
197 InvokeData *pending_invoke;
199 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
204 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
205 * within a finite amount of time.
209 * Set to TRUE if this thread is suspended in suspend_current ().
211 gboolean really_suspended;
212 /* Used to pass the context to the breakpoint/single step handler */
213 MonoContext handler_ctx;
214 /* Whenever thread_stop () was called for this thread */
217 /* Number of thread interruptions not yet processed */
218 gint32 interrupt_count;
220 /* Whenever to disable breakpoints (used during invokes) */
221 gboolean disable_breakpoints;
224 * Number of times this thread has been resumed using resume_thread ().
226 guint32 resume_count;
228 MonoInternalThread *thread;
231 * Information about the frame which transitioned to native code for running
234 StackFrameInfo async_last_frame;
237 * The context where the stack walk can be started for running threads.
239 MonoThreadUnwindState async_state;
242 * The context used for filter clauses
244 MonoThreadUnwindState filter_state;
247 * The callee address of the last mono_runtime_invoke call
249 gpointer invoke_addr;
251 gboolean abort_requested;
254 * The current mono_runtime_invoke invocation.
259 * The context where single stepping should resume while the thread is suspended because
260 * of an EXCEPTION event.
262 MonoThreadUnwindState catch_state;
265 * The context which needs to be restored after handling a single step/breakpoint
266 * event. This is the same as the ctx at step/breakpoint site, but includes changes
267 * to caller saved registers done by set_var ().
269 MonoContext restore_ctx;
271 /* The currently unloading appdomain */
272 MonoDomain *domain_unloading;
277 void (*connect) (const char *address);
278 void (*close1) (void);
279 void (*close2) (void);
280 gboolean (*send) (void *buf, int len);
281 int (*recv) (void *buf, int len);
285 * Wire Protocol definitions
288 #define HEADER_LENGTH 11
290 #define MAJOR_VERSION 2
291 #define MINOR_VERSION 34
295 CMD_SET_OBJECT_REF = 9,
296 CMD_SET_STRING_REF = 10,
298 CMD_SET_ARRAY_REF = 13,
299 CMD_SET_EVENT_REQUEST = 15,
300 CMD_SET_STACK_FRAME = 16,
301 CMD_SET_APPDOMAIN = 20,
302 CMD_SET_ASSEMBLY = 21,
311 EVENT_KIND_VM_START = 0,
312 EVENT_KIND_VM_DEATH = 1,
313 EVENT_KIND_THREAD_START = 2,
314 EVENT_KIND_THREAD_DEATH = 3,
315 EVENT_KIND_APPDOMAIN_CREATE = 4,
316 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
317 EVENT_KIND_METHOD_ENTRY = 6,
318 EVENT_KIND_METHOD_EXIT = 7,
319 EVENT_KIND_ASSEMBLY_LOAD = 8,
320 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
321 EVENT_KIND_BREAKPOINT = 10,
322 EVENT_KIND_STEP = 11,
323 EVENT_KIND_TYPE_LOAD = 12,
324 EVENT_KIND_EXCEPTION = 13,
325 EVENT_KIND_KEEPALIVE = 14,
326 EVENT_KIND_USER_BREAK = 15,
327 EVENT_KIND_USER_LOG = 16
331 SUSPEND_POLICY_NONE = 0,
332 SUSPEND_POLICY_EVENT_THREAD = 1,
333 SUSPEND_POLICY_ALL = 2
338 ERR_INVALID_OBJECT = 20,
339 ERR_INVALID_FIELDID = 25,
340 ERR_INVALID_FRAMEID = 30,
341 ERR_NOT_IMPLEMENTED = 100,
342 ERR_NOT_SUSPENDED = 101,
343 ERR_INVALID_ARGUMENT = 102,
345 ERR_NO_INVOCATION = 104,
346 ERR_ABSENT_INFORMATION = 105,
347 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
348 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
353 MOD_KIND_THREAD_ONLY = 3,
354 MOD_KIND_LOCATION_ONLY = 7,
355 MOD_KIND_EXCEPTION_ONLY = 8,
357 MOD_KIND_ASSEMBLY_ONLY = 11,
358 MOD_KIND_SOURCE_FILE_ONLY = 12,
359 MOD_KIND_TYPE_NAME_ONLY = 13
374 STEP_FILTER_NONE = 0,
375 STEP_FILTER_STATIC_CTOR = 1,
376 STEP_FILTER_DEBUGGER_HIDDEN = 2,
377 STEP_FILTER_DEBUGGER_STEP_THROUGH = 4,
378 STEP_FILTER_DEBUGGER_NON_USER_CODE = 8
382 TOKEN_TYPE_STRING = 0,
384 TOKEN_TYPE_FIELD = 2,
385 TOKEN_TYPE_METHOD = 3,
386 TOKEN_TYPE_UNKNOWN = 4
390 VALUE_TYPE_ID_NULL = 0xf0,
391 VALUE_TYPE_ID_TYPE = 0xf1,
392 VALUE_TYPE_ID_PARENT_VTYPE = 0xf2
396 FRAME_FLAG_DEBUGGER_INVOKE = 1,
397 FRAME_FLAG_NATIVE_TRANSITION = 2
401 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
402 INVOKE_FLAG_SINGLE_THREADED = 2
406 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
407 } BindingFlagsExtensions;
411 CMD_VM_ALL_THREADS = 2,
416 CMD_VM_INVOKE_METHOD = 7,
417 CMD_VM_SET_PROTOCOL_VERSION = 8,
418 CMD_VM_ABORT_INVOKE = 9,
419 CMD_VM_SET_KEEPALIVE = 10,
420 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
421 CMD_VM_GET_TYPES = 12,
422 CMD_VM_INVOKE_METHODS = 13,
423 CMD_VM_START_BUFFERING = 14,
424 CMD_VM_STOP_BUFFERING = 15
428 CMD_THREAD_GET_FRAME_INFO = 1,
429 CMD_THREAD_GET_NAME = 2,
430 CMD_THREAD_GET_STATE = 3,
431 CMD_THREAD_GET_INFO = 4,
432 CMD_THREAD_GET_ID = 5,
433 CMD_THREAD_GET_TID = 6,
434 CMD_THREAD_SET_IP = 7
438 CMD_EVENT_REQUEST_SET = 1,
439 CMD_EVENT_REQUEST_CLEAR = 2,
440 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
448 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
449 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
450 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
451 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
452 CMD_APPDOMAIN_CREATE_STRING = 5,
453 CMD_APPDOMAIN_GET_CORLIB = 6,
454 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
458 CMD_ASSEMBLY_GET_LOCATION = 1,
459 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
460 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
461 CMD_ASSEMBLY_GET_OBJECT = 4,
462 CMD_ASSEMBLY_GET_TYPE = 5,
463 CMD_ASSEMBLY_GET_NAME = 6
467 CMD_MODULE_GET_INFO = 1,
471 CMD_FIELD_GET_INFO = 1,
475 CMD_METHOD_GET_NAME = 1,
476 CMD_METHOD_GET_DECLARING_TYPE = 2,
477 CMD_METHOD_GET_DEBUG_INFO = 3,
478 CMD_METHOD_GET_PARAM_INFO = 4,
479 CMD_METHOD_GET_LOCALS_INFO = 5,
480 CMD_METHOD_GET_INFO = 6,
481 CMD_METHOD_GET_BODY = 7,
482 CMD_METHOD_RESOLVE_TOKEN = 8,
483 CMD_METHOD_GET_CATTRS = 9,
484 CMD_METHOD_MAKE_GENERIC_METHOD = 10
488 CMD_TYPE_GET_INFO = 1,
489 CMD_TYPE_GET_METHODS = 2,
490 CMD_TYPE_GET_FIELDS = 3,
491 CMD_TYPE_GET_VALUES = 4,
492 CMD_TYPE_GET_OBJECT = 5,
493 CMD_TYPE_GET_SOURCE_FILES = 6,
494 CMD_TYPE_SET_VALUES = 7,
495 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
496 CMD_TYPE_GET_PROPERTIES = 9,
497 CMD_TYPE_GET_CATTRS = 10,
498 CMD_TYPE_GET_FIELD_CATTRS = 11,
499 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
500 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
501 CMD_TYPE_GET_VALUES_2 = 14,
502 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
503 CMD_TYPE_GET_INTERFACES = 16,
504 CMD_TYPE_GET_INTERFACE_MAP = 17,
505 CMD_TYPE_IS_INITIALIZED = 18,
506 CMD_TYPE_CREATE_INSTANCE = 19
510 CMD_STACK_FRAME_GET_VALUES = 1,
511 CMD_STACK_FRAME_GET_THIS = 2,
512 CMD_STACK_FRAME_SET_VALUES = 3
516 CMD_ARRAY_REF_GET_LENGTH = 1,
517 CMD_ARRAY_REF_GET_VALUES = 2,
518 CMD_ARRAY_REF_SET_VALUES = 3,
522 CMD_STRING_REF_GET_VALUE = 1,
523 CMD_STRING_REF_GET_LENGTH = 2,
524 CMD_STRING_REF_GET_CHARS = 3
528 CMD_OBJECT_REF_GET_TYPE = 1,
529 CMD_OBJECT_REF_GET_VALUES = 2,
530 CMD_OBJECT_REF_IS_COLLECTED = 3,
531 CMD_OBJECT_REF_GET_ADDRESS = 4,
532 CMD_OBJECT_REF_GET_DOMAIN = 5,
533 CMD_OBJECT_REF_SET_VALUES = 6,
534 CMD_OBJECT_REF_GET_INFO = 7,
540 int count; /* For kind == MOD_KIND_COUNT */
541 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
542 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
543 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
544 GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
545 GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
546 StepFilter filter; /* For kind == MOD_KIND_STEP */
548 gboolean caught, uncaught, subclasses; /* For kind == MOD_KIND_EXCEPTION_ONLY */
557 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
561 * Describes a single step request.
565 MonoInternalThread *thread;
571 MonoMethod *last_method;
573 /* Whenever single stepping is performed using start/stop_single_stepping () */
575 /* The list of breakpoints used to implement step-over */
577 /* The number of frames at the start of a step-over */
582 * Contains additional information for an event
585 /* For EVENT_KIND_EXCEPTION */
587 MonoContext catch_ctx;
589 /* For EVENT_KIND_USER_LOG */
591 char *category, *message;
592 /* For EVENT_KIND_TYPE_LOAD */
596 /* Dummy structure used for the profiler callbacks */
602 guint8 *buf, *p, *end;
605 typedef struct ReplyPacket {
611 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
614 #define get_last_sock_error() WSAGetLastError()
615 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
616 #define MONO_EINTR WSAEINTR
618 #define get_last_sock_error() errno
619 #define MONO_EWOULDBLOCK EWOULDBLOCK
620 #define MONO_EINTR EINTR
623 #define CHECK_PROTOCOL_VERSION(major,minor) \
624 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
630 static AgentConfig agent_config;
633 * Whenever the agent is fully initialized.
634 * When using the onuncaught or onthrow options, only some parts of the agent are
635 * initialized on startup, and the full initialization which includes connection
636 * establishment and the startup of the agent thread is only done in response to
639 static gint32 inited;
641 #ifndef DISABLE_SOCKET_TRANSPORT
643 static int listen_fd;
646 static int packet_id = 0;
648 static int objref_id = 0;
650 static int event_request_id = 0;
652 static int frame_id = 0;
654 static GPtrArray *event_requests;
656 static MonoNativeTlsKey debugger_tls_id;
658 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
660 /* Maps MonoInternalThread -> DebuggerTlsData */
661 static MonoGHashTable *thread_to_tls;
663 /* Maps tid -> MonoInternalThread */
664 static MonoGHashTable *tid_to_thread;
666 /* Maps tid -> MonoThread (not MonoInternalThread) */
667 static MonoGHashTable *tid_to_thread_obj;
669 static gsize debugger_thread_id;
671 static HANDLE debugger_thread_handle;
673 static int log_level;
675 static gboolean embedding;
677 static FILE *log_file;
679 /* Assemblies whose assembly load event has no been sent yet */
680 static GPtrArray *pending_assembly_loads;
682 /* Whenever the debugger thread has exited */
683 static gboolean debugger_thread_exited;
685 /* Cond variable used to wait for debugger_thread_exited becoming true */
686 static mono_cond_t debugger_thread_exited_cond;
688 /* Mutex for the cond var above */
689 static mono_mutex_t debugger_thread_exited_mutex;
691 static DebuggerProfiler debugger_profiler;
693 /* The single step request instance */
694 static SingleStepReq *ss_req = NULL;
695 static gpointer ss_invoke_addr = NULL;
697 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
698 /* Number of single stepping operations in progress */
702 /* The protocol version of the client */
703 static int major_version, minor_version;
705 /* Whenever the variables above are set by the client */
706 static gboolean protocol_version_set;
708 /* A hash table containing all active domains */
709 static GHashTable *domains;
711 /* The number of times the runtime is suspended */
712 static gint32 suspend_count;
714 /* Whenever to buffer reply messages and send them together */
715 static gboolean buffer_replies;
717 /* Buffered reply packets */
718 static ReplyPacket reply_packets [128];
721 static void transport_init (void);
722 static void transport_connect (const char *address);
723 static gboolean transport_handshake (void);
724 static void register_transport (DebuggerTransport *trans);
726 static guint32 WINAPI debugger_thread (void *arg);
728 static void runtime_initialized (MonoProfiler *prof);
730 static void runtime_shutdown (MonoProfiler *prof);
732 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
734 static void thread_end (MonoProfiler *prof, uintptr_t tid);
736 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
738 static void appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain);
740 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
742 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
744 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
746 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
748 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
750 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
752 static void emit_assembly_load (gpointer assembly, gpointer user_data);
754 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
756 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
758 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
760 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
762 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
764 static void start_single_stepping (void);
766 static void stop_single_stepping (void);
768 static void suspend_current (void);
770 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
772 static void clear_types_for_assembly (MonoAssembly *assembly);
774 static void clear_breakpoints_for_domain (MonoDomain *domain);
776 static void process_profiler_event (EventKind event, gpointer arg);
778 /* Submodule init/cleanup */
779 static void breakpoints_init (void);
780 static void breakpoints_cleanup (void);
782 static void objrefs_init (void);
783 static void objrefs_cleanup (void);
785 static void ids_init (void);
786 static void ids_cleanup (void);
788 static void suspend_init (void);
790 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch);
791 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
792 static void ss_destroy (SingleStepReq *req);
794 static void start_debugger_thread (void);
795 static void stop_debugger_thread (void);
797 static void finish_agent_init (gboolean on_startup);
799 static void process_profiler_event (EventKind event, gpointer arg);
801 static void invalidate_frames (DebuggerTlsData *tls);
803 #ifndef DISABLE_SOCKET_TRANSPORT
805 register_socket_transport (void);
809 parse_address (char *address, char **host, int *port)
811 char *pos = strchr (address, ':');
813 if (pos == NULL || pos == address)
816 *host = g_malloc (pos - address + 1);
817 strncpy (*host, address, pos - address);
818 (*host) [pos - address] = '\0';
820 *port = atoi (pos + 1);
828 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
829 fprintf (stderr, "Available options:\n");
830 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
831 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
832 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
833 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
834 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
835 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
836 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
837 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
838 fprintf (stderr, " setpgid=y/n\t\t\tWhether to call setpid(0, 0) after startup.\n");
839 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
843 parse_flag (const char *option, char *flag)
845 if (!strcmp (flag, "y"))
847 else if (!strcmp (flag, "n"))
850 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
857 mono_debugger_agent_parse_options (char *options)
864 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
865 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
869 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
871 options = g_strdup_printf ("%s,%s", options, extra);
873 agent_config.enabled = TRUE;
874 agent_config.suspend = TRUE;
875 agent_config.server = FALSE;
876 agent_config.defer = FALSE;
877 agent_config.address = NULL;
879 //agent_config.log_level = 10;
881 args = g_strsplit (options, ",", -1);
882 for (ptr = args; ptr && *ptr; ptr ++) {
885 if (strncmp (arg, "transport=", 10) == 0) {
886 agent_config.transport = g_strdup (arg + 10);
887 } else if (strncmp (arg, "address=", 8) == 0) {
888 agent_config.address = g_strdup (arg + 8);
889 } else if (strncmp (arg, "loglevel=", 9) == 0) {
890 agent_config.log_level = atoi (arg + 9);
891 } else if (strncmp (arg, "logfile=", 8) == 0) {
892 agent_config.log_file = g_strdup (arg + 8);
893 } else if (strncmp (arg, "suspend=", 8) == 0) {
894 agent_config.suspend = parse_flag ("suspend", arg + 8);
895 } else if (strncmp (arg, "server=", 7) == 0) {
896 agent_config.server = parse_flag ("server", arg + 7);
897 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
898 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
899 } else if (strncmp (arg, "onthrow=", 8) == 0) {
900 /* We support multiple onthrow= options */
901 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
902 } else if (strncmp (arg, "onthrow", 7) == 0) {
903 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
904 } else if (strncmp (arg, "help", 4) == 0) {
907 } else if (strncmp (arg, "timeout=", 8) == 0) {
908 agent_config.timeout = atoi (arg + 8);
909 } else if (strncmp (arg, "launch=", 7) == 0) {
910 agent_config.launch = g_strdup (arg + 7);
911 } else if (strncmp (arg, "embedding=", 10) == 0) {
912 agent_config.embedding = atoi (arg + 10) == 1;
913 } else if (strncmp (arg, "keepalive=", 10) == 0) {
914 agent_config.keepalive = atoi (arg + 10);
915 } else if (strncmp (arg, "setpgid=", 8) == 0) {
916 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
923 if (agent_config.server && !agent_config.suspend) {
924 /* Waiting for deferred attachment */
925 agent_config.defer = TRUE;
926 if (agent_config.address == NULL) {
927 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (getpid () % 1000));
931 //agent_config.log_level = 0;
933 if (agent_config.transport == NULL) {
934 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
938 if (agent_config.address == NULL && !agent_config.server) {
939 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
944 if (!strcmp (agent_config.transport, "dt_socket")) {
945 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
946 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
953 mono_debugger_agent_init (void)
955 if (!agent_config.enabled)
960 /* Need to know whenever a thread has acquired the loader mutex */
961 mono_loader_lock_track_ownership (TRUE);
963 event_requests = g_ptr_array_new ();
965 mono_mutex_init (&debugger_thread_exited_mutex);
966 mono_cond_init (&debugger_thread_exited_cond, NULL);
968 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
969 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
970 mono_profiler_install_runtime_initialized (runtime_initialized);
971 mono_profiler_install_appdomain (NULL, appdomain_load, appdomain_start_unload, appdomain_unload);
972 mono_profiler_install_thread (thread_startup, thread_end);
973 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
974 mono_profiler_install_jit_end (jit_end);
975 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
977 mono_native_tls_alloc (&debugger_tls_id, NULL);
979 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
980 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls);
982 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
983 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread);
985 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
986 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj);
988 pending_assembly_loads = g_ptr_array_new ();
989 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
991 log_level = agent_config.log_level;
993 embedding = agent_config.embedding;
996 if (agent_config.log_file) {
997 log_file = fopen (agent_config.log_file, "w+");
999 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
1008 breakpoints_init ();
1011 mini_get_debug_options ()->gen_seq_points = TRUE;
1013 * This is needed because currently we don't handle liveness info.
1015 mini_get_debug_options ()->mdb_optimizations = TRUE;
1017 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
1018 /* This is needed because we can't set local variables in registers yet */
1019 mono_disable_optimizations (MONO_OPT_LINEARS);
1023 * The stack walk done from thread_interrupt () needs to be signal safe, but it
1024 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
1025 * safe (#3411). So load AOT info eagerly when the debugger is running as a
1028 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
1031 if (agent_config.setpgid)
1035 if (!agent_config.onuncaught && !agent_config.onthrow)
1036 finish_agent_init (TRUE);
1040 * finish_agent_init:
1042 * Finish the initialization of the agent. This involves connecting the transport
1043 * and starting the agent thread. This is either done at startup, or
1044 * in response to some event like an unhandled exception.
1047 finish_agent_init (gboolean on_startup)
1051 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
1054 if (agent_config.launch) {
1057 // FIXME: Generated address
1058 // FIXME: Races with transport_connect ()
1060 argv [0] = agent_config.launch;
1061 argv [1] = agent_config.transport;
1062 argv [2] = agent_config.address;
1065 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1067 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1072 transport_connect (agent_config.address);
1075 /* Do some which is usually done after sending the VMStart () event */
1076 vm_start_event_sent = TRUE;
1077 start_debugger_thread ();
1082 mono_debugger_agent_cleanup (void)
1087 stop_debugger_thread ();
1089 breakpoints_cleanup ();
1093 mono_mutex_destroy (&debugger_thread_exited_mutex);
1094 mono_cond_destroy (&debugger_thread_exited_cond);
1101 #ifndef DISABLE_SOCKET_TRANSPORT
1106 * recv() + handle incomplete reads and EINTR
1109 socket_transport_recv (void *buf, int len)
1115 static gint32 last_keepalive;
1120 res = recv (fd, (char *) buf + total, len - total, flags);
1123 if (agent_config.keepalive) {
1124 gboolean need_keepalive = FALSE;
1125 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1126 need_keepalive = TRUE;
1127 } else if (res == -1) {
1128 /* This could happen if recv () is interrupted repeatedly */
1129 msecs = mono_msec_ticks ();
1130 if (msecs - last_keepalive >= agent_config.keepalive) {
1131 need_keepalive = TRUE;
1132 last_keepalive = msecs;
1135 if (need_keepalive) {
1136 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1140 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1145 #define HAVE_GETADDRINFO 1
1149 set_keepalive (void)
1154 if (!agent_config.keepalive || !conn_fd)
1157 tv.tv_sec = agent_config.keepalive / 1000;
1158 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1160 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1161 g_assert (result >= 0);
1165 socket_transport_accept (int socket_fd)
1167 conn_fd = accept (socket_fd, NULL, NULL);
1168 if (conn_fd == -1) {
1169 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1171 DEBUG (1, fprintf (log_file, "Accepted connection from client, connection fd=%d.\n", conn_fd));
1178 socket_transport_send (void *data, int len)
1183 res = send (conn_fd, data, len, 0);
1184 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1192 * socket_transport_connect:
1194 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1197 socket_transport_connect (const char *address)
1199 #ifdef HAVE_GETADDRINFO
1200 struct addrinfo hints;
1201 struct addrinfo *result, *rp;
1203 struct hostent *result;
1205 int sfd = -1, s, res;
1206 char port_string [128];
1210 if (agent_config.address) {
1211 res = parse_address (agent_config.address, &host, &port);
1212 g_assert (res == 0);
1222 sprintf (port_string, "%d", port);
1224 mono_network_init ();
1226 /* Obtain address(es) matching host/port */
1227 #ifdef HAVE_GETADDRINFO
1228 memset (&hints, 0, sizeof (struct addrinfo));
1229 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
1230 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
1232 hints.ai_protocol = 0; /* Any protocol */
1234 s = getaddrinfo (host, port_string, &hints, &result);
1236 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %s\n", host, port, gai_strerror (s));
1240 /* The PS3 doesn't even have _r or hstrerror () */
1241 result = gethostbyname (host);
1243 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, h_errno);
1248 if (agent_config.server) {
1249 #ifdef HAVE_GETADDRINFO
1250 /* Wait for a connection */
1252 struct sockaddr_in addr;
1255 /* No address, generate one */
1256 sfd = socket (AF_INET, SOCK_STREAM, 0);
1259 /* This will bind the socket to a random port */
1260 res = listen (sfd, 16);
1262 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1267 addrlen = sizeof (addr);
1268 memset (&addr, 0, sizeof (addr));
1269 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1270 g_assert (res == 0);
1272 host = (char*)"127.0.0.1";
1273 port = ntohs (addr.sin_port);
1275 /* Emit the address to stdout */
1276 /* FIXME: Should print another interface, not localhost */
1277 printf ("%s:%d\n", host, port);
1279 /* Listen on the provided address */
1280 for (rp = result; rp != NULL; rp = rp->ai_next) {
1283 sfd = socket (rp->ai_family, rp->ai_socktype,
1288 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1291 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
1295 res = listen (sfd, 16);
1304 * this function is not present on win2000 which we still support, and the
1305 * workaround described here:
1306 * http://msdn.microsoft.com/en-us/library/ms737931(VS.85).aspx
1307 * only works with MSVC.
1309 #ifdef HAVE_GETADDRINFO
1310 freeaddrinfo (result);
1315 if (agent_config.defer)
1318 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
1320 if (agent_config.timeout) {
1325 tv.tv_usec = agent_config.timeout * 1000;
1327 FD_SET (sfd, &readfds);
1328 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1330 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1335 conn_fd = socket_transport_accept (sfd);
1339 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
1342 #endif /* HAVE_GETADDRINFO */
1344 /* Connect to the specified address */
1345 #ifdef HAVE_GETADDRINFO
1346 /* FIXME: Respect the timeout */
1347 for (rp = result; rp != NULL; rp = rp->ai_next) {
1348 sfd = socket (rp->ai_family, rp->ai_socktype,
1353 if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
1354 break; /* Success */
1360 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1364 sfd = socket (result->h_addrtype, SOCK_STREAM, 0);
1366 g_assert_not_reached ();
1367 res = connect (sfd, (void*)result->h_addr_list [0], result->h_length);
1369 g_assert_not_reached ();
1375 /* See the comment above */
1376 #ifdef HAVE_GETADDRINFO
1377 freeaddrinfo (result);
1382 if (!transport_handshake ())
1387 socket_transport_close1 (void)
1389 /* This will interrupt the agent thread */
1390 /* Close the read part only so it can still send back replies */
1391 /* Also shut down the connection listener so that we can exit normally */
1393 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1394 shutdown (conn_fd, SD_BOTH);
1395 shutdown (listen_fd, SD_BOTH);
1396 closesocket (listen_fd);
1398 shutdown (conn_fd, SHUT_RD);
1399 shutdown (listen_fd, SHUT_RDWR);
1405 socket_transport_close2 (void)
1408 shutdown (conn_fd, SD_BOTH);
1410 shutdown (conn_fd, SHUT_RDWR);
1415 register_socket_transport (void)
1417 DebuggerTransport trans;
1419 trans.name = "dt_socket";
1420 trans.connect = socket_transport_connect;
1421 trans.close1 = socket_transport_close1;
1422 trans.close2 = socket_transport_close2;
1423 trans.send = socket_transport_send;
1424 trans.recv = socket_transport_recv;
1426 register_transport (&trans);
1429 #endif /* DISABLE_SOCKET_TRANSPORT */
1435 #define MAX_TRANSPORTS 16
1437 static DebuggerTransport *transport;
1439 static DebuggerTransport transports [MAX_TRANSPORTS];
1440 static int ntransports;
1443 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1446 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1448 register_transport (trans);
1452 register_transport (DebuggerTransport *trans)
1454 g_assert (ntransports < MAX_TRANSPORTS);
1456 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1461 transport_init (void)
1465 #ifndef DISABLE_SOCKET_TRANSPORT
1466 register_socket_transport ();
1469 for (i = 0; i < ntransports; ++i) {
1470 if (!strcmp (agent_config.transport, transports [i].name))
1473 if (i == ntransports) {
1474 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1475 for (i = 0; i < ntransports; ++i)
1476 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1477 fprintf (stderr, "\n");
1480 transport = &transports [i];
1484 transport_connect (const char *address)
1486 transport->connect (address);
1490 transport_close1 (void)
1492 transport->close1 ();
1496 transport_close2 (void)
1498 transport->close2 ();
1502 transport_send (void *buf, int len)
1504 return transport->send (buf, len);
1508 transport_recv (void *buf, int len)
1510 return transport->recv (buf, len);
1514 mono_debugger_agent_transport_handshake (void)
1516 return transport_handshake ();
1520 transport_handshake (void)
1522 char handshake_msg [128];
1526 disconnected = TRUE;
1528 /* Write handshake message */
1529 sprintf (handshake_msg, "DWP-Handshake");
1531 res = transport_send (handshake_msg, strlen (handshake_msg));
1532 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1533 g_assert (res != -1);
1536 res = transport_recv (buf, strlen (handshake_msg));
1537 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg) != 0))) {
1538 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1543 * To support older clients, the client sends its protocol version after connecting
1544 * using a command. Until that is received, default to our protocol version.
1546 major_version = MAJOR_VERSION;
1547 minor_version = MINOR_VERSION;
1548 protocol_version_set = FALSE;
1550 #ifndef DISABLE_SOCKET_TRANSPORT
1551 // FIXME: Move this somewhere else
1553 * Set TCP_NODELAY on the socket so the client receives events/command
1554 * results immediately.
1558 int result = setsockopt (conn_fd,
1563 g_assert (result >= 0);
1569 disconnected = FALSE;
1574 stop_debugger_thread (void)
1579 transport_close1 ();
1582 * Wait for the thread to exit.
1584 * If we continue with the shutdown without waiting for it, then the client might
1585 * not receive an answer to its last command like a resume.
1586 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
1589 //WaitForSingleObject (debugger_thread_handle, INFINITE);
1590 if (GetCurrentThreadId () != debugger_thread_id) {
1592 mono_mutex_lock (&debugger_thread_exited_mutex);
1593 if (!debugger_thread_exited) {
1595 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
1596 mono_mutex_unlock (&debugger_thread_exited_mutex);
1598 mono_mutex_lock (&debugger_thread_exited_mutex);
1601 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1604 mono_mutex_unlock (&debugger_thread_exited_mutex);
1605 } while (!debugger_thread_exited);
1608 transport_close2 ();
1612 start_debugger_thread (void)
1614 debugger_thread_handle = mono_threads_create_thread (debugger_thread, NULL, 0, 0, NULL);
1615 g_assert (debugger_thread_handle);
1619 * Functions to decode protocol data
1623 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1626 g_assert (*endbuf <= limit);
1631 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1634 g_assert (*endbuf <= limit);
1636 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1639 static inline gint64
1640 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1642 guint32 high = decode_int (buf, &buf, limit);
1643 guint32 low = decode_int (buf, &buf, limit);
1647 return ((((guint64)high) << 32) | ((guint64)low));
1651 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1653 return decode_int (buf, endbuf, limit);
1657 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1659 int len = decode_int (buf, &buf, limit);
1667 s = g_malloc (len + 1);
1670 memcpy (s, buf, len);
1679 * Functions to encode protocol data
1683 buffer_init (Buffer *buf, int size)
1685 buf->buf = g_malloc (size);
1687 buf->end = buf->buf + size;
1691 buffer_len (Buffer *buf)
1693 return buf->p - buf->buf;
1697 buffer_make_room (Buffer *buf, int size)
1699 if (buf->end - buf->p < size) {
1700 int new_size = buf->end - buf->buf + size + 32;
1701 guint8 *p = g_realloc (buf->buf, new_size);
1702 size = buf->p - buf->buf;
1705 buf->end = buf->buf + new_size;
1710 buffer_add_byte (Buffer *buf, guint8 val)
1712 buffer_make_room (buf, 1);
1718 buffer_add_short (Buffer *buf, guint32 val)
1720 buffer_make_room (buf, 2);
1721 buf->p [0] = (val >> 8) & 0xff;
1722 buf->p [1] = (val >> 0) & 0xff;
1727 buffer_add_int (Buffer *buf, guint32 val)
1729 buffer_make_room (buf, 4);
1730 buf->p [0] = (val >> 24) & 0xff;
1731 buf->p [1] = (val >> 16) & 0xff;
1732 buf->p [2] = (val >> 8) & 0xff;
1733 buf->p [3] = (val >> 0) & 0xff;
1738 buffer_add_long (Buffer *buf, guint64 l)
1740 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1741 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1745 buffer_add_id (Buffer *buf, int id)
1747 buffer_add_int (buf, (guint64)id);
1751 buffer_add_data (Buffer *buf, guint8 *data, int len)
1753 buffer_make_room (buf, len);
1754 memcpy (buf->p, data, len);
1759 buffer_add_string (Buffer *buf, const char *str)
1764 buffer_add_int (buf, 0);
1767 buffer_add_int (buf, len);
1768 buffer_add_data (buf, (guint8*)str, len);
1773 buffer_add_buffer (Buffer *buf, Buffer *data)
1775 buffer_add_data (buf, data->buf, buffer_len (data));
1779 buffer_free (Buffer *buf)
1785 send_packet (int command_set, int command, Buffer *data)
1791 id = InterlockedIncrement (&packet_id);
1793 len = data->p - data->buf + 11;
1794 buffer_init (&buf, len);
1795 buffer_add_int (&buf, len);
1796 buffer_add_int (&buf, id);
1797 buffer_add_byte (&buf, 0); /* flags */
1798 buffer_add_byte (&buf, command_set);
1799 buffer_add_byte (&buf, command);
1800 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1802 res = transport_send (buf.buf, len);
1810 send_reply_packets (int npackets, ReplyPacket *packets)
1817 for (i = 0; i < npackets; ++i)
1818 len += buffer_len (packets [i].data) + 11;
1819 buffer_init (&buf, len);
1820 for (i = 0; i < npackets; ++i) {
1821 buffer_add_int (&buf, buffer_len (packets [i].data) + 11);
1822 buffer_add_int (&buf, packets [i].id);
1823 buffer_add_byte (&buf, 0x80); /* flags */
1824 buffer_add_byte (&buf, (packets [i].error >> 8) & 0xff);
1825 buffer_add_byte (&buf, packets [i].error);
1826 buffer_add_buffer (&buf, packets [i].data);
1828 res = transport_send (buf.buf, len);
1836 send_reply_packet (int id, int error, Buffer *data)
1840 memset (&packet, 0, sizeof (ReplyPacket));
1842 packet.error = error;
1845 return send_reply_packets (1, &packet);
1849 send_buffered_reply_packets (void)
1853 send_reply_packets (nreply_packets, reply_packets);
1854 for (i = 0; i < nreply_packets; ++i)
1855 buffer_free (reply_packets [i].data);
1856 DEBUG (1, fprintf (log_file, "[dbg] Sent %d buffered reply packets [at=%lx].\n", nreply_packets, (long)mono_100ns_ticks () / 10000));
1861 buffer_reply_packet (int id, int error, Buffer *data)
1865 if (nreply_packets == 128)
1866 send_buffered_reply_packets ();
1868 p = &reply_packets [nreply_packets];
1871 p->data = g_new0 (Buffer, 1);
1872 buffer_init (p->data, buffer_len (data));
1873 buffer_add_buffer (p->data, data);
1882 * Represents an object accessible by the debugger client.
1885 /* Unique id used in the wire protocol to refer to objects */
1888 * A weakref gc handle pointing to the object. The gc handle is used to
1889 * detect if the object was garbage collected.
1894 /* Maps objid -> ObjRef */
1895 static GHashTable *objrefs;
1898 free_objref (gpointer value)
1902 mono_gchandle_free (o->handle);
1910 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1914 objrefs_cleanup (void)
1916 g_hash_table_destroy (objrefs);
1920 static GHashTable *obj_to_objref;
1921 static MonoGHashTable *suspended_objs;
1924 * Return an ObjRef for OBJ.
1927 get_objref (MonoObject *obj)
1930 GSList *reflist = NULL, *l;
1936 mono_loader_lock ();
1938 if (!obj_to_objref) {
1939 obj_to_objref = g_hash_table_new (NULL, NULL);
1940 suspended_objs = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
1941 MONO_GC_REGISTER_ROOT_FIXED (suspended_objs);
1944 if (suspend_count) {
1946 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1948 mono_g_hash_table_insert (suspended_objs, obj, NULL);
1951 /* FIXME: The tables can grow indefinitely */
1953 if (mono_gc_is_moving ()) {
1955 * Objects can move, so use a hash table mapping hash codes to lists of
1956 * ObjRef structures.
1958 hash = mono_object_hash (obj);
1960 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1961 for (l = reflist; l; l = l->next) {
1963 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1964 mono_loader_unlock ();
1969 /* Use a hash table with masked pointers to internalize object references */
1970 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1971 /* ref might refer to a different object with the same addr which was GCd */
1972 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1973 mono_loader_unlock ();
1978 ref = g_new0 (ObjRef, 1);
1979 ref->id = InterlockedIncrement (&objref_id);
1980 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1982 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
1984 if (mono_gc_is_moving ()) {
1985 reflist = g_slist_append (reflist, ref);
1986 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
1988 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
1991 mono_loader_unlock ();
1997 true_pred (gpointer key, gpointer value, gpointer user_data)
2003 clear_suspended_objs (void)
2005 mono_loader_lock ();
2006 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
2007 mono_loader_unlock ();
2011 get_objid (MonoObject *obj)
2013 return get_objref (obj)->id;
2017 * Set OBJ to the object identified by OBJID.
2018 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
2022 get_object_allow_null (int objid, MonoObject **obj)
2032 return ERR_INVALID_OBJECT;
2034 mono_loader_lock ();
2036 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
2039 *obj = mono_gchandle_get_target (ref->handle);
2040 mono_loader_unlock ();
2042 return ERR_INVALID_OBJECT;
2045 mono_loader_unlock ();
2046 return ERR_INVALID_OBJECT;
2051 get_object (int objid, MonoObject **obj)
2053 int err = get_object_allow_null (objid, obj);
2058 return ERR_INVALID_OBJECT;
2063 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
2065 return decode_id (buf, endbuf, limit);
2069 buffer_add_objid (Buffer *buf, MonoObject *o)
2071 buffer_add_id (buf, get_objid (o));
2090 * Represents a runtime structure accessible to the debugger client
2093 /* Unique id used in the wire protocol */
2095 /* Domain of the runtime structure, NULL if the domain was unloaded */
2102 MonoAssembly *assembly;
2103 MonoClassField *field;
2105 MonoProperty *property;
2110 /* Maps runtime structure -> Id */
2111 GHashTable *val_to_id [ID_NUM];
2112 /* Classes whose class load event has been sent */
2113 GHashTable *loaded_classes;
2114 /* Maps MonoClass->GPtrArray of file names */
2115 GHashTable *source_files;
2116 /* Maps source file basename -> GSList of classes */
2117 GHashTable *source_file_to_class;
2118 /* Same with ignore-case */
2119 GHashTable *source_file_to_class_ignorecase;
2123 static GPtrArray *ids [ID_NUM];
2130 for (i = 0; i < ID_NUM; ++i)
2131 ids [i] = g_ptr_array_new ();
2139 for (i = 0; i < ID_NUM; ++i) {
2141 for (j = 0; j < ids [i]->len; ++j)
2142 g_free (g_ptr_array_index (ids [i], j));
2143 g_ptr_array_free (ids [i], TRUE);
2150 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2152 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
2154 GHashTableIter iter;
2155 GPtrArray *file_names;
2160 for (i = 0; i < ID_NUM; ++i)
2161 if (info->val_to_id [i])
2162 g_hash_table_destroy (info->val_to_id [i]);
2163 g_hash_table_destroy (info->loaded_classes);
2165 g_hash_table_iter_init (&iter, info->source_files);
2166 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2167 for (i = 0; i < file_names->len; ++i)
2168 g_free (g_ptr_array_index (file_names, i));
2169 g_ptr_array_free (file_names, TRUE);
2172 g_hash_table_iter_init (&iter, info->source_file_to_class);
2173 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2178 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2179 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2187 domain_jit_info (domain)->agent_info = NULL;
2189 /* Clear ids referencing structures in the domain */
2190 for (i = 0; i < ID_NUM; ++i) {
2192 for (j = 0; j < ids [i]->len; ++j) {
2193 Id *id = g_ptr_array_index (ids [i], j);
2194 if (id->domain == domain)
2200 mono_loader_lock ();
2201 g_hash_table_remove (domains, domain);
2202 mono_loader_unlock ();
2205 static AgentDomainInfo*
2206 get_agent_domain_info (MonoDomain *domain)
2208 AgentDomainInfo *info = NULL;
2210 mono_domain_lock (domain);
2212 info = domain_jit_info (domain)->agent_info;
2214 info = domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
2215 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2216 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2217 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2218 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2221 mono_domain_unlock (domain);
2227 get_id (MonoDomain *domain, IdType type, gpointer val)
2230 AgentDomainInfo *info;
2235 mono_loader_lock ();
2237 mono_domain_lock (domain);
2239 info = get_agent_domain_info (domain);
2241 if (info->val_to_id [type] == NULL)
2242 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2244 id = g_hash_table_lookup (info->val_to_id [type], val);
2246 mono_domain_unlock (domain);
2247 mono_loader_unlock ();
2251 id = g_new0 (Id, 1);
2253 id->id = ids [type]->len + 1;
2254 id->domain = domain;
2257 g_hash_table_insert (info->val_to_id [type], val, id);
2259 mono_domain_unlock (domain);
2261 g_ptr_array_add (ids [type], id);
2263 mono_loader_unlock ();
2268 static inline gpointer
2269 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
2273 int id = decode_id (buf, endbuf, limit);
2282 // FIXME: error handling
2283 mono_loader_lock ();
2284 g_assert (id > 0 && id <= ids [type]->len);
2286 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2287 mono_loader_unlock ();
2289 if (res->domain == NULL) {
2290 DEBUG (0, fprintf (log_file, "ERR_UNLOADED, id=%d, type=%d.\n", id, type));
2291 *err = ERR_UNLOADED;
2296 *domain = res->domain;
2298 return res->data.val;
2302 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2304 int id = get_id (domain, type, val);
2306 buffer_add_id (buf, id);
2310 static inline MonoClass*
2311 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2315 klass = decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2316 if (G_UNLIKELY (log_level >= 2) && klass) {
2319 s = mono_type_full_name (&klass->byval_arg);
2320 DEBUG(2, fprintf (log_file, "[dbg] recv class [%s]\n", s));
2326 static inline MonoAssembly*
2327 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2329 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2332 static inline MonoImage*
2333 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2335 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2338 static inline MonoMethod*
2339 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2343 m = decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2344 if (G_UNLIKELY (log_level >= 2) && m) {
2347 s = mono_method_full_name (m, TRUE);
2348 DEBUG(2, fprintf (log_file, "[dbg] recv method [%s]\n", s));
2354 static inline MonoClassField*
2355 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2357 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2360 static inline MonoDomain*
2361 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2363 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2366 static inline MonoProperty*
2367 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2369 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2373 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2375 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2376 if (G_UNLIKELY (log_level >= 2) && klass) {
2379 s = mono_type_full_name (&klass->byval_arg);
2380 if (GetCurrentThreadId () == debugger_thread_id)
2381 DEBUG(2, fprintf (log_file, "[dbg] send class [%s]\n", s));
2383 DEBUG(2, fprintf (log_file, "[%p] send class [%s]\n", (gpointer)GetCurrentThreadId (), s));
2389 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2391 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2392 if (G_UNLIKELY (log_level >= 2) && method) {
2395 s = mono_method_full_name (method, 1);
2396 DEBUG(2, fprintf (log_file, "[dbg] send method [%s]\n", s));
2402 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2406 id = buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2407 if (G_UNLIKELY (log_level >= 2) && assembly)
2408 DEBUG(2, fprintf (log_file, "[dbg] send assembly [%s][%s][%d]\n", assembly->aname.name, domain->friendly_name, id));
2412 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2414 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2418 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2420 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2424 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2426 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2430 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2432 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2435 static void invoke_method (void);
2442 * save_thread_context:
2444 * Set CTX as the current threads context which is used for computing stack traces.
2445 * This function is signal-safe.
2448 save_thread_context (MonoContext *ctx)
2450 DebuggerTlsData *tls;
2452 tls = mono_native_tls_get_value (debugger_tls_id);
2456 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2458 mono_thread_state_init_from_current (&tls->context);
2461 /* Number of threads suspended */
2463 * If this is equal to the size of thread_to_tls, the runtime is considered
2466 static gint32 threads_suspend_count;
2468 static mono_mutex_t suspend_mutex;
2470 /* Cond variable used to wait for suspend_count becoming 0 */
2471 static mono_cond_t suspend_cond;
2473 /* Semaphore used to wait for a thread becoming suspended */
2474 static MonoSemType suspend_sem;
2479 mono_mutex_init (&suspend_mutex);
2480 mono_cond_init (&suspend_cond, NULL);
2481 MONO_SEM_INIT (&suspend_sem, 0);
2486 StackFrameInfo last_frame;
2487 gboolean last_frame_set;
2490 } GetLastFrameUserData;
2493 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2495 GetLastFrameUserData *data = user_data;
2497 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
2500 if (!data->last_frame_set) {
2501 /* Store the last frame */
2502 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2503 data->last_frame_set = TRUE;
2506 /* Store the context/lmf for the frame above the last frame */
2507 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2508 data->lmf = info->lmf;
2516 * Process interruption of a thread. If SIGCTX is set, process the current thread. If
2517 * INFO is set, process the thread described by INFO.
2518 * This should be signal safe.
2521 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, void *sigctx, MonoJitInfo *ji)
2525 MonoNativeThreadId tid;
2528 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2529 * guarantee the signal handler will be called that many times. Instead of tracking
2530 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2531 * has been requested that hasn't been handled yet, otherwise we can have threads
2532 * refuse to die when VM_EXIT is called
2534 #if defined(__APPLE__)
2535 if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
2539 * We use interrupt_count to determine whenever this interrupt should be processed
2540 * by us or the normal interrupt processing code in the signal handler.
2541 * There is no race here with notify_thread (), since the signal is sent after
2542 * incrementing interrupt_count.
2544 if (tls->interrupt_count == 0)
2547 InterlockedDecrement (&tls->interrupt_count);
2551 ip = mono_arch_ip_from_context (sigctx);
2553 ip = MONO_CONTEXT_GET_IP (&info->suspend_state.ctx);
2558 tid = mono_thread_info_get_tid (info);
2560 tid = (MonoNativeThreadId)GetCurrentThreadId ();
2562 // FIXME: Races when the thread leaves managed code before hitting a single step
2566 /* Running managed code, will be suspended by the single step code */
2567 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip));
2571 * Running native code, will be suspended when it returns to/enters
2572 * managed code. Treat it as already suspended.
2573 * This might interrupt the code in process_single_step_inner (), we use the
2574 * tls->suspending flag to avoid races when that happens.
2576 if (!tls->suspended && !tls->suspending) {
2578 GetLastFrameUserData data;
2580 // FIXME: printf is not signal safe, but this is only used during
2581 // debugger debugging
2583 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip));
2584 //save_thread_context (&ctx);
2587 /* Already terminated */
2591 * We are in a difficult position: we want to be able to provide stack
2592 * traces for this thread, but we can't use the current ctx+lmf, since
2593 * the thread is still running, so it might return to managed code,
2594 * making these invalid.
2595 * So we start a stack walk and save the first frame, along with the
2596 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2597 * suspended when it returns to managed code, so the parent's ctx should
2600 data.last_frame_set = FALSE;
2602 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
2604 * Don't pass MONO_UNWIND_ACTUAL_METHOD, its not signal safe, and
2605 * get_last_frame () doesn't need it, the last frame cannot be a ginst
2606 * since we are not in a JITted method.
2608 mono_walk_stack_with_ctx (get_last_frame, &ctx, MONO_UNWIND_NONE, &data);
2610 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, &info->suspend_state, MONO_UNWIND_SIGNAL_SAFE, &data);
2612 if (data.last_frame_set) {
2613 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2614 res = mono_thread_state_init_from_monoctx (&tls->async_state, &ctx);
2616 mono_thread_state_init_from_monoctx (&tls->context, &ctx);
2619 memcpy (&tls->async_state.ctx, &data.ctx, sizeof (MonoContext));
2620 tls->async_state.unwind_data [MONO_UNWIND_DATA_LMF] = data.lmf;
2621 tls->async_state.unwind_data [MONO_UNWIND_DATA_JIT_TLS] = tls->thread->jit_data;
2623 tls->async_state.valid = FALSE;
2626 mono_memory_barrier ();
2628 tls->suspended = TRUE;
2629 MONO_SEM_POST (&suspend_sem);
2636 * mono_debugger_agent_thread_interrupt:
2638 * Called by the abort signal handler.
2639 * Should be signal safe.
2642 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
2644 DebuggerTlsData *tls;
2649 tls = mono_native_tls_get_value (debugger_tls_id);
2651 DEBUG (1, fprintf (log_file, "[%p] Received interrupt with no TLS, continuing.\n", (gpointer)GetCurrentThreadId ()));
2655 return thread_interrupt (tls, NULL, sigctx, ji);
2659 static void CALLBACK notify_thread_apc (ULONG_PTR param)
2662 mono_debugger_agent_thread_interrupt (NULL, NULL);
2664 #endif /* HOST_WIN32 */
2667 * reset_native_thread_suspend_state:
2669 * Reset the suspended flag and state on native threads
2672 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2674 DebuggerTlsData *tls = value;
2676 if (!tls->really_suspended && tls->suspended) {
2677 tls->suspended = FALSE;
2679 * The thread might still be running if it was executing native code, so the state won't be invalided by
2680 * suspend_current ().
2682 tls->context.valid = FALSE;
2683 tls->async_state.valid = FALSE;
2684 invalidate_frames (tls);
2691 * Notify a thread that it needs to suspend.
2694 notify_thread (gpointer key, gpointer value, gpointer user_data)
2696 MonoInternalThread *thread = key;
2697 DebuggerTlsData *tls = value;
2698 gsize tid = thread->tid;
2701 if (GetCurrentThreadId () == tid || tls->terminated)
2704 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2707 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2708 * guarantee the signal handler will be called that many times. Instead of tracking
2709 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2710 * has been requested that hasn't been handled yet, otherwise we can have threads
2711 * refuse to die when VM_EXIT is called
2713 #if defined(__APPLE__)
2714 if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
2718 * Maybe we could use the normal interrupt infrastructure, but that does a lot
2719 * of things like breaking waits etc. which we don't want.
2721 InterlockedIncrement (&tls->interrupt_count);
2724 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2726 QueueUserAPC (notify_thread_apc, thread->handle, NULL);
2728 if (mono_thread_info_new_interrupt_enabled ()) {
2729 MonoThreadInfo *info;
2732 info = mono_thread_info_safe_suspend_sync ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE);
2734 DEBUG(1, fprintf (log_file, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2736 * Attached thread which died without detaching.
2738 tls->terminated = TRUE;
2740 ji = mono_jit_info_table_find (info->suspend_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], MONO_CONTEXT_GET_IP (&info->suspend_state.ctx));
2742 thread_interrupt (tls, info, NULL, ji);
2744 mono_thread_info_finish_suspend_and_resume (info);
2747 res = mono_thread_kill (thread, mono_thread_get_abort_signal ());
2749 DEBUG(1, fprintf (log_file, "[%p] mono_thread_kill () failed for %p: %d...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid, res));
2751 * Attached thread which died without detaching.
2753 tls->terminated = TRUE;
2760 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2762 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2766 if (mono_loader_lock_is_owned_by_self ()) {
2768 * Shortcut for the check in suspend_current (). This speeds up processing
2769 * when executing long running code inside the loader lock, i.e. assembly load
2775 if (debugger_thread_id == GetCurrentThreadId ())
2778 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2779 if (suspend_count - tls->resume_count > 0)
2780 tls->suspending = TRUE;
2782 DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2784 if (suspend_count - tls->resume_count == 0) {
2786 * We are executing a single threaded invoke but the single step for
2787 * suspending is still active.
2788 * FIXME: This slows down single threaded invokes.
2790 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
2794 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2796 /* Can't suspend in these methods */
2797 method = jinfo_get_method (ji);
2798 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2801 save_thread_context (ctx);
2809 * Increase the suspend count of the VM. While the suspend count is greater
2810 * than 0, runtime threads are suspended at certain points during execution.
2815 mono_loader_lock ();
2817 mono_mutex_lock (&suspend_mutex);
2821 DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
2823 if (suspend_count == 1) {
2824 // FIXME: Is it safe to call this inside the lock ?
2825 start_single_stepping ();
2826 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2829 mono_mutex_unlock (&suspend_mutex);
2831 if (suspend_count == 1)
2833 * Suspend creation of new threadpool threads, since they cannot run
2835 mono_thread_pool_suspend ();
2837 mono_loader_unlock ();
2843 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2851 g_assert (debugger_thread_id == GetCurrentThreadId ());
2853 mono_loader_lock ();
2855 mono_mutex_lock (&suspend_mutex);
2857 g_assert (suspend_count > 0);
2860 DEBUG(1, fprintf (log_file, "[%p] Resuming vm, suspend count=%d...\n", (gpointer)GetCurrentThreadId (), suspend_count));
2862 if (suspend_count == 0) {
2863 // FIXME: Is it safe to call this inside the lock ?
2864 stop_single_stepping ();
2865 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2868 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2869 err = mono_cond_broadcast (&suspend_cond);
2870 g_assert (err == 0);
2872 mono_mutex_unlock (&suspend_mutex);
2873 //g_assert (err == 0);
2875 if (suspend_count == 0)
2876 mono_thread_pool_resume ();
2878 mono_loader_unlock ();
2884 * Resume just one thread.
2887 resume_thread (MonoInternalThread *thread)
2890 DebuggerTlsData *tls;
2892 g_assert (debugger_thread_id == GetCurrentThreadId ());
2894 mono_loader_lock ();
2896 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2899 mono_mutex_lock (&suspend_mutex);
2901 g_assert (suspend_count > 0);
2903 DEBUG(1, fprintf (log_file, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid));
2905 tls->resume_count += suspend_count;
2908 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2909 * but only the one whose resume_count field is > 0 will be resumed.
2911 err = mono_cond_broadcast (&suspend_cond);
2912 g_assert (err == 0);
2914 mono_mutex_unlock (&suspend_mutex);
2915 //g_assert (err == 0);
2917 mono_loader_unlock ();
2921 invalidate_frames (DebuggerTlsData *tls)
2926 tls = mono_native_tls_get_value (debugger_tls_id);
2929 for (i = 0; i < tls->frame_count; ++i) {
2930 if (tls->frames [i]->jit)
2931 mono_debug_free_method_jit_info (tls->frames [i]->jit);
2932 g_free (tls->frames [i]);
2934 g_free (tls->frames);
2935 tls->frame_count = 0;
2942 * Suspend the current thread until the runtime is resumed. If the thread has a
2943 * pending invoke, then the invoke is executed before this function returns.
2946 suspend_current (void)
2949 DebuggerTlsData *tls;
2951 g_assert (debugger_thread_id != GetCurrentThreadId ());
2953 if (mono_loader_lock_is_owned_by_self ()) {
2955 * If we own the loader mutex, can't suspend until we release it, since the
2956 * whole runtime can deadlock otherwise.
2961 tls = mono_native_tls_get_value (debugger_tls_id);
2964 mono_mutex_lock (&suspend_mutex);
2966 tls->suspending = FALSE;
2967 tls->really_suspended = TRUE;
2969 if (!tls->suspended) {
2970 tls->suspended = TRUE;
2971 MONO_SEM_POST (&suspend_sem);
2974 DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
2976 while (suspend_count - tls->resume_count > 0) {
2978 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
2980 mono_mutex_unlock (&suspend_mutex);
2982 mono_mutex_lock (&suspend_mutex);
2988 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
2989 g_assert (err == 0);
2993 tls->suspended = FALSE;
2994 tls->really_suspended = FALSE;
2996 threads_suspend_count --;
2998 mono_mutex_unlock (&suspend_mutex);
3000 DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
3002 if (tls->pending_invoke) {
3003 /* Save the original context */
3004 tls->pending_invoke->has_ctx = TRUE;
3005 tls->pending_invoke->ctx = tls->context.ctx;
3010 /* The frame info becomes invalid after a resume */
3011 tls->context.valid = FALSE;
3012 tls->async_state.valid = FALSE;
3013 invalidate_frames (tls);
3017 count_thread (gpointer key, gpointer value, gpointer user_data)
3019 DebuggerTlsData *tls = value;
3021 if (!tls->suspended && !tls->terminated)
3022 *(int*)user_data = *(int*)user_data + 1;
3026 count_threads_to_wait_for (void)
3030 mono_loader_lock ();
3031 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
3032 mono_loader_unlock ();
3040 * Wait until the runtime is completely suspended.
3043 wait_for_suspend (void)
3045 int nthreads, nwait, err;
3046 gboolean waited = FALSE;
3048 // FIXME: Threads starting/stopping ?
3049 mono_loader_lock ();
3050 nthreads = mono_g_hash_table_size (thread_to_tls);
3051 mono_loader_unlock ();
3054 nwait = count_threads_to_wait_for ();
3056 DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
3057 err = MONO_SEM_WAIT (&suspend_sem);
3058 g_assert (err == 0);
3066 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
3072 * Return whenever the runtime is suspended.
3077 return count_threads_to_wait_for () == 0;
3080 static MonoSeqPointInfo*
3081 get_seq_points (MonoDomain *domain, MonoMethod *method)
3083 MonoSeqPointInfo *seq_points;
3085 mono_domain_lock (domain);
3086 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
3087 if (!seq_points && method->is_inflated) {
3088 /* generic sharing + aot */
3089 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (method));
3091 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mini_get_shared_method (method));
3093 mono_domain_unlock (domain);
3099 no_seq_points_found (MonoMethod *method)
3102 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3104 printf ("Unable to find seq points for method '%s'.\n", mono_method_full_name (method, TRUE));
3108 * find_next_seq_point_for_native_offset:
3110 * Find the first sequence point after NATIVE_OFFSET.
3113 find_next_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
3115 MonoSeqPointInfo *seq_points;
3118 seq_points = get_seq_points (domain, method);
3124 g_assert (seq_points);
3128 for (i = 0; i < seq_points->len; ++i) {
3129 if (seq_points->seq_points [i].native_offset >= native_offset)
3130 return &seq_points->seq_points [i];
3137 * find_prev_seq_point_for_native_offset:
3139 * Find the first sequence point before NATIVE_OFFSET.
3142 find_prev_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
3144 MonoSeqPointInfo *seq_points;
3147 seq_points = get_seq_points (domain, method);
3153 for (i = seq_points->len - 1; i >= 0; --i) {
3154 if (seq_points->seq_points [i].native_offset <= native_offset)
3155 return &seq_points->seq_points [i];
3164 * Find the sequence point corresponding to the IL offset IL_OFFSET, which
3165 * should be the location of a sequence point.
3167 static G_GNUC_UNUSED SeqPoint*
3168 find_seq_point (MonoDomain *domain, MonoMethod *method, gint32 il_offset, MonoSeqPointInfo **info)
3170 MonoSeqPointInfo *seq_points;
3175 seq_points = get_seq_points (domain, method);
3180 for (i = 0; i < seq_points->len; ++i) {
3181 if (seq_points->seq_points [i].il_offset == il_offset)
3182 return &seq_points->seq_points [i];
3189 DebuggerTlsData *tls;
3191 } ComputeFramesUserData;
3194 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3196 ComputeFramesUserData *ud = user_data;
3198 MonoMethod *method, *actual_method, *api_method;
3202 if (info->type != FRAME_TYPE_MANAGED) {
3203 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3204 /* Mark the last frame as an invoke frame */
3206 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3212 method = jinfo_get_method (info->ji);
3214 method = info->method;
3215 actual_method = info->actual_method;
3216 api_method = method;
3221 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3224 if (info->il_offset == -1) {
3225 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3226 if (ud->frames == NULL) {
3227 sp = find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL);
3229 info->il_offset = sp->il_offset;
3231 if (info->il_offset == -1)
3232 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3235 DEBUG (1, fprintf (log_file, "\tFrame: %s:%x(%x) %d\n", mono_method_full_name (method, TRUE), info->il_offset, info->native_offset, info->managed));
3237 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3238 if (!CHECK_PROTOCOL_VERSION (2, 17))
3239 /* Older clients can't handle this flag */
3241 api_method = mono_marshal_method_from_wrapper (method);
3244 actual_method = api_method;
3245 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3248 frame = g_new0 (StackFrame, 1);
3249 frame->method = method;
3250 frame->actual_method = actual_method;
3251 frame->api_method = api_method;
3252 frame->il_offset = info->il_offset;
3253 frame->native_offset = info->native_offset;
3254 frame->flags = flags;
3255 frame->ji = info->ji;
3256 if (info->reg_locations)
3257 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3260 frame->has_ctx = TRUE;
3262 frame->domain = info->domain;
3264 ud->frames = g_slist_append (ud->frames, frame);
3270 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3272 ComputeFramesUserData *ud = user_data;
3275 * 'tls->filter_ctx' is the location of the throw site.
3277 * mono_walk_stack() will never actually hit the throw site, but unwind
3278 * directly from the filter to the call site; we abort stack unwinding here
3279 * once this happens and resume from the throw site.
3282 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3285 return process_frame (info, ctx, user_data);
3289 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3291 ComputeFramesUserData user_data;
3293 int i, findex, new_frame_count;
3294 StackFrame **new_frames, *f;
3295 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3297 // FIXME: Locking on tls
3298 if (tls->frames && tls->frames_up_to_date)
3301 DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
3303 user_data.tls = tls;
3304 user_data.frames = NULL;
3305 if (tls->terminated) {
3306 tls->frame_count = 0;
3308 } if (!tls->really_suspended && tls->async_state.valid) {
3309 /* Have to use the state saved by the signal handler */
3310 process_frame (&tls->async_last_frame, NULL, &user_data);
3311 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3312 } else if (tls->filter_state.valid) {
3314 * We are inside an exception filter.
3316 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3318 if (tls->context.valid)
3319 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3321 * After that, we resume unwinding from the location where the exception has been thrown.
3323 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3324 } else if (tls->context.valid) {
3325 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3328 tls->frame_count = 0;
3332 new_frame_count = g_slist_length (user_data.frames);
3333 new_frames = g_new0 (StackFrame*, new_frame_count);
3335 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3339 * Reuse the id for already existing stack frames, so invokes don't invalidate
3340 * the still valid stack frames.
3342 for (i = 0; i < tls->frame_count; ++i) {
3343 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3344 f->id = tls->frames [i]->id;
3349 if (i >= tls->frame_count)
3350 f->id = InterlockedIncrement (&frame_id);
3352 new_frames [findex ++] = f;
3355 g_slist_free (user_data.frames);
3357 invalidate_frames (tls);
3359 tls->frames = new_frames;
3360 tls->frame_count = new_frame_count;
3361 tls->frames_up_to_date = TRUE;
3365 * GHFunc to emit an appdomain creation event
3366 * @param key Don't care
3367 * @param value A loaded appdomain
3368 * @param user_data Don't care
3371 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3373 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3374 g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
3378 * GHFunc to emit a thread start event
3379 * @param key A thread id
3380 * @param value A thread object
3381 * @param user_data Don't care
3384 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3386 if (GPOINTER_TO_INT (key) != debugger_thread_id)
3387 process_profiler_event (EVENT_KIND_THREAD_START, value);
3391 * GFunc to emit an assembly load event
3392 * @param value A loaded assembly
3393 * @param user_data Don't care
3396 emit_assembly_load (gpointer value, gpointer user_data)
3398 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3402 * GFunc to emit a type load event
3403 * @param value A loaded type
3404 * @param user_data Don't care
3407 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3409 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3413 strdup_tolower (char *s)
3418 for (p = s2; *p; ++p)
3428 * create_event_list:
3430 * Return a list of event request ids matching EVENT, starting from REQS, which
3431 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3433 * We return request ids, instead of requests, to simplify threading, since
3434 * requests could be deleted anytime when the loader lock is not held.
3435 * LOCKING: Assumes the loader lock is held.
3438 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3441 GSList *events = NULL;
3443 *suspend_policy = SUSPEND_POLICY_NONE;
3446 reqs = event_requests;
3451 for (i = 0; i < reqs->len; ++i) {
3452 EventRequest *req = g_ptr_array_index (reqs, i);
3453 if (req->event_kind == event) {
3454 gboolean filtered = FALSE;
3457 for (j = 0; j < req->nmodifiers; ++j) {
3458 Modifier *mod = &req->modifiers [j];
3460 if (mod->kind == MOD_KIND_COUNT) {
3462 if (mod->data.count > 0) {
3463 if (mod->data.count > 0) {
3465 if (mod->data.count == 0)
3469 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3470 if (mod->data.thread != mono_thread_internal_current ())
3472 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3473 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3475 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3477 if (ei->caught && !mod->caught)
3479 if (!ei->caught && !mod->uncaught)
3481 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3483 gboolean found = FALSE;
3484 MonoAssembly **assemblies = mod->data.assemblies;
3487 for (k = 0; assemblies [k]; ++k)
3488 if (assemblies [k] == jinfo_get_method (ji)->klass->image->assembly)
3493 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3494 gpointer iter = NULL;
3496 MonoDebugSourceInfo *sinfo;
3497 char *source_file, *s;
3498 gboolean found = FALSE;
3500 GPtrArray *source_file_list;
3502 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3503 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3506 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
3507 for (i = 0; i < source_file_list->len; ++i) {
3508 sinfo = g_ptr_array_index (source_file_list, i);
3510 * Do a case-insesitive match by converting the file name to
3513 s = strdup_tolower (sinfo->source_file);
3514 if (g_hash_table_lookup (mod->data.source_files, s))
3517 char *s2 = g_path_get_basename (sinfo->source_file);
3518 char *s3 = strdup_tolower (s2);
3520 if (g_hash_table_lookup (mod->data.source_files, s3))
3527 g_ptr_array_free (source_file_list, TRUE);
3532 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3535 s = mono_type_full_name (&ei->klass->byval_arg);
3536 if (!g_hash_table_lookup (mod->data.type_names, s))
3539 } else if (mod->kind == MOD_KIND_STEP) {
3540 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3541 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3542 !strcmp (jinfo_get_method (ji)->name, ".cctor"))
3544 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3545 MonoCustomAttrInfo *ainfo;
3546 static MonoClass *klass;
3549 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3552 if (!ji->dbg_hidden_inited) {
3553 ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji));
3555 if (mono_custom_attrs_has_attr (ainfo, klass))
3556 ji->dbg_hidden = TRUE;
3557 mono_custom_attrs_free (ainfo);
3559 ji->dbg_hidden_inited = TRUE;
3564 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3565 MonoCustomAttrInfo *ainfo;
3566 static MonoClass *klass;
3569 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3572 if (!ji->dbg_step_through_inited) {
3573 ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji));
3575 if (mono_custom_attrs_has_attr (ainfo, klass))
3576 ji->dbg_step_through = TRUE;
3577 mono_custom_attrs_free (ainfo);
3579 ainfo = mono_custom_attrs_from_class (jinfo_get_method (ji)->klass);
3581 if (mono_custom_attrs_has_attr (ainfo, klass))
3582 ji->dbg_step_through = TRUE;
3583 mono_custom_attrs_free (ainfo);
3585 ji->dbg_step_through_inited = TRUE;
3587 if (ji->dbg_step_through)
3590 if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3591 MonoCustomAttrInfo *ainfo;
3592 static MonoClass *klass;
3595 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute");
3598 if (!ji->dbg_non_user_code_inited) {
3599 ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji));
3601 if (mono_custom_attrs_has_attr (ainfo, klass))
3602 ji->dbg_non_user_code = TRUE;
3603 mono_custom_attrs_free (ainfo);
3605 ainfo = mono_custom_attrs_from_class (jinfo_get_method (ji)->klass);
3607 if (mono_custom_attrs_has_attr (ainfo, klass))
3608 ji->dbg_non_user_code = TRUE;
3609 mono_custom_attrs_free (ainfo);
3611 ji->dbg_non_user_code_inited = TRUE;
3613 if (ji->dbg_non_user_code)
3620 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3621 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3626 /* Send a VM START/DEATH event by default */
3627 if (event == EVENT_KIND_VM_START)
3628 events = g_slist_append (events, GINT_TO_POINTER (0));
3629 if (event == EVENT_KIND_VM_DEATH)
3630 events = g_slist_append (events, GINT_TO_POINTER (0));
3635 static G_GNUC_UNUSED const char*
3636 event_to_string (EventKind event)
3639 case EVENT_KIND_VM_START: return "VM_START";
3640 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3641 case EVENT_KIND_THREAD_START: return "THREAD_START";
3642 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3643 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3644 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3645 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3646 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3647 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3648 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3649 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3650 case EVENT_KIND_STEP: return "STEP";
3651 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3652 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3653 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3654 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3655 case EVENT_KIND_USER_LOG: return "USER_LOG";
3657 g_assert_not_reached ();
3665 * Send an event to the client, suspending the vm if needed.
3666 * LOCKING: Since this can suspend the calling thread, no locks should be held
3668 * The EVENTS list is freed by this function.
3671 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3675 MonoDomain *domain = mono_domain_get ();
3676 MonoThread *thread = NULL;
3677 MonoObject *keepalive_obj = NULL;
3678 gboolean send_success = FALSE;
3683 DEBUG (2, fprintf (log_file, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event)));
3687 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3688 // FIXME: We miss those events
3689 DEBUG (2, fprintf (log_file, "VM start event not sent yet: dropping %s\n", event_to_string (event)));
3693 if (vm_death_event_sent) {
3694 DEBUG (2, fprintf (log_file, "VM death event has been sent: dropping %s\n", event_to_string (event)));
3698 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3699 DEBUG (2, fprintf (log_file, "Mono runtime is shutting down: dropping %s\n", event_to_string (event)));
3704 DEBUG (2, fprintf (log_file, "Debugger client is not connected: dropping %s\n", event_to_string (event)));
3708 if (event == EVENT_KIND_KEEPALIVE)
3709 suspend_policy = SUSPEND_POLICY_NONE;
3714 if (agent_config.defer) {
3715 /* Make sure the thread id is always set when doing deferred debugging */
3716 if (debugger_thread_id == GetCurrentThreadId ()) {
3717 /* Don't suspend on events from the debugger thread */
3718 suspend_policy = SUSPEND_POLICY_NONE;
3719 thread = mono_thread_get_main ();
3721 else thread = mono_thread_current ();
3723 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3724 // FIXME: Send these with a NULL thread, don't suspend the current thread
3729 nevents = g_slist_length (events);
3730 buffer_init (&buf, 128);
3731 buffer_add_byte (&buf, suspend_policy);
3732 buffer_add_int (&buf, nevents);
3734 for (l = events; l; l = l->next) {
3735 buffer_add_byte (&buf, event); // event kind
3736 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3741 thread = mono_thread_current ();
3743 if (event == EVENT_KIND_VM_START && arg != NULL)
3746 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3749 case EVENT_KIND_THREAD_START:
3750 case EVENT_KIND_THREAD_DEATH:
3752 case EVENT_KIND_APPDOMAIN_CREATE:
3753 case EVENT_KIND_APPDOMAIN_UNLOAD:
3754 buffer_add_domainid (&buf, arg);
3756 case EVENT_KIND_METHOD_ENTRY:
3757 case EVENT_KIND_METHOD_EXIT:
3758 buffer_add_methodid (&buf, domain, arg);
3760 case EVENT_KIND_ASSEMBLY_LOAD:
3761 buffer_add_assemblyid (&buf, domain, arg);
3763 case EVENT_KIND_ASSEMBLY_UNLOAD: {
3764 DebuggerTlsData *tls;
3766 /* The domain the assembly belonged to is not equal to the current domain */
3767 tls = mono_native_tls_get_value (debugger_tls_id);
3769 g_assert (tls->domain_unloading);
3771 buffer_add_assemblyid (&buf, tls->domain_unloading, arg);
3774 case EVENT_KIND_TYPE_LOAD:
3775 buffer_add_typeid (&buf, domain, arg);
3777 case EVENT_KIND_BREAKPOINT:
3778 case EVENT_KIND_STEP:
3779 buffer_add_methodid (&buf, domain, arg);
3780 buffer_add_long (&buf, il_offset);
3782 case EVENT_KIND_VM_START:
3783 buffer_add_domainid (&buf, mono_get_root_domain ());
3785 case EVENT_KIND_VM_DEATH:
3786 if (CHECK_PROTOCOL_VERSION (2, 27))
3787 buffer_add_int (&buf, mono_environment_exitcode_get ());
3789 case EVENT_KIND_EXCEPTION: {
3790 EventInfo *ei = arg;
3791 buffer_add_objid (&buf, ei->exc);
3793 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3794 * later after the suspension. (#12494).
3796 keepalive_obj = ei->exc;
3799 case EVENT_KIND_USER_BREAK:
3801 case EVENT_KIND_USER_LOG: {
3802 EventInfo *ei = arg;
3803 buffer_add_int (&buf, ei->level);
3804 buffer_add_string (&buf, ei->category ? ei->category : "");
3805 buffer_add_string (&buf, ei->message ? ei->message : "");
3808 case EVENT_KIND_KEEPALIVE:
3809 suspend_policy = SUSPEND_POLICY_NONE;
3812 g_assert_not_reached ();
3816 if (event == EVENT_KIND_VM_START) {
3817 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3818 if (!agent_config.defer)
3819 start_debugger_thread ();
3822 if (event == EVENT_KIND_VM_DEATH) {
3823 vm_death_event_sent = TRUE;
3824 suspend_policy = SUSPEND_POLICY_NONE;
3827 if (mono_runtime_is_shutting_down ())
3828 suspend_policy = SUSPEND_POLICY_NONE;
3830 if (suspend_policy != SUSPEND_POLICY_NONE) {
3832 * Save the thread context and start suspending before sending the packet,
3833 * since we could be receiving the resume request before send_packet ()
3836 save_thread_context (ctx);
3840 /* This will keep this object alive */
3841 get_objref (keepalive_obj);
3844 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3848 g_slist_free (events);
3851 if (!send_success) {
3852 DEBUG (2, fprintf (log_file, "Sending command %s failed.\n", event_to_string (event)));
3856 if (event == EVENT_KIND_VM_START) {
3857 vm_start_event_sent = TRUE;
3860 DEBUG (1, fprintf (log_file, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer)GetCurrentThreadId (), nevents, event_to_string (event), ecount, suspend_policy));
3862 switch (suspend_policy) {
3863 case SUSPEND_POLICY_NONE:
3865 case SUSPEND_POLICY_ALL:
3868 case SUSPEND_POLICY_EVENT_THREAD:
3872 g_assert_not_reached ();
3877 process_profiler_event (EventKind event, gpointer arg)
3881 EventInfo ei, *ei_arg = NULL;
3883 if (event == EVENT_KIND_TYPE_LOAD) {
3888 mono_loader_lock ();
3889 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3890 mono_loader_unlock ();
3892 process_event (event, arg, 0, NULL, events, suspend_policy);
3896 runtime_initialized (MonoProfiler *prof)
3898 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3899 if (agent_config.defer)
3900 start_debugger_thread ();
3904 runtime_shutdown (MonoProfiler *prof)
3906 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3908 mono_debugger_agent_cleanup ();
3912 thread_startup (MonoProfiler *prof, uintptr_t tid)
3914 MonoInternalThread *thread = mono_thread_internal_current ();
3915 MonoInternalThread *old_thread;
3916 DebuggerTlsData *tls;
3918 if (tid == debugger_thread_id)
3921 g_assert (thread->tid == tid);
3923 mono_loader_lock ();
3924 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3925 mono_loader_unlock ();
3927 if (thread == old_thread) {
3929 * For some reason, thread_startup () might be called for the same thread
3930 * multiple times (attach ?).
3932 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
3936 * thread_end () might not be called for some threads, and the tid could
3939 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
3940 mono_loader_lock ();
3941 mono_g_hash_table_remove (thread_to_tls, old_thread);
3942 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3943 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3944 mono_loader_unlock ();
3948 tls = mono_native_tls_get_value (debugger_tls_id);
3950 // FIXME: Free this somewhere
3951 tls = g_new0 (DebuggerTlsData, 1);
3952 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3953 tls->thread = thread;
3954 mono_native_tls_set_value (debugger_tls_id, tls);
3956 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3958 mono_loader_lock ();
3959 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3960 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3961 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3962 mono_loader_unlock ();
3964 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3967 * suspend_vm () could have missed this thread, so wait for a resume.
3973 thread_end (MonoProfiler *prof, uintptr_t tid)
3975 MonoInternalThread *thread;
3976 DebuggerTlsData *tls = NULL;
3978 mono_loader_lock ();
3979 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3981 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3982 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3984 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3985 tls->terminated = TRUE;
3986 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3987 MONO_GC_UNREGISTER_ROOT (tls->thread);
3991 mono_loader_unlock ();
3993 /* We might be called for threads started before we registered the start callback */
3995 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3996 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
4001 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
4003 mono_loader_lock ();
4004 g_hash_table_insert (domains, domain, domain);
4005 mono_loader_unlock ();
4007 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
4011 appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain)
4013 DebuggerTlsData *tls;
4016 * Remember the currently unloading appdomain as it is needed to generate
4017 * proper ids for unloading assemblies.
4019 tls = mono_native_tls_get_value (debugger_tls_id);
4021 tls->domain_unloading = domain;
4025 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
4027 DebuggerTlsData *tls;
4029 tls = mono_native_tls_get_value (debugger_tls_id);
4031 tls->domain_unloading = NULL;
4033 clear_breakpoints_for_domain (domain);
4035 mono_loader_lock ();
4036 /* Invalidate each thread's frame stack */
4037 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
4038 mono_loader_unlock ();
4040 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
4044 * invalidate_each_thread:
4046 * A GHFunc to invalidate frames.
4047 * value must be a DebuggerTlsData*
4050 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
4052 invalidate_frames (value);
4056 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
4058 /* Sent later in jit_end () */
4059 mono_loader_lock ();
4060 g_ptr_array_add (pending_assembly_loads, assembly);
4061 mono_loader_unlock ();
4065 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
4067 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
4069 clear_event_requests_for_assembly (assembly);
4070 clear_types_for_assembly (assembly);
4074 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
4076 #if defined(HOST_WIN32) && !defined(__GNUC__)
4077 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
4079 gpointer stackptr = __builtin_frame_address (1);
4081 MonoInternalThread *thread = mono_thread_internal_current ();
4082 DebuggerTlsData *tls;
4084 mono_loader_lock ();
4086 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4087 /* Could be the debugger thread with assembly/type load hooks */
4089 tls->invoke_addr = stackptr;
4091 mono_loader_unlock ();
4095 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
4098 #if defined(HOST_WIN32) && !defined(__GNUC__)
4099 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
4101 gpointer stackptr = __builtin_frame_address (1);
4104 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
4108 * We need to stop single stepping when exiting a runtime invoke, since if it is
4109 * a step out, it may return to native code, and thus never end.
4111 mono_loader_lock ();
4112 ss_invoke_addr = NULL;
4114 for (i = 0; i < event_requests->len; ++i) {
4115 EventRequest *req = g_ptr_array_index (event_requests, i);
4117 if (req->event_kind == EVENT_KIND_STEP) {
4118 ss_destroy (req->info);
4119 g_ptr_array_remove_index_fast (event_requests, i);
4124 mono_loader_unlock ();
4128 send_type_load (MonoClass *klass)
4130 gboolean type_load = FALSE;
4131 MonoDomain *domain = mono_domain_get ();
4132 AgentDomainInfo *info = NULL;
4134 mono_loader_lock ();
4135 mono_domain_lock (domain);
4137 info = get_agent_domain_info (domain);
4139 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
4141 g_hash_table_insert (info->loaded_classes, klass, klass);
4144 mono_domain_unlock (domain);
4145 mono_loader_unlock ();
4147 emit_type_load (klass, klass, NULL);
4151 * Emit load events for all types currently loaded in the domain.
4152 * Takes the loader and domain locks.
4153 * user_data is unused.
4156 send_types_for_domain (MonoDomain *domain, void *user_data)
4158 AgentDomainInfo *info = NULL;
4160 mono_loader_lock ();
4161 mono_domain_lock (domain);
4162 info = get_agent_domain_info (domain);
4164 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4165 mono_domain_unlock (domain);
4166 mono_loader_unlock ();
4170 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
4173 * We emit type load events when the first method of the type is JITted,
4174 * since the class load profiler callbacks might be called with the
4175 * loader lock held. They could also occur in the debugger thread.
4176 * Same for assembly load events.
4179 MonoAssembly *assembly = NULL;
4181 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4182 mono_loader_lock ();
4183 if (pending_assembly_loads->len > 0) {
4184 assembly = g_ptr_array_index (pending_assembly_loads, 0);
4185 g_ptr_array_remove_index (pending_assembly_loads, 0);
4187 mono_loader_unlock ();
4190 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4196 send_type_load (method->klass);
4199 add_pending_breakpoints (method, jinfo);
4203 * BREAKPOINTS/SINGLE STEPPING
4207 * Contains information about an inserted breakpoint.
4210 long il_offset, native_offset;
4215 } BreakpointInstance;
4218 * Contains generic information about a breakpoint.
4222 * The method where the breakpoint is placed. Can be NULL in which case it
4223 * is inserted into every method. This is used to implement method entry/
4224 * exit events. Can be a generic method definition, in which case the
4225 * breakpoint is inserted into every instance.
4231 * A list of BreakpointInstance structures describing where the breakpoint
4232 * was inserted. There could be more than one because of
4233 * generics/appdomains/method entry/exit.
4235 GPtrArray *children;
4238 /* List of breakpoints */
4239 static GPtrArray *breakpoints;
4240 /* Maps breakpoint locations to the number of breakpoints at that location */
4241 static GHashTable *bp_locs;
4244 breakpoints_init (void)
4246 breakpoints = g_ptr_array_new ();
4247 bp_locs = g_hash_table_new (NULL, NULL);
4251 * insert_breakpoint:
4253 * Insert the breakpoint described by BP into the method described by
4257 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4260 BreakpointInstance *inst;
4261 SeqPoint *sp = NULL;
4264 mono_error_init (error);
4266 for (i = 0; i < seq_points->len; ++i) {
4267 sp = &seq_points->seq_points [i];
4269 if (sp->il_offset == bp->il_offset)
4273 if (i == seq_points->len) {
4275 * The set of IL offsets with seq points doesn't completely match the
4276 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4278 for (i = 0; i < seq_points->len; ++i) {
4279 sp = &seq_points->seq_points [i];
4281 if (sp->il_offset != METHOD_ENTRY_IL_OFFSET && sp->il_offset != METHOD_EXIT_IL_OFFSET && sp->il_offset + 1 == bp->il_offset)
4286 if (i == seq_points->len) {
4287 char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d, seq_points=%d\n", mono_method_full_name (jinfo_get_method (ji), TRUE), bp->il_offset, seq_points->len);
4289 for (i = 0; i < seq_points->len; ++i)
4290 DEBUG (1, fprintf (log_file, "%d\n", seq_points->seq_points [i].il_offset));
4293 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4294 g_warning ("%s", s);
4298 g_warning ("%s", s);
4304 inst = g_new0 (BreakpointInstance, 1);
4306 inst->native_offset = sp->native_offset;
4307 inst->ip = (guint8*)ji->code_start + sp->native_offset;
4309 inst->domain = domain;
4311 mono_loader_lock ();
4313 g_ptr_array_add (bp->children, inst);
4315 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4316 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4317 mono_loader_unlock ();
4319 if (sp->native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4320 DEBUG (1, fprintf (log_file, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset));
4321 } else if (count == 0) {
4322 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4323 mono_arch_set_breakpoint (ji, inst->ip);
4329 DEBUG(1, fprintf (log_file, "[dbg] Inserted breakpoint at %s:0x%x.\n", mono_method_full_name (jinfo_get_method (ji), TRUE), (int)sp->il_offset));
4333 remove_breakpoint (BreakpointInstance *inst)
4335 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4337 MonoJitInfo *ji = inst->ji;
4338 guint8 *ip = inst->ip;
4340 mono_loader_lock ();
4341 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4342 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4343 mono_loader_unlock ();
4345 g_assert (count > 0);
4347 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4348 mono_arch_clear_breakpoint (ji, ip);
4355 static inline gboolean
4356 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4362 if (method == bp->method)
4364 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4367 if (bp->method->is_inflated && method->is_inflated) {
4368 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4369 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4371 /* Open generic methods should match closed generic methods of the same class */
4372 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4373 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4374 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4376 /* FIXME: Handle !mvar */
4377 if (t1->type != MONO_TYPE_MVAR)
4388 * add_pending_breakpoints:
4390 * Insert pending breakpoints into the newly JITted method METHOD.
4393 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4396 MonoSeqPointInfo *seq_points;
4398 MonoMethod *jmethod;
4403 domain = mono_domain_get ();
4405 mono_loader_lock ();
4407 for (i = 0; i < breakpoints->len; ++i) {
4408 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4409 gboolean found = FALSE;
4411 if (!bp_matches_method (bp, method))
4414 for (j = 0; j < bp->children->len; ++j) {
4415 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4422 jmethod = jinfo_get_method (ji);
4423 mono_domain_lock (domain);
4424 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, jmethod);
4425 if (!seq_points && jmethod->is_inflated)
4426 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (jmethod));
4427 mono_domain_unlock (domain);
4429 /* Could be AOT code */
4431 g_assert (seq_points);
4433 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4437 mono_loader_unlock ();
4441 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4447 mono_error_init (error);
4449 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4451 /* Might be AOTed code */
4452 code = mono_aot_get_method (domain, method);
4454 ji = mono_jit_info_table_find (domain, code);
4459 insert_breakpoint (seq_points, domain, ji, bp, error);
4463 clear_breakpoint (MonoBreakpoint *bp);
4468 * Set a breakpoint at IL_OFFSET in METHOD.
4469 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4470 * METHOD can also be a generic method definition, in which case a breakpoint
4471 * is placed in all instances of the method.
4472 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4475 static MonoBreakpoint*
4476 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4479 GHashTableIter iter, iter2;
4482 MonoSeqPointInfo *seq_points;
4485 mono_error_init (error);
4488 // - suspend/resume the vm to prevent code patching problems
4489 // - multiple breakpoints on the same location
4490 // - dynamic methods
4493 bp = g_new0 (MonoBreakpoint, 1);
4494 bp->method = method;
4495 bp->il_offset = il_offset;
4497 bp->children = g_ptr_array_new ();
4499 DEBUG(1, fprintf (log_file, "[dbg] Setting %sbreakpoint at %s:0x%x.\n", (req->event_kind == EVENT_KIND_STEP) ? "single step " : "", method ? mono_method_full_name (method, TRUE) : "<all>", (int)il_offset));
4501 mono_loader_lock ();
4503 g_hash_table_iter_init (&iter, domains);
4504 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4505 mono_domain_lock (domain);
4507 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4508 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4509 if (bp_matches_method (bp, m))
4510 set_bp_in_method (domain, m, seq_points, bp, error);
4513 mono_domain_unlock (domain);
4516 mono_loader_unlock ();
4518 mono_loader_lock ();
4519 g_ptr_array_add (breakpoints, bp);
4520 mono_loader_unlock ();
4522 if (error && !mono_error_ok (error)) {
4523 clear_breakpoint (bp);
4531 clear_breakpoint (MonoBreakpoint *bp)
4535 // FIXME: locking, races
4536 for (i = 0; i < bp->children->len; ++i) {
4537 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4539 remove_breakpoint (inst);
4544 mono_loader_lock ();
4545 g_ptr_array_remove (breakpoints, bp);
4546 mono_loader_unlock ();
4548 g_ptr_array_free (bp->children, TRUE);
4553 breakpoints_cleanup (void)
4557 mono_loader_lock ();
4559 while (i < event_requests->len) {
4560 EventRequest *req = g_ptr_array_index (event_requests, i);
4562 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4563 clear_breakpoint (req->info);
4564 g_ptr_array_remove_index_fast (event_requests, i);
4571 for (i = 0; i < breakpoints->len; ++i)
4572 g_free (g_ptr_array_index (breakpoints, i));
4574 g_ptr_array_free (breakpoints, TRUE);
4575 g_hash_table_destroy (bp_locs);
4580 mono_loader_unlock ();
4584 * clear_breakpoints_for_domain:
4586 * Clear breakpoint instances which reference DOMAIN.
4589 clear_breakpoints_for_domain (MonoDomain *domain)
4593 /* This could be called after shutdown */
4597 mono_loader_lock ();
4598 for (i = 0; i < breakpoints->len; ++i) {
4599 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4602 while (j < bp->children->len) {
4603 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4605 if (inst->domain == domain) {
4606 remove_breakpoint (inst);
4610 g_ptr_array_remove_index_fast (bp->children, j);
4616 mono_loader_unlock ();
4622 * Return FALSE if single stepping needs to continue.
4625 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp, DebuggerTlsData *tls, MonoContext *ctx)
4627 MonoDebugMethodInfo *minfo;
4628 MonoDebugSourceLocation *loc = NULL;
4629 gboolean hit = TRUE;
4632 if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK)) {
4634 * These seq points are inserted by the JIT after calls, step over needs to skip them.
4636 DEBUG (1, fprintf (log_file, "[%p] Seq point at nonempty stack %x while stepping over, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset));
4640 if (req->depth == STEP_DEPTH_OVER && hit) {
4641 if (!tls->context.valid)
4642 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4643 compute_frame_info (tls->thread, tls);
4644 if (req->nframes && tls->frame_count && tls->frame_count > req->nframes) {
4645 /* Hit the breakpoint in a recursive call */
4646 DEBUG (1, fprintf (log_file, "[%p] Breakpoint at lower frame while stepping over, continuing single stepping.\n", (gpointer)GetCurrentThreadId ()));
4651 if (req->size != STEP_SIZE_LINE)
4654 /* Have to check whenever a different source line was reached */
4655 method = jinfo_get_method (ji);
4656 minfo = mono_debug_lookup_method (method);
4659 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4661 if (!loc || (loc && method == ss_req->last_method && loc->row == ss_req->last_line)) {
4662 /* Have to continue single stepping */
4664 DEBUG(1, fprintf (log_file, "[%p] No line number info for il offset %x, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset));
4666 DEBUG(1, fprintf (log_file, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer)GetCurrentThreadId (), loc->row));
4671 ss_req->last_method = method;
4672 ss_req->last_line = loc->row;
4673 mono_debug_free_source_location (loc);
4680 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4682 return bp->method && bp->method->klass->image->assembly == assembly;
4686 process_breakpoint_inner (DebuggerTlsData *tls)
4690 int i, j, suspend_policy;
4691 guint32 native_offset;
4693 BreakpointInstance *inst;
4694 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4695 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4696 EventKind kind = EVENT_KIND_BREAKPOINT;
4697 MonoContext *ctx = &tls->restore_ctx;
4699 MonoSeqPointInfo *info;
4702 // FIXME: Speed this up
4704 ip = MONO_CONTEXT_GET_IP (ctx);
4705 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4707 method = jinfo_get_method (ji);
4709 /* Compute the native offset of the breakpoint from the ip */
4710 native_offset = ip - (guint8*)ji->code_start;
4713 * Skip the instruction causing the breakpoint signal.
4715 mono_arch_skip_breakpoint (ctx, ji);
4717 if (method->wrapper_type || tls->disable_breakpoints)
4720 bp_reqs = g_ptr_array_new ();
4721 ss_reqs = g_ptr_array_new ();
4722 ss_reqs_orig = g_ptr_array_new ();
4724 mono_loader_lock ();
4727 * The ip points to the instruction causing the breakpoint event, which is after
4728 * the offset recorded in the seq point map, so find the prev seq point before ip.
4730 sp = find_prev_seq_point_for_native_offset (mono_domain_get (), method, native_offset, &info);
4732 no_seq_points_found (method);
4735 DEBUG(1, fprintf (log_file, "[%p] Breakpoint hit, method=%s, ip=%p, offset=0x%x, sp il offset=0x%x.\n", (gpointer)GetCurrentThreadId (), method->name, ip, native_offset, sp ? sp->il_offset : -1));
4738 for (i = 0; i < breakpoints->len; ++i) {
4739 bp = g_ptr_array_index (breakpoints, i);
4744 for (j = 0; j < bp->children->len; ++j) {
4745 inst = g_ptr_array_index (bp->children, j);
4746 if (inst->ji == ji && inst->sp == sp) {
4747 if (bp->req->event_kind == EVENT_KIND_STEP) {
4748 g_ptr_array_add (ss_reqs_orig, bp->req);
4750 g_ptr_array_add (bp_reqs, bp->req);
4755 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4756 /* Maybe a method entry/exit event */
4757 if (sp->il_offset == METHOD_ENTRY_IL_OFFSET)
4758 kind = EVENT_KIND_METHOD_ENTRY;
4759 else if (sp->il_offset == METHOD_EXIT_IL_OFFSET)
4760 kind = EVENT_KIND_METHOD_EXIT;
4763 /* Process single step requests */
4764 for (i = 0; i < ss_reqs_orig->len; ++i) {
4765 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4766 SingleStepReq *ss_req = req->info;
4769 if (mono_thread_internal_current () != ss_req->thread)
4772 hit = ss_update (ss_req, ji, sp, tls, ctx);
4774 g_ptr_array_add (ss_reqs, req);
4776 /* Start single stepping again from the current sequence point */
4777 ss_start (ss_req, method, sp, info, ctx, tls, FALSE);
4780 if (ss_reqs->len > 0)
4781 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4782 if (bp_reqs->len > 0)
4783 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4784 if (kind != EVENT_KIND_BREAKPOINT)
4785 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4787 mono_loader_unlock ();
4789 g_ptr_array_free (bp_reqs, TRUE);
4790 g_ptr_array_free (ss_reqs, TRUE);
4793 * FIXME: The first event will suspend, so the second will only be sent after the
4797 process_event (EVENT_KIND_STEP, method, 0, ctx, ss_events, suspend_policy);
4799 process_event (kind, method, 0, ctx, bp_events, suspend_policy);
4800 if (enter_leave_events)
4801 process_event (kind, method, 0, ctx, enter_leave_events, suspend_policy);
4804 /* Process a breakpoint/single step event after resuming from a signal handler */
4806 process_signal_event (void (*func) (DebuggerTlsData*))
4808 DebuggerTlsData *tls;
4809 MonoContext orig_restore_ctx, ctx;
4811 tls = mono_native_tls_get_value (debugger_tls_id);
4812 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4813 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4814 memcpy (&tls->restore_ctx, &tls->handler_ctx, sizeof (MonoContext));
4818 /* This is called when resuming from a signal handler, so it shouldn't return */
4819 memcpy (&ctx, &tls->restore_ctx, sizeof (MonoContext));
4820 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4821 mono_restore_context (&ctx);
4822 g_assert_not_reached ();
4826 process_breakpoint (void)
4828 process_signal_event (process_breakpoint_inner);
4832 resume_from_signal_handler (void *sigctx, void *func)
4834 DebuggerTlsData *tls;
4837 /* Save the original context in TLS */
4838 // FIXME: This might not work on an altstack ?
4839 tls = mono_native_tls_get_value (debugger_tls_id);
4841 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer)GetCurrentThreadId ());
4844 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4845 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4846 // clob:c could be added to op_seq_point.
4848 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4849 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4850 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4851 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4853 MONO_CONTEXT_SET_IP (&ctx, func);
4855 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4857 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4858 mono_ppc_set_func_into_sigctx (sigctx, func);
4863 mono_debugger_agent_breakpoint_hit (void *sigctx)
4866 * We are called from a signal handler, and running code there causes all kinds of
4867 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4868 * So set up the signal context to return to the real breakpoint handler function.
4870 resume_from_signal_handler (sigctx, process_breakpoint);
4874 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4876 if (frame->managed) {
4877 *(MonoContext*)data = *ctx;
4886 * Called by System.Diagnostics.Debugger:Break ().
4889 mono_debugger_agent_user_break (void)
4891 if (agent_config.enabled) {
4896 /* Obtain a context */
4897 MONO_CONTEXT_SET_IP (&ctx, NULL);
4898 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4899 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4901 mono_loader_lock ();
4902 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4903 mono_loader_unlock ();
4905 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4912 ss_depth_to_string (StepDepth depth)
4915 case STEP_DEPTH_OVER:
4917 case STEP_DEPTH_OUT:
4919 case STEP_DEPTH_INTO:
4922 g_assert_not_reached ();
4928 process_single_step_inner (DebuggerTlsData *tls)
4933 int il_offset, suspend_policy;
4936 MonoContext *ctx = &tls->restore_ctx;
4939 MonoSeqPointInfo *info;
4941 ip = MONO_CONTEXT_GET_IP (ctx);
4943 /* Skip the instruction causing the single step */
4944 mono_arch_skip_single_step (ctx);
4946 if (suspend_count > 0) {
4947 process_suspend (tls, ctx);
4952 // FIXME: A suspend race
4955 if (mono_thread_internal_current () != ss_req->thread)
4958 if (log_level > 0) {
4959 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4961 DEBUG (1, fprintf (log_file, "[%p] Single step event (depth=%s) at %s (%p), sp %p, last sp %p\n", (gpointer)GetCurrentThreadId (), ss_depth_to_string (ss_req->depth), mono_method_full_name (jinfo_get_method (ji), TRUE), MONO_CONTEXT_GET_IP (ctx), MONO_CONTEXT_GET_SP (ctx), ss_req->last_sp));
4964 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4966 method = jinfo_get_method (ji);
4969 if (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4974 * Stopping in memset makes half-initialized vtypes visible.
4975 * Stopping in memcpy makes half-copied vtypes visible.
4977 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
4981 * The ip points to the instruction causing the single step event, which is before
4982 * the offset recorded in the seq point map, so find the next seq point after ip.
4984 sp = find_next_seq_point_for_native_offset (domain, method, (guint8*)ip - (guint8*)ji->code_start, &info);
4987 il_offset = sp->il_offset;
4989 if (!ss_update (ss_req, ji, sp, tls, ctx))
4992 /* Start single stepping again from the current sequence point */
4993 ss_start (ss_req, method, sp, info, ctx, tls, FALSE);
4995 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
4996 (method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4997 !strcmp (method->name, ".cctor"))
5000 // FIXME: Has to lock earlier
5002 reqs = g_ptr_array_new ();
5004 mono_loader_lock ();
5006 g_ptr_array_add (reqs, ss_req->req);
5008 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
5010 g_ptr_array_free (reqs, TRUE);
5012 mono_loader_unlock ();
5014 process_event (EVENT_KIND_STEP, jinfo_get_method (ji), il_offset, ctx, events, suspend_policy);
5018 process_single_step (void)
5020 process_signal_event (process_single_step_inner);
5024 * mono_debugger_agent_single_step_event:
5026 * Called from a signal handler to handle a single step event.
5029 mono_debugger_agent_single_step_event (void *sigctx)
5031 /* Resume to process_single_step through the signal context */
5033 // FIXME: Since step out/over is implemented using step in, the step in case should
5034 // be as fast as possible. Move the relevant code from process_single_step_inner ()
5037 if (GetCurrentThreadId () == debugger_thread_id) {
5039 * This could happen despite our best effors when the runtime calls
5040 * assembly/type resolve hooks.
5041 * FIXME: Breakpoints too.
5045 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
5046 mono_arch_skip_single_step (&ctx);
5047 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
5051 resume_from_signal_handler (sigctx, process_single_step);
5055 debugger_agent_single_step_from_context (MonoContext *ctx)
5057 DebuggerTlsData *tls;
5058 MonoContext orig_restore_ctx;
5060 tls = mono_native_tls_get_value (debugger_tls_id);
5063 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
5064 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
5065 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
5067 process_single_step_inner (tls);
5069 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
5070 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
5074 debugger_agent_breakpoint_from_context (MonoContext *ctx)
5076 DebuggerTlsData *tls;
5077 MonoContext orig_restore_ctx;
5079 tls = mono_native_tls_get_value (debugger_tls_id);
5081 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
5082 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
5084 process_breakpoint_inner (tls);
5086 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
5087 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
5091 * start_single_stepping:
5093 * Turn on single stepping. Can be called multiple times, for example,
5094 * by a single step event request + a suspend.
5097 start_single_stepping (void)
5099 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5100 int val = InterlockedIncrement (&ss_count);
5103 mono_arch_start_single_stepping ();
5105 if (ss_req != NULL && ss_invoke_addr == NULL) {
5106 DebuggerTlsData *tls;
5108 mono_loader_lock ();
5110 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
5111 ss_invoke_addr = tls->invoke_addr;
5113 mono_loader_unlock ();
5116 g_assert_not_reached ();
5121 stop_single_stepping (void)
5123 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5124 int val = InterlockedDecrement (&ss_count);
5127 mono_arch_stop_single_stepping ();
5129 ss_invoke_addr = NULL;
5131 g_assert_not_reached ();
5138 * Stop the single stepping operation given by SS_REQ.
5141 ss_stop (SingleStepReq *ss_req)
5146 for (l = ss_req->bps; l; l = l->next) {
5147 clear_breakpoint (l->data);
5149 g_slist_free (ss_req->bps);
5153 if (ss_req->global) {
5154 stop_single_stepping ();
5155 ss_req->global = FALSE;
5162 * Start the single stepping operation given by SS_REQ from the sequence point SP.
5163 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
5164 * belong to the same thread as CTX.
5167 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
5169 int i, j, frame_index;
5172 gboolean enable_global = FALSE;
5174 /* Stop the previous operation */
5178 * Implement single stepping using breakpoints if possible.
5180 if (step_to_catch) {
5181 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
5182 ss_req->bps = g_slist_append (ss_req->bps, bp);
5186 if ((!sp || sp->next_len == 0 || ss_req->depth == STEP_DEPTH_OUT || ss_req->depth == STEP_DEPTH_OVER) && ctx) {
5187 /* Need parent frames */
5188 if (!tls->context.valid)
5189 mono_thread_state_init_from_monoctx (&tls->context, ctx);
5190 compute_frame_info (tls->thread, tls);
5194 * Find the first sequence point in the current or in a previous frame which
5195 * is not the last in its method.
5197 if (ss_req->depth == STEP_DEPTH_OUT) {
5198 /* Ignore seq points in current method */
5199 while (frame_index < tls->frame_count) {
5200 StackFrame *frame = tls->frames [frame_index];
5202 method = frame->method;
5203 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5205 if (sp && sp->next_len != 0)
5208 // There could be method calls before the next seq point in the caller when using nested calls
5209 //enable_global = TRUE;
5211 if (sp && sp->next_len == 0) {
5213 while (frame_index < tls->frame_count) {
5214 StackFrame *frame = tls->frames [frame_index];
5216 method = frame->method;
5217 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5218 if (sp && sp->next_len != 0)
5226 if (sp && sp->next_len > 0) {
5227 for (i = 0; i < sp->next_len; ++i) {
5228 next_sp = &info->seq_points [sp->next [i]];
5230 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
5231 ss_req->bps = g_slist_append (ss_req->bps, bp);
5235 if (ss_req->depth == STEP_DEPTH_OVER) {
5236 if (ss_req->nframes == 0)
5237 ss_req->nframes = tls->frame_count;
5238 /* Need to stop in catch clauses as well */
5239 for (i = 0; i < tls->frame_count; ++i) {
5240 StackFrame *frame = tls->frames [i];
5243 MonoJitInfo *jinfo = frame->ji;
5244 for (j = 0; j < jinfo->num_clauses; ++j) {
5245 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5247 sp = find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL);
5249 bp = set_breakpoint (frame->method, sp->il_offset, ss_req->req, NULL);
5250 ss_req->bps = g_slist_append (ss_req->bps, bp);
5258 if (ss_req->depth == STEP_DEPTH_INTO) {
5259 /* Enable global stepping so we stop at method entry too */
5260 enable_global = TRUE;
5264 * The ctx/frame info computed above will become invalid when we continue.
5266 tls->context.valid = FALSE;
5267 tls->async_state.valid = FALSE;
5268 invalidate_frames (tls);
5271 if (enable_global) {
5272 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
5273 ss_req->global = TRUE;
5274 start_single_stepping ();
5275 } else if (!ss_req->bps) {
5276 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
5277 ss_req->global = TRUE;
5278 start_single_stepping ();
5280 ss_req->global = FALSE;
5285 * Start single stepping of thread THREAD
5288 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
5290 DebuggerTlsData *tls;
5291 MonoSeqPointInfo *info = NULL;
5292 SeqPoint *sp = NULL;
5293 MonoMethod *method = NULL;
5294 MonoDebugMethodInfo *minfo;
5295 gboolean step_to_catch = FALSE;
5297 if (suspend_count == 0)
5298 return ERR_NOT_SUSPENDED;
5300 wait_for_suspend ();
5302 // FIXME: Multiple requests
5304 DEBUG (0, fprintf (log_file, "Received a single step request while the previous one was still active.\n"));
5305 return ERR_NOT_IMPLEMENTED;
5308 DEBUG (1, fprintf (log_file, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
5310 ss_req = g_new0 (SingleStepReq, 1);
5312 ss_req->thread = thread;
5313 ss_req->size = size;
5314 ss_req->depth = depth;
5317 mono_loader_lock ();
5318 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5319 mono_loader_unlock ();
5321 g_assert (tls->context.valid);
5322 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5324 if (tls->catch_state.valid) {
5326 StackFrameInfo frame;
5327 MonoContext new_ctx;
5328 MonoLMF *lmf = NULL;
5331 * We are stopped at a throw site. Stepping should go to the catch site.
5334 /* Find the the jit info for the catch context */
5335 res = mono_find_jit_info_ext (tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], thread->jit_data, NULL, &tls->catch_state.ctx, &new_ctx, NULL, &lmf, NULL, &frame);
5337 g_assert (frame.type == FRAME_TYPE_MANAGED);
5340 * Find the seq point corresponding to the landing site ip, which is the first seq
5343 sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
5345 no_seq_points_found (frame.method);
5348 method = frame.method;
5350 step_to_catch = TRUE;
5351 /* This make sure the seq point is not skipped by process_single_step () */
5352 ss_req->last_sp = NULL;
5355 if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
5358 /* Compute the initial line info */
5359 compute_frame_info (thread, tls);
5361 if (tls->frame_count) {
5362 frame = tls->frames [0];
5364 ss_req->last_method = frame->method;
5365 ss_req->last_line = -1;
5367 minfo = mono_debug_lookup_method (frame->method);
5368 if (minfo && frame->il_offset != -1) {
5369 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
5372 ss_req->last_line = loc->row;
5379 if (!step_to_catch) {
5382 compute_frame_info (thread, tls);
5384 if (tls->frame_count) {
5385 frame = tls->frames [0];
5387 if (!method && frame->il_offset != -1) {
5388 /* FIXME: Sort the table and use a binary search */
5389 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5391 no_seq_points_found (frame->method);
5393 method = frame->method;
5398 ss_start (ss_req, method, sp, info, &tls->context.ctx, tls, step_to_catch);
5404 ss_destroy (SingleStepReq *req)
5407 g_assert (ss_req == req);
5416 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5419 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5425 if (!agent_config.enabled)
5428 mono_loader_lock ();
5429 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5430 mono_loader_unlock ();
5433 ei.category = category ? mono_string_to_utf8 (category) : NULL;
5434 ei.message = message ? mono_string_to_utf8 (message) : NULL;
5436 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5438 g_free (ei.category);
5439 g_free (ei.message);
5443 mono_debugger_agent_debug_log_is_enabled (void)
5445 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5446 return agent_config.enabled;
5449 #if defined(PLATFORM_ANDROID) || defined(TARGET_ANDROID)
5451 mono_debugger_agent_unhandled_exception (MonoException *exc)
5460 memset (&ei, 0, sizeof (EventInfo));
5461 ei.exc = (MonoObject*)exc;
5463 mono_loader_lock ();
5464 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5465 mono_loader_unlock ();
5467 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5472 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5473 MonoContext *catch_ctx)
5475 int i, j, suspend_policy;
5477 MonoJitInfo *ji, *catch_ji;
5479 DebuggerTlsData *tls = NULL;
5481 if (thread_to_tls != NULL) {
5482 MonoInternalThread *thread = mono_thread_internal_current ();
5484 mono_loader_lock ();
5485 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5486 mono_loader_unlock ();
5488 if (tls && tls->abort_requested)
5490 if (tls && tls->disable_breakpoints)
5494 memset (&ei, 0, sizeof (EventInfo));
5496 /* Just-In-Time debugging */
5498 if (agent_config.onuncaught && !inited) {
5499 finish_agent_init (FALSE);
5502 * Send an unsolicited EXCEPTION event with a dummy request id.
5504 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5505 ei.exc = (MonoObject*)exc;
5506 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5509 } else if (agent_config.onthrow && !inited) {
5511 gboolean found = FALSE;
5513 for (l = agent_config.onthrow; l; l = l->next) {
5514 char *ex_type = l->data;
5515 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5517 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5524 finish_agent_init (FALSE);
5527 * Send an unsolicited EXCEPTION event with a dummy request id.
5529 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5530 ei.exc = (MonoObject*)exc;
5531 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5539 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5541 catch_ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5545 ei.exc = (MonoObject*)exc;
5546 ei.caught = catch_ctx != NULL;
5548 mono_loader_lock ();
5550 /* Treat exceptions which are caught in non-user code as unhandled */
5551 for (i = 0; i < event_requests->len; ++i) {
5552 EventRequest *req = g_ptr_array_index (event_requests, i);
5553 if (req->event_kind != EVENT_KIND_EXCEPTION)
5556 for (j = 0; j < req->nmodifiers; ++j) {
5557 Modifier *mod = &req->modifiers [j];
5559 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5561 gboolean found = FALSE;
5562 MonoAssembly **assemblies = mod->data.assemblies;
5565 for (k = 0; assemblies [k]; ++k)
5566 if (assemblies [k] == jinfo_get_method (catch_ji)->klass->image->assembly)
5575 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5576 mono_loader_unlock ();
5578 if (tls && ei.caught && catch_ctx) {
5579 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5580 tls->catch_state.ctx = *catch_ctx;
5581 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5582 tls->catch_state.valid = TRUE;
5585 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5588 tls->catch_state.valid = FALSE;
5592 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5594 DebuggerTlsData *tls;
5599 tls = mono_native_tls_get_value (debugger_tls_id);
5604 * We're about to invoke an exception filter during the first pass of exception handling.
5606 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5607 * 'orig_ctx' is the context where the exception has been thrown.
5610 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5612 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5613 * the call site (line 37) and then continue to Main(), but it would never
5614 * include the throw site (line 32).
5616 * Since exception filters are invoked during the first pass of exception handling,
5617 * the stack frames of the throw site are still intact, so we should include them
5620 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5622 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5623 * but report the location of the 'throw' to the user.
5627 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5631 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5633 DebuggerTlsData *tls;
5638 tls = mono_native_tls_get_value (debugger_tls_id);
5642 tls->filter_state.valid = FALSE;
5646 * buffer_add_value_full:
5648 * Add the encoding of the value at ADDR described by T to the buffer.
5649 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5653 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5654 gboolean as_vtype, GHashTable *parent_vtypes)
5657 gboolean boxed_vtype = FALSE;
5660 if (!(*(void**)addr)) {
5661 /* This can happen with compiler generated locals */
5662 //printf ("%s\n", mono_type_full_name (t));
5663 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5666 g_assert (*(void**)addr);
5667 addr = *(void**)addr;
5672 case MONO_TYPE_BOOLEAN:
5675 case MONO_TYPE_CHAR:
5695 case MONO_TYPE_VOID:
5696 buffer_add_byte (buf, t->type);
5698 case MONO_TYPE_BOOLEAN:
5701 buffer_add_byte (buf, t->type);
5702 buffer_add_int (buf, *(gint8*)addr);
5704 case MONO_TYPE_CHAR:
5707 buffer_add_byte (buf, t->type);
5708 buffer_add_int (buf, *(gint16*)addr);
5713 buffer_add_byte (buf, t->type);
5714 buffer_add_int (buf, *(gint32*)addr);
5719 buffer_add_byte (buf, t->type);
5720 buffer_add_long (buf, *(gint64*)addr);
5724 /* Treat it as a vtype */
5726 case MONO_TYPE_PTR: {
5727 gssize val = *(gssize*)addr;
5729 buffer_add_byte (buf, t->type);
5730 buffer_add_long (buf, val);
5734 case MONO_TYPE_STRING:
5735 case MONO_TYPE_SZARRAY:
5736 case MONO_TYPE_OBJECT:
5737 case MONO_TYPE_CLASS:
5738 case MONO_TYPE_ARRAY:
5739 obj = *(MonoObject**)addr;
5742 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5744 if (obj->vtable->klass->valuetype) {
5745 t = &obj->vtable->klass->byval_arg;
5746 addr = mono_object_unbox (obj);
5749 } else if (obj->vtable->klass->rank) {
5750 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5751 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5752 buffer_add_byte (buf, MONO_TYPE_CLASS);
5754 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5756 buffer_add_objid (buf, obj);
5760 case MONO_TYPE_VALUETYPE: {
5764 MonoClass *klass = mono_class_from_mono_type (t);
5769 * Handle boxed vtypes recursively referencing themselves using fields.
5772 parent_vtypes = g_hash_table_new (NULL, NULL);
5773 vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
5775 if (CHECK_PROTOCOL_VERSION (2, 33)) {
5776 buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
5777 buffer_add_int (buf, vtype_index - 1);
5779 /* The client can't handle PARENT_VTYPE */
5780 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5784 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
5788 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5789 buffer_add_byte (buf, klass->enumtype);
5790 buffer_add_typeid (buf, domain, klass);
5794 while ((f = mono_class_get_fields (klass, &iter))) {
5795 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5797 if (mono_field_is_deleted (f))
5801 buffer_add_int (buf, nfields);
5804 while ((f = mono_class_get_fields (klass, &iter))) {
5805 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5807 if (mono_field_is_deleted (f))
5809 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE, parent_vtypes);
5813 g_hash_table_remove (parent_vtypes, addr);
5814 if (g_hash_table_size (parent_vtypes) == 0) {
5815 g_hash_table_destroy (parent_vtypes);
5816 parent_vtypes = NULL;
5821 case MONO_TYPE_GENERICINST:
5822 if (mono_type_generic_inst_is_valuetype (t)) {
5834 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5836 buffer_add_value_full (buf, t, addr, domain, FALSE, NULL);
5840 obj_is_of_type (MonoObject *obj, MonoType *t)
5842 MonoClass *klass = obj->vtable->klass;
5843 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5844 if (mono_class_is_transparent_proxy (klass)) {
5845 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5846 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5856 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5859 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5865 gpointer iter = NULL;
5869 is_enum = decode_byte (buf, &buf, limit);
5870 /* Enums are sent as a normal vtype */
5872 return ERR_NOT_IMPLEMENTED;
5873 klass = decode_typeid (buf, &buf, limit, &d, &err);
5877 if (t && klass != mono_class_from_mono_type (t)) {
5878 char *name = mono_type_full_name (t);
5879 char *name2 = mono_type_full_name (&klass->byval_arg);
5880 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got %s.\n", (gpointer)GetCurrentThreadId (), name, name2));
5883 return ERR_INVALID_ARGUMENT;
5886 nfields = decode_int (buf, &buf, limit);
5887 while ((f = mono_class_get_fields (klass, &iter))) {
5888 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5890 if (mono_field_is_deleted (f))
5892 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5897 g_assert (nfields == 0);
5905 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5909 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5910 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5911 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5912 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5913 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
5914 char *name = mono_type_full_name (t);
5915 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5917 return ERR_INVALID_ARGUMENT;
5921 case MONO_TYPE_BOOLEAN:
5922 *(guint8*)addr = decode_int (buf, &buf, limit);
5924 case MONO_TYPE_CHAR:
5925 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5928 *(gint8*)addr = decode_int (buf, &buf, limit);
5931 *(guint8*)addr = decode_int (buf, &buf, limit);
5934 *(gint16*)addr = decode_int (buf, &buf, limit);
5937 *(guint16*)addr = decode_int (buf, &buf, limit);
5940 *(gint32*)addr = decode_int (buf, &buf, limit);
5943 *(guint32*)addr = decode_int (buf, &buf, limit);
5946 *(gint64*)addr = decode_long (buf, &buf, limit);
5949 *(guint64*)addr = decode_long (buf, &buf, limit);
5952 *(guint32*)addr = decode_int (buf, &buf, limit);
5955 *(guint64*)addr = decode_long (buf, &buf, limit);
5958 /* We send these as I8, so we get them back as such */
5959 g_assert (type == MONO_TYPE_I8);
5960 *(gssize*)addr = decode_long (buf, &buf, limit);
5962 case MONO_TYPE_GENERICINST:
5963 if (MONO_TYPE_ISSTRUCT (t)) {
5964 /* The client sends these as a valuetype */
5972 /* We send these as vtypes, so we get them back as such */
5973 g_assert (type == MONO_TYPE_VALUETYPE);
5976 case MONO_TYPE_VALUETYPE:
5977 err = decode_vtype (t, domain, addr,buf, &buf, limit);
5983 if (MONO_TYPE_IS_REFERENCE (t)) {
5984 if (type == MONO_TYPE_OBJECT) {
5985 int objid = decode_objid (buf, &buf, limit);
5989 err = get_object (objid, (MonoObject**)&obj);
5994 if (!obj_is_of_type (obj, t)) {
5995 DEBUG (1, fprintf (log_file, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name));
5996 return ERR_INVALID_ARGUMENT;
5999 if (obj && obj->vtable->domain != domain)
6000 return ERR_INVALID_ARGUMENT;
6002 mono_gc_wbarrier_generic_store (addr, obj);
6003 } else if (type == VALUE_TYPE_ID_NULL) {
6004 *(MonoObject**)addr = NULL;
6005 } else if (type == MONO_TYPE_VALUETYPE) {
6013 /* This can happen when round-tripping boxed vtypes */
6015 * Obtain vtype class.
6016 * Same as the beginning of the handle_vtype case above.
6019 is_enum = decode_byte (buf, &buf, limit);
6021 return ERR_NOT_IMPLEMENTED;
6022 klass = decode_typeid (buf, &buf, limit, &d, &err);
6026 /* Decode the vtype into a temporary buffer, then box it. */
6027 vtype_buf_size = mono_class_value_size (klass, NULL);
6028 vtype_buf = g_malloc0 (vtype_buf_size);
6029 g_assert (vtype_buf);
6032 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
6037 *(MonoObject**)addr = mono_value_box (d, klass, vtype_buf);
6040 char *name = mono_type_full_name (t);
6041 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
6043 return ERR_INVALID_ARGUMENT;
6057 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6060 int type = decode_byte (buf, &buf, limit);
6062 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
6063 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
6064 guint8 *nullable_buf;
6067 * First try decoding it as a Nullable`1
6069 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6074 * Then try decoding as a primitive value or null.
6076 if (targ->type == type) {
6077 nullable_buf = g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
6078 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
6080 g_free (nullable_buf);
6083 mono_nullable_init (addr, mono_value_box (domain, mono_class_from_mono_type (targ), nullable_buf), mono_class_from_mono_type (t));
6084 g_free (nullable_buf);
6087 } else if (type == VALUE_TYPE_ID_NULL) {
6088 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
6094 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6098 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
6102 guint8 *addr, *gaddr;
6105 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6106 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6109 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
6110 reg_val = mono_arch_context_get_int_reg (ctx, reg);
6112 buffer_add_value_full (buf, t, ®_val, domain, as_vtype, NULL);
6114 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6115 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6116 addr += (gint32)var->offset;
6118 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6120 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6122 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6125 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6126 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
6127 /* Same as regoffset, but with an indirection */
6128 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6129 addr += (gint32)var->offset;
6131 gaddr = *(gpointer*)addr;
6133 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL);
6135 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
6136 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
6137 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
6138 MonoGSharedVtMethodRuntimeInfo *info;
6144 g_assert (info_var);
6145 g_assert (locals_var);
6147 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6148 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6149 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6150 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6151 addr += (gint32)info_var->offset;
6152 info = *(gpointer*)addr;
6153 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6154 info = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6156 g_assert_not_reached ();
6160 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6161 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6162 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6163 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6164 addr += (gint32)locals_var->offset;
6165 locals = *(gpointer*)addr;
6166 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6167 locals = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6169 g_assert_not_reached ();
6173 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6175 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6180 g_assert_not_reached ();
6185 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
6189 guint8 *addr, *gaddr;
6191 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6192 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6194 if (MONO_TYPE_IS_REFERENCE (t))
6195 size = sizeof (gpointer);
6197 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6200 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6201 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6203 gboolean is_signed = FALSE;
6206 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6209 // FIXME: Write barriers
6210 mono_gc_memmove_atomic (addr, val, size);
6215 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6220 v = is_signed ? *(gint8*)val : *(guint8*)val;
6223 v = is_signed ? *(gint16*)val : *(guint16*)val;
6226 v = is_signed ? *(gint32*)val : *(guint32*)val;
6229 v = is_signed ? *(gint64*)val : *(guint64*)val;
6232 g_assert_not_reached ();
6235 /* Set value on the stack or in the return ctx */
6236 if (reg_locations [reg]) {
6237 /* Saved on the stack */
6238 DEBUG (1, fprintf (log_file, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v));
6239 *(reg_locations [reg]) = v;
6242 DEBUG (1, fprintf (log_file, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v));
6243 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6246 // FIXME: Move these to mono-context.h/c.
6247 mono_arch_context_set_int_reg (ctx, reg, v);
6249 // FIXME: Can't set registers, so we disable linears
6254 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6255 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6256 addr += (gint32)var->offset;
6258 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6261 addr = *(guint8**)addr;
6267 // FIXME: Write barriers
6268 mono_gc_memmove_atomic (addr, val, size);
6270 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6271 /* Same as regoffset, but with an indirection */
6272 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6273 addr += (gint32)var->offset;
6275 gaddr = *(gpointer*)addr;
6277 // FIXME: Write barriers
6278 mono_gc_memmove_atomic (gaddr, val, size);
6280 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6284 g_assert_not_reached ();
6289 clear_event_request (int req_id, int etype)
6293 mono_loader_lock ();
6294 for (i = 0; i < event_requests->len; ++i) {
6295 EventRequest *req = g_ptr_array_index (event_requests, i);
6297 if (req->id == req_id && req->event_kind == etype) {
6298 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6299 clear_breakpoint (req->info);
6300 if (req->event_kind == EVENT_KIND_STEP)
6301 ss_destroy (req->info);
6302 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6303 clear_breakpoint (req->info);
6304 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6305 clear_breakpoint (req->info);
6306 g_ptr_array_remove_index_fast (event_requests, i);
6311 mono_loader_unlock ();
6315 event_req_matches_assembly (EventRequest *req, MonoAssembly *assembly)
6317 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6318 return breakpoint_matches_assembly (req->info, assembly);
6322 for (i = 0; i < req->nmodifiers; ++i) {
6323 Modifier *m = &req->modifiers [i];
6325 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6327 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6328 for (j = 0; m->data.assemblies [j]; ++j)
6329 if (m->data.assemblies [j] == assembly)
6339 * clear_event_requests_for_assembly:
6341 * Clear all events requests which reference ASSEMBLY.
6344 clear_event_requests_for_assembly (MonoAssembly *assembly)
6349 mono_loader_lock ();
6353 for (i = 0; i < event_requests->len; ++i) {
6354 EventRequest *req = g_ptr_array_index (event_requests, i);
6356 if (event_req_matches_assembly (req, assembly)) {
6357 clear_event_request (req->id, req->event_kind);
6363 mono_loader_unlock ();
6367 * type_comes_from_assembly:
6369 * GHRFunc that returns TRUE if klass comes from assembly
6372 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6374 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6378 * clear_types_for_assembly:
6380 * Clears types from loaded_classes for a given assembly
6383 clear_types_for_assembly (MonoAssembly *assembly)
6385 MonoDomain *domain = mono_domain_get ();
6386 AgentDomainInfo *info = NULL;
6388 mono_loader_lock ();
6389 info = get_agent_domain_info (domain);
6390 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6391 mono_loader_unlock ();
6395 add_thread (gpointer key, gpointer value, gpointer user_data)
6397 MonoInternalThread *thread = value;
6398 Buffer *buf = user_data;
6400 buffer_add_objid (buf, (MonoObject*)thread);
6404 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6406 guint8 *end = invoke->endp;
6409 MonoMethodSignature *sig;
6412 MonoObject *this, *res, *exc;
6415 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6418 MonoStopwatch watch;
6420 if (invoke->method) {
6422 * Invoke this method directly, currently only Environment.Exit () is supported.
6425 DEBUG (1, fprintf (log_file, "[%p] Invoking method '%s' on receiver '%s'.\n", (gpointer)GetCurrentThreadId (), mono_method_full_name (invoke->method, TRUE), this ? this->vtable->klass->name : "<null>"));
6426 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
6427 g_assert_not_reached ();
6430 m = decode_methodid (p, &p, end, &domain, &err);
6433 sig = mono_method_signature (m);
6435 if (m->klass->valuetype)
6436 this_buf = g_alloca (mono_class_instance_size (m->klass));
6438 this_buf = g_alloca (sizeof (MonoObject*));
6439 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6440 /* Should be null */
6441 int type = decode_byte (p, &p, end);
6442 if (type != VALUE_TYPE_ID_NULL) {
6443 DEBUG (1, fprintf (log_file, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer)GetCurrentThreadId ()));
6444 return ERR_INVALID_ARGUMENT;
6446 memset (this_buf, 0, mono_class_instance_size (m->klass));
6448 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6453 if (!m->klass->valuetype)
6454 this = *(MonoObject**)this_buf;
6458 if (MONO_CLASS_IS_INTERFACE (m->klass)) {
6460 DEBUG (1, fprintf (log_file, "[%p] Error: Interface method invoked without this argument.\n", (gpointer)GetCurrentThreadId ()));
6461 return ERR_INVALID_ARGUMENT;
6463 m = mono_object_get_virtual_method (this, m);
6466 DEBUG (1, fprintf (log_file, "[%p] Invoking method '%s' on receiver '%s'.\n", (gpointer)GetCurrentThreadId (), mono_method_full_name (m, TRUE), this ? this->vtable->klass->name : "<null>"));
6468 if (this && this->vtable->domain != domain)
6471 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
6472 if (!strcmp (m->name, ".ctor")) {
6473 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
6474 return ERR_INVALID_ARGUMENT;
6476 this = mono_object_new (domain, m->klass);
6478 return ERR_INVALID_ARGUMENT;
6482 if (this && !obj_is_of_type (this, &m->klass->byval_arg))
6483 return ERR_INVALID_ARGUMENT;
6485 nargs = decode_int (p, &p, end);
6486 if (nargs != sig->param_count)
6487 return ERR_INVALID_ARGUMENT;
6488 /* Use alloca to get gc tracking */
6489 arg_buf = g_alloca (nargs * sizeof (gpointer));
6490 memset (arg_buf, 0, nargs * sizeof (gpointer));
6491 args = g_alloca (nargs * sizeof (gpointer));
6492 for (i = 0; i < nargs; ++i) {
6493 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6494 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6498 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6501 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6502 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6505 args [i] = arg_buf [i];
6512 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6513 tls->disable_breakpoints = TRUE;
6515 tls->disable_breakpoints = FALSE;
6518 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6520 /* FIXME: Move this to arch specific code */
6521 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6522 if (invoke->has_ctx) {
6525 lmf_addr = mono_get_lmf_addr ();
6528 memset (&ext, 0, sizeof (ext));
6529 mono_arch_init_lmf_ext (&ext, *lmf_addr);
6531 ext.debugger_invoke = TRUE;
6532 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6534 mono_set_lmf ((MonoLMF*)&ext);
6538 mono_stopwatch_start (&watch);
6539 if (m->klass->valuetype)
6540 res = mono_runtime_invoke (m, this_buf, args, &exc);
6542 res = mono_runtime_invoke (m, this, args, &exc);
6543 mono_stopwatch_stop (&watch);
6544 DEBUG (1, fprintf (log_file, "[%p] Invoke result: %p, exc: %s, time: %ld ms.\n", (gpointer)GetCurrentThreadId (), res, exc ? exc->vtable->klass->name : NULL, (long)mono_stopwatch_elapsed_ms (&watch)));
6546 buffer_add_byte (buf, 0);
6547 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6549 buffer_add_byte (buf, 1);
6550 if (sig->ret->type == MONO_TYPE_VOID) {
6551 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
6552 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
6555 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6556 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6557 buffer_add_value (buf, sig->ret, &res, domain);
6558 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6559 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6560 MonoClass *k = mono_class_from_mono_type (sig->ret);
6561 guint8 *nullable_buf = g_alloca (mono_class_value_size (k, NULL));
6563 g_assert (nullable_buf);
6564 mono_nullable_init (nullable_buf, res, k);
6565 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6568 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6575 tls->disable_breakpoints = FALSE;
6577 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6578 if (invoke->has_ctx)
6579 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
6583 // FIXME: byref arguments
6591 * Invoke the method given by tls->pending_invoke in the current thread.
6594 invoke_method (void)
6596 DebuggerTlsData *tls;
6601 MonoContext restore_ctx;
6604 tls = mono_native_tls_get_value (debugger_tls_id);
6608 * Store the `InvokeData *' in `tls->invoke' until we're done with
6609 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6612 mono_loader_lock ();
6614 invoke = tls->pending_invoke;
6616 tls->pending_invoke = NULL;
6618 invoke->last_invoke = tls->invoke;
6619 tls->invoke = invoke;
6621 mono_loader_unlock ();
6623 tls->frames_up_to_date = FALSE;
6629 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6630 buffer_init (&buf, 128);
6633 /* Fail the other invokes as well */
6635 err = do_invoke_method (tls, &buf, invoke, p, &p);
6638 /* Start suspending before sending the reply */
6639 if (mindex == invoke->nmethods - 1) {
6640 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6641 for (i = 0; i < invoke->suspend_count; ++i)
6646 send_reply_packet (id, err, &buf);
6651 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6653 if (invoke->has_ctx)
6654 save_thread_context (&restore_ctx);
6656 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6657 g_assert (tls->resume_count);
6658 tls->resume_count -= invoke->suspend_count;
6661 DEBUG (1, fprintf (log_file, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer)GetCurrentThreadId (), err, tls->resume_count));
6664 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6666 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
6667 * after the mono_runtime_invoke() already returned, but it doesn't matter
6668 * because we reset the abort here.
6671 mono_loader_lock ();
6673 if (tls->abort_requested)
6674 mono_thread_internal_reset_abort (tls->thread);
6676 tls->invoke = tls->invoke->last_invoke;
6677 tls->abort_requested = FALSE;
6679 mono_loader_unlock ();
6688 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6690 MonoThread *thread = value;
6691 DebuggerTlsData *tls;
6694 mono_loader_lock ();
6695 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6697 res = tls->really_suspended;
6698 mono_loader_unlock ();
6704 get_source_files_for_type (MonoClass *klass)
6706 gpointer iter = NULL;
6708 MonoDebugSourceInfo *sinfo;
6712 files = g_ptr_array_new ();
6714 while ((method = mono_class_get_methods (klass, &iter))) {
6715 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6716 GPtrArray *source_file_list;
6719 mono_debug_symfile_get_line_numbers_full (minfo, NULL, &source_file_list, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
6720 for (j = 0; j < source_file_list->len; ++j) {
6721 sinfo = g_ptr_array_index (source_file_list, j);
6722 for (i = 0; i < files->len; ++i)
6723 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6725 if (i == files->len)
6726 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6728 g_ptr_array_free (source_file_list, TRUE);
6736 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6739 case CMD_VM_VERSION: {
6740 char *build_info, *version;
6742 build_info = mono_get_runtime_build_info ();
6743 version = g_strdup_printf ("mono %s", build_info);
6745 buffer_add_string (buf, version); /* vm version */
6746 buffer_add_int (buf, MAJOR_VERSION);
6747 buffer_add_int (buf, MINOR_VERSION);
6748 g_free (build_info);
6752 case CMD_VM_SET_PROTOCOL_VERSION: {
6753 major_version = decode_int (p, &p, end);
6754 minor_version = decode_int (p, &p, end);
6755 protocol_version_set = TRUE;
6756 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
6759 case CMD_VM_ALL_THREADS: {
6761 mono_loader_lock ();
6762 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6763 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6764 mono_loader_unlock ();
6767 case CMD_VM_SUSPEND:
6769 wait_for_suspend ();
6772 if (suspend_count == 0)
6773 return ERR_NOT_SUSPENDED;
6775 clear_suspended_objs ();
6777 case CMD_VM_DISPOSE:
6778 /* Clear all event requests */
6779 mono_loader_lock ();
6780 while (event_requests->len > 0) {
6781 EventRequest *req = g_ptr_array_index (event_requests, 0);
6783 clear_event_request (req->id, req->event_kind);
6785 mono_loader_unlock ();
6787 while (suspend_count > 0)
6789 disconnected = TRUE;
6790 vm_start_event_sent = FALSE;
6793 MonoInternalThread *thread;
6794 DebuggerTlsData *tls;
6795 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6796 MonoClass *env_class;
6798 MonoMethod *exit_method = NULL;
6802 exit_code = decode_int (p, &p, end);
6804 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6806 /* Have to send a reply before exiting */
6807 send_reply_packet (id, 0, buf);
6809 /* Clear all event requests */
6810 mono_loader_lock ();
6811 while (event_requests->len > 0) {
6812 EventRequest *req = g_ptr_array_index (event_requests, 0);
6814 clear_event_request (req->id, req->event_kind);
6816 mono_loader_unlock ();
6819 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6820 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6821 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6822 * better than doing the shutdown ourselves, since it avoids various races.
6826 wait_for_suspend ();
6828 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6829 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
6831 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6834 mono_loader_lock ();
6835 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6836 mono_loader_unlock ();
6838 if (thread && exit_method) {
6839 mono_loader_lock ();
6840 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6841 mono_loader_unlock ();
6843 args = g_new0 (gpointer, 1);
6844 args [0] = g_malloc (sizeof (int));
6845 *(int*)(args [0]) = exit_code;
6847 tls->pending_invoke = g_new0 (InvokeData, 1);
6848 tls->pending_invoke->method = exit_method;
6849 tls->pending_invoke->args = args;
6850 tls->pending_invoke->nmethods = 1;
6852 while (suspend_count > 0)
6856 * No thread found, do it ourselves.
6857 * FIXME: This can race with normal shutdown etc.
6859 while (suspend_count > 0)
6862 if (!mono_runtime_try_shutdown ())
6865 mono_environment_exitcode_set (exit_code);
6867 /* Suspend all managed threads since the runtime is going away */
6868 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
6869 mono_thread_suspend_all_other_threads ();
6870 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
6871 mono_runtime_quit ();
6872 transport_close2 ();
6873 DEBUG(1, fprintf (log_file, "Exiting...\n"));
6879 case CMD_VM_INVOKE_METHOD:
6880 case CMD_VM_INVOKE_METHODS: {
6881 int objid = decode_objid (p, &p, end);
6883 DebuggerTlsData *tls;
6884 int i, count, err, flags, nmethods;
6886 err = get_object (objid, (MonoObject**)&thread);
6890 flags = decode_int (p, &p, end);
6892 if (command == CMD_VM_INVOKE_METHODS)
6893 nmethods = decode_int (p, &p, end);
6897 // Wait for suspending if it already started
6899 wait_for_suspend ();
6900 if (!is_suspended ())
6901 return ERR_NOT_SUSPENDED;
6903 mono_loader_lock ();
6904 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6905 mono_loader_unlock ();
6908 if (!tls->really_suspended)
6909 /* The thread is still running native code, can't do invokes */
6910 return ERR_NOT_SUSPENDED;
6913 * Store the invoke data into tls, the thread will execute it after it is
6916 if (tls->pending_invoke)
6917 return ERR_NOT_SUSPENDED;
6918 tls->pending_invoke = g_new0 (InvokeData, 1);
6919 tls->pending_invoke->id = id;
6920 tls->pending_invoke->flags = flags;
6921 tls->pending_invoke->p = g_malloc (end - p);
6922 memcpy (tls->pending_invoke->p, p, end - p);
6923 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
6924 tls->pending_invoke->suspend_count = suspend_count;
6925 tls->pending_invoke->nmethods = nmethods;
6927 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
6928 resume_thread (THREAD_TO_INTERNAL (thread));
6931 count = suspend_count;
6932 for (i = 0; i < count; ++i)
6937 case CMD_VM_ABORT_INVOKE: {
6938 int objid = decode_objid (p, &p, end);
6940 DebuggerTlsData *tls;
6943 err = get_object (objid, (MonoObject**)&thread);
6947 invoke_id = decode_int (p, &p, end);
6949 mono_loader_lock ();
6950 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6953 if (tls->abort_requested) {
6954 mono_loader_unlock ();
6959 * Check whether we're still inside the mono_runtime_invoke() and that it's
6960 * actually the correct invocation.
6962 * Careful, we do not stop the thread that's doing the invocation, so we can't
6963 * inspect its stack. However, invoke_method() also acquires the loader lock
6964 * when it's done, so we're safe here.
6968 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
6969 mono_loader_unlock ();
6970 return ERR_NO_INVOCATION;
6973 tls->abort_requested = TRUE;
6975 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
6976 mono_loader_unlock ();
6980 case CMD_VM_SET_KEEPALIVE: {
6981 int timeout = decode_int (p, &p, end);
6982 agent_config.keepalive = timeout;
6984 #ifndef DISABLE_SOCKET_TRANSPORT
6991 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
6992 GHashTableIter iter, kiter;
6997 char *fname, *basename;
6998 gboolean ignore_case;
6999 GSList *class_list, *l;
7000 GPtrArray *res_classes, *res_domains;
7002 fname = decode_string (p, &p, end);
7003 ignore_case = decode_byte (p, &p, end);
7005 basename = g_path_get_basename (fname);
7007 res_classes = g_ptr_array_new ();
7008 res_domains = g_ptr_array_new ();
7010 mono_loader_lock ();
7011 g_hash_table_iter_init (&iter, domains);
7012 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7013 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
7015 /* Update 'source_file_to_class' cache */
7016 g_hash_table_iter_init (&kiter, info->loaded_classes);
7017 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
7018 if (!g_hash_table_lookup (info->source_files, klass)) {
7019 files = get_source_files_for_type (klass);
7020 g_hash_table_insert (info->source_files, klass, files);
7022 for (i = 0; i < files->len; ++i) {
7023 char *s = g_ptr_array_index (files, i);
7024 char *s2 = g_path_get_basename (s);
7027 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
7029 class_list = g_slist_prepend (class_list, klass);
7030 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
7032 class_list = g_slist_prepend (class_list, klass);
7033 g_hash_table_insert (info->source_file_to_class, s2, class_list);
7036 /* The _ignorecase hash contains the lowercase path */
7037 s3 = strdup_tolower (s2);
7038 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
7040 class_list = g_slist_prepend (class_list, klass);
7041 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
7043 class_list = g_slist_prepend (class_list, klass);
7044 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
7056 s = strdup_tolower (basename);
7057 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
7060 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
7063 for (l = class_list; l; l = l->next) {
7066 g_ptr_array_add (res_classes, klass);
7067 g_ptr_array_add (res_domains, domain);
7070 mono_loader_unlock ();
7075 buffer_add_int (buf, res_classes->len);
7076 for (i = 0; i < res_classes->len; ++i)
7077 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
7078 g_ptr_array_free (res_classes, TRUE);
7079 g_ptr_array_free (res_domains, TRUE);
7082 case CMD_VM_GET_TYPES: {
7083 GHashTableIter iter;
7087 gboolean ignore_case;
7088 GPtrArray *res_classes, *res_domains;
7089 MonoTypeNameParse info;
7091 name = decode_string (p, &p, end);
7092 ignore_case = decode_byte (p, &p, end);
7094 if (!mono_reflection_parse_type (name, &info)) {
7096 mono_reflection_free_type_info (&info);
7097 return ERR_INVALID_ARGUMENT;
7100 res_classes = g_ptr_array_new ();
7101 res_domains = g_ptr_array_new ();
7103 mono_loader_lock ();
7104 g_hash_table_iter_init (&iter, domains);
7105 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7107 gboolean type_resolve;
7111 mono_domain_assemblies_lock (domain);
7112 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7116 type_resolve = TRUE;
7117 t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
7119 g_ptr_array_add (res_classes, mono_type_get_class (t));
7120 g_ptr_array_add (res_domains, domain);
7124 mono_domain_assemblies_unlock (domain);
7126 mono_loader_unlock ();
7129 mono_reflection_free_type_info (&info);
7131 buffer_add_int (buf, res_classes->len);
7132 for (i = 0; i < res_classes->len; ++i)
7133 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
7134 g_ptr_array_free (res_classes, TRUE);
7135 g_ptr_array_free (res_domains, TRUE);
7138 case CMD_VM_START_BUFFERING:
7139 case CMD_VM_STOP_BUFFERING:
7140 /* Handled in the main loop */
7143 return ERR_NOT_IMPLEMENTED;
7150 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7156 case CMD_EVENT_REQUEST_SET: {
7158 int i, event_kind, suspend_policy, nmodifiers, mod;
7161 MonoThread *step_thread;
7162 int size = 0, depth = 0, filter = 0, step_thread_id = 0;
7166 event_kind = decode_byte (p, &p, end);
7167 suspend_policy = decode_byte (p, &p, end);
7168 nmodifiers = decode_byte (p, &p, end);
7170 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7171 req->id = InterlockedIncrement (&event_request_id);
7172 req->event_kind = event_kind;
7173 req->suspend_policy = suspend_policy;
7174 req->nmodifiers = nmodifiers;
7177 for (i = 0; i < nmodifiers; ++i) {
7178 mod = decode_byte (p, &p, end);
7180 req->modifiers [i].kind = mod;
7181 if (mod == MOD_KIND_COUNT) {
7182 req->modifiers [i].data.count = decode_int (p, &p, end);
7183 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7184 method = decode_methodid (p, &p, end, &domain, &err);
7187 location = decode_long (p, &p, end);
7188 } else if (mod == MOD_KIND_STEP) {
7189 step_thread_id = decode_id (p, &p, end);
7190 size = decode_int (p, &p, end);
7191 depth = decode_int (p, &p, end);
7192 if (CHECK_PROTOCOL_VERSION (2, 16))
7193 filter = decode_int (p, &p, end);
7194 req->modifiers [i].data.filter = filter;
7195 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7196 /* Treat STEP_THOUGH the same as HIDDEN */
7197 req->modifiers [i].data.filter |= STEP_FILTER_DEBUGGER_STEP_THROUGH;
7198 } else if (mod == MOD_KIND_THREAD_ONLY) {
7199 int id = decode_id (p, &p, end);
7201 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7206 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7207 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7211 req->modifiers [i].caught = decode_byte (p, &p, end);
7212 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7213 if (CHECK_PROTOCOL_VERSION (2, 25))
7214 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7216 req->modifiers [i].subclasses = TRUE;
7217 DEBUG(1, fprintf (log_file, "[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" : ""));
7219 req->modifiers [i].data.exc_class = exc_class;
7221 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
7223 return ERR_INVALID_ARGUMENT;
7226 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7227 int n = decode_int (p, &p, end);
7230 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
7231 for (j = 0; j < n; ++j) {
7232 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7234 g_free (req->modifiers [i].data.assemblies);
7238 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7239 int n = decode_int (p, &p, end);
7242 modifier = &req->modifiers [i];
7243 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7244 for (j = 0; j < n; ++j) {
7245 char *s = decode_string (p, &p, end);
7249 s2 = strdup_tolower (s);
7250 g_hash_table_insert (modifier->data.source_files, s2, s2);
7254 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7255 int n = decode_int (p, &p, end);
7258 modifier = &req->modifiers [i];
7259 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7260 for (j = 0; j < n; ++j) {
7261 char *s = decode_string (p, &p, end);
7264 g_hash_table_insert (modifier->data.type_names, s, s);
7268 return ERR_NOT_IMPLEMENTED;
7272 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7275 req->info = set_breakpoint (method, location, req, &error);
7276 if (!mono_error_ok (&error)) {
7278 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
7279 mono_error_cleanup (&error);
7280 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7282 } else if (req->event_kind == EVENT_KIND_STEP) {
7283 g_assert (step_thread_id);
7285 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7291 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
7296 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7297 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7298 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7299 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7300 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7301 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7303 if (req->nmodifiers) {
7305 return ERR_NOT_IMPLEMENTED;
7309 mono_loader_lock ();
7310 g_ptr_array_add (event_requests, req);
7312 if (agent_config.defer) {
7313 /* Transmit cached data to the client on receipt of the event request */
7314 switch (req->event_kind) {
7315 case EVENT_KIND_APPDOMAIN_CREATE:
7316 /* Emit load events for currently loaded domains */
7317 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7319 case EVENT_KIND_ASSEMBLY_LOAD:
7320 /* Emit load events for currently loaded assemblies */
7321 mono_assembly_foreach (emit_assembly_load, NULL);
7323 case EVENT_KIND_THREAD_START:
7324 /* Emit start events for currently started threads */
7325 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7327 case EVENT_KIND_TYPE_LOAD:
7328 /* Emit type load events for currently loaded types */
7329 mono_domain_foreach (send_types_for_domain, NULL);
7335 mono_loader_unlock ();
7337 buffer_add_int (buf, req->id);
7340 case CMD_EVENT_REQUEST_CLEAR: {
7341 int etype = decode_byte (p, &p, end);
7342 int req_id = decode_int (p, &p, end);
7344 // FIXME: Make a faster mapping from req_id to request
7345 mono_loader_lock ();
7346 clear_event_request (req_id, etype);
7347 mono_loader_unlock ();
7350 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7353 mono_loader_lock ();
7355 while (i < event_requests->len) {
7356 EventRequest *req = g_ptr_array_index (event_requests, i);
7358 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7359 clear_breakpoint (req->info);
7361 g_ptr_array_remove_index_fast (event_requests, i);
7367 mono_loader_unlock ();
7371 return ERR_NOT_IMPLEMENTED;
7378 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7384 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7385 buffer_add_domainid (buf, mono_get_root_domain ());
7388 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7389 domain = decode_domainid (p, &p, end, NULL, &err);
7392 buffer_add_string (buf, domain->friendly_name);
7395 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7400 domain = decode_domainid (p, &p, end, NULL, &err);
7403 mono_loader_lock ();
7405 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7408 buffer_add_int (buf, count);
7409 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7411 buffer_add_assemblyid (buf, domain, ass);
7413 mono_loader_unlock ();
7416 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7417 domain = decode_domainid (p, &p, end, NULL, &err);
7421 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7424 case CMD_APPDOMAIN_GET_CORLIB: {
7425 domain = decode_domainid (p, &p, end, NULL, &err);
7429 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7432 case CMD_APPDOMAIN_CREATE_STRING: {
7436 domain = decode_domainid (p, &p, end, NULL, &err);
7439 s = decode_string (p, &p, end);
7441 o = mono_string_new (domain, s);
7442 buffer_add_objid (buf, (MonoObject*)o);
7445 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7447 MonoDomain *domain2;
7450 domain = decode_domainid (p, &p, end, NULL, &err);
7453 klass = decode_typeid (p, &p, end, &domain2, &err);
7458 g_assert (domain == domain2);
7460 o = mono_object_new (domain, klass);
7462 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
7466 buffer_add_objid (buf, o);
7470 return ERR_NOT_IMPLEMENTED;
7477 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7483 ass = decode_assemblyid (p, &p, end, &domain, &err);
7488 case CMD_ASSEMBLY_GET_LOCATION: {
7489 buffer_add_string (buf, mono_image_get_filename (ass->image));
7492 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7496 if (ass->image->dynamic) {
7497 buffer_add_id (buf, 0);
7499 token = mono_image_get_entry_point (ass->image);
7501 buffer_add_id (buf, 0);
7503 m = mono_get_method (ass->image, token, NULL);
7504 buffer_add_methodid (buf, domain, m);
7509 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7510 buffer_add_moduleid (buf, domain, ass->image);
7513 case CMD_ASSEMBLY_GET_OBJECT: {
7514 MonoObject *o = (MonoObject*)mono_assembly_get_object (domain, ass);
7515 buffer_add_objid (buf, o);
7518 case CMD_ASSEMBLY_GET_TYPE: {
7519 char *s = decode_string (p, &p, end);
7520 gboolean ignorecase = decode_byte (p, &p, end);
7521 MonoTypeNameParse info;
7523 gboolean type_resolve, res;
7524 MonoDomain *d = mono_domain_get ();
7526 /* This is needed to be able to find referenced assemblies */
7527 res = mono_domain_set (domain, FALSE);
7530 if (!mono_reflection_parse_type (s, &info)) {
7533 if (info.assembly.name)
7535 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
7537 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
7538 mono_reflection_free_type_info (&info);
7541 mono_domain_set (d, TRUE);
7545 case CMD_ASSEMBLY_GET_NAME: {
7547 MonoAssembly *mass = ass;
7549 name = g_strdup_printf (
7550 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7552 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7553 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7554 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7555 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7557 buffer_add_string (buf, name);
7562 return ERR_NOT_IMPLEMENTED;
7569 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7575 case CMD_MODULE_GET_INFO: {
7576 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7579 basename = g_path_get_basename (image->name);
7580 buffer_add_string (buf, basename); // name
7581 buffer_add_string (buf, image->module_name); // scopename
7582 buffer_add_string (buf, image->name); // fqname
7583 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7584 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7589 return ERR_NOT_IMPLEMENTED;
7596 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7602 case CMD_FIELD_GET_INFO: {
7603 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
7605 buffer_add_string (buf, f->name);
7606 buffer_add_typeid (buf, domain, f->parent);
7607 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7608 buffer_add_int (buf, f->type->attrs);
7612 return ERR_NOT_IMPLEMENTED;
7619 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7621 if (val && val->vtable->klass == mono_defaults.monotype_class) {
7622 /* Special case these so the client doesn't have to handle Type objects */
7624 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7625 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7626 } else if (MONO_TYPE_IS_REFERENCE (t))
7627 buffer_add_value (buf, t, &val, domain);
7629 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7633 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7639 buffer_add_int (buf, 0);
7643 for (i = 0; i < cinfo->num_attrs; ++i) {
7644 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7647 buffer_add_int (buf, nattrs);
7649 for (i = 0; i < cinfo->num_attrs; ++i) {
7650 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7651 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7652 MonoArray *typed_args, *named_args;
7654 CattrNamedArg *arginfo = NULL;
7657 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
7658 g_assert (mono_error_ok (&error));
7660 buffer_add_methodid (buf, domain, attr->ctor);
7664 buffer_add_int (buf, mono_array_length (typed_args));
7665 for (j = 0; j < mono_array_length (typed_args); ++j) {
7666 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7668 t = mono_method_signature (attr->ctor)->params [j];
7670 buffer_add_cattr_arg (buf, t, domain, val);
7673 buffer_add_int (buf, 0);
7678 buffer_add_int (buf, mono_array_length (named_args));
7680 for (j = 0; j < mono_array_length (named_args); ++j) {
7681 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7683 if (arginfo [j].prop) {
7684 buffer_add_byte (buf, 0x54);
7685 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7686 } else if (arginfo [j].field) {
7687 buffer_add_byte (buf, 0x53);
7688 buffer_add_fieldid (buf, domain, arginfo [j].field);
7690 g_assert_not_reached ();
7693 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7696 buffer_add_int (buf, 0);
7703 /* FIXME: Code duplication with icall.c */
7705 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7710 mono_class_setup_interfaces (klass, error);
7711 if (!mono_error_ok (error))
7714 for (i = 0; i < klass->interface_count; i++) {
7715 ic = klass->interfaces [i];
7716 g_hash_table_insert (ifaces, ic, ic);
7718 collect_interfaces (ic, ifaces, error);
7719 if (!mono_error_ok (error))
7725 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7735 case CMD_TYPE_GET_INFO: {
7736 buffer_add_string (buf, klass->name_space);
7737 buffer_add_string (buf, klass->name);
7739 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7740 buffer_add_string (buf, name);
7742 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7743 buffer_add_moduleid (buf, domain, klass->image);
7744 buffer_add_typeid (buf, domain, klass->parent);
7745 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7746 buffer_add_typeid (buf, domain, klass->element_class);
7748 buffer_add_id (buf, 0);
7749 buffer_add_int (buf, klass->type_token);
7750 buffer_add_byte (buf, klass->rank);
7751 buffer_add_int (buf, klass->flags);
7753 type = &klass->byval_arg;
7754 // FIXME: Can't decide whenever a class represents a byref type
7757 if (type->type == MONO_TYPE_PTR)
7759 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7761 if (type->type == MONO_TYPE_VALUETYPE)
7763 if (klass->enumtype)
7765 if (klass->generic_container)
7767 if (klass->generic_container || klass->generic_class)
7769 buffer_add_byte (buf, b);
7772 while ((nested = mono_class_get_nested_types (klass, &iter)))
7774 buffer_add_int (buf, nnested);
7776 while ((nested = mono_class_get_nested_types (klass, &iter)))
7777 buffer_add_typeid (buf, domain, nested);
7778 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7779 if (klass->generic_container)
7780 buffer_add_typeid (buf, domain, klass);
7781 else if (klass->generic_class)
7782 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7784 buffer_add_id (buf, 0);
7786 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7789 if (klass->generic_class) {
7790 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7792 count = inst->type_argc;
7793 buffer_add_int (buf, count);
7794 for (i = 0; i < count; i++)
7795 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7796 } else if (klass->generic_container) {
7797 MonoGenericContainer *container = klass->generic_container;
7800 count = container->type_argc;
7801 buffer_add_int (buf, count);
7802 for (i = 0; i < count; i++) {
7803 pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
7804 buffer_add_typeid (buf, domain, pklass);
7807 buffer_add_int (buf, 0);
7812 case CMD_TYPE_GET_METHODS: {
7815 gpointer iter = NULL;
7818 mono_class_setup_methods (klass);
7820 nmethods = mono_class_num_methods (klass);
7822 buffer_add_int (buf, nmethods);
7824 while ((m = mono_class_get_methods (klass, &iter))) {
7825 buffer_add_methodid (buf, domain, m);
7828 g_assert (i == nmethods);
7831 case CMD_TYPE_GET_FIELDS: {
7834 gpointer iter = NULL;
7837 nfields = mono_class_num_fields (klass);
7839 buffer_add_int (buf, nfields);
7841 while ((f = mono_class_get_fields (klass, &iter))) {
7842 buffer_add_fieldid (buf, domain, f);
7843 buffer_add_string (buf, f->name);
7844 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7845 buffer_add_int (buf, f->type->attrs);
7848 g_assert (i == nfields);
7851 case CMD_TYPE_GET_PROPERTIES: {
7854 gpointer iter = NULL;
7857 nprops = mono_class_num_properties (klass);
7859 buffer_add_int (buf, nprops);
7861 while ((p = mono_class_get_properties (klass, &iter))) {
7862 buffer_add_propertyid (buf, domain, p);
7863 buffer_add_string (buf, p->name);
7864 buffer_add_methodid (buf, domain, p->get);
7865 buffer_add_methodid (buf, domain, p->set);
7866 buffer_add_int (buf, p->attrs);
7869 g_assert (i == nprops);
7872 case CMD_TYPE_GET_CATTRS: {
7873 MonoClass *attr_klass;
7874 MonoCustomAttrInfo *cinfo;
7876 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7877 /* attr_klass can be NULL */
7881 cinfo = mono_custom_attrs_from_class (klass);
7883 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7886 case CMD_TYPE_GET_FIELD_CATTRS: {
7887 MonoClass *attr_klass;
7888 MonoCustomAttrInfo *cinfo;
7889 MonoClassField *field;
7891 field = decode_fieldid (p, &p, end, NULL, &err);
7894 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7898 cinfo = mono_custom_attrs_from_field (klass, field);
7900 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7903 case CMD_TYPE_GET_PROPERTY_CATTRS: {
7904 MonoClass *attr_klass;
7905 MonoCustomAttrInfo *cinfo;
7908 prop = decode_propertyid (p, &p, end, NULL, &err);
7911 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7915 cinfo = mono_custom_attrs_from_property (klass, prop);
7917 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7920 case CMD_TYPE_GET_VALUES:
7921 case CMD_TYPE_GET_VALUES_2: {
7928 MonoThread *thread_obj;
7929 MonoInternalThread *thread = NULL;
7930 guint32 special_static_type;
7932 if (command == CMD_TYPE_GET_VALUES_2) {
7933 int objid = decode_objid (p, &p, end);
7936 err = get_object (objid, (MonoObject**)&thread_obj);
7940 thread = THREAD_TO_INTERNAL (thread_obj);
7943 len = decode_int (p, &p, end);
7944 for (i = 0; i < len; ++i) {
7945 f = decode_fieldid (p, &p, end, NULL, &err);
7949 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7950 return ERR_INVALID_FIELDID;
7951 special_static_type = mono_class_field_get_special_static_type (f);
7952 if (special_static_type != SPECIAL_STATIC_NONE) {
7953 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
7954 return ERR_INVALID_FIELDID;
7957 /* Check that the field belongs to the object */
7959 for (k = klass; k; k = k->parent) {
7960 if (k == f->parent) {
7966 return ERR_INVALID_FIELDID;
7968 vtable = mono_class_vtable (domain, f->parent);
7969 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7970 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
7971 buffer_add_value (buf, f->type, val, domain);
7976 case CMD_TYPE_SET_VALUES: {
7984 len = decode_int (p, &p, end);
7985 for (i = 0; i < len; ++i) {
7986 f = decode_fieldid (p, &p, end, NULL, &err);
7990 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7991 return ERR_INVALID_FIELDID;
7992 if (mono_class_field_is_special_static (f))
7993 return ERR_INVALID_FIELDID;
7995 /* Check that the field belongs to the object */
7997 for (k = klass; k; k = k->parent) {
7998 if (k == f->parent) {
8004 return ERR_INVALID_FIELDID;
8006 // FIXME: Check for literal/const
8008 vtable = mono_class_vtable (domain, f->parent);
8009 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8010 err = decode_value (f->type, domain, val, p, &p, end);
8015 if (MONO_TYPE_IS_REFERENCE (f->type))
8016 mono_field_static_set_value (vtable, f, *(gpointer*)val);
8018 mono_field_static_set_value (vtable, f, val);
8023 case CMD_TYPE_GET_OBJECT: {
8024 MonoObject *o = (MonoObject*)mono_type_get_object (domain, &klass->byval_arg);
8025 buffer_add_objid (buf, o);
8028 case CMD_TYPE_GET_SOURCE_FILES:
8029 case CMD_TYPE_GET_SOURCE_FILES_2: {
8030 char *source_file, *base;
8034 files = get_source_files_for_type (klass);
8036 buffer_add_int (buf, files->len);
8037 for (i = 0; i < files->len; ++i) {
8038 source_file = g_ptr_array_index (files, i);
8039 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8040 buffer_add_string (buf, source_file);
8042 base = g_path_get_basename (source_file);
8043 buffer_add_string (buf, base);
8046 g_free (source_file);
8048 g_ptr_array_free (files, TRUE);
8051 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8052 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8056 if (mono_class_is_assignable_from (klass, oklass))
8057 buffer_add_byte (buf, 1);
8059 buffer_add_byte (buf, 0);
8062 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8063 char *name = decode_string (p, &p, end);
8064 int i, flags = decode_int (p, &p, end);
8065 MonoException *ex = NULL;
8066 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
8069 return ERR_LOADER_ERROR;
8070 buffer_add_int (buf, array->len);
8071 for (i = 0; i < array->len; ++i) {
8072 MonoMethod *method = g_ptr_array_index (array, i);
8073 buffer_add_methodid (buf, domain, method);
8076 g_ptr_array_free (array, TRUE);
8080 case CMD_TYPE_GET_INTERFACES: {
8082 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8084 MonoClass *tclass, *iface;
8085 GHashTableIter iter;
8089 for (parent = tclass; parent; parent = parent->parent) {
8090 mono_class_setup_interfaces (parent, &error);
8091 if (!mono_error_ok (&error))
8092 return ERR_LOADER_ERROR;
8093 collect_interfaces (parent, iface_hash, &error);
8094 if (!mono_error_ok (&error))
8095 return ERR_LOADER_ERROR;
8098 buffer_add_int (buf, g_hash_table_size (iface_hash));
8100 g_hash_table_iter_init (&iter, iface_hash);
8101 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8102 buffer_add_typeid (buf, domain, iface);
8103 g_hash_table_destroy (iface_hash);
8106 case CMD_TYPE_GET_INTERFACE_MAP: {
8107 int tindex, ioffset;
8108 gboolean variance_used;
8110 int len, nmethods, i;
8114 len = decode_int (p, &p, end);
8115 mono_class_setup_vtable (klass);
8117 for (tindex = 0; tindex < len; ++tindex) {
8118 iclass = decode_typeid (p, &p, end, NULL, &err);
8122 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8124 return ERR_INVALID_ARGUMENT;
8126 nmethods = mono_class_num_methods (iclass);
8127 buffer_add_int (buf, nmethods);
8130 while ((method = mono_class_get_methods (iclass, &iter))) {
8131 buffer_add_methodid (buf, domain, method);
8133 for (i = 0; i < nmethods; ++i)
8134 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
8138 case CMD_TYPE_IS_INITIALIZED: {
8139 MonoVTable *vtable = mono_class_vtable (domain, klass);
8142 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8144 buffer_add_int (buf, 0);
8147 case CMD_TYPE_CREATE_INSTANCE: {
8150 obj = mono_object_new (domain, klass);
8151 buffer_add_objid (buf, obj);
8155 return ERR_NOT_IMPLEMENTED;
8162 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8165 MonoDomain *old_domain;
8169 klass = decode_typeid (p, &p, end, &domain, &err);
8173 old_domain = mono_domain_get ();
8175 mono_domain_set (domain, TRUE);
8177 err = type_commands_internal (command, klass, domain, p, end, buf);
8179 mono_domain_set (old_domain, TRUE);
8185 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8187 MonoMethodHeader *header;
8191 case CMD_METHOD_GET_NAME: {
8192 buffer_add_string (buf, method->name);
8195 case CMD_METHOD_GET_DECLARING_TYPE: {
8196 buffer_add_typeid (buf, domain, method->klass);
8199 case CMD_METHOD_GET_DEBUG_INFO: {
8200 MonoDebugMethodInfo *minfo;
8202 int i, j, n_il_offsets;
8205 int *column_numbers;
8206 int *end_line_numbers;
8207 int *end_column_numbers;
8209 GPtrArray *source_file_list;
8211 header = mono_method_get_header (method);
8213 buffer_add_int (buf, 0);
8214 buffer_add_string (buf, "");
8215 buffer_add_int (buf, 0);
8219 minfo = mono_debug_lookup_method (method);
8221 buffer_add_int (buf, header->code_size);
8222 buffer_add_string (buf, "");
8223 buffer_add_int (buf, 0);
8224 mono_metadata_free_mh (header);
8228 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, &n_il_offsets, &il_offsets, &line_numbers, &column_numbers, &source_files, &end_line_numbers, &end_column_numbers);
8229 buffer_add_int (buf, header->code_size);
8230 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8231 buffer_add_int (buf, source_file_list->len);
8232 for (i = 0; i < source_file_list->len; ++i) {
8233 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
8234 buffer_add_string (buf, sinfo->source_file);
8235 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8236 for (j = 0; j < 16; ++j)
8237 buffer_add_byte (buf, sinfo->hash [j]);
8241 buffer_add_string (buf, source_file);
8243 buffer_add_int (buf, n_il_offsets);
8244 DEBUG (10, fprintf (log_file, "Line number table for method %s:\n", mono_method_full_name (method, TRUE)));
8245 for (i = 0; i < n_il_offsets; ++i) {
8246 const char *srcfile = "";
8248 if (source_files [i] != -1) {
8249 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
8250 srcfile = sinfo->source_file;
8252 DEBUG (10, fprintf (log_file, "IL%x -> %s:%d %d\n", il_offsets [i], srcfile, line_numbers [i], column_numbers ? column_numbers [i] : -1));
8253 buffer_add_int (buf, il_offsets [i]);
8254 buffer_add_int (buf, line_numbers [i]);
8255 if (CHECK_PROTOCOL_VERSION (2, 13))
8256 buffer_add_int (buf, source_files [i]);
8257 if (CHECK_PROTOCOL_VERSION (2, 19))
8258 buffer_add_int (buf, column_numbers ? column_numbers [i] : -1);
8259 if (CHECK_PROTOCOL_VERSION (2, 32)) {
8260 buffer_add_int (buf, end_line_numbers ? end_line_numbers [i] : -1);
8261 buffer_add_int (buf, end_column_numbers ? end_column_numbers [i] : -1);
8264 g_free (source_file);
8265 g_free (il_offsets);
8266 g_free (line_numbers);
8267 g_free (column_numbers);
8268 g_free (end_line_numbers);
8269 g_free (end_column_numbers);
8270 g_free (source_files);
8271 g_ptr_array_free (source_file_list, TRUE);
8272 mono_metadata_free_mh (header);
8275 case CMD_METHOD_GET_PARAM_INFO: {
8276 MonoMethodSignature *sig = mono_method_signature (method);
8280 /* FIXME: mono_class_from_mono_type () and byrefs */
8282 /* FIXME: Use a smaller encoding */
8283 buffer_add_int (buf, sig->call_convention);
8284 buffer_add_int (buf, sig->param_count);
8285 buffer_add_int (buf, sig->generic_param_count);
8286 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
8287 for (i = 0; i < sig->param_count; ++i) {
8289 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
8292 /* Emit parameter names */
8293 names = g_new (char *, sig->param_count);
8294 mono_method_get_param_names (method, (const char **) names);
8295 for (i = 0; i < sig->param_count; ++i)
8296 buffer_add_string (buf, names [i]);
8301 case CMD_METHOD_GET_LOCALS_INFO: {
8302 int i, j, num_locals;
8303 MonoDebugLocalsInfo *locals;
8305 header = mono_method_get_header (method);
8307 return ERR_INVALID_ARGUMENT;
8309 buffer_add_int (buf, header->num_locals);
8312 for (i = 0; i < header->num_locals; ++i)
8313 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
8316 locals = mono_debug_lookup_locals (method);
8318 num_locals = locals->num_locals;
8321 for (i = 0; i < header->num_locals; ++i) {
8322 for (j = 0; j < num_locals; ++j)
8323 if (locals->locals [j].index == i)
8326 buffer_add_string (buf, locals->locals [j].name);
8328 buffer_add_string (buf, "");
8332 for (i = 0; i < header->num_locals; ++i) {
8333 for (j = 0; j < num_locals; ++j)
8334 if (locals->locals [j].index == i)
8336 if (j < num_locals && locals->locals [j].block) {
8337 buffer_add_int (buf, locals->locals [j].block->start_offset);
8338 buffer_add_int (buf, locals->locals [j].block->end_offset);
8340 buffer_add_int (buf, 0);
8341 buffer_add_int (buf, header->code_size);
8344 mono_metadata_free_mh (header);
8347 mono_debug_symfile_free_locals (locals);
8351 case CMD_METHOD_GET_INFO:
8352 buffer_add_int (buf, method->flags);
8353 buffer_add_int (buf, method->iflags);
8354 buffer_add_int (buf, method->token);
8355 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8357 if (method->is_generic)
8359 if (mono_method_signature (method)->generic_param_count)
8361 buffer_add_byte (buf, attrs);
8362 if (method->is_generic || method->is_inflated) {
8365 if (method->is_generic) {
8368 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8370 result = imethod->declaring;
8371 if (imethod->context.class_inst) {
8372 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8373 /*Generic methods gets the context of the GTD.*/
8374 if (mono_class_get_context (klass))
8375 result = mono_class_inflate_generic_method_full (result, klass, mono_class_get_context (klass));
8379 buffer_add_methodid (buf, domain, result);
8381 buffer_add_id (buf, 0);
8383 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8384 if (mono_method_signature (method)->generic_param_count) {
8387 if (method->is_inflated) {
8388 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
8390 count = inst->type_argc;
8391 buffer_add_int (buf, count);
8393 for (i = 0; i < count; i++)
8394 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8396 buffer_add_int (buf, 0);
8398 } else if (method->is_generic) {
8399 MonoGenericContainer *container = mono_method_get_generic_container (method);
8401 count = mono_method_signature (method)->generic_param_count;
8402 buffer_add_int (buf, count);
8403 for (i = 0; i < count; i++) {
8404 MonoGenericParam *param = mono_generic_container_get_param (container, i);
8405 MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
8406 buffer_add_typeid (buf, domain, pklass);
8409 buffer_add_int (buf, 0);
8412 buffer_add_int (buf, 0);
8417 case CMD_METHOD_GET_BODY: {
8420 header = mono_method_get_header (method);
8422 buffer_add_int (buf, 0);
8424 if (CHECK_PROTOCOL_VERSION (2, 18))
8425 buffer_add_int (buf, 0);
8427 buffer_add_int (buf, header->code_size);
8428 for (i = 0; i < header->code_size; ++i)
8429 buffer_add_byte (buf, header->code [i]);
8431 if (CHECK_PROTOCOL_VERSION (2, 18)) {
8432 buffer_add_int (buf, header->num_clauses);
8433 for (i = 0; i < header->num_clauses; ++i) {
8434 MonoExceptionClause *clause = &header->clauses [i];
8436 buffer_add_int (buf, clause->flags);
8437 buffer_add_int (buf, clause->try_offset);
8438 buffer_add_int (buf, clause->try_len);
8439 buffer_add_int (buf, clause->handler_offset);
8440 buffer_add_int (buf, clause->handler_len);
8441 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
8442 buffer_add_typeid (buf, domain, clause->data.catch_class);
8443 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8444 buffer_add_int (buf, clause->data.filter_offset);
8448 mono_metadata_free_mh (header);
8453 case CMD_METHOD_RESOLVE_TOKEN: {
8454 guint32 token = decode_int (p, &p, end);
8457 switch (mono_metadata_token_code (token)) {
8458 case MONO_TOKEN_STRING: {
8462 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
8465 s2 = mono_string_to_utf8 (s);
8467 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8468 buffer_add_string (buf, s2);
8474 MonoClass *handle_class;
8476 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8477 val = mono_method_get_wrapper_data (method, token);
8478 handle_class = mono_method_get_wrapper_data (method, token + 1);
8480 if (handle_class == NULL) {
8481 // Can't figure out the token type
8482 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8486 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
8490 if (handle_class == mono_defaults.typehandle_class) {
8491 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8492 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8493 buffer_add_typeid (buf, domain, (MonoClass *) val);
8495 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
8496 } else if (handle_class == mono_defaults.fieldhandle_class) {
8497 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8498 buffer_add_fieldid (buf, domain, val);
8499 } else if (handle_class == mono_defaults.methodhandle_class) {
8500 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8501 buffer_add_methodid (buf, domain, val);
8502 } else if (handle_class == mono_defaults.string_class) {
8505 s = mono_string_to_utf8 (val);
8506 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8507 buffer_add_string (buf, s);
8510 g_assert_not_reached ();
8517 case CMD_METHOD_GET_CATTRS: {
8518 MonoClass *attr_klass;
8519 MonoCustomAttrInfo *cinfo;
8521 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8522 /* attr_klass can be NULL */
8526 cinfo = mono_custom_attrs_from_method (method);
8528 buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
8531 case CMD_METHOD_MAKE_GENERIC_METHOD: {
8532 MonoType **type_argv;
8536 MonoGenericInst *ginst;
8537 MonoGenericContext tmp_context;
8538 MonoMethod *inflated;
8540 type_argc = decode_int (p, &p, end);
8541 type_argv = g_new0 (MonoType*, type_argc);
8542 for (i = 0; i < type_argc; ++i) {
8543 klass = decode_typeid (p, &p, end, &d, &err);
8550 return ERR_INVALID_ARGUMENT;
8552 type_argv [i] = &klass->byval_arg;
8554 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
8556 tmp_context.class_inst = method->klass->generic_class ? method->klass->generic_class->context.class_inst : NULL;
8557 tmp_context.method_inst = ginst;
8559 inflated = mono_class_inflate_generic_method (method, &tmp_context);
8560 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
8561 return ERR_INVALID_ARGUMENT;
8562 buffer_add_methodid (buf, domain, inflated);
8566 return ERR_NOT_IMPLEMENTED;
8573 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8576 MonoDomain *old_domain;
8580 method = decode_methodid (p, &p, end, &domain, &err);
8584 old_domain = mono_domain_get ();
8586 mono_domain_set (domain, TRUE);
8588 err = method_commands_internal (command, method, domain, p, end, buf);
8590 mono_domain_set (old_domain, TRUE);
8596 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8598 int objid = decode_objid (p, &p, end);
8600 MonoThread *thread_obj;
8601 MonoInternalThread *thread;
8603 err = get_object (objid, (MonoObject**)&thread_obj);
8607 thread = THREAD_TO_INTERNAL (thread_obj);
8610 case CMD_THREAD_GET_NAME: {
8612 gunichar2 *s = mono_thread_get_name (thread, &name_len);
8615 buffer_add_int (buf, 0);
8620 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
8622 buffer_add_int (buf, len);
8623 buffer_add_data (buf, (guint8*)name, len);
8628 case CMD_THREAD_GET_FRAME_INFO: {
8629 DebuggerTlsData *tls;
8630 int i, start_frame, length;
8632 // Wait for suspending if it already started
8633 // FIXME: Races with suspend_count
8634 while (!is_suspended ()) {
8636 wait_for_suspend ();
8640 wait_for_suspend ();
8641 if (!is_suspended ())
8642 return ERR_NOT_SUSPENDED;
8645 start_frame = decode_int (p, &p, end);
8646 length = decode_int (p, &p, end);
8648 if (start_frame != 0 || length != -1)
8649 return ERR_NOT_IMPLEMENTED;
8651 mono_loader_lock ();
8652 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8653 mono_loader_unlock ();
8656 compute_frame_info (thread, tls);
8658 buffer_add_int (buf, tls->frame_count);
8659 for (i = 0; i < tls->frame_count; ++i) {
8660 buffer_add_int (buf, tls->frames [i]->id);
8661 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
8662 buffer_add_int (buf, tls->frames [i]->il_offset);
8664 * Instead of passing the frame type directly to the client, we associate
8665 * it with the previous frame using a set of flags. This avoids lots of
8666 * conditional code in the client, since a frame whose type isn't
8667 * FRAME_TYPE_MANAGED has no method, location, etc.
8669 buffer_add_byte (buf, tls->frames [i]->flags);
8674 case CMD_THREAD_GET_STATE:
8675 buffer_add_int (buf, thread->state);
8677 case CMD_THREAD_GET_INFO:
8678 buffer_add_byte (buf, thread->threadpool_thread);
8680 case CMD_THREAD_GET_ID:
8681 buffer_add_long (buf, (guint64)(gsize)thread);
8683 case CMD_THREAD_GET_TID:
8684 buffer_add_long (buf, (guint64)thread->tid);
8686 case CMD_THREAD_SET_IP: {
8687 DebuggerTlsData *tls;
8690 MonoSeqPointInfo *seq_points;
8691 SeqPoint *sp = NULL;
8695 method = decode_methodid (p, &p, end, &domain, &err);
8698 il_offset = decode_long (p, &p, end);
8700 while (!is_suspended ()) {
8702 wait_for_suspend ();
8705 mono_loader_lock ();
8706 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8707 mono_loader_unlock ();
8710 compute_frame_info (thread, tls);
8711 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
8712 return ERR_INVALID_ARGUMENT;
8714 seq_points = get_seq_points (domain, method);
8715 g_assert (seq_points);
8717 for (i = 0; i < seq_points->len; ++i) {
8718 sp = &seq_points->seq_points [i];
8720 if (sp->il_offset == il_offset)
8723 if (i == seq_points->len)
8724 return ERR_INVALID_ARGUMENT;
8726 // FIXME: Check that the ip change is safe
8728 DEBUG (1, fprintf (log_file, "[dbg] Setting IP to %s:0x%0x(0x%0x)\n", tls->frames [0]->actual_method->name, (int)sp->il_offset, (int)sp->native_offset));
8729 MONO_CONTEXT_SET_IP (&tls->restore_ctx, (guint8*)tls->frames [0]->ji->code_start + sp->native_offset);
8733 return ERR_NOT_IMPLEMENTED;
8740 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8744 MonoThread *thread_obj;
8745 MonoInternalThread *thread;
8746 int pos, i, len, frame_idx;
8747 DebuggerTlsData *tls;
8749 MonoDebugMethodJitInfo *jit;
8750 MonoDebugVarInfo *var;
8751 MonoMethodSignature *sig;
8753 MonoMethodHeader *header;
8755 objid = decode_objid (p, &p, end);
8756 err = get_object (objid, (MonoObject**)&thread_obj);
8760 thread = THREAD_TO_INTERNAL (thread_obj);
8762 id = decode_id (p, &p, end);
8764 mono_loader_lock ();
8765 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8766 mono_loader_unlock ();
8769 for (i = 0; i < tls->frame_count; ++i) {
8770 if (tls->frames [i]->id == id)
8773 if (i == tls->frame_count)
8774 return ERR_INVALID_FRAMEID;
8777 frame = tls->frames [frame_idx];
8779 if (!frame->has_ctx)
8780 return ERR_ABSENT_INFORMATION;
8783 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
8784 if (!frame->jit && frame->api_method->is_inflated)
8785 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
8789 /* This could happen for aot images with no jit debug info */
8790 s = mono_method_full_name (frame->api_method, TRUE);
8791 DEBUG (1, fprintf (log_file, "[dbg] No debug information found for '%s'.\n", s));
8793 return ERR_ABSENT_INFORMATION;
8798 sig = mono_method_signature (frame->actual_method);
8800 if (!get_seq_points (frame->domain, frame->actual_method))
8802 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
8804 return ERR_ABSENT_INFORMATION;
8807 case CMD_STACK_FRAME_GET_VALUES: {
8808 len = decode_int (p, &p, end);
8809 header = mono_method_get_header (frame->actual_method);
8811 for (i = 0; i < len; ++i) {
8812 pos = decode_int (p, &p, end);
8817 g_assert (pos >= 0 && pos < jit->num_params);
8819 var = &jit->params [pos];
8821 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
8823 g_assert (pos >= 0 && pos < jit->num_locals);
8825 var = &jit->locals [pos];
8827 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
8830 mono_metadata_free_mh (header);
8833 case CMD_STACK_FRAME_GET_THIS: {
8834 if (frame->api_method->klass->valuetype) {
8835 if (!sig->hasthis) {
8836 MonoObject *p = NULL;
8837 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
8839 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8842 if (!sig->hasthis) {
8843 MonoObject *p = NULL;
8844 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
8846 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8851 case CMD_STACK_FRAME_SET_VALUES: {
8854 MonoDebugVarInfo *var;
8856 len = decode_int (p, &p, end);
8857 header = mono_method_get_header (frame->actual_method);
8859 for (i = 0; i < len; ++i) {
8860 pos = decode_int (p, &p, end);
8865 g_assert (pos >= 0 && pos < jit->num_params);
8867 t = sig->params [pos];
8868 var = &jit->params [pos];
8870 g_assert (pos >= 0 && pos < jit->num_locals);
8872 t = header->locals [pos];
8873 var = &jit->locals [pos];
8876 if (MONO_TYPE_IS_REFERENCE (t))
8877 val_buf = g_alloca (sizeof (MonoObject*));
8879 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
8880 err = decode_value (t, frame->domain, val_buf, p, &p, end);
8884 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_ctx);
8886 mono_metadata_free_mh (header);
8890 return ERR_NOT_IMPLEMENTED;
8897 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8900 int objid, err, index, len, i, esize;
8903 objid = decode_objid (p, &p, end);
8904 err = get_object (objid, (MonoObject**)&arr);
8909 case CMD_ARRAY_REF_GET_LENGTH:
8910 buffer_add_int (buf, arr->obj.vtable->klass->rank);
8912 buffer_add_int (buf, arr->max_length);
8913 buffer_add_int (buf, 0);
8915 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
8916 buffer_add_int (buf, arr->bounds [i].length);
8917 buffer_add_int (buf, arr->bounds [i].lower_bound);
8921 case CMD_ARRAY_REF_GET_VALUES:
8922 index = decode_int (p, &p, end);
8923 len = decode_int (p, &p, end);
8925 g_assert (index >= 0 && len >= 0);
8926 // Reordered to avoid integer overflow
8927 g_assert (!(index > arr->max_length - len));
8929 esize = mono_array_element_size (arr->obj.vtable->klass);
8930 for (i = index; i < index + len; ++i) {
8931 elem = (gpointer*)((char*)arr->vector + (i * esize));
8932 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
8935 case CMD_ARRAY_REF_SET_VALUES:
8936 index = decode_int (p, &p, end);
8937 len = decode_int (p, &p, end);
8939 g_assert (index >= 0 && len >= 0);
8940 // Reordered to avoid integer overflow
8941 g_assert (!(index > arr->max_length - len));
8943 esize = mono_array_element_size (arr->obj.vtable->klass);
8944 for (i = index; i < index + len; ++i) {
8945 elem = (gpointer*)((char*)arr->vector + (i * esize));
8947 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
8951 return ERR_NOT_IMPLEMENTED;
8958 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8963 int i, index, length;
8966 objid = decode_objid (p, &p, end);
8967 err = get_object (objid, (MonoObject**)&str);
8972 case CMD_STRING_REF_GET_VALUE:
8973 s = mono_string_to_utf8 (str);
8974 buffer_add_string (buf, s);
8977 case CMD_STRING_REF_GET_LENGTH:
8978 buffer_add_long (buf, mono_string_length (str));
8980 case CMD_STRING_REF_GET_CHARS:
8981 index = decode_long (p, &p, end);
8982 length = decode_long (p, &p, end);
8983 if (index > mono_string_length (str) - length)
8984 return ERR_INVALID_ARGUMENT;
8985 c = mono_string_chars (str) + index;
8986 for (i = 0; i < length; ++i)
8987 buffer_add_short (buf, c [i]);
8990 return ERR_NOT_IMPLEMENTED;
8997 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9006 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9007 objid = decode_objid (p, &p, end);
9008 err = get_object (objid, &obj);
9010 buffer_add_int (buf, 1);
9012 buffer_add_int (buf, 0);
9016 objid = decode_objid (p, &p, end);
9017 err = get_object (objid, &obj);
9022 case CMD_OBJECT_REF_GET_TYPE:
9023 /* This handles transparent proxies too */
9024 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9026 case CMD_OBJECT_REF_GET_VALUES:
9027 len = decode_int (p, &p, end);
9029 for (i = 0; i < len; ++i) {
9030 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9034 /* Check that the field belongs to the object */
9036 for (k = obj->vtable->klass; k; k = k->parent) {
9037 if (k == f->parent) {
9043 return ERR_INVALID_FIELDID;
9045 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9049 if (mono_class_field_is_special_static (f))
9050 return ERR_INVALID_FIELDID;
9052 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9053 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9054 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9055 mono_field_static_get_value (vtable, f, val);
9056 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9059 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
9063 case CMD_OBJECT_REF_SET_VALUES:
9064 len = decode_int (p, &p, end);
9066 for (i = 0; i < len; ++i) {
9067 f = decode_fieldid (p, &p, end, NULL, &err);
9071 /* Check that the field belongs to the object */
9073 for (k = obj->vtable->klass; k; k = k->parent) {
9074 if (k == f->parent) {
9080 return ERR_INVALID_FIELDID;
9082 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9086 if (mono_class_field_is_special_static (f))
9087 return ERR_INVALID_FIELDID;
9089 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9090 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9092 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9093 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
9098 mono_field_static_set_value (vtable, f, val);
9101 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
9107 case CMD_OBJECT_REF_GET_ADDRESS:
9108 buffer_add_long (buf, (gssize)obj);
9110 case CMD_OBJECT_REF_GET_DOMAIN:
9111 buffer_add_domainid (buf, obj->vtable->domain);
9113 case CMD_OBJECT_REF_GET_INFO:
9114 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9115 buffer_add_domainid (buf, obj->vtable->domain);
9118 return ERR_NOT_IMPLEMENTED;
9125 command_set_to_string (CommandSet command_set)
9127 switch (command_set) {
9130 case CMD_SET_OBJECT_REF:
9131 return "OBJECT_REF";
9132 case CMD_SET_STRING_REF:
9133 return "STRING_REF";
9134 case CMD_SET_THREAD:
9136 case CMD_SET_ARRAY_REF:
9138 case CMD_SET_EVENT_REQUEST:
9139 return "EVENT_REQUEST";
9140 case CMD_SET_STACK_FRAME:
9141 return "STACK_FRAME";
9142 case CMD_SET_APPDOMAIN:
9144 case CMD_SET_ASSEMBLY:
9146 case CMD_SET_METHOD:
9150 case CMD_SET_MODULE:
9161 static const char* vm_cmds_str [] = {
9169 "SET_PROTOCOL_VERSION",
9172 "GET_TYPES_FOR_SOURCE_FILE",
9177 static const char* thread_cmds_str[] = {
9187 static const char* event_cmds_str[] = {
9190 "REQUEST_CLEAR_ALL_BREAKPOINTS"
9193 static const char* appdomain_cmds_str[] = {
9195 "GET_FRIENDLY_NAME",
9197 "GET_ENTRY_ASSEMBLY",
9200 "CREATE_BOXED_VALUE"
9203 static const char* assembly_cmds_str[] = {
9206 "GET_MANIFEST_MODULE",
9212 static const char* module_cmds_str[] = {
9216 static const char* field_cmds_str[] = {
9220 static const char* method_cmds_str[] = {
9222 "GET_DECLARING_TYPE",
9230 "MAKE_GENERIC_METHOD"
9233 static const char* type_cmds_str[] = {
9241 "IS_ASSIGNABLE_FROM",
9245 "GET_PROPERTY_CATTRS",
9246 "GET_SOURCE_FILES_2",
9248 "GET_METHODS_BY_NAME_FLAGS",
9250 "GET_INTERFACE_MAP",
9254 static const char* stack_frame_cmds_str[] = {
9260 static const char* array_cmds_str[] = {
9266 static const char* string_cmds_str[] = {
9272 static const char* object_cmds_str[] = {
9283 cmd_to_string (CommandSet set, int command)
9291 cmds_len = G_N_ELEMENTS (vm_cmds_str);
9293 case CMD_SET_OBJECT_REF:
9294 cmds = object_cmds_str;
9295 cmds_len = G_N_ELEMENTS (object_cmds_str);
9297 case CMD_SET_STRING_REF:
9298 cmds = string_cmds_str;
9299 cmds_len = G_N_ELEMENTS (string_cmds_str);
9301 case CMD_SET_THREAD:
9302 cmds = thread_cmds_str;
9303 cmds_len = G_N_ELEMENTS (thread_cmds_str);
9305 case CMD_SET_ARRAY_REF:
9306 cmds = array_cmds_str;
9307 cmds_len = G_N_ELEMENTS (array_cmds_str);
9309 case CMD_SET_EVENT_REQUEST:
9310 cmds = event_cmds_str;
9311 cmds_len = G_N_ELEMENTS (event_cmds_str);
9313 case CMD_SET_STACK_FRAME:
9314 cmds = stack_frame_cmds_str;
9315 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
9317 case CMD_SET_APPDOMAIN:
9318 cmds = appdomain_cmds_str;
9319 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
9321 case CMD_SET_ASSEMBLY:
9322 cmds = assembly_cmds_str;
9323 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
9325 case CMD_SET_METHOD:
9326 cmds = method_cmds_str;
9327 cmds_len = G_N_ELEMENTS (method_cmds_str);
9330 cmds = type_cmds_str;
9331 cmds_len = G_N_ELEMENTS (type_cmds_str);
9333 case CMD_SET_MODULE:
9334 cmds = module_cmds_str;
9335 cmds_len = G_N_ELEMENTS (module_cmds_str);
9338 cmds = field_cmds_str;
9339 cmds_len = G_N_ELEMENTS (field_cmds_str);
9342 cmds = event_cmds_str;
9343 cmds_len = G_N_ELEMENTS (event_cmds_str);
9348 if (command > 0 && command <= cmds_len)
9349 return cmds [command - 1];
9355 wait_for_attach (void)
9357 #ifndef DISABLE_SOCKET_TRANSPORT
9358 if (listen_fd == -1) {
9359 DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
9363 /* Block and wait for client connection */
9364 conn_fd = socket_transport_accept (listen_fd);
9365 DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
9366 if (conn_fd == -1) {
9367 DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
9371 g_assert_not_reached ();
9375 disconnected = !transport_handshake ();
9377 DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
9387 * This thread handles communication with the debugger client using a JDWP
9390 static guint32 WINAPI
9391 debugger_thread (void *arg)
9393 int res, len, id, flags, command_set = 0, command = 0;
9394 guint8 header [HEADER_LENGTH];
9395 guint8 *data, *p, *end;
9399 gboolean attach_failed = FALSE;
9401 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
9403 debugger_thread_id = GetCurrentThreadId ();
9405 mono_jit_thread_attach (mono_get_root_domain ());
9407 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
9409 mono_set_is_debugger_attached (TRUE);
9411 if (agent_config.defer) {
9412 if (!wait_for_attach ()) {
9413 DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
9414 attach_failed = TRUE; // Don't abort process when we can't listen
9416 /* Send start event to client */
9417 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
9421 while (!attach_failed) {
9422 res = transport_recv (header, HEADER_LENGTH);
9424 /* This will break if the socket is closed during shutdown too */
9425 if (res != HEADER_LENGTH) {
9426 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH));
9431 end = header + HEADER_LENGTH;
9433 len = decode_int (p, &p, end);
9434 id = decode_int (p, &p, end);
9435 flags = decode_byte (p, &p, end);
9436 command_set = decode_byte (p, &p, end);
9437 command = decode_byte (p, &p, end);
9439 g_assert (flags == 0);
9442 const char *cmd_str;
9445 cmd_str = cmd_to_string (command_set, command);
9447 sprintf (cmd_num, "%d", command);
9451 DEBUG (1, fprintf (log_file, "[dbg] Command %s(%s) [%d][at=%lx].\n", command_set_to_string (command_set), cmd_str, id, (long)mono_100ns_ticks () / 10000));
9454 data = g_malloc (len - HEADER_LENGTH);
9455 if (len - HEADER_LENGTH > 0)
9457 res = transport_recv (data, len - HEADER_LENGTH);
9458 if (res != len - HEADER_LENGTH) {
9459 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH));
9465 end = data + (len - HEADER_LENGTH);
9467 buffer_init (&buf, 128);
9472 /* Process the request */
9473 switch (command_set) {
9475 err = vm_commands (command, id, p, end, &buf);
9476 if (!err && command == CMD_VM_INVOKE_METHOD)
9477 /* Sent after the invoke is complete */
9480 case CMD_SET_EVENT_REQUEST:
9481 err = event_commands (command, p, end, &buf);
9483 case CMD_SET_APPDOMAIN:
9484 err = domain_commands (command, p, end, &buf);
9486 case CMD_SET_ASSEMBLY:
9487 err = assembly_commands (command, p, end, &buf);
9489 case CMD_SET_MODULE:
9490 err = module_commands (command, p, end, &buf);
9493 err = field_commands (command, p, end, &buf);
9496 err = type_commands (command, p, end, &buf);
9498 case CMD_SET_METHOD:
9499 err = method_commands (command, p, end, &buf);
9501 case CMD_SET_THREAD:
9502 err = thread_commands (command, p, end, &buf);
9504 case CMD_SET_STACK_FRAME:
9505 err = frame_commands (command, p, end, &buf);
9507 case CMD_SET_ARRAY_REF:
9508 err = array_commands (command, p, end, &buf);
9510 case CMD_SET_STRING_REF:
9511 err = string_commands (command, p, end, &buf);
9513 case CMD_SET_OBJECT_REF:
9514 err = object_commands (command, p, end, &buf);
9517 err = ERR_NOT_IMPLEMENTED;
9520 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
9521 buffer_replies = TRUE;
9525 if (buffer_replies) {
9526 buffer_reply_packet (id, err, &buf);
9528 send_reply_packet (id, err, &buf);
9529 //DEBUG (1, fprintf (log_file, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000));
9533 if (!err && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
9534 send_buffered_reply_packets ();
9535 buffer_replies = FALSE;
9541 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
9545 mono_set_is_debugger_attached (FALSE);
9547 mono_mutex_lock (&debugger_thread_exited_mutex);
9548 debugger_thread_exited = TRUE;
9549 mono_cond_signal (&debugger_thread_exited_cond);
9550 mono_mutex_unlock (&debugger_thread_exited_mutex);
9552 DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
9554 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
9555 DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
9556 start_debugger_thread ();
9562 #else /* DISABLE_DEBUGGER_AGENT */
9565 mono_debugger_agent_parse_options (char *options)
9567 g_error ("This runtime is configured with the debugger agent disabled.");
9571 mono_debugger_agent_init (void)
9576 mono_debugger_agent_breakpoint_hit (void *sigctx)
9581 mono_debugger_agent_single_step_event (void *sigctx)
9586 mono_debugger_agent_free_domain_info (MonoDomain *domain)
9591 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
9597 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
9598 MonoContext *catch_ctx)
9603 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9608 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9613 mono_debugger_agent_user_break (void)
9619 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
9624 mono_debugger_agent_debug_log_is_enabled (void)