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/threads-types.h>
73 #include <mono/metadata/socket-io.h>
74 #include <mono/metadata/assembly.h>
75 #include <mono/utils/mono-semaphore.h>
76 #include <mono/utils/mono-error-internals.h>
77 #include <mono/utils/mono-stack-unwinding.h>
78 #include <mono/utils/mono-time.h>
79 #include <mono/utils/mono-threads.h>
80 #include "debugger-agent.h"
83 #if defined(__APPLE__)
84 #include <TargetConditionals.h>
87 On iOS we can't use System.Environment.Exit () as it will do the wrong
90 #if !defined (TARGET_OS_IPHONE) || !(TARGET_OS_IPHONE == 1 || TARGET_IPHONE_SIMULATOR == 1)
91 #define TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
95 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
96 #define DISABLE_DEBUGGER_AGENT 1
99 #ifdef DISABLE_SOFT_DEBUG
100 #define DISABLE_DEBUGGER_AGENT 1
103 #ifndef DISABLE_DEBUGGER_AGENT
105 #include <mono/io-layer/mono-mutex.h>
107 /* Definitions to make backporting to 2.6 easier */
108 //#define MonoInternalThread MonoThread
109 //#define mono_thread_internal_current mono_thread_current
110 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
132 guint32 il_offset, native_offset;
136 * If method is gshared, this is the actual instance, otherwise this is equal to
139 MonoMethod *actual_method;
141 * This is the method which is visible to debugger clients. Same as method,
142 * except for native-to-managed wrappers.
144 MonoMethod *api_method;
146 MonoDebugMethodJitInfo *jit;
149 mgreg_t *reg_locations [MONO_MAX_IREGS];
151 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
152 * the frame can become invalid.
157 typedef struct _InvokeData InvokeData;
165 /* This is the context which needs to be restored after the invoke */
169 * If this is set, invoke this method with the arguments given by ARGS.
173 guint32 suspend_count;
176 InvokeData *last_invoke;
180 MonoThreadUnwindState context;
182 /* This is computed on demand when it is requested using the wire protocol */
183 /* It is freed up when the thread is resumed */
187 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
190 gboolean frames_up_to_date;
192 * Points to data about a pending invoke which needs to be executed after the thread
195 InvokeData *pending_invoke;
197 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
202 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
203 * within a finite amount of time.
207 * Set to TRUE if this thread is suspended in suspend_current ().
209 gboolean really_suspended;
210 /* Used to pass the context to the breakpoint/single step handler */
211 MonoContext handler_ctx;
212 /* Whenever thread_stop () was called for this thread */
215 /* Number of thread interruptions not yet processed */
216 gint32 interrupt_count;
218 /* Whenever to disable breakpoints (used during invokes) */
219 gboolean disable_breakpoints;
222 * Number of times this thread has been resumed using resume_thread ().
224 guint32 resume_count;
226 MonoInternalThread *thread;
229 * Information about the frame which transitioned to native code for running
232 StackFrameInfo async_last_frame;
235 * The context where the stack walk can be started for running threads.
237 MonoThreadUnwindState async_state;
240 * The context used for filter clauses
242 MonoThreadUnwindState filter_state;
245 * The callee address of the last mono_runtime_invoke call
247 gpointer invoke_addr;
249 gboolean abort_requested;
252 * The current mono_runtime_invoke invocation.
257 * The context where single stepping should resume while the thread is suspended because
258 * of an EXCEPTION event.
260 MonoContext catch_ctx;
262 gboolean has_catch_ctx;
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;
274 void (*connect) (const char *address);
275 void (*close1) (void);
276 void (*close2) (void);
277 gboolean (*send) (void *buf, int len);
278 int (*recv) (void *buf, int len);
282 * Wire Protocol definitions
285 #define HEADER_LENGTH 11
287 #define MAJOR_VERSION 2
288 #define MINOR_VERSION 22
292 CMD_SET_OBJECT_REF = 9,
293 CMD_SET_STRING_REF = 10,
295 CMD_SET_ARRAY_REF = 13,
296 CMD_SET_EVENT_REQUEST = 15,
297 CMD_SET_STACK_FRAME = 16,
298 CMD_SET_APPDOMAIN = 20,
299 CMD_SET_ASSEMBLY = 21,
307 EVENT_KIND_VM_START = 0,
308 EVENT_KIND_VM_DEATH = 1,
309 EVENT_KIND_THREAD_START = 2,
310 EVENT_KIND_THREAD_DEATH = 3,
311 EVENT_KIND_APPDOMAIN_CREATE = 4,
312 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
313 EVENT_KIND_METHOD_ENTRY = 6,
314 EVENT_KIND_METHOD_EXIT = 7,
315 EVENT_KIND_ASSEMBLY_LOAD = 8,
316 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
317 EVENT_KIND_BREAKPOINT = 10,
318 EVENT_KIND_STEP = 11,
319 EVENT_KIND_TYPE_LOAD = 12,
320 EVENT_KIND_EXCEPTION = 13,
321 EVENT_KIND_KEEPALIVE = 14,
322 EVENT_KIND_USER_BREAK = 15,
323 EVENT_KIND_USER_LOG = 16
327 SUSPEND_POLICY_NONE = 0,
328 SUSPEND_POLICY_EVENT_THREAD = 1,
329 SUSPEND_POLICY_ALL = 2
334 ERR_INVALID_OBJECT = 20,
335 ERR_INVALID_FIELDID = 25,
336 ERR_INVALID_FRAMEID = 30,
337 ERR_NOT_IMPLEMENTED = 100,
338 ERR_NOT_SUSPENDED = 101,
339 ERR_INVALID_ARGUMENT = 102,
341 ERR_NO_INVOCATION = 104,
342 ERR_ABSENT_INFORMATION = 105,
343 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
344 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
349 MOD_KIND_THREAD_ONLY = 3,
350 MOD_KIND_LOCATION_ONLY = 7,
351 MOD_KIND_EXCEPTION_ONLY = 8,
353 MOD_KIND_ASSEMBLY_ONLY = 11,
354 MOD_KIND_SOURCE_FILE_ONLY = 12,
355 MOD_KIND_TYPE_NAME_ONLY = 13
370 STEP_FILTER_NONE = 0,
371 STEP_FILTER_STATIC_CTOR = 1,
372 STEP_FILTER_DEBUGGER_HIDDEN = 2
376 TOKEN_TYPE_STRING = 0,
378 TOKEN_TYPE_FIELD = 2,
379 TOKEN_TYPE_METHOD = 3,
380 TOKEN_TYPE_UNKNOWN = 4
384 VALUE_TYPE_ID_NULL = 0xf0,
385 VALUE_TYPE_ID_TYPE = 0xf1
389 FRAME_FLAG_DEBUGGER_INVOKE = 1,
390 FRAME_FLAG_NATIVE_TRANSITION = 2
394 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
395 INVOKE_FLAG_SINGLE_THREADED = 2
399 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
400 } BindingFlagsExtensions;
404 CMD_VM_ALL_THREADS = 2,
409 CMD_VM_INVOKE_METHOD = 7,
410 CMD_VM_SET_PROTOCOL_VERSION = 8,
411 CMD_VM_ABORT_INVOKE = 9,
412 CMD_VM_SET_KEEPALIVE = 10,
413 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
414 CMD_VM_GET_TYPES = 12,
415 CMD_VM_INVOKE_METHODS = 13
419 CMD_THREAD_GET_FRAME_INFO = 1,
420 CMD_THREAD_GET_NAME = 2,
421 CMD_THREAD_GET_STATE = 3,
422 CMD_THREAD_GET_INFO = 4,
423 CMD_THREAD_GET_ID = 5,
424 CMD_THREAD_GET_TID = 6
428 CMD_EVENT_REQUEST_SET = 1,
429 CMD_EVENT_REQUEST_CLEAR = 2,
430 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
438 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
439 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
440 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
441 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
442 CMD_APPDOMAIN_CREATE_STRING = 5,
443 CMD_APPDOMAIN_GET_CORLIB = 6,
444 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
448 CMD_ASSEMBLY_GET_LOCATION = 1,
449 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
450 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
451 CMD_ASSEMBLY_GET_OBJECT = 4,
452 CMD_ASSEMBLY_GET_TYPE = 5,
453 CMD_ASSEMBLY_GET_NAME = 6
457 CMD_MODULE_GET_INFO = 1,
461 CMD_METHOD_GET_NAME = 1,
462 CMD_METHOD_GET_DECLARING_TYPE = 2,
463 CMD_METHOD_GET_DEBUG_INFO = 3,
464 CMD_METHOD_GET_PARAM_INFO = 4,
465 CMD_METHOD_GET_LOCALS_INFO = 5,
466 CMD_METHOD_GET_INFO = 6,
467 CMD_METHOD_GET_BODY = 7,
468 CMD_METHOD_RESOLVE_TOKEN = 8,
469 CMD_METHOD_GET_CATTRS = 9,
473 CMD_TYPE_GET_INFO = 1,
474 CMD_TYPE_GET_METHODS = 2,
475 CMD_TYPE_GET_FIELDS = 3,
476 CMD_TYPE_GET_VALUES = 4,
477 CMD_TYPE_GET_OBJECT = 5,
478 CMD_TYPE_GET_SOURCE_FILES = 6,
479 CMD_TYPE_SET_VALUES = 7,
480 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
481 CMD_TYPE_GET_PROPERTIES = 9,
482 CMD_TYPE_GET_CATTRS = 10,
483 CMD_TYPE_GET_FIELD_CATTRS = 11,
484 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
485 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
486 CMD_TYPE_GET_VALUES_2 = 14,
487 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
488 CMD_TYPE_GET_INTERFACES = 16,
489 CMD_TYPE_GET_INTERFACE_MAP = 17,
493 CMD_STACK_FRAME_GET_VALUES = 1,
494 CMD_STACK_FRAME_GET_THIS = 2,
495 CMD_STACK_FRAME_SET_VALUES = 3
499 CMD_ARRAY_REF_GET_LENGTH = 1,
500 CMD_ARRAY_REF_GET_VALUES = 2,
501 CMD_ARRAY_REF_SET_VALUES = 3,
505 CMD_STRING_REF_GET_VALUE = 1,
506 CMD_STRING_REF_GET_LENGTH = 2,
507 CMD_STRING_REF_GET_CHARS = 3
511 CMD_OBJECT_REF_GET_TYPE = 1,
512 CMD_OBJECT_REF_GET_VALUES = 2,
513 CMD_OBJECT_REF_IS_COLLECTED = 3,
514 CMD_OBJECT_REF_GET_ADDRESS = 4,
515 CMD_OBJECT_REF_GET_DOMAIN = 5,
516 CMD_OBJECT_REF_SET_VALUES = 6,
517 CMD_OBJECT_REF_GET_INFO = 7,
523 int count; /* For kind == MOD_KIND_COUNT */
524 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
525 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
526 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
527 GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
528 GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
529 StepFilter filter; /* For kind == MOD_KIND_STEP */
531 gboolean caught, uncaught; /* For kind == MOD_KIND_EXCEPTION_ONLY */
540 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
544 * Describes a single step request.
548 MonoInternalThread *thread;
554 MonoMethod *last_method;
556 /* Whenever single stepping is performed using start/stop_single_stepping () */
558 /* The list of breakpoints used to implement step-over */
563 * Contains additional information for an event
566 /* For EVENT_KIND_EXCEPTION */
568 MonoContext catch_ctx;
570 /* For EVENT_KIND_USER_LOG */
572 char *category, *message;
573 /* For EVENT_KIND_TYPE_LOAD */
577 /* Dummy structure used for the profiler callbacks */
582 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
585 #define get_last_sock_error() WSAGetLastError()
586 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
587 #define MONO_EINTR WSAEINTR
589 #define get_last_sock_error() errno
590 #define MONO_EWOULDBLOCK EWOULDBLOCK
591 #define MONO_EINTR EINTR
594 #define CHECK_PROTOCOL_VERSION(major,minor) \
595 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
601 static AgentConfig agent_config;
604 * Whenever the agent is fully initialized.
605 * When using the onuncaught or onthrow options, only some parts of the agent are
606 * initialized on startup, and the full initialization which includes connection
607 * establishment and the startup of the agent thread is only done in response to
610 static gint32 inited;
612 #ifndef DISABLE_SOCKET_TRANSPORT
614 static int listen_fd;
617 static int packet_id = 0;
619 static int objref_id = 0;
621 static int event_request_id = 0;
623 static int frame_id = 0;
625 static GPtrArray *event_requests;
627 static MonoNativeTlsKey debugger_tls_id;
629 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
631 /* Maps MonoInternalThread -> DebuggerTlsData */
632 static MonoGHashTable *thread_to_tls;
634 /* Maps tid -> MonoInternalThread */
635 static MonoGHashTable *tid_to_thread;
637 /* Maps tid -> MonoThread (not MonoInternalThread) */
638 static MonoGHashTable *tid_to_thread_obj;
640 static gsize debugger_thread_id;
642 static HANDLE debugger_thread_handle;
644 static int log_level;
646 static gboolean embedding;
648 static FILE *log_file;
650 /* Assemblies whose assembly load event has no been sent yet */
651 static GPtrArray *pending_assembly_loads;
653 /* Whenever the debugger thread has exited */
654 static gboolean debugger_thread_exited;
656 /* Cond variable used to wait for debugger_thread_exited becoming true */
657 static mono_cond_t debugger_thread_exited_cond;
659 /* Mutex for the cond var above */
660 static mono_mutex_t debugger_thread_exited_mutex;
662 static DebuggerProfiler debugger_profiler;
664 /* The single step request instance */
665 static SingleStepReq *ss_req = NULL;
666 static gpointer ss_invoke_addr = NULL;
668 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
669 /* Number of single stepping operations in progress */
673 /* The protocol version of the client */
674 static int major_version, minor_version;
676 /* Whenever the variables above are set by the client */
677 static gboolean protocol_version_set;
679 /* A hash table containing all active domains */
680 static GHashTable *domains;
682 static void transport_init (void);
683 static void transport_connect (const char *address);
684 static gboolean transport_handshake (void);
685 static void register_transport (DebuggerTransport *trans);
687 static guint32 WINAPI debugger_thread (void *arg);
689 static void runtime_initialized (MonoProfiler *prof);
691 static void runtime_shutdown (MonoProfiler *prof);
693 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
695 static void thread_end (MonoProfiler *prof, uintptr_t tid);
697 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
699 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
701 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
703 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
705 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
707 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
709 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
711 static void emit_assembly_load (gpointer assembly, gpointer user_data);
713 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
715 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
717 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
719 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
721 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
723 static void start_single_stepping (void);
725 static void stop_single_stepping (void);
727 static void suspend_current (void);
729 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
731 static void clear_types_for_assembly (MonoAssembly *assembly);
733 static void clear_breakpoints_for_domain (MonoDomain *domain);
735 static void process_profiler_event (EventKind event, gpointer arg);
737 /* Submodule init/cleanup */
738 static void breakpoints_init (void);
739 static void breakpoints_cleanup (void);
741 static void objrefs_init (void);
742 static void objrefs_cleanup (void);
744 static void ids_init (void);
745 static void ids_cleanup (void);
747 static void suspend_init (void);
749 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch);
750 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
751 static void ss_destroy (SingleStepReq *req);
753 static void start_debugger_thread (void);
754 static void stop_debugger_thread (void);
756 static void finish_agent_init (gboolean on_startup);
758 static void process_profiler_event (EventKind event, gpointer arg);
760 static void invalidate_frames (DebuggerTlsData *tls);
762 #ifndef DISABLE_SOCKET_TRANSPORT
764 register_socket_transport (void);
768 parse_address (char *address, char **host, int *port)
770 char *pos = strchr (address, ':');
772 if (pos == NULL || pos == address)
775 *host = g_malloc (pos - address + 1);
776 strncpy (*host, address, pos - address);
777 (*host) [pos - address] = '\0';
779 *port = atoi (pos + 1);
787 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
788 fprintf (stderr, "Available options:\n");
789 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
790 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
791 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
792 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
793 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
794 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
795 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
796 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
797 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
801 parse_flag (const char *option, char *flag)
803 if (!strcmp (flag, "y"))
805 else if (!strcmp (flag, "n"))
808 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
815 mono_debugger_agent_parse_options (char *options)
822 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
823 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
827 extra = getenv ("MONO_SDB_ENV_OPTIONS");
829 options = g_strdup_printf ("%s,%s", options, extra);
831 agent_config.enabled = TRUE;
832 agent_config.suspend = TRUE;
833 agent_config.server = FALSE;
834 agent_config.defer = FALSE;
835 agent_config.address = NULL;
837 args = g_strsplit (options, ",", -1);
838 for (ptr = args; ptr && *ptr; ptr ++) {
841 if (strncmp (arg, "transport=", 10) == 0) {
842 agent_config.transport = g_strdup (arg + 10);
843 } else if (strncmp (arg, "address=", 8) == 0) {
844 agent_config.address = g_strdup (arg + 8);
845 } else if (strncmp (arg, "loglevel=", 9) == 0) {
846 agent_config.log_level = atoi (arg + 9);
847 } else if (strncmp (arg, "logfile=", 8) == 0) {
848 agent_config.log_file = g_strdup (arg + 8);
849 } else if (strncmp (arg, "suspend=", 8) == 0) {
850 agent_config.suspend = parse_flag ("suspend", arg + 8);
851 } else if (strncmp (arg, "server=", 7) == 0) {
852 agent_config.server = parse_flag ("server", arg + 7);
853 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
854 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
855 } else if (strncmp (arg, "onthrow=", 8) == 0) {
856 /* We support multiple onthrow= options */
857 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
858 } else if (strncmp (arg, "onthrow", 7) == 0) {
859 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
860 } else if (strncmp (arg, "help", 4) == 0) {
863 } else if (strncmp (arg, "timeout=", 8) == 0) {
864 agent_config.timeout = atoi (arg + 8);
865 } else if (strncmp (arg, "launch=", 7) == 0) {
866 agent_config.launch = g_strdup (arg + 7);
867 } else if (strncmp (arg, "embedding=", 10) == 0) {
868 agent_config.embedding = atoi (arg + 10) == 1;
869 } else if (strncmp (arg, "keepalive=", 10) == 0) {
870 agent_config.keepalive = atoi (arg + 10);
877 if (agent_config.server && !agent_config.suspend) {
878 /* Waiting for deferred attachment */
879 agent_config.defer = TRUE;
880 if (agent_config.address == NULL) {
881 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (GetCurrentProcessId () % 1000));
885 //agent_config.log_level = 0;
887 if (agent_config.transport == NULL) {
888 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
892 if (agent_config.address == NULL && !agent_config.server) {
893 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
898 if (!strcmp (agent_config.transport, "dt_socket")) {
899 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
900 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
907 mono_debugger_agent_init (void)
909 if (!agent_config.enabled)
914 /* Need to know whenever a thread has acquired the loader mutex */
915 mono_loader_lock_track_ownership (TRUE);
917 event_requests = g_ptr_array_new ();
919 mono_mutex_init (&debugger_thread_exited_mutex, NULL);
920 mono_cond_init (&debugger_thread_exited_cond, NULL);
922 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
923 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
924 mono_profiler_install_runtime_initialized (runtime_initialized);
925 mono_profiler_install_appdomain (NULL, appdomain_load, NULL, appdomain_unload);
926 mono_profiler_install_thread (thread_startup, thread_end);
927 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
928 mono_profiler_install_jit_end (jit_end);
929 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
931 mono_native_tls_alloc (&debugger_tls_id, NULL);
933 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
934 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls);
936 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
937 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread);
939 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
940 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj);
942 pending_assembly_loads = g_ptr_array_new ();
943 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
945 log_level = agent_config.log_level;
947 embedding = agent_config.embedding;
950 if (agent_config.log_file) {
951 log_file = fopen (agent_config.log_file, "w+");
953 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
965 mini_get_debug_options ()->gen_seq_points = TRUE;
967 * This is needed because currently we don't handle liveness info.
969 mini_get_debug_options ()->mdb_optimizations = TRUE;
971 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
972 /* This is needed because we can't set local variables in registers yet */
973 mono_disable_optimizations (MONO_OPT_LINEARS);
977 * The stack walk done from thread_interrupt () needs to be signal safe, but it
978 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
979 * safe (#3411). So load AOT info eagerly when the debugger is running as a
982 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
984 if (!agent_config.onuncaught && !agent_config.onthrow)
985 finish_agent_init (TRUE);
991 * Finish the initialization of the agent. This involves connecting the transport
992 * and starting the agent thread. This is either done at startup, or
993 * in response to some event like an unhandled exception.
996 finish_agent_init (gboolean on_startup)
1000 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
1003 if (agent_config.launch) {
1006 // FIXME: Generated address
1007 // FIXME: Races with transport_connect ()
1009 argv [0] = agent_config.launch;
1010 argv [1] = agent_config.transport;
1011 argv [2] = agent_config.address;
1014 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1016 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1021 transport_connect (agent_config.address);
1024 /* Do some which is usually done after sending the VMStart () event */
1025 vm_start_event_sent = TRUE;
1026 start_debugger_thread ();
1031 mono_debugger_agent_cleanup (void)
1036 stop_debugger_thread ();
1038 breakpoints_cleanup ();
1042 mono_mutex_destroy (&debugger_thread_exited_mutex);
1043 mono_cond_destroy (&debugger_thread_exited_cond);
1050 #ifndef DISABLE_SOCKET_TRANSPORT
1055 * recv() + handle incomplete reads and EINTR
1058 socket_transport_recv (void *buf, int len)
1064 static gint32 last_keepalive;
1069 res = recv (fd, (char *) buf + total, len - total, flags);
1072 if (agent_config.keepalive) {
1073 gboolean need_keepalive = FALSE;
1074 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1075 need_keepalive = TRUE;
1076 } else if (res == -1) {
1077 /* This could happen if recv () is interrupted repeatedly */
1078 msecs = mono_msec_ticks ();
1079 if (msecs - last_keepalive >= agent_config.keepalive) {
1080 need_keepalive = TRUE;
1081 last_keepalive = msecs;
1084 if (need_keepalive) {
1085 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1089 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1094 #define HAVE_GETADDRINFO 1
1098 set_keepalive (void)
1103 if (!agent_config.keepalive || !conn_fd)
1106 tv.tv_sec = agent_config.keepalive / 1000;
1107 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1109 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1110 g_assert (result >= 0);
1114 socket_transport_accept (int socket_fd)
1116 conn_fd = accept (socket_fd, NULL, NULL);
1117 if (conn_fd == -1) {
1118 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1120 DEBUG (1, fprintf (log_file, "Accepted connection from client, connection fd=%d.\n", conn_fd));
1127 socket_transport_send (void *data, int len)
1132 res = send (conn_fd, data, len, 0);
1133 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1141 * socket_transport_connect:
1143 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1146 socket_transport_connect (const char *address)
1148 #ifdef HAVE_GETADDRINFO
1149 struct addrinfo hints;
1150 struct addrinfo *result, *rp;
1152 struct hostent *result;
1154 int sfd = -1, s, res;
1155 char port_string [128];
1159 if (agent_config.address) {
1160 res = parse_address (agent_config.address, &host, &port);
1161 g_assert (res == 0);
1171 sprintf (port_string, "%d", port);
1173 mono_network_init ();
1175 /* Obtain address(es) matching host/port */
1176 #ifdef HAVE_GETADDRINFO
1177 memset (&hints, 0, sizeof (struct addrinfo));
1178 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
1179 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
1181 hints.ai_protocol = 0; /* Any protocol */
1183 s = getaddrinfo (host, port_string, &hints, &result);
1185 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %s\n", host, port, gai_strerror (s));
1189 /* The PS3 doesn't even have _r or hstrerror () */
1190 result = gethostbyname (host);
1192 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, h_errno);
1197 if (agent_config.server) {
1198 #ifdef HAVE_GETADDRINFO
1199 /* Wait for a connection */
1201 struct sockaddr_in addr;
1204 /* No address, generate one */
1205 sfd = socket (AF_INET, SOCK_STREAM, 0);
1208 /* This will bind the socket to a random port */
1209 res = listen (sfd, 16);
1211 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1216 addrlen = sizeof (addr);
1217 memset (&addr, 0, sizeof (addr));
1218 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1219 g_assert (res == 0);
1221 host = (char*)"127.0.0.1";
1222 port = ntohs (addr.sin_port);
1224 /* Emit the address to stdout */
1225 /* FIXME: Should print another interface, not localhost */
1226 printf ("%s:%d\n", host, port);
1228 /* Listen on the provided address */
1229 for (rp = result; rp != NULL; rp = rp->ai_next) {
1232 sfd = socket (rp->ai_family, rp->ai_socktype,
1237 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1240 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
1244 res = listen (sfd, 16);
1253 * this function is not present on win2000 which we still support, and the
1254 * workaround described here:
1255 * http://msdn.microsoft.com/en-us/library/ms737931(VS.85).aspx
1256 * only works with MSVC.
1258 #ifdef HAVE_GETADDRINFO
1259 freeaddrinfo (result);
1264 if (agent_config.defer)
1267 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
1269 if (agent_config.timeout) {
1274 tv.tv_usec = agent_config.timeout * 1000;
1276 FD_SET (sfd, &readfds);
1277 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1279 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1284 conn_fd = socket_transport_accept (sfd);
1288 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
1291 #endif /* HAVE_GETADDRINFO */
1293 /* Connect to the specified address */
1294 #ifdef HAVE_GETADDRINFO
1295 /* FIXME: Respect the timeout */
1296 for (rp = result; rp != NULL; rp = rp->ai_next) {
1297 sfd = socket (rp->ai_family, rp->ai_socktype,
1302 if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
1303 break; /* Success */
1309 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1313 sfd = socket (result->h_addrtype, SOCK_STREAM, 0);
1315 g_assert_not_reached ();
1316 res = connect (sfd, (void*)result->h_addr_list [0], result->h_length);
1318 g_assert_not_reached ();
1324 /* See the comment above */
1325 #ifdef HAVE_GETADDRINFO
1326 freeaddrinfo (result);
1331 if (!transport_handshake ())
1336 socket_transport_close1 (void)
1338 /* This will interrupt the agent thread */
1339 /* Close the read part only so it can still send back replies */
1340 /* Also shut down the connection listener so that we can exit normally */
1342 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1343 shutdown (conn_fd, SD_BOTH);
1344 shutdown (listen_fd, SD_BOTH);
1345 closesocket (listen_fd);
1347 shutdown (conn_fd, SHUT_RD);
1348 shutdown (listen_fd, SHUT_RDWR);
1354 socket_transport_close2 (void)
1357 shutdown (conn_fd, SD_BOTH);
1359 shutdown (conn_fd, SHUT_RDWR);
1364 register_socket_transport (void)
1366 DebuggerTransport trans;
1368 trans.name = "dt_socket";
1369 trans.connect = socket_transport_connect;
1370 trans.close1 = socket_transport_close1;
1371 trans.close2 = socket_transport_close2;
1372 trans.send = socket_transport_send;
1373 trans.recv = socket_transport_recv;
1375 register_transport (&trans);
1378 #endif /* DISABLE_SOCKET_TRANSPORT */
1384 #define MAX_TRANSPORTS 16
1386 static DebuggerTransport *transport;
1388 static DebuggerTransport transports [MAX_TRANSPORTS];
1389 static int ntransports;
1392 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1394 register_transport (trans);
1398 register_transport (DebuggerTransport *trans)
1400 g_assert (ntransports < MAX_TRANSPORTS);
1402 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1407 transport_init (void)
1411 #ifndef DISABLE_SOCKET_TRANSPORT
1412 register_socket_transport ();
1415 for (i = 0; i < ntransports; ++i) {
1416 if (!strcmp (agent_config.transport, transports [i].name))
1419 if (i == ntransports) {
1420 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1421 for (i = 0; i < ntransports; ++i)
1422 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1423 fprintf (stderr, "\n");
1426 transport = &transports [i];
1430 transport_connect (const char *address)
1432 transport->connect (address);
1436 transport_close1 (void)
1438 transport->close1 ();
1442 transport_close2 (void)
1444 transport->close2 ();
1448 transport_send (void *buf, int len)
1450 return transport->send (buf, len);
1454 transport_recv (void *buf, int len)
1456 return transport->recv (buf, len);
1460 mono_debugger_agent_transport_handshake (void)
1462 return transport_handshake ();
1466 transport_handshake (void)
1468 char handshake_msg [128];
1472 disconnected = TRUE;
1474 /* Write handshake message */
1475 sprintf (handshake_msg, "DWP-Handshake");
1477 res = transport_send (handshake_msg, strlen (handshake_msg));
1478 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1479 g_assert (res != -1);
1482 res = transport_recv (buf, strlen (handshake_msg));
1483 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg) != 0))) {
1484 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1489 * To support older clients, the client sends its protocol version after connecting
1490 * using a command. Until that is received, default to our protocol version.
1492 major_version = MAJOR_VERSION;
1493 minor_version = MINOR_VERSION;
1494 protocol_version_set = FALSE;
1496 #ifndef DISABLE_SOCKET_TRANSPORT
1497 // FIXME: Move this somewhere else
1499 * Set TCP_NODELAY on the socket so the client receives events/command
1500 * results immediately.
1504 int result = setsockopt (conn_fd,
1509 g_assert (result >= 0);
1515 disconnected = FALSE;
1520 stop_debugger_thread (void)
1525 transport_close1 ();
1528 * Wait for the thread to exit.
1530 * If we continue with the shutdown without waiting for it, then the client might
1531 * not receive an answer to its last command like a resume.
1532 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
1535 //WaitForSingleObject (debugger_thread_handle, INFINITE);
1536 if (GetCurrentThreadId () != debugger_thread_id) {
1538 mono_mutex_lock (&debugger_thread_exited_mutex);
1539 if (!debugger_thread_exited) {
1541 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
1542 mono_mutex_unlock (&debugger_thread_exited_mutex);
1544 mono_mutex_lock (&debugger_thread_exited_mutex);
1547 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1550 mono_mutex_unlock (&debugger_thread_exited_mutex);
1551 } while (!debugger_thread_exited);
1554 transport_close2 ();
1558 start_debugger_thread (void)
1562 debugger_thread_handle = mono_create_thread (NULL, 0, debugger_thread, NULL, 0, &tid);
1563 g_assert (debugger_thread_handle);
1567 * Functions to decode protocol data
1571 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1574 g_assert (*endbuf <= limit);
1579 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1582 g_assert (*endbuf <= limit);
1584 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1587 static inline gint64
1588 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1590 guint32 high = decode_int (buf, &buf, limit);
1591 guint32 low = decode_int (buf, &buf, limit);
1595 return ((((guint64)high) << 32) | ((guint64)low));
1599 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1601 return decode_int (buf, endbuf, limit);
1605 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1607 int len = decode_int (buf, &buf, limit);
1615 s = g_malloc (len + 1);
1618 memcpy (s, buf, len);
1627 * Functions to encode protocol data
1631 guint8 *buf, *p, *end;
1635 buffer_init (Buffer *buf, int size)
1637 buf->buf = g_malloc (size);
1639 buf->end = buf->buf + size;
1643 buffer_make_room (Buffer *buf, int size)
1645 if (buf->end - buf->p < size) {
1646 int new_size = buf->end - buf->buf + size + 32;
1647 guint8 *p = g_realloc (buf->buf, new_size);
1648 size = buf->p - buf->buf;
1651 buf->end = buf->buf + new_size;
1656 buffer_add_byte (Buffer *buf, guint8 val)
1658 buffer_make_room (buf, 1);
1664 buffer_add_short (Buffer *buf, guint32 val)
1666 buffer_make_room (buf, 2);
1667 buf->p [0] = (val >> 8) & 0xff;
1668 buf->p [1] = (val >> 0) & 0xff;
1673 buffer_add_int (Buffer *buf, guint32 val)
1675 buffer_make_room (buf, 4);
1676 buf->p [0] = (val >> 24) & 0xff;
1677 buf->p [1] = (val >> 16) & 0xff;
1678 buf->p [2] = (val >> 8) & 0xff;
1679 buf->p [3] = (val >> 0) & 0xff;
1684 buffer_add_long (Buffer *buf, guint64 l)
1686 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1687 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1691 buffer_add_id (Buffer *buf, int id)
1693 buffer_add_int (buf, (guint64)id);
1697 buffer_add_data (Buffer *buf, guint8 *data, int len)
1699 buffer_make_room (buf, len);
1700 memcpy (buf->p, data, len);
1705 buffer_add_string (Buffer *buf, const char *str)
1710 buffer_add_int (buf, 0);
1713 buffer_add_int (buf, len);
1714 buffer_add_data (buf, (guint8*)str, len);
1719 buffer_free (Buffer *buf)
1725 send_packet (int command_set, int command, Buffer *data)
1731 id = InterlockedIncrement (&packet_id);
1733 len = data->p - data->buf + 11;
1734 buffer_init (&buf, len);
1735 buffer_add_int (&buf, len);
1736 buffer_add_int (&buf, id);
1737 buffer_add_byte (&buf, 0); /* flags */
1738 buffer_add_byte (&buf, command_set);
1739 buffer_add_byte (&buf, command);
1740 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1742 res = transport_send (buf.buf, len);
1750 send_reply_packet (int id, int error, Buffer *data)
1756 len = data->p - data->buf + 11;
1757 buffer_init (&buf, len);
1758 buffer_add_int (&buf, len);
1759 buffer_add_int (&buf, id);
1760 buffer_add_byte (&buf, 0x80); /* flags */
1761 buffer_add_byte (&buf, (error >> 8) & 0xff);
1762 buffer_add_byte (&buf, error);
1763 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1765 res = transport_send (buf.buf, len);
1777 * Represents an object accessible by the debugger client.
1780 /* Unique id used in the wire protocol to refer to objects */
1783 * A weakref gc handle pointing to the object. The gc handle is used to
1784 * detect if the object was garbage collected.
1789 /* Maps objid -> ObjRef */
1790 static GHashTable *objrefs;
1793 free_objref (gpointer value)
1797 mono_gchandle_free (o->handle);
1805 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1809 objrefs_cleanup (void)
1811 g_hash_table_destroy (objrefs);
1815 static GHashTable *obj_to_objref;
1818 * Return an ObjRef for OBJ.
1821 get_objref (MonoObject *obj)
1824 GSList *reflist = NULL, *l;
1830 mono_loader_lock ();
1833 obj_to_objref = g_hash_table_new (NULL, NULL);
1835 /* FIXME: The tables can grow indefinitely */
1837 if (mono_gc_is_moving ()) {
1839 * Objects can move, so use a hash table mapping hash codes to lists of
1840 * ObjRef structures.
1842 hash = mono_object_hash (obj);
1844 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1845 for (l = reflist; l; l = l->next) {
1847 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1848 mono_loader_unlock ();
1853 /* Use a hash table with masked pointers to internalize object references */
1854 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1855 /* ref might refer to a different object with the same addr which was GCd */
1856 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1857 mono_loader_unlock ();
1862 ref = g_new0 (ObjRef, 1);
1863 ref->id = InterlockedIncrement (&objref_id);
1864 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1866 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
1868 if (mono_gc_is_moving ()) {
1869 reflist = g_slist_append (reflist, ref);
1870 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
1872 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
1875 mono_loader_unlock ();
1881 get_objid (MonoObject *obj)
1883 return get_objref (obj)->id;
1887 * Set OBJ to the object identified by OBJID.
1888 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
1892 get_object_allow_null (int objid, MonoObject **obj)
1902 return ERR_INVALID_OBJECT;
1904 mono_loader_lock ();
1906 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
1909 *obj = mono_gchandle_get_target (ref->handle);
1910 mono_loader_unlock ();
1912 return ERR_INVALID_OBJECT;
1915 mono_loader_unlock ();
1916 return ERR_INVALID_OBJECT;
1921 get_object (int objid, MonoObject **obj)
1923 int err = get_object_allow_null (objid, obj);
1928 return ERR_INVALID_OBJECT;
1933 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
1935 return decode_id (buf, endbuf, limit);
1939 buffer_add_objid (Buffer *buf, MonoObject *o)
1941 buffer_add_id (buf, get_objid (o));
1960 * Represents a runtime structure accessible to the debugger client
1963 /* Unique id used in the wire protocol */
1965 /* Domain of the runtime structure, NULL if the domain was unloaded */
1972 MonoAssembly *assembly;
1973 MonoClassField *field;
1975 MonoProperty *property;
1980 /* Maps runtime structure -> Id */
1981 GHashTable *val_to_id [ID_NUM];
1982 /* Classes whose class load event has been sent */
1983 GHashTable *loaded_classes;
1984 /* Maps MonoClass->GPtrArray of file names */
1985 GHashTable *source_files;
1986 /* Maps source file basename -> GSList of classes */
1987 GHashTable *source_file_to_class;
1988 /* Same with ignore-case */
1989 GHashTable *source_file_to_class_ignorecase;
1993 static GPtrArray *ids [ID_NUM];
2000 for (i = 0; i < ID_NUM; ++i)
2001 ids [i] = g_ptr_array_new ();
2009 for (i = 0; i < ID_NUM; ++i) {
2011 for (j = 0; j < ids [i]->len; ++j)
2012 g_free (g_ptr_array_index (ids [i], j));
2013 g_ptr_array_free (ids [i], TRUE);
2020 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2022 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
2024 GHashTableIter iter;
2025 GPtrArray *file_names;
2030 for (i = 0; i < ID_NUM; ++i)
2031 if (info->val_to_id [i])
2032 g_hash_table_destroy (info->val_to_id [i]);
2033 g_hash_table_destroy (info->loaded_classes);
2035 g_hash_table_iter_init (&iter, info->source_files);
2036 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2037 for (i = 0; i < file_names->len; ++i)
2038 g_free (g_ptr_array_index (file_names, i));
2039 g_ptr_array_free (file_names, TRUE);
2042 g_hash_table_iter_init (&iter, info->source_file_to_class);
2043 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2048 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2049 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2057 domain_jit_info (domain)->agent_info = NULL;
2059 /* Clear ids referencing structures in the domain */
2060 for (i = 0; i < ID_NUM; ++i) {
2062 for (j = 0; j < ids [i]->len; ++j) {
2063 Id *id = g_ptr_array_index (ids [i], j);
2064 if (id->domain == domain)
2070 mono_loader_lock ();
2071 g_hash_table_remove (domains, domain);
2072 mono_loader_unlock ();
2075 static AgentDomainInfo*
2076 get_agent_domain_info (MonoDomain *domain)
2078 AgentDomainInfo *info = NULL;
2080 mono_domain_lock (domain);
2082 info = domain_jit_info (domain)->agent_info;
2084 info = domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
2085 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2086 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2087 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2088 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2091 mono_domain_unlock (domain);
2097 get_id (MonoDomain *domain, IdType type, gpointer val)
2100 AgentDomainInfo *info;
2105 mono_loader_lock ();
2107 mono_domain_lock (domain);
2109 info = get_agent_domain_info (domain);
2111 if (info->val_to_id [type] == NULL)
2112 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2114 id = g_hash_table_lookup (info->val_to_id [type], val);
2116 mono_domain_unlock (domain);
2117 mono_loader_unlock ();
2121 id = g_new0 (Id, 1);
2123 id->id = ids [type]->len + 1;
2124 id->domain = domain;
2127 g_hash_table_insert (info->val_to_id [type], val, id);
2129 mono_domain_unlock (domain);
2131 g_ptr_array_add (ids [type], id);
2133 mono_loader_unlock ();
2138 static inline gpointer
2139 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
2143 int id = decode_id (buf, endbuf, limit);
2152 // FIXME: error handling
2153 mono_loader_lock ();
2154 g_assert (id > 0 && id <= ids [type]->len);
2156 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2157 mono_loader_unlock ();
2159 if (res->domain == NULL) {
2160 *err = ERR_UNLOADED;
2165 *domain = res->domain;
2167 return res->data.val;
2171 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2173 buffer_add_id (buf, get_id (domain, type, val));
2176 static inline MonoClass*
2177 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2179 return decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2182 static inline MonoAssembly*
2183 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2185 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2188 static inline MonoImage*
2189 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2191 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2194 static inline MonoMethod*
2195 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2197 return decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2200 static inline MonoClassField*
2201 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2203 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2206 static inline MonoDomain*
2207 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2209 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2212 static inline MonoProperty*
2213 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2215 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2219 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2221 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2225 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2227 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2231 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2233 buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2237 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2239 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2243 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2245 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2249 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2251 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2255 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2257 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2260 static void invoke_method (void);
2267 * save_thread_context:
2269 * Set CTX as the current threads context which is used for computing stack traces.
2270 * This function is signal-safe.
2273 save_thread_context (MonoContext *ctx)
2275 DebuggerTlsData *tls;
2277 tls = mono_native_tls_get_value (debugger_tls_id);
2281 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2283 mono_thread_state_init_from_current (&tls->context);
2286 /* The number of times the runtime is suspended */
2287 static gint32 suspend_count;
2289 /* Number of threads suspended */
2291 * If this is equal to the size of thread_to_tls, the runtime is considered
2294 static gint32 threads_suspend_count;
2296 static mono_mutex_t suspend_mutex;
2298 /* Cond variable used to wait for suspend_count becoming 0 */
2299 static mono_cond_t suspend_cond;
2301 /* Semaphore used to wait for a thread becoming suspended */
2302 static MonoSemType suspend_sem;
2307 mono_mutex_init (&suspend_mutex, NULL);
2308 mono_cond_init (&suspend_cond, NULL);
2309 MONO_SEM_INIT (&suspend_sem, 0);
2314 StackFrameInfo last_frame;
2315 gboolean last_frame_set;
2318 } GetLastFrameUserData;
2321 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2323 GetLastFrameUserData *data = user_data;
2325 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
2328 if (!data->last_frame_set) {
2329 /* Store the last frame */
2330 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2331 data->last_frame_set = TRUE;
2334 /* Store the context/lmf for the frame above the last frame */
2335 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2336 data->lmf = info->lmf;
2344 * Process interruption of a thread. If SIGCTX is set, process the current thread. If
2345 * INFO is set, process the thread described by INFO.
2346 * This should be signal safe.
2349 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, void *sigctx, MonoJitInfo *ji)
2353 MonoNativeThreadId tid;
2356 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2357 * guarantee the signal handler will be called that many times. Instead of tracking
2358 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2359 * has been requested that hasn't been handled yet, otherwise we can have threads
2360 * refuse to die when VM_EXIT is called
2362 #if defined(__APPLE__)
2363 if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
2367 * We use interrupt_count to determine whenever this interrupt should be processed
2368 * by us or the normal interrupt processing code in the signal handler.
2369 * There is no race here with notify_thread (), since the signal is sent after
2370 * incrementing interrupt_count.
2372 if (tls->interrupt_count == 0)
2375 InterlockedDecrement (&tls->interrupt_count);
2379 ip = mono_arch_ip_from_context (sigctx);
2381 ip = MONO_CONTEXT_GET_IP (&info->suspend_state.ctx);
2386 tid = mono_thread_info_get_tid (info);
2388 tid = (MonoNativeThreadId)GetCurrentThreadId ();
2390 // FIXME: Races when the thread leaves managed code before hitting a single step
2394 /* Running managed code, will be suspended by the single step code */
2395 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, ji->method->name, ip));
2399 * Running native code, will be suspended when it returns to/enters
2400 * managed code. Treat it as already suspended.
2401 * This might interrupt the code in process_single_step_inner (), we use the
2402 * tls->suspending flag to avoid races when that happens.
2404 if (!tls->suspended && !tls->suspending) {
2406 GetLastFrameUserData data;
2408 // FIXME: printf is not signal safe, but this is only used during
2409 // debugger debugging
2411 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip));
2412 //save_thread_context (&ctx);
2415 /* Already terminated */
2418 tls->context.valid = FALSE;
2421 * We are in a difficult position: we want to be able to provide stack
2422 * traces for this thread, but we can't use the current ctx+lmf, since
2423 * the thread is still running, so it might return to managed code,
2424 * making these invalid.
2425 * So we start a stack walk and save the first frame, along with the
2426 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2427 * suspended when it returns to managed code, so the parent's ctx should
2430 data.last_frame_set = FALSE;
2432 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
2434 * Don't pass MONO_UNWIND_ACTUAL_METHOD, its not signal safe, and
2435 * get_last_frame () doesn't need it, the last frame cannot be a ginst
2436 * since we are not in a JITted method.
2438 mono_walk_stack_with_ctx (get_last_frame, &ctx, MONO_UNWIND_NONE, &data);
2440 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, &info->suspend_state, MONO_UNWIND_SIGNAL_SAFE, &data);
2442 if (data.last_frame_set) {
2443 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2444 res = mono_thread_state_init_from_monoctx (&tls->async_state, &ctx);
2446 mono_thread_state_init_from_monoctx (&tls->context, &ctx);
2449 memcpy (&tls->async_state.ctx, &data.ctx, sizeof (MonoContext));
2450 tls->async_state.unwind_data [MONO_UNWIND_DATA_LMF] = data.lmf;
2451 tls->async_state.unwind_data [MONO_UNWIND_DATA_JIT_TLS] = tls->thread->jit_data;
2453 /* No managed frames */
2454 tls->async_state.valid = FALSE;
2456 mono_memory_barrier ();
2458 tls->suspended = TRUE;
2459 MONO_SEM_POST (&suspend_sem);
2466 * mono_debugger_agent_thread_interrupt:
2468 * Called by the abort signal handler.
2469 * Should be signal safe.
2472 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
2474 DebuggerTlsData *tls;
2479 tls = mono_native_tls_get_value (debugger_tls_id);
2481 DEBUG (1, fprintf (log_file, "[%p] Received interrupt with no TLS, continuing.\n", (gpointer)GetCurrentThreadId ()));
2485 return thread_interrupt (tls, NULL, sigctx, ji);
2489 static void CALLBACK notify_thread_apc (ULONG_PTR param)
2492 mono_debugger_agent_thread_interrupt (NULL, NULL);
2494 #endif /* HOST_WIN32 */
2497 * reset_native_thread_suspend_state:
2499 * Reset the suspended flag and state on native threads
2502 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2504 DebuggerTlsData *tls = value;
2506 if (!tls->really_suspended && tls->suspended) {
2507 tls->suspended = FALSE;
2509 * The thread might still be running if it was executing native code, so the state won't be invalided by
2510 * suspend_current ().
2512 tls->context.valid = FALSE;
2513 tls->async_state.valid = FALSE;
2514 invalidate_frames (tls);
2521 * Notify a thread that it needs to suspend.
2524 notify_thread (gpointer key, gpointer value, gpointer user_data)
2526 MonoInternalThread *thread = key;
2527 DebuggerTlsData *tls = value;
2528 gsize tid = thread->tid;
2531 if (GetCurrentThreadId () == tid || tls->terminated)
2534 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2537 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2538 * guarantee the signal handler will be called that many times. Instead of tracking
2539 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2540 * has been requested that hasn't been handled yet, otherwise we can have threads
2541 * refuse to die when VM_EXIT is called
2543 #if defined(__APPLE__)
2544 if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
2548 * Maybe we could use the normal interrupt infrastructure, but that does a lot
2549 * of things like breaking waits etc. which we don't want.
2551 InterlockedIncrement (&tls->interrupt_count);
2554 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2556 QueueUserAPC (notify_thread_apc, thread->handle, NULL);
2558 if (mono_thread_info_new_interrupt_enabled ()) {
2559 MonoThreadInfo *info;
2562 info = mono_thread_info_safe_suspend_sync ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE);
2565 ji = mono_jit_info_table_find (info->suspend_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], MONO_CONTEXT_GET_IP (&info->suspend_state.ctx));
2567 thread_interrupt (tls, info, NULL, ji);
2569 mono_thread_info_resume (mono_thread_info_get_tid (info));
2571 res = mono_thread_kill (thread, mono_thread_get_abort_signal ());
2573 DEBUG(1, fprintf (log_file, "[%p] mono_thread_kill () failed for %p: %d...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid, res));
2575 * Attached thread which died without detaching.
2577 tls->terminated = TRUE;
2584 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2586 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2589 if (mono_loader_lock_is_owned_by_self ()) {
2591 * Shortcut for the check in suspend_current (). This speeds up processing
2592 * when executing long running code inside the loader lock, i.e. assembly load
2598 if (debugger_thread_id == GetCurrentThreadId ())
2601 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2602 if (suspend_count - tls->resume_count > 0)
2603 tls->suspending = TRUE;
2605 DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2607 if (suspend_count - tls->resume_count == 0) {
2609 * We are executing a single threaded invoke but the single step for
2610 * suspending is still active.
2611 * FIXME: This slows down single threaded invokes.
2613 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
2617 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2619 /* Can't suspend in these methods */
2620 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
2623 save_thread_context (ctx);
2631 * Increase the suspend count of the VM. While the suspend count is greater
2632 * than 0, runtime threads are suspended at certain points during execution.
2637 mono_loader_lock ();
2639 mono_mutex_lock (&suspend_mutex);
2643 DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
2645 if (suspend_count == 1) {
2646 // FIXME: Is it safe to call this inside the lock ?
2647 start_single_stepping ();
2648 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2651 mono_mutex_unlock (&suspend_mutex);
2653 mono_loader_unlock ();
2659 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2667 g_assert (debugger_thread_id == GetCurrentThreadId ());
2669 mono_loader_lock ();
2671 mono_mutex_lock (&suspend_mutex);
2673 g_assert (suspend_count > 0);
2676 DEBUG(1, fprintf (log_file, "[%p] Resuming vm, suspend count=%d...\n", (gpointer)GetCurrentThreadId (), suspend_count));
2678 if (suspend_count == 0) {
2679 // FIXME: Is it safe to call this inside the lock ?
2680 stop_single_stepping ();
2681 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2684 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2685 err = mono_cond_broadcast (&suspend_cond);
2686 g_assert (err == 0);
2688 mono_mutex_unlock (&suspend_mutex);
2689 //g_assert (err == 0);
2691 mono_loader_unlock ();
2697 * Resume just one thread.
2700 resume_thread (MonoInternalThread *thread)
2703 DebuggerTlsData *tls;
2705 g_assert (debugger_thread_id == GetCurrentThreadId ());
2707 mono_loader_lock ();
2709 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2712 mono_mutex_lock (&suspend_mutex);
2714 g_assert (suspend_count > 0);
2716 DEBUG(1, fprintf (log_file, "[%p] Resuming thread...\n", (gpointer)(gssize)thread->tid));
2718 tls->resume_count += suspend_count;
2721 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2722 * but only the one whose resume_count field is > 0 will be resumed.
2724 err = mono_cond_broadcast (&suspend_cond);
2725 g_assert (err == 0);
2727 mono_mutex_unlock (&suspend_mutex);
2728 //g_assert (err == 0);
2730 mono_loader_unlock ();
2734 invalidate_frames (DebuggerTlsData *tls)
2739 tls = mono_native_tls_get_value (debugger_tls_id);
2742 for (i = 0; i < tls->frame_count; ++i) {
2743 if (tls->frames [i]->jit)
2744 mono_debug_free_method_jit_info (tls->frames [i]->jit);
2745 g_free (tls->frames [i]);
2747 g_free (tls->frames);
2748 tls->frame_count = 0;
2755 * Suspend the current thread until the runtime is resumed. If the thread has a
2756 * pending invoke, then the invoke is executed before this function returns.
2759 suspend_current (void)
2762 DebuggerTlsData *tls;
2764 g_assert (debugger_thread_id != GetCurrentThreadId ());
2766 if (mono_loader_lock_is_owned_by_self ()) {
2768 * If we own the loader mutex, can't suspend until we release it, since the
2769 * whole runtime can deadlock otherwise.
2774 tls = mono_native_tls_get_value (debugger_tls_id);
2777 mono_mutex_lock (&suspend_mutex);
2779 tls->suspending = FALSE;
2780 tls->really_suspended = TRUE;
2782 if (!tls->suspended) {
2783 tls->suspended = TRUE;
2784 MONO_SEM_POST (&suspend_sem);
2787 DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
2789 while (suspend_count - tls->resume_count > 0) {
2791 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
2793 mono_mutex_unlock (&suspend_mutex);
2795 mono_mutex_lock (&suspend_mutex);
2801 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
2802 g_assert (err == 0);
2806 tls->suspended = FALSE;
2807 tls->really_suspended = FALSE;
2809 threads_suspend_count --;
2811 mono_mutex_unlock (&suspend_mutex);
2813 DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
2815 if (tls->pending_invoke) {
2816 /* Save the original context */
2817 tls->pending_invoke->has_ctx = TRUE;
2818 tls->pending_invoke->ctx = tls->context.ctx;
2823 /* The frame info becomes invalid after a resume */
2824 tls->context.valid = FALSE;
2825 tls->async_state.valid = FALSE;
2826 invalidate_frames (tls);
2830 count_thread (gpointer key, gpointer value, gpointer user_data)
2832 DebuggerTlsData *tls = value;
2834 if (!tls->suspended && !tls->terminated)
2835 *(int*)user_data = *(int*)user_data + 1;
2839 count_threads_to_wait_for (void)
2843 mono_loader_lock ();
2844 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2845 mono_loader_unlock ();
2853 * Wait until the runtime is completely suspended.
2856 wait_for_suspend (void)
2858 int nthreads, nwait, err;
2859 gboolean waited = FALSE;
2861 // FIXME: Threads starting/stopping ?
2862 mono_loader_lock ();
2863 nthreads = mono_g_hash_table_size (thread_to_tls);
2864 mono_loader_unlock ();
2867 nwait = count_threads_to_wait_for ();
2869 DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
2870 err = MONO_SEM_WAIT (&suspend_sem);
2871 g_assert (err == 0);
2879 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
2885 * Return whenever the runtime is suspended.
2890 return count_threads_to_wait_for () == 0;
2893 static MonoSeqPointInfo*
2894 get_seq_points (MonoDomain *domain, MonoMethod *method)
2896 MonoSeqPointInfo *seq_points;
2898 mono_domain_lock (domain);
2899 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2900 if (!seq_points && method->is_inflated) {
2901 /* generic sharing + aot */
2902 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (method));
2904 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mini_get_shared_method (method));
2906 mono_domain_unlock (domain);
2911 static MonoSeqPointInfo*
2912 find_seq_points (MonoDomain *domain, MonoMethod *method)
2914 MonoSeqPointInfo *seq_points = get_seq_points (domain, method);
2917 printf ("Unable to find seq points for method '%s'.\n", mono_method_full_name (method, TRUE));
2918 g_assert (seq_points);
2924 * find_next_seq_point_for_native_offset:
2926 * Find the first sequence point after NATIVE_OFFSET.
2929 find_next_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2931 MonoSeqPointInfo *seq_points;
2934 seq_points = find_seq_points (domain, method);
2938 for (i = 0; i < seq_points->len; ++i) {
2939 if (seq_points->seq_points [i].native_offset >= native_offset)
2940 return &seq_points->seq_points [i];
2947 * find_prev_seq_point_for_native_offset:
2949 * Find the first sequence point before NATIVE_OFFSET.
2952 find_prev_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2954 MonoSeqPointInfo *seq_points;
2957 seq_points = find_seq_points (domain, method);
2961 for (i = seq_points->len - 1; i >= 0; --i) {
2962 if (seq_points->seq_points [i].native_offset <= native_offset)
2963 return &seq_points->seq_points [i];
2972 * Find the sequence point corresponding to the IL offset IL_OFFSET, which
2973 * should be the location of a sequence point.
2975 static G_GNUC_UNUSED SeqPoint*
2976 find_seq_point (MonoDomain *domain, MonoMethod *method, gint32 il_offset, MonoSeqPointInfo **info)
2978 MonoSeqPointInfo *seq_points;
2983 seq_points = get_seq_points (domain, method);
2988 for (i = 0; i < seq_points->len; ++i) {
2989 if (seq_points->seq_points [i].il_offset == il_offset)
2990 return &seq_points->seq_points [i];
2997 DebuggerTlsData *tls;
2999 } ComputeFramesUserData;
3002 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3004 ComputeFramesUserData *ud = user_data;
3006 MonoMethod *method, *actual_method, *api_method;
3010 if (info->type != FRAME_TYPE_MANAGED) {
3011 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3012 /* Mark the last frame as an invoke frame */
3014 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3020 method = info->ji->method;
3022 method = info->method;
3023 actual_method = info->actual_method;
3024 api_method = method;
3029 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3032 if (info->il_offset == -1) {
3033 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3034 if (ud->frames == NULL) {
3035 sp = find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL);
3037 info->il_offset = sp->il_offset;
3039 if (info->il_offset == -1)
3040 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3043 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));
3045 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3046 if (!CHECK_PROTOCOL_VERSION (2, 17))
3047 /* Older clients can't handle this flag */
3049 api_method = mono_marshal_method_from_wrapper (method);
3052 actual_method = api_method;
3053 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3056 frame = g_new0 (StackFrame, 1);
3057 frame->method = method;
3058 frame->actual_method = actual_method;
3059 frame->api_method = api_method;
3060 frame->il_offset = info->il_offset;
3061 frame->native_offset = info->native_offset;
3062 frame->flags = flags;
3063 frame->ji = info->ji;
3064 if (info->reg_locations)
3065 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3068 frame->has_ctx = TRUE;
3070 frame->domain = info->domain;
3072 ud->frames = g_slist_append (ud->frames, frame);
3078 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3080 ComputeFramesUserData *ud = user_data;
3083 * 'tls->filter_ctx' is the location of the throw site.
3085 * mono_walk_stack() will never actually hit the throw site, but unwind
3086 * directly from the filter to the call site; we abort stack unwinding here
3087 * once this happens and resume from the throw site.
3090 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3093 return process_frame (info, ctx, user_data);
3097 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3099 ComputeFramesUserData user_data;
3101 int i, findex, new_frame_count;
3102 StackFrame **new_frames, *f;
3103 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3105 // FIXME: Locking on tls
3106 if (tls->frames && tls->frames_up_to_date)
3109 DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
3111 user_data.tls = tls;
3112 user_data.frames = NULL;
3113 if (tls->terminated) {
3114 tls->frame_count = 0;
3116 } if (!tls->really_suspended && tls->async_state.valid) {
3117 /* Have to use the state saved by the signal handler */
3118 process_frame (&tls->async_last_frame, NULL, &user_data);
3119 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3120 } else if (tls->filter_state.valid) {
3122 * We are inside an exception filter.
3124 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3126 if (tls->context.valid)
3127 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3129 * After that, we resume unwinding from the location where the exception has been thrown.
3131 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3132 } else if (tls->context.valid) {
3133 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3136 tls->frame_count = 0;
3140 new_frame_count = g_slist_length (user_data.frames);
3141 new_frames = g_new0 (StackFrame*, new_frame_count);
3143 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3147 * Reuse the id for already existing stack frames, so invokes don't invalidate
3148 * the still valid stack frames.
3150 for (i = 0; i < tls->frame_count; ++i) {
3151 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3152 f->id = tls->frames [i]->id;
3157 if (i >= tls->frame_count)
3158 f->id = InterlockedIncrement (&frame_id);
3160 new_frames [findex ++] = f;
3163 g_slist_free (user_data.frames);
3165 invalidate_frames (tls);
3167 tls->frames = new_frames;
3168 tls->frame_count = new_frame_count;
3169 tls->frames_up_to_date = TRUE;
3173 * GHFunc to emit an appdomain creation event
3174 * @param key Don't care
3175 * @param value A loaded appdomain
3176 * @param user_data Don't care
3179 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3181 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3182 g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
3186 * GHFunc to emit a thread start event
3187 * @param key A thread id
3188 * @param value A thread object
3189 * @param user_data Don't care
3192 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3194 if (GPOINTER_TO_INT (key) != debugger_thread_id)
3195 process_profiler_event (EVENT_KIND_THREAD_START, value);
3199 * GFunc to emit an assembly load event
3200 * @param value A loaded assembly
3201 * @param user_data Don't care
3204 emit_assembly_load (gpointer value, gpointer user_data)
3206 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3210 * GFunc to emit a type load event
3211 * @param value A loaded type
3212 * @param user_data Don't care
3215 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3217 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3221 strdup_tolower (char *s)
3226 for (p = s2; *p; ++p)
3236 * create_event_list:
3238 * Return a list of event request ids matching EVENT, starting from REQS, which
3239 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3241 * We return request ids, instead of requests, to simplify threading, since
3242 * requests could be deleted anytime when the loader lock is not held.
3243 * LOCKING: Assumes the loader lock is held.
3246 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3249 GSList *events = NULL;
3251 *suspend_policy = SUSPEND_POLICY_NONE;
3254 reqs = event_requests;
3259 for (i = 0; i < reqs->len; ++i) {
3260 EventRequest *req = g_ptr_array_index (reqs, i);
3261 if (req->event_kind == event) {
3262 gboolean filtered = FALSE;
3265 for (j = 0; j < req->nmodifiers; ++j) {
3266 Modifier *mod = &req->modifiers [j];
3268 if (mod->kind == MOD_KIND_COUNT) {
3270 if (mod->data.count > 0) {
3271 if (mod->data.count > 0) {
3273 if (mod->data.count == 0)
3277 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3278 if (mod->data.thread != mono_thread_internal_current ())
3280 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3281 if (mod->data.exc_class && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3283 if (ei->caught && !mod->caught)
3285 if (!ei->caught && !mod->uncaught)
3287 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3289 gboolean found = FALSE;
3290 MonoAssembly **assemblies = mod->data.assemblies;
3293 for (k = 0; assemblies [k]; ++k)
3294 if (assemblies [k] == ji->method->klass->image->assembly)
3299 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3300 gpointer iter = NULL;
3302 MonoDebugSourceInfo *sinfo;
3303 char *source_file, *s;
3304 gboolean found = FALSE;
3306 GPtrArray *source_file_list;
3308 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3309 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3312 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, NULL, NULL, NULL, NULL, NULL);
3313 for (i = 0; i < source_file_list->len; ++i) {
3314 sinfo = g_ptr_array_index (source_file_list, i);
3316 * Do a case-insesitive match by converting the file name to
3319 s = strdup_tolower (sinfo->source_file);
3320 if (g_hash_table_lookup (mod->data.source_files, s))
3324 g_ptr_array_free (source_file_list, TRUE);
3329 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3332 s = mono_type_full_name (&ei->klass->byval_arg);
3333 if (!g_hash_table_lookup (mod->data.type_names, s))
3336 } else if (mod->kind == MOD_KIND_STEP) {
3337 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3338 (ji->method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3339 !strcmp (ji->method->name, ".cctor"))
3341 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3342 MonoCustomAttrInfo *ainfo;
3343 static MonoClass *klass;
3346 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3349 if (!ji->dbg_hidden_inited) {
3350 ainfo = mono_custom_attrs_from_method (ji->method);
3352 if (mono_custom_attrs_has_attr (ainfo, klass))
3353 ji->dbg_hidden = TRUE;
3354 mono_custom_attrs_free (ainfo);
3356 ji->dbg_hidden_inited = TRUE;
3365 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3366 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3371 /* Send a VM START/DEATH event by default */
3372 if (event == EVENT_KIND_VM_START)
3373 events = g_slist_append (events, GINT_TO_POINTER (0));
3374 if (event == EVENT_KIND_VM_DEATH)
3375 events = g_slist_append (events, GINT_TO_POINTER (0));
3380 static G_GNUC_UNUSED const char*
3381 event_to_string (EventKind event)
3384 case EVENT_KIND_VM_START: return "VM_START";
3385 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3386 case EVENT_KIND_THREAD_START: return "THREAD_START";
3387 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3388 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3389 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3390 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3391 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3392 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3393 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3394 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3395 case EVENT_KIND_STEP: return "STEP";
3396 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3397 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3398 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3399 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3400 case EVENT_KIND_USER_LOG: return "USER_LOG";
3402 g_assert_not_reached ();
3409 * Send an event to the client, suspending the vm if needed.
3410 * LOCKING: Since this can suspend the calling thread, no locks should be held
3412 * The EVENTS list is freed by this function.
3415 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3419 MonoDomain *domain = mono_domain_get ();
3420 MonoThread *thread = NULL;
3421 gboolean send_success = FALSE;
3426 DEBUG (2, fprintf (log_file, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event)));
3430 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3431 // FIXME: We miss those events
3432 DEBUG (2, fprintf (log_file, "VM start event not sent yet: dropping %s\n", event_to_string (event)));
3436 if (vm_death_event_sent) {
3437 DEBUG (2, fprintf (log_file, "VM death event has been sent: dropping %s\n", event_to_string (event)));
3441 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3442 DEBUG (2, fprintf (log_file, "Mono runtime is shutting down: dropping %s\n", event_to_string (event)));
3447 DEBUG (2, fprintf (log_file, "Debugger client is not connected: dropping %s\n", event_to_string (event)));
3451 if (event == EVENT_KIND_KEEPALIVE)
3452 suspend_policy = SUSPEND_POLICY_NONE;
3457 if (agent_config.defer) {
3458 /* Make sure the thread id is always set when doing deferred debugging */
3459 if (debugger_thread_id == GetCurrentThreadId ()) {
3460 /* Don't suspend on events from the debugger thread */
3461 suspend_policy = SUSPEND_POLICY_NONE;
3462 thread = mono_thread_get_main ();
3464 else thread = mono_thread_current ();
3466 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3467 // FIXME: Send these with a NULL thread, don't suspend the current thread
3472 nevents = g_slist_length (events);
3473 buffer_init (&buf, 128);
3474 buffer_add_byte (&buf, suspend_policy);
3475 buffer_add_int (&buf, nevents);
3477 for (l = events; l; l = l->next) {
3478 buffer_add_byte (&buf, event); // event kind
3479 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3484 thread = mono_thread_current ();
3486 if (event == EVENT_KIND_VM_START && arg != NULL)
3489 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3492 case EVENT_KIND_THREAD_START:
3493 case EVENT_KIND_THREAD_DEATH:
3495 case EVENT_KIND_APPDOMAIN_CREATE:
3496 case EVENT_KIND_APPDOMAIN_UNLOAD:
3497 buffer_add_domainid (&buf, arg);
3499 case EVENT_KIND_METHOD_ENTRY:
3500 case EVENT_KIND_METHOD_EXIT:
3501 buffer_add_methodid (&buf, domain, arg);
3503 case EVENT_KIND_ASSEMBLY_LOAD:
3504 case EVENT_KIND_ASSEMBLY_UNLOAD:
3505 buffer_add_assemblyid (&buf, domain, arg);
3507 case EVENT_KIND_TYPE_LOAD:
3508 buffer_add_typeid (&buf, domain, arg);
3510 case EVENT_KIND_BREAKPOINT:
3511 case EVENT_KIND_STEP:
3512 buffer_add_methodid (&buf, domain, arg);
3513 buffer_add_long (&buf, il_offset);
3515 case EVENT_KIND_VM_START:
3516 buffer_add_domainid (&buf, mono_get_root_domain ());
3518 case EVENT_KIND_VM_DEATH:
3520 case EVENT_KIND_EXCEPTION: {
3521 EventInfo *ei = arg;
3522 buffer_add_objid (&buf, ei->exc);
3525 case EVENT_KIND_USER_BREAK:
3527 case EVENT_KIND_USER_LOG: {
3528 EventInfo *ei = arg;
3529 buffer_add_int (&buf, ei->level);
3530 buffer_add_string (&buf, ei->category ? ei->category : "");
3531 buffer_add_string (&buf, ei->message ? ei->message : "");
3534 case EVENT_KIND_KEEPALIVE:
3535 suspend_policy = SUSPEND_POLICY_NONE;
3538 g_assert_not_reached ();
3542 if (event == EVENT_KIND_VM_START) {
3543 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3544 if (!agent_config.defer)
3545 start_debugger_thread ();
3548 if (event == EVENT_KIND_VM_DEATH) {
3549 vm_death_event_sent = TRUE;
3550 suspend_policy = SUSPEND_POLICY_NONE;
3553 if (mono_runtime_is_shutting_down ())
3554 suspend_policy = SUSPEND_POLICY_NONE;
3556 if (suspend_policy != SUSPEND_POLICY_NONE) {
3558 * Save the thread context and start suspending before sending the packet,
3559 * since we could be receiving the resume request before send_packet ()
3562 save_thread_context (ctx);
3566 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3570 g_slist_free (events);
3573 if (!send_success) {
3574 DEBUG (2, fprintf (log_file, "Sending command %s failed.\n", event_to_string (event)));
3578 if (event == EVENT_KIND_VM_START) {
3579 vm_start_event_sent = TRUE;
3582 DEBUG (1, fprintf (log_file, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer)GetCurrentThreadId (), nevents, event_to_string (event), ecount, suspend_policy));
3584 switch (suspend_policy) {
3585 case SUSPEND_POLICY_NONE:
3587 case SUSPEND_POLICY_ALL:
3590 case SUSPEND_POLICY_EVENT_THREAD:
3594 g_assert_not_reached ();
3599 process_profiler_event (EventKind event, gpointer arg)
3603 EventInfo ei, *ei_arg = NULL;
3605 if (event == EVENT_KIND_TYPE_LOAD) {
3610 mono_loader_lock ();
3611 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3612 mono_loader_unlock ();
3614 process_event (event, arg, 0, NULL, events, suspend_policy);
3618 runtime_initialized (MonoProfiler *prof)
3620 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3621 if (agent_config.defer)
3622 start_debugger_thread ();
3626 runtime_shutdown (MonoProfiler *prof)
3628 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3630 mono_debugger_agent_cleanup ();
3634 thread_startup (MonoProfiler *prof, uintptr_t tid)
3636 MonoInternalThread *thread = mono_thread_internal_current ();
3637 MonoInternalThread *old_thread;
3638 DebuggerTlsData *tls;
3640 if (tid == debugger_thread_id)
3643 g_assert (thread->tid == tid);
3645 mono_loader_lock ();
3646 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3647 mono_loader_unlock ();
3649 if (thread == old_thread) {
3651 * For some reason, thread_startup () might be called for the same thread
3652 * multiple times (attach ?).
3654 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
3658 * thread_end () might not be called for some threads, and the tid could
3661 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
3662 mono_loader_lock ();
3663 mono_g_hash_table_remove (thread_to_tls, old_thread);
3664 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3665 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3666 mono_loader_unlock ();
3670 tls = mono_native_tls_get_value (debugger_tls_id);
3672 // FIXME: Free this somewhere
3673 tls = g_new0 (DebuggerTlsData, 1);
3674 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3675 tls->thread = thread;
3676 mono_native_tls_set_value (debugger_tls_id, tls);
3678 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3680 mono_loader_lock ();
3681 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3682 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3683 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3684 mono_loader_unlock ();
3686 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3689 * suspend_vm () could have missed this thread, so wait for a resume.
3695 thread_end (MonoProfiler *prof, uintptr_t tid)
3697 MonoInternalThread *thread;
3698 DebuggerTlsData *tls = NULL;
3700 mono_loader_lock ();
3701 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3703 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3704 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3706 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3707 tls->terminated = TRUE;
3708 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3709 MONO_GC_UNREGISTER_ROOT (tls->thread);
3713 mono_loader_unlock ();
3715 /* We might be called for threads started before we registered the start callback */
3717 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3718 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3723 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3725 mono_loader_lock ();
3726 g_hash_table_insert (domains, domain, domain);
3727 mono_loader_unlock ();
3729 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3733 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3735 clear_breakpoints_for_domain (domain);
3737 mono_loader_lock ();
3738 /* Invalidate each thread's frame stack */
3739 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3740 mono_loader_unlock ();
3742 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3746 * invalidate_each_thread:
3748 * A GHFunc to invalidate frames.
3749 * value must be a DebuggerTlsData*
3752 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3754 invalidate_frames (value);
3758 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3760 /* Sent later in jit_end () */
3761 mono_loader_lock ();
3762 g_ptr_array_add (pending_assembly_loads, assembly);
3763 mono_loader_unlock ();
3767 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3769 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3771 clear_event_requests_for_assembly (assembly);
3772 clear_types_for_assembly (assembly);
3776 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3778 #if defined(HOST_WIN32) && !defined(__GNUC__)
3779 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3781 gpointer stackptr = __builtin_frame_address (1);
3783 MonoInternalThread *thread = mono_thread_internal_current ();
3784 DebuggerTlsData *tls;
3786 mono_loader_lock ();
3788 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3789 /* Could be the debugger thread with assembly/type load hooks */
3791 tls->invoke_addr = stackptr;
3793 mono_loader_unlock ();
3797 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3800 #if defined(HOST_WIN32) && !defined(__GNUC__)
3801 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3803 gpointer stackptr = __builtin_frame_address (1);
3806 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
3810 * We need to stop single stepping when exiting a runtime invoke, since if it is
3811 * a step out, it may return to native code, and thus never end.
3813 mono_loader_lock ();
3814 ss_invoke_addr = NULL;
3816 for (i = 0; i < event_requests->len; ++i) {
3817 EventRequest *req = g_ptr_array_index (event_requests, i);
3819 if (req->event_kind == EVENT_KIND_STEP) {
3820 ss_destroy (req->info);
3821 g_ptr_array_remove_index_fast (event_requests, i);
3826 mono_loader_unlock ();
3830 send_type_load (MonoClass *klass)
3832 gboolean type_load = FALSE;
3833 MonoDomain *domain = mono_domain_get ();
3834 AgentDomainInfo *info = NULL;
3836 mono_loader_lock ();
3837 mono_domain_lock (domain);
3839 info = get_agent_domain_info (domain);
3841 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
3843 g_hash_table_insert (info->loaded_classes, klass, klass);
3846 mono_domain_unlock (domain);
3847 mono_loader_unlock ();
3849 emit_type_load (klass, klass, NULL);
3853 * Emit load events for all types currently loaded in the domain.
3854 * Takes the loader and domain locks.
3855 * user_data is unused.
3858 send_types_for_domain (MonoDomain *domain, void *user_data)
3860 AgentDomainInfo *info = NULL;
3862 mono_loader_lock ();
3863 mono_domain_lock (domain);
3864 info = get_agent_domain_info (domain);
3866 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
3867 mono_domain_unlock (domain);
3868 mono_loader_unlock ();
3872 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
3875 * We emit type load events when the first method of the type is JITted,
3876 * since the class load profiler callbacks might be called with the
3877 * loader lock held. They could also occur in the debugger thread.
3878 * Same for assembly load events.
3881 MonoAssembly *assembly = NULL;
3883 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
3884 mono_loader_lock ();
3885 if (pending_assembly_loads->len > 0) {
3886 assembly = g_ptr_array_index (pending_assembly_loads, 0);
3887 g_ptr_array_remove_index (pending_assembly_loads, 0);
3889 mono_loader_unlock ();
3892 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
3898 send_type_load (method->klass);
3901 add_pending_breakpoints (method, jinfo);
3905 * BREAKPOINTS/SINGLE STEPPING
3909 * Contains information about an inserted breakpoint.
3912 long il_offset, native_offset;
3917 } BreakpointInstance;
3920 * Contains generic information about a breakpoint.
3924 * The method where the breakpoint is placed. Can be NULL in which case it
3925 * is inserted into every method. This is used to implement method entry/
3926 * exit events. Can be a generic method definition, in which case the
3927 * breakpoint is inserted into every instance.
3933 * A list of BreakpointInstance structures describing where the breakpoint
3934 * was inserted. There could be more than one because of
3935 * generics/appdomains/method entry/exit.
3937 GPtrArray *children;
3940 /* List of breakpoints */
3941 static GPtrArray *breakpoints;
3942 /* Maps breakpoint locations to the number of breakpoints at that location */
3943 static GHashTable *bp_locs;
3946 breakpoints_init (void)
3948 breakpoints = g_ptr_array_new ();
3949 bp_locs = g_hash_table_new (NULL, NULL);
3953 * insert_breakpoint:
3955 * Insert the breakpoint described by BP into the method described by
3959 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
3962 BreakpointInstance *inst;
3963 SeqPoint *sp = NULL;
3966 mono_error_init (error);
3968 for (i = 0; i < seq_points->len; ++i) {
3969 sp = &seq_points->seq_points [i];
3971 if (sp->il_offset == bp->il_offset)
3975 if (i == seq_points->len) {
3977 * The set of IL offsets with seq points doesn't completely match the
3978 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
3980 for (i = 0; i < seq_points->len; ++i) {
3981 sp = &seq_points->seq_points [i];
3983 if (sp->il_offset != METHOD_ENTRY_IL_OFFSET && sp->il_offset != METHOD_EXIT_IL_OFFSET && sp->il_offset + 1 == bp->il_offset)
3988 if (i == seq_points->len) {
3989 char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d, seq_points=%d\n", mono_method_full_name (ji->method, TRUE), bp->il_offset, seq_points->len);
3991 for (i = 0; i < seq_points->len; ++i)
3992 DEBUG (1, fprintf (log_file, "%d\n", seq_points->seq_points [i].il_offset));
3995 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4004 inst = g_new0 (BreakpointInstance, 1);
4006 inst->native_offset = sp->native_offset;
4007 inst->ip = (guint8*)ji->code_start + sp->native_offset;
4009 inst->domain = domain;
4011 mono_loader_lock ();
4013 g_ptr_array_add (bp->children, inst);
4015 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4016 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4017 mono_loader_unlock ();
4020 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4021 mono_arch_set_breakpoint (ji, inst->ip);
4027 DEBUG(1, fprintf (log_file, "[dbg] Inserted breakpoint at %s:0x%x.\n", mono_method_full_name (ji->method, TRUE), (int)sp->il_offset));
4031 remove_breakpoint (BreakpointInstance *inst)
4033 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4035 MonoJitInfo *ji = inst->ji;
4036 guint8 *ip = inst->ip;
4038 mono_loader_lock ();
4039 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4040 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4041 mono_loader_unlock ();
4043 g_assert (count > 0);
4046 mono_arch_clear_breakpoint (ji, ip);
4053 static inline gboolean
4054 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4060 if (method == bp->method)
4062 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4065 if (bp->method->is_inflated && method->is_inflated) {
4066 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4067 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4069 /* Open generic methods should match closed generic methods of the same class */
4070 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4071 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4072 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4074 /* FIXME: Handle !mvar */
4075 if (t1->type != MONO_TYPE_MVAR)
4086 * add_pending_breakpoints:
4088 * Insert pending breakpoints into the newly JITted method METHOD.
4091 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4094 MonoSeqPointInfo *seq_points;
4100 domain = mono_domain_get ();
4102 mono_loader_lock ();
4104 for (i = 0; i < breakpoints->len; ++i) {
4105 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4106 gboolean found = FALSE;
4108 if (!bp_matches_method (bp, method))
4111 for (j = 0; j < bp->children->len; ++j) {
4112 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4119 mono_domain_lock (domain);
4120 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
4121 if (!seq_points && ji->method->is_inflated)
4122 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (ji->method));
4123 mono_domain_unlock (domain);
4125 /* Could be AOT code */
4127 g_assert (seq_points);
4129 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4133 mono_loader_unlock ();
4137 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4143 mono_error_init (error);
4145 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4147 /* Might be AOTed code */
4148 code = mono_aot_get_method (domain, method);
4150 ji = mono_jit_info_table_find (domain, code);
4155 insert_breakpoint (seq_points, domain, ji, bp, error);
4159 clear_breakpoint (MonoBreakpoint *bp);
4164 * Set a breakpoint at IL_OFFSET in METHOD.
4165 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4166 * METHOD can also be a generic method definition, in which case a breakpoint
4167 * is placed in all instances of the method.
4168 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4171 static MonoBreakpoint*
4172 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4175 GHashTableIter iter, iter2;
4178 MonoSeqPointInfo *seq_points;
4181 mono_error_init (error);
4184 // - suspend/resume the vm to prevent code patching problems
4185 // - multiple breakpoints on the same location
4186 // - dynamic methods
4189 bp = g_new0 (MonoBreakpoint, 1);
4190 bp->method = method;
4191 bp->il_offset = il_offset;
4193 bp->children = g_ptr_array_new ();
4195 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));
4197 mono_loader_lock ();
4199 g_hash_table_iter_init (&iter, domains);
4200 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4201 mono_domain_lock (domain);
4203 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4204 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4205 if (bp_matches_method (bp, m))
4206 set_bp_in_method (domain, m, seq_points, bp, error);
4209 mono_domain_unlock (domain);
4212 mono_loader_unlock ();
4214 mono_loader_lock ();
4215 g_ptr_array_add (breakpoints, bp);
4216 mono_loader_unlock ();
4218 if (error && !mono_error_ok (error)) {
4219 clear_breakpoint (bp);
4227 clear_breakpoint (MonoBreakpoint *bp)
4231 // FIXME: locking, races
4232 for (i = 0; i < bp->children->len; ++i) {
4233 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4235 remove_breakpoint (inst);
4240 mono_loader_lock ();
4241 g_ptr_array_remove (breakpoints, bp);
4242 mono_loader_unlock ();
4244 g_ptr_array_free (bp->children, TRUE);
4249 breakpoints_cleanup (void)
4253 mono_loader_lock ();
4255 while (i < event_requests->len) {
4256 EventRequest *req = g_ptr_array_index (event_requests, i);
4258 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4259 clear_breakpoint (req->info);
4260 g_ptr_array_remove_index_fast (event_requests, i);
4267 for (i = 0; i < breakpoints->len; ++i)
4268 g_free (g_ptr_array_index (breakpoints, i));
4270 g_ptr_array_free (breakpoints, TRUE);
4271 g_hash_table_destroy (bp_locs);
4276 mono_loader_unlock ();
4280 * clear_breakpoints_for_domain:
4282 * Clear breakpoint instances which reference DOMAIN.
4285 clear_breakpoints_for_domain (MonoDomain *domain)
4289 /* This could be called after shutdown */
4293 mono_loader_lock ();
4294 for (i = 0; i < breakpoints->len; ++i) {
4295 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4298 while (j < bp->children->len) {
4299 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4301 if (inst->domain == domain) {
4302 remove_breakpoint (inst);
4306 g_ptr_array_remove_index_fast (bp->children, j);
4312 mono_loader_unlock ();
4316 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4318 return bp->method && bp->method->klass->image->assembly == assembly;
4322 process_breakpoint_inner (DebuggerTlsData *tls)
4326 int i, j, suspend_policy;
4327 guint32 native_offset;
4329 BreakpointInstance *inst;
4330 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4331 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4332 EventKind kind = EVENT_KIND_BREAKPOINT;
4333 MonoContext *ctx = &tls->restore_ctx;
4334 MonoSeqPointInfo *info;
4337 // FIXME: Speed this up
4339 ip = MONO_CONTEXT_GET_IP (ctx);
4340 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4342 g_assert (ji->method);
4344 /* Compute the native offset of the breakpoint from the ip */
4345 native_offset = ip - (guint8*)ji->code_start;
4348 * Skip the instruction causing the breakpoint signal.
4350 mono_arch_skip_breakpoint (ctx, ji);
4352 if (ji->method->wrapper_type || tls->disable_breakpoints)
4355 bp_reqs = g_ptr_array_new ();
4356 ss_reqs = g_ptr_array_new ();
4357 ss_reqs_orig = g_ptr_array_new ();
4359 mono_loader_lock ();
4362 * The ip points to the instruction causing the breakpoint event, which is after
4363 * the offset recorded in the seq point map, so find the prev seq point before ip.
4365 sp = find_prev_seq_point_for_native_offset (mono_domain_get (), ji->method, native_offset, &info);
4367 DEBUG(1, fprintf (log_file, "[%p] Breakpoint hit, method=%s, ip=%p, offset=0x%x, sp il offset=0x%x.\n", (gpointer)GetCurrentThreadId (), ji->method->name, ip, native_offset, sp ? sp->il_offset : -1));
4370 for (i = 0; i < breakpoints->len; ++i) {
4371 bp = g_ptr_array_index (breakpoints, i);
4376 for (j = 0; j < bp->children->len; ++j) {
4377 inst = g_ptr_array_index (bp->children, j);
4378 if (inst->ji == ji && inst->sp == sp) {
4379 if (bp->req->event_kind == EVENT_KIND_STEP) {
4380 g_ptr_array_add (ss_reqs_orig, bp->req);
4382 g_ptr_array_add (bp_reqs, bp->req);
4387 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4388 /* Maybe a method entry/exit event */
4389 if (sp->il_offset == METHOD_ENTRY_IL_OFFSET)
4390 kind = EVENT_KIND_METHOD_ENTRY;
4391 else if (sp->il_offset == METHOD_EXIT_IL_OFFSET)
4392 kind = EVENT_KIND_METHOD_EXIT;
4395 /* Process single step requests */
4396 for (i = 0; i < ss_reqs_orig->len; ++i) {
4397 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4398 SingleStepReq *ss_req = req->info;
4399 gboolean hit = TRUE;
4401 if (ss_req->size == STEP_SIZE_LINE) {
4402 /* Have to check whenever a different source line was reached */
4403 MonoDebugMethodInfo *minfo;
4404 MonoDebugSourceLocation *loc = NULL;
4406 minfo = mono_debug_lookup_method (ji->method);
4409 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4411 if (!loc || (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line)) {
4412 /* Have to continue single stepping */
4413 DEBUG(1, fprintf (log_file, "[%p] Same source line, continuing single stepping.\n", (gpointer)GetCurrentThreadId ()));
4418 ss_req->last_method = ji->method;
4419 ss_req->last_line = loc->row;
4420 mono_debug_free_source_location (loc);
4425 g_ptr_array_add (ss_reqs, req);
4427 /* Start single stepping again from the current sequence point */
4428 ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4431 if (ss_reqs->len > 0)
4432 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4433 if (bp_reqs->len > 0)
4434 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4435 if (kind != EVENT_KIND_BREAKPOINT)
4436 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4438 mono_loader_unlock ();
4440 g_ptr_array_free (bp_reqs, TRUE);
4441 g_ptr_array_free (ss_reqs, TRUE);
4444 * FIXME: The first event will suspend, so the second will only be sent after the
4448 process_event (EVENT_KIND_STEP, ji->method, 0, ctx, ss_events, suspend_policy);
4450 process_event (kind, ji->method, 0, ctx, bp_events, suspend_policy);
4451 if (enter_leave_events)
4452 process_event (kind, ji->method, 0, ctx, enter_leave_events, suspend_policy);
4455 /* Process a breakpoint/single step event after resuming from a signal handler */
4457 process_signal_event (void (*func) (DebuggerTlsData*))
4459 DebuggerTlsData *tls;
4460 MonoContext orig_restore_ctx, ctx;
4461 static void (*restore_context) (void *);
4463 if (!restore_context)
4464 restore_context = mono_get_restore_context ();
4466 tls = mono_native_tls_get_value (debugger_tls_id);
4467 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4468 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4469 memcpy (&tls->restore_ctx, &tls->handler_ctx, sizeof (MonoContext));
4473 /* This is called when resuming from a signal handler, so it shouldn't return */
4474 memcpy (&ctx, &tls->restore_ctx, sizeof (MonoContext));
4475 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4476 restore_context (&ctx);
4477 g_assert_not_reached ();
4481 process_breakpoint (void)
4483 process_signal_event (process_breakpoint_inner);
4487 resume_from_signal_handler (void *sigctx, void *func)
4489 DebuggerTlsData *tls;
4492 /* Save the original context in TLS */
4493 // FIXME: This might not work on an altstack ?
4494 tls = mono_native_tls_get_value (debugger_tls_id);
4497 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4498 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4499 // clob:c could be added to op_seq_point.
4501 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4502 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4503 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4504 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4506 MONO_CONTEXT_SET_IP (&ctx, func);
4508 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4510 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4511 mono_ppc_set_func_into_sigctx (sigctx, func);
4516 mono_debugger_agent_breakpoint_hit (void *sigctx)
4519 * We are called from a signal handler, and running code there causes all kinds of
4520 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4521 * So set up the signal context to return to the real breakpoint handler function.
4523 resume_from_signal_handler (sigctx, process_breakpoint);
4527 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4529 if (frame->managed) {
4530 *(MonoContext*)data = *ctx;
4539 * Called by System.Diagnostics.Debugger:Break ().
4542 mono_debugger_agent_user_break (void)
4544 if (agent_config.enabled) {
4549 /* Obtain a context */
4550 MONO_CONTEXT_SET_IP (&ctx, NULL);
4551 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4552 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4554 mono_loader_lock ();
4555 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4556 mono_loader_unlock ();
4558 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4565 ss_depth_to_string (StepDepth depth)
4568 case STEP_DEPTH_OVER:
4570 case STEP_DEPTH_OUT:
4572 case STEP_DEPTH_INTO:
4575 g_assert_not_reached ();
4581 process_single_step_inner (DebuggerTlsData *tls)
4586 int il_offset, suspend_policy;
4589 MonoContext *ctx = &tls->restore_ctx;
4591 MonoSeqPointInfo *info;
4593 ip = MONO_CONTEXT_GET_IP (ctx);
4595 /* Skip the instruction causing the single step */
4596 mono_arch_skip_single_step (ctx);
4598 if (suspend_count > 0) {
4599 process_suspend (tls, ctx);
4604 // FIXME: A suspend race
4607 if (mono_thread_internal_current () != ss_req->thread)
4610 if (log_level > 0) {
4611 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4613 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 (ji->method, TRUE), MONO_CONTEXT_GET_IP (ctx), MONO_CONTEXT_GET_SP (ctx), ss_req->last_sp));
4616 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4618 g_assert (ji->method);
4620 if (ji->method->wrapper_type && ji->method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4625 * Stopping in memset makes half-initialized vtypes visible.
4626 * Stopping in memcpy makes half-copied vtypes visible.
4628 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
4632 * The ip points to the instruction causing the single step event, which is before
4633 * the offset recorded in the seq point map, so find the next seq point after ip.
4635 sp = find_next_seq_point_for_native_offset (domain, ji->method, (guint8*)ip - (guint8*)ji->code_start, &info);
4638 il_offset = sp->il_offset;
4640 // FIXME: No tests fail if this is disabled
4642 if (ss_req->size == STEP_SIZE_LINE) {
4646 /* Step until a different source line is reached */
4647 MonoDebugMethodInfo *minfo;
4649 minfo = mono_debug_lookup_method (ji->method);
4652 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4654 if (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line) {
4655 mono_debug_free_source_location (loc);
4660 * Step until we reach a location with line number info,
4661 * otherwise the client can't show a location.
4662 * This can happen for example with statics initialized inline
4663 * outside of a cctor.
4668 ss_req->last_method = ji->method;
4669 ss_req->last_line = loc->row;
4670 mono_debug_free_source_location (loc);
4676 /* Start single stepping again from the current sequence point */
4677 ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4679 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
4680 (ji->method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4681 !strcmp (ji->method->name, ".cctor"))
4684 // FIXME: Has to lock earlier
4686 reqs = g_ptr_array_new ();
4688 mono_loader_lock ();
4690 g_ptr_array_add (reqs, ss_req->req);
4692 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4694 g_ptr_array_free (reqs, TRUE);
4696 mono_loader_unlock ();
4698 process_event (EVENT_KIND_STEP, ji->method, il_offset, ctx, events, suspend_policy);
4702 process_single_step (void)
4704 process_signal_event (process_single_step_inner);
4708 * mono_debugger_agent_single_step_event:
4710 * Called from a signal handler to handle a single step event.
4713 mono_debugger_agent_single_step_event (void *sigctx)
4715 /* Resume to process_single_step through the signal context */
4717 // FIXME: Since step out/over is implemented using step in, the step in case should
4718 // be as fast as possible. Move the relevant code from process_single_step_inner ()
4721 if (GetCurrentThreadId () == debugger_thread_id) {
4723 * This could happen despite our best effors when the runtime calls
4724 * assembly/type resolve hooks.
4725 * FIXME: Breakpoints too.
4729 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4730 mono_arch_skip_single_step (&ctx);
4731 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4735 resume_from_signal_handler (sigctx, process_single_step);
4739 debugger_agent_single_step_from_context (MonoContext *ctx)
4741 DebuggerTlsData *tls;
4742 MonoContext orig_restore_ctx;
4744 tls = mono_native_tls_get_value (debugger_tls_id);
4747 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4748 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4749 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4751 process_single_step_inner (tls);
4753 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4754 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4758 debugger_agent_breakpoint_from_context (MonoContext *ctx)
4760 DebuggerTlsData *tls;
4761 MonoContext orig_restore_ctx;
4763 tls = mono_native_tls_get_value (debugger_tls_id);
4765 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4766 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4768 process_breakpoint_inner (tls);
4770 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4771 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4775 * start_single_stepping:
4777 * Turn on single stepping. Can be called multiple times, for example,
4778 * by a single step event request + a suspend.
4781 start_single_stepping (void)
4783 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4784 int val = InterlockedIncrement (&ss_count);
4787 mono_arch_start_single_stepping ();
4789 if (ss_req != NULL && ss_invoke_addr == NULL) {
4790 DebuggerTlsData *tls;
4792 mono_loader_lock ();
4794 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
4795 ss_invoke_addr = tls->invoke_addr;
4797 mono_loader_unlock ();
4800 g_assert_not_reached ();
4805 stop_single_stepping (void)
4807 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4808 int val = InterlockedDecrement (&ss_count);
4811 mono_arch_stop_single_stepping ();
4813 g_assert_not_reached ();
4820 * Stop the single stepping operation given by SS_REQ.
4823 ss_stop (SingleStepReq *ss_req)
4828 for (l = ss_req->bps; l; l = l->next) {
4829 clear_breakpoint (l->data);
4831 g_slist_free (ss_req->bps);
4835 if (ss_req->global) {
4836 stop_single_stepping ();
4837 ss_req->global = FALSE;
4844 * Start the single stepping operation given by SS_REQ from the sequence point SP.
4845 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
4846 * belong to the same thread as CTX.
4849 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
4851 int i, j, frame_index;
4854 gboolean enable_global = FALSE;
4856 /* Stop the previous operation */
4860 * Implement single stepping using breakpoints if possible.
4862 if (step_to_catch) {
4863 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
4864 ss_req->bps = g_slist_append (ss_req->bps, bp);
4868 if ((!sp || sp->next_len == 0 || ss_req->depth == STEP_DEPTH_OUT || ss_req->depth == STEP_DEPTH_OVER) && ctx) {
4869 /* Need parent frames */
4870 if (!tls->context.valid)
4871 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4872 compute_frame_info (tls->thread, tls);
4876 * Find the first sequence point in the current or in a previous frame which
4877 * is not the last in its method.
4879 if (ss_req->depth == STEP_DEPTH_OUT) {
4880 /* Ignore seq points in current method */
4881 while (frame_index < tls->frame_count) {
4882 StackFrame *frame = tls->frames [frame_index];
4884 method = frame->method;
4885 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4887 if (sp && sp->next_len != 0)
4890 // There could be method calls before the next seq point in the caller when using nested calls
4891 //enable_global = TRUE;
4893 while (sp && sp->next_len == 0) {
4895 if (frame_index < tls->frame_count) {
4896 StackFrame *frame = tls->frames [frame_index];
4898 method = frame->method;
4899 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4905 if (sp && sp->next_len > 0) {
4906 for (i = 0; i < sp->next_len; ++i) {
4907 next_sp = &info->seq_points [sp->next [i]];
4909 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
4910 ss_req->bps = g_slist_append (ss_req->bps, bp);
4914 if (ss_req->depth == STEP_DEPTH_OVER) {
4915 /* Need to stop in catch clauses as well */
4916 for (i = 0; i < tls->frame_count; ++i) {
4917 StackFrame *frame = tls->frames [i];
4920 MonoJitInfo *jinfo = frame->ji;
4921 for (j = 0; j < jinfo->num_clauses; ++j) {
4922 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
4924 sp = find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL);
4926 bp = set_breakpoint (frame->method, sp->il_offset, ss_req->req, NULL);
4927 ss_req->bps = g_slist_append (ss_req->bps, bp);
4935 if (ss_req->depth == STEP_DEPTH_INTO) {
4936 /* Enable global stepping so we stop at method entry too */
4937 enable_global = TRUE;
4941 * The ctx/frame info computed above will become invalid when we continue.
4943 tls->context.valid = FALSE;
4944 tls->async_state.valid = FALSE;
4945 invalidate_frames (tls);
4948 if (enable_global) {
4949 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
4950 ss_req->global = TRUE;
4951 start_single_stepping ();
4952 } else if (!ss_req->bps) {
4953 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
4954 ss_req->global = TRUE;
4955 start_single_stepping ();
4957 ss_req->global = FALSE;
4962 * Start single stepping of thread THREAD
4965 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
4967 DebuggerTlsData *tls;
4968 MonoSeqPointInfo *info = NULL;
4969 SeqPoint *sp = NULL;
4970 MonoMethod *method = NULL;
4971 MonoDebugMethodInfo *minfo;
4972 gboolean step_to_catch = FALSE;
4974 if (suspend_count == 0)
4975 return ERR_NOT_SUSPENDED;
4977 wait_for_suspend ();
4979 // FIXME: Multiple requests
4981 DEBUG (0, fprintf (log_file, "Received a single step request while the previous one was still active.\n"));
4982 return ERR_NOT_IMPLEMENTED;
4985 DEBUG (1, fprintf (log_file, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
4987 ss_req = g_new0 (SingleStepReq, 1);
4989 ss_req->thread = thread;
4990 ss_req->size = size;
4991 ss_req->depth = depth;
4994 mono_loader_lock ();
4995 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4996 mono_loader_unlock ();
4998 g_assert (tls->context.valid);
4999 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5001 if (tls->has_catch_ctx) {
5003 StackFrameInfo frame;
5004 MonoContext new_ctx;
5005 MonoLMF *lmf = NULL;
5008 * We are stopped at a throw site. Stepping should go to the catch site.
5011 /* Find the the jit info for the catch context */
5012 res = mono_find_jit_info_ext (mono_domain_get (), thread->jit_data, NULL, &tls->catch_ctx, &new_ctx, NULL, &lmf, NULL, &frame);
5014 g_assert (frame.type == FRAME_TYPE_MANAGED);
5017 * Find the seq point corresponding to the landing site ip, which is the first seq
5020 sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
5023 method = frame.method;
5025 step_to_catch = TRUE;
5026 /* This make sure the seq point is not skipped by process_single_step () */
5027 ss_req->last_sp = NULL;
5030 if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
5033 /* Compute the initial line info */
5034 compute_frame_info (thread, tls);
5036 if (tls->frame_count) {
5037 frame = tls->frames [0];
5039 ss_req->last_method = frame->method;
5040 ss_req->last_line = -1;
5042 minfo = mono_debug_lookup_method (frame->method);
5043 if (minfo && frame->il_offset != -1) {
5044 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
5047 ss_req->last_line = loc->row;
5054 if (!step_to_catch) {
5057 compute_frame_info (thread, tls);
5059 if (tls->frame_count) {
5060 frame = tls->frames [0];
5062 if (!method && frame->il_offset != -1) {
5063 /* FIXME: Sort the table and use a binary search */
5064 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5066 method = frame->method;
5071 ss_start (ss_req, method, sp, info, &tls->context.ctx, tls, step_to_catch);
5077 ss_destroy (SingleStepReq *req)
5080 g_assert (ss_req == req);
5089 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5092 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5098 if (!agent_config.enabled)
5101 mono_loader_lock ();
5102 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5103 mono_loader_unlock ();
5106 ei.category = category ? mono_string_to_utf8 (category) : NULL;
5107 ei.message = message ? mono_string_to_utf8 (message) : NULL;
5109 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5111 g_free (ei.category);
5112 g_free (ei.message);
5116 mono_debugger_agent_debug_log_is_enabled (void)
5118 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5119 return agent_config.enabled;
5122 #ifdef PLATFORM_ANDROID
5124 mono_debugger_agent_unhandled_exception (MonoException *exc)
5133 memset (&ei, 0, sizeof (EventInfo));
5134 ei.exc = (MonoObject*)exc;
5136 mono_loader_lock ();
5137 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5138 mono_loader_unlock ();
5140 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5145 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5146 MonoContext *catch_ctx)
5152 DebuggerTlsData *tls = NULL;
5154 if (thread_to_tls != NULL) {
5155 MonoInternalThread *thread = mono_thread_internal_current ();
5157 mono_loader_lock ();
5158 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5159 mono_loader_unlock ();
5161 if (tls && tls->abort_requested)
5163 if (tls && tls->disable_breakpoints)
5167 memset (&ei, 0, sizeof (EventInfo));
5169 /* Just-In-Time debugging */
5171 if (agent_config.onuncaught && !inited) {
5172 finish_agent_init (FALSE);
5175 * Send an unsolicited EXCEPTION event with a dummy request id.
5177 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5178 ei.exc = (MonoObject*)exc;
5179 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5182 } else if (agent_config.onthrow && !inited) {
5184 gboolean found = FALSE;
5186 for (l = agent_config.onthrow; l; l = l->next) {
5187 char *ex_type = l->data;
5188 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5190 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5197 finish_agent_init (FALSE);
5200 * Send an unsolicited EXCEPTION event with a dummy request id.
5202 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5203 ei.exc = (MonoObject*)exc;
5204 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5212 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5214 ei.exc = (MonoObject*)exc;
5215 ei.caught = catch_ctx != NULL;
5217 mono_loader_lock ();
5218 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5219 mono_loader_unlock ();
5221 if (tls && catch_ctx) {
5222 tls->catch_ctx = *catch_ctx;
5223 tls->has_catch_ctx = TRUE;
5226 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5229 tls->has_catch_ctx = FALSE;
5233 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5235 DebuggerTlsData *tls;
5240 tls = mono_native_tls_get_value (debugger_tls_id);
5245 * We're about to invoke an exception filter during the first pass of exception handling.
5247 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5248 * 'orig_ctx' is the context where the exception has been thrown.
5251 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5253 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5254 * the call site (line 37) and then continue to Main(), but it would never
5255 * include the throw site (line 32).
5257 * Since exception filters are invoked during the first pass of exception handling,
5258 * the stack frames of the throw site are still intact, so we should include them
5261 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5263 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5264 * but report the location of the 'throw' to the user.
5268 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5272 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5274 DebuggerTlsData *tls;
5279 tls = mono_native_tls_get_value (debugger_tls_id);
5283 tls->filter_state.valid = FALSE;
5287 * buffer_add_value_full:
5289 * Add the encoding of the value at ADDR described by T to the buffer.
5290 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5294 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5300 g_assert (*(void**)addr);
5301 addr = *(void**)addr;
5306 case MONO_TYPE_BOOLEAN:
5309 case MONO_TYPE_CHAR:
5329 case MONO_TYPE_VOID:
5330 buffer_add_byte (buf, t->type);
5332 case MONO_TYPE_BOOLEAN:
5335 buffer_add_byte (buf, t->type);
5336 buffer_add_int (buf, *(gint8*)addr);
5338 case MONO_TYPE_CHAR:
5341 buffer_add_byte (buf, t->type);
5342 buffer_add_int (buf, *(gint16*)addr);
5347 buffer_add_byte (buf, t->type);
5348 buffer_add_int (buf, *(gint32*)addr);
5353 buffer_add_byte (buf, t->type);
5354 buffer_add_long (buf, *(gint64*)addr);
5358 /* Treat it as a vtype */
5360 case MONO_TYPE_PTR: {
5361 gssize val = *(gssize*)addr;
5363 buffer_add_byte (buf, t->type);
5364 buffer_add_long (buf, val);
5368 case MONO_TYPE_STRING:
5369 case MONO_TYPE_SZARRAY:
5370 case MONO_TYPE_OBJECT:
5371 case MONO_TYPE_CLASS:
5372 case MONO_TYPE_ARRAY:
5373 obj = *(MonoObject**)addr;
5376 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5378 if (obj->vtable->klass->valuetype) {
5379 t = &obj->vtable->klass->byval_arg;
5380 addr = mono_object_unbox (obj);
5382 } else if (obj->vtable->klass->rank) {
5383 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5384 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5385 buffer_add_byte (buf, MONO_TYPE_CLASS);
5387 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5389 buffer_add_objid (buf, obj);
5393 case MONO_TYPE_VALUETYPE: {
5397 MonoClass *klass = mono_class_from_mono_type (t);
5399 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5400 buffer_add_byte (buf, klass->enumtype);
5401 buffer_add_typeid (buf, domain, klass);
5405 while ((f = mono_class_get_fields (klass, &iter))) {
5406 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5408 if (mono_field_is_deleted (f))
5412 buffer_add_int (buf, nfields);
5415 while ((f = mono_class_get_fields (klass, &iter))) {
5416 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5418 if (mono_field_is_deleted (f))
5420 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE);
5424 case MONO_TYPE_GENERICINST:
5425 if (mono_type_generic_inst_is_valuetype (t)) {
5437 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5439 buffer_add_value_full (buf, t, addr, domain, FALSE);
5443 obj_is_of_type (MonoObject *obj, MonoType *t)
5445 MonoClass *klass = obj->vtable->klass;
5446 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5447 if (klass == mono_defaults.transparent_proxy_class) {
5448 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5449 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5459 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5462 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5466 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5467 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5468 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5469 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5470 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
5471 char *name = mono_type_full_name (t);
5472 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5474 return ERR_INVALID_ARGUMENT;
5478 case MONO_TYPE_BOOLEAN:
5479 *(guint8*)addr = decode_int (buf, &buf, limit);
5481 case MONO_TYPE_CHAR:
5482 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5485 *(gint8*)addr = decode_int (buf, &buf, limit);
5488 *(guint8*)addr = decode_int (buf, &buf, limit);
5491 *(gint16*)addr = decode_int (buf, &buf, limit);
5494 *(guint16*)addr = decode_int (buf, &buf, limit);
5497 *(gint32*)addr = decode_int (buf, &buf, limit);
5500 *(guint32*)addr = decode_int (buf, &buf, limit);
5503 *(gint64*)addr = decode_long (buf, &buf, limit);
5506 *(guint64*)addr = decode_long (buf, &buf, limit);
5509 *(guint32*)addr = decode_int (buf, &buf, limit);
5512 *(guint64*)addr = decode_long (buf, &buf, limit);
5515 /* We send these as I8, so we get them back as such */
5516 g_assert (type == MONO_TYPE_I8);
5517 *(gssize*)addr = decode_long (buf, &buf, limit);
5519 case MONO_TYPE_GENERICINST:
5520 if (MONO_TYPE_ISSTRUCT (t)) {
5521 /* The client sends these as a valuetype */
5529 /* We send these as vtypes, so we get them back as such */
5530 g_assert (type == MONO_TYPE_VALUETYPE);
5533 case MONO_TYPE_VALUETYPE: {
5534 gboolean is_enum = decode_byte (buf, &buf, limit);
5538 gpointer iter = NULL;
5541 /* Enums are sent as a normal vtype */
5543 return ERR_NOT_IMPLEMENTED;
5544 klass = decode_typeid (buf, &buf, limit, &d, &err);
5548 if (klass != mono_class_from_mono_type (t))
5549 return ERR_INVALID_ARGUMENT;
5551 nfields = decode_int (buf, &buf, limit);
5552 while ((f = mono_class_get_fields (klass, &iter))) {
5553 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5555 if (mono_field_is_deleted (f))
5557 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5562 g_assert (nfields == 0);
5567 if (MONO_TYPE_IS_REFERENCE (t)) {
5568 if (type == MONO_TYPE_OBJECT) {
5569 int objid = decode_objid (buf, &buf, limit);
5573 err = get_object (objid, (MonoObject**)&obj);
5578 if (!obj_is_of_type (obj, t)) {
5579 DEBUG (1, fprintf (log_file, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name));
5580 return ERR_INVALID_ARGUMENT;
5583 if (obj && obj->vtable->domain != domain)
5584 return ERR_INVALID_ARGUMENT;
5586 mono_gc_wbarrier_generic_store (addr, obj);
5587 } else if (type == VALUE_TYPE_ID_NULL) {
5588 *(MonoObject**)addr = NULL;
5590 return ERR_INVALID_ARGUMENT;
5604 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5607 int type = decode_byte (buf, &buf, limit);
5609 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
5610 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
5611 guint8 *nullable_buf;
5614 * First try decoding it as a Nullable`1
5616 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5621 * Then try decoding as a primitive value or null.
5623 if (targ->type == type) {
5624 nullable_buf = g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
5625 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
5627 g_free (nullable_buf);
5630 mono_nullable_init (addr, mono_value_box (domain, mono_class_from_mono_type (targ), nullable_buf), mono_class_from_mono_type (t));
5631 g_free (nullable_buf);
5634 } else if (type == VALUE_TYPE_ID_NULL) {
5635 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
5641 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5645 add_var (Buffer *buf, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
5652 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5653 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5656 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
5657 reg_val = mono_arch_context_get_int_reg (ctx, reg);
5659 buffer_add_value_full (buf, t, ®_val, domain, as_vtype);
5661 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5662 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5663 addr += (gint32)var->offset;
5665 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5667 buffer_add_value_full (buf, t, addr, domain, as_vtype);
5669 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5673 g_assert_not_reached ();
5678 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
5684 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5685 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5687 if (MONO_TYPE_IS_REFERENCE (t))
5688 size = sizeof (gpointer);
5690 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
5693 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
5694 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
5696 gboolean is_signed = FALSE;
5698 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
5703 v = is_signed ? *(gint8*)val : *(guint8*)val;
5706 v = is_signed ? *(gint16*)val : *(guint16*)val;
5709 v = is_signed ? *(gint32*)val : *(guint32*)val;
5712 v = is_signed ? *(gint64*)val : *(guint64*)val;
5715 g_assert_not_reached ();
5721 /* Set value on the stack or in the return ctx */
5722 if (reg_locations [reg]) {
5723 /* Saved on the stack */
5724 DEBUG (1, fprintf (log_file, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v));
5725 *(reg_locations [reg]) = v;
5728 DEBUG (1, fprintf (log_file, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v));
5729 mono_arch_context_set_int_reg (restore_ctx, reg, v);
5732 // FIXME: Move these to mono-context.h/c.
5733 mono_arch_context_set_int_reg (ctx, reg, v);
5735 // FIXME: Can't set registers, so we disable linears
5740 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5741 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5742 addr += (gint32)var->offset;
5744 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5747 addr = *(guint8**)addr;
5753 // FIXME: Write barriers
5754 mono_gc_memmove (addr, val, size);
5756 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5760 g_assert_not_reached ();
5765 clear_event_request (int req_id, int etype)
5769 mono_loader_lock ();
5770 for (i = 0; i < event_requests->len; ++i) {
5771 EventRequest *req = g_ptr_array_index (event_requests, i);
5773 if (req->id == req_id && req->event_kind == etype) {
5774 if (req->event_kind == EVENT_KIND_BREAKPOINT)
5775 clear_breakpoint (req->info);
5776 if (req->event_kind == EVENT_KIND_STEP)
5777 ss_destroy (req->info);
5778 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
5779 clear_breakpoint (req->info);
5780 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
5781 clear_breakpoint (req->info);
5782 g_ptr_array_remove_index_fast (event_requests, i);
5787 mono_loader_unlock ();
5791 event_req_matches_assembly (EventRequest *req, MonoAssembly *assembly)
5793 if (req->event_kind == EVENT_KIND_BREAKPOINT)
5794 return breakpoint_matches_assembly (req->info, assembly);
5798 for (i = 0; i < req->nmodifiers; ++i) {
5799 Modifier *m = &req->modifiers [i];
5801 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
5803 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
5804 for (j = 0; m->data.assemblies [j]; ++j)
5805 if (m->data.assemblies [j] == assembly)
5815 * clear_event_requests_for_assembly:
5817 * Clear all events requests which reference ASSEMBLY.
5820 clear_event_requests_for_assembly (MonoAssembly *assembly)
5825 mono_loader_lock ();
5829 for (i = 0; i < event_requests->len; ++i) {
5830 EventRequest *req = g_ptr_array_index (event_requests, i);
5832 if (event_req_matches_assembly (req, assembly)) {
5833 clear_event_request (req->id, req->event_kind);
5839 mono_loader_unlock ();
5843 * type_comes_from_assembly:
5845 * GHRFunc that returns TRUE if klass comes from assembly
5848 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
5850 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
5854 * clear_types_for_assembly:
5856 * Clears types from loaded_classes for a given assembly
5859 clear_types_for_assembly (MonoAssembly *assembly)
5861 MonoDomain *domain = mono_domain_get ();
5862 AgentDomainInfo *info = NULL;
5864 mono_loader_lock ();
5865 info = get_agent_domain_info (domain);
5866 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
5867 mono_loader_unlock ();
5871 add_thread (gpointer key, gpointer value, gpointer user_data)
5873 MonoInternalThread *thread = value;
5874 Buffer *buf = user_data;
5876 buffer_add_objid (buf, (MonoObject*)thread);
5880 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
5882 guint8 *end = invoke->endp;
5885 MonoMethodSignature *sig;
5888 MonoObject *this, *res, *exc;
5891 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5894 MonoStopwatch watch;
5896 if (invoke->method) {
5898 * Invoke this method directly, currently only Environment.Exit () is supported.
5901 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>"));
5902 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
5903 g_assert_not_reached ();
5906 m = decode_methodid (p, &p, end, &domain, &err);
5909 sig = mono_method_signature (m);
5911 if (m->klass->valuetype)
5912 this_buf = g_alloca (mono_class_instance_size (m->klass));
5914 this_buf = g_alloca (sizeof (MonoObject*));
5915 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
5916 /* Should be null */
5917 int type = decode_byte (p, &p, end);
5918 if (type != VALUE_TYPE_ID_NULL)
5919 return ERR_INVALID_ARGUMENT;
5920 memset (this_buf, 0, mono_class_instance_size (m->klass));
5922 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
5927 if (!m->klass->valuetype)
5928 this = *(MonoObject**)this_buf;
5932 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>"));
5934 if (this && this->vtable->domain != domain)
5937 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
5938 if (!strcmp (m->name, ".ctor")) {
5939 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
5940 return ERR_INVALID_ARGUMENT;
5942 this = mono_object_new (domain, m->klass);
5944 return ERR_INVALID_ARGUMENT;
5948 if (this && !obj_is_of_type (this, &m->klass->byval_arg))
5949 return ERR_INVALID_ARGUMENT;
5951 nargs = decode_int (p, &p, end);
5952 if (nargs != sig->param_count)
5953 return ERR_INVALID_ARGUMENT;
5954 /* Use alloca to get gc tracking */
5955 arg_buf = g_alloca (nargs * sizeof (gpointer));
5956 memset (arg_buf, 0, nargs * sizeof (gpointer));
5957 args = g_alloca (nargs * sizeof (gpointer));
5958 for (i = 0; i < nargs; ++i) {
5959 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
5960 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
5964 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
5967 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
5968 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
5971 args [i] = arg_buf [i];
5978 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
5979 tls->disable_breakpoints = TRUE;
5981 tls->disable_breakpoints = FALSE;
5984 * Add an LMF frame to link the stack frames on the invoke method with our caller.
5986 /* FIXME: Move this to arch specific code */
5987 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5988 if (invoke->has_ctx) {
5991 lmf_addr = mono_get_lmf_addr ();
5994 memset (&ext, 0, sizeof (ext));
5996 ext.lmf.previous_lmf = *(lmf_addr);
5997 /* Mark that this is a MonoLMFExt */
5998 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
5999 ext.lmf.rsp = (gssize)&ext;
6000 #elif defined(TARGET_X86)
6001 ext.lmf.previous_lmf = (gsize)*(lmf_addr);
6002 /* Mark that this is a MonoLMFExt */
6003 ext.lmf.previous_lmf = (gsize)(gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6004 ext.lmf.ebp = (gssize)&ext;
6005 #elif defined(TARGET_ARM)
6006 ext.lmf.previous_lmf = *(lmf_addr);
6007 /* Mark that this is a MonoLMFExt */
6008 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6009 ext.lmf.sp = (gssize)&ext;
6010 #elif defined(TARGET_POWERPC)
6011 ext.lmf.previous_lmf = *(lmf_addr);
6012 /* Mark that this is a MonoLMFExt */
6013 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6014 ext.lmf.ebp = (gssize)&ext;
6015 #elif defined(TARGET_S390X)
6016 ext.lmf.previous_lmf = *(lmf_addr);
6017 /* Mark that this is a MonoLMFExt */
6018 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6019 ext.lmf.ebp = (gssize)&ext;
6020 #elif defined(TARGET_MIPS)
6021 ext.lmf.previous_lmf = *(lmf_addr);
6022 /* Mark that this is a MonoLMFExt */
6023 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6024 ext.lmf.iregs [mips_sp] = (gssize)&ext;
6026 g_assert_not_reached ();
6029 ext.debugger_invoke = TRUE;
6030 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6032 mono_set_lmf ((MonoLMF*)&ext);
6036 mono_stopwatch_start (&watch);
6037 if (m->klass->valuetype)
6038 res = mono_runtime_invoke (m, this_buf, args, &exc);
6040 res = mono_runtime_invoke (m, this, args, &exc);
6041 mono_stopwatch_stop (&watch);
6042 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)));
6044 buffer_add_byte (buf, 0);
6045 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6047 buffer_add_byte (buf, 1);
6048 if (sig->ret->type == MONO_TYPE_VOID) {
6049 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
6050 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
6053 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6054 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6055 buffer_add_value (buf, sig->ret, &res, domain);
6056 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6057 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6058 MonoClass *k = mono_class_from_mono_type (sig->ret);
6059 guint8 *nullable_buf = g_alloca (mono_class_value_size (k, NULL));
6061 g_assert (nullable_buf);
6062 mono_nullable_init (nullable_buf, res, k);
6063 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6066 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6073 tls->disable_breakpoints = FALSE;
6075 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6076 if (invoke->has_ctx)
6077 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
6081 // FIXME: byref arguments
6089 * Invoke the method given by tls->pending_invoke in the current thread.
6092 invoke_method (void)
6094 DebuggerTlsData *tls;
6099 static void (*restore_context) (void *);
6100 MonoContext restore_ctx;
6103 if (!restore_context)
6104 restore_context = mono_get_restore_context ();
6106 tls = mono_native_tls_get_value (debugger_tls_id);
6110 * Store the `InvokeData *' in `tls->invoke' until we're done with
6111 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6114 mono_loader_lock ();
6116 invoke = tls->pending_invoke;
6118 tls->pending_invoke = NULL;
6120 invoke->last_invoke = tls->invoke;
6121 tls->invoke = invoke;
6123 mono_loader_unlock ();
6125 tls->frames_up_to_date = FALSE;
6131 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6132 buffer_init (&buf, 128);
6135 /* Fail the other invokes as well */
6137 err = do_invoke_method (tls, &buf, invoke, p, &p);
6140 /* Start suspending before sending the reply */
6141 if (mindex == invoke->nmethods - 1) {
6142 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6143 for (i = 0; i < invoke->suspend_count; ++i)
6148 send_reply_packet (id, err, &buf);
6153 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6155 if (invoke->has_ctx)
6156 save_thread_context (&restore_ctx);
6158 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6159 g_assert (tls->resume_count);
6160 tls->resume_count -= invoke->suspend_count;
6163 DEBUG (1, fprintf (log_file, "[%p] Invoke finished, resume_count = %d.\n", (gpointer)GetCurrentThreadId (), tls->resume_count));
6166 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6168 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
6169 * after the mono_runtime_invoke() already returned, but it doesn't matter
6170 * because we reset the abort here.
6173 mono_loader_lock ();
6175 if (tls->abort_requested)
6176 mono_thread_internal_reset_abort (tls->thread);
6178 tls->invoke = tls->invoke->last_invoke;
6179 tls->abort_requested = FALSE;
6181 mono_loader_unlock ();
6190 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6192 MonoThread *thread = value;
6193 DebuggerTlsData *tls;
6196 mono_loader_lock ();
6197 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6199 res = tls->really_suspended;
6200 mono_loader_unlock ();
6206 get_source_files_for_type (MonoClass *klass)
6208 gpointer iter = NULL;
6210 MonoDebugSourceInfo *sinfo;
6214 files = g_ptr_array_new ();
6216 while ((method = mono_class_get_methods (klass, &iter))) {
6217 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6218 GPtrArray *source_file_list;
6221 mono_debug_symfile_get_line_numbers_full (minfo, NULL, &source_file_list, NULL, NULL, NULL, NULL, NULL);
6222 for (j = 0; j < source_file_list->len; ++j) {
6223 sinfo = g_ptr_array_index (source_file_list, j);
6224 for (i = 0; i < files->len; ++i)
6225 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6227 if (i == files->len)
6228 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6230 g_ptr_array_free (source_file_list, TRUE);
6238 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6241 case CMD_VM_VERSION: {
6242 char *build_info, *version;
6244 build_info = mono_get_runtime_build_info ();
6245 version = g_strdup_printf ("mono %s", build_info);
6247 buffer_add_string (buf, version); /* vm version */
6248 buffer_add_int (buf, MAJOR_VERSION);
6249 buffer_add_int (buf, MINOR_VERSION);
6250 g_free (build_info);
6254 case CMD_VM_SET_PROTOCOL_VERSION: {
6255 major_version = decode_int (p, &p, end);
6256 minor_version = decode_int (p, &p, end);
6257 protocol_version_set = TRUE;
6258 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
6261 case CMD_VM_ALL_THREADS: {
6263 mono_loader_lock ();
6264 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6265 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6266 mono_loader_unlock ();
6269 case CMD_VM_SUSPEND:
6271 wait_for_suspend ();
6274 if (suspend_count == 0)
6275 return ERR_NOT_SUSPENDED;
6278 case CMD_VM_DISPOSE:
6279 /* Clear all event requests */
6280 mono_loader_lock ();
6281 while (event_requests->len > 0) {
6282 EventRequest *req = g_ptr_array_index (event_requests, 0);
6284 clear_event_request (req->id, req->event_kind);
6286 mono_loader_unlock ();
6288 while (suspend_count > 0)
6290 disconnected = TRUE;
6291 vm_start_event_sent = FALSE;
6294 MonoInternalThread *thread;
6295 DebuggerTlsData *tls;
6296 MonoClass *env_class;
6297 MonoMethod *exit_method = NULL;
6301 exit_code = decode_int (p, &p, end);
6303 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6305 /* Have to send a reply before exiting */
6306 send_reply_packet (id, 0, buf);
6308 /* Clear all event requests */
6309 mono_loader_lock ();
6310 while (event_requests->len > 0) {
6311 EventRequest *req = g_ptr_array_index (event_requests, 0);
6313 clear_event_request (req->id, req->event_kind);
6315 mono_loader_unlock ();
6318 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6319 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6320 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6321 * better than doing the shutdown ourselves, since it avoids various races.
6325 wait_for_suspend ();
6327 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6328 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
6330 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6333 mono_loader_lock ();
6334 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6335 mono_loader_unlock ();
6337 if (thread && exit_method) {
6338 mono_loader_lock ();
6339 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6340 mono_loader_unlock ();
6342 args = g_new0 (gpointer, 1);
6343 args [0] = g_malloc (sizeof (int));
6344 *(int*)(args [0]) = exit_code;
6346 tls->pending_invoke = g_new0 (InvokeData, 1);
6347 tls->pending_invoke->method = exit_method;
6348 tls->pending_invoke->args = args;
6349 tls->pending_invoke->nmethods = 1;
6351 while (suspend_count > 0)
6355 * No thread found, do it ourselves.
6356 * FIXME: This can race with normal shutdown etc.
6358 while (suspend_count > 0)
6361 mono_runtime_set_shutting_down ();
6363 mono_threads_set_shutting_down ();
6365 /* Suspend all managed threads since the runtime is going away */
6366 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
6367 mono_thread_suspend_all_other_threads ();
6368 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
6369 mono_runtime_quit ();
6370 transport_close2 ();
6371 DEBUG(1, fprintf (log_file, "Exiting...\n"));
6377 case CMD_VM_INVOKE_METHOD:
6378 case CMD_VM_INVOKE_METHODS: {
6379 int objid = decode_objid (p, &p, end);
6381 DebuggerTlsData *tls;
6382 int i, count, err, flags, nmethods;
6384 err = get_object (objid, (MonoObject**)&thread);
6388 flags = decode_int (p, &p, end);
6390 if (command == CMD_VM_INVOKE_METHODS)
6391 nmethods = decode_int (p, &p, end);
6395 // Wait for suspending if it already started
6397 wait_for_suspend ();
6398 if (!is_suspended ())
6399 return ERR_NOT_SUSPENDED;
6401 mono_loader_lock ();
6402 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6403 mono_loader_unlock ();
6406 if (!tls->really_suspended)
6407 /* The thread is still running native code, can't do invokes */
6408 return ERR_NOT_SUSPENDED;
6411 * Store the invoke data into tls, the thread will execute it after it is
6414 if (tls->pending_invoke)
6415 return ERR_NOT_SUSPENDED;
6416 tls->pending_invoke = g_new0 (InvokeData, 1);
6417 tls->pending_invoke->id = id;
6418 tls->pending_invoke->flags = flags;
6419 tls->pending_invoke->p = g_malloc (end - p);
6420 memcpy (tls->pending_invoke->p, p, end - p);
6421 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
6422 tls->pending_invoke->suspend_count = suspend_count;
6423 tls->pending_invoke->nmethods = nmethods;
6425 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
6426 resume_thread (THREAD_TO_INTERNAL (thread));
6429 count = suspend_count;
6430 for (i = 0; i < count; ++i)
6435 case CMD_VM_ABORT_INVOKE: {
6436 int objid = decode_objid (p, &p, end);
6438 DebuggerTlsData *tls;
6441 err = get_object (objid, (MonoObject**)&thread);
6445 invoke_id = decode_int (p, &p, end);
6447 mono_loader_lock ();
6448 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6451 if (tls->abort_requested) {
6452 mono_loader_unlock ();
6457 * Check whether we're still inside the mono_runtime_invoke() and that it's
6458 * actually the correct invocation.
6460 * Careful, we do not stop the thread that's doing the invocation, so we can't
6461 * inspect its stack. However, invoke_method() also acquires the loader lock
6462 * when it's done, so we're safe here.
6466 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
6467 mono_loader_unlock ();
6468 return ERR_NO_INVOCATION;
6471 tls->abort_requested = TRUE;
6473 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
6474 mono_loader_unlock ();
6478 case CMD_VM_SET_KEEPALIVE: {
6479 int timeout = decode_int (p, &p, end);
6480 agent_config.keepalive = timeout;
6482 #ifndef DISABLE_SOCKET_TRANSPORT
6489 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
6490 GHashTableIter iter, kiter;
6495 char *fname, *basename;
6496 gboolean ignore_case;
6497 GSList *class_list, *l;
6498 GPtrArray *res_classes, *res_domains;
6500 fname = decode_string (p, &p, end);
6501 ignore_case = decode_byte (p, &p, end);
6503 basename = g_path_get_basename (fname);
6505 res_classes = g_ptr_array_new ();
6506 res_domains = g_ptr_array_new ();
6508 mono_loader_lock ();
6509 g_hash_table_iter_init (&iter, domains);
6510 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6511 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
6513 /* Update 'source_file_to_class' cache */
6514 g_hash_table_iter_init (&kiter, info->loaded_classes);
6515 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
6516 if (!g_hash_table_lookup (info->source_files, klass)) {
6517 files = get_source_files_for_type (klass);
6518 g_hash_table_insert (info->source_files, klass, files);
6520 for (i = 0; i < files->len; ++i) {
6521 char *s = g_ptr_array_index (files, i);
6522 char *s2 = g_path_get_basename (s);
6525 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
6527 class_list = g_slist_prepend (class_list, klass);
6528 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
6530 class_list = g_slist_prepend (class_list, klass);
6531 g_hash_table_insert (info->source_file_to_class, s2, class_list);
6534 /* The _ignorecase hash contains the lowercase path */
6535 s3 = strdup_tolower (s2);
6536 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
6538 class_list = g_slist_prepend (class_list, klass);
6539 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
6541 class_list = g_slist_prepend (class_list, klass);
6542 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
6554 s = strdup_tolower (basename);
6555 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
6558 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
6561 for (l = class_list; l; l = l->next) {
6564 g_ptr_array_add (res_classes, klass);
6565 g_ptr_array_add (res_domains, domain);
6568 mono_loader_unlock ();
6573 buffer_add_int (buf, res_classes->len);
6574 for (i = 0; i < res_classes->len; ++i)
6575 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6576 g_ptr_array_free (res_classes, TRUE);
6577 g_ptr_array_free (res_domains, TRUE);
6580 case CMD_VM_GET_TYPES: {
6581 GHashTableIter iter;
6585 gboolean ignore_case;
6586 GPtrArray *res_classes, *res_domains;
6587 MonoTypeNameParse info;
6589 name = decode_string (p, &p, end);
6590 ignore_case = decode_byte (p, &p, end);
6592 if (!mono_reflection_parse_type (name, &info)) {
6594 mono_reflection_free_type_info (&info);
6595 return ERR_INVALID_ARGUMENT;
6598 res_classes = g_ptr_array_new ();
6599 res_domains = g_ptr_array_new ();
6601 mono_loader_lock ();
6602 g_hash_table_iter_init (&iter, domains);
6603 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6605 gboolean type_resolve;
6609 mono_domain_assemblies_lock (domain);
6610 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6614 type_resolve = TRUE;
6615 t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
6617 g_ptr_array_add (res_classes, mono_type_get_class (t));
6618 g_ptr_array_add (res_domains, domain);
6622 mono_domain_assemblies_unlock (domain);
6624 mono_loader_unlock ();
6627 mono_reflection_free_type_info (&info);
6629 buffer_add_int (buf, res_classes->len);
6630 for (i = 0; i < res_classes->len; ++i)
6631 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6632 g_ptr_array_free (res_classes, TRUE);
6633 g_ptr_array_free (res_domains, TRUE);
6638 return ERR_NOT_IMPLEMENTED;
6645 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6651 case CMD_EVENT_REQUEST_SET: {
6653 int i, event_kind, suspend_policy, nmodifiers, mod;
6656 MonoThread *step_thread;
6657 int size = 0, depth = 0, filter = 0, step_thread_id = 0;
6661 event_kind = decode_byte (p, &p, end);
6662 suspend_policy = decode_byte (p, &p, end);
6663 nmodifiers = decode_byte (p, &p, end);
6665 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
6666 req->id = InterlockedIncrement (&event_request_id);
6667 req->event_kind = event_kind;
6668 req->suspend_policy = suspend_policy;
6669 req->nmodifiers = nmodifiers;
6672 for (i = 0; i < nmodifiers; ++i) {
6673 mod = decode_byte (p, &p, end);
6675 req->modifiers [i].kind = mod;
6676 if (mod == MOD_KIND_COUNT) {
6677 req->modifiers [i].data.count = decode_int (p, &p, end);
6678 } else if (mod == MOD_KIND_LOCATION_ONLY) {
6679 method = decode_methodid (p, &p, end, &domain, &err);
6682 location = decode_long (p, &p, end);
6683 } else if (mod == MOD_KIND_STEP) {
6684 step_thread_id = decode_id (p, &p, end);
6685 size = decode_int (p, &p, end);
6686 depth = decode_int (p, &p, end);
6687 if (CHECK_PROTOCOL_VERSION (2, 16))
6688 filter = decode_int (p, &p, end);
6689 req->modifiers [i].data.filter = filter;
6690 } else if (mod == MOD_KIND_THREAD_ONLY) {
6691 int id = decode_id (p, &p, end);
6693 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
6698 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
6699 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
6703 req->modifiers [i].caught = decode_byte (p, &p, end);
6704 req->modifiers [i].uncaught = decode_byte (p, &p, end);
6705 DEBUG(1, fprintf (log_file, "[dbg] \tEXCEPTION_ONLY filter (%s%s%s).\n", exc_class ? exc_class->name : "all", req->modifiers [i].caught ? ", caught" : "", req->modifiers [i].uncaught ? ", uncaught" : ""));
6707 req->modifiers [i].data.exc_class = exc_class;
6709 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
6711 return ERR_INVALID_ARGUMENT;
6714 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
6715 int n = decode_int (p, &p, end);
6718 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
6719 for (j = 0; j < n; ++j) {
6720 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
6722 g_free (req->modifiers [i].data.assemblies);
6726 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
6727 int n = decode_int (p, &p, end);
6730 modifier = &req->modifiers [i];
6731 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
6732 for (j = 0; j < n; ++j) {
6733 char *s = decode_string (p, &p, end);
6737 s2 = strdup_tolower (s);
6738 g_hash_table_insert (modifier->data.source_files, s2, s2);
6742 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
6743 int n = decode_int (p, &p, end);
6746 modifier = &req->modifiers [i];
6747 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
6748 for (j = 0; j < n; ++j) {
6749 char *s = decode_string (p, &p, end);
6752 g_hash_table_insert (modifier->data.type_names, s, s);
6756 return ERR_NOT_IMPLEMENTED;
6760 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
6763 req->info = set_breakpoint (method, location, req, &error);
6764 if (!mono_error_ok (&error)) {
6766 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
6767 mono_error_cleanup (&error);
6768 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
6770 } else if (req->event_kind == EVENT_KIND_STEP) {
6771 g_assert (step_thread_id);
6773 err = get_object (step_thread_id, (MonoObject**)&step_thread);
6779 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
6784 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
6785 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
6786 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
6787 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
6788 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
6789 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
6791 if (req->nmodifiers) {
6793 return ERR_NOT_IMPLEMENTED;
6797 mono_loader_lock ();
6798 g_ptr_array_add (event_requests, req);
6800 if (agent_config.defer) {
6801 /* Transmit cached data to the client on receipt of the event request */
6802 switch (req->event_kind) {
6803 case EVENT_KIND_APPDOMAIN_CREATE:
6804 /* Emit load events for currently loaded domains */
6805 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
6807 case EVENT_KIND_ASSEMBLY_LOAD:
6808 /* Emit load events for currently loaded assemblies */
6809 mono_assembly_foreach (emit_assembly_load, NULL);
6811 case EVENT_KIND_THREAD_START:
6812 /* Emit start events for currently started threads */
6813 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
6815 case EVENT_KIND_TYPE_LOAD:
6816 /* Emit type load events for currently loaded types */
6817 mono_domain_foreach (send_types_for_domain, NULL);
6823 mono_loader_unlock ();
6825 buffer_add_int (buf, req->id);
6828 case CMD_EVENT_REQUEST_CLEAR: {
6829 int etype = decode_byte (p, &p, end);
6830 int req_id = decode_int (p, &p, end);
6832 // FIXME: Make a faster mapping from req_id to request
6833 mono_loader_lock ();
6834 clear_event_request (req_id, etype);
6835 mono_loader_unlock ();
6838 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
6841 mono_loader_lock ();
6843 while (i < event_requests->len) {
6844 EventRequest *req = g_ptr_array_index (event_requests, i);
6846 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
6847 clear_breakpoint (req->info);
6849 g_ptr_array_remove_index_fast (event_requests, i);
6855 mono_loader_unlock ();
6859 return ERR_NOT_IMPLEMENTED;
6866 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6872 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
6873 buffer_add_domainid (buf, mono_get_root_domain ());
6876 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
6877 domain = decode_domainid (p, &p, end, NULL, &err);
6880 buffer_add_string (buf, domain->friendly_name);
6883 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
6888 domain = decode_domainid (p, &p, end, NULL, &err);
6891 mono_loader_lock ();
6893 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6896 buffer_add_int (buf, count);
6897 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6899 buffer_add_assemblyid (buf, domain, ass);
6901 mono_loader_unlock ();
6904 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
6905 domain = decode_domainid (p, &p, end, NULL, &err);
6909 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
6912 case CMD_APPDOMAIN_GET_CORLIB: {
6913 domain = decode_domainid (p, &p, end, NULL, &err);
6917 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
6920 case CMD_APPDOMAIN_CREATE_STRING: {
6924 domain = decode_domainid (p, &p, end, NULL, &err);
6927 s = decode_string (p, &p, end);
6929 o = mono_string_new (domain, s);
6930 buffer_add_objid (buf, (MonoObject*)o);
6933 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
6935 MonoDomain *domain2;
6938 domain = decode_domainid (p, &p, end, NULL, &err);
6941 klass = decode_typeid (p, &p, end, &domain2, &err);
6946 g_assert (domain == domain2);
6948 o = mono_object_new (domain, klass);
6950 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
6954 buffer_add_objid (buf, o);
6958 return ERR_NOT_IMPLEMENTED;
6965 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6971 ass = decode_assemblyid (p, &p, end, &domain, &err);
6976 case CMD_ASSEMBLY_GET_LOCATION: {
6977 buffer_add_string (buf, mono_image_get_filename (ass->image));
6980 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
6984 if (ass->image->dynamic) {
6985 buffer_add_id (buf, 0);
6987 token = mono_image_get_entry_point (ass->image);
6989 buffer_add_id (buf, 0);
6991 m = mono_get_method (ass->image, token, NULL);
6992 buffer_add_methodid (buf, domain, m);
6997 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
6998 buffer_add_moduleid (buf, domain, ass->image);
7001 case CMD_ASSEMBLY_GET_OBJECT: {
7002 MonoObject *o = (MonoObject*)mono_assembly_get_object (domain, ass);
7003 buffer_add_objid (buf, o);
7006 case CMD_ASSEMBLY_GET_TYPE: {
7007 char *s = decode_string (p, &p, end);
7008 gboolean ignorecase = decode_byte (p, &p, end);
7009 MonoTypeNameParse info;
7011 gboolean type_resolve, res;
7012 MonoDomain *d = mono_domain_get ();
7014 /* This is needed to be able to find referenced assemblies */
7015 res = mono_domain_set (domain, FALSE);
7018 if (!mono_reflection_parse_type (s, &info)) {
7021 if (info.assembly.name)
7023 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
7025 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
7026 mono_reflection_free_type_info (&info);
7029 mono_domain_set (d, TRUE);
7033 case CMD_ASSEMBLY_GET_NAME: {
7035 MonoAssembly *mass = ass;
7037 name = g_strdup_printf (
7038 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7040 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7041 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7042 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7043 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7045 buffer_add_string (buf, name);
7050 return ERR_NOT_IMPLEMENTED;
7057 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7063 case CMD_MODULE_GET_INFO: {
7064 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7067 basename = g_path_get_basename (image->name);
7068 buffer_add_string (buf, basename); // name
7069 buffer_add_string (buf, image->module_name); // scopename
7070 buffer_add_string (buf, image->name); // fqname
7071 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7072 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7077 return ERR_NOT_IMPLEMENTED;
7084 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7086 if (val && val->vtable->klass == mono_defaults.monotype_class) {
7087 /* Special case these so the client doesn't have to handle Type objects */
7089 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7090 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7091 } else if (MONO_TYPE_IS_REFERENCE (t))
7092 buffer_add_value (buf, t, &val, domain);
7094 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7098 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7104 buffer_add_int (buf, 0);
7108 for (i = 0; i < cinfo->num_attrs; ++i) {
7109 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7112 buffer_add_int (buf, nattrs);
7114 for (i = 0; i < cinfo->num_attrs; ++i) {
7115 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7116 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7117 MonoArray *typed_args, *named_args;
7119 CattrNamedArg *arginfo;
7121 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo);
7123 buffer_add_methodid (buf, domain, attr->ctor);
7127 buffer_add_int (buf, mono_array_length (typed_args));
7128 for (j = 0; j < mono_array_length (typed_args); ++j) {
7129 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7131 t = mono_method_signature (attr->ctor)->params [j];
7133 buffer_add_cattr_arg (buf, t, domain, val);
7136 buffer_add_int (buf, 0);
7141 buffer_add_int (buf, mono_array_length (named_args));
7143 for (j = 0; j < mono_array_length (named_args); ++j) {
7144 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7146 if (arginfo [j].prop) {
7147 buffer_add_byte (buf, 0x54);
7148 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7149 } else if (arginfo [j].field) {
7150 buffer_add_byte (buf, 0x53);
7151 buffer_add_fieldid (buf, domain, arginfo [j].field);
7153 g_assert_not_reached ();
7156 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7159 buffer_add_int (buf, 0);
7165 /* FIXME: Code duplication with icall.c */
7167 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7172 mono_class_setup_interfaces (klass, error);
7173 if (!mono_error_ok (error))
7176 for (i = 0; i < klass->interface_count; i++) {
7177 ic = klass->interfaces [i];
7178 g_hash_table_insert (ifaces, ic, ic);
7180 collect_interfaces (ic, ifaces, error);
7181 if (!mono_error_ok (error))
7187 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7197 case CMD_TYPE_GET_INFO: {
7198 buffer_add_string (buf, klass->name_space);
7199 buffer_add_string (buf, klass->name);
7201 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7202 buffer_add_string (buf, name);
7204 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7205 buffer_add_moduleid (buf, domain, klass->image);
7206 buffer_add_typeid (buf, domain, klass->parent);
7207 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7208 buffer_add_typeid (buf, domain, klass->element_class);
7210 buffer_add_id (buf, 0);
7211 buffer_add_int (buf, klass->type_token);
7212 buffer_add_byte (buf, klass->rank);
7213 buffer_add_int (buf, klass->flags);
7215 type = &klass->byval_arg;
7216 // FIXME: Can't decide whenever a class represents a byref type
7219 if (type->type == MONO_TYPE_PTR)
7221 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7223 if (type->type == MONO_TYPE_VALUETYPE)
7225 if (klass->enumtype)
7227 if (klass->generic_container)
7229 if (klass->generic_container || klass->generic_class)
7231 buffer_add_byte (buf, b);
7234 while ((nested = mono_class_get_nested_types (klass, &iter)))
7236 buffer_add_int (buf, nnested);
7238 while ((nested = mono_class_get_nested_types (klass, &iter)))
7239 buffer_add_typeid (buf, domain, nested);
7240 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7241 if (klass->generic_container)
7242 buffer_add_typeid (buf, domain, klass);
7243 else if (klass->generic_class)
7244 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7246 buffer_add_id (buf, 0);
7248 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7251 if (klass->generic_class) {
7252 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7254 count = inst->type_argc;
7255 buffer_add_int (buf, count);
7256 for (i = 0; i < count; i++)
7257 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7258 } else if (klass->generic_container) {
7259 MonoGenericContainer *container = klass->generic_container;
7262 count = container->type_argc;
7263 buffer_add_int (buf, count);
7264 for (i = 0; i < count; i++) {
7265 pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
7266 buffer_add_typeid (buf, domain, pklass);
7269 buffer_add_int (buf, 0);
7274 case CMD_TYPE_GET_METHODS: {
7277 gpointer iter = NULL;
7280 mono_class_setup_methods (klass);
7282 nmethods = mono_class_num_methods (klass);
7284 buffer_add_int (buf, nmethods);
7286 while ((m = mono_class_get_methods (klass, &iter))) {
7287 buffer_add_methodid (buf, domain, m);
7290 g_assert (i == nmethods);
7293 case CMD_TYPE_GET_FIELDS: {
7296 gpointer iter = NULL;
7299 nfields = mono_class_num_fields (klass);
7301 buffer_add_int (buf, nfields);
7303 while ((f = mono_class_get_fields (klass, &iter))) {
7304 buffer_add_fieldid (buf, domain, f);
7305 buffer_add_string (buf, f->name);
7306 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7307 buffer_add_int (buf, f->type->attrs);
7310 g_assert (i == nfields);
7313 case CMD_TYPE_GET_PROPERTIES: {
7316 gpointer iter = NULL;
7319 nprops = mono_class_num_properties (klass);
7321 buffer_add_int (buf, nprops);
7323 while ((p = mono_class_get_properties (klass, &iter))) {
7324 buffer_add_propertyid (buf, domain, p);
7325 buffer_add_string (buf, p->name);
7326 buffer_add_methodid (buf, domain, p->get);
7327 buffer_add_methodid (buf, domain, p->set);
7328 buffer_add_int (buf, p->attrs);
7331 g_assert (i == nprops);
7334 case CMD_TYPE_GET_CATTRS: {
7335 MonoClass *attr_klass;
7336 MonoCustomAttrInfo *cinfo;
7338 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7339 /* attr_klass can be NULL */
7343 cinfo = mono_custom_attrs_from_class (klass);
7345 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7348 case CMD_TYPE_GET_FIELD_CATTRS: {
7349 MonoClass *attr_klass;
7350 MonoCustomAttrInfo *cinfo;
7351 MonoClassField *field;
7353 field = decode_fieldid (p, &p, end, NULL, &err);
7356 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7360 cinfo = mono_custom_attrs_from_field (klass, field);
7362 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7365 case CMD_TYPE_GET_PROPERTY_CATTRS: {
7366 MonoClass *attr_klass;
7367 MonoCustomAttrInfo *cinfo;
7370 prop = decode_propertyid (p, &p, end, NULL, &err);
7373 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7377 cinfo = mono_custom_attrs_from_property (klass, prop);
7379 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7382 case CMD_TYPE_GET_VALUES:
7383 case CMD_TYPE_GET_VALUES_2: {
7390 MonoThread *thread_obj;
7391 MonoInternalThread *thread = NULL;
7392 guint32 special_static_type;
7394 if (command == CMD_TYPE_GET_VALUES_2) {
7395 int objid = decode_objid (p, &p, end);
7398 err = get_object (objid, (MonoObject**)&thread_obj);
7402 thread = THREAD_TO_INTERNAL (thread_obj);
7405 len = decode_int (p, &p, end);
7406 for (i = 0; i < len; ++i) {
7407 f = decode_fieldid (p, &p, end, NULL, &err);
7411 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7412 return ERR_INVALID_FIELDID;
7413 special_static_type = mono_class_field_get_special_static_type (f);
7414 if (special_static_type != SPECIAL_STATIC_NONE) {
7415 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
7416 return ERR_INVALID_FIELDID;
7419 /* Check that the field belongs to the object */
7421 for (k = klass; k; k = k->parent) {
7422 if (k == f->parent) {
7428 return ERR_INVALID_FIELDID;
7430 vtable = mono_class_vtable (domain, f->parent);
7431 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7432 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
7433 buffer_add_value (buf, f->type, val, domain);
7438 case CMD_TYPE_SET_VALUES: {
7446 len = decode_int (p, &p, end);
7447 for (i = 0; i < len; ++i) {
7448 f = decode_fieldid (p, &p, end, NULL, &err);
7452 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7453 return ERR_INVALID_FIELDID;
7454 if (mono_class_field_is_special_static (f))
7455 return ERR_INVALID_FIELDID;
7457 /* Check that the field belongs to the object */
7459 for (k = klass; k; k = k->parent) {
7460 if (k == f->parent) {
7466 return ERR_INVALID_FIELDID;
7468 // FIXME: Check for literal/const
7470 vtable = mono_class_vtable (domain, f->parent);
7471 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7472 err = decode_value (f->type, domain, val, p, &p, end);
7477 if (MONO_TYPE_IS_REFERENCE (f->type))
7478 mono_field_static_set_value (vtable, f, *(gpointer*)val);
7480 mono_field_static_set_value (vtable, f, val);
7485 case CMD_TYPE_GET_OBJECT: {
7486 MonoObject *o = (MonoObject*)mono_type_get_object (domain, &klass->byval_arg);
7487 buffer_add_objid (buf, o);
7490 case CMD_TYPE_GET_SOURCE_FILES:
7491 case CMD_TYPE_GET_SOURCE_FILES_2: {
7492 char *source_file, *base;
7496 files = get_source_files_for_type (klass);
7498 buffer_add_int (buf, files->len);
7499 for (i = 0; i < files->len; ++i) {
7500 source_file = g_ptr_array_index (files, i);
7501 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
7502 buffer_add_string (buf, source_file);
7504 base = g_path_get_basename (source_file);
7505 buffer_add_string (buf, base);
7508 g_free (source_file);
7510 g_ptr_array_free (files, TRUE);
7513 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
7514 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
7518 if (mono_class_is_assignable_from (klass, oklass))
7519 buffer_add_byte (buf, 1);
7521 buffer_add_byte (buf, 0);
7524 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
7525 char *name = decode_string (p, &p, end);
7526 int i, flags = decode_int (p, &p, end);
7527 MonoException *ex = NULL;
7528 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
7531 return ERR_LOADER_ERROR;
7532 buffer_add_int (buf, array->len);
7533 for (i = 0; i < array->len; ++i) {
7534 MonoMethod *method = g_ptr_array_index (array, i);
7535 buffer_add_methodid (buf, domain, method);
7538 g_ptr_array_free (array, TRUE);
7542 case CMD_TYPE_GET_INTERFACES: {
7544 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
7546 MonoClass *tclass, *iface;
7547 GHashTableIter iter;
7551 for (parent = tclass; parent; parent = parent->parent) {
7552 mono_class_setup_interfaces (parent, &error);
7553 if (!mono_error_ok (&error))
7554 return ERR_LOADER_ERROR;
7555 collect_interfaces (parent, iface_hash, &error);
7556 if (!mono_error_ok (&error))
7557 return ERR_LOADER_ERROR;
7560 buffer_add_int (buf, g_hash_table_size (iface_hash));
7562 g_hash_table_iter_init (&iter, iface_hash);
7563 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
7564 buffer_add_typeid (buf, domain, iface);
7565 g_hash_table_destroy (iface_hash);
7568 case CMD_TYPE_GET_INTERFACE_MAP: {
7569 int tindex, ioffset;
7570 gboolean variance_used;
7572 int len, nmethods, i;
7576 len = decode_int (p, &p, end);
7577 mono_class_setup_vtable (klass);
7579 for (tindex = 0; tindex < len; ++tindex) {
7580 iclass = decode_typeid (p, &p, end, NULL, &err);
7584 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
7586 return ERR_INVALID_ARGUMENT;
7588 nmethods = mono_class_num_methods (iclass);
7589 buffer_add_int (buf, nmethods);
7592 while ((method = mono_class_get_methods (iclass, &iter))) {
7593 buffer_add_methodid (buf, domain, method);
7595 for (i = 0; i < nmethods; ++i)
7596 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
7601 return ERR_NOT_IMPLEMENTED;
7608 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7611 MonoDomain *old_domain;
7615 klass = decode_typeid (p, &p, end, &domain, &err);
7619 old_domain = mono_domain_get ();
7621 mono_domain_set (domain, TRUE);
7623 err = type_commands_internal (command, klass, domain, p, end, buf);
7625 mono_domain_set (old_domain, TRUE);
7631 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7633 MonoMethodHeader *header;
7637 case CMD_METHOD_GET_NAME: {
7638 buffer_add_string (buf, method->name);
7641 case CMD_METHOD_GET_DECLARING_TYPE: {
7642 buffer_add_typeid (buf, domain, method->klass);
7645 case CMD_METHOD_GET_DEBUG_INFO: {
7646 MonoDebugMethodInfo *minfo;
7648 int i, j, n_il_offsets;
7651 int *column_numbers;
7653 GPtrArray *source_file_list;
7655 header = mono_method_get_header (method);
7657 buffer_add_int (buf, 0);
7658 buffer_add_string (buf, "");
7659 buffer_add_int (buf, 0);
7663 minfo = mono_debug_lookup_method (method);
7665 buffer_add_int (buf, header->code_size);
7666 buffer_add_string (buf, "");
7667 buffer_add_int (buf, 0);
7668 mono_metadata_free_mh (header);
7672 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, &n_il_offsets, &il_offsets, &line_numbers, &column_numbers, &source_files);
7673 buffer_add_int (buf, header->code_size);
7674 if (CHECK_PROTOCOL_VERSION (2, 13)) {
7675 buffer_add_int (buf, source_file_list->len);
7676 for (i = 0; i < source_file_list->len; ++i) {
7677 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
7678 buffer_add_string (buf, sinfo->source_file);
7679 if (CHECK_PROTOCOL_VERSION (2, 14)) {
7680 for (j = 0; j < 16; ++j)
7681 buffer_add_byte (buf, sinfo->hash [j]);
7685 buffer_add_string (buf, source_file);
7687 buffer_add_int (buf, n_il_offsets);
7688 DEBUG (10, fprintf (log_file, "Line number table for method %s:\n", mono_method_full_name (method, TRUE)));
7689 for (i = 0; i < n_il_offsets; ++i) {
7690 const char *srcfile = "";
7692 if (source_files [i] != -1) {
7693 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
7694 srcfile = sinfo->source_file;
7696 DEBUG (10, fprintf (log_file, "IL%x -> %s:%d %d\n", il_offsets [i], srcfile, line_numbers [i], column_numbers ? column_numbers [i] : -1));
7697 buffer_add_int (buf, il_offsets [i]);
7698 buffer_add_int (buf, line_numbers [i]);
7699 if (CHECK_PROTOCOL_VERSION (2, 13))
7700 buffer_add_int (buf, source_files [i]);
7701 if (CHECK_PROTOCOL_VERSION (2, 19))
7702 buffer_add_int (buf, column_numbers ? column_numbers [i] : -1);
7704 g_free (source_file);
7705 g_free (il_offsets);
7706 g_free (line_numbers);
7707 g_free (source_files);
7708 g_ptr_array_free (source_file_list, TRUE);
7709 mono_metadata_free_mh (header);
7712 case CMD_METHOD_GET_PARAM_INFO: {
7713 MonoMethodSignature *sig = mono_method_signature (method);
7717 /* FIXME: mono_class_from_mono_type () and byrefs */
7719 /* FIXME: Use a smaller encoding */
7720 buffer_add_int (buf, sig->call_convention);
7721 buffer_add_int (buf, sig->param_count);
7722 buffer_add_int (buf, sig->generic_param_count);
7723 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
7724 for (i = 0; i < sig->param_count; ++i) {
7726 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
7729 /* Emit parameter names */
7730 names = g_new (char *, sig->param_count);
7731 mono_method_get_param_names (method, (const char **) names);
7732 for (i = 0; i < sig->param_count; ++i)
7733 buffer_add_string (buf, names [i]);
7738 case CMD_METHOD_GET_LOCALS_INFO: {
7739 int i, j, num_locals;
7740 MonoDebugLocalsInfo *locals;
7742 header = mono_method_get_header (method);
7744 return ERR_INVALID_ARGUMENT;
7746 buffer_add_int (buf, header->num_locals);
7749 for (i = 0; i < header->num_locals; ++i)
7750 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
7753 locals = mono_debug_lookup_locals (method);
7755 num_locals = locals->num_locals;
7758 for (i = 0; i < header->num_locals; ++i) {
7759 for (j = 0; j < num_locals; ++j)
7760 if (locals->locals [j].index == i)
7763 buffer_add_string (buf, locals->locals [j].name);
7765 buffer_add_string (buf, "");
7769 for (i = 0; i < header->num_locals; ++i) {
7770 for (j = 0; j < num_locals; ++j)
7771 if (locals->locals [j].index == i)
7773 if (j < num_locals && locals->locals [j].block) {
7774 buffer_add_int (buf, locals->locals [j].block->start_offset);
7775 buffer_add_int (buf, locals->locals [j].block->end_offset);
7777 buffer_add_int (buf, 0);
7778 buffer_add_int (buf, header->code_size);
7781 mono_metadata_free_mh (header);
7784 mono_debug_symfile_free_locals (locals);
7788 case CMD_METHOD_GET_INFO:
7789 buffer_add_int (buf, method->flags);
7790 buffer_add_int (buf, method->iflags);
7791 buffer_add_int (buf, method->token);
7792 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7794 if (method->is_generic)
7796 if (mono_method_signature (method)->generic_param_count)
7798 buffer_add_byte (buf, attrs);
7799 if (method->is_generic || method->is_inflated) {
7802 if (method->is_generic) {
7805 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
7807 result = imethod->declaring;
7808 if (imethod->context.class_inst) {
7809 MonoClass *klass = ((MonoMethod *) imethod)->klass;
7810 /*Generic methods gets the context of the GTD.*/
7811 if (mono_class_get_context (klass))
7812 result = mono_class_inflate_generic_method_full (result, klass, mono_class_get_context (klass));
7816 buffer_add_methodid (buf, domain, result);
7818 buffer_add_id (buf, 0);
7820 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7821 if (mono_method_signature (method)->generic_param_count) {
7824 if (method->is_inflated) {
7825 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
7827 count = inst->type_argc;
7828 buffer_add_int (buf, count);
7830 for (i = 0; i < count; i++)
7831 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7833 buffer_add_int (buf, 0);
7835 } else if (method->is_generic) {
7836 MonoGenericContainer *container = mono_method_get_generic_container (method);
7838 count = mono_method_signature (method)->generic_param_count;
7839 buffer_add_int (buf, count);
7840 for (i = 0; i < count; i++) {
7841 MonoGenericParam *param = mono_generic_container_get_param (container, i);
7842 MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
7843 buffer_add_typeid (buf, domain, pklass);
7846 buffer_add_int (buf, 0);
7849 buffer_add_int (buf, 0);
7854 case CMD_METHOD_GET_BODY: {
7857 header = mono_method_get_header (method);
7859 buffer_add_int (buf, 0);
7861 if (CHECK_PROTOCOL_VERSION (2, 18))
7862 buffer_add_int (buf, 0);
7864 buffer_add_int (buf, header->code_size);
7865 for (i = 0; i < header->code_size; ++i)
7866 buffer_add_byte (buf, header->code [i]);
7868 if (CHECK_PROTOCOL_VERSION (2, 18)) {
7869 buffer_add_int (buf, header->num_clauses);
7870 for (i = 0; i < header->num_clauses; ++i) {
7871 MonoExceptionClause *clause = &header->clauses [i];
7873 buffer_add_int (buf, clause->flags);
7874 buffer_add_int (buf, clause->try_offset);
7875 buffer_add_int (buf, clause->try_len);
7876 buffer_add_int (buf, clause->handler_offset);
7877 buffer_add_int (buf, clause->handler_len);
7878 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
7879 buffer_add_typeid (buf, domain, clause->data.catch_class);
7880 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
7881 buffer_add_int (buf, clause->data.filter_offset);
7885 mono_metadata_free_mh (header);
7890 case CMD_METHOD_RESOLVE_TOKEN: {
7891 guint32 token = decode_int (p, &p, end);
7894 switch (mono_metadata_token_code (token)) {
7895 case MONO_TOKEN_STRING: {
7899 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
7902 s2 = mono_string_to_utf8 (s);
7904 buffer_add_byte (buf, TOKEN_TYPE_STRING);
7905 buffer_add_string (buf, s2);
7911 MonoClass *handle_class;
7913 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
7914 val = mono_method_get_wrapper_data (method, token);
7915 handle_class = mono_method_get_wrapper_data (method, token + 1);
7917 if (handle_class == NULL) {
7918 // Can't figure out the token type
7919 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
7923 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
7927 if (handle_class == mono_defaults.typehandle_class) {
7928 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
7929 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
7930 buffer_add_typeid (buf, domain, (MonoClass *) val);
7932 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
7933 } else if (handle_class == mono_defaults.fieldhandle_class) {
7934 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
7935 buffer_add_fieldid (buf, domain, val);
7936 } else if (handle_class == mono_defaults.methodhandle_class) {
7937 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
7938 buffer_add_methodid (buf, domain, val);
7939 } else if (handle_class == mono_defaults.string_class) {
7942 s = mono_string_to_utf8 (val);
7943 buffer_add_byte (buf, TOKEN_TYPE_STRING);
7944 buffer_add_string (buf, s);
7947 g_assert_not_reached ();
7954 case CMD_METHOD_GET_CATTRS: {
7955 MonoClass *attr_klass;
7956 MonoCustomAttrInfo *cinfo;
7958 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7959 /* attr_klass can be NULL */
7963 cinfo = mono_custom_attrs_from_method (method);
7965 buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
7969 return ERR_NOT_IMPLEMENTED;
7976 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7979 MonoDomain *old_domain;
7983 method = decode_methodid (p, &p, end, &domain, &err);
7987 old_domain = mono_domain_get ();
7989 mono_domain_set (domain, TRUE);
7991 err = method_commands_internal (command, method, domain, p, end, buf);
7993 mono_domain_set (old_domain, TRUE);
7999 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8001 int objid = decode_objid (p, &p, end);
8003 MonoThread *thread_obj;
8004 MonoInternalThread *thread;
8006 err = get_object (objid, (MonoObject**)&thread_obj);
8010 thread = THREAD_TO_INTERNAL (thread_obj);
8013 case CMD_THREAD_GET_NAME: {
8015 gunichar2 *s = mono_thread_get_name (thread, &name_len);
8018 buffer_add_int (buf, 0);
8023 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
8025 buffer_add_int (buf, len);
8026 buffer_add_data (buf, (guint8*)name, len);
8031 case CMD_THREAD_GET_FRAME_INFO: {
8032 DebuggerTlsData *tls;
8033 int i, start_frame, length;
8035 // Wait for suspending if it already started
8036 // FIXME: Races with suspend_count
8037 while (!is_suspended ()) {
8039 wait_for_suspend ();
8043 wait_for_suspend ();
8044 if (!is_suspended ())
8045 return ERR_NOT_SUSPENDED;
8048 start_frame = decode_int (p, &p, end);
8049 length = decode_int (p, &p, end);
8051 if (start_frame != 0 || length != -1)
8052 return ERR_NOT_IMPLEMENTED;
8054 mono_loader_lock ();
8055 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8056 mono_loader_unlock ();
8059 compute_frame_info (thread, tls);
8061 buffer_add_int (buf, tls->frame_count);
8062 for (i = 0; i < tls->frame_count; ++i) {
8063 buffer_add_int (buf, tls->frames [i]->id);
8064 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
8065 buffer_add_int (buf, tls->frames [i]->il_offset);
8067 * Instead of passing the frame type directly to the client, we associate
8068 * it with the previous frame using a set of flags. This avoids lots of
8069 * conditional code in the client, since a frame whose type isn't
8070 * FRAME_TYPE_MANAGED has no method, location, etc.
8072 buffer_add_byte (buf, tls->frames [i]->flags);
8077 case CMD_THREAD_GET_STATE:
8078 buffer_add_int (buf, thread->state);
8080 case CMD_THREAD_GET_INFO:
8081 buffer_add_byte (buf, thread->threadpool_thread);
8083 case CMD_THREAD_GET_ID:
8084 buffer_add_long (buf, (guint64)(gsize)thread);
8086 case CMD_THREAD_GET_TID:
8087 buffer_add_long (buf, (guint64)thread->tid);
8090 return ERR_NOT_IMPLEMENTED;
8097 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8101 MonoThread *thread_obj;
8102 MonoInternalThread *thread;
8103 int pos, i, len, frame_idx;
8104 DebuggerTlsData *tls;
8106 MonoDebugMethodJitInfo *jit;
8107 MonoDebugVarInfo *var;
8108 MonoMethodSignature *sig;
8110 MonoMethodHeader *header;
8112 objid = decode_objid (p, &p, end);
8113 err = get_object (objid, (MonoObject**)&thread_obj);
8117 thread = THREAD_TO_INTERNAL (thread_obj);
8119 id = decode_id (p, &p, end);
8121 mono_loader_lock ();
8122 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8123 mono_loader_unlock ();
8126 for (i = 0; i < tls->frame_count; ++i) {
8127 if (tls->frames [i]->id == id)
8130 if (i == tls->frame_count)
8131 return ERR_INVALID_FRAMEID;
8134 frame = tls->frames [frame_idx];
8136 if (!frame->has_ctx)
8138 return ERR_INVALID_FRAMEID;
8141 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
8142 if (!frame->jit && frame->api_method->is_inflated)
8143 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
8147 /* This could happen for aot images with no jit debug info */
8148 s = mono_method_full_name (frame->api_method, TRUE);
8149 DEBUG (1, fprintf (log_file, "[dbg] No debug information found for '%s'.\n", s));
8151 return ERR_ABSENT_INFORMATION;
8156 sig = mono_method_signature (frame->actual_method);
8158 if (!get_seq_points (frame->domain, frame->actual_method))
8160 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
8162 return ERR_ABSENT_INFORMATION;
8165 case CMD_STACK_FRAME_GET_VALUES: {
8166 len = decode_int (p, &p, end);
8167 header = mono_method_get_header (frame->actual_method);
8169 for (i = 0; i < len; ++i) {
8170 pos = decode_int (p, &p, end);
8175 g_assert (pos >= 0 && pos < jit->num_params);
8177 var = &jit->params [pos];
8179 add_var (buf, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
8181 g_assert (pos >= 0 && pos < jit->num_locals);
8183 var = &jit->locals [pos];
8185 add_var (buf, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
8188 mono_metadata_free_mh (header);
8191 case CMD_STACK_FRAME_GET_THIS: {
8192 if (frame->api_method->klass->valuetype) {
8193 if (!sig->hasthis) {
8194 MonoObject *p = NULL;
8195 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
8197 add_var (buf, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8200 if (!sig->hasthis) {
8201 MonoObject *p = NULL;
8202 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
8204 add_var (buf, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8209 case CMD_STACK_FRAME_SET_VALUES: {
8212 MonoDebugVarInfo *var;
8214 len = decode_int (p, &p, end);
8215 header = mono_method_get_header (frame->actual_method);
8217 for (i = 0; i < len; ++i) {
8218 pos = decode_int (p, &p, end);
8223 g_assert (pos >= 0 && pos < jit->num_params);
8225 t = sig->params [pos];
8226 var = &jit->params [pos];
8228 g_assert (pos >= 0 && pos < jit->num_locals);
8230 t = header->locals [pos];
8231 var = &jit->locals [pos];
8234 if (MONO_TYPE_IS_REFERENCE (t))
8235 val_buf = g_alloca (sizeof (MonoObject*));
8237 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
8238 err = decode_value (t, frame->domain, val_buf, p, &p, end);
8242 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_ctx);
8244 mono_metadata_free_mh (header);
8248 return ERR_NOT_IMPLEMENTED;
8255 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8258 int objid, err, index, len, i, esize;
8261 objid = decode_objid (p, &p, end);
8262 err = get_object (objid, (MonoObject**)&arr);
8267 case CMD_ARRAY_REF_GET_LENGTH:
8268 buffer_add_int (buf, arr->obj.vtable->klass->rank);
8270 buffer_add_int (buf, arr->max_length);
8271 buffer_add_int (buf, 0);
8273 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
8274 buffer_add_int (buf, arr->bounds [i].length);
8275 buffer_add_int (buf, arr->bounds [i].lower_bound);
8279 case CMD_ARRAY_REF_GET_VALUES:
8280 index = decode_int (p, &p, end);
8281 len = decode_int (p, &p, end);
8283 g_assert (index >= 0 && len >= 0);
8284 // Reordered to avoid integer overflow
8285 g_assert (!(index > arr->max_length - len));
8287 esize = mono_array_element_size (arr->obj.vtable->klass);
8288 for (i = index; i < index + len; ++i) {
8289 elem = (gpointer*)((char*)arr->vector + (i * esize));
8290 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
8293 case CMD_ARRAY_REF_SET_VALUES:
8294 index = decode_int (p, &p, end);
8295 len = decode_int (p, &p, end);
8297 g_assert (index >= 0 && len >= 0);
8298 // Reordered to avoid integer overflow
8299 g_assert (!(index > arr->max_length - len));
8301 esize = mono_array_element_size (arr->obj.vtable->klass);
8302 for (i = index; i < index + len; ++i) {
8303 elem = (gpointer*)((char*)arr->vector + (i * esize));
8305 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
8309 return ERR_NOT_IMPLEMENTED;
8316 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8321 int i, index, length;
8324 objid = decode_objid (p, &p, end);
8325 err = get_object (objid, (MonoObject**)&str);
8330 case CMD_STRING_REF_GET_VALUE:
8331 s = mono_string_to_utf8 (str);
8332 buffer_add_string (buf, s);
8335 case CMD_STRING_REF_GET_LENGTH:
8336 buffer_add_long (buf, mono_string_length (str));
8338 case CMD_STRING_REF_GET_CHARS:
8339 index = decode_long (p, &p, end);
8340 length = decode_long (p, &p, end);
8341 if (index > mono_string_length (str) - length)
8342 return ERR_INVALID_ARGUMENT;
8343 c = mono_string_chars (str) + index;
8344 for (i = 0; i < length; ++i)
8345 buffer_add_short (buf, c [i]);
8348 return ERR_NOT_IMPLEMENTED;
8355 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8364 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
8365 objid = decode_objid (p, &p, end);
8366 err = get_object (objid, &obj);
8368 buffer_add_int (buf, 1);
8370 buffer_add_int (buf, 0);
8374 objid = decode_objid (p, &p, end);
8375 err = get_object (objid, &obj);
8380 case CMD_OBJECT_REF_GET_TYPE:
8381 /* This handles transparent proxies too */
8382 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8384 case CMD_OBJECT_REF_GET_VALUES:
8385 len = decode_int (p, &p, end);
8387 for (i = 0; i < len; ++i) {
8388 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
8392 /* Check that the field belongs to the object */
8394 for (k = obj->vtable->klass; k; k = k->parent) {
8395 if (k == f->parent) {
8401 return ERR_INVALID_FIELDID;
8403 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8407 if (mono_class_field_is_special_static (f))
8408 return ERR_INVALID_FIELDID;
8410 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8411 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8412 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8413 mono_field_static_get_value (vtable, f, val);
8414 buffer_add_value (buf, f->type, val, obj->vtable->domain);
8417 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
8421 case CMD_OBJECT_REF_SET_VALUES:
8422 len = decode_int (p, &p, end);
8424 for (i = 0; i < len; ++i) {
8425 f = decode_fieldid (p, &p, end, NULL, &err);
8429 /* Check that the field belongs to the object */
8431 for (k = obj->vtable->klass; k; k = k->parent) {
8432 if (k == f->parent) {
8438 return ERR_INVALID_FIELDID;
8440 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8444 if (mono_class_field_is_special_static (f))
8445 return ERR_INVALID_FIELDID;
8447 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8448 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8450 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8451 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
8456 mono_field_static_set_value (vtable, f, val);
8459 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
8465 case CMD_OBJECT_REF_GET_ADDRESS:
8466 buffer_add_long (buf, (gssize)obj);
8468 case CMD_OBJECT_REF_GET_DOMAIN:
8469 buffer_add_domainid (buf, obj->vtable->domain);
8471 case CMD_OBJECT_REF_GET_INFO:
8472 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8473 buffer_add_domainid (buf, obj->vtable->domain);
8476 return ERR_NOT_IMPLEMENTED;
8483 command_set_to_string (CommandSet command_set)
8485 switch (command_set) {
8488 case CMD_SET_OBJECT_REF:
8489 return "OBJECT_REF";
8490 case CMD_SET_STRING_REF:
8491 return "STRING_REF";
8492 case CMD_SET_THREAD:
8494 case CMD_SET_ARRAY_REF:
8496 case CMD_SET_EVENT_REQUEST:
8497 return "EVENT_REQUEST";
8498 case CMD_SET_STACK_FRAME:
8499 return "STACK_FRAME";
8500 case CMD_SET_APPDOMAIN:
8502 case CMD_SET_ASSEMBLY:
8504 case CMD_SET_METHOD:
8508 case CMD_SET_MODULE:
8518 cmd_to_string (CommandSet set, int command)
8523 case CMD_VM_VERSION:
8525 case CMD_VM_ALL_THREADS:
8526 return "ALL_THREADS";
8527 case CMD_VM_SUSPEND:
8533 case CMD_VM_DISPOSE:
8535 case CMD_VM_INVOKE_METHOD:
8536 return "INVOKE_METHOD";
8537 case CMD_VM_SET_PROTOCOL_VERSION:
8538 return "SET_PROTOCOL_VERSION";
8539 case CMD_VM_ABORT_INVOKE:
8540 return "ABORT_INVOKE";
8541 case CMD_VM_SET_KEEPALIVE:
8542 return "SET_KEEPALIVE";
8555 wait_for_attach (void)
8557 #ifndef DISABLE_SOCKET_TRANSPORT
8558 if (listen_fd == -1) {
8559 DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
8563 /* Block and wait for client connection */
8564 conn_fd = socket_transport_accept (listen_fd);
8565 DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
8566 if (conn_fd == -1) {
8567 DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
8571 g_assert_not_reached ();
8575 disconnected = !transport_handshake ();
8577 DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
8587 * This thread handles communication with the debugger client using a JDWP
8590 static guint32 WINAPI
8591 debugger_thread (void *arg)
8593 int res, len, id, flags, command_set = 0, command = 0;
8594 guint8 header [HEADER_LENGTH];
8595 guint8 *data, *p, *end;
8599 gboolean attach_failed = FALSE;
8601 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
8603 debugger_thread_id = GetCurrentThreadId ();
8605 mono_jit_thread_attach (mono_get_root_domain ());
8607 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
8609 mono_set_is_debugger_attached (TRUE);
8611 if (agent_config.defer) {
8612 if (!wait_for_attach ()) {
8613 DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
8614 attach_failed = TRUE; // Don't abort process when we can't listen
8616 /* Send start event to client */
8617 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
8621 while (!attach_failed) {
8622 res = transport_recv (header, HEADER_LENGTH);
8624 /* This will break if the socket is closed during shutdown too */
8625 if (res != HEADER_LENGTH)
8629 end = header + HEADER_LENGTH;
8631 len = decode_int (p, &p, end);
8632 id = decode_int (p, &p, end);
8633 flags = decode_byte (p, &p, end);
8634 command_set = decode_byte (p, &p, end);
8635 command = decode_byte (p, &p, end);
8637 g_assert (flags == 0);
8640 const char *cmd_str;
8643 cmd_str = cmd_to_string (command_set, command);
8645 sprintf (cmd_num, "%d", command);
8649 DEBUG (1, fprintf (log_file, "[dbg] Received command %s(%s), id=%d.\n", command_set_to_string (command_set), cmd_str, id));
8652 data = g_malloc (len - HEADER_LENGTH);
8653 if (len - HEADER_LENGTH > 0)
8655 res = transport_recv (data, len - HEADER_LENGTH);
8656 if (res != len - HEADER_LENGTH)
8661 end = data + (len - HEADER_LENGTH);
8663 buffer_init (&buf, 128);
8668 /* Process the request */
8669 switch (command_set) {
8671 err = vm_commands (command, id, p, end, &buf);
8672 if (!err && command == CMD_VM_INVOKE_METHOD)
8673 /* Sent after the invoke is complete */
8676 case CMD_SET_EVENT_REQUEST:
8677 err = event_commands (command, p, end, &buf);
8679 case CMD_SET_APPDOMAIN:
8680 err = domain_commands (command, p, end, &buf);
8682 case CMD_SET_ASSEMBLY:
8683 err = assembly_commands (command, p, end, &buf);
8685 case CMD_SET_MODULE:
8686 err = module_commands (command, p, end, &buf);
8689 err = type_commands (command, p, end, &buf);
8691 case CMD_SET_METHOD:
8692 err = method_commands (command, p, end, &buf);
8694 case CMD_SET_THREAD:
8695 err = thread_commands (command, p, end, &buf);
8697 case CMD_SET_STACK_FRAME:
8698 err = frame_commands (command, p, end, &buf);
8700 case CMD_SET_ARRAY_REF:
8701 err = array_commands (command, p, end, &buf);
8703 case CMD_SET_STRING_REF:
8704 err = string_commands (command, p, end, &buf);
8706 case CMD_SET_OBJECT_REF:
8707 err = object_commands (command, p, end, &buf);
8710 err = ERR_NOT_IMPLEMENTED;
8714 send_reply_packet (id, err, &buf);
8719 if (command_set == CMD_SET_VM && command == CMD_VM_DISPOSE)
8723 mono_set_is_debugger_attached (FALSE);
8725 mono_mutex_lock (&debugger_thread_exited_mutex);
8726 debugger_thread_exited = TRUE;
8727 mono_cond_signal (&debugger_thread_exited_cond);
8728 mono_mutex_unlock (&debugger_thread_exited_mutex);
8730 DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
8732 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
8733 DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
8734 start_debugger_thread ();
8740 #else /* DISABLE_DEBUGGER_AGENT */
8743 mono_debugger_agent_parse_options (char *options)
8745 g_error ("This runtime is configured with the debugger agent disabled.");
8749 mono_debugger_agent_init (void)
8754 mono_debugger_agent_breakpoint_hit (void *sigctx)
8759 mono_debugger_agent_single_step_event (void *sigctx)
8764 mono_debugger_agent_free_domain_info (MonoDomain *domain)
8769 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
8775 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
8776 MonoContext *catch_ctx)
8781 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
8786 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
8791 mono_debugger_agent_user_break (void)
8797 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
8802 mono_debugger_agent_debug_log_is_enabled (void)