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/metadata/runtime.h>
76 #include <mono/metadata/threadpool.h>
77 #include <mono/metadata/verify-internals.h>
78 #include <mono/utils/mono-semaphore.h>
79 #include <mono/utils/mono-error-internals.h>
80 #include <mono/utils/mono-stack-unwinding.h>
81 #include <mono/utils/mono-time.h>
82 #include <mono/utils/mono-threads.h>
83 #include "debugger-agent.h"
87 On iOS we can't use System.Environment.Exit () as it will do the wrong
90 #if !defined (TARGET_IOS)
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/utils/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 MonoThreadUnwindState catch_state;
263 * The context which needs to be restored after handling a single step/breakpoint
264 * event. This is the same as the ctx at step/breakpoint site, but includes changes
265 * to caller saved registers done by set_var ().
267 MonoContext restore_ctx;
272 void (*connect) (const char *address);
273 void (*close1) (void);
274 void (*close2) (void);
275 gboolean (*send) (void *buf, int len);
276 int (*recv) (void *buf, int len);
280 * Wire Protocol definitions
283 #define HEADER_LENGTH 11
285 #define MAJOR_VERSION 2
286 #define MINOR_VERSION 24
290 CMD_SET_OBJECT_REF = 9,
291 CMD_SET_STRING_REF = 10,
293 CMD_SET_ARRAY_REF = 13,
294 CMD_SET_EVENT_REQUEST = 15,
295 CMD_SET_STACK_FRAME = 16,
296 CMD_SET_APPDOMAIN = 20,
297 CMD_SET_ASSEMBLY = 21,
305 EVENT_KIND_VM_START = 0,
306 EVENT_KIND_VM_DEATH = 1,
307 EVENT_KIND_THREAD_START = 2,
308 EVENT_KIND_THREAD_DEATH = 3,
309 EVENT_KIND_APPDOMAIN_CREATE = 4,
310 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
311 EVENT_KIND_METHOD_ENTRY = 6,
312 EVENT_KIND_METHOD_EXIT = 7,
313 EVENT_KIND_ASSEMBLY_LOAD = 8,
314 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
315 EVENT_KIND_BREAKPOINT = 10,
316 EVENT_KIND_STEP = 11,
317 EVENT_KIND_TYPE_LOAD = 12,
318 EVENT_KIND_EXCEPTION = 13,
319 EVENT_KIND_KEEPALIVE = 14,
320 EVENT_KIND_USER_BREAK = 15,
321 EVENT_KIND_USER_LOG = 16
325 SUSPEND_POLICY_NONE = 0,
326 SUSPEND_POLICY_EVENT_THREAD = 1,
327 SUSPEND_POLICY_ALL = 2
332 ERR_INVALID_OBJECT = 20,
333 ERR_INVALID_FIELDID = 25,
334 ERR_INVALID_FRAMEID = 30,
335 ERR_NOT_IMPLEMENTED = 100,
336 ERR_NOT_SUSPENDED = 101,
337 ERR_INVALID_ARGUMENT = 102,
339 ERR_NO_INVOCATION = 104,
340 ERR_ABSENT_INFORMATION = 105,
341 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
342 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
347 MOD_KIND_THREAD_ONLY = 3,
348 MOD_KIND_LOCATION_ONLY = 7,
349 MOD_KIND_EXCEPTION_ONLY = 8,
351 MOD_KIND_ASSEMBLY_ONLY = 11,
352 MOD_KIND_SOURCE_FILE_ONLY = 12,
353 MOD_KIND_TYPE_NAME_ONLY = 13
368 STEP_FILTER_NONE = 0,
369 STEP_FILTER_STATIC_CTOR = 1,
370 STEP_FILTER_DEBUGGER_HIDDEN = 2
374 TOKEN_TYPE_STRING = 0,
376 TOKEN_TYPE_FIELD = 2,
377 TOKEN_TYPE_METHOD = 3,
378 TOKEN_TYPE_UNKNOWN = 4
382 VALUE_TYPE_ID_NULL = 0xf0,
383 VALUE_TYPE_ID_TYPE = 0xf1
387 FRAME_FLAG_DEBUGGER_INVOKE = 1,
388 FRAME_FLAG_NATIVE_TRANSITION = 2
392 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
393 INVOKE_FLAG_SINGLE_THREADED = 2
397 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
398 } BindingFlagsExtensions;
402 CMD_VM_ALL_THREADS = 2,
407 CMD_VM_INVOKE_METHOD = 7,
408 CMD_VM_SET_PROTOCOL_VERSION = 8,
409 CMD_VM_ABORT_INVOKE = 9,
410 CMD_VM_SET_KEEPALIVE = 10,
411 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
412 CMD_VM_GET_TYPES = 12,
413 CMD_VM_INVOKE_METHODS = 13
417 CMD_THREAD_GET_FRAME_INFO = 1,
418 CMD_THREAD_GET_NAME = 2,
419 CMD_THREAD_GET_STATE = 3,
420 CMD_THREAD_GET_INFO = 4,
421 CMD_THREAD_GET_ID = 5,
422 CMD_THREAD_GET_TID = 6
426 CMD_EVENT_REQUEST_SET = 1,
427 CMD_EVENT_REQUEST_CLEAR = 2,
428 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
436 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
437 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
438 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
439 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
440 CMD_APPDOMAIN_CREATE_STRING = 5,
441 CMD_APPDOMAIN_GET_CORLIB = 6,
442 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
446 CMD_ASSEMBLY_GET_LOCATION = 1,
447 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
448 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
449 CMD_ASSEMBLY_GET_OBJECT = 4,
450 CMD_ASSEMBLY_GET_TYPE = 5,
451 CMD_ASSEMBLY_GET_NAME = 6
455 CMD_MODULE_GET_INFO = 1,
459 CMD_METHOD_GET_NAME = 1,
460 CMD_METHOD_GET_DECLARING_TYPE = 2,
461 CMD_METHOD_GET_DEBUG_INFO = 3,
462 CMD_METHOD_GET_PARAM_INFO = 4,
463 CMD_METHOD_GET_LOCALS_INFO = 5,
464 CMD_METHOD_GET_INFO = 6,
465 CMD_METHOD_GET_BODY = 7,
466 CMD_METHOD_RESOLVE_TOKEN = 8,
467 CMD_METHOD_GET_CATTRS = 9,
468 CMD_METHOD_MAKE_GENERIC_METHOD = 10
472 CMD_TYPE_GET_INFO = 1,
473 CMD_TYPE_GET_METHODS = 2,
474 CMD_TYPE_GET_FIELDS = 3,
475 CMD_TYPE_GET_VALUES = 4,
476 CMD_TYPE_GET_OBJECT = 5,
477 CMD_TYPE_GET_SOURCE_FILES = 6,
478 CMD_TYPE_SET_VALUES = 7,
479 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
480 CMD_TYPE_GET_PROPERTIES = 9,
481 CMD_TYPE_GET_CATTRS = 10,
482 CMD_TYPE_GET_FIELD_CATTRS = 11,
483 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
484 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
485 CMD_TYPE_GET_VALUES_2 = 14,
486 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
487 CMD_TYPE_GET_INTERFACES = 16,
488 CMD_TYPE_GET_INTERFACE_MAP = 17,
489 CMD_TYPE_IS_INITIALIZED = 18
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 /* The number of times the runtime is suspended */
683 static gint32 suspend_count;
685 static void transport_init (void);
686 static void transport_connect (const char *address);
687 static gboolean transport_handshake (void);
688 static void register_transport (DebuggerTransport *trans);
690 static guint32 WINAPI debugger_thread (void *arg);
692 static void runtime_initialized (MonoProfiler *prof);
694 static void runtime_shutdown (MonoProfiler *prof);
696 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
698 static void thread_end (MonoProfiler *prof, uintptr_t tid);
700 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
702 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
704 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
706 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
708 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
710 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
712 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
714 static void emit_assembly_load (gpointer assembly, gpointer user_data);
716 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
718 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
720 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
722 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
724 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
726 static void start_single_stepping (void);
728 static void stop_single_stepping (void);
730 static void suspend_current (void);
732 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
734 static void clear_types_for_assembly (MonoAssembly *assembly);
736 static void clear_breakpoints_for_domain (MonoDomain *domain);
738 static void process_profiler_event (EventKind event, gpointer arg);
740 /* Submodule init/cleanup */
741 static void breakpoints_init (void);
742 static void breakpoints_cleanup (void);
744 static void objrefs_init (void);
745 static void objrefs_cleanup (void);
747 static void ids_init (void);
748 static void ids_cleanup (void);
750 static void suspend_init (void);
752 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch);
753 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
754 static void ss_destroy (SingleStepReq *req);
756 static void start_debugger_thread (void);
757 static void stop_debugger_thread (void);
759 static void finish_agent_init (gboolean on_startup);
761 static void process_profiler_event (EventKind event, gpointer arg);
763 static void invalidate_frames (DebuggerTlsData *tls);
765 #ifndef DISABLE_SOCKET_TRANSPORT
767 register_socket_transport (void);
771 parse_address (char *address, char **host, int *port)
773 char *pos = strchr (address, ':');
775 if (pos == NULL || pos == address)
778 *host = g_malloc (pos - address + 1);
779 strncpy (*host, address, pos - address);
780 (*host) [pos - address] = '\0';
782 *port = atoi (pos + 1);
790 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
791 fprintf (stderr, "Available options:\n");
792 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
793 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
794 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
795 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
796 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
797 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
798 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
799 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
800 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
804 parse_flag (const char *option, char *flag)
806 if (!strcmp (flag, "y"))
808 else if (!strcmp (flag, "n"))
811 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
818 mono_debugger_agent_parse_options (char *options)
825 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
826 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
830 extra = getenv ("MONO_SDB_ENV_OPTIONS");
832 options = g_strdup_printf ("%s,%s", options, extra);
834 agent_config.enabled = TRUE;
835 agent_config.suspend = TRUE;
836 agent_config.server = FALSE;
837 agent_config.defer = FALSE;
838 agent_config.address = NULL;
840 args = g_strsplit (options, ",", -1);
841 for (ptr = args; ptr && *ptr; ptr ++) {
844 if (strncmp (arg, "transport=", 10) == 0) {
845 agent_config.transport = g_strdup (arg + 10);
846 } else if (strncmp (arg, "address=", 8) == 0) {
847 agent_config.address = g_strdup (arg + 8);
848 } else if (strncmp (arg, "loglevel=", 9) == 0) {
849 agent_config.log_level = atoi (arg + 9);
850 } else if (strncmp (arg, "logfile=", 8) == 0) {
851 agent_config.log_file = g_strdup (arg + 8);
852 } else if (strncmp (arg, "suspend=", 8) == 0) {
853 agent_config.suspend = parse_flag ("suspend", arg + 8);
854 } else if (strncmp (arg, "server=", 7) == 0) {
855 agent_config.server = parse_flag ("server", arg + 7);
856 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
857 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
858 } else if (strncmp (arg, "onthrow=", 8) == 0) {
859 /* We support multiple onthrow= options */
860 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
861 } else if (strncmp (arg, "onthrow", 7) == 0) {
862 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
863 } else if (strncmp (arg, "help", 4) == 0) {
866 } else if (strncmp (arg, "timeout=", 8) == 0) {
867 agent_config.timeout = atoi (arg + 8);
868 } else if (strncmp (arg, "launch=", 7) == 0) {
869 agent_config.launch = g_strdup (arg + 7);
870 } else if (strncmp (arg, "embedding=", 10) == 0) {
871 agent_config.embedding = atoi (arg + 10) == 1;
872 } else if (strncmp (arg, "keepalive=", 10) == 0) {
873 agent_config.keepalive = atoi (arg + 10);
880 if (agent_config.server && !agent_config.suspend) {
881 /* Waiting for deferred attachment */
882 agent_config.defer = TRUE;
883 if (agent_config.address == NULL) {
884 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (GetCurrentProcessId () % 1000));
888 //agent_config.log_level = 0;
890 if (agent_config.transport == NULL) {
891 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
895 if (agent_config.address == NULL && !agent_config.server) {
896 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
901 if (!strcmp (agent_config.transport, "dt_socket")) {
902 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
903 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
910 mono_debugger_agent_init (void)
912 if (!agent_config.enabled)
917 /* Need to know whenever a thread has acquired the loader mutex */
918 mono_loader_lock_track_ownership (TRUE);
920 event_requests = g_ptr_array_new ();
922 mono_mutex_init (&debugger_thread_exited_mutex);
923 mono_cond_init (&debugger_thread_exited_cond, NULL);
925 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
926 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
927 mono_profiler_install_runtime_initialized (runtime_initialized);
928 mono_profiler_install_appdomain (NULL, appdomain_load, NULL, appdomain_unload);
929 mono_profiler_install_thread (thread_startup, thread_end);
930 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
931 mono_profiler_install_jit_end (jit_end);
932 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
934 mono_native_tls_alloc (&debugger_tls_id, NULL);
936 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
937 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls);
939 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
940 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread);
942 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
943 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj);
945 pending_assembly_loads = g_ptr_array_new ();
946 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
948 log_level = agent_config.log_level;
950 embedding = agent_config.embedding;
953 if (agent_config.log_file) {
954 log_file = fopen (agent_config.log_file, "w+");
956 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
968 mini_get_debug_options ()->gen_seq_points = TRUE;
970 * This is needed because currently we don't handle liveness info.
972 mini_get_debug_options ()->mdb_optimizations = TRUE;
974 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
975 /* This is needed because we can't set local variables in registers yet */
976 mono_disable_optimizations (MONO_OPT_LINEARS);
980 * The stack walk done from thread_interrupt () needs to be signal safe, but it
981 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
982 * safe (#3411). So load AOT info eagerly when the debugger is running as a
985 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
987 if (!agent_config.onuncaught && !agent_config.onthrow)
988 finish_agent_init (TRUE);
994 * Finish the initialization of the agent. This involves connecting the transport
995 * and starting the agent thread. This is either done at startup, or
996 * in response to some event like an unhandled exception.
999 finish_agent_init (gboolean on_startup)
1003 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
1006 if (agent_config.launch) {
1009 // FIXME: Generated address
1010 // FIXME: Races with transport_connect ()
1012 argv [0] = agent_config.launch;
1013 argv [1] = agent_config.transport;
1014 argv [2] = agent_config.address;
1017 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1019 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1024 transport_connect (agent_config.address);
1027 /* Do some which is usually done after sending the VMStart () event */
1028 vm_start_event_sent = TRUE;
1029 start_debugger_thread ();
1034 mono_debugger_agent_cleanup (void)
1039 stop_debugger_thread ();
1041 breakpoints_cleanup ();
1045 mono_mutex_destroy (&debugger_thread_exited_mutex);
1046 mono_cond_destroy (&debugger_thread_exited_cond);
1053 #ifndef DISABLE_SOCKET_TRANSPORT
1058 * recv() + handle incomplete reads and EINTR
1061 socket_transport_recv (void *buf, int len)
1067 static gint32 last_keepalive;
1072 res = recv (fd, (char *) buf + total, len - total, flags);
1075 if (agent_config.keepalive) {
1076 gboolean need_keepalive = FALSE;
1077 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1078 need_keepalive = TRUE;
1079 } else if (res == -1) {
1080 /* This could happen if recv () is interrupted repeatedly */
1081 msecs = mono_msec_ticks ();
1082 if (msecs - last_keepalive >= agent_config.keepalive) {
1083 need_keepalive = TRUE;
1084 last_keepalive = msecs;
1087 if (need_keepalive) {
1088 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1092 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1097 #define HAVE_GETADDRINFO 1
1101 set_keepalive (void)
1106 if (!agent_config.keepalive || !conn_fd)
1109 tv.tv_sec = agent_config.keepalive / 1000;
1110 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1112 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1113 g_assert (result >= 0);
1117 socket_transport_accept (int socket_fd)
1119 conn_fd = accept (socket_fd, NULL, NULL);
1120 if (conn_fd == -1) {
1121 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1123 DEBUG (1, fprintf (log_file, "Accepted connection from client, connection fd=%d.\n", conn_fd));
1130 socket_transport_send (void *data, int len)
1135 res = send (conn_fd, data, len, 0);
1136 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1144 * socket_transport_connect:
1146 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1149 socket_transport_connect (const char *address)
1151 #ifdef HAVE_GETADDRINFO
1152 struct addrinfo hints;
1153 struct addrinfo *result, *rp;
1155 struct hostent *result;
1157 int sfd = -1, s, res;
1158 char port_string [128];
1162 if (agent_config.address) {
1163 res = parse_address (agent_config.address, &host, &port);
1164 g_assert (res == 0);
1174 sprintf (port_string, "%d", port);
1176 mono_network_init ();
1178 /* Obtain address(es) matching host/port */
1179 #ifdef HAVE_GETADDRINFO
1180 memset (&hints, 0, sizeof (struct addrinfo));
1181 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
1182 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
1184 hints.ai_protocol = 0; /* Any protocol */
1186 s = getaddrinfo (host, port_string, &hints, &result);
1188 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %s\n", host, port, gai_strerror (s));
1192 /* The PS3 doesn't even have _r or hstrerror () */
1193 result = gethostbyname (host);
1195 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, h_errno);
1200 if (agent_config.server) {
1201 #ifdef HAVE_GETADDRINFO
1202 /* Wait for a connection */
1204 struct sockaddr_in addr;
1207 /* No address, generate one */
1208 sfd = socket (AF_INET, SOCK_STREAM, 0);
1211 /* This will bind the socket to a random port */
1212 res = listen (sfd, 16);
1214 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1219 addrlen = sizeof (addr);
1220 memset (&addr, 0, sizeof (addr));
1221 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1222 g_assert (res == 0);
1224 host = (char*)"127.0.0.1";
1225 port = ntohs (addr.sin_port);
1227 /* Emit the address to stdout */
1228 /* FIXME: Should print another interface, not localhost */
1229 printf ("%s:%d\n", host, port);
1231 /* Listen on the provided address */
1232 for (rp = result; rp != NULL; rp = rp->ai_next) {
1235 sfd = socket (rp->ai_family, rp->ai_socktype,
1240 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1243 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
1247 res = listen (sfd, 16);
1256 * this function is not present on win2000 which we still support, and the
1257 * workaround described here:
1258 * http://msdn.microsoft.com/en-us/library/ms737931(VS.85).aspx
1259 * only works with MSVC.
1261 #ifdef HAVE_GETADDRINFO
1262 freeaddrinfo (result);
1267 if (agent_config.defer)
1270 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
1272 if (agent_config.timeout) {
1277 tv.tv_usec = agent_config.timeout * 1000;
1279 FD_SET (sfd, &readfds);
1280 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1282 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1287 conn_fd = socket_transport_accept (sfd);
1291 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
1294 #endif /* HAVE_GETADDRINFO */
1296 /* Connect to the specified address */
1297 #ifdef HAVE_GETADDRINFO
1298 /* FIXME: Respect the timeout */
1299 for (rp = result; rp != NULL; rp = rp->ai_next) {
1300 sfd = socket (rp->ai_family, rp->ai_socktype,
1305 if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
1306 break; /* Success */
1312 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1316 sfd = socket (result->h_addrtype, SOCK_STREAM, 0);
1318 g_assert_not_reached ();
1319 res = connect (sfd, (void*)result->h_addr_list [0], result->h_length);
1321 g_assert_not_reached ();
1327 /* See the comment above */
1328 #ifdef HAVE_GETADDRINFO
1329 freeaddrinfo (result);
1334 if (!transport_handshake ())
1339 socket_transport_close1 (void)
1341 /* This will interrupt the agent thread */
1342 /* Close the read part only so it can still send back replies */
1343 /* Also shut down the connection listener so that we can exit normally */
1345 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1346 shutdown (conn_fd, SD_BOTH);
1347 shutdown (listen_fd, SD_BOTH);
1348 closesocket (listen_fd);
1350 shutdown (conn_fd, SHUT_RD);
1351 shutdown (listen_fd, SHUT_RDWR);
1357 socket_transport_close2 (void)
1360 shutdown (conn_fd, SD_BOTH);
1362 shutdown (conn_fd, SHUT_RDWR);
1367 register_socket_transport (void)
1369 DebuggerTransport trans;
1371 trans.name = "dt_socket";
1372 trans.connect = socket_transport_connect;
1373 trans.close1 = socket_transport_close1;
1374 trans.close2 = socket_transport_close2;
1375 trans.send = socket_transport_send;
1376 trans.recv = socket_transport_recv;
1378 register_transport (&trans);
1381 #endif /* DISABLE_SOCKET_TRANSPORT */
1387 #define MAX_TRANSPORTS 16
1389 static DebuggerTransport *transport;
1391 static DebuggerTransport transports [MAX_TRANSPORTS];
1392 static int ntransports;
1395 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1398 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1400 register_transport (trans);
1404 register_transport (DebuggerTransport *trans)
1406 g_assert (ntransports < MAX_TRANSPORTS);
1408 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1413 transport_init (void)
1417 #ifndef DISABLE_SOCKET_TRANSPORT
1418 register_socket_transport ();
1421 for (i = 0; i < ntransports; ++i) {
1422 if (!strcmp (agent_config.transport, transports [i].name))
1425 if (i == ntransports) {
1426 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1427 for (i = 0; i < ntransports; ++i)
1428 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1429 fprintf (stderr, "\n");
1432 transport = &transports [i];
1436 transport_connect (const char *address)
1438 transport->connect (address);
1442 transport_close1 (void)
1444 transport->close1 ();
1448 transport_close2 (void)
1450 transport->close2 ();
1454 transport_send (void *buf, int len)
1456 return transport->send (buf, len);
1460 transport_recv (void *buf, int len)
1462 return transport->recv (buf, len);
1466 mono_debugger_agent_transport_handshake (void)
1468 return transport_handshake ();
1472 transport_handshake (void)
1474 char handshake_msg [128];
1478 disconnected = TRUE;
1480 /* Write handshake message */
1481 sprintf (handshake_msg, "DWP-Handshake");
1483 res = transport_send (handshake_msg, strlen (handshake_msg));
1484 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1485 g_assert (res != -1);
1488 res = transport_recv (buf, strlen (handshake_msg));
1489 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg) != 0))) {
1490 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1495 * To support older clients, the client sends its protocol version after connecting
1496 * using a command. Until that is received, default to our protocol version.
1498 major_version = MAJOR_VERSION;
1499 minor_version = MINOR_VERSION;
1500 protocol_version_set = FALSE;
1502 #ifndef DISABLE_SOCKET_TRANSPORT
1503 // FIXME: Move this somewhere else
1505 * Set TCP_NODELAY on the socket so the client receives events/command
1506 * results immediately.
1510 int result = setsockopt (conn_fd,
1515 g_assert (result >= 0);
1521 disconnected = FALSE;
1526 stop_debugger_thread (void)
1531 transport_close1 ();
1534 * Wait for the thread to exit.
1536 * If we continue with the shutdown without waiting for it, then the client might
1537 * not receive an answer to its last command like a resume.
1538 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
1541 //WaitForSingleObject (debugger_thread_handle, INFINITE);
1542 if (GetCurrentThreadId () != debugger_thread_id) {
1544 mono_mutex_lock (&debugger_thread_exited_mutex);
1545 if (!debugger_thread_exited) {
1547 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
1548 mono_mutex_unlock (&debugger_thread_exited_mutex);
1550 mono_mutex_lock (&debugger_thread_exited_mutex);
1553 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1556 mono_mutex_unlock (&debugger_thread_exited_mutex);
1557 } while (!debugger_thread_exited);
1560 transport_close2 ();
1564 start_debugger_thread (void)
1568 debugger_thread_handle = mono_create_thread (NULL, 0, debugger_thread, NULL, 0, &tid);
1569 g_assert (debugger_thread_handle);
1573 * Functions to decode protocol data
1577 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1580 g_assert (*endbuf <= limit);
1585 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1588 g_assert (*endbuf <= limit);
1590 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1593 static inline gint64
1594 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1596 guint32 high = decode_int (buf, &buf, limit);
1597 guint32 low = decode_int (buf, &buf, limit);
1601 return ((((guint64)high) << 32) | ((guint64)low));
1605 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1607 return decode_int (buf, endbuf, limit);
1611 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1613 int len = decode_int (buf, &buf, limit);
1621 s = g_malloc (len + 1);
1624 memcpy (s, buf, len);
1633 * Functions to encode protocol data
1637 guint8 *buf, *p, *end;
1641 buffer_init (Buffer *buf, int size)
1643 buf->buf = g_malloc (size);
1645 buf->end = buf->buf + size;
1649 buffer_make_room (Buffer *buf, int size)
1651 if (buf->end - buf->p < size) {
1652 int new_size = buf->end - buf->buf + size + 32;
1653 guint8 *p = g_realloc (buf->buf, new_size);
1654 size = buf->p - buf->buf;
1657 buf->end = buf->buf + new_size;
1662 buffer_add_byte (Buffer *buf, guint8 val)
1664 buffer_make_room (buf, 1);
1670 buffer_add_short (Buffer *buf, guint32 val)
1672 buffer_make_room (buf, 2);
1673 buf->p [0] = (val >> 8) & 0xff;
1674 buf->p [1] = (val >> 0) & 0xff;
1679 buffer_add_int (Buffer *buf, guint32 val)
1681 buffer_make_room (buf, 4);
1682 buf->p [0] = (val >> 24) & 0xff;
1683 buf->p [1] = (val >> 16) & 0xff;
1684 buf->p [2] = (val >> 8) & 0xff;
1685 buf->p [3] = (val >> 0) & 0xff;
1690 buffer_add_long (Buffer *buf, guint64 l)
1692 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1693 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1697 buffer_add_id (Buffer *buf, int id)
1699 buffer_add_int (buf, (guint64)id);
1703 buffer_add_data (Buffer *buf, guint8 *data, int len)
1705 buffer_make_room (buf, len);
1706 memcpy (buf->p, data, len);
1711 buffer_add_string (Buffer *buf, const char *str)
1716 buffer_add_int (buf, 0);
1719 buffer_add_int (buf, len);
1720 buffer_add_data (buf, (guint8*)str, len);
1725 buffer_free (Buffer *buf)
1731 send_packet (int command_set, int command, Buffer *data)
1737 id = InterlockedIncrement (&packet_id);
1739 len = data->p - data->buf + 11;
1740 buffer_init (&buf, len);
1741 buffer_add_int (&buf, len);
1742 buffer_add_int (&buf, id);
1743 buffer_add_byte (&buf, 0); /* flags */
1744 buffer_add_byte (&buf, command_set);
1745 buffer_add_byte (&buf, command);
1746 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1748 res = transport_send (buf.buf, len);
1756 send_reply_packet (int id, int error, Buffer *data)
1762 len = data->p - data->buf + 11;
1763 buffer_init (&buf, len);
1764 buffer_add_int (&buf, len);
1765 buffer_add_int (&buf, id);
1766 buffer_add_byte (&buf, 0x80); /* flags */
1767 buffer_add_byte (&buf, (error >> 8) & 0xff);
1768 buffer_add_byte (&buf, error);
1769 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1771 res = transport_send (buf.buf, len);
1783 * Represents an object accessible by the debugger client.
1786 /* Unique id used in the wire protocol to refer to objects */
1789 * A weakref gc handle pointing to the object. The gc handle is used to
1790 * detect if the object was garbage collected.
1795 /* Maps objid -> ObjRef */
1796 static GHashTable *objrefs;
1799 free_objref (gpointer value)
1803 mono_gchandle_free (o->handle);
1811 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1815 objrefs_cleanup (void)
1817 g_hash_table_destroy (objrefs);
1821 static GHashTable *obj_to_objref;
1822 static MonoGHashTable *suspended_objs;
1825 * Return an ObjRef for OBJ.
1828 get_objref (MonoObject *obj)
1831 GSList *reflist = NULL, *l;
1837 mono_loader_lock ();
1839 if (!obj_to_objref) {
1840 obj_to_objref = g_hash_table_new (NULL, NULL);
1841 suspended_objs = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
1842 MONO_GC_REGISTER_ROOT_FIXED (suspended_objs);
1845 if (suspend_count) {
1847 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1849 mono_g_hash_table_insert (suspended_objs, obj, NULL);
1852 /* FIXME: The tables can grow indefinitely */
1854 if (mono_gc_is_moving ()) {
1856 * Objects can move, so use a hash table mapping hash codes to lists of
1857 * ObjRef structures.
1859 hash = mono_object_hash (obj);
1861 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1862 for (l = reflist; l; l = l->next) {
1864 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1865 mono_loader_unlock ();
1870 /* Use a hash table with masked pointers to internalize object references */
1871 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1872 /* ref might refer to a different object with the same addr which was GCd */
1873 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1874 mono_loader_unlock ();
1879 ref = g_new0 (ObjRef, 1);
1880 ref->id = InterlockedIncrement (&objref_id);
1881 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1883 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
1885 if (mono_gc_is_moving ()) {
1886 reflist = g_slist_append (reflist, ref);
1887 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
1889 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
1892 mono_loader_unlock ();
1898 true_pred (gpointer key, gpointer value, gpointer user_data)
1904 clear_suspended_objs (void)
1906 mono_loader_lock ();
1907 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
1908 mono_loader_unlock ();
1912 get_objid (MonoObject *obj)
1914 return get_objref (obj)->id;
1918 * Set OBJ to the object identified by OBJID.
1919 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
1923 get_object_allow_null (int objid, MonoObject **obj)
1933 return ERR_INVALID_OBJECT;
1935 mono_loader_lock ();
1937 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
1940 *obj = mono_gchandle_get_target (ref->handle);
1941 mono_loader_unlock ();
1943 return ERR_INVALID_OBJECT;
1946 mono_loader_unlock ();
1947 return ERR_INVALID_OBJECT;
1952 get_object (int objid, MonoObject **obj)
1954 int err = get_object_allow_null (objid, obj);
1959 return ERR_INVALID_OBJECT;
1964 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
1966 return decode_id (buf, endbuf, limit);
1970 buffer_add_objid (Buffer *buf, MonoObject *o)
1972 buffer_add_id (buf, get_objid (o));
1991 * Represents a runtime structure accessible to the debugger client
1994 /* Unique id used in the wire protocol */
1996 /* Domain of the runtime structure, NULL if the domain was unloaded */
2003 MonoAssembly *assembly;
2004 MonoClassField *field;
2006 MonoProperty *property;
2011 /* Maps runtime structure -> Id */
2012 GHashTable *val_to_id [ID_NUM];
2013 /* Classes whose class load event has been sent */
2014 GHashTable *loaded_classes;
2015 /* Maps MonoClass->GPtrArray of file names */
2016 GHashTable *source_files;
2017 /* Maps source file basename -> GSList of classes */
2018 GHashTable *source_file_to_class;
2019 /* Same with ignore-case */
2020 GHashTable *source_file_to_class_ignorecase;
2024 static GPtrArray *ids [ID_NUM];
2031 for (i = 0; i < ID_NUM; ++i)
2032 ids [i] = g_ptr_array_new ();
2040 for (i = 0; i < ID_NUM; ++i) {
2042 for (j = 0; j < ids [i]->len; ++j)
2043 g_free (g_ptr_array_index (ids [i], j));
2044 g_ptr_array_free (ids [i], TRUE);
2051 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2053 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
2055 GHashTableIter iter;
2056 GPtrArray *file_names;
2061 for (i = 0; i < ID_NUM; ++i)
2062 if (info->val_to_id [i])
2063 g_hash_table_destroy (info->val_to_id [i]);
2064 g_hash_table_destroy (info->loaded_classes);
2066 g_hash_table_iter_init (&iter, info->source_files);
2067 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2068 for (i = 0; i < file_names->len; ++i)
2069 g_free (g_ptr_array_index (file_names, i));
2070 g_ptr_array_free (file_names, TRUE);
2073 g_hash_table_iter_init (&iter, info->source_file_to_class);
2074 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2079 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2080 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2088 domain_jit_info (domain)->agent_info = NULL;
2090 /* Clear ids referencing structures in the domain */
2091 for (i = 0; i < ID_NUM; ++i) {
2093 for (j = 0; j < ids [i]->len; ++j) {
2094 Id *id = g_ptr_array_index (ids [i], j);
2095 if (id->domain == domain)
2101 mono_loader_lock ();
2102 g_hash_table_remove (domains, domain);
2103 mono_loader_unlock ();
2106 static AgentDomainInfo*
2107 get_agent_domain_info (MonoDomain *domain)
2109 AgentDomainInfo *info = NULL;
2111 mono_domain_lock (domain);
2113 info = domain_jit_info (domain)->agent_info;
2115 info = domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
2116 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2117 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2118 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2119 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2122 mono_domain_unlock (domain);
2128 get_id (MonoDomain *domain, IdType type, gpointer val)
2131 AgentDomainInfo *info;
2136 mono_loader_lock ();
2138 mono_domain_lock (domain);
2140 info = get_agent_domain_info (domain);
2142 if (info->val_to_id [type] == NULL)
2143 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2145 id = g_hash_table_lookup (info->val_to_id [type], val);
2147 mono_domain_unlock (domain);
2148 mono_loader_unlock ();
2152 id = g_new0 (Id, 1);
2154 id->id = ids [type]->len + 1;
2155 id->domain = domain;
2158 g_hash_table_insert (info->val_to_id [type], val, id);
2160 mono_domain_unlock (domain);
2162 g_ptr_array_add (ids [type], id);
2164 mono_loader_unlock ();
2169 static inline gpointer
2170 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
2174 int id = decode_id (buf, endbuf, limit);
2183 // FIXME: error handling
2184 mono_loader_lock ();
2185 g_assert (id > 0 && id <= ids [type]->len);
2187 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2188 mono_loader_unlock ();
2190 if (res->domain == NULL) {
2191 *err = ERR_UNLOADED;
2196 *domain = res->domain;
2198 return res->data.val;
2202 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2204 buffer_add_id (buf, get_id (domain, type, val));
2207 static inline MonoClass*
2208 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2210 return decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2213 static inline MonoAssembly*
2214 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2216 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2219 static inline MonoImage*
2220 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2222 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2225 static inline MonoMethod*
2226 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2228 return decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2231 static inline MonoClassField*
2232 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2234 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2237 static inline MonoDomain*
2238 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2240 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2243 static inline MonoProperty*
2244 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2246 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2250 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2252 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2256 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2258 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2262 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2264 buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2268 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2270 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2274 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2276 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2280 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2282 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2286 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2288 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2291 static void invoke_method (void);
2298 * save_thread_context:
2300 * Set CTX as the current threads context which is used for computing stack traces.
2301 * This function is signal-safe.
2304 save_thread_context (MonoContext *ctx)
2306 DebuggerTlsData *tls;
2308 tls = mono_native_tls_get_value (debugger_tls_id);
2312 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2314 mono_thread_state_init_from_current (&tls->context);
2317 /* Number of threads suspended */
2319 * If this is equal to the size of thread_to_tls, the runtime is considered
2322 static gint32 threads_suspend_count;
2324 static mono_mutex_t suspend_mutex;
2326 /* Cond variable used to wait for suspend_count becoming 0 */
2327 static mono_cond_t suspend_cond;
2329 /* Semaphore used to wait for a thread becoming suspended */
2330 static MonoSemType suspend_sem;
2335 mono_mutex_init (&suspend_mutex);
2336 mono_cond_init (&suspend_cond, NULL);
2337 MONO_SEM_INIT (&suspend_sem, 0);
2342 StackFrameInfo last_frame;
2343 gboolean last_frame_set;
2346 } GetLastFrameUserData;
2349 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2351 GetLastFrameUserData *data = user_data;
2353 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
2356 if (!data->last_frame_set) {
2357 /* Store the last frame */
2358 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2359 data->last_frame_set = TRUE;
2362 /* Store the context/lmf for the frame above the last frame */
2363 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2364 data->lmf = info->lmf;
2372 * Process interruption of a thread. If SIGCTX is set, process the current thread. If
2373 * INFO is set, process the thread described by INFO.
2374 * This should be signal safe.
2377 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, void *sigctx, MonoJitInfo *ji)
2381 MonoNativeThreadId tid;
2384 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2385 * guarantee the signal handler will be called that many times. Instead of tracking
2386 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2387 * has been requested that hasn't been handled yet, otherwise we can have threads
2388 * refuse to die when VM_EXIT is called
2390 #if defined(__APPLE__)
2391 if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
2395 * We use interrupt_count to determine whenever this interrupt should be processed
2396 * by us or the normal interrupt processing code in the signal handler.
2397 * There is no race here with notify_thread (), since the signal is sent after
2398 * incrementing interrupt_count.
2400 if (tls->interrupt_count == 0)
2403 InterlockedDecrement (&tls->interrupt_count);
2407 ip = mono_arch_ip_from_context (sigctx);
2409 ip = MONO_CONTEXT_GET_IP (&info->suspend_state.ctx);
2414 tid = mono_thread_info_get_tid (info);
2416 tid = (MonoNativeThreadId)GetCurrentThreadId ();
2418 // FIXME: Races when the thread leaves managed code before hitting a single step
2422 /* Running managed code, will be suspended by the single step code */
2423 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, ji->method->name, ip));
2427 * Running native code, will be suspended when it returns to/enters
2428 * managed code. Treat it as already suspended.
2429 * This might interrupt the code in process_single_step_inner (), we use the
2430 * tls->suspending flag to avoid races when that happens.
2432 if (!tls->suspended && !tls->suspending) {
2434 GetLastFrameUserData data;
2436 // FIXME: printf is not signal safe, but this is only used during
2437 // debugger debugging
2439 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip));
2440 //save_thread_context (&ctx);
2443 /* Already terminated */
2446 tls->context.valid = FALSE;
2449 * We are in a difficult position: we want to be able to provide stack
2450 * traces for this thread, but we can't use the current ctx+lmf, since
2451 * the thread is still running, so it might return to managed code,
2452 * making these invalid.
2453 * So we start a stack walk and save the first frame, along with the
2454 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2455 * suspended when it returns to managed code, so the parent's ctx should
2458 data.last_frame_set = FALSE;
2460 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
2462 * Don't pass MONO_UNWIND_ACTUAL_METHOD, its not signal safe, and
2463 * get_last_frame () doesn't need it, the last frame cannot be a ginst
2464 * since we are not in a JITted method.
2466 mono_walk_stack_with_ctx (get_last_frame, &ctx, MONO_UNWIND_NONE, &data);
2468 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, &info->suspend_state, MONO_UNWIND_SIGNAL_SAFE, &data);
2470 if (data.last_frame_set) {
2471 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2472 res = mono_thread_state_init_from_monoctx (&tls->async_state, &ctx);
2474 mono_thread_state_init_from_monoctx (&tls->context, &ctx);
2477 memcpy (&tls->async_state.ctx, &data.ctx, sizeof (MonoContext));
2478 tls->async_state.unwind_data [MONO_UNWIND_DATA_LMF] = data.lmf;
2479 tls->async_state.unwind_data [MONO_UNWIND_DATA_JIT_TLS] = tls->thread->jit_data;
2481 /* No managed frames */
2482 tls->async_state.valid = FALSE;
2484 mono_memory_barrier ();
2486 tls->suspended = TRUE;
2487 MONO_SEM_POST (&suspend_sem);
2494 * mono_debugger_agent_thread_interrupt:
2496 * Called by the abort signal handler.
2497 * Should be signal safe.
2500 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
2502 DebuggerTlsData *tls;
2507 tls = mono_native_tls_get_value (debugger_tls_id);
2509 DEBUG (1, fprintf (log_file, "[%p] Received interrupt with no TLS, continuing.\n", (gpointer)GetCurrentThreadId ()));
2513 return thread_interrupt (tls, NULL, sigctx, ji);
2517 static void CALLBACK notify_thread_apc (ULONG_PTR param)
2520 mono_debugger_agent_thread_interrupt (NULL, NULL);
2522 #endif /* HOST_WIN32 */
2525 * reset_native_thread_suspend_state:
2527 * Reset the suspended flag and state on native threads
2530 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2532 DebuggerTlsData *tls = value;
2534 if (!tls->really_suspended && tls->suspended) {
2535 tls->suspended = FALSE;
2537 * The thread might still be running if it was executing native code, so the state won't be invalided by
2538 * suspend_current ().
2540 tls->context.valid = FALSE;
2541 tls->async_state.valid = FALSE;
2542 invalidate_frames (tls);
2549 * Notify a thread that it needs to suspend.
2552 notify_thread (gpointer key, gpointer value, gpointer user_data)
2554 MonoInternalThread *thread = key;
2555 DebuggerTlsData *tls = value;
2556 gsize tid = thread->tid;
2559 if (GetCurrentThreadId () == tid || tls->terminated)
2562 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2565 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2566 * guarantee the signal handler will be called that many times. Instead of tracking
2567 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2568 * has been requested that hasn't been handled yet, otherwise we can have threads
2569 * refuse to die when VM_EXIT is called
2571 #if defined(__APPLE__)
2572 if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
2576 * Maybe we could use the normal interrupt infrastructure, but that does a lot
2577 * of things like breaking waits etc. which we don't want.
2579 InterlockedIncrement (&tls->interrupt_count);
2582 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2584 QueueUserAPC (notify_thread_apc, thread->handle, NULL);
2586 if (mono_thread_info_new_interrupt_enabled ()) {
2587 MonoThreadInfo *info;
2590 info = mono_thread_info_safe_suspend_sync ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE);
2592 DEBUG(1, fprintf (log_file, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2594 * Attached thread which died without detaching.
2596 tls->terminated = TRUE;
2598 ji = mono_jit_info_table_find (info->suspend_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], MONO_CONTEXT_GET_IP (&info->suspend_state.ctx));
2600 thread_interrupt (tls, info, NULL, ji);
2602 mono_thread_info_resume (mono_thread_info_get_tid (info));
2605 res = mono_thread_kill (thread, mono_thread_get_abort_signal ());
2607 DEBUG(1, fprintf (log_file, "[%p] mono_thread_kill () failed for %p: %d...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid, res));
2609 * Attached thread which died without detaching.
2611 tls->terminated = TRUE;
2618 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2620 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2623 if (mono_loader_lock_is_owned_by_self ()) {
2625 * Shortcut for the check in suspend_current (). This speeds up processing
2626 * when executing long running code inside the loader lock, i.e. assembly load
2632 if (debugger_thread_id == GetCurrentThreadId ())
2635 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2636 if (suspend_count - tls->resume_count > 0)
2637 tls->suspending = TRUE;
2639 DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2641 if (suspend_count - tls->resume_count == 0) {
2643 * We are executing a single threaded invoke but the single step for
2644 * suspending is still active.
2645 * FIXME: This slows down single threaded invokes.
2647 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
2651 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2653 /* Can't suspend in these methods */
2654 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
2657 save_thread_context (ctx);
2665 * Increase the suspend count of the VM. While the suspend count is greater
2666 * than 0, runtime threads are suspended at certain points during execution.
2671 mono_loader_lock ();
2673 mono_mutex_lock (&suspend_mutex);
2677 DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
2679 if (suspend_count == 1) {
2680 // FIXME: Is it safe to call this inside the lock ?
2681 start_single_stepping ();
2682 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2685 mono_mutex_unlock (&suspend_mutex);
2687 if (suspend_count == 1)
2689 * Suspend creation of new threadpool threads, since they cannot run
2691 mono_thread_pool_suspend ();
2693 mono_loader_unlock ();
2699 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2707 g_assert (debugger_thread_id == GetCurrentThreadId ());
2709 mono_loader_lock ();
2711 mono_mutex_lock (&suspend_mutex);
2713 g_assert (suspend_count > 0);
2716 DEBUG(1, fprintf (log_file, "[%p] Resuming vm, suspend count=%d...\n", (gpointer)GetCurrentThreadId (), suspend_count));
2718 if (suspend_count == 0) {
2719 // FIXME: Is it safe to call this inside the lock ?
2720 stop_single_stepping ();
2721 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2724 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2725 err = mono_cond_broadcast (&suspend_cond);
2726 g_assert (err == 0);
2728 mono_mutex_unlock (&suspend_mutex);
2729 //g_assert (err == 0);
2731 if (suspend_count == 0)
2732 mono_thread_pool_resume ();
2734 mono_loader_unlock ();
2740 * Resume just one thread.
2743 resume_thread (MonoInternalThread *thread)
2746 DebuggerTlsData *tls;
2748 g_assert (debugger_thread_id == GetCurrentThreadId ());
2750 mono_loader_lock ();
2752 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2755 mono_mutex_lock (&suspend_mutex);
2757 g_assert (suspend_count > 0);
2759 DEBUG(1, fprintf (log_file, "[%p] Resuming thread...\n", (gpointer)(gssize)thread->tid));
2761 tls->resume_count += suspend_count;
2764 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2765 * but only the one whose resume_count field is > 0 will be resumed.
2767 err = mono_cond_broadcast (&suspend_cond);
2768 g_assert (err == 0);
2770 mono_mutex_unlock (&suspend_mutex);
2771 //g_assert (err == 0);
2773 mono_loader_unlock ();
2777 invalidate_frames (DebuggerTlsData *tls)
2782 tls = mono_native_tls_get_value (debugger_tls_id);
2785 for (i = 0; i < tls->frame_count; ++i) {
2786 if (tls->frames [i]->jit)
2787 mono_debug_free_method_jit_info (tls->frames [i]->jit);
2788 g_free (tls->frames [i]);
2790 g_free (tls->frames);
2791 tls->frame_count = 0;
2798 * Suspend the current thread until the runtime is resumed. If the thread has a
2799 * pending invoke, then the invoke is executed before this function returns.
2802 suspend_current (void)
2805 DebuggerTlsData *tls;
2807 g_assert (debugger_thread_id != GetCurrentThreadId ());
2809 if (mono_loader_lock_is_owned_by_self ()) {
2811 * If we own the loader mutex, can't suspend until we release it, since the
2812 * whole runtime can deadlock otherwise.
2817 tls = mono_native_tls_get_value (debugger_tls_id);
2820 mono_mutex_lock (&suspend_mutex);
2822 tls->suspending = FALSE;
2823 tls->really_suspended = TRUE;
2825 if (!tls->suspended) {
2826 tls->suspended = TRUE;
2827 MONO_SEM_POST (&suspend_sem);
2830 DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
2832 while (suspend_count - tls->resume_count > 0) {
2834 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
2836 mono_mutex_unlock (&suspend_mutex);
2838 mono_mutex_lock (&suspend_mutex);
2844 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
2845 g_assert (err == 0);
2849 tls->suspended = FALSE;
2850 tls->really_suspended = FALSE;
2852 threads_suspend_count --;
2854 mono_mutex_unlock (&suspend_mutex);
2856 DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
2858 if (tls->pending_invoke) {
2859 /* Save the original context */
2860 tls->pending_invoke->has_ctx = TRUE;
2861 tls->pending_invoke->ctx = tls->context.ctx;
2866 /* The frame info becomes invalid after a resume */
2867 tls->context.valid = FALSE;
2868 tls->async_state.valid = FALSE;
2869 invalidate_frames (tls);
2873 count_thread (gpointer key, gpointer value, gpointer user_data)
2875 DebuggerTlsData *tls = value;
2877 if (!tls->suspended && !tls->terminated)
2878 *(int*)user_data = *(int*)user_data + 1;
2882 count_threads_to_wait_for (void)
2886 mono_loader_lock ();
2887 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2888 mono_loader_unlock ();
2896 * Wait until the runtime is completely suspended.
2899 wait_for_suspend (void)
2901 int nthreads, nwait, err;
2902 gboolean waited = FALSE;
2904 // FIXME: Threads starting/stopping ?
2905 mono_loader_lock ();
2906 nthreads = mono_g_hash_table_size (thread_to_tls);
2907 mono_loader_unlock ();
2910 nwait = count_threads_to_wait_for ();
2912 DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
2913 err = MONO_SEM_WAIT (&suspend_sem);
2914 g_assert (err == 0);
2922 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
2928 * Return whenever the runtime is suspended.
2933 return count_threads_to_wait_for () == 0;
2936 static MonoSeqPointInfo*
2937 get_seq_points (MonoDomain *domain, MonoMethod *method)
2939 MonoSeqPointInfo *seq_points;
2941 mono_domain_lock (domain);
2942 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2943 if (!seq_points && method->is_inflated) {
2944 /* generic sharing + aot */
2945 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (method));
2947 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mini_get_shared_method (method));
2949 mono_domain_unlock (domain);
2955 no_seq_points_found (MonoMethod *method)
2958 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
2960 printf ("Unable to find seq points for method '%s'.\n", mono_method_full_name (method, TRUE));
2964 * find_next_seq_point_for_native_offset:
2966 * Find the first sequence point after NATIVE_OFFSET.
2969 find_next_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2971 MonoSeqPointInfo *seq_points;
2974 seq_points = get_seq_points (domain, method);
2980 g_assert (seq_points);
2984 for (i = 0; i < seq_points->len; ++i) {
2985 if (seq_points->seq_points [i].native_offset >= native_offset)
2986 return &seq_points->seq_points [i];
2993 * find_prev_seq_point_for_native_offset:
2995 * Find the first sequence point before NATIVE_OFFSET.
2998 find_prev_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
3000 MonoSeqPointInfo *seq_points;
3003 seq_points = get_seq_points (domain, method);
3009 for (i = seq_points->len - 1; i >= 0; --i) {
3010 if (seq_points->seq_points [i].native_offset <= native_offset)
3011 return &seq_points->seq_points [i];
3020 * Find the sequence point corresponding to the IL offset IL_OFFSET, which
3021 * should be the location of a sequence point.
3023 static G_GNUC_UNUSED SeqPoint*
3024 find_seq_point (MonoDomain *domain, MonoMethod *method, gint32 il_offset, MonoSeqPointInfo **info)
3026 MonoSeqPointInfo *seq_points;
3031 seq_points = get_seq_points (domain, method);
3036 for (i = 0; i < seq_points->len; ++i) {
3037 if (seq_points->seq_points [i].il_offset == il_offset)
3038 return &seq_points->seq_points [i];
3045 DebuggerTlsData *tls;
3047 } ComputeFramesUserData;
3050 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3052 ComputeFramesUserData *ud = user_data;
3054 MonoMethod *method, *actual_method, *api_method;
3058 if (info->type != FRAME_TYPE_MANAGED) {
3059 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3060 /* Mark the last frame as an invoke frame */
3062 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3068 method = info->ji->method;
3070 method = info->method;
3071 actual_method = info->actual_method;
3072 api_method = method;
3077 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3080 if (info->il_offset == -1) {
3081 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3082 if (ud->frames == NULL) {
3083 sp = find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL);
3085 info->il_offset = sp->il_offset;
3087 if (info->il_offset == -1)
3088 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3091 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));
3093 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3094 if (!CHECK_PROTOCOL_VERSION (2, 17))
3095 /* Older clients can't handle this flag */
3097 api_method = mono_marshal_method_from_wrapper (method);
3100 actual_method = api_method;
3101 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3104 frame = g_new0 (StackFrame, 1);
3105 frame->method = method;
3106 frame->actual_method = actual_method;
3107 frame->api_method = api_method;
3108 frame->il_offset = info->il_offset;
3109 frame->native_offset = info->native_offset;
3110 frame->flags = flags;
3111 frame->ji = info->ji;
3112 if (info->reg_locations)
3113 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3116 frame->has_ctx = TRUE;
3118 frame->domain = info->domain;
3120 ud->frames = g_slist_append (ud->frames, frame);
3126 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3128 ComputeFramesUserData *ud = user_data;
3131 * 'tls->filter_ctx' is the location of the throw site.
3133 * mono_walk_stack() will never actually hit the throw site, but unwind
3134 * directly from the filter to the call site; we abort stack unwinding here
3135 * once this happens and resume from the throw site.
3138 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3141 return process_frame (info, ctx, user_data);
3145 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3147 ComputeFramesUserData user_data;
3149 int i, findex, new_frame_count;
3150 StackFrame **new_frames, *f;
3151 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3153 // FIXME: Locking on tls
3154 if (tls->frames && tls->frames_up_to_date)
3157 DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
3159 user_data.tls = tls;
3160 user_data.frames = NULL;
3161 if (tls->terminated) {
3162 tls->frame_count = 0;
3164 } if (!tls->really_suspended && tls->async_state.valid) {
3165 /* Have to use the state saved by the signal handler */
3166 process_frame (&tls->async_last_frame, NULL, &user_data);
3167 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3168 } else if (tls->filter_state.valid) {
3170 * We are inside an exception filter.
3172 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3174 if (tls->context.valid)
3175 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3177 * After that, we resume unwinding from the location where the exception has been thrown.
3179 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3180 } else if (tls->context.valid) {
3181 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3184 tls->frame_count = 0;
3188 new_frame_count = g_slist_length (user_data.frames);
3189 new_frames = g_new0 (StackFrame*, new_frame_count);
3191 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3195 * Reuse the id for already existing stack frames, so invokes don't invalidate
3196 * the still valid stack frames.
3198 for (i = 0; i < tls->frame_count; ++i) {
3199 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3200 f->id = tls->frames [i]->id;
3205 if (i >= tls->frame_count)
3206 f->id = InterlockedIncrement (&frame_id);
3208 new_frames [findex ++] = f;
3211 g_slist_free (user_data.frames);
3213 invalidate_frames (tls);
3215 tls->frames = new_frames;
3216 tls->frame_count = new_frame_count;
3217 tls->frames_up_to_date = TRUE;
3221 * GHFunc to emit an appdomain creation event
3222 * @param key Don't care
3223 * @param value A loaded appdomain
3224 * @param user_data Don't care
3227 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3229 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3230 g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
3234 * GHFunc to emit a thread start event
3235 * @param key A thread id
3236 * @param value A thread object
3237 * @param user_data Don't care
3240 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3242 if (GPOINTER_TO_INT (key) != debugger_thread_id)
3243 process_profiler_event (EVENT_KIND_THREAD_START, value);
3247 * GFunc to emit an assembly load event
3248 * @param value A loaded assembly
3249 * @param user_data Don't care
3252 emit_assembly_load (gpointer value, gpointer user_data)
3254 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3258 * GFunc to emit a type load event
3259 * @param value A loaded type
3260 * @param user_data Don't care
3263 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3265 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3269 strdup_tolower (char *s)
3274 for (p = s2; *p; ++p)
3284 * create_event_list:
3286 * Return a list of event request ids matching EVENT, starting from REQS, which
3287 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3289 * We return request ids, instead of requests, to simplify threading, since
3290 * requests could be deleted anytime when the loader lock is not held.
3291 * LOCKING: Assumes the loader lock is held.
3294 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3297 GSList *events = NULL;
3299 *suspend_policy = SUSPEND_POLICY_NONE;
3302 reqs = event_requests;
3307 for (i = 0; i < reqs->len; ++i) {
3308 EventRequest *req = g_ptr_array_index (reqs, i);
3309 if (req->event_kind == event) {
3310 gboolean filtered = FALSE;
3313 for (j = 0; j < req->nmodifiers; ++j) {
3314 Modifier *mod = &req->modifiers [j];
3316 if (mod->kind == MOD_KIND_COUNT) {
3318 if (mod->data.count > 0) {
3319 if (mod->data.count > 0) {
3321 if (mod->data.count == 0)
3325 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3326 if (mod->data.thread != mono_thread_internal_current ())
3328 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3329 if (mod->data.exc_class && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3331 if (ei->caught && !mod->caught)
3333 if (!ei->caught && !mod->uncaught)
3335 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3337 gboolean found = FALSE;
3338 MonoAssembly **assemblies = mod->data.assemblies;
3341 for (k = 0; assemblies [k]; ++k)
3342 if (assemblies [k] == ji->method->klass->image->assembly)
3347 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3348 gpointer iter = NULL;
3350 MonoDebugSourceInfo *sinfo;
3351 char *source_file, *s;
3352 gboolean found = FALSE;
3354 GPtrArray *source_file_list;
3356 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3357 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3360 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, NULL, NULL, NULL, NULL, NULL);
3361 for (i = 0; i < source_file_list->len; ++i) {
3362 sinfo = g_ptr_array_index (source_file_list, i);
3364 * Do a case-insesitive match by converting the file name to
3367 s = strdup_tolower (sinfo->source_file);
3368 if (g_hash_table_lookup (mod->data.source_files, s))
3371 char *s2 = g_path_get_basename (sinfo->source_file);
3372 char *s3 = strdup_tolower (s2);
3374 if (g_hash_table_lookup (mod->data.source_files, s3))
3381 g_ptr_array_free (source_file_list, TRUE);
3386 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3389 s = mono_type_full_name (&ei->klass->byval_arg);
3390 if (!g_hash_table_lookup (mod->data.type_names, s))
3393 } else if (mod->kind == MOD_KIND_STEP) {
3394 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3395 (ji->method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3396 !strcmp (ji->method->name, ".cctor"))
3398 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3399 MonoCustomAttrInfo *ainfo;
3400 static MonoClass *klass;
3403 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3406 if (!ji->dbg_hidden_inited) {
3407 ainfo = mono_custom_attrs_from_method (ji->method);
3409 if (mono_custom_attrs_has_attr (ainfo, klass))
3410 ji->dbg_hidden = TRUE;
3411 mono_custom_attrs_free (ainfo);
3413 ji->dbg_hidden_inited = TRUE;
3422 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3423 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3428 /* Send a VM START/DEATH event by default */
3429 if (event == EVENT_KIND_VM_START)
3430 events = g_slist_append (events, GINT_TO_POINTER (0));
3431 if (event == EVENT_KIND_VM_DEATH)
3432 events = g_slist_append (events, GINT_TO_POINTER (0));
3437 static G_GNUC_UNUSED const char*
3438 event_to_string (EventKind event)
3441 case EVENT_KIND_VM_START: return "VM_START";
3442 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3443 case EVENT_KIND_THREAD_START: return "THREAD_START";
3444 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3445 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3446 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3447 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3448 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3449 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3450 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3451 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3452 case EVENT_KIND_STEP: return "STEP";
3453 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3454 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3455 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3456 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3457 case EVENT_KIND_USER_LOG: return "USER_LOG";
3459 g_assert_not_reached ();
3466 * Send an event to the client, suspending the vm if needed.
3467 * LOCKING: Since this can suspend the calling thread, no locks should be held
3469 * The EVENTS list is freed by this function.
3472 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3476 MonoDomain *domain = mono_domain_get ();
3477 MonoThread *thread = NULL;
3478 MonoObject *keepalive_obj = NULL;
3479 gboolean send_success = FALSE;
3484 DEBUG (2, fprintf (log_file, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event)));
3488 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3489 // FIXME: We miss those events
3490 DEBUG (2, fprintf (log_file, "VM start event not sent yet: dropping %s\n", event_to_string (event)));
3494 if (vm_death_event_sent) {
3495 DEBUG (2, fprintf (log_file, "VM death event has been sent: dropping %s\n", event_to_string (event)));
3499 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3500 DEBUG (2, fprintf (log_file, "Mono runtime is shutting down: dropping %s\n", event_to_string (event)));
3505 DEBUG (2, fprintf (log_file, "Debugger client is not connected: dropping %s\n", event_to_string (event)));
3509 if (event == EVENT_KIND_KEEPALIVE)
3510 suspend_policy = SUSPEND_POLICY_NONE;
3515 if (agent_config.defer) {
3516 /* Make sure the thread id is always set when doing deferred debugging */
3517 if (debugger_thread_id == GetCurrentThreadId ()) {
3518 /* Don't suspend on events from the debugger thread */
3519 suspend_policy = SUSPEND_POLICY_NONE;
3520 thread = mono_thread_get_main ();
3522 else thread = mono_thread_current ();
3524 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3525 // FIXME: Send these with a NULL thread, don't suspend the current thread
3530 nevents = g_slist_length (events);
3531 buffer_init (&buf, 128);
3532 buffer_add_byte (&buf, suspend_policy);
3533 buffer_add_int (&buf, nevents);
3535 for (l = events; l; l = l->next) {
3536 buffer_add_byte (&buf, event); // event kind
3537 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3542 thread = mono_thread_current ();
3544 if (event == EVENT_KIND_VM_START && arg != NULL)
3547 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3550 case EVENT_KIND_THREAD_START:
3551 case EVENT_KIND_THREAD_DEATH:
3553 case EVENT_KIND_APPDOMAIN_CREATE:
3554 case EVENT_KIND_APPDOMAIN_UNLOAD:
3555 buffer_add_domainid (&buf, arg);
3557 case EVENT_KIND_METHOD_ENTRY:
3558 case EVENT_KIND_METHOD_EXIT:
3559 buffer_add_methodid (&buf, domain, arg);
3561 case EVENT_KIND_ASSEMBLY_LOAD:
3562 case EVENT_KIND_ASSEMBLY_UNLOAD:
3563 buffer_add_assemblyid (&buf, domain, arg);
3565 case EVENT_KIND_TYPE_LOAD:
3566 buffer_add_typeid (&buf, domain, arg);
3568 case EVENT_KIND_BREAKPOINT:
3569 case EVENT_KIND_STEP:
3570 buffer_add_methodid (&buf, domain, arg);
3571 buffer_add_long (&buf, il_offset);
3573 case EVENT_KIND_VM_START:
3574 buffer_add_domainid (&buf, mono_get_root_domain ());
3576 case EVENT_KIND_VM_DEATH:
3578 case EVENT_KIND_EXCEPTION: {
3579 EventInfo *ei = arg;
3580 buffer_add_objid (&buf, ei->exc);
3582 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3583 * later after the suspension. (#12494).
3585 keepalive_obj = ei->exc;
3588 case EVENT_KIND_USER_BREAK:
3590 case EVENT_KIND_USER_LOG: {
3591 EventInfo *ei = arg;
3592 buffer_add_int (&buf, ei->level);
3593 buffer_add_string (&buf, ei->category ? ei->category : "");
3594 buffer_add_string (&buf, ei->message ? ei->message : "");
3597 case EVENT_KIND_KEEPALIVE:
3598 suspend_policy = SUSPEND_POLICY_NONE;
3601 g_assert_not_reached ();
3605 if (event == EVENT_KIND_VM_START) {
3606 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3607 if (!agent_config.defer)
3608 start_debugger_thread ();
3611 if (event == EVENT_KIND_VM_DEATH) {
3612 vm_death_event_sent = TRUE;
3613 suspend_policy = SUSPEND_POLICY_NONE;
3616 if (mono_runtime_is_shutting_down ())
3617 suspend_policy = SUSPEND_POLICY_NONE;
3619 if (suspend_policy != SUSPEND_POLICY_NONE) {
3621 * Save the thread context and start suspending before sending the packet,
3622 * since we could be receiving the resume request before send_packet ()
3625 save_thread_context (ctx);
3629 /* This will keep this object alive */
3630 get_objref (keepalive_obj);
3633 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3637 g_slist_free (events);
3640 if (!send_success) {
3641 DEBUG (2, fprintf (log_file, "Sending command %s failed.\n", event_to_string (event)));
3645 if (event == EVENT_KIND_VM_START) {
3646 vm_start_event_sent = TRUE;
3649 DEBUG (1, fprintf (log_file, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer)GetCurrentThreadId (), nevents, event_to_string (event), ecount, suspend_policy));
3651 switch (suspend_policy) {
3652 case SUSPEND_POLICY_NONE:
3654 case SUSPEND_POLICY_ALL:
3657 case SUSPEND_POLICY_EVENT_THREAD:
3661 g_assert_not_reached ();
3666 process_profiler_event (EventKind event, gpointer arg)
3670 EventInfo ei, *ei_arg = NULL;
3672 if (event == EVENT_KIND_TYPE_LOAD) {
3677 mono_loader_lock ();
3678 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3679 mono_loader_unlock ();
3681 process_event (event, arg, 0, NULL, events, suspend_policy);
3685 runtime_initialized (MonoProfiler *prof)
3687 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3688 if (agent_config.defer)
3689 start_debugger_thread ();
3693 runtime_shutdown (MonoProfiler *prof)
3695 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3697 mono_debugger_agent_cleanup ();
3701 thread_startup (MonoProfiler *prof, uintptr_t tid)
3703 MonoInternalThread *thread = mono_thread_internal_current ();
3704 MonoInternalThread *old_thread;
3705 DebuggerTlsData *tls;
3707 if (tid == debugger_thread_id)
3710 g_assert (thread->tid == tid);
3712 mono_loader_lock ();
3713 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3714 mono_loader_unlock ();
3716 if (thread == old_thread) {
3718 * For some reason, thread_startup () might be called for the same thread
3719 * multiple times (attach ?).
3721 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
3725 * thread_end () might not be called for some threads, and the tid could
3728 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
3729 mono_loader_lock ();
3730 mono_g_hash_table_remove (thread_to_tls, old_thread);
3731 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3732 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3733 mono_loader_unlock ();
3737 tls = mono_native_tls_get_value (debugger_tls_id);
3739 // FIXME: Free this somewhere
3740 tls = g_new0 (DebuggerTlsData, 1);
3741 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3742 tls->thread = thread;
3743 mono_native_tls_set_value (debugger_tls_id, tls);
3745 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3747 mono_loader_lock ();
3748 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3749 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3750 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3751 mono_loader_unlock ();
3753 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3756 * suspend_vm () could have missed this thread, so wait for a resume.
3762 thread_end (MonoProfiler *prof, uintptr_t tid)
3764 MonoInternalThread *thread;
3765 DebuggerTlsData *tls = NULL;
3767 mono_loader_lock ();
3768 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3770 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3771 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3773 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3774 tls->terminated = TRUE;
3775 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3776 MONO_GC_UNREGISTER_ROOT (tls->thread);
3780 mono_loader_unlock ();
3782 /* We might be called for threads started before we registered the start callback */
3784 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3785 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3790 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3792 mono_loader_lock ();
3793 g_hash_table_insert (domains, domain, domain);
3794 mono_loader_unlock ();
3796 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3800 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3802 clear_breakpoints_for_domain (domain);
3804 mono_loader_lock ();
3805 /* Invalidate each thread's frame stack */
3806 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3807 mono_loader_unlock ();
3809 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3813 * invalidate_each_thread:
3815 * A GHFunc to invalidate frames.
3816 * value must be a DebuggerTlsData*
3819 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3821 invalidate_frames (value);
3825 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3827 /* Sent later in jit_end () */
3828 mono_loader_lock ();
3829 g_ptr_array_add (pending_assembly_loads, assembly);
3830 mono_loader_unlock ();
3834 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3836 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3838 clear_event_requests_for_assembly (assembly);
3839 clear_types_for_assembly (assembly);
3843 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3845 #if defined(HOST_WIN32) && !defined(__GNUC__)
3846 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3848 gpointer stackptr = __builtin_frame_address (1);
3850 MonoInternalThread *thread = mono_thread_internal_current ();
3851 DebuggerTlsData *tls;
3853 mono_loader_lock ();
3855 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3856 /* Could be the debugger thread with assembly/type load hooks */
3858 tls->invoke_addr = stackptr;
3860 mono_loader_unlock ();
3864 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3867 #if defined(HOST_WIN32) && !defined(__GNUC__)
3868 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3870 gpointer stackptr = __builtin_frame_address (1);
3873 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
3877 * We need to stop single stepping when exiting a runtime invoke, since if it is
3878 * a step out, it may return to native code, and thus never end.
3880 mono_loader_lock ();
3881 ss_invoke_addr = NULL;
3883 for (i = 0; i < event_requests->len; ++i) {
3884 EventRequest *req = g_ptr_array_index (event_requests, i);
3886 if (req->event_kind == EVENT_KIND_STEP) {
3887 ss_destroy (req->info);
3888 g_ptr_array_remove_index_fast (event_requests, i);
3893 mono_loader_unlock ();
3897 send_type_load (MonoClass *klass)
3899 gboolean type_load = FALSE;
3900 MonoDomain *domain = mono_domain_get ();
3901 AgentDomainInfo *info = NULL;
3903 mono_loader_lock ();
3904 mono_domain_lock (domain);
3906 info = get_agent_domain_info (domain);
3908 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
3910 g_hash_table_insert (info->loaded_classes, klass, klass);
3913 mono_domain_unlock (domain);
3914 mono_loader_unlock ();
3916 emit_type_load (klass, klass, NULL);
3920 * Emit load events for all types currently loaded in the domain.
3921 * Takes the loader and domain locks.
3922 * user_data is unused.
3925 send_types_for_domain (MonoDomain *domain, void *user_data)
3927 AgentDomainInfo *info = NULL;
3929 mono_loader_lock ();
3930 mono_domain_lock (domain);
3931 info = get_agent_domain_info (domain);
3933 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
3934 mono_domain_unlock (domain);
3935 mono_loader_unlock ();
3939 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
3942 * We emit type load events when the first method of the type is JITted,
3943 * since the class load profiler callbacks might be called with the
3944 * loader lock held. They could also occur in the debugger thread.
3945 * Same for assembly load events.
3948 MonoAssembly *assembly = NULL;
3950 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
3951 mono_loader_lock ();
3952 if (pending_assembly_loads->len > 0) {
3953 assembly = g_ptr_array_index (pending_assembly_loads, 0);
3954 g_ptr_array_remove_index (pending_assembly_loads, 0);
3956 mono_loader_unlock ();
3959 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
3965 send_type_load (method->klass);
3968 add_pending_breakpoints (method, jinfo);
3972 * BREAKPOINTS/SINGLE STEPPING
3976 * Contains information about an inserted breakpoint.
3979 long il_offset, native_offset;
3984 } BreakpointInstance;
3987 * Contains generic information about a breakpoint.
3991 * The method where the breakpoint is placed. Can be NULL in which case it
3992 * is inserted into every method. This is used to implement method entry/
3993 * exit events. Can be a generic method definition, in which case the
3994 * breakpoint is inserted into every instance.
4000 * A list of BreakpointInstance structures describing where the breakpoint
4001 * was inserted. There could be more than one because of
4002 * generics/appdomains/method entry/exit.
4004 GPtrArray *children;
4007 /* List of breakpoints */
4008 static GPtrArray *breakpoints;
4009 /* Maps breakpoint locations to the number of breakpoints at that location */
4010 static GHashTable *bp_locs;
4013 breakpoints_init (void)
4015 breakpoints = g_ptr_array_new ();
4016 bp_locs = g_hash_table_new (NULL, NULL);
4020 * insert_breakpoint:
4022 * Insert the breakpoint described by BP into the method described by
4026 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4029 BreakpointInstance *inst;
4030 SeqPoint *sp = NULL;
4033 mono_error_init (error);
4035 for (i = 0; i < seq_points->len; ++i) {
4036 sp = &seq_points->seq_points [i];
4038 if (sp->il_offset == bp->il_offset)
4042 if (i == seq_points->len) {
4044 * The set of IL offsets with seq points doesn't completely match the
4045 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4047 for (i = 0; i < seq_points->len; ++i) {
4048 sp = &seq_points->seq_points [i];
4050 if (sp->il_offset != METHOD_ENTRY_IL_OFFSET && sp->il_offset != METHOD_EXIT_IL_OFFSET && sp->il_offset + 1 == bp->il_offset)
4055 if (i == seq_points->len) {
4056 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);
4058 for (i = 0; i < seq_points->len; ++i)
4059 DEBUG (1, fprintf (log_file, "%d\n", seq_points->seq_points [i].il_offset));
4062 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4063 g_warning ("%s", s);
4067 g_warning ("%s", s);
4073 inst = g_new0 (BreakpointInstance, 1);
4075 inst->native_offset = sp->native_offset;
4076 inst->ip = (guint8*)ji->code_start + sp->native_offset;
4078 inst->domain = domain;
4080 mono_loader_lock ();
4082 g_ptr_array_add (bp->children, inst);
4084 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4085 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4086 mono_loader_unlock ();
4088 if (sp->native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4089 DEBUG (1, fprintf (log_file, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset));
4090 } else if (count == 0) {
4091 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4092 mono_arch_set_breakpoint (ji, inst->ip);
4098 DEBUG(1, fprintf (log_file, "[dbg] Inserted breakpoint at %s:0x%x.\n", mono_method_full_name (ji->method, TRUE), (int)sp->il_offset));
4102 remove_breakpoint (BreakpointInstance *inst)
4104 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4106 MonoJitInfo *ji = inst->ji;
4107 guint8 *ip = inst->ip;
4109 mono_loader_lock ();
4110 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4111 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4112 mono_loader_unlock ();
4114 g_assert (count > 0);
4116 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4117 mono_arch_clear_breakpoint (ji, ip);
4124 static inline gboolean
4125 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4131 if (method == bp->method)
4133 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4136 if (bp->method->is_inflated && method->is_inflated) {
4137 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4138 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4140 /* Open generic methods should match closed generic methods of the same class */
4141 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4142 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4143 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4145 /* FIXME: Handle !mvar */
4146 if (t1->type != MONO_TYPE_MVAR)
4157 * add_pending_breakpoints:
4159 * Insert pending breakpoints into the newly JITted method METHOD.
4162 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4165 MonoSeqPointInfo *seq_points;
4171 domain = mono_domain_get ();
4173 mono_loader_lock ();
4175 for (i = 0; i < breakpoints->len; ++i) {
4176 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4177 gboolean found = FALSE;
4179 if (!bp_matches_method (bp, method))
4182 for (j = 0; j < bp->children->len; ++j) {
4183 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4190 mono_domain_lock (domain);
4191 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
4192 if (!seq_points && ji->method->is_inflated)
4193 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (ji->method));
4194 mono_domain_unlock (domain);
4196 /* Could be AOT code */
4198 g_assert (seq_points);
4200 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4204 mono_loader_unlock ();
4208 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4214 mono_error_init (error);
4216 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4218 /* Might be AOTed code */
4219 code = mono_aot_get_method (domain, method);
4221 ji = mono_jit_info_table_find (domain, code);
4226 insert_breakpoint (seq_points, domain, ji, bp, error);
4230 clear_breakpoint (MonoBreakpoint *bp);
4235 * Set a breakpoint at IL_OFFSET in METHOD.
4236 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4237 * METHOD can also be a generic method definition, in which case a breakpoint
4238 * is placed in all instances of the method.
4239 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4242 static MonoBreakpoint*
4243 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4246 GHashTableIter iter, iter2;
4249 MonoSeqPointInfo *seq_points;
4252 mono_error_init (error);
4255 // - suspend/resume the vm to prevent code patching problems
4256 // - multiple breakpoints on the same location
4257 // - dynamic methods
4260 bp = g_new0 (MonoBreakpoint, 1);
4261 bp->method = method;
4262 bp->il_offset = il_offset;
4264 bp->children = g_ptr_array_new ();
4266 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));
4268 mono_loader_lock ();
4270 g_hash_table_iter_init (&iter, domains);
4271 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4272 mono_domain_lock (domain);
4274 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4275 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4276 if (bp_matches_method (bp, m))
4277 set_bp_in_method (domain, m, seq_points, bp, error);
4280 mono_domain_unlock (domain);
4283 mono_loader_unlock ();
4285 mono_loader_lock ();
4286 g_ptr_array_add (breakpoints, bp);
4287 mono_loader_unlock ();
4289 if (error && !mono_error_ok (error)) {
4290 clear_breakpoint (bp);
4298 clear_breakpoint (MonoBreakpoint *bp)
4302 // FIXME: locking, races
4303 for (i = 0; i < bp->children->len; ++i) {
4304 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4306 remove_breakpoint (inst);
4311 mono_loader_lock ();
4312 g_ptr_array_remove (breakpoints, bp);
4313 mono_loader_unlock ();
4315 g_ptr_array_free (bp->children, TRUE);
4320 breakpoints_cleanup (void)
4324 mono_loader_lock ();
4326 while (i < event_requests->len) {
4327 EventRequest *req = g_ptr_array_index (event_requests, i);
4329 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4330 clear_breakpoint (req->info);
4331 g_ptr_array_remove_index_fast (event_requests, i);
4338 for (i = 0; i < breakpoints->len; ++i)
4339 g_free (g_ptr_array_index (breakpoints, i));
4341 g_ptr_array_free (breakpoints, TRUE);
4342 g_hash_table_destroy (bp_locs);
4347 mono_loader_unlock ();
4351 * clear_breakpoints_for_domain:
4353 * Clear breakpoint instances which reference DOMAIN.
4356 clear_breakpoints_for_domain (MonoDomain *domain)
4360 /* This could be called after shutdown */
4364 mono_loader_lock ();
4365 for (i = 0; i < breakpoints->len; ++i) {
4366 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4369 while (j < bp->children->len) {
4370 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4372 if (inst->domain == domain) {
4373 remove_breakpoint (inst);
4377 g_ptr_array_remove_index_fast (bp->children, j);
4383 mono_loader_unlock ();
4387 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4389 return bp->method && bp->method->klass->image->assembly == assembly;
4393 process_breakpoint_inner (DebuggerTlsData *tls)
4397 int i, j, suspend_policy;
4398 guint32 native_offset;
4400 BreakpointInstance *inst;
4401 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4402 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4403 EventKind kind = EVENT_KIND_BREAKPOINT;
4404 MonoContext *ctx = &tls->restore_ctx;
4405 MonoSeqPointInfo *info;
4408 // FIXME: Speed this up
4410 ip = MONO_CONTEXT_GET_IP (ctx);
4411 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4413 g_assert (ji->method);
4415 /* Compute the native offset of the breakpoint from the ip */
4416 native_offset = ip - (guint8*)ji->code_start;
4419 * Skip the instruction causing the breakpoint signal.
4421 mono_arch_skip_breakpoint (ctx, ji);
4423 if (ji->method->wrapper_type || tls->disable_breakpoints)
4426 bp_reqs = g_ptr_array_new ();
4427 ss_reqs = g_ptr_array_new ();
4428 ss_reqs_orig = g_ptr_array_new ();
4430 mono_loader_lock ();
4433 * The ip points to the instruction causing the breakpoint event, which is after
4434 * the offset recorded in the seq point map, so find the prev seq point before ip.
4436 sp = find_prev_seq_point_for_native_offset (mono_domain_get (), ji->method, native_offset, &info);
4438 no_seq_points_found (ji->method);
4441 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));
4444 for (i = 0; i < breakpoints->len; ++i) {
4445 bp = g_ptr_array_index (breakpoints, i);
4450 for (j = 0; j < bp->children->len; ++j) {
4451 inst = g_ptr_array_index (bp->children, j);
4452 if (inst->ji == ji && inst->sp == sp) {
4453 if (bp->req->event_kind == EVENT_KIND_STEP) {
4454 g_ptr_array_add (ss_reqs_orig, bp->req);
4456 g_ptr_array_add (bp_reqs, bp->req);
4461 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4462 /* Maybe a method entry/exit event */
4463 if (sp->il_offset == METHOD_ENTRY_IL_OFFSET)
4464 kind = EVENT_KIND_METHOD_ENTRY;
4465 else if (sp->il_offset == METHOD_EXIT_IL_OFFSET)
4466 kind = EVENT_KIND_METHOD_EXIT;
4469 /* Process single step requests */
4470 for (i = 0; i < ss_reqs_orig->len; ++i) {
4471 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4472 SingleStepReq *ss_req = req->info;
4473 gboolean hit = TRUE;
4475 if (ss_req->size == STEP_SIZE_LINE) {
4476 /* Have to check whenever a different source line was reached */
4477 MonoDebugMethodInfo *minfo;
4478 MonoDebugSourceLocation *loc = NULL;
4480 minfo = mono_debug_lookup_method (ji->method);
4483 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4485 if (!loc || (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line)) {
4486 /* Have to continue single stepping */
4487 DEBUG(1, fprintf (log_file, "[%p] Same source line, continuing single stepping.\n", (gpointer)GetCurrentThreadId ()));
4492 ss_req->last_method = ji->method;
4493 ss_req->last_line = loc->row;
4494 mono_debug_free_source_location (loc);
4499 g_ptr_array_add (ss_reqs, req);
4501 /* Start single stepping again from the current sequence point */
4502 ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4505 if (ss_reqs->len > 0)
4506 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4507 if (bp_reqs->len > 0)
4508 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4509 if (kind != EVENT_KIND_BREAKPOINT)
4510 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4512 mono_loader_unlock ();
4514 g_ptr_array_free (bp_reqs, TRUE);
4515 g_ptr_array_free (ss_reqs, TRUE);
4518 * FIXME: The first event will suspend, so the second will only be sent after the
4522 process_event (EVENT_KIND_STEP, ji->method, 0, ctx, ss_events, suspend_policy);
4524 process_event (kind, ji->method, 0, ctx, bp_events, suspend_policy);
4525 if (enter_leave_events)
4526 process_event (kind, ji->method, 0, ctx, enter_leave_events, suspend_policy);
4529 /* Process a breakpoint/single step event after resuming from a signal handler */
4531 process_signal_event (void (*func) (DebuggerTlsData*))
4533 DebuggerTlsData *tls;
4534 MonoContext orig_restore_ctx, ctx;
4535 static void (*restore_context) (void *);
4537 if (!restore_context)
4538 restore_context = mono_get_restore_context ();
4540 tls = mono_native_tls_get_value (debugger_tls_id);
4541 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4542 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4543 memcpy (&tls->restore_ctx, &tls->handler_ctx, sizeof (MonoContext));
4547 /* This is called when resuming from a signal handler, so it shouldn't return */
4548 memcpy (&ctx, &tls->restore_ctx, sizeof (MonoContext));
4549 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4550 restore_context (&ctx);
4551 g_assert_not_reached ();
4555 process_breakpoint (void)
4557 process_signal_event (process_breakpoint_inner);
4561 resume_from_signal_handler (void *sigctx, void *func)
4563 DebuggerTlsData *tls;
4566 /* Save the original context in TLS */
4567 // FIXME: This might not work on an altstack ?
4568 tls = mono_native_tls_get_value (debugger_tls_id);
4570 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer)GetCurrentThreadId ());
4573 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4574 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4575 // clob:c could be added to op_seq_point.
4577 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4578 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4579 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4580 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4582 MONO_CONTEXT_SET_IP (&ctx, func);
4584 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4586 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4587 mono_ppc_set_func_into_sigctx (sigctx, func);
4592 mono_debugger_agent_breakpoint_hit (void *sigctx)
4595 * We are called from a signal handler, and running code there causes all kinds of
4596 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4597 * So set up the signal context to return to the real breakpoint handler function.
4599 resume_from_signal_handler (sigctx, process_breakpoint);
4603 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4605 if (frame->managed) {
4606 *(MonoContext*)data = *ctx;
4615 * Called by System.Diagnostics.Debugger:Break ().
4618 mono_debugger_agent_user_break (void)
4620 if (agent_config.enabled) {
4625 /* Obtain a context */
4626 MONO_CONTEXT_SET_IP (&ctx, NULL);
4627 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4628 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4630 mono_loader_lock ();
4631 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4632 mono_loader_unlock ();
4634 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4641 ss_depth_to_string (StepDepth depth)
4644 case STEP_DEPTH_OVER:
4646 case STEP_DEPTH_OUT:
4648 case STEP_DEPTH_INTO:
4651 g_assert_not_reached ();
4657 process_single_step_inner (DebuggerTlsData *tls)
4662 int il_offset, suspend_policy;
4665 MonoContext *ctx = &tls->restore_ctx;
4667 MonoSeqPointInfo *info;
4669 ip = MONO_CONTEXT_GET_IP (ctx);
4671 /* Skip the instruction causing the single step */
4672 mono_arch_skip_single_step (ctx);
4674 if (suspend_count > 0) {
4675 process_suspend (tls, ctx);
4680 // FIXME: A suspend race
4683 if (mono_thread_internal_current () != ss_req->thread)
4686 if (log_level > 0) {
4687 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4689 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));
4692 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4694 g_assert (ji->method);
4696 if (ji->method->wrapper_type && ji->method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4701 * Stopping in memset makes half-initialized vtypes visible.
4702 * Stopping in memcpy makes half-copied vtypes visible.
4704 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
4708 * The ip points to the instruction causing the single step event, which is before
4709 * the offset recorded in the seq point map, so find the next seq point after ip.
4711 sp = find_next_seq_point_for_native_offset (domain, ji->method, (guint8*)ip - (guint8*)ji->code_start, &info);
4714 il_offset = sp->il_offset;
4716 // FIXME: No tests fail if this is disabled
4718 if (ss_req->size == STEP_SIZE_LINE) {
4722 /* Step until a different source line is reached */
4723 MonoDebugMethodInfo *minfo;
4725 minfo = mono_debug_lookup_method (ji->method);
4728 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4730 if (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line) {
4731 mono_debug_free_source_location (loc);
4736 * Step until we reach a location with line number info,
4737 * otherwise the client can't show a location.
4738 * This can happen for example with statics initialized inline
4739 * outside of a cctor.
4744 ss_req->last_method = ji->method;
4745 ss_req->last_line = loc->row;
4746 mono_debug_free_source_location (loc);
4752 /* Start single stepping again from the current sequence point */
4753 ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4755 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
4756 (ji->method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4757 !strcmp (ji->method->name, ".cctor"))
4760 // FIXME: Has to lock earlier
4762 reqs = g_ptr_array_new ();
4764 mono_loader_lock ();
4766 g_ptr_array_add (reqs, ss_req->req);
4768 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4770 g_ptr_array_free (reqs, TRUE);
4772 mono_loader_unlock ();
4774 process_event (EVENT_KIND_STEP, ji->method, il_offset, ctx, events, suspend_policy);
4778 process_single_step (void)
4780 process_signal_event (process_single_step_inner);
4784 * mono_debugger_agent_single_step_event:
4786 * Called from a signal handler to handle a single step event.
4789 mono_debugger_agent_single_step_event (void *sigctx)
4791 /* Resume to process_single_step through the signal context */
4793 // FIXME: Since step out/over is implemented using step in, the step in case should
4794 // be as fast as possible. Move the relevant code from process_single_step_inner ()
4797 if (GetCurrentThreadId () == debugger_thread_id) {
4799 * This could happen despite our best effors when the runtime calls
4800 * assembly/type resolve hooks.
4801 * FIXME: Breakpoints too.
4805 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4806 mono_arch_skip_single_step (&ctx);
4807 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4811 resume_from_signal_handler (sigctx, process_single_step);
4815 debugger_agent_single_step_from_context (MonoContext *ctx)
4817 DebuggerTlsData *tls;
4818 MonoContext orig_restore_ctx;
4820 tls = mono_native_tls_get_value (debugger_tls_id);
4823 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4824 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4825 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4827 process_single_step_inner (tls);
4829 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4830 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4834 debugger_agent_breakpoint_from_context (MonoContext *ctx)
4836 DebuggerTlsData *tls;
4837 MonoContext orig_restore_ctx;
4839 tls = mono_native_tls_get_value (debugger_tls_id);
4841 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4842 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4844 process_breakpoint_inner (tls);
4846 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4847 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4851 * start_single_stepping:
4853 * Turn on single stepping. Can be called multiple times, for example,
4854 * by a single step event request + a suspend.
4857 start_single_stepping (void)
4859 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4860 int val = InterlockedIncrement (&ss_count);
4863 mono_arch_start_single_stepping ();
4865 if (ss_req != NULL && ss_invoke_addr == NULL) {
4866 DebuggerTlsData *tls;
4868 mono_loader_lock ();
4870 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
4871 ss_invoke_addr = tls->invoke_addr;
4873 mono_loader_unlock ();
4876 g_assert_not_reached ();
4881 stop_single_stepping (void)
4883 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4884 int val = InterlockedDecrement (&ss_count);
4887 mono_arch_stop_single_stepping ();
4889 ss_invoke_addr = NULL;
4891 g_assert_not_reached ();
4898 * Stop the single stepping operation given by SS_REQ.
4901 ss_stop (SingleStepReq *ss_req)
4906 for (l = ss_req->bps; l; l = l->next) {
4907 clear_breakpoint (l->data);
4909 g_slist_free (ss_req->bps);
4913 if (ss_req->global) {
4914 stop_single_stepping ();
4915 ss_req->global = FALSE;
4922 * Start the single stepping operation given by SS_REQ from the sequence point SP.
4923 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
4924 * belong to the same thread as CTX.
4927 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
4929 int i, j, frame_index;
4932 gboolean enable_global = FALSE;
4934 /* Stop the previous operation */
4938 * Implement single stepping using breakpoints if possible.
4940 if (step_to_catch) {
4941 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
4942 ss_req->bps = g_slist_append (ss_req->bps, bp);
4946 if ((!sp || sp->next_len == 0 || ss_req->depth == STEP_DEPTH_OUT || ss_req->depth == STEP_DEPTH_OVER) && ctx) {
4947 /* Need parent frames */
4948 if (!tls->context.valid)
4949 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4950 compute_frame_info (tls->thread, tls);
4954 * Find the first sequence point in the current or in a previous frame which
4955 * is not the last in its method.
4957 if (ss_req->depth == STEP_DEPTH_OUT) {
4958 /* Ignore seq points in current method */
4959 while (frame_index < tls->frame_count) {
4960 StackFrame *frame = tls->frames [frame_index];
4962 method = frame->method;
4963 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4965 if (sp && sp->next_len != 0)
4968 // There could be method calls before the next seq point in the caller when using nested calls
4969 //enable_global = TRUE;
4971 if (sp && sp->next_len == 0) {
4973 while (frame_index < tls->frame_count) {
4974 StackFrame *frame = tls->frames [frame_index];
4976 method = frame->method;
4977 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4978 if (sp && sp->next_len != 0)
4986 if (sp && sp->next_len > 0) {
4987 for (i = 0; i < sp->next_len; ++i) {
4988 next_sp = &info->seq_points [sp->next [i]];
4990 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
4991 ss_req->bps = g_slist_append (ss_req->bps, bp);
4995 if (ss_req->depth == STEP_DEPTH_OVER) {
4996 /* Need to stop in catch clauses as well */
4997 for (i = 0; i < tls->frame_count; ++i) {
4998 StackFrame *frame = tls->frames [i];
5001 MonoJitInfo *jinfo = frame->ji;
5002 for (j = 0; j < jinfo->num_clauses; ++j) {
5003 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5005 sp = find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL);
5007 bp = set_breakpoint (frame->method, sp->il_offset, ss_req->req, NULL);
5008 ss_req->bps = g_slist_append (ss_req->bps, bp);
5016 if (ss_req->depth == STEP_DEPTH_INTO) {
5017 /* Enable global stepping so we stop at method entry too */
5018 enable_global = TRUE;
5022 * The ctx/frame info computed above will become invalid when we continue.
5024 tls->context.valid = FALSE;
5025 tls->async_state.valid = FALSE;
5026 invalidate_frames (tls);
5029 if (enable_global) {
5030 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
5031 ss_req->global = TRUE;
5032 start_single_stepping ();
5033 } else if (!ss_req->bps) {
5034 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
5035 ss_req->global = TRUE;
5036 start_single_stepping ();
5038 ss_req->global = FALSE;
5043 * Start single stepping of thread THREAD
5046 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
5048 DebuggerTlsData *tls;
5049 MonoSeqPointInfo *info = NULL;
5050 SeqPoint *sp = NULL;
5051 MonoMethod *method = NULL;
5052 MonoDebugMethodInfo *minfo;
5053 gboolean step_to_catch = FALSE;
5055 if (suspend_count == 0)
5056 return ERR_NOT_SUSPENDED;
5058 wait_for_suspend ();
5060 // FIXME: Multiple requests
5062 DEBUG (0, fprintf (log_file, "Received a single step request while the previous one was still active.\n"));
5063 return ERR_NOT_IMPLEMENTED;
5066 DEBUG (1, fprintf (log_file, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
5068 ss_req = g_new0 (SingleStepReq, 1);
5070 ss_req->thread = thread;
5071 ss_req->size = size;
5072 ss_req->depth = depth;
5075 mono_loader_lock ();
5076 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5077 mono_loader_unlock ();
5079 g_assert (tls->context.valid);
5080 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5082 if (tls->catch_state.valid) {
5084 StackFrameInfo frame;
5085 MonoContext new_ctx;
5086 MonoLMF *lmf = NULL;
5089 * We are stopped at a throw site. Stepping should go to the catch site.
5092 /* Find the the jit info for the catch context */
5093 res = mono_find_jit_info_ext (tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], thread->jit_data, NULL, &tls->catch_state.ctx, &new_ctx, NULL, &lmf, NULL, &frame);
5095 g_assert (frame.type == FRAME_TYPE_MANAGED);
5098 * Find the seq point corresponding to the landing site ip, which is the first seq
5101 sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
5103 no_seq_points_found (frame.method);
5106 method = frame.method;
5108 step_to_catch = TRUE;
5109 /* This make sure the seq point is not skipped by process_single_step () */
5110 ss_req->last_sp = NULL;
5113 if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
5116 /* Compute the initial line info */
5117 compute_frame_info (thread, tls);
5119 if (tls->frame_count) {
5120 frame = tls->frames [0];
5122 ss_req->last_method = frame->method;
5123 ss_req->last_line = -1;
5125 minfo = mono_debug_lookup_method (frame->method);
5126 if (minfo && frame->il_offset != -1) {
5127 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
5130 ss_req->last_line = loc->row;
5137 if (!step_to_catch) {
5140 compute_frame_info (thread, tls);
5142 if (tls->frame_count) {
5143 frame = tls->frames [0];
5145 if (!method && frame->il_offset != -1) {
5146 /* FIXME: Sort the table and use a binary search */
5147 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5149 no_seq_points_found (frame->method);
5151 method = frame->method;
5156 ss_start (ss_req, method, sp, info, &tls->context.ctx, tls, step_to_catch);
5162 ss_destroy (SingleStepReq *req)
5165 g_assert (ss_req == req);
5174 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5177 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5183 if (!agent_config.enabled)
5186 mono_loader_lock ();
5187 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5188 mono_loader_unlock ();
5191 ei.category = category ? mono_string_to_utf8 (category) : NULL;
5192 ei.message = message ? mono_string_to_utf8 (message) : NULL;
5194 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5196 g_free (ei.category);
5197 g_free (ei.message);
5201 mono_debugger_agent_debug_log_is_enabled (void)
5203 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5204 return agent_config.enabled;
5207 #ifdef PLATFORM_ANDROID
5209 mono_debugger_agent_unhandled_exception (MonoException *exc)
5218 memset (&ei, 0, sizeof (EventInfo));
5219 ei.exc = (MonoObject*)exc;
5221 mono_loader_lock ();
5222 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5223 mono_loader_unlock ();
5225 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5230 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5231 MonoContext *catch_ctx)
5233 int i, j, suspend_policy;
5235 MonoJitInfo *ji, *catch_ji;
5237 DebuggerTlsData *tls = NULL;
5239 if (thread_to_tls != NULL) {
5240 MonoInternalThread *thread = mono_thread_internal_current ();
5242 mono_loader_lock ();
5243 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5244 mono_loader_unlock ();
5246 if (tls && tls->abort_requested)
5248 if (tls && tls->disable_breakpoints)
5252 memset (&ei, 0, sizeof (EventInfo));
5254 /* Just-In-Time debugging */
5256 if (agent_config.onuncaught && !inited) {
5257 finish_agent_init (FALSE);
5260 * Send an unsolicited EXCEPTION event with a dummy request id.
5262 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5263 ei.exc = (MonoObject*)exc;
5264 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5267 } else if (agent_config.onthrow && !inited) {
5269 gboolean found = FALSE;
5271 for (l = agent_config.onthrow; l; l = l->next) {
5272 char *ex_type = l->data;
5273 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5275 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5282 finish_agent_init (FALSE);
5285 * Send an unsolicited EXCEPTION event with a dummy request id.
5287 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5288 ei.exc = (MonoObject*)exc;
5289 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5297 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5299 catch_ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5303 ei.exc = (MonoObject*)exc;
5304 ei.caught = catch_ctx != NULL;
5306 mono_loader_lock ();
5308 /* Treat exceptions which are caught in non-user code as unhandled */
5309 for (i = 0; i < event_requests->len; ++i) {
5310 EventRequest *req = g_ptr_array_index (event_requests, i);
5311 if (req->event_kind != EVENT_KIND_EXCEPTION)
5314 for (j = 0; j < req->nmodifiers; ++j) {
5315 Modifier *mod = &req->modifiers [j];
5317 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5319 gboolean found = FALSE;
5320 MonoAssembly **assemblies = mod->data.assemblies;
5323 for (k = 0; assemblies [k]; ++k)
5324 if (assemblies [k] == catch_ji->method->klass->image->assembly)
5333 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5334 mono_loader_unlock ();
5336 if (tls && ei.caught && catch_ctx) {
5337 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5338 tls->catch_state.ctx = *catch_ctx;
5339 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5340 tls->catch_state.valid = TRUE;
5343 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5346 tls->catch_state.valid = FALSE;
5350 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5352 DebuggerTlsData *tls;
5357 tls = mono_native_tls_get_value (debugger_tls_id);
5362 * We're about to invoke an exception filter during the first pass of exception handling.
5364 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5365 * 'orig_ctx' is the context where the exception has been thrown.
5368 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5370 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5371 * the call site (line 37) and then continue to Main(), but it would never
5372 * include the throw site (line 32).
5374 * Since exception filters are invoked during the first pass of exception handling,
5375 * the stack frames of the throw site are still intact, so we should include them
5378 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5380 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5381 * but report the location of the 'throw' to the user.
5385 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5389 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5391 DebuggerTlsData *tls;
5396 tls = mono_native_tls_get_value (debugger_tls_id);
5400 tls->filter_state.valid = FALSE;
5404 * buffer_add_value_full:
5406 * Add the encoding of the value at ADDR described by T to the buffer.
5407 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5411 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5417 if (!(*(void**)addr)) {
5418 /* This can happen with compiler generated locals */
5419 //printf ("%s\n", mono_type_full_name (t));
5420 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5423 g_assert (*(void**)addr);
5424 addr = *(void**)addr;
5429 case MONO_TYPE_BOOLEAN:
5432 case MONO_TYPE_CHAR:
5452 case MONO_TYPE_VOID:
5453 buffer_add_byte (buf, t->type);
5455 case MONO_TYPE_BOOLEAN:
5458 buffer_add_byte (buf, t->type);
5459 buffer_add_int (buf, *(gint8*)addr);
5461 case MONO_TYPE_CHAR:
5464 buffer_add_byte (buf, t->type);
5465 buffer_add_int (buf, *(gint16*)addr);
5470 buffer_add_byte (buf, t->type);
5471 buffer_add_int (buf, *(gint32*)addr);
5476 buffer_add_byte (buf, t->type);
5477 buffer_add_long (buf, *(gint64*)addr);
5481 /* Treat it as a vtype */
5483 case MONO_TYPE_PTR: {
5484 gssize val = *(gssize*)addr;
5486 buffer_add_byte (buf, t->type);
5487 buffer_add_long (buf, val);
5491 case MONO_TYPE_STRING:
5492 case MONO_TYPE_SZARRAY:
5493 case MONO_TYPE_OBJECT:
5494 case MONO_TYPE_CLASS:
5495 case MONO_TYPE_ARRAY:
5496 obj = *(MonoObject**)addr;
5499 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5501 if (obj->vtable->klass->valuetype) {
5502 t = &obj->vtable->klass->byval_arg;
5503 addr = mono_object_unbox (obj);
5505 } else if (obj->vtable->klass->rank) {
5506 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5507 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5508 buffer_add_byte (buf, MONO_TYPE_CLASS);
5510 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5512 buffer_add_objid (buf, obj);
5516 case MONO_TYPE_VALUETYPE: {
5520 MonoClass *klass = mono_class_from_mono_type (t);
5522 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5523 buffer_add_byte (buf, klass->enumtype);
5524 buffer_add_typeid (buf, domain, klass);
5528 while ((f = mono_class_get_fields (klass, &iter))) {
5529 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5531 if (mono_field_is_deleted (f))
5535 buffer_add_int (buf, nfields);
5538 while ((f = mono_class_get_fields (klass, &iter))) {
5539 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5541 if (mono_field_is_deleted (f))
5543 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE);
5547 case MONO_TYPE_GENERICINST:
5548 if (mono_type_generic_inst_is_valuetype (t)) {
5560 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5562 buffer_add_value_full (buf, t, addr, domain, FALSE);
5566 obj_is_of_type (MonoObject *obj, MonoType *t)
5568 MonoClass *klass = obj->vtable->klass;
5569 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5570 if (mono_class_is_transparent_proxy (klass)) {
5571 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5572 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5582 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5585 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5589 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5590 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5591 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5592 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5593 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
5594 char *name = mono_type_full_name (t);
5595 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5597 return ERR_INVALID_ARGUMENT;
5601 case MONO_TYPE_BOOLEAN:
5602 *(guint8*)addr = decode_int (buf, &buf, limit);
5604 case MONO_TYPE_CHAR:
5605 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5608 *(gint8*)addr = decode_int (buf, &buf, limit);
5611 *(guint8*)addr = decode_int (buf, &buf, limit);
5614 *(gint16*)addr = decode_int (buf, &buf, limit);
5617 *(guint16*)addr = decode_int (buf, &buf, limit);
5620 *(gint32*)addr = decode_int (buf, &buf, limit);
5623 *(guint32*)addr = decode_int (buf, &buf, limit);
5626 *(gint64*)addr = decode_long (buf, &buf, limit);
5629 *(guint64*)addr = decode_long (buf, &buf, limit);
5632 *(guint32*)addr = decode_int (buf, &buf, limit);
5635 *(guint64*)addr = decode_long (buf, &buf, limit);
5638 /* We send these as I8, so we get them back as such */
5639 g_assert (type == MONO_TYPE_I8);
5640 *(gssize*)addr = decode_long (buf, &buf, limit);
5642 case MONO_TYPE_GENERICINST:
5643 if (MONO_TYPE_ISSTRUCT (t)) {
5644 /* The client sends these as a valuetype */
5652 /* We send these as vtypes, so we get them back as such */
5653 g_assert (type == MONO_TYPE_VALUETYPE);
5656 case MONO_TYPE_VALUETYPE: {
5657 gboolean is_enum = decode_byte (buf, &buf, limit);
5661 gpointer iter = NULL;
5664 /* Enums are sent as a normal vtype */
5666 return ERR_NOT_IMPLEMENTED;
5667 klass = decode_typeid (buf, &buf, limit, &d, &err);
5671 if (klass != mono_class_from_mono_type (t))
5672 return ERR_INVALID_ARGUMENT;
5674 nfields = decode_int (buf, &buf, limit);
5675 while ((f = mono_class_get_fields (klass, &iter))) {
5676 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5678 if (mono_field_is_deleted (f))
5680 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5685 g_assert (nfields == 0);
5690 if (MONO_TYPE_IS_REFERENCE (t)) {
5691 if (type == MONO_TYPE_OBJECT) {
5692 int objid = decode_objid (buf, &buf, limit);
5696 err = get_object (objid, (MonoObject**)&obj);
5701 if (!obj_is_of_type (obj, t)) {
5702 DEBUG (1, fprintf (log_file, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name));
5703 return ERR_INVALID_ARGUMENT;
5706 if (obj && obj->vtable->domain != domain)
5707 return ERR_INVALID_ARGUMENT;
5709 mono_gc_wbarrier_generic_store (addr, obj);
5710 } else if (type == VALUE_TYPE_ID_NULL) {
5711 *(MonoObject**)addr = NULL;
5713 return ERR_INVALID_ARGUMENT;
5727 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5730 int type = decode_byte (buf, &buf, limit);
5732 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
5733 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
5734 guint8 *nullable_buf;
5737 * First try decoding it as a Nullable`1
5739 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5744 * Then try decoding as a primitive value or null.
5746 if (targ->type == type) {
5747 nullable_buf = g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
5748 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
5750 g_free (nullable_buf);
5753 mono_nullable_init (addr, mono_value_box (domain, mono_class_from_mono_type (targ), nullable_buf), mono_class_from_mono_type (t));
5754 g_free (nullable_buf);
5757 } else if (type == VALUE_TYPE_ID_NULL) {
5758 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
5764 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5768 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
5772 guint8 *addr, *gaddr;
5775 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5776 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5779 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
5780 reg_val = mono_arch_context_get_int_reg (ctx, reg);
5782 buffer_add_value_full (buf, t, ®_val, domain, as_vtype);
5784 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5785 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5786 addr += (gint32)var->offset;
5788 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5790 buffer_add_value_full (buf, t, addr, domain, as_vtype);
5792 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5795 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
5796 /* Same as regoffset, but with an indirection */
5797 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5798 addr += (gint32)var->offset;
5800 gaddr = *(gpointer*)addr;
5802 buffer_add_value_full (buf, t, gaddr, domain, as_vtype);
5804 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
5805 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
5806 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
5807 MonoGSharedVtMethodRuntimeInfo *info;
5813 g_assert (info_var);
5814 g_assert (locals_var);
5816 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5817 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5818 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
5819 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5820 addr += (gint32)info_var->offset;
5821 info = *(gpointer*)addr;
5822 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
5823 info = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5825 g_assert_not_reached ();
5829 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5830 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5831 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
5832 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5833 addr += (gint32)locals_var->offset;
5834 locals = *(gpointer*)addr;
5835 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
5836 locals = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5838 g_assert_not_reached ();
5842 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
5844 buffer_add_value_full (buf, t, addr, domain, as_vtype);
5849 g_assert_not_reached ();
5854 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
5858 guint8 *addr, *gaddr;
5860 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5861 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5863 if (MONO_TYPE_IS_REFERENCE (t))
5864 size = sizeof (gpointer);
5866 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
5869 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
5870 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
5872 gboolean is_signed = FALSE;
5874 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
5879 v = is_signed ? *(gint8*)val : *(guint8*)val;
5882 v = is_signed ? *(gint16*)val : *(guint16*)val;
5885 v = is_signed ? *(gint32*)val : *(guint32*)val;
5888 v = is_signed ? *(gint64*)val : *(guint64*)val;
5891 g_assert_not_reached ();
5897 /* Set value on the stack or in the return ctx */
5898 if (reg_locations [reg]) {
5899 /* Saved on the stack */
5900 DEBUG (1, fprintf (log_file, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v));
5901 *(reg_locations [reg]) = v;
5904 DEBUG (1, fprintf (log_file, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v));
5905 mono_arch_context_set_int_reg (restore_ctx, reg, v);
5908 // FIXME: Move these to mono-context.h/c.
5909 mono_arch_context_set_int_reg (ctx, reg, v);
5911 // FIXME: Can't set registers, so we disable linears
5916 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5917 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5918 addr += (gint32)var->offset;
5920 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5923 addr = *(guint8**)addr;
5929 // FIXME: Write barriers
5930 mono_gc_memmove (addr, val, size);
5932 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
5933 /* Same as regoffset, but with an indirection */
5934 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5935 addr += (gint32)var->offset;
5937 gaddr = *(gpointer*)addr;
5939 // FIXME: Write barriers
5940 mono_gc_memmove (gaddr, val, size);
5942 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5946 g_assert_not_reached ();
5951 clear_event_request (int req_id, int etype)
5955 mono_loader_lock ();
5956 for (i = 0; i < event_requests->len; ++i) {
5957 EventRequest *req = g_ptr_array_index (event_requests, i);
5959 if (req->id == req_id && req->event_kind == etype) {
5960 if (req->event_kind == EVENT_KIND_BREAKPOINT)
5961 clear_breakpoint (req->info);
5962 if (req->event_kind == EVENT_KIND_STEP)
5963 ss_destroy (req->info);
5964 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
5965 clear_breakpoint (req->info);
5966 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
5967 clear_breakpoint (req->info);
5968 g_ptr_array_remove_index_fast (event_requests, i);
5973 mono_loader_unlock ();
5977 event_req_matches_assembly (EventRequest *req, MonoAssembly *assembly)
5979 if (req->event_kind == EVENT_KIND_BREAKPOINT)
5980 return breakpoint_matches_assembly (req->info, assembly);
5984 for (i = 0; i < req->nmodifiers; ++i) {
5985 Modifier *m = &req->modifiers [i];
5987 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
5989 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
5990 for (j = 0; m->data.assemblies [j]; ++j)
5991 if (m->data.assemblies [j] == assembly)
6001 * clear_event_requests_for_assembly:
6003 * Clear all events requests which reference ASSEMBLY.
6006 clear_event_requests_for_assembly (MonoAssembly *assembly)
6011 mono_loader_lock ();
6015 for (i = 0; i < event_requests->len; ++i) {
6016 EventRequest *req = g_ptr_array_index (event_requests, i);
6018 if (event_req_matches_assembly (req, assembly)) {
6019 clear_event_request (req->id, req->event_kind);
6025 mono_loader_unlock ();
6029 * type_comes_from_assembly:
6031 * GHRFunc that returns TRUE if klass comes from assembly
6034 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6036 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6040 * clear_types_for_assembly:
6042 * Clears types from loaded_classes for a given assembly
6045 clear_types_for_assembly (MonoAssembly *assembly)
6047 MonoDomain *domain = mono_domain_get ();
6048 AgentDomainInfo *info = NULL;
6050 mono_loader_lock ();
6051 info = get_agent_domain_info (domain);
6052 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6053 mono_loader_unlock ();
6057 add_thread (gpointer key, gpointer value, gpointer user_data)
6059 MonoInternalThread *thread = value;
6060 Buffer *buf = user_data;
6062 buffer_add_objid (buf, (MonoObject*)thread);
6066 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6068 guint8 *end = invoke->endp;
6071 MonoMethodSignature *sig;
6074 MonoObject *this, *res, *exc;
6077 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6080 MonoStopwatch watch;
6082 if (invoke->method) {
6084 * Invoke this method directly, currently only Environment.Exit () is supported.
6087 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>"));
6088 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
6089 g_assert_not_reached ();
6092 m = decode_methodid (p, &p, end, &domain, &err);
6095 sig = mono_method_signature (m);
6097 if (m->klass->valuetype)
6098 this_buf = g_alloca (mono_class_instance_size (m->klass));
6100 this_buf = g_alloca (sizeof (MonoObject*));
6101 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6102 /* Should be null */
6103 int type = decode_byte (p, &p, end);
6104 if (type != VALUE_TYPE_ID_NULL)
6105 return ERR_INVALID_ARGUMENT;
6106 memset (this_buf, 0, mono_class_instance_size (m->klass));
6108 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6113 if (!m->klass->valuetype)
6114 this = *(MonoObject**)this_buf;
6118 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>"));
6120 if (this && this->vtable->domain != domain)
6123 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
6124 if (!strcmp (m->name, ".ctor")) {
6125 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
6126 return ERR_INVALID_ARGUMENT;
6128 this = mono_object_new (domain, m->klass);
6130 return ERR_INVALID_ARGUMENT;
6134 if (this && !obj_is_of_type (this, &m->klass->byval_arg))
6135 return ERR_INVALID_ARGUMENT;
6137 nargs = decode_int (p, &p, end);
6138 if (nargs != sig->param_count)
6139 return ERR_INVALID_ARGUMENT;
6140 /* Use alloca to get gc tracking */
6141 arg_buf = g_alloca (nargs * sizeof (gpointer));
6142 memset (arg_buf, 0, nargs * sizeof (gpointer));
6143 args = g_alloca (nargs * sizeof (gpointer));
6144 for (i = 0; i < nargs; ++i) {
6145 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6146 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6150 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6153 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6154 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6157 args [i] = arg_buf [i];
6164 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6165 tls->disable_breakpoints = TRUE;
6167 tls->disable_breakpoints = FALSE;
6170 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6172 /* FIXME: Move this to arch specific code */
6173 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6174 if (invoke->has_ctx) {
6177 lmf_addr = mono_get_lmf_addr ();
6180 memset (&ext, 0, sizeof (ext));
6182 ext.lmf.previous_lmf = *(lmf_addr);
6183 /* Mark that this is a MonoLMFExt */
6184 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6185 ext.lmf.rsp = (gssize)&ext;
6186 #elif defined(TARGET_X86)
6187 ext.lmf.previous_lmf = (gsize)*(lmf_addr);
6188 /* Mark that this is a MonoLMFExt */
6189 ext.lmf.previous_lmf = (gsize)(gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6190 ext.lmf.ebp = (gssize)&ext;
6191 #elif defined(TARGET_ARM)
6192 ext.lmf.previous_lmf = *(lmf_addr);
6193 /* Mark that this is a MonoLMFExt */
6194 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6195 ext.lmf.sp = (gssize)&ext;
6196 #elif defined(TARGET_POWERPC)
6197 ext.lmf.previous_lmf = *(lmf_addr);
6198 /* Mark that this is a MonoLMFExt */
6199 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6200 ext.lmf.ebp = (gssize)&ext;
6201 #elif defined(TARGET_S390X)
6202 ext.lmf.previous_lmf = *(lmf_addr);
6203 /* Mark that this is a MonoLMFExt */
6204 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6205 ext.lmf.ebp = (gssize)&ext;
6206 #elif defined(TARGET_MIPS)
6207 ext.lmf.previous_lmf = *(lmf_addr);
6208 /* Mark that this is a MonoLMFExt */
6209 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6210 ext.lmf.iregs [mips_sp] = (gssize)&ext;
6212 g_assert_not_reached ();
6215 ext.debugger_invoke = TRUE;
6216 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6218 mono_set_lmf ((MonoLMF*)&ext);
6222 mono_stopwatch_start (&watch);
6223 if (m->klass->valuetype)
6224 res = mono_runtime_invoke (m, this_buf, args, &exc);
6226 res = mono_runtime_invoke (m, this, args, &exc);
6227 mono_stopwatch_stop (&watch);
6228 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)));
6230 buffer_add_byte (buf, 0);
6231 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6233 buffer_add_byte (buf, 1);
6234 if (sig->ret->type == MONO_TYPE_VOID) {
6235 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
6236 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
6239 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6240 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6241 buffer_add_value (buf, sig->ret, &res, domain);
6242 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6243 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6244 MonoClass *k = mono_class_from_mono_type (sig->ret);
6245 guint8 *nullable_buf = g_alloca (mono_class_value_size (k, NULL));
6247 g_assert (nullable_buf);
6248 mono_nullable_init (nullable_buf, res, k);
6249 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6252 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6259 tls->disable_breakpoints = FALSE;
6261 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6262 if (invoke->has_ctx)
6263 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
6267 // FIXME: byref arguments
6275 * Invoke the method given by tls->pending_invoke in the current thread.
6278 invoke_method (void)
6280 DebuggerTlsData *tls;
6285 static void (*restore_context) (void *);
6286 MonoContext restore_ctx;
6289 if (!restore_context)
6290 restore_context = mono_get_restore_context ();
6292 tls = mono_native_tls_get_value (debugger_tls_id);
6296 * Store the `InvokeData *' in `tls->invoke' until we're done with
6297 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6300 mono_loader_lock ();
6302 invoke = tls->pending_invoke;
6304 tls->pending_invoke = NULL;
6306 invoke->last_invoke = tls->invoke;
6307 tls->invoke = invoke;
6309 mono_loader_unlock ();
6311 tls->frames_up_to_date = FALSE;
6317 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6318 buffer_init (&buf, 128);
6321 /* Fail the other invokes as well */
6323 err = do_invoke_method (tls, &buf, invoke, p, &p);
6326 /* Start suspending before sending the reply */
6327 if (mindex == invoke->nmethods - 1) {
6328 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6329 for (i = 0; i < invoke->suspend_count; ++i)
6334 send_reply_packet (id, err, &buf);
6339 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6341 if (invoke->has_ctx)
6342 save_thread_context (&restore_ctx);
6344 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6345 g_assert (tls->resume_count);
6346 tls->resume_count -= invoke->suspend_count;
6349 DEBUG (1, fprintf (log_file, "[%p] Invoke finished, resume_count = %d.\n", (gpointer)GetCurrentThreadId (), tls->resume_count));
6352 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6354 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
6355 * after the mono_runtime_invoke() already returned, but it doesn't matter
6356 * because we reset the abort here.
6359 mono_loader_lock ();
6361 if (tls->abort_requested)
6362 mono_thread_internal_reset_abort (tls->thread);
6364 tls->invoke = tls->invoke->last_invoke;
6365 tls->abort_requested = FALSE;
6367 mono_loader_unlock ();
6376 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6378 MonoThread *thread = value;
6379 DebuggerTlsData *tls;
6382 mono_loader_lock ();
6383 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6385 res = tls->really_suspended;
6386 mono_loader_unlock ();
6392 get_source_files_for_type (MonoClass *klass)
6394 gpointer iter = NULL;
6396 MonoDebugSourceInfo *sinfo;
6400 files = g_ptr_array_new ();
6402 while ((method = mono_class_get_methods (klass, &iter))) {
6403 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6404 GPtrArray *source_file_list;
6407 mono_debug_symfile_get_line_numbers_full (minfo, NULL, &source_file_list, NULL, NULL, NULL, NULL, NULL);
6408 for (j = 0; j < source_file_list->len; ++j) {
6409 sinfo = g_ptr_array_index (source_file_list, j);
6410 for (i = 0; i < files->len; ++i)
6411 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6413 if (i == files->len)
6414 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6416 g_ptr_array_free (source_file_list, TRUE);
6424 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6427 case CMD_VM_VERSION: {
6428 char *build_info, *version;
6430 build_info = mono_get_runtime_build_info ();
6431 version = g_strdup_printf ("mono %s", build_info);
6433 buffer_add_string (buf, version); /* vm version */
6434 buffer_add_int (buf, MAJOR_VERSION);
6435 buffer_add_int (buf, MINOR_VERSION);
6436 g_free (build_info);
6440 case CMD_VM_SET_PROTOCOL_VERSION: {
6441 major_version = decode_int (p, &p, end);
6442 minor_version = decode_int (p, &p, end);
6443 protocol_version_set = TRUE;
6444 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
6447 case CMD_VM_ALL_THREADS: {
6449 mono_loader_lock ();
6450 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6451 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6452 mono_loader_unlock ();
6455 case CMD_VM_SUSPEND:
6457 wait_for_suspend ();
6460 if (suspend_count == 0)
6461 return ERR_NOT_SUSPENDED;
6463 clear_suspended_objs ();
6465 case CMD_VM_DISPOSE:
6466 /* Clear all event requests */
6467 mono_loader_lock ();
6468 while (event_requests->len > 0) {
6469 EventRequest *req = g_ptr_array_index (event_requests, 0);
6471 clear_event_request (req->id, req->event_kind);
6473 mono_loader_unlock ();
6475 while (suspend_count > 0)
6477 disconnected = TRUE;
6478 vm_start_event_sent = FALSE;
6481 MonoInternalThread *thread;
6482 DebuggerTlsData *tls;
6483 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6484 MonoClass *env_class;
6486 MonoMethod *exit_method = NULL;
6490 exit_code = decode_int (p, &p, end);
6492 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6494 /* Have to send a reply before exiting */
6495 send_reply_packet (id, 0, buf);
6497 /* Clear all event requests */
6498 mono_loader_lock ();
6499 while (event_requests->len > 0) {
6500 EventRequest *req = g_ptr_array_index (event_requests, 0);
6502 clear_event_request (req->id, req->event_kind);
6504 mono_loader_unlock ();
6507 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6508 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6509 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6510 * better than doing the shutdown ourselves, since it avoids various races.
6514 wait_for_suspend ();
6516 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6517 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
6519 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6522 mono_loader_lock ();
6523 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6524 mono_loader_unlock ();
6526 if (thread && exit_method) {
6527 mono_loader_lock ();
6528 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6529 mono_loader_unlock ();
6531 args = g_new0 (gpointer, 1);
6532 args [0] = g_malloc (sizeof (int));
6533 *(int*)(args [0]) = exit_code;
6535 tls->pending_invoke = g_new0 (InvokeData, 1);
6536 tls->pending_invoke->method = exit_method;
6537 tls->pending_invoke->args = args;
6538 tls->pending_invoke->nmethods = 1;
6540 while (suspend_count > 0)
6544 * No thread found, do it ourselves.
6545 * FIXME: This can race with normal shutdown etc.
6547 while (suspend_count > 0)
6550 if (!mono_runtime_try_shutdown ())
6553 /* Suspend all managed threads since the runtime is going away */
6554 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
6555 mono_thread_suspend_all_other_threads ();
6556 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
6557 mono_runtime_quit ();
6558 transport_close2 ();
6559 DEBUG(1, fprintf (log_file, "Exiting...\n"));
6565 case CMD_VM_INVOKE_METHOD:
6566 case CMD_VM_INVOKE_METHODS: {
6567 int objid = decode_objid (p, &p, end);
6569 DebuggerTlsData *tls;
6570 int i, count, err, flags, nmethods;
6572 err = get_object (objid, (MonoObject**)&thread);
6576 flags = decode_int (p, &p, end);
6578 if (command == CMD_VM_INVOKE_METHODS)
6579 nmethods = decode_int (p, &p, end);
6583 // Wait for suspending if it already started
6585 wait_for_suspend ();
6586 if (!is_suspended ())
6587 return ERR_NOT_SUSPENDED;
6589 mono_loader_lock ();
6590 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6591 mono_loader_unlock ();
6594 if (!tls->really_suspended)
6595 /* The thread is still running native code, can't do invokes */
6596 return ERR_NOT_SUSPENDED;
6599 * Store the invoke data into tls, the thread will execute it after it is
6602 if (tls->pending_invoke)
6603 return ERR_NOT_SUSPENDED;
6604 tls->pending_invoke = g_new0 (InvokeData, 1);
6605 tls->pending_invoke->id = id;
6606 tls->pending_invoke->flags = flags;
6607 tls->pending_invoke->p = g_malloc (end - p);
6608 memcpy (tls->pending_invoke->p, p, end - p);
6609 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
6610 tls->pending_invoke->suspend_count = suspend_count;
6611 tls->pending_invoke->nmethods = nmethods;
6613 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
6614 resume_thread (THREAD_TO_INTERNAL (thread));
6617 count = suspend_count;
6618 for (i = 0; i < count; ++i)
6623 case CMD_VM_ABORT_INVOKE: {
6624 int objid = decode_objid (p, &p, end);
6626 DebuggerTlsData *tls;
6629 err = get_object (objid, (MonoObject**)&thread);
6633 invoke_id = decode_int (p, &p, end);
6635 mono_loader_lock ();
6636 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6639 if (tls->abort_requested) {
6640 mono_loader_unlock ();
6645 * Check whether we're still inside the mono_runtime_invoke() and that it's
6646 * actually the correct invocation.
6648 * Careful, we do not stop the thread that's doing the invocation, so we can't
6649 * inspect its stack. However, invoke_method() also acquires the loader lock
6650 * when it's done, so we're safe here.
6654 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
6655 mono_loader_unlock ();
6656 return ERR_NO_INVOCATION;
6659 tls->abort_requested = TRUE;
6661 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
6662 mono_loader_unlock ();
6666 case CMD_VM_SET_KEEPALIVE: {
6667 int timeout = decode_int (p, &p, end);
6668 agent_config.keepalive = timeout;
6670 #ifndef DISABLE_SOCKET_TRANSPORT
6677 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
6678 GHashTableIter iter, kiter;
6683 char *fname, *basename;
6684 gboolean ignore_case;
6685 GSList *class_list, *l;
6686 GPtrArray *res_classes, *res_domains;
6688 fname = decode_string (p, &p, end);
6689 ignore_case = decode_byte (p, &p, end);
6691 basename = g_path_get_basename (fname);
6693 res_classes = g_ptr_array_new ();
6694 res_domains = g_ptr_array_new ();
6696 mono_loader_lock ();
6697 g_hash_table_iter_init (&iter, domains);
6698 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6699 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
6701 /* Update 'source_file_to_class' cache */
6702 g_hash_table_iter_init (&kiter, info->loaded_classes);
6703 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
6704 if (!g_hash_table_lookup (info->source_files, klass)) {
6705 files = get_source_files_for_type (klass);
6706 g_hash_table_insert (info->source_files, klass, files);
6708 for (i = 0; i < files->len; ++i) {
6709 char *s = g_ptr_array_index (files, i);
6710 char *s2 = g_path_get_basename (s);
6713 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
6715 class_list = g_slist_prepend (class_list, klass);
6716 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
6718 class_list = g_slist_prepend (class_list, klass);
6719 g_hash_table_insert (info->source_file_to_class, s2, class_list);
6722 /* The _ignorecase hash contains the lowercase path */
6723 s3 = strdup_tolower (s2);
6724 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
6726 class_list = g_slist_prepend (class_list, klass);
6727 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
6729 class_list = g_slist_prepend (class_list, klass);
6730 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
6742 s = strdup_tolower (basename);
6743 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
6746 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
6749 for (l = class_list; l; l = l->next) {
6752 g_ptr_array_add (res_classes, klass);
6753 g_ptr_array_add (res_domains, domain);
6756 mono_loader_unlock ();
6761 buffer_add_int (buf, res_classes->len);
6762 for (i = 0; i < res_classes->len; ++i)
6763 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6764 g_ptr_array_free (res_classes, TRUE);
6765 g_ptr_array_free (res_domains, TRUE);
6768 case CMD_VM_GET_TYPES: {
6769 GHashTableIter iter;
6773 gboolean ignore_case;
6774 GPtrArray *res_classes, *res_domains;
6775 MonoTypeNameParse info;
6777 name = decode_string (p, &p, end);
6778 ignore_case = decode_byte (p, &p, end);
6780 if (!mono_reflection_parse_type (name, &info)) {
6782 mono_reflection_free_type_info (&info);
6783 return ERR_INVALID_ARGUMENT;
6786 res_classes = g_ptr_array_new ();
6787 res_domains = g_ptr_array_new ();
6789 mono_loader_lock ();
6790 g_hash_table_iter_init (&iter, domains);
6791 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6793 gboolean type_resolve;
6797 mono_domain_assemblies_lock (domain);
6798 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6802 type_resolve = TRUE;
6803 t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
6805 g_ptr_array_add (res_classes, mono_type_get_class (t));
6806 g_ptr_array_add (res_domains, domain);
6810 mono_domain_assemblies_unlock (domain);
6812 mono_loader_unlock ();
6815 mono_reflection_free_type_info (&info);
6817 buffer_add_int (buf, res_classes->len);
6818 for (i = 0; i < res_classes->len; ++i)
6819 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6820 g_ptr_array_free (res_classes, TRUE);
6821 g_ptr_array_free (res_domains, TRUE);
6826 return ERR_NOT_IMPLEMENTED;
6833 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6839 case CMD_EVENT_REQUEST_SET: {
6841 int i, event_kind, suspend_policy, nmodifiers, mod;
6844 MonoThread *step_thread;
6845 int size = 0, depth = 0, filter = 0, step_thread_id = 0;
6849 event_kind = decode_byte (p, &p, end);
6850 suspend_policy = decode_byte (p, &p, end);
6851 nmodifiers = decode_byte (p, &p, end);
6853 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
6854 req->id = InterlockedIncrement (&event_request_id);
6855 req->event_kind = event_kind;
6856 req->suspend_policy = suspend_policy;
6857 req->nmodifiers = nmodifiers;
6860 for (i = 0; i < nmodifiers; ++i) {
6861 mod = decode_byte (p, &p, end);
6863 req->modifiers [i].kind = mod;
6864 if (mod == MOD_KIND_COUNT) {
6865 req->modifiers [i].data.count = decode_int (p, &p, end);
6866 } else if (mod == MOD_KIND_LOCATION_ONLY) {
6867 method = decode_methodid (p, &p, end, &domain, &err);
6870 location = decode_long (p, &p, end);
6871 } else if (mod == MOD_KIND_STEP) {
6872 step_thread_id = decode_id (p, &p, end);
6873 size = decode_int (p, &p, end);
6874 depth = decode_int (p, &p, end);
6875 if (CHECK_PROTOCOL_VERSION (2, 16))
6876 filter = decode_int (p, &p, end);
6877 req->modifiers [i].data.filter = filter;
6878 } else if (mod == MOD_KIND_THREAD_ONLY) {
6879 int id = decode_id (p, &p, end);
6881 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
6886 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
6887 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
6891 req->modifiers [i].caught = decode_byte (p, &p, end);
6892 req->modifiers [i].uncaught = decode_byte (p, &p, end);
6893 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" : ""));
6895 req->modifiers [i].data.exc_class = exc_class;
6897 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
6899 return ERR_INVALID_ARGUMENT;
6902 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
6903 int n = decode_int (p, &p, end);
6906 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
6907 for (j = 0; j < n; ++j) {
6908 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
6910 g_free (req->modifiers [i].data.assemblies);
6914 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
6915 int n = decode_int (p, &p, end);
6918 modifier = &req->modifiers [i];
6919 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
6920 for (j = 0; j < n; ++j) {
6921 char *s = decode_string (p, &p, end);
6925 s2 = strdup_tolower (s);
6926 g_hash_table_insert (modifier->data.source_files, s2, s2);
6930 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
6931 int n = decode_int (p, &p, end);
6934 modifier = &req->modifiers [i];
6935 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
6936 for (j = 0; j < n; ++j) {
6937 char *s = decode_string (p, &p, end);
6940 g_hash_table_insert (modifier->data.type_names, s, s);
6944 return ERR_NOT_IMPLEMENTED;
6948 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
6951 req->info = set_breakpoint (method, location, req, &error);
6952 if (!mono_error_ok (&error)) {
6954 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
6955 mono_error_cleanup (&error);
6956 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
6958 } else if (req->event_kind == EVENT_KIND_STEP) {
6959 g_assert (step_thread_id);
6961 err = get_object (step_thread_id, (MonoObject**)&step_thread);
6967 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
6972 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
6973 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
6974 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
6975 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
6976 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
6977 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
6979 if (req->nmodifiers) {
6981 return ERR_NOT_IMPLEMENTED;
6985 mono_loader_lock ();
6986 g_ptr_array_add (event_requests, req);
6988 if (agent_config.defer) {
6989 /* Transmit cached data to the client on receipt of the event request */
6990 switch (req->event_kind) {
6991 case EVENT_KIND_APPDOMAIN_CREATE:
6992 /* Emit load events for currently loaded domains */
6993 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
6995 case EVENT_KIND_ASSEMBLY_LOAD:
6996 /* Emit load events for currently loaded assemblies */
6997 mono_assembly_foreach (emit_assembly_load, NULL);
6999 case EVENT_KIND_THREAD_START:
7000 /* Emit start events for currently started threads */
7001 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7003 case EVENT_KIND_TYPE_LOAD:
7004 /* Emit type load events for currently loaded types */
7005 mono_domain_foreach (send_types_for_domain, NULL);
7011 mono_loader_unlock ();
7013 buffer_add_int (buf, req->id);
7016 case CMD_EVENT_REQUEST_CLEAR: {
7017 int etype = decode_byte (p, &p, end);
7018 int req_id = decode_int (p, &p, end);
7020 // FIXME: Make a faster mapping from req_id to request
7021 mono_loader_lock ();
7022 clear_event_request (req_id, etype);
7023 mono_loader_unlock ();
7026 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7029 mono_loader_lock ();
7031 while (i < event_requests->len) {
7032 EventRequest *req = g_ptr_array_index (event_requests, i);
7034 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7035 clear_breakpoint (req->info);
7037 g_ptr_array_remove_index_fast (event_requests, i);
7043 mono_loader_unlock ();
7047 return ERR_NOT_IMPLEMENTED;
7054 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7060 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7061 buffer_add_domainid (buf, mono_get_root_domain ());
7064 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7065 domain = decode_domainid (p, &p, end, NULL, &err);
7068 buffer_add_string (buf, domain->friendly_name);
7071 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7076 domain = decode_domainid (p, &p, end, NULL, &err);
7079 mono_loader_lock ();
7081 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7084 buffer_add_int (buf, count);
7085 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7087 buffer_add_assemblyid (buf, domain, ass);
7089 mono_loader_unlock ();
7092 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7093 domain = decode_domainid (p, &p, end, NULL, &err);
7097 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7100 case CMD_APPDOMAIN_GET_CORLIB: {
7101 domain = decode_domainid (p, &p, end, NULL, &err);
7105 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7108 case CMD_APPDOMAIN_CREATE_STRING: {
7112 domain = decode_domainid (p, &p, end, NULL, &err);
7115 s = decode_string (p, &p, end);
7117 o = mono_string_new (domain, s);
7118 buffer_add_objid (buf, (MonoObject*)o);
7121 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7123 MonoDomain *domain2;
7126 domain = decode_domainid (p, &p, end, NULL, &err);
7129 klass = decode_typeid (p, &p, end, &domain2, &err);
7134 g_assert (domain == domain2);
7136 o = mono_object_new (domain, klass);
7138 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
7142 buffer_add_objid (buf, o);
7146 return ERR_NOT_IMPLEMENTED;
7153 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7159 ass = decode_assemblyid (p, &p, end, &domain, &err);
7164 case CMD_ASSEMBLY_GET_LOCATION: {
7165 buffer_add_string (buf, mono_image_get_filename (ass->image));
7168 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7172 if (ass->image->dynamic) {
7173 buffer_add_id (buf, 0);
7175 token = mono_image_get_entry_point (ass->image);
7177 buffer_add_id (buf, 0);
7179 m = mono_get_method (ass->image, token, NULL);
7180 buffer_add_methodid (buf, domain, m);
7185 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7186 buffer_add_moduleid (buf, domain, ass->image);
7189 case CMD_ASSEMBLY_GET_OBJECT: {
7190 MonoObject *o = (MonoObject*)mono_assembly_get_object (domain, ass);
7191 buffer_add_objid (buf, o);
7194 case CMD_ASSEMBLY_GET_TYPE: {
7195 char *s = decode_string (p, &p, end);
7196 gboolean ignorecase = decode_byte (p, &p, end);
7197 MonoTypeNameParse info;
7199 gboolean type_resolve, res;
7200 MonoDomain *d = mono_domain_get ();
7202 /* This is needed to be able to find referenced assemblies */
7203 res = mono_domain_set (domain, FALSE);
7206 if (!mono_reflection_parse_type (s, &info)) {
7209 if (info.assembly.name)
7211 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
7213 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
7214 mono_reflection_free_type_info (&info);
7217 mono_domain_set (d, TRUE);
7221 case CMD_ASSEMBLY_GET_NAME: {
7223 MonoAssembly *mass = ass;
7225 name = g_strdup_printf (
7226 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7228 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7229 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7230 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7231 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7233 buffer_add_string (buf, name);
7238 return ERR_NOT_IMPLEMENTED;
7245 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7251 case CMD_MODULE_GET_INFO: {
7252 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7255 basename = g_path_get_basename (image->name);
7256 buffer_add_string (buf, basename); // name
7257 buffer_add_string (buf, image->module_name); // scopename
7258 buffer_add_string (buf, image->name); // fqname
7259 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7260 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7265 return ERR_NOT_IMPLEMENTED;
7272 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7274 if (val && val->vtable->klass == mono_defaults.monotype_class) {
7275 /* Special case these so the client doesn't have to handle Type objects */
7277 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7278 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7279 } else if (MONO_TYPE_IS_REFERENCE (t))
7280 buffer_add_value (buf, t, &val, domain);
7282 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7286 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7292 buffer_add_int (buf, 0);
7296 for (i = 0; i < cinfo->num_attrs; ++i) {
7297 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7300 buffer_add_int (buf, nattrs);
7302 for (i = 0; i < cinfo->num_attrs; ++i) {
7303 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7304 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7305 MonoArray *typed_args, *named_args;
7307 CattrNamedArg *arginfo;
7309 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo);
7311 buffer_add_methodid (buf, domain, attr->ctor);
7315 buffer_add_int (buf, mono_array_length (typed_args));
7316 for (j = 0; j < mono_array_length (typed_args); ++j) {
7317 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7319 t = mono_method_signature (attr->ctor)->params [j];
7321 buffer_add_cattr_arg (buf, t, domain, val);
7324 buffer_add_int (buf, 0);
7329 buffer_add_int (buf, mono_array_length (named_args));
7331 for (j = 0; j < mono_array_length (named_args); ++j) {
7332 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7334 if (arginfo [j].prop) {
7335 buffer_add_byte (buf, 0x54);
7336 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7337 } else if (arginfo [j].field) {
7338 buffer_add_byte (buf, 0x53);
7339 buffer_add_fieldid (buf, domain, arginfo [j].field);
7341 g_assert_not_reached ();
7344 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7347 buffer_add_int (buf, 0);
7353 /* FIXME: Code duplication with icall.c */
7355 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7360 mono_class_setup_interfaces (klass, error);
7361 if (!mono_error_ok (error))
7364 for (i = 0; i < klass->interface_count; i++) {
7365 ic = klass->interfaces [i];
7366 g_hash_table_insert (ifaces, ic, ic);
7368 collect_interfaces (ic, ifaces, error);
7369 if (!mono_error_ok (error))
7375 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7385 case CMD_TYPE_GET_INFO: {
7386 buffer_add_string (buf, klass->name_space);
7387 buffer_add_string (buf, klass->name);
7389 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7390 buffer_add_string (buf, name);
7392 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7393 buffer_add_moduleid (buf, domain, klass->image);
7394 buffer_add_typeid (buf, domain, klass->parent);
7395 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7396 buffer_add_typeid (buf, domain, klass->element_class);
7398 buffer_add_id (buf, 0);
7399 buffer_add_int (buf, klass->type_token);
7400 buffer_add_byte (buf, klass->rank);
7401 buffer_add_int (buf, klass->flags);
7403 type = &klass->byval_arg;
7404 // FIXME: Can't decide whenever a class represents a byref type
7407 if (type->type == MONO_TYPE_PTR)
7409 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7411 if (type->type == MONO_TYPE_VALUETYPE)
7413 if (klass->enumtype)
7415 if (klass->generic_container)
7417 if (klass->generic_container || klass->generic_class)
7419 buffer_add_byte (buf, b);
7422 while ((nested = mono_class_get_nested_types (klass, &iter)))
7424 buffer_add_int (buf, nnested);
7426 while ((nested = mono_class_get_nested_types (klass, &iter)))
7427 buffer_add_typeid (buf, domain, nested);
7428 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7429 if (klass->generic_container)
7430 buffer_add_typeid (buf, domain, klass);
7431 else if (klass->generic_class)
7432 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7434 buffer_add_id (buf, 0);
7436 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7439 if (klass->generic_class) {
7440 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7442 count = inst->type_argc;
7443 buffer_add_int (buf, count);
7444 for (i = 0; i < count; i++)
7445 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7446 } else if (klass->generic_container) {
7447 MonoGenericContainer *container = klass->generic_container;
7450 count = container->type_argc;
7451 buffer_add_int (buf, count);
7452 for (i = 0; i < count; i++) {
7453 pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
7454 buffer_add_typeid (buf, domain, pklass);
7457 buffer_add_int (buf, 0);
7462 case CMD_TYPE_GET_METHODS: {
7465 gpointer iter = NULL;
7468 mono_class_setup_methods (klass);
7470 nmethods = mono_class_num_methods (klass);
7472 buffer_add_int (buf, nmethods);
7474 while ((m = mono_class_get_methods (klass, &iter))) {
7475 buffer_add_methodid (buf, domain, m);
7478 g_assert (i == nmethods);
7481 case CMD_TYPE_GET_FIELDS: {
7484 gpointer iter = NULL;
7487 nfields = mono_class_num_fields (klass);
7489 buffer_add_int (buf, nfields);
7491 while ((f = mono_class_get_fields (klass, &iter))) {
7492 buffer_add_fieldid (buf, domain, f);
7493 buffer_add_string (buf, f->name);
7494 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7495 buffer_add_int (buf, f->type->attrs);
7498 g_assert (i == nfields);
7501 case CMD_TYPE_GET_PROPERTIES: {
7504 gpointer iter = NULL;
7507 nprops = mono_class_num_properties (klass);
7509 buffer_add_int (buf, nprops);
7511 while ((p = mono_class_get_properties (klass, &iter))) {
7512 buffer_add_propertyid (buf, domain, p);
7513 buffer_add_string (buf, p->name);
7514 buffer_add_methodid (buf, domain, p->get);
7515 buffer_add_methodid (buf, domain, p->set);
7516 buffer_add_int (buf, p->attrs);
7519 g_assert (i == nprops);
7522 case CMD_TYPE_GET_CATTRS: {
7523 MonoClass *attr_klass;
7524 MonoCustomAttrInfo *cinfo;
7526 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7527 /* attr_klass can be NULL */
7531 cinfo = mono_custom_attrs_from_class (klass);
7533 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7536 case CMD_TYPE_GET_FIELD_CATTRS: {
7537 MonoClass *attr_klass;
7538 MonoCustomAttrInfo *cinfo;
7539 MonoClassField *field;
7541 field = decode_fieldid (p, &p, end, NULL, &err);
7544 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7548 cinfo = mono_custom_attrs_from_field (klass, field);
7550 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7553 case CMD_TYPE_GET_PROPERTY_CATTRS: {
7554 MonoClass *attr_klass;
7555 MonoCustomAttrInfo *cinfo;
7558 prop = decode_propertyid (p, &p, end, NULL, &err);
7561 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7565 cinfo = mono_custom_attrs_from_property (klass, prop);
7567 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7570 case CMD_TYPE_GET_VALUES:
7571 case CMD_TYPE_GET_VALUES_2: {
7578 MonoThread *thread_obj;
7579 MonoInternalThread *thread = NULL;
7580 guint32 special_static_type;
7582 if (command == CMD_TYPE_GET_VALUES_2) {
7583 int objid = decode_objid (p, &p, end);
7586 err = get_object (objid, (MonoObject**)&thread_obj);
7590 thread = THREAD_TO_INTERNAL (thread_obj);
7593 len = decode_int (p, &p, end);
7594 for (i = 0; i < len; ++i) {
7595 f = decode_fieldid (p, &p, end, NULL, &err);
7599 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7600 return ERR_INVALID_FIELDID;
7601 special_static_type = mono_class_field_get_special_static_type (f);
7602 if (special_static_type != SPECIAL_STATIC_NONE) {
7603 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
7604 return ERR_INVALID_FIELDID;
7607 /* Check that the field belongs to the object */
7609 for (k = klass; k; k = k->parent) {
7610 if (k == f->parent) {
7616 return ERR_INVALID_FIELDID;
7618 vtable = mono_class_vtable (domain, f->parent);
7619 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7620 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
7621 buffer_add_value (buf, f->type, val, domain);
7626 case CMD_TYPE_SET_VALUES: {
7634 len = decode_int (p, &p, end);
7635 for (i = 0; i < len; ++i) {
7636 f = decode_fieldid (p, &p, end, NULL, &err);
7640 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7641 return ERR_INVALID_FIELDID;
7642 if (mono_class_field_is_special_static (f))
7643 return ERR_INVALID_FIELDID;
7645 /* Check that the field belongs to the object */
7647 for (k = klass; k; k = k->parent) {
7648 if (k == f->parent) {
7654 return ERR_INVALID_FIELDID;
7656 // FIXME: Check for literal/const
7658 vtable = mono_class_vtable (domain, f->parent);
7659 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7660 err = decode_value (f->type, domain, val, p, &p, end);
7665 if (MONO_TYPE_IS_REFERENCE (f->type))
7666 mono_field_static_set_value (vtable, f, *(gpointer*)val);
7668 mono_field_static_set_value (vtable, f, val);
7673 case CMD_TYPE_GET_OBJECT: {
7674 MonoObject *o = (MonoObject*)mono_type_get_object (domain, &klass->byval_arg);
7675 buffer_add_objid (buf, o);
7678 case CMD_TYPE_GET_SOURCE_FILES:
7679 case CMD_TYPE_GET_SOURCE_FILES_2: {
7680 char *source_file, *base;
7684 files = get_source_files_for_type (klass);
7686 buffer_add_int (buf, files->len);
7687 for (i = 0; i < files->len; ++i) {
7688 source_file = g_ptr_array_index (files, i);
7689 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
7690 buffer_add_string (buf, source_file);
7692 base = g_path_get_basename (source_file);
7693 buffer_add_string (buf, base);
7696 g_free (source_file);
7698 g_ptr_array_free (files, TRUE);
7701 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
7702 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
7706 if (mono_class_is_assignable_from (klass, oklass))
7707 buffer_add_byte (buf, 1);
7709 buffer_add_byte (buf, 0);
7712 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
7713 char *name = decode_string (p, &p, end);
7714 int i, flags = decode_int (p, &p, end);
7715 MonoException *ex = NULL;
7716 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
7719 return ERR_LOADER_ERROR;
7720 buffer_add_int (buf, array->len);
7721 for (i = 0; i < array->len; ++i) {
7722 MonoMethod *method = g_ptr_array_index (array, i);
7723 buffer_add_methodid (buf, domain, method);
7726 g_ptr_array_free (array, TRUE);
7730 case CMD_TYPE_GET_INTERFACES: {
7732 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
7734 MonoClass *tclass, *iface;
7735 GHashTableIter iter;
7739 for (parent = tclass; parent; parent = parent->parent) {
7740 mono_class_setup_interfaces (parent, &error);
7741 if (!mono_error_ok (&error))
7742 return ERR_LOADER_ERROR;
7743 collect_interfaces (parent, iface_hash, &error);
7744 if (!mono_error_ok (&error))
7745 return ERR_LOADER_ERROR;
7748 buffer_add_int (buf, g_hash_table_size (iface_hash));
7750 g_hash_table_iter_init (&iter, iface_hash);
7751 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
7752 buffer_add_typeid (buf, domain, iface);
7753 g_hash_table_destroy (iface_hash);
7756 case CMD_TYPE_GET_INTERFACE_MAP: {
7757 int tindex, ioffset;
7758 gboolean variance_used;
7760 int len, nmethods, i;
7764 len = decode_int (p, &p, end);
7765 mono_class_setup_vtable (klass);
7767 for (tindex = 0; tindex < len; ++tindex) {
7768 iclass = decode_typeid (p, &p, end, NULL, &err);
7772 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
7774 return ERR_INVALID_ARGUMENT;
7776 nmethods = mono_class_num_methods (iclass);
7777 buffer_add_int (buf, nmethods);
7780 while ((method = mono_class_get_methods (iclass, &iter))) {
7781 buffer_add_methodid (buf, domain, method);
7783 for (i = 0; i < nmethods; ++i)
7784 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
7788 case CMD_TYPE_IS_INITIALIZED: {
7789 MonoVTable *vtable = mono_class_vtable (domain, klass);
7792 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
7794 buffer_add_int (buf, 0);
7798 return ERR_NOT_IMPLEMENTED;
7805 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7808 MonoDomain *old_domain;
7812 klass = decode_typeid (p, &p, end, &domain, &err);
7816 old_domain = mono_domain_get ();
7818 mono_domain_set (domain, TRUE);
7820 err = type_commands_internal (command, klass, domain, p, end, buf);
7822 mono_domain_set (old_domain, TRUE);
7828 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7830 MonoMethodHeader *header;
7834 case CMD_METHOD_GET_NAME: {
7835 buffer_add_string (buf, method->name);
7838 case CMD_METHOD_GET_DECLARING_TYPE: {
7839 buffer_add_typeid (buf, domain, method->klass);
7842 case CMD_METHOD_GET_DEBUG_INFO: {
7843 MonoDebugMethodInfo *minfo;
7845 int i, j, n_il_offsets;
7848 int *column_numbers;
7850 GPtrArray *source_file_list;
7852 header = mono_method_get_header (method);
7854 buffer_add_int (buf, 0);
7855 buffer_add_string (buf, "");
7856 buffer_add_int (buf, 0);
7860 minfo = mono_debug_lookup_method (method);
7862 buffer_add_int (buf, header->code_size);
7863 buffer_add_string (buf, "");
7864 buffer_add_int (buf, 0);
7865 mono_metadata_free_mh (header);
7869 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, &n_il_offsets, &il_offsets, &line_numbers, &column_numbers, &source_files);
7870 buffer_add_int (buf, header->code_size);
7871 if (CHECK_PROTOCOL_VERSION (2, 13)) {
7872 buffer_add_int (buf, source_file_list->len);
7873 for (i = 0; i < source_file_list->len; ++i) {
7874 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
7875 buffer_add_string (buf, sinfo->source_file);
7876 if (CHECK_PROTOCOL_VERSION (2, 14)) {
7877 for (j = 0; j < 16; ++j)
7878 buffer_add_byte (buf, sinfo->hash [j]);
7882 buffer_add_string (buf, source_file);
7884 buffer_add_int (buf, n_il_offsets);
7885 DEBUG (10, fprintf (log_file, "Line number table for method %s:\n", mono_method_full_name (method, TRUE)));
7886 for (i = 0; i < n_il_offsets; ++i) {
7887 const char *srcfile = "";
7889 if (source_files [i] != -1) {
7890 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
7891 srcfile = sinfo->source_file;
7893 DEBUG (10, fprintf (log_file, "IL%x -> %s:%d %d\n", il_offsets [i], srcfile, line_numbers [i], column_numbers ? column_numbers [i] : -1));
7894 buffer_add_int (buf, il_offsets [i]);
7895 buffer_add_int (buf, line_numbers [i]);
7896 if (CHECK_PROTOCOL_VERSION (2, 13))
7897 buffer_add_int (buf, source_files [i]);
7898 if (CHECK_PROTOCOL_VERSION (2, 19))
7899 buffer_add_int (buf, column_numbers ? column_numbers [i] : -1);
7901 g_free (source_file);
7902 g_free (il_offsets);
7903 g_free (line_numbers);
7904 g_free (source_files);
7905 g_ptr_array_free (source_file_list, TRUE);
7906 mono_metadata_free_mh (header);
7909 case CMD_METHOD_GET_PARAM_INFO: {
7910 MonoMethodSignature *sig = mono_method_signature (method);
7914 /* FIXME: mono_class_from_mono_type () and byrefs */
7916 /* FIXME: Use a smaller encoding */
7917 buffer_add_int (buf, sig->call_convention);
7918 buffer_add_int (buf, sig->param_count);
7919 buffer_add_int (buf, sig->generic_param_count);
7920 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
7921 for (i = 0; i < sig->param_count; ++i) {
7923 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
7926 /* Emit parameter names */
7927 names = g_new (char *, sig->param_count);
7928 mono_method_get_param_names (method, (const char **) names);
7929 for (i = 0; i < sig->param_count; ++i)
7930 buffer_add_string (buf, names [i]);
7935 case CMD_METHOD_GET_LOCALS_INFO: {
7936 int i, j, num_locals;
7937 MonoDebugLocalsInfo *locals;
7939 header = mono_method_get_header (method);
7941 return ERR_INVALID_ARGUMENT;
7943 buffer_add_int (buf, header->num_locals);
7946 for (i = 0; i < header->num_locals; ++i)
7947 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
7950 locals = mono_debug_lookup_locals (method);
7952 num_locals = locals->num_locals;
7955 for (i = 0; i < header->num_locals; ++i) {
7956 for (j = 0; j < num_locals; ++j)
7957 if (locals->locals [j].index == i)
7960 buffer_add_string (buf, locals->locals [j].name);
7962 buffer_add_string (buf, "");
7966 for (i = 0; i < header->num_locals; ++i) {
7967 for (j = 0; j < num_locals; ++j)
7968 if (locals->locals [j].index == i)
7970 if (j < num_locals && locals->locals [j].block) {
7971 buffer_add_int (buf, locals->locals [j].block->start_offset);
7972 buffer_add_int (buf, locals->locals [j].block->end_offset);
7974 buffer_add_int (buf, 0);
7975 buffer_add_int (buf, header->code_size);
7978 mono_metadata_free_mh (header);
7981 mono_debug_symfile_free_locals (locals);
7985 case CMD_METHOD_GET_INFO:
7986 buffer_add_int (buf, method->flags);
7987 buffer_add_int (buf, method->iflags);
7988 buffer_add_int (buf, method->token);
7989 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7991 if (method->is_generic)
7993 if (mono_method_signature (method)->generic_param_count)
7995 buffer_add_byte (buf, attrs);
7996 if (method->is_generic || method->is_inflated) {
7999 if (method->is_generic) {
8002 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8004 result = imethod->declaring;
8005 if (imethod->context.class_inst) {
8006 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8007 /*Generic methods gets the context of the GTD.*/
8008 if (mono_class_get_context (klass))
8009 result = mono_class_inflate_generic_method_full (result, klass, mono_class_get_context (klass));
8013 buffer_add_methodid (buf, domain, result);
8015 buffer_add_id (buf, 0);
8017 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8018 if (mono_method_signature (method)->generic_param_count) {
8021 if (method->is_inflated) {
8022 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
8024 count = inst->type_argc;
8025 buffer_add_int (buf, count);
8027 for (i = 0; i < count; i++)
8028 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8030 buffer_add_int (buf, 0);
8032 } else if (method->is_generic) {
8033 MonoGenericContainer *container = mono_method_get_generic_container (method);
8035 count = mono_method_signature (method)->generic_param_count;
8036 buffer_add_int (buf, count);
8037 for (i = 0; i < count; i++) {
8038 MonoGenericParam *param = mono_generic_container_get_param (container, i);
8039 MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
8040 buffer_add_typeid (buf, domain, pklass);
8043 buffer_add_int (buf, 0);
8046 buffer_add_int (buf, 0);
8051 case CMD_METHOD_GET_BODY: {
8054 header = mono_method_get_header (method);
8056 buffer_add_int (buf, 0);
8058 if (CHECK_PROTOCOL_VERSION (2, 18))
8059 buffer_add_int (buf, 0);
8061 buffer_add_int (buf, header->code_size);
8062 for (i = 0; i < header->code_size; ++i)
8063 buffer_add_byte (buf, header->code [i]);
8065 if (CHECK_PROTOCOL_VERSION (2, 18)) {
8066 buffer_add_int (buf, header->num_clauses);
8067 for (i = 0; i < header->num_clauses; ++i) {
8068 MonoExceptionClause *clause = &header->clauses [i];
8070 buffer_add_int (buf, clause->flags);
8071 buffer_add_int (buf, clause->try_offset);
8072 buffer_add_int (buf, clause->try_len);
8073 buffer_add_int (buf, clause->handler_offset);
8074 buffer_add_int (buf, clause->handler_len);
8075 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
8076 buffer_add_typeid (buf, domain, clause->data.catch_class);
8077 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8078 buffer_add_int (buf, clause->data.filter_offset);
8082 mono_metadata_free_mh (header);
8087 case CMD_METHOD_RESOLVE_TOKEN: {
8088 guint32 token = decode_int (p, &p, end);
8091 switch (mono_metadata_token_code (token)) {
8092 case MONO_TOKEN_STRING: {
8096 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
8099 s2 = mono_string_to_utf8 (s);
8101 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8102 buffer_add_string (buf, s2);
8108 MonoClass *handle_class;
8110 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8111 val = mono_method_get_wrapper_data (method, token);
8112 handle_class = mono_method_get_wrapper_data (method, token + 1);
8114 if (handle_class == NULL) {
8115 // Can't figure out the token type
8116 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8120 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
8124 if (handle_class == mono_defaults.typehandle_class) {
8125 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8126 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8127 buffer_add_typeid (buf, domain, (MonoClass *) val);
8129 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
8130 } else if (handle_class == mono_defaults.fieldhandle_class) {
8131 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8132 buffer_add_fieldid (buf, domain, val);
8133 } else if (handle_class == mono_defaults.methodhandle_class) {
8134 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8135 buffer_add_methodid (buf, domain, val);
8136 } else if (handle_class == mono_defaults.string_class) {
8139 s = mono_string_to_utf8 (val);
8140 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8141 buffer_add_string (buf, s);
8144 g_assert_not_reached ();
8151 case CMD_METHOD_GET_CATTRS: {
8152 MonoClass *attr_klass;
8153 MonoCustomAttrInfo *cinfo;
8155 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8156 /* attr_klass can be NULL */
8160 cinfo = mono_custom_attrs_from_method (method);
8162 buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
8165 case CMD_METHOD_MAKE_GENERIC_METHOD: {
8166 MonoType **type_argv;
8170 MonoGenericInst *ginst;
8171 MonoGenericContext tmp_context;
8172 MonoMethod *inflated;
8174 type_argc = decode_int (p, &p, end);
8175 type_argv = g_new0 (MonoType*, type_argc);
8176 for (i = 0; i < type_argc; ++i) {
8177 klass = decode_typeid (p, &p, end, &d, &err);
8184 return ERR_INVALID_ARGUMENT;
8186 type_argv [i] = &klass->byval_arg;
8188 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
8190 tmp_context.class_inst = method->klass->generic_class ? method->klass->generic_class->context.class_inst : NULL;
8191 tmp_context.method_inst = ginst;
8193 inflated = mono_class_inflate_generic_method (method, &tmp_context);
8194 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
8195 return ERR_INVALID_ARGUMENT;
8196 buffer_add_methodid (buf, domain, inflated);
8200 return ERR_NOT_IMPLEMENTED;
8207 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8210 MonoDomain *old_domain;
8214 method = decode_methodid (p, &p, end, &domain, &err);
8218 old_domain = mono_domain_get ();
8220 mono_domain_set (domain, TRUE);
8222 err = method_commands_internal (command, method, domain, p, end, buf);
8224 mono_domain_set (old_domain, TRUE);
8230 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8232 int objid = decode_objid (p, &p, end);
8234 MonoThread *thread_obj;
8235 MonoInternalThread *thread;
8237 err = get_object (objid, (MonoObject**)&thread_obj);
8241 thread = THREAD_TO_INTERNAL (thread_obj);
8244 case CMD_THREAD_GET_NAME: {
8246 gunichar2 *s = mono_thread_get_name (thread, &name_len);
8249 buffer_add_int (buf, 0);
8254 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
8256 buffer_add_int (buf, len);
8257 buffer_add_data (buf, (guint8*)name, len);
8262 case CMD_THREAD_GET_FRAME_INFO: {
8263 DebuggerTlsData *tls;
8264 int i, start_frame, length;
8266 // Wait for suspending if it already started
8267 // FIXME: Races with suspend_count
8268 while (!is_suspended ()) {
8270 wait_for_suspend ();
8274 wait_for_suspend ();
8275 if (!is_suspended ())
8276 return ERR_NOT_SUSPENDED;
8279 start_frame = decode_int (p, &p, end);
8280 length = decode_int (p, &p, end);
8282 if (start_frame != 0 || length != -1)
8283 return ERR_NOT_IMPLEMENTED;
8285 mono_loader_lock ();
8286 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8287 mono_loader_unlock ();
8290 compute_frame_info (thread, tls);
8292 buffer_add_int (buf, tls->frame_count);
8293 for (i = 0; i < tls->frame_count; ++i) {
8294 buffer_add_int (buf, tls->frames [i]->id);
8295 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
8296 buffer_add_int (buf, tls->frames [i]->il_offset);
8298 * Instead of passing the frame type directly to the client, we associate
8299 * it with the previous frame using a set of flags. This avoids lots of
8300 * conditional code in the client, since a frame whose type isn't
8301 * FRAME_TYPE_MANAGED has no method, location, etc.
8303 buffer_add_byte (buf, tls->frames [i]->flags);
8308 case CMD_THREAD_GET_STATE:
8309 buffer_add_int (buf, thread->state);
8311 case CMD_THREAD_GET_INFO:
8312 buffer_add_byte (buf, thread->threadpool_thread);
8314 case CMD_THREAD_GET_ID:
8315 buffer_add_long (buf, (guint64)(gsize)thread);
8317 case CMD_THREAD_GET_TID:
8318 buffer_add_long (buf, (guint64)thread->tid);
8321 return ERR_NOT_IMPLEMENTED;
8328 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8332 MonoThread *thread_obj;
8333 MonoInternalThread *thread;
8334 int pos, i, len, frame_idx;
8335 DebuggerTlsData *tls;
8337 MonoDebugMethodJitInfo *jit;
8338 MonoDebugVarInfo *var;
8339 MonoMethodSignature *sig;
8341 MonoMethodHeader *header;
8343 objid = decode_objid (p, &p, end);
8344 err = get_object (objid, (MonoObject**)&thread_obj);
8348 thread = THREAD_TO_INTERNAL (thread_obj);
8350 id = decode_id (p, &p, end);
8352 mono_loader_lock ();
8353 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8354 mono_loader_unlock ();
8357 for (i = 0; i < tls->frame_count; ++i) {
8358 if (tls->frames [i]->id == id)
8361 if (i == tls->frame_count)
8362 return ERR_INVALID_FRAMEID;
8365 frame = tls->frames [frame_idx];
8367 if (!frame->has_ctx)
8368 return ERR_ABSENT_INFORMATION;
8371 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
8372 if (!frame->jit && frame->api_method->is_inflated)
8373 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
8377 /* This could happen for aot images with no jit debug info */
8378 s = mono_method_full_name (frame->api_method, TRUE);
8379 DEBUG (1, fprintf (log_file, "[dbg] No debug information found for '%s'.\n", s));
8381 return ERR_ABSENT_INFORMATION;
8386 sig = mono_method_signature (frame->actual_method);
8388 if (!get_seq_points (frame->domain, frame->actual_method))
8390 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
8392 return ERR_ABSENT_INFORMATION;
8395 case CMD_STACK_FRAME_GET_VALUES: {
8396 len = decode_int (p, &p, end);
8397 header = mono_method_get_header (frame->actual_method);
8399 for (i = 0; i < len; ++i) {
8400 pos = decode_int (p, &p, end);
8405 g_assert (pos >= 0 && pos < jit->num_params);
8407 var = &jit->params [pos];
8409 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
8411 g_assert (pos >= 0 && pos < jit->num_locals);
8413 var = &jit->locals [pos];
8415 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
8418 mono_metadata_free_mh (header);
8421 case CMD_STACK_FRAME_GET_THIS: {
8422 if (frame->api_method->klass->valuetype) {
8423 if (!sig->hasthis) {
8424 MonoObject *p = NULL;
8425 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
8427 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8430 if (!sig->hasthis) {
8431 MonoObject *p = NULL;
8432 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
8434 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8439 case CMD_STACK_FRAME_SET_VALUES: {
8442 MonoDebugVarInfo *var;
8444 len = decode_int (p, &p, end);
8445 header = mono_method_get_header (frame->actual_method);
8447 for (i = 0; i < len; ++i) {
8448 pos = decode_int (p, &p, end);
8453 g_assert (pos >= 0 && pos < jit->num_params);
8455 t = sig->params [pos];
8456 var = &jit->params [pos];
8458 g_assert (pos >= 0 && pos < jit->num_locals);
8460 t = header->locals [pos];
8461 var = &jit->locals [pos];
8464 if (MONO_TYPE_IS_REFERENCE (t))
8465 val_buf = g_alloca (sizeof (MonoObject*));
8467 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
8468 err = decode_value (t, frame->domain, val_buf, p, &p, end);
8472 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_ctx);
8474 mono_metadata_free_mh (header);
8478 return ERR_NOT_IMPLEMENTED;
8485 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8488 int objid, err, index, len, i, esize;
8491 objid = decode_objid (p, &p, end);
8492 err = get_object (objid, (MonoObject**)&arr);
8497 case CMD_ARRAY_REF_GET_LENGTH:
8498 buffer_add_int (buf, arr->obj.vtable->klass->rank);
8500 buffer_add_int (buf, arr->max_length);
8501 buffer_add_int (buf, 0);
8503 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
8504 buffer_add_int (buf, arr->bounds [i].length);
8505 buffer_add_int (buf, arr->bounds [i].lower_bound);
8509 case CMD_ARRAY_REF_GET_VALUES:
8510 index = decode_int (p, &p, end);
8511 len = decode_int (p, &p, end);
8513 g_assert (index >= 0 && len >= 0);
8514 // Reordered to avoid integer overflow
8515 g_assert (!(index > arr->max_length - len));
8517 esize = mono_array_element_size (arr->obj.vtable->klass);
8518 for (i = index; i < index + len; ++i) {
8519 elem = (gpointer*)((char*)arr->vector + (i * esize));
8520 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
8523 case CMD_ARRAY_REF_SET_VALUES:
8524 index = decode_int (p, &p, end);
8525 len = decode_int (p, &p, end);
8527 g_assert (index >= 0 && len >= 0);
8528 // Reordered to avoid integer overflow
8529 g_assert (!(index > arr->max_length - len));
8531 esize = mono_array_element_size (arr->obj.vtable->klass);
8532 for (i = index; i < index + len; ++i) {
8533 elem = (gpointer*)((char*)arr->vector + (i * esize));
8535 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
8539 return ERR_NOT_IMPLEMENTED;
8546 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8551 int i, index, length;
8554 objid = decode_objid (p, &p, end);
8555 err = get_object (objid, (MonoObject**)&str);
8560 case CMD_STRING_REF_GET_VALUE:
8561 s = mono_string_to_utf8 (str);
8562 buffer_add_string (buf, s);
8565 case CMD_STRING_REF_GET_LENGTH:
8566 buffer_add_long (buf, mono_string_length (str));
8568 case CMD_STRING_REF_GET_CHARS:
8569 index = decode_long (p, &p, end);
8570 length = decode_long (p, &p, end);
8571 if (index > mono_string_length (str) - length)
8572 return ERR_INVALID_ARGUMENT;
8573 c = mono_string_chars (str) + index;
8574 for (i = 0; i < length; ++i)
8575 buffer_add_short (buf, c [i]);
8578 return ERR_NOT_IMPLEMENTED;
8585 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8594 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
8595 objid = decode_objid (p, &p, end);
8596 err = get_object (objid, &obj);
8598 buffer_add_int (buf, 1);
8600 buffer_add_int (buf, 0);
8604 objid = decode_objid (p, &p, end);
8605 err = get_object (objid, &obj);
8610 case CMD_OBJECT_REF_GET_TYPE:
8611 /* This handles transparent proxies too */
8612 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8614 case CMD_OBJECT_REF_GET_VALUES:
8615 len = decode_int (p, &p, end);
8617 for (i = 0; i < len; ++i) {
8618 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
8622 /* Check that the field belongs to the object */
8624 for (k = obj->vtable->klass; k; k = k->parent) {
8625 if (k == f->parent) {
8631 return ERR_INVALID_FIELDID;
8633 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8637 if (mono_class_field_is_special_static (f))
8638 return ERR_INVALID_FIELDID;
8640 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8641 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8642 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8643 mono_field_static_get_value (vtable, f, val);
8644 buffer_add_value (buf, f->type, val, obj->vtable->domain);
8647 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
8651 case CMD_OBJECT_REF_SET_VALUES:
8652 len = decode_int (p, &p, end);
8654 for (i = 0; i < len; ++i) {
8655 f = decode_fieldid (p, &p, end, NULL, &err);
8659 /* Check that the field belongs to the object */
8661 for (k = obj->vtable->klass; k; k = k->parent) {
8662 if (k == f->parent) {
8668 return ERR_INVALID_FIELDID;
8670 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8674 if (mono_class_field_is_special_static (f))
8675 return ERR_INVALID_FIELDID;
8677 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8678 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8680 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8681 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
8686 mono_field_static_set_value (vtable, f, val);
8689 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
8695 case CMD_OBJECT_REF_GET_ADDRESS:
8696 buffer_add_long (buf, (gssize)obj);
8698 case CMD_OBJECT_REF_GET_DOMAIN:
8699 buffer_add_domainid (buf, obj->vtable->domain);
8701 case CMD_OBJECT_REF_GET_INFO:
8702 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8703 buffer_add_domainid (buf, obj->vtable->domain);
8706 return ERR_NOT_IMPLEMENTED;
8713 command_set_to_string (CommandSet command_set)
8715 switch (command_set) {
8718 case CMD_SET_OBJECT_REF:
8719 return "OBJECT_REF";
8720 case CMD_SET_STRING_REF:
8721 return "STRING_REF";
8722 case CMD_SET_THREAD:
8724 case CMD_SET_ARRAY_REF:
8726 case CMD_SET_EVENT_REQUEST:
8727 return "EVENT_REQUEST";
8728 case CMD_SET_STACK_FRAME:
8729 return "STACK_FRAME";
8730 case CMD_SET_APPDOMAIN:
8732 case CMD_SET_ASSEMBLY:
8734 case CMD_SET_METHOD:
8738 case CMD_SET_MODULE:
8748 cmd_to_string (CommandSet set, int command)
8753 case CMD_VM_VERSION:
8755 case CMD_VM_ALL_THREADS:
8756 return "ALL_THREADS";
8757 case CMD_VM_SUSPEND:
8763 case CMD_VM_DISPOSE:
8765 case CMD_VM_INVOKE_METHOD:
8766 return "INVOKE_METHOD";
8767 case CMD_VM_SET_PROTOCOL_VERSION:
8768 return "SET_PROTOCOL_VERSION";
8769 case CMD_VM_ABORT_INVOKE:
8770 return "ABORT_INVOKE";
8771 case CMD_VM_SET_KEEPALIVE:
8772 return "SET_KEEPALIVE";
8785 wait_for_attach (void)
8787 #ifndef DISABLE_SOCKET_TRANSPORT
8788 if (listen_fd == -1) {
8789 DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
8793 /* Block and wait for client connection */
8794 conn_fd = socket_transport_accept (listen_fd);
8795 DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
8796 if (conn_fd == -1) {
8797 DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
8801 g_assert_not_reached ();
8805 disconnected = !transport_handshake ();
8807 DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
8817 * This thread handles communication with the debugger client using a JDWP
8820 static guint32 WINAPI
8821 debugger_thread (void *arg)
8823 int res, len, id, flags, command_set = 0, command = 0;
8824 guint8 header [HEADER_LENGTH];
8825 guint8 *data, *p, *end;
8829 gboolean attach_failed = FALSE;
8831 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
8833 debugger_thread_id = GetCurrentThreadId ();
8835 mono_jit_thread_attach (mono_get_root_domain ());
8837 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
8839 mono_set_is_debugger_attached (TRUE);
8841 if (agent_config.defer) {
8842 if (!wait_for_attach ()) {
8843 DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
8844 attach_failed = TRUE; // Don't abort process when we can't listen
8846 /* Send start event to client */
8847 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
8851 while (!attach_failed) {
8852 res = transport_recv (header, HEADER_LENGTH);
8854 /* This will break if the socket is closed during shutdown too */
8855 if (res != HEADER_LENGTH) {
8856 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH));
8861 end = header + HEADER_LENGTH;
8863 len = decode_int (p, &p, end);
8864 id = decode_int (p, &p, end);
8865 flags = decode_byte (p, &p, end);
8866 command_set = decode_byte (p, &p, end);
8867 command = decode_byte (p, &p, end);
8869 g_assert (flags == 0);
8872 const char *cmd_str;
8875 cmd_str = cmd_to_string (command_set, command);
8877 sprintf (cmd_num, "%d", command);
8881 DEBUG (1, fprintf (log_file, "[dbg] Received command %s(%s), id=%d.\n", command_set_to_string (command_set), cmd_str, id));
8884 data = g_malloc (len - HEADER_LENGTH);
8885 if (len - HEADER_LENGTH > 0)
8887 res = transport_recv (data, len - HEADER_LENGTH);
8888 if (res != len - HEADER_LENGTH) {
8889 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH));
8895 end = data + (len - HEADER_LENGTH);
8897 buffer_init (&buf, 128);
8902 /* Process the request */
8903 switch (command_set) {
8905 err = vm_commands (command, id, p, end, &buf);
8906 if (!err && command == CMD_VM_INVOKE_METHOD)
8907 /* Sent after the invoke is complete */
8910 case CMD_SET_EVENT_REQUEST:
8911 err = event_commands (command, p, end, &buf);
8913 case CMD_SET_APPDOMAIN:
8914 err = domain_commands (command, p, end, &buf);
8916 case CMD_SET_ASSEMBLY:
8917 err = assembly_commands (command, p, end, &buf);
8919 case CMD_SET_MODULE:
8920 err = module_commands (command, p, end, &buf);
8923 err = type_commands (command, p, end, &buf);
8925 case CMD_SET_METHOD:
8926 err = method_commands (command, p, end, &buf);
8928 case CMD_SET_THREAD:
8929 err = thread_commands (command, p, end, &buf);
8931 case CMD_SET_STACK_FRAME:
8932 err = frame_commands (command, p, end, &buf);
8934 case CMD_SET_ARRAY_REF:
8935 err = array_commands (command, p, end, &buf);
8937 case CMD_SET_STRING_REF:
8938 err = string_commands (command, p, end, &buf);
8940 case CMD_SET_OBJECT_REF:
8941 err = object_commands (command, p, end, &buf);
8944 err = ERR_NOT_IMPLEMENTED;
8948 send_reply_packet (id, err, &buf);
8953 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
8957 mono_set_is_debugger_attached (FALSE);
8959 mono_mutex_lock (&debugger_thread_exited_mutex);
8960 debugger_thread_exited = TRUE;
8961 mono_cond_signal (&debugger_thread_exited_cond);
8962 mono_mutex_unlock (&debugger_thread_exited_mutex);
8964 DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
8966 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
8967 DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
8968 start_debugger_thread ();
8974 #else /* DISABLE_DEBUGGER_AGENT */
8977 mono_debugger_agent_parse_options (char *options)
8979 g_error ("This runtime is configured with the debugger agent disabled.");
8983 mono_debugger_agent_init (void)
8988 mono_debugger_agent_breakpoint_hit (void *sigctx)
8993 mono_debugger_agent_single_step_event (void *sigctx)
8998 mono_debugger_agent_free_domain_info (MonoDomain *domain)
9003 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
9009 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
9010 MonoContext *catch_ctx)
9015 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9020 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9025 mono_debugger_agent_user_break (void)
9031 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
9036 mono_debugger_agent_debug_log_is_enabled (void)