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)
2212 klass = decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2213 if (G_UNLIKELY (log_level >= 2) && klass) {
2216 s = mono_type_full_name (&klass->byval_arg);
2217 DEBUG(2, fprintf (log_file, "[dbg] recv class [%s]\n", s));
2223 static inline MonoAssembly*
2224 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2226 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2229 static inline MonoImage*
2230 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2232 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2235 static inline MonoMethod*
2236 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2240 m = decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2241 if (G_UNLIKELY (log_level >= 2) && m) {
2244 s = mono_method_full_name (m, TRUE);
2245 DEBUG(2, fprintf (log_file, "[dbg] recv method [%s]\n", s));
2251 static inline MonoClassField*
2252 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2254 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2257 static inline MonoDomain*
2258 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2260 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2263 static inline MonoProperty*
2264 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2266 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2270 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2272 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2273 if (G_UNLIKELY (log_level >= 2) && klass) {
2276 s = mono_type_full_name (&klass->byval_arg);
2277 if (GetCurrentThreadId () == debugger_thread_id)
2278 DEBUG(2, fprintf (log_file, "[dbg] send class [%s]\n", s));
2280 DEBUG(2, fprintf (log_file, "[%p] send class [%s]\n", (gpointer)GetCurrentThreadId (), s));
2286 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2288 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2289 if (G_UNLIKELY (log_level >= 2) && method) {
2292 s = mono_method_full_name (method, 1);
2293 DEBUG(2, fprintf (log_file, "[dbg] send method [%s]\n", s));
2299 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2301 buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2305 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2307 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2311 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2313 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2317 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2319 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2323 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2325 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2328 static void invoke_method (void);
2335 * save_thread_context:
2337 * Set CTX as the current threads context which is used for computing stack traces.
2338 * This function is signal-safe.
2341 save_thread_context (MonoContext *ctx)
2343 DebuggerTlsData *tls;
2345 tls = mono_native_tls_get_value (debugger_tls_id);
2349 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2351 mono_thread_state_init_from_current (&tls->context);
2354 /* Number of threads suspended */
2356 * If this is equal to the size of thread_to_tls, the runtime is considered
2359 static gint32 threads_suspend_count;
2361 static mono_mutex_t suspend_mutex;
2363 /* Cond variable used to wait for suspend_count becoming 0 */
2364 static mono_cond_t suspend_cond;
2366 /* Semaphore used to wait for a thread becoming suspended */
2367 static MonoSemType suspend_sem;
2372 mono_mutex_init (&suspend_mutex);
2373 mono_cond_init (&suspend_cond, NULL);
2374 MONO_SEM_INIT (&suspend_sem, 0);
2379 StackFrameInfo last_frame;
2380 gboolean last_frame_set;
2383 } GetLastFrameUserData;
2386 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2388 GetLastFrameUserData *data = user_data;
2390 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
2393 if (!data->last_frame_set) {
2394 /* Store the last frame */
2395 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2396 data->last_frame_set = TRUE;
2399 /* Store the context/lmf for the frame above the last frame */
2400 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2401 data->lmf = info->lmf;
2409 * Process interruption of a thread. If SIGCTX is set, process the current thread. If
2410 * INFO is set, process the thread described by INFO.
2411 * This should be signal safe.
2414 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, void *sigctx, MonoJitInfo *ji)
2418 MonoNativeThreadId tid;
2421 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2422 * guarantee the signal handler will be called that many times. Instead of tracking
2423 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2424 * has been requested that hasn't been handled yet, otherwise we can have threads
2425 * refuse to die when VM_EXIT is called
2427 #if defined(__APPLE__)
2428 if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
2432 * We use interrupt_count to determine whenever this interrupt should be processed
2433 * by us or the normal interrupt processing code in the signal handler.
2434 * There is no race here with notify_thread (), since the signal is sent after
2435 * incrementing interrupt_count.
2437 if (tls->interrupt_count == 0)
2440 InterlockedDecrement (&tls->interrupt_count);
2444 ip = mono_arch_ip_from_context (sigctx);
2446 ip = MONO_CONTEXT_GET_IP (&info->suspend_state.ctx);
2451 tid = mono_thread_info_get_tid (info);
2453 tid = (MonoNativeThreadId)GetCurrentThreadId ();
2455 // FIXME: Races when the thread leaves managed code before hitting a single step
2459 /* Running managed code, will be suspended by the single step code */
2460 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, ji->method->name, ip));
2464 * Running native code, will be suspended when it returns to/enters
2465 * managed code. Treat it as already suspended.
2466 * This might interrupt the code in process_single_step_inner (), we use the
2467 * tls->suspending flag to avoid races when that happens.
2469 if (!tls->suspended && !tls->suspending) {
2471 GetLastFrameUserData data;
2473 // FIXME: printf is not signal safe, but this is only used during
2474 // debugger debugging
2476 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip));
2477 //save_thread_context (&ctx);
2480 /* Already terminated */
2483 tls->context.valid = FALSE;
2486 * We are in a difficult position: we want to be able to provide stack
2487 * traces for this thread, but we can't use the current ctx+lmf, since
2488 * the thread is still running, so it might return to managed code,
2489 * making these invalid.
2490 * So we start a stack walk and save the first frame, along with the
2491 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2492 * suspended when it returns to managed code, so the parent's ctx should
2495 data.last_frame_set = FALSE;
2497 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
2499 * Don't pass MONO_UNWIND_ACTUAL_METHOD, its not signal safe, and
2500 * get_last_frame () doesn't need it, the last frame cannot be a ginst
2501 * since we are not in a JITted method.
2503 mono_walk_stack_with_ctx (get_last_frame, &ctx, MONO_UNWIND_NONE, &data);
2505 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, &info->suspend_state, MONO_UNWIND_SIGNAL_SAFE, &data);
2507 if (data.last_frame_set) {
2508 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2509 res = mono_thread_state_init_from_monoctx (&tls->async_state, &ctx);
2511 mono_thread_state_init_from_monoctx (&tls->context, &ctx);
2514 memcpy (&tls->async_state.ctx, &data.ctx, sizeof (MonoContext));
2515 tls->async_state.unwind_data [MONO_UNWIND_DATA_LMF] = data.lmf;
2516 tls->async_state.unwind_data [MONO_UNWIND_DATA_JIT_TLS] = tls->thread->jit_data;
2518 /* No managed frames */
2519 tls->async_state.valid = FALSE;
2521 mono_memory_barrier ();
2523 tls->suspended = TRUE;
2524 MONO_SEM_POST (&suspend_sem);
2531 * mono_debugger_agent_thread_interrupt:
2533 * Called by the abort signal handler.
2534 * Should be signal safe.
2537 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
2539 DebuggerTlsData *tls;
2544 tls = mono_native_tls_get_value (debugger_tls_id);
2546 DEBUG (1, fprintf (log_file, "[%p] Received interrupt with no TLS, continuing.\n", (gpointer)GetCurrentThreadId ()));
2550 return thread_interrupt (tls, NULL, sigctx, ji);
2554 static void CALLBACK notify_thread_apc (ULONG_PTR param)
2557 mono_debugger_agent_thread_interrupt (NULL, NULL);
2559 #endif /* HOST_WIN32 */
2562 * reset_native_thread_suspend_state:
2564 * Reset the suspended flag and state on native threads
2567 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2569 DebuggerTlsData *tls = value;
2571 if (!tls->really_suspended && tls->suspended) {
2572 tls->suspended = FALSE;
2574 * The thread might still be running if it was executing native code, so the state won't be invalided by
2575 * suspend_current ().
2577 tls->context.valid = FALSE;
2578 tls->async_state.valid = FALSE;
2579 invalidate_frames (tls);
2586 * Notify a thread that it needs to suspend.
2589 notify_thread (gpointer key, gpointer value, gpointer user_data)
2591 MonoInternalThread *thread = key;
2592 DebuggerTlsData *tls = value;
2593 gsize tid = thread->tid;
2596 if (GetCurrentThreadId () == tid || tls->terminated)
2599 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2602 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2603 * guarantee the signal handler will be called that many times. Instead of tracking
2604 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2605 * has been requested that hasn't been handled yet, otherwise we can have threads
2606 * refuse to die when VM_EXIT is called
2608 #if defined(__APPLE__)
2609 if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
2613 * Maybe we could use the normal interrupt infrastructure, but that does a lot
2614 * of things like breaking waits etc. which we don't want.
2616 InterlockedIncrement (&tls->interrupt_count);
2619 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2621 QueueUserAPC (notify_thread_apc, thread->handle, NULL);
2623 if (mono_thread_info_new_interrupt_enabled ()) {
2624 MonoThreadInfo *info;
2627 info = mono_thread_info_safe_suspend_sync ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE);
2629 DEBUG(1, fprintf (log_file, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2631 * Attached thread which died without detaching.
2633 tls->terminated = TRUE;
2635 ji = mono_jit_info_table_find (info->suspend_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], MONO_CONTEXT_GET_IP (&info->suspend_state.ctx));
2637 thread_interrupt (tls, info, NULL, ji);
2639 mono_thread_info_resume (mono_thread_info_get_tid (info));
2642 res = mono_thread_kill (thread, mono_thread_get_abort_signal ());
2644 DEBUG(1, fprintf (log_file, "[%p] mono_thread_kill () failed for %p: %d...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid, res));
2646 * Attached thread which died without detaching.
2648 tls->terminated = TRUE;
2655 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2657 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2660 if (mono_loader_lock_is_owned_by_self ()) {
2662 * Shortcut for the check in suspend_current (). This speeds up processing
2663 * when executing long running code inside the loader lock, i.e. assembly load
2669 if (debugger_thread_id == GetCurrentThreadId ())
2672 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2673 if (suspend_count - tls->resume_count > 0)
2674 tls->suspending = TRUE;
2676 DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2678 if (suspend_count - tls->resume_count == 0) {
2680 * We are executing a single threaded invoke but the single step for
2681 * suspending is still active.
2682 * FIXME: This slows down single threaded invokes.
2684 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
2688 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2690 /* Can't suspend in these methods */
2691 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
2694 save_thread_context (ctx);
2702 * Increase the suspend count of the VM. While the suspend count is greater
2703 * than 0, runtime threads are suspended at certain points during execution.
2708 mono_loader_lock ();
2710 mono_mutex_lock (&suspend_mutex);
2714 DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
2716 if (suspend_count == 1) {
2717 // FIXME: Is it safe to call this inside the lock ?
2718 start_single_stepping ();
2719 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2722 mono_mutex_unlock (&suspend_mutex);
2724 if (suspend_count == 1)
2726 * Suspend creation of new threadpool threads, since they cannot run
2728 mono_thread_pool_suspend ();
2730 mono_loader_unlock ();
2736 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2744 g_assert (debugger_thread_id == GetCurrentThreadId ());
2746 mono_loader_lock ();
2748 mono_mutex_lock (&suspend_mutex);
2750 g_assert (suspend_count > 0);
2753 DEBUG(1, fprintf (log_file, "[%p] Resuming vm, suspend count=%d...\n", (gpointer)GetCurrentThreadId (), suspend_count));
2755 if (suspend_count == 0) {
2756 // FIXME: Is it safe to call this inside the lock ?
2757 stop_single_stepping ();
2758 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2761 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2762 err = mono_cond_broadcast (&suspend_cond);
2763 g_assert (err == 0);
2765 mono_mutex_unlock (&suspend_mutex);
2766 //g_assert (err == 0);
2768 if (suspend_count == 0)
2769 mono_thread_pool_resume ();
2771 mono_loader_unlock ();
2777 * Resume just one thread.
2780 resume_thread (MonoInternalThread *thread)
2783 DebuggerTlsData *tls;
2785 g_assert (debugger_thread_id == GetCurrentThreadId ());
2787 mono_loader_lock ();
2789 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2792 mono_mutex_lock (&suspend_mutex);
2794 g_assert (suspend_count > 0);
2796 DEBUG(1, fprintf (log_file, "[%p] Resuming thread...\n", (gpointer)(gssize)thread->tid));
2798 tls->resume_count += suspend_count;
2801 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2802 * but only the one whose resume_count field is > 0 will be resumed.
2804 err = mono_cond_broadcast (&suspend_cond);
2805 g_assert (err == 0);
2807 mono_mutex_unlock (&suspend_mutex);
2808 //g_assert (err == 0);
2810 mono_loader_unlock ();
2814 invalidate_frames (DebuggerTlsData *tls)
2819 tls = mono_native_tls_get_value (debugger_tls_id);
2822 for (i = 0; i < tls->frame_count; ++i) {
2823 if (tls->frames [i]->jit)
2824 mono_debug_free_method_jit_info (tls->frames [i]->jit);
2825 g_free (tls->frames [i]);
2827 g_free (tls->frames);
2828 tls->frame_count = 0;
2835 * Suspend the current thread until the runtime is resumed. If the thread has a
2836 * pending invoke, then the invoke is executed before this function returns.
2839 suspend_current (void)
2842 DebuggerTlsData *tls;
2844 g_assert (debugger_thread_id != GetCurrentThreadId ());
2846 if (mono_loader_lock_is_owned_by_self ()) {
2848 * If we own the loader mutex, can't suspend until we release it, since the
2849 * whole runtime can deadlock otherwise.
2854 tls = mono_native_tls_get_value (debugger_tls_id);
2857 mono_mutex_lock (&suspend_mutex);
2859 tls->suspending = FALSE;
2860 tls->really_suspended = TRUE;
2862 if (!tls->suspended) {
2863 tls->suspended = TRUE;
2864 MONO_SEM_POST (&suspend_sem);
2867 DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
2869 while (suspend_count - tls->resume_count > 0) {
2871 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
2873 mono_mutex_unlock (&suspend_mutex);
2875 mono_mutex_lock (&suspend_mutex);
2881 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
2882 g_assert (err == 0);
2886 tls->suspended = FALSE;
2887 tls->really_suspended = FALSE;
2889 threads_suspend_count --;
2891 mono_mutex_unlock (&suspend_mutex);
2893 DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
2895 if (tls->pending_invoke) {
2896 /* Save the original context */
2897 tls->pending_invoke->has_ctx = TRUE;
2898 tls->pending_invoke->ctx = tls->context.ctx;
2903 /* The frame info becomes invalid after a resume */
2904 tls->context.valid = FALSE;
2905 tls->async_state.valid = FALSE;
2906 invalidate_frames (tls);
2910 count_thread (gpointer key, gpointer value, gpointer user_data)
2912 DebuggerTlsData *tls = value;
2914 if (!tls->suspended && !tls->terminated)
2915 *(int*)user_data = *(int*)user_data + 1;
2919 count_threads_to_wait_for (void)
2923 mono_loader_lock ();
2924 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2925 mono_loader_unlock ();
2933 * Wait until the runtime is completely suspended.
2936 wait_for_suspend (void)
2938 int nthreads, nwait, err;
2939 gboolean waited = FALSE;
2941 // FIXME: Threads starting/stopping ?
2942 mono_loader_lock ();
2943 nthreads = mono_g_hash_table_size (thread_to_tls);
2944 mono_loader_unlock ();
2947 nwait = count_threads_to_wait_for ();
2949 DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
2950 err = MONO_SEM_WAIT (&suspend_sem);
2951 g_assert (err == 0);
2959 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
2965 * Return whenever the runtime is suspended.
2970 return count_threads_to_wait_for () == 0;
2973 static MonoSeqPointInfo*
2974 get_seq_points (MonoDomain *domain, MonoMethod *method)
2976 MonoSeqPointInfo *seq_points;
2978 mono_domain_lock (domain);
2979 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2980 if (!seq_points && method->is_inflated) {
2981 /* generic sharing + aot */
2982 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (method));
2984 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mini_get_shared_method (method));
2986 mono_domain_unlock (domain);
2992 no_seq_points_found (MonoMethod *method)
2995 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
2997 printf ("Unable to find seq points for method '%s'.\n", mono_method_full_name (method, TRUE));
3001 * find_next_seq_point_for_native_offset:
3003 * Find the first sequence point after NATIVE_OFFSET.
3006 find_next_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
3008 MonoSeqPointInfo *seq_points;
3011 seq_points = get_seq_points (domain, method);
3017 g_assert (seq_points);
3021 for (i = 0; i < seq_points->len; ++i) {
3022 if (seq_points->seq_points [i].native_offset >= native_offset)
3023 return &seq_points->seq_points [i];
3030 * find_prev_seq_point_for_native_offset:
3032 * Find the first sequence point before NATIVE_OFFSET.
3035 find_prev_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
3037 MonoSeqPointInfo *seq_points;
3040 seq_points = get_seq_points (domain, method);
3046 for (i = seq_points->len - 1; i >= 0; --i) {
3047 if (seq_points->seq_points [i].native_offset <= native_offset)
3048 return &seq_points->seq_points [i];
3057 * Find the sequence point corresponding to the IL offset IL_OFFSET, which
3058 * should be the location of a sequence point.
3060 static G_GNUC_UNUSED SeqPoint*
3061 find_seq_point (MonoDomain *domain, MonoMethod *method, gint32 il_offset, MonoSeqPointInfo **info)
3063 MonoSeqPointInfo *seq_points;
3068 seq_points = get_seq_points (domain, method);
3073 for (i = 0; i < seq_points->len; ++i) {
3074 if (seq_points->seq_points [i].il_offset == il_offset)
3075 return &seq_points->seq_points [i];
3082 DebuggerTlsData *tls;
3084 } ComputeFramesUserData;
3087 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3089 ComputeFramesUserData *ud = user_data;
3091 MonoMethod *method, *actual_method, *api_method;
3095 if (info->type != FRAME_TYPE_MANAGED) {
3096 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3097 /* Mark the last frame as an invoke frame */
3099 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3105 method = info->ji->method;
3107 method = info->method;
3108 actual_method = info->actual_method;
3109 api_method = method;
3114 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3117 if (info->il_offset == -1) {
3118 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3119 if (ud->frames == NULL) {
3120 sp = find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL);
3122 info->il_offset = sp->il_offset;
3124 if (info->il_offset == -1)
3125 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3128 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));
3130 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3131 if (!CHECK_PROTOCOL_VERSION (2, 17))
3132 /* Older clients can't handle this flag */
3134 api_method = mono_marshal_method_from_wrapper (method);
3137 actual_method = api_method;
3138 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3141 frame = g_new0 (StackFrame, 1);
3142 frame->method = method;
3143 frame->actual_method = actual_method;
3144 frame->api_method = api_method;
3145 frame->il_offset = info->il_offset;
3146 frame->native_offset = info->native_offset;
3147 frame->flags = flags;
3148 frame->ji = info->ji;
3149 if (info->reg_locations)
3150 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3153 frame->has_ctx = TRUE;
3155 frame->domain = info->domain;
3157 ud->frames = g_slist_append (ud->frames, frame);
3163 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3165 ComputeFramesUserData *ud = user_data;
3168 * 'tls->filter_ctx' is the location of the throw site.
3170 * mono_walk_stack() will never actually hit the throw site, but unwind
3171 * directly from the filter to the call site; we abort stack unwinding here
3172 * once this happens and resume from the throw site.
3175 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3178 return process_frame (info, ctx, user_data);
3182 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3184 ComputeFramesUserData user_data;
3186 int i, findex, new_frame_count;
3187 StackFrame **new_frames, *f;
3188 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3190 // FIXME: Locking on tls
3191 if (tls->frames && tls->frames_up_to_date)
3194 DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
3196 user_data.tls = tls;
3197 user_data.frames = NULL;
3198 if (tls->terminated) {
3199 tls->frame_count = 0;
3201 } if (!tls->really_suspended && tls->async_state.valid) {
3202 /* Have to use the state saved by the signal handler */
3203 process_frame (&tls->async_last_frame, NULL, &user_data);
3204 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3205 } else if (tls->filter_state.valid) {
3207 * We are inside an exception filter.
3209 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3211 if (tls->context.valid)
3212 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3214 * After that, we resume unwinding from the location where the exception has been thrown.
3216 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3217 } else if (tls->context.valid) {
3218 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3221 tls->frame_count = 0;
3225 new_frame_count = g_slist_length (user_data.frames);
3226 new_frames = g_new0 (StackFrame*, new_frame_count);
3228 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3232 * Reuse the id for already existing stack frames, so invokes don't invalidate
3233 * the still valid stack frames.
3235 for (i = 0; i < tls->frame_count; ++i) {
3236 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3237 f->id = tls->frames [i]->id;
3242 if (i >= tls->frame_count)
3243 f->id = InterlockedIncrement (&frame_id);
3245 new_frames [findex ++] = f;
3248 g_slist_free (user_data.frames);
3250 invalidate_frames (tls);
3252 tls->frames = new_frames;
3253 tls->frame_count = new_frame_count;
3254 tls->frames_up_to_date = TRUE;
3258 * GHFunc to emit an appdomain creation event
3259 * @param key Don't care
3260 * @param value A loaded appdomain
3261 * @param user_data Don't care
3264 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3266 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3267 g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
3271 * GHFunc to emit a thread start event
3272 * @param key A thread id
3273 * @param value A thread object
3274 * @param user_data Don't care
3277 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3279 if (GPOINTER_TO_INT (key) != debugger_thread_id)
3280 process_profiler_event (EVENT_KIND_THREAD_START, value);
3284 * GFunc to emit an assembly load event
3285 * @param value A loaded assembly
3286 * @param user_data Don't care
3289 emit_assembly_load (gpointer value, gpointer user_data)
3291 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3295 * GFunc to emit a type load event
3296 * @param value A loaded type
3297 * @param user_data Don't care
3300 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3302 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3306 strdup_tolower (char *s)
3311 for (p = s2; *p; ++p)
3321 * create_event_list:
3323 * Return a list of event request ids matching EVENT, starting from REQS, which
3324 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3326 * We return request ids, instead of requests, to simplify threading, since
3327 * requests could be deleted anytime when the loader lock is not held.
3328 * LOCKING: Assumes the loader lock is held.
3331 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3334 GSList *events = NULL;
3336 *suspend_policy = SUSPEND_POLICY_NONE;
3339 reqs = event_requests;
3344 for (i = 0; i < reqs->len; ++i) {
3345 EventRequest *req = g_ptr_array_index (reqs, i);
3346 if (req->event_kind == event) {
3347 gboolean filtered = FALSE;
3350 for (j = 0; j < req->nmodifiers; ++j) {
3351 Modifier *mod = &req->modifiers [j];
3353 if (mod->kind == MOD_KIND_COUNT) {
3355 if (mod->data.count > 0) {
3356 if (mod->data.count > 0) {
3358 if (mod->data.count == 0)
3362 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3363 if (mod->data.thread != mono_thread_internal_current ())
3365 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3366 if (mod->data.exc_class && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3368 if (ei->caught && !mod->caught)
3370 if (!ei->caught && !mod->uncaught)
3372 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3374 gboolean found = FALSE;
3375 MonoAssembly **assemblies = mod->data.assemblies;
3378 for (k = 0; assemblies [k]; ++k)
3379 if (assemblies [k] == ji->method->klass->image->assembly)
3384 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3385 gpointer iter = NULL;
3387 MonoDebugSourceInfo *sinfo;
3388 char *source_file, *s;
3389 gboolean found = FALSE;
3391 GPtrArray *source_file_list;
3393 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3394 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3397 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, NULL, NULL, NULL, NULL, NULL);
3398 for (i = 0; i < source_file_list->len; ++i) {
3399 sinfo = g_ptr_array_index (source_file_list, i);
3401 * Do a case-insesitive match by converting the file name to
3404 s = strdup_tolower (sinfo->source_file);
3405 if (g_hash_table_lookup (mod->data.source_files, s))
3408 char *s2 = g_path_get_basename (sinfo->source_file);
3409 char *s3 = strdup_tolower (s2);
3411 if (g_hash_table_lookup (mod->data.source_files, s3))
3418 g_ptr_array_free (source_file_list, TRUE);
3423 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3426 s = mono_type_full_name (&ei->klass->byval_arg);
3427 if (!g_hash_table_lookup (mod->data.type_names, s))
3430 } else if (mod->kind == MOD_KIND_STEP) {
3431 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3432 (ji->method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3433 !strcmp (ji->method->name, ".cctor"))
3435 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3436 MonoCustomAttrInfo *ainfo;
3437 static MonoClass *klass;
3440 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3443 if (!ji->dbg_hidden_inited) {
3444 ainfo = mono_custom_attrs_from_method (ji->method);
3446 if (mono_custom_attrs_has_attr (ainfo, klass))
3447 ji->dbg_hidden = TRUE;
3448 mono_custom_attrs_free (ainfo);
3450 ji->dbg_hidden_inited = TRUE;
3459 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3460 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3465 /* Send a VM START/DEATH event by default */
3466 if (event == EVENT_KIND_VM_START)
3467 events = g_slist_append (events, GINT_TO_POINTER (0));
3468 if (event == EVENT_KIND_VM_DEATH)
3469 events = g_slist_append (events, GINT_TO_POINTER (0));
3474 static G_GNUC_UNUSED const char*
3475 event_to_string (EventKind event)
3478 case EVENT_KIND_VM_START: return "VM_START";
3479 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3480 case EVENT_KIND_THREAD_START: return "THREAD_START";
3481 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3482 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3483 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3484 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3485 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3486 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3487 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3488 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3489 case EVENT_KIND_STEP: return "STEP";
3490 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3491 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3492 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3493 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3494 case EVENT_KIND_USER_LOG: return "USER_LOG";
3496 g_assert_not_reached ();
3504 * Send an event to the client, suspending the vm if needed.
3505 * LOCKING: Since this can suspend the calling thread, no locks should be held
3507 * The EVENTS list is freed by this function.
3510 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3514 MonoDomain *domain = mono_domain_get ();
3515 MonoThread *thread = NULL;
3516 MonoObject *keepalive_obj = NULL;
3517 gboolean send_success = FALSE;
3522 DEBUG (2, fprintf (log_file, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event)));
3526 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3527 // FIXME: We miss those events
3528 DEBUG (2, fprintf (log_file, "VM start event not sent yet: dropping %s\n", event_to_string (event)));
3532 if (vm_death_event_sent) {
3533 DEBUG (2, fprintf (log_file, "VM death event has been sent: dropping %s\n", event_to_string (event)));
3537 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3538 DEBUG (2, fprintf (log_file, "Mono runtime is shutting down: dropping %s\n", event_to_string (event)));
3543 DEBUG (2, fprintf (log_file, "Debugger client is not connected: dropping %s\n", event_to_string (event)));
3547 if (event == EVENT_KIND_KEEPALIVE)
3548 suspend_policy = SUSPEND_POLICY_NONE;
3553 if (agent_config.defer) {
3554 /* Make sure the thread id is always set when doing deferred debugging */
3555 if (debugger_thread_id == GetCurrentThreadId ()) {
3556 /* Don't suspend on events from the debugger thread */
3557 suspend_policy = SUSPEND_POLICY_NONE;
3558 thread = mono_thread_get_main ();
3560 else thread = mono_thread_current ();
3562 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3563 // FIXME: Send these with a NULL thread, don't suspend the current thread
3568 nevents = g_slist_length (events);
3569 buffer_init (&buf, 128);
3570 buffer_add_byte (&buf, suspend_policy);
3571 buffer_add_int (&buf, nevents);
3573 for (l = events; l; l = l->next) {
3574 buffer_add_byte (&buf, event); // event kind
3575 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3580 thread = mono_thread_current ();
3582 if (event == EVENT_KIND_VM_START && arg != NULL)
3585 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3588 case EVENT_KIND_THREAD_START:
3589 case EVENT_KIND_THREAD_DEATH:
3591 case EVENT_KIND_APPDOMAIN_CREATE:
3592 case EVENT_KIND_APPDOMAIN_UNLOAD:
3593 buffer_add_domainid (&buf, arg);
3595 case EVENT_KIND_METHOD_ENTRY:
3596 case EVENT_KIND_METHOD_EXIT:
3597 buffer_add_methodid (&buf, domain, arg);
3599 case EVENT_KIND_ASSEMBLY_LOAD:
3600 case EVENT_KIND_ASSEMBLY_UNLOAD:
3601 buffer_add_assemblyid (&buf, domain, arg);
3603 case EVENT_KIND_TYPE_LOAD:
3604 buffer_add_typeid (&buf, domain, arg);
3606 case EVENT_KIND_BREAKPOINT:
3607 case EVENT_KIND_STEP:
3608 buffer_add_methodid (&buf, domain, arg);
3609 buffer_add_long (&buf, il_offset);
3611 case EVENT_KIND_VM_START:
3612 buffer_add_domainid (&buf, mono_get_root_domain ());
3614 case EVENT_KIND_VM_DEATH:
3616 case EVENT_KIND_EXCEPTION: {
3617 EventInfo *ei = arg;
3618 buffer_add_objid (&buf, ei->exc);
3620 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3621 * later after the suspension. (#12494).
3623 keepalive_obj = ei->exc;
3626 case EVENT_KIND_USER_BREAK:
3628 case EVENT_KIND_USER_LOG: {
3629 EventInfo *ei = arg;
3630 buffer_add_int (&buf, ei->level);
3631 buffer_add_string (&buf, ei->category ? ei->category : "");
3632 buffer_add_string (&buf, ei->message ? ei->message : "");
3635 case EVENT_KIND_KEEPALIVE:
3636 suspend_policy = SUSPEND_POLICY_NONE;
3639 g_assert_not_reached ();
3643 if (event == EVENT_KIND_VM_START) {
3644 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3645 if (!agent_config.defer)
3646 start_debugger_thread ();
3649 if (event == EVENT_KIND_VM_DEATH) {
3650 vm_death_event_sent = TRUE;
3651 suspend_policy = SUSPEND_POLICY_NONE;
3654 if (mono_runtime_is_shutting_down ())
3655 suspend_policy = SUSPEND_POLICY_NONE;
3657 if (suspend_policy != SUSPEND_POLICY_NONE) {
3659 * Save the thread context and start suspending before sending the packet,
3660 * since we could be receiving the resume request before send_packet ()
3663 save_thread_context (ctx);
3667 /* This will keep this object alive */
3668 get_objref (keepalive_obj);
3671 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3675 g_slist_free (events);
3678 if (!send_success) {
3679 DEBUG (2, fprintf (log_file, "Sending command %s failed.\n", event_to_string (event)));
3683 if (event == EVENT_KIND_VM_START) {
3684 vm_start_event_sent = TRUE;
3687 DEBUG (1, fprintf (log_file, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer)GetCurrentThreadId (), nevents, event_to_string (event), ecount, suspend_policy));
3689 switch (suspend_policy) {
3690 case SUSPEND_POLICY_NONE:
3692 case SUSPEND_POLICY_ALL:
3695 case SUSPEND_POLICY_EVENT_THREAD:
3699 g_assert_not_reached ();
3704 process_profiler_event (EventKind event, gpointer arg)
3708 EventInfo ei, *ei_arg = NULL;
3710 if (event == EVENT_KIND_TYPE_LOAD) {
3715 mono_loader_lock ();
3716 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3717 mono_loader_unlock ();
3719 process_event (event, arg, 0, NULL, events, suspend_policy);
3723 runtime_initialized (MonoProfiler *prof)
3725 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3726 if (agent_config.defer)
3727 start_debugger_thread ();
3731 runtime_shutdown (MonoProfiler *prof)
3733 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3735 mono_debugger_agent_cleanup ();
3739 thread_startup (MonoProfiler *prof, uintptr_t tid)
3741 MonoInternalThread *thread = mono_thread_internal_current ();
3742 MonoInternalThread *old_thread;
3743 DebuggerTlsData *tls;
3745 if (tid == debugger_thread_id)
3748 g_assert (thread->tid == tid);
3750 mono_loader_lock ();
3751 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3752 mono_loader_unlock ();
3754 if (thread == old_thread) {
3756 * For some reason, thread_startup () might be called for the same thread
3757 * multiple times (attach ?).
3759 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
3763 * thread_end () might not be called for some threads, and the tid could
3766 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
3767 mono_loader_lock ();
3768 mono_g_hash_table_remove (thread_to_tls, old_thread);
3769 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3770 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3771 mono_loader_unlock ();
3775 tls = mono_native_tls_get_value (debugger_tls_id);
3777 // FIXME: Free this somewhere
3778 tls = g_new0 (DebuggerTlsData, 1);
3779 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3780 tls->thread = thread;
3781 mono_native_tls_set_value (debugger_tls_id, tls);
3783 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3785 mono_loader_lock ();
3786 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3787 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3788 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3789 mono_loader_unlock ();
3791 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3794 * suspend_vm () could have missed this thread, so wait for a resume.
3800 thread_end (MonoProfiler *prof, uintptr_t tid)
3802 MonoInternalThread *thread;
3803 DebuggerTlsData *tls = NULL;
3805 mono_loader_lock ();
3806 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3808 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3809 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3811 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3812 tls->terminated = TRUE;
3813 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3814 MONO_GC_UNREGISTER_ROOT (tls->thread);
3818 mono_loader_unlock ();
3820 /* We might be called for threads started before we registered the start callback */
3822 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3823 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3828 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3830 mono_loader_lock ();
3831 g_hash_table_insert (domains, domain, domain);
3832 mono_loader_unlock ();
3834 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3838 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3840 clear_breakpoints_for_domain (domain);
3842 mono_loader_lock ();
3843 /* Invalidate each thread's frame stack */
3844 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3845 mono_loader_unlock ();
3847 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3851 * invalidate_each_thread:
3853 * A GHFunc to invalidate frames.
3854 * value must be a DebuggerTlsData*
3857 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3859 invalidate_frames (value);
3863 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3865 /* Sent later in jit_end () */
3866 mono_loader_lock ();
3867 g_ptr_array_add (pending_assembly_loads, assembly);
3868 mono_loader_unlock ();
3872 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3874 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3876 clear_event_requests_for_assembly (assembly);
3877 clear_types_for_assembly (assembly);
3881 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3883 #if defined(HOST_WIN32) && !defined(__GNUC__)
3884 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3886 gpointer stackptr = __builtin_frame_address (1);
3888 MonoInternalThread *thread = mono_thread_internal_current ();
3889 DebuggerTlsData *tls;
3891 mono_loader_lock ();
3893 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3894 /* Could be the debugger thread with assembly/type load hooks */
3896 tls->invoke_addr = stackptr;
3898 mono_loader_unlock ();
3902 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3905 #if defined(HOST_WIN32) && !defined(__GNUC__)
3906 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3908 gpointer stackptr = __builtin_frame_address (1);
3911 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
3915 * We need to stop single stepping when exiting a runtime invoke, since if it is
3916 * a step out, it may return to native code, and thus never end.
3918 mono_loader_lock ();
3919 ss_invoke_addr = NULL;
3921 for (i = 0; i < event_requests->len; ++i) {
3922 EventRequest *req = g_ptr_array_index (event_requests, i);
3924 if (req->event_kind == EVENT_KIND_STEP) {
3925 ss_destroy (req->info);
3926 g_ptr_array_remove_index_fast (event_requests, i);
3931 mono_loader_unlock ();
3935 send_type_load (MonoClass *klass)
3937 gboolean type_load = FALSE;
3938 MonoDomain *domain = mono_domain_get ();
3939 AgentDomainInfo *info = NULL;
3941 mono_loader_lock ();
3942 mono_domain_lock (domain);
3944 info = get_agent_domain_info (domain);
3946 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
3948 g_hash_table_insert (info->loaded_classes, klass, klass);
3951 mono_domain_unlock (domain);
3952 mono_loader_unlock ();
3954 emit_type_load (klass, klass, NULL);
3958 * Emit load events for all types currently loaded in the domain.
3959 * Takes the loader and domain locks.
3960 * user_data is unused.
3963 send_types_for_domain (MonoDomain *domain, void *user_data)
3965 AgentDomainInfo *info = NULL;
3967 mono_loader_lock ();
3968 mono_domain_lock (domain);
3969 info = get_agent_domain_info (domain);
3971 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
3972 mono_domain_unlock (domain);
3973 mono_loader_unlock ();
3977 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
3980 * We emit type load events when the first method of the type is JITted,
3981 * since the class load profiler callbacks might be called with the
3982 * loader lock held. They could also occur in the debugger thread.
3983 * Same for assembly load events.
3986 MonoAssembly *assembly = NULL;
3988 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
3989 mono_loader_lock ();
3990 if (pending_assembly_loads->len > 0) {
3991 assembly = g_ptr_array_index (pending_assembly_loads, 0);
3992 g_ptr_array_remove_index (pending_assembly_loads, 0);
3994 mono_loader_unlock ();
3997 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4003 send_type_load (method->klass);
4006 add_pending_breakpoints (method, jinfo);
4010 * BREAKPOINTS/SINGLE STEPPING
4014 * Contains information about an inserted breakpoint.
4017 long il_offset, native_offset;
4022 } BreakpointInstance;
4025 * Contains generic information about a breakpoint.
4029 * The method where the breakpoint is placed. Can be NULL in which case it
4030 * is inserted into every method. This is used to implement method entry/
4031 * exit events. Can be a generic method definition, in which case the
4032 * breakpoint is inserted into every instance.
4038 * A list of BreakpointInstance structures describing where the breakpoint
4039 * was inserted. There could be more than one because of
4040 * generics/appdomains/method entry/exit.
4042 GPtrArray *children;
4045 /* List of breakpoints */
4046 static GPtrArray *breakpoints;
4047 /* Maps breakpoint locations to the number of breakpoints at that location */
4048 static GHashTable *bp_locs;
4051 breakpoints_init (void)
4053 breakpoints = g_ptr_array_new ();
4054 bp_locs = g_hash_table_new (NULL, NULL);
4058 * insert_breakpoint:
4060 * Insert the breakpoint described by BP into the method described by
4064 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4067 BreakpointInstance *inst;
4068 SeqPoint *sp = NULL;
4071 mono_error_init (error);
4073 for (i = 0; i < seq_points->len; ++i) {
4074 sp = &seq_points->seq_points [i];
4076 if (sp->il_offset == bp->il_offset)
4080 if (i == seq_points->len) {
4082 * The set of IL offsets with seq points doesn't completely match the
4083 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4085 for (i = 0; i < seq_points->len; ++i) {
4086 sp = &seq_points->seq_points [i];
4088 if (sp->il_offset != METHOD_ENTRY_IL_OFFSET && sp->il_offset != METHOD_EXIT_IL_OFFSET && sp->il_offset + 1 == bp->il_offset)
4093 if (i == seq_points->len) {
4094 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);
4096 for (i = 0; i < seq_points->len; ++i)
4097 DEBUG (1, fprintf (log_file, "%d\n", seq_points->seq_points [i].il_offset));
4100 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4101 g_warning ("%s", s);
4105 g_warning ("%s", s);
4111 inst = g_new0 (BreakpointInstance, 1);
4113 inst->native_offset = sp->native_offset;
4114 inst->ip = (guint8*)ji->code_start + sp->native_offset;
4116 inst->domain = domain;
4118 mono_loader_lock ();
4120 g_ptr_array_add (bp->children, inst);
4122 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4123 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4124 mono_loader_unlock ();
4126 if (sp->native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4127 DEBUG (1, fprintf (log_file, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset));
4128 } else if (count == 0) {
4129 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4130 mono_arch_set_breakpoint (ji, inst->ip);
4136 DEBUG(1, fprintf (log_file, "[dbg] Inserted breakpoint at %s:0x%x.\n", mono_method_full_name (ji->method, TRUE), (int)sp->il_offset));
4140 remove_breakpoint (BreakpointInstance *inst)
4142 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4144 MonoJitInfo *ji = inst->ji;
4145 guint8 *ip = inst->ip;
4147 mono_loader_lock ();
4148 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4149 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4150 mono_loader_unlock ();
4152 g_assert (count > 0);
4154 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4155 mono_arch_clear_breakpoint (ji, ip);
4162 static inline gboolean
4163 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4169 if (method == bp->method)
4171 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4174 if (bp->method->is_inflated && method->is_inflated) {
4175 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4176 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4178 /* Open generic methods should match closed generic methods of the same class */
4179 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4180 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4181 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4183 /* FIXME: Handle !mvar */
4184 if (t1->type != MONO_TYPE_MVAR)
4195 * add_pending_breakpoints:
4197 * Insert pending breakpoints into the newly JITted method METHOD.
4200 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4203 MonoSeqPointInfo *seq_points;
4209 domain = mono_domain_get ();
4211 mono_loader_lock ();
4213 for (i = 0; i < breakpoints->len; ++i) {
4214 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4215 gboolean found = FALSE;
4217 if (!bp_matches_method (bp, method))
4220 for (j = 0; j < bp->children->len; ++j) {
4221 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4228 mono_domain_lock (domain);
4229 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
4230 if (!seq_points && ji->method->is_inflated)
4231 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (ji->method));
4232 mono_domain_unlock (domain);
4234 /* Could be AOT code */
4236 g_assert (seq_points);
4238 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4242 mono_loader_unlock ();
4246 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4252 mono_error_init (error);
4254 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4256 /* Might be AOTed code */
4257 code = mono_aot_get_method (domain, method);
4259 ji = mono_jit_info_table_find (domain, code);
4264 insert_breakpoint (seq_points, domain, ji, bp, error);
4268 clear_breakpoint (MonoBreakpoint *bp);
4273 * Set a breakpoint at IL_OFFSET in METHOD.
4274 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4275 * METHOD can also be a generic method definition, in which case a breakpoint
4276 * is placed in all instances of the method.
4277 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4280 static MonoBreakpoint*
4281 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4284 GHashTableIter iter, iter2;
4287 MonoSeqPointInfo *seq_points;
4290 mono_error_init (error);
4293 // - suspend/resume the vm to prevent code patching problems
4294 // - multiple breakpoints on the same location
4295 // - dynamic methods
4298 bp = g_new0 (MonoBreakpoint, 1);
4299 bp->method = method;
4300 bp->il_offset = il_offset;
4302 bp->children = g_ptr_array_new ();
4304 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));
4306 mono_loader_lock ();
4308 g_hash_table_iter_init (&iter, domains);
4309 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4310 mono_domain_lock (domain);
4312 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4313 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4314 if (bp_matches_method (bp, m))
4315 set_bp_in_method (domain, m, seq_points, bp, error);
4318 mono_domain_unlock (domain);
4321 mono_loader_unlock ();
4323 mono_loader_lock ();
4324 g_ptr_array_add (breakpoints, bp);
4325 mono_loader_unlock ();
4327 if (error && !mono_error_ok (error)) {
4328 clear_breakpoint (bp);
4336 clear_breakpoint (MonoBreakpoint *bp)
4340 // FIXME: locking, races
4341 for (i = 0; i < bp->children->len; ++i) {
4342 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4344 remove_breakpoint (inst);
4349 mono_loader_lock ();
4350 g_ptr_array_remove (breakpoints, bp);
4351 mono_loader_unlock ();
4353 g_ptr_array_free (bp->children, TRUE);
4358 breakpoints_cleanup (void)
4362 mono_loader_lock ();
4364 while (i < event_requests->len) {
4365 EventRequest *req = g_ptr_array_index (event_requests, i);
4367 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4368 clear_breakpoint (req->info);
4369 g_ptr_array_remove_index_fast (event_requests, i);
4376 for (i = 0; i < breakpoints->len; ++i)
4377 g_free (g_ptr_array_index (breakpoints, i));
4379 g_ptr_array_free (breakpoints, TRUE);
4380 g_hash_table_destroy (bp_locs);
4385 mono_loader_unlock ();
4389 * clear_breakpoints_for_domain:
4391 * Clear breakpoint instances which reference DOMAIN.
4394 clear_breakpoints_for_domain (MonoDomain *domain)
4398 /* This could be called after shutdown */
4402 mono_loader_lock ();
4403 for (i = 0; i < breakpoints->len; ++i) {
4404 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4407 while (j < bp->children->len) {
4408 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4410 if (inst->domain == domain) {
4411 remove_breakpoint (inst);
4415 g_ptr_array_remove_index_fast (bp->children, j);
4421 mono_loader_unlock ();
4427 * Return FALSE if single stepping needs to continue because we are at the same line.
4430 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp)
4432 MonoDebugMethodInfo *minfo;
4433 MonoDebugSourceLocation *loc = NULL;
4434 gboolean hit = TRUE;
4436 if (req->size != STEP_SIZE_LINE)
4439 /* Have to check whenever a different source line was reached */
4440 minfo = mono_debug_lookup_method (ji->method);
4443 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4445 if (!loc || (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line)) {
4446 /* Have to continue single stepping */
4448 DEBUG(1, fprintf (log_file, "[%p] No line number info for il offset %x, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset));
4450 DEBUG(1, fprintf (log_file, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer)GetCurrentThreadId (), loc->row));
4455 ss_req->last_method = ji->method;
4456 ss_req->last_line = loc->row;
4457 mono_debug_free_source_location (loc);
4464 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4466 return bp->method && bp->method->klass->image->assembly == assembly;
4470 process_breakpoint_inner (DebuggerTlsData *tls)
4474 int i, j, suspend_policy;
4475 guint32 native_offset;
4477 BreakpointInstance *inst;
4478 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4479 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4480 EventKind kind = EVENT_KIND_BREAKPOINT;
4481 MonoContext *ctx = &tls->restore_ctx;
4482 MonoSeqPointInfo *info;
4485 // FIXME: Speed this up
4487 ip = MONO_CONTEXT_GET_IP (ctx);
4488 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4490 g_assert (ji->method);
4492 /* Compute the native offset of the breakpoint from the ip */
4493 native_offset = ip - (guint8*)ji->code_start;
4496 * Skip the instruction causing the breakpoint signal.
4498 mono_arch_skip_breakpoint (ctx, ji);
4500 if (ji->method->wrapper_type || tls->disable_breakpoints)
4503 bp_reqs = g_ptr_array_new ();
4504 ss_reqs = g_ptr_array_new ();
4505 ss_reqs_orig = g_ptr_array_new ();
4507 mono_loader_lock ();
4510 * The ip points to the instruction causing the breakpoint event, which is after
4511 * the offset recorded in the seq point map, so find the prev seq point before ip.
4513 sp = find_prev_seq_point_for_native_offset (mono_domain_get (), ji->method, native_offset, &info);
4515 no_seq_points_found (ji->method);
4518 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));
4521 for (i = 0; i < breakpoints->len; ++i) {
4522 bp = g_ptr_array_index (breakpoints, i);
4527 for (j = 0; j < bp->children->len; ++j) {
4528 inst = g_ptr_array_index (bp->children, j);
4529 if (inst->ji == ji && inst->sp == sp) {
4530 if (bp->req->event_kind == EVENT_KIND_STEP) {
4531 g_ptr_array_add (ss_reqs_orig, bp->req);
4533 g_ptr_array_add (bp_reqs, bp->req);
4538 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4539 /* Maybe a method entry/exit event */
4540 if (sp->il_offset == METHOD_ENTRY_IL_OFFSET)
4541 kind = EVENT_KIND_METHOD_ENTRY;
4542 else if (sp->il_offset == METHOD_EXIT_IL_OFFSET)
4543 kind = EVENT_KIND_METHOD_EXIT;
4546 /* Process single step requests */
4547 for (i = 0; i < ss_reqs_orig->len; ++i) {
4548 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4549 SingleStepReq *ss_req = req->info;
4552 hit = ss_update (ss_req, ji, sp);
4554 g_ptr_array_add (ss_reqs, req);
4556 /* Start single stepping again from the current sequence point */
4557 ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4560 if (ss_reqs->len > 0)
4561 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4562 if (bp_reqs->len > 0)
4563 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4564 if (kind != EVENT_KIND_BREAKPOINT)
4565 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4567 mono_loader_unlock ();
4569 g_ptr_array_free (bp_reqs, TRUE);
4570 g_ptr_array_free (ss_reqs, TRUE);
4573 * FIXME: The first event will suspend, so the second will only be sent after the
4577 process_event (EVENT_KIND_STEP, ji->method, 0, ctx, ss_events, suspend_policy);
4579 process_event (kind, ji->method, 0, ctx, bp_events, suspend_policy);
4580 if (enter_leave_events)
4581 process_event (kind, ji->method, 0, ctx, enter_leave_events, suspend_policy);
4584 /* Process a breakpoint/single step event after resuming from a signal handler */
4586 process_signal_event (void (*func) (DebuggerTlsData*))
4588 DebuggerTlsData *tls;
4589 MonoContext orig_restore_ctx, ctx;
4590 static void (*restore_context) (void *);
4592 if (!restore_context)
4593 restore_context = mono_get_restore_context ();
4595 tls = mono_native_tls_get_value (debugger_tls_id);
4596 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4597 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4598 memcpy (&tls->restore_ctx, &tls->handler_ctx, sizeof (MonoContext));
4602 /* This is called when resuming from a signal handler, so it shouldn't return */
4603 memcpy (&ctx, &tls->restore_ctx, sizeof (MonoContext));
4604 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4605 restore_context (&ctx);
4606 g_assert_not_reached ();
4610 process_breakpoint (void)
4612 process_signal_event (process_breakpoint_inner);
4616 resume_from_signal_handler (void *sigctx, void *func)
4618 DebuggerTlsData *tls;
4621 /* Save the original context in TLS */
4622 // FIXME: This might not work on an altstack ?
4623 tls = mono_native_tls_get_value (debugger_tls_id);
4625 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer)GetCurrentThreadId ());
4628 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4629 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4630 // clob:c could be added to op_seq_point.
4632 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4633 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4634 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4635 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4637 MONO_CONTEXT_SET_IP (&ctx, func);
4639 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4641 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4642 mono_ppc_set_func_into_sigctx (sigctx, func);
4647 mono_debugger_agent_breakpoint_hit (void *sigctx)
4650 * We are called from a signal handler, and running code there causes all kinds of
4651 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4652 * So set up the signal context to return to the real breakpoint handler function.
4654 resume_from_signal_handler (sigctx, process_breakpoint);
4658 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4660 if (frame->managed) {
4661 *(MonoContext*)data = *ctx;
4670 * Called by System.Diagnostics.Debugger:Break ().
4673 mono_debugger_agent_user_break (void)
4675 if (agent_config.enabled) {
4680 /* Obtain a context */
4681 MONO_CONTEXT_SET_IP (&ctx, NULL);
4682 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4683 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4685 mono_loader_lock ();
4686 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4687 mono_loader_unlock ();
4689 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4696 ss_depth_to_string (StepDepth depth)
4699 case STEP_DEPTH_OVER:
4701 case STEP_DEPTH_OUT:
4703 case STEP_DEPTH_INTO:
4706 g_assert_not_reached ();
4712 process_single_step_inner (DebuggerTlsData *tls)
4717 int il_offset, suspend_policy;
4720 MonoContext *ctx = &tls->restore_ctx;
4722 MonoSeqPointInfo *info;
4724 ip = MONO_CONTEXT_GET_IP (ctx);
4726 /* Skip the instruction causing the single step */
4727 mono_arch_skip_single_step (ctx);
4729 if (suspend_count > 0) {
4730 process_suspend (tls, ctx);
4735 // FIXME: A suspend race
4738 if (mono_thread_internal_current () != ss_req->thread)
4741 if (log_level > 0) {
4742 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4744 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));
4747 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4749 g_assert (ji->method);
4751 if (ji->method->wrapper_type && ji->method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4756 * Stopping in memset makes half-initialized vtypes visible.
4757 * Stopping in memcpy makes half-copied vtypes visible.
4759 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
4763 * The ip points to the instruction causing the single step event, which is before
4764 * the offset recorded in the seq point map, so find the next seq point after ip.
4766 sp = find_next_seq_point_for_native_offset (domain, ji->method, (guint8*)ip - (guint8*)ji->code_start, &info);
4769 il_offset = sp->il_offset;
4771 if (!ss_update (ss_req, ji, sp))
4774 /* Start single stepping again from the current sequence point */
4775 ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4777 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
4778 (ji->method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4779 !strcmp (ji->method->name, ".cctor"))
4782 // FIXME: Has to lock earlier
4784 reqs = g_ptr_array_new ();
4786 mono_loader_lock ();
4788 g_ptr_array_add (reqs, ss_req->req);
4790 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4792 g_ptr_array_free (reqs, TRUE);
4794 mono_loader_unlock ();
4796 process_event (EVENT_KIND_STEP, ji->method, il_offset, ctx, events, suspend_policy);
4800 process_single_step (void)
4802 process_signal_event (process_single_step_inner);
4806 * mono_debugger_agent_single_step_event:
4808 * Called from a signal handler to handle a single step event.
4811 mono_debugger_agent_single_step_event (void *sigctx)
4813 /* Resume to process_single_step through the signal context */
4815 // FIXME: Since step out/over is implemented using step in, the step in case should
4816 // be as fast as possible. Move the relevant code from process_single_step_inner ()
4819 if (GetCurrentThreadId () == debugger_thread_id) {
4821 * This could happen despite our best effors when the runtime calls
4822 * assembly/type resolve hooks.
4823 * FIXME: Breakpoints too.
4827 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4828 mono_arch_skip_single_step (&ctx);
4829 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4833 resume_from_signal_handler (sigctx, process_single_step);
4837 debugger_agent_single_step_from_context (MonoContext *ctx)
4839 DebuggerTlsData *tls;
4840 MonoContext orig_restore_ctx;
4842 tls = mono_native_tls_get_value (debugger_tls_id);
4845 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4846 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4847 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4849 process_single_step_inner (tls);
4851 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4852 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4856 debugger_agent_breakpoint_from_context (MonoContext *ctx)
4858 DebuggerTlsData *tls;
4859 MonoContext orig_restore_ctx;
4861 tls = mono_native_tls_get_value (debugger_tls_id);
4863 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4864 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4866 process_breakpoint_inner (tls);
4868 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4869 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4873 * start_single_stepping:
4875 * Turn on single stepping. Can be called multiple times, for example,
4876 * by a single step event request + a suspend.
4879 start_single_stepping (void)
4881 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4882 int val = InterlockedIncrement (&ss_count);
4885 mono_arch_start_single_stepping ();
4887 if (ss_req != NULL && ss_invoke_addr == NULL) {
4888 DebuggerTlsData *tls;
4890 mono_loader_lock ();
4892 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
4893 ss_invoke_addr = tls->invoke_addr;
4895 mono_loader_unlock ();
4898 g_assert_not_reached ();
4903 stop_single_stepping (void)
4905 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4906 int val = InterlockedDecrement (&ss_count);
4909 mono_arch_stop_single_stepping ();
4911 ss_invoke_addr = NULL;
4913 g_assert_not_reached ();
4920 * Stop the single stepping operation given by SS_REQ.
4923 ss_stop (SingleStepReq *ss_req)
4928 for (l = ss_req->bps; l; l = l->next) {
4929 clear_breakpoint (l->data);
4931 g_slist_free (ss_req->bps);
4935 if (ss_req->global) {
4936 stop_single_stepping ();
4937 ss_req->global = FALSE;
4944 * Start the single stepping operation given by SS_REQ from the sequence point SP.
4945 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
4946 * belong to the same thread as CTX.
4949 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
4951 int i, j, frame_index;
4954 gboolean enable_global = FALSE;
4956 /* Stop the previous operation */
4960 * Implement single stepping using breakpoints if possible.
4962 if (step_to_catch) {
4963 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
4964 ss_req->bps = g_slist_append (ss_req->bps, bp);
4968 if ((!sp || sp->next_len == 0 || ss_req->depth == STEP_DEPTH_OUT || ss_req->depth == STEP_DEPTH_OVER) && ctx) {
4969 /* Need parent frames */
4970 if (!tls->context.valid)
4971 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4972 compute_frame_info (tls->thread, tls);
4976 * Find the first sequence point in the current or in a previous frame which
4977 * is not the last in its method.
4979 if (ss_req->depth == STEP_DEPTH_OUT) {
4980 /* Ignore seq points in current method */
4981 while (frame_index < tls->frame_count) {
4982 StackFrame *frame = tls->frames [frame_index];
4984 method = frame->method;
4985 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4987 if (sp && sp->next_len != 0)
4990 // There could be method calls before the next seq point in the caller when using nested calls
4991 //enable_global = TRUE;
4993 if (sp && sp->next_len == 0) {
4995 while (frame_index < tls->frame_count) {
4996 StackFrame *frame = tls->frames [frame_index];
4998 method = frame->method;
4999 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5000 if (sp && sp->next_len != 0)
5008 if (sp && sp->next_len > 0) {
5009 for (i = 0; i < sp->next_len; ++i) {
5010 next_sp = &info->seq_points [sp->next [i]];
5012 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
5013 ss_req->bps = g_slist_append (ss_req->bps, bp);
5017 if (ss_req->depth == STEP_DEPTH_OVER) {
5018 /* Need to stop in catch clauses as well */
5019 for (i = 0; i < tls->frame_count; ++i) {
5020 StackFrame *frame = tls->frames [i];
5023 MonoJitInfo *jinfo = frame->ji;
5024 for (j = 0; j < jinfo->num_clauses; ++j) {
5025 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5027 sp = find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL);
5029 bp = set_breakpoint (frame->method, sp->il_offset, ss_req->req, NULL);
5030 ss_req->bps = g_slist_append (ss_req->bps, bp);
5038 if (ss_req->depth == STEP_DEPTH_INTO) {
5039 /* Enable global stepping so we stop at method entry too */
5040 enable_global = TRUE;
5044 * The ctx/frame info computed above will become invalid when we continue.
5046 tls->context.valid = FALSE;
5047 tls->async_state.valid = FALSE;
5048 invalidate_frames (tls);
5051 if (enable_global) {
5052 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
5053 ss_req->global = TRUE;
5054 start_single_stepping ();
5055 } else if (!ss_req->bps) {
5056 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
5057 ss_req->global = TRUE;
5058 start_single_stepping ();
5060 ss_req->global = FALSE;
5065 * Start single stepping of thread THREAD
5068 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
5070 DebuggerTlsData *tls;
5071 MonoSeqPointInfo *info = NULL;
5072 SeqPoint *sp = NULL;
5073 MonoMethod *method = NULL;
5074 MonoDebugMethodInfo *minfo;
5075 gboolean step_to_catch = FALSE;
5077 if (suspend_count == 0)
5078 return ERR_NOT_SUSPENDED;
5080 wait_for_suspend ();
5082 // FIXME: Multiple requests
5084 DEBUG (0, fprintf (log_file, "Received a single step request while the previous one was still active.\n"));
5085 return ERR_NOT_IMPLEMENTED;
5088 DEBUG (1, fprintf (log_file, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
5090 ss_req = g_new0 (SingleStepReq, 1);
5092 ss_req->thread = thread;
5093 ss_req->size = size;
5094 ss_req->depth = depth;
5097 mono_loader_lock ();
5098 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5099 mono_loader_unlock ();
5101 g_assert (tls->context.valid);
5102 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5104 if (tls->catch_state.valid) {
5106 StackFrameInfo frame;
5107 MonoContext new_ctx;
5108 MonoLMF *lmf = NULL;
5111 * We are stopped at a throw site. Stepping should go to the catch site.
5114 /* Find the the jit info for the catch context */
5115 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);
5117 g_assert (frame.type == FRAME_TYPE_MANAGED);
5120 * Find the seq point corresponding to the landing site ip, which is the first seq
5123 sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
5125 no_seq_points_found (frame.method);
5128 method = frame.method;
5130 step_to_catch = TRUE;
5131 /* This make sure the seq point is not skipped by process_single_step () */
5132 ss_req->last_sp = NULL;
5135 if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
5138 /* Compute the initial line info */
5139 compute_frame_info (thread, tls);
5141 if (tls->frame_count) {
5142 frame = tls->frames [0];
5144 ss_req->last_method = frame->method;
5145 ss_req->last_line = -1;
5147 minfo = mono_debug_lookup_method (frame->method);
5148 if (minfo && frame->il_offset != -1) {
5149 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
5152 ss_req->last_line = loc->row;
5159 if (!step_to_catch) {
5162 compute_frame_info (thread, tls);
5164 if (tls->frame_count) {
5165 frame = tls->frames [0];
5167 if (!method && frame->il_offset != -1) {
5168 /* FIXME: Sort the table and use a binary search */
5169 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5171 no_seq_points_found (frame->method);
5173 method = frame->method;
5178 ss_start (ss_req, method, sp, info, &tls->context.ctx, tls, step_to_catch);
5184 ss_destroy (SingleStepReq *req)
5187 g_assert (ss_req == req);
5196 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5199 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5205 if (!agent_config.enabled)
5208 mono_loader_lock ();
5209 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5210 mono_loader_unlock ();
5213 ei.category = category ? mono_string_to_utf8 (category) : NULL;
5214 ei.message = message ? mono_string_to_utf8 (message) : NULL;
5216 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5218 g_free (ei.category);
5219 g_free (ei.message);
5223 mono_debugger_agent_debug_log_is_enabled (void)
5225 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5226 return agent_config.enabled;
5229 #ifdef PLATFORM_ANDROID
5231 mono_debugger_agent_unhandled_exception (MonoException *exc)
5240 memset (&ei, 0, sizeof (EventInfo));
5241 ei.exc = (MonoObject*)exc;
5243 mono_loader_lock ();
5244 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5245 mono_loader_unlock ();
5247 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5252 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5253 MonoContext *catch_ctx)
5255 int i, j, suspend_policy;
5257 MonoJitInfo *ji, *catch_ji;
5259 DebuggerTlsData *tls = NULL;
5261 if (thread_to_tls != NULL) {
5262 MonoInternalThread *thread = mono_thread_internal_current ();
5264 mono_loader_lock ();
5265 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5266 mono_loader_unlock ();
5268 if (tls && tls->abort_requested)
5270 if (tls && tls->disable_breakpoints)
5274 memset (&ei, 0, sizeof (EventInfo));
5276 /* Just-In-Time debugging */
5278 if (agent_config.onuncaught && !inited) {
5279 finish_agent_init (FALSE);
5282 * Send an unsolicited EXCEPTION event with a dummy request id.
5284 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5285 ei.exc = (MonoObject*)exc;
5286 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5289 } else if (agent_config.onthrow && !inited) {
5291 gboolean found = FALSE;
5293 for (l = agent_config.onthrow; l; l = l->next) {
5294 char *ex_type = l->data;
5295 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5297 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5304 finish_agent_init (FALSE);
5307 * Send an unsolicited EXCEPTION event with a dummy request id.
5309 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5310 ei.exc = (MonoObject*)exc;
5311 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5319 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5321 catch_ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5325 ei.exc = (MonoObject*)exc;
5326 ei.caught = catch_ctx != NULL;
5328 mono_loader_lock ();
5330 /* Treat exceptions which are caught in non-user code as unhandled */
5331 for (i = 0; i < event_requests->len; ++i) {
5332 EventRequest *req = g_ptr_array_index (event_requests, i);
5333 if (req->event_kind != EVENT_KIND_EXCEPTION)
5336 for (j = 0; j < req->nmodifiers; ++j) {
5337 Modifier *mod = &req->modifiers [j];
5339 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5341 gboolean found = FALSE;
5342 MonoAssembly **assemblies = mod->data.assemblies;
5345 for (k = 0; assemblies [k]; ++k)
5346 if (assemblies [k] == catch_ji->method->klass->image->assembly)
5355 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5356 mono_loader_unlock ();
5358 if (tls && ei.caught && catch_ctx) {
5359 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5360 tls->catch_state.ctx = *catch_ctx;
5361 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5362 tls->catch_state.valid = TRUE;
5365 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5368 tls->catch_state.valid = FALSE;
5372 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5374 DebuggerTlsData *tls;
5379 tls = mono_native_tls_get_value (debugger_tls_id);
5384 * We're about to invoke an exception filter during the first pass of exception handling.
5386 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5387 * 'orig_ctx' is the context where the exception has been thrown.
5390 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5392 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5393 * the call site (line 37) and then continue to Main(), but it would never
5394 * include the throw site (line 32).
5396 * Since exception filters are invoked during the first pass of exception handling,
5397 * the stack frames of the throw site are still intact, so we should include them
5400 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5402 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5403 * but report the location of the 'throw' to the user.
5407 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5411 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5413 DebuggerTlsData *tls;
5418 tls = mono_native_tls_get_value (debugger_tls_id);
5422 tls->filter_state.valid = FALSE;
5426 * buffer_add_value_full:
5428 * Add the encoding of the value at ADDR described by T to the buffer.
5429 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5433 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5439 if (!(*(void**)addr)) {
5440 /* This can happen with compiler generated locals */
5441 //printf ("%s\n", mono_type_full_name (t));
5442 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5445 g_assert (*(void**)addr);
5446 addr = *(void**)addr;
5451 case MONO_TYPE_BOOLEAN:
5454 case MONO_TYPE_CHAR:
5474 case MONO_TYPE_VOID:
5475 buffer_add_byte (buf, t->type);
5477 case MONO_TYPE_BOOLEAN:
5480 buffer_add_byte (buf, t->type);
5481 buffer_add_int (buf, *(gint8*)addr);
5483 case MONO_TYPE_CHAR:
5486 buffer_add_byte (buf, t->type);
5487 buffer_add_int (buf, *(gint16*)addr);
5492 buffer_add_byte (buf, t->type);
5493 buffer_add_int (buf, *(gint32*)addr);
5498 buffer_add_byte (buf, t->type);
5499 buffer_add_long (buf, *(gint64*)addr);
5503 /* Treat it as a vtype */
5505 case MONO_TYPE_PTR: {
5506 gssize val = *(gssize*)addr;
5508 buffer_add_byte (buf, t->type);
5509 buffer_add_long (buf, val);
5513 case MONO_TYPE_STRING:
5514 case MONO_TYPE_SZARRAY:
5515 case MONO_TYPE_OBJECT:
5516 case MONO_TYPE_CLASS:
5517 case MONO_TYPE_ARRAY:
5518 obj = *(MonoObject**)addr;
5521 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5523 if (obj->vtable->klass->valuetype) {
5524 t = &obj->vtable->klass->byval_arg;
5525 addr = mono_object_unbox (obj);
5527 } else if (obj->vtable->klass->rank) {
5528 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5529 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5530 buffer_add_byte (buf, MONO_TYPE_CLASS);
5532 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5534 buffer_add_objid (buf, obj);
5538 case MONO_TYPE_VALUETYPE: {
5542 MonoClass *klass = mono_class_from_mono_type (t);
5544 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5545 buffer_add_byte (buf, klass->enumtype);
5546 buffer_add_typeid (buf, domain, klass);
5550 while ((f = mono_class_get_fields (klass, &iter))) {
5551 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5553 if (mono_field_is_deleted (f))
5557 buffer_add_int (buf, nfields);
5560 while ((f = mono_class_get_fields (klass, &iter))) {
5561 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5563 if (mono_field_is_deleted (f))
5565 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE);
5569 case MONO_TYPE_GENERICINST:
5570 if (mono_type_generic_inst_is_valuetype (t)) {
5582 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5584 buffer_add_value_full (buf, t, addr, domain, FALSE);
5588 obj_is_of_type (MonoObject *obj, MonoType *t)
5590 MonoClass *klass = obj->vtable->klass;
5591 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5592 if (mono_class_is_transparent_proxy (klass)) {
5593 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5594 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5604 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5607 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5613 gpointer iter = NULL;
5617 is_enum = decode_byte (buf, &buf, limit);
5618 /* Enums are sent as a normal vtype */
5620 return ERR_NOT_IMPLEMENTED;
5621 klass = decode_typeid (buf, &buf, limit, &d, &err);
5625 if (t && klass != mono_class_from_mono_type (t)) {
5626 char *name = mono_type_full_name (t);
5627 char *name2 = mono_type_full_name (&klass->byval_arg);
5628 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got %s.\n", (gpointer)GetCurrentThreadId (), name, name2));
5631 return ERR_INVALID_ARGUMENT;
5634 nfields = decode_int (buf, &buf, limit);
5635 while ((f = mono_class_get_fields (klass, &iter))) {
5636 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5638 if (mono_field_is_deleted (f))
5640 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5645 g_assert (nfields == 0);
5650 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5654 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5655 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5656 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5657 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5658 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
5659 char *name = mono_type_full_name (t);
5660 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5662 return ERR_INVALID_ARGUMENT;
5666 case MONO_TYPE_BOOLEAN:
5667 *(guint8*)addr = decode_int (buf, &buf, limit);
5669 case MONO_TYPE_CHAR:
5670 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5673 *(gint8*)addr = decode_int (buf, &buf, limit);
5676 *(guint8*)addr = decode_int (buf, &buf, limit);
5679 *(gint16*)addr = decode_int (buf, &buf, limit);
5682 *(guint16*)addr = decode_int (buf, &buf, limit);
5685 *(gint32*)addr = decode_int (buf, &buf, limit);
5688 *(guint32*)addr = decode_int (buf, &buf, limit);
5691 *(gint64*)addr = decode_long (buf, &buf, limit);
5694 *(guint64*)addr = decode_long (buf, &buf, limit);
5697 *(guint32*)addr = decode_int (buf, &buf, limit);
5700 *(guint64*)addr = decode_long (buf, &buf, limit);
5703 /* We send these as I8, so we get them back as such */
5704 g_assert (type == MONO_TYPE_I8);
5705 *(gssize*)addr = decode_long (buf, &buf, limit);
5707 case MONO_TYPE_GENERICINST:
5708 if (MONO_TYPE_ISSTRUCT (t)) {
5709 /* The client sends these as a valuetype */
5717 /* We send these as vtypes, so we get them back as such */
5718 g_assert (type == MONO_TYPE_VALUETYPE);
5721 case MONO_TYPE_VALUETYPE:
5722 err = decode_vtype (t, domain, addr,buf, &buf, limit);
5728 if (MONO_TYPE_IS_REFERENCE (t)) {
5729 if (type == MONO_TYPE_OBJECT) {
5730 int objid = decode_objid (buf, &buf, limit);
5734 err = get_object (objid, (MonoObject**)&obj);
5739 if (!obj_is_of_type (obj, t)) {
5740 DEBUG (1, fprintf (log_file, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name));
5741 return ERR_INVALID_ARGUMENT;
5744 if (obj && obj->vtable->domain != domain)
5745 return ERR_INVALID_ARGUMENT;
5747 mono_gc_wbarrier_generic_store (addr, obj);
5748 } else if (type == VALUE_TYPE_ID_NULL) {
5749 *(MonoObject**)addr = NULL;
5750 } else if (type == MONO_TYPE_VALUETYPE) {
5758 /* This can happen when round-tripping boxed vtypes */
5760 * Obtain vtype class.
5761 * Same as the beginning of the handle_vtype case above.
5764 is_enum = decode_byte (buf, &buf, limit);
5766 return ERR_NOT_IMPLEMENTED;
5767 klass = decode_typeid (buf, &buf, limit, &d, &err);
5771 /* Decode the vtype into a temporary buffer, then box it. */
5772 vtype_buf_size = mono_class_value_size (klass, NULL);
5773 vtype_buf = g_malloc0 (vtype_buf_size);
5774 g_assert (vtype_buf);
5777 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
5782 *(MonoObject**)addr = mono_value_box (d, klass, vtype_buf);
5785 char *name = mono_type_full_name (t);
5786 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5788 return ERR_INVALID_ARGUMENT;
5802 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5805 int type = decode_byte (buf, &buf, limit);
5807 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
5808 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
5809 guint8 *nullable_buf;
5812 * First try decoding it as a Nullable`1
5814 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5819 * Then try decoding as a primitive value or null.
5821 if (targ->type == type) {
5822 nullable_buf = g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
5823 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
5825 g_free (nullable_buf);
5828 mono_nullable_init (addr, mono_value_box (domain, mono_class_from_mono_type (targ), nullable_buf), mono_class_from_mono_type (t));
5829 g_free (nullable_buf);
5832 } else if (type == VALUE_TYPE_ID_NULL) {
5833 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
5839 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5843 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
5847 guint8 *addr, *gaddr;
5850 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5851 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5854 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
5855 reg_val = mono_arch_context_get_int_reg (ctx, reg);
5857 buffer_add_value_full (buf, t, ®_val, domain, as_vtype);
5859 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5860 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5861 addr += (gint32)var->offset;
5863 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5865 buffer_add_value_full (buf, t, addr, domain, as_vtype);
5867 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5870 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
5871 /* Same as regoffset, but with an indirection */
5872 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5873 addr += (gint32)var->offset;
5875 gaddr = *(gpointer*)addr;
5877 buffer_add_value_full (buf, t, gaddr, domain, as_vtype);
5879 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
5880 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
5881 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
5882 MonoGSharedVtMethodRuntimeInfo *info;
5888 g_assert (info_var);
5889 g_assert (locals_var);
5891 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5892 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5893 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
5894 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5895 addr += (gint32)info_var->offset;
5896 info = *(gpointer*)addr;
5897 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
5898 info = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5900 g_assert_not_reached ();
5904 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5905 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5906 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
5907 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5908 addr += (gint32)locals_var->offset;
5909 locals = *(gpointer*)addr;
5910 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
5911 locals = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5913 g_assert_not_reached ();
5917 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
5919 buffer_add_value_full (buf, t, addr, domain, as_vtype);
5924 g_assert_not_reached ();
5929 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
5933 guint8 *addr, *gaddr;
5935 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5936 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5938 if (MONO_TYPE_IS_REFERENCE (t))
5939 size = sizeof (gpointer);
5941 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
5944 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
5945 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
5947 gboolean is_signed = FALSE;
5949 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
5954 v = is_signed ? *(gint8*)val : *(guint8*)val;
5957 v = is_signed ? *(gint16*)val : *(guint16*)val;
5960 v = is_signed ? *(gint32*)val : *(guint32*)val;
5963 v = is_signed ? *(gint64*)val : *(guint64*)val;
5966 g_assert_not_reached ();
5972 /* Set value on the stack or in the return ctx */
5973 if (reg_locations [reg]) {
5974 /* Saved on the stack */
5975 DEBUG (1, fprintf (log_file, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v));
5976 *(reg_locations [reg]) = v;
5979 DEBUG (1, fprintf (log_file, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v));
5980 mono_arch_context_set_int_reg (restore_ctx, reg, v);
5983 // FIXME: Move these to mono-context.h/c.
5984 mono_arch_context_set_int_reg (ctx, reg, v);
5986 // FIXME: Can't set registers, so we disable linears
5991 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5992 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5993 addr += (gint32)var->offset;
5995 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5998 addr = *(guint8**)addr;
6004 // FIXME: Write barriers
6005 mono_gc_memmove (addr, val, size);
6007 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6008 /* Same as regoffset, but with an indirection */
6009 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6010 addr += (gint32)var->offset;
6012 gaddr = *(gpointer*)addr;
6014 // FIXME: Write barriers
6015 mono_gc_memmove (gaddr, val, size);
6017 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6021 g_assert_not_reached ();
6026 clear_event_request (int req_id, int etype)
6030 mono_loader_lock ();
6031 for (i = 0; i < event_requests->len; ++i) {
6032 EventRequest *req = g_ptr_array_index (event_requests, i);
6034 if (req->id == req_id && req->event_kind == etype) {
6035 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6036 clear_breakpoint (req->info);
6037 if (req->event_kind == EVENT_KIND_STEP)
6038 ss_destroy (req->info);
6039 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6040 clear_breakpoint (req->info);
6041 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6042 clear_breakpoint (req->info);
6043 g_ptr_array_remove_index_fast (event_requests, i);
6048 mono_loader_unlock ();
6052 event_req_matches_assembly (EventRequest *req, MonoAssembly *assembly)
6054 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6055 return breakpoint_matches_assembly (req->info, assembly);
6059 for (i = 0; i < req->nmodifiers; ++i) {
6060 Modifier *m = &req->modifiers [i];
6062 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6064 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6065 for (j = 0; m->data.assemblies [j]; ++j)
6066 if (m->data.assemblies [j] == assembly)
6076 * clear_event_requests_for_assembly:
6078 * Clear all events requests which reference ASSEMBLY.
6081 clear_event_requests_for_assembly (MonoAssembly *assembly)
6086 mono_loader_lock ();
6090 for (i = 0; i < event_requests->len; ++i) {
6091 EventRequest *req = g_ptr_array_index (event_requests, i);
6093 if (event_req_matches_assembly (req, assembly)) {
6094 clear_event_request (req->id, req->event_kind);
6100 mono_loader_unlock ();
6104 * type_comes_from_assembly:
6106 * GHRFunc that returns TRUE if klass comes from assembly
6109 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6111 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6115 * clear_types_for_assembly:
6117 * Clears types from loaded_classes for a given assembly
6120 clear_types_for_assembly (MonoAssembly *assembly)
6122 MonoDomain *domain = mono_domain_get ();
6123 AgentDomainInfo *info = NULL;
6125 mono_loader_lock ();
6126 info = get_agent_domain_info (domain);
6127 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6128 mono_loader_unlock ();
6132 add_thread (gpointer key, gpointer value, gpointer user_data)
6134 MonoInternalThread *thread = value;
6135 Buffer *buf = user_data;
6137 buffer_add_objid (buf, (MonoObject*)thread);
6141 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6143 guint8 *end = invoke->endp;
6146 MonoMethodSignature *sig;
6149 MonoObject *this, *res, *exc;
6152 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6155 MonoStopwatch watch;
6157 if (invoke->method) {
6159 * Invoke this method directly, currently only Environment.Exit () is supported.
6162 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>"));
6163 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
6164 g_assert_not_reached ();
6167 m = decode_methodid (p, &p, end, &domain, &err);
6170 sig = mono_method_signature (m);
6172 if (m->klass->valuetype)
6173 this_buf = g_alloca (mono_class_instance_size (m->klass));
6175 this_buf = g_alloca (sizeof (MonoObject*));
6176 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6177 /* Should be null */
6178 int type = decode_byte (p, &p, end);
6179 if (type != VALUE_TYPE_ID_NULL) {
6180 DEBUG (1, fprintf (log_file, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer)GetCurrentThreadId ()));
6181 return ERR_INVALID_ARGUMENT;
6183 memset (this_buf, 0, mono_class_instance_size (m->klass));
6185 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6190 if (!m->klass->valuetype)
6191 this = *(MonoObject**)this_buf;
6195 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>"));
6197 if (this && this->vtable->domain != domain)
6200 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
6201 if (!strcmp (m->name, ".ctor")) {
6202 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
6203 return ERR_INVALID_ARGUMENT;
6205 this = mono_object_new (domain, m->klass);
6207 return ERR_INVALID_ARGUMENT;
6211 if (this && !obj_is_of_type (this, &m->klass->byval_arg))
6212 return ERR_INVALID_ARGUMENT;
6214 nargs = decode_int (p, &p, end);
6215 if (nargs != sig->param_count)
6216 return ERR_INVALID_ARGUMENT;
6217 /* Use alloca to get gc tracking */
6218 arg_buf = g_alloca (nargs * sizeof (gpointer));
6219 memset (arg_buf, 0, nargs * sizeof (gpointer));
6220 args = g_alloca (nargs * sizeof (gpointer));
6221 for (i = 0; i < nargs; ++i) {
6222 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6223 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6227 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6230 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6231 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6234 args [i] = arg_buf [i];
6241 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6242 tls->disable_breakpoints = TRUE;
6244 tls->disable_breakpoints = FALSE;
6247 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6249 /* FIXME: Move this to arch specific code */
6250 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6251 if (invoke->has_ctx) {
6254 lmf_addr = mono_get_lmf_addr ();
6257 memset (&ext, 0, sizeof (ext));
6259 ext.lmf.previous_lmf = *(lmf_addr);
6260 /* Mark that this is a MonoLMFExt */
6261 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6262 ext.lmf.rsp = (gssize)&ext;
6263 #elif defined(TARGET_X86)
6264 ext.lmf.previous_lmf = (gsize)*(lmf_addr);
6265 /* Mark that this is a MonoLMFExt */
6266 ext.lmf.previous_lmf = (gsize)(gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6267 ext.lmf.ebp = (gssize)&ext;
6268 #elif defined(TARGET_ARM)
6269 ext.lmf.previous_lmf = *(lmf_addr);
6270 /* Mark that this is a MonoLMFExt */
6271 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6272 ext.lmf.sp = (gssize)&ext;
6273 #elif defined(TARGET_POWERPC)
6274 ext.lmf.previous_lmf = *(lmf_addr);
6275 /* Mark that this is a MonoLMFExt */
6276 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6277 ext.lmf.ebp = (gssize)&ext;
6278 #elif defined(TARGET_S390X)
6279 ext.lmf.previous_lmf = *(lmf_addr);
6280 /* Mark that this is a MonoLMFExt */
6281 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6282 ext.lmf.ebp = (gssize)&ext;
6283 #elif defined(TARGET_MIPS)
6284 ext.lmf.previous_lmf = *(lmf_addr);
6285 /* Mark that this is a MonoLMFExt */
6286 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6287 ext.lmf.iregs [mips_sp] = (gssize)&ext;
6289 g_assert_not_reached ();
6292 ext.debugger_invoke = TRUE;
6293 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6295 mono_set_lmf ((MonoLMF*)&ext);
6299 mono_stopwatch_start (&watch);
6300 if (m->klass->valuetype)
6301 res = mono_runtime_invoke (m, this_buf, args, &exc);
6303 res = mono_runtime_invoke (m, this, args, &exc);
6304 mono_stopwatch_stop (&watch);
6305 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)));
6307 buffer_add_byte (buf, 0);
6308 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6310 buffer_add_byte (buf, 1);
6311 if (sig->ret->type == MONO_TYPE_VOID) {
6312 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
6313 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
6316 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6317 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6318 buffer_add_value (buf, sig->ret, &res, domain);
6319 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6320 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6321 MonoClass *k = mono_class_from_mono_type (sig->ret);
6322 guint8 *nullable_buf = g_alloca (mono_class_value_size (k, NULL));
6324 g_assert (nullable_buf);
6325 mono_nullable_init (nullable_buf, res, k);
6326 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6329 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6336 tls->disable_breakpoints = FALSE;
6338 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6339 if (invoke->has_ctx)
6340 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
6344 // FIXME: byref arguments
6352 * Invoke the method given by tls->pending_invoke in the current thread.
6355 invoke_method (void)
6357 DebuggerTlsData *tls;
6362 static void (*restore_context) (void *);
6363 MonoContext restore_ctx;
6366 if (!restore_context)
6367 restore_context = mono_get_restore_context ();
6369 tls = mono_native_tls_get_value (debugger_tls_id);
6373 * Store the `InvokeData *' in `tls->invoke' until we're done with
6374 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6377 mono_loader_lock ();
6379 invoke = tls->pending_invoke;
6381 tls->pending_invoke = NULL;
6383 invoke->last_invoke = tls->invoke;
6384 tls->invoke = invoke;
6386 mono_loader_unlock ();
6388 tls->frames_up_to_date = FALSE;
6394 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6395 buffer_init (&buf, 128);
6398 /* Fail the other invokes as well */
6400 err = do_invoke_method (tls, &buf, invoke, p, &p);
6403 /* Start suspending before sending the reply */
6404 if (mindex == invoke->nmethods - 1) {
6405 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6406 for (i = 0; i < invoke->suspend_count; ++i)
6411 send_reply_packet (id, err, &buf);
6416 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6418 if (invoke->has_ctx)
6419 save_thread_context (&restore_ctx);
6421 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6422 g_assert (tls->resume_count);
6423 tls->resume_count -= invoke->suspend_count;
6426 DEBUG (1, fprintf (log_file, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer)GetCurrentThreadId (), err, tls->resume_count));
6429 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6431 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
6432 * after the mono_runtime_invoke() already returned, but it doesn't matter
6433 * because we reset the abort here.
6436 mono_loader_lock ();
6438 if (tls->abort_requested)
6439 mono_thread_internal_reset_abort (tls->thread);
6441 tls->invoke = tls->invoke->last_invoke;
6442 tls->abort_requested = FALSE;
6444 mono_loader_unlock ();
6453 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6455 MonoThread *thread = value;
6456 DebuggerTlsData *tls;
6459 mono_loader_lock ();
6460 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6462 res = tls->really_suspended;
6463 mono_loader_unlock ();
6469 get_source_files_for_type (MonoClass *klass)
6471 gpointer iter = NULL;
6473 MonoDebugSourceInfo *sinfo;
6477 files = g_ptr_array_new ();
6479 while ((method = mono_class_get_methods (klass, &iter))) {
6480 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6481 GPtrArray *source_file_list;
6484 mono_debug_symfile_get_line_numbers_full (minfo, NULL, &source_file_list, NULL, NULL, NULL, NULL, NULL);
6485 for (j = 0; j < source_file_list->len; ++j) {
6486 sinfo = g_ptr_array_index (source_file_list, j);
6487 for (i = 0; i < files->len; ++i)
6488 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6490 if (i == files->len)
6491 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6493 g_ptr_array_free (source_file_list, TRUE);
6501 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6504 case CMD_VM_VERSION: {
6505 char *build_info, *version;
6507 build_info = mono_get_runtime_build_info ();
6508 version = g_strdup_printf ("mono %s", build_info);
6510 buffer_add_string (buf, version); /* vm version */
6511 buffer_add_int (buf, MAJOR_VERSION);
6512 buffer_add_int (buf, MINOR_VERSION);
6513 g_free (build_info);
6517 case CMD_VM_SET_PROTOCOL_VERSION: {
6518 major_version = decode_int (p, &p, end);
6519 minor_version = decode_int (p, &p, end);
6520 protocol_version_set = TRUE;
6521 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
6524 case CMD_VM_ALL_THREADS: {
6526 mono_loader_lock ();
6527 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6528 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6529 mono_loader_unlock ();
6532 case CMD_VM_SUSPEND:
6534 wait_for_suspend ();
6537 if (suspend_count == 0)
6538 return ERR_NOT_SUSPENDED;
6540 clear_suspended_objs ();
6542 case CMD_VM_DISPOSE:
6543 /* Clear all event requests */
6544 mono_loader_lock ();
6545 while (event_requests->len > 0) {
6546 EventRequest *req = g_ptr_array_index (event_requests, 0);
6548 clear_event_request (req->id, req->event_kind);
6550 mono_loader_unlock ();
6552 while (suspend_count > 0)
6554 disconnected = TRUE;
6555 vm_start_event_sent = FALSE;
6558 MonoInternalThread *thread;
6559 DebuggerTlsData *tls;
6560 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6561 MonoClass *env_class;
6563 MonoMethod *exit_method = NULL;
6567 exit_code = decode_int (p, &p, end);
6569 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6571 /* Have to send a reply before exiting */
6572 send_reply_packet (id, 0, buf);
6574 /* Clear all event requests */
6575 mono_loader_lock ();
6576 while (event_requests->len > 0) {
6577 EventRequest *req = g_ptr_array_index (event_requests, 0);
6579 clear_event_request (req->id, req->event_kind);
6581 mono_loader_unlock ();
6584 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6585 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6586 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6587 * better than doing the shutdown ourselves, since it avoids various races.
6591 wait_for_suspend ();
6593 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6594 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
6596 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6599 mono_loader_lock ();
6600 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6601 mono_loader_unlock ();
6603 if (thread && exit_method) {
6604 mono_loader_lock ();
6605 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6606 mono_loader_unlock ();
6608 args = g_new0 (gpointer, 1);
6609 args [0] = g_malloc (sizeof (int));
6610 *(int*)(args [0]) = exit_code;
6612 tls->pending_invoke = g_new0 (InvokeData, 1);
6613 tls->pending_invoke->method = exit_method;
6614 tls->pending_invoke->args = args;
6615 tls->pending_invoke->nmethods = 1;
6617 while (suspend_count > 0)
6621 * No thread found, do it ourselves.
6622 * FIXME: This can race with normal shutdown etc.
6624 while (suspend_count > 0)
6627 if (!mono_runtime_try_shutdown ())
6630 /* Suspend all managed threads since the runtime is going away */
6631 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
6632 mono_thread_suspend_all_other_threads ();
6633 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
6634 mono_runtime_quit ();
6635 transport_close2 ();
6636 DEBUG(1, fprintf (log_file, "Exiting...\n"));
6642 case CMD_VM_INVOKE_METHOD:
6643 case CMD_VM_INVOKE_METHODS: {
6644 int objid = decode_objid (p, &p, end);
6646 DebuggerTlsData *tls;
6647 int i, count, err, flags, nmethods;
6649 err = get_object (objid, (MonoObject**)&thread);
6653 flags = decode_int (p, &p, end);
6655 if (command == CMD_VM_INVOKE_METHODS)
6656 nmethods = decode_int (p, &p, end);
6660 // Wait for suspending if it already started
6662 wait_for_suspend ();
6663 if (!is_suspended ())
6664 return ERR_NOT_SUSPENDED;
6666 mono_loader_lock ();
6667 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6668 mono_loader_unlock ();
6671 if (!tls->really_suspended)
6672 /* The thread is still running native code, can't do invokes */
6673 return ERR_NOT_SUSPENDED;
6676 * Store the invoke data into tls, the thread will execute it after it is
6679 if (tls->pending_invoke)
6680 return ERR_NOT_SUSPENDED;
6681 tls->pending_invoke = g_new0 (InvokeData, 1);
6682 tls->pending_invoke->id = id;
6683 tls->pending_invoke->flags = flags;
6684 tls->pending_invoke->p = g_malloc (end - p);
6685 memcpy (tls->pending_invoke->p, p, end - p);
6686 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
6687 tls->pending_invoke->suspend_count = suspend_count;
6688 tls->pending_invoke->nmethods = nmethods;
6690 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
6691 resume_thread (THREAD_TO_INTERNAL (thread));
6694 count = suspend_count;
6695 for (i = 0; i < count; ++i)
6700 case CMD_VM_ABORT_INVOKE: {
6701 int objid = decode_objid (p, &p, end);
6703 DebuggerTlsData *tls;
6706 err = get_object (objid, (MonoObject**)&thread);
6710 invoke_id = decode_int (p, &p, end);
6712 mono_loader_lock ();
6713 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6716 if (tls->abort_requested) {
6717 mono_loader_unlock ();
6722 * Check whether we're still inside the mono_runtime_invoke() and that it's
6723 * actually the correct invocation.
6725 * Careful, we do not stop the thread that's doing the invocation, so we can't
6726 * inspect its stack. However, invoke_method() also acquires the loader lock
6727 * when it's done, so we're safe here.
6731 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
6732 mono_loader_unlock ();
6733 return ERR_NO_INVOCATION;
6736 tls->abort_requested = TRUE;
6738 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
6739 mono_loader_unlock ();
6743 case CMD_VM_SET_KEEPALIVE: {
6744 int timeout = decode_int (p, &p, end);
6745 agent_config.keepalive = timeout;
6747 #ifndef DISABLE_SOCKET_TRANSPORT
6754 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
6755 GHashTableIter iter, kiter;
6760 char *fname, *basename;
6761 gboolean ignore_case;
6762 GSList *class_list, *l;
6763 GPtrArray *res_classes, *res_domains;
6765 fname = decode_string (p, &p, end);
6766 ignore_case = decode_byte (p, &p, end);
6768 basename = g_path_get_basename (fname);
6770 res_classes = g_ptr_array_new ();
6771 res_domains = g_ptr_array_new ();
6773 mono_loader_lock ();
6774 g_hash_table_iter_init (&iter, domains);
6775 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6776 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
6778 /* Update 'source_file_to_class' cache */
6779 g_hash_table_iter_init (&kiter, info->loaded_classes);
6780 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
6781 if (!g_hash_table_lookup (info->source_files, klass)) {
6782 files = get_source_files_for_type (klass);
6783 g_hash_table_insert (info->source_files, klass, files);
6785 for (i = 0; i < files->len; ++i) {
6786 char *s = g_ptr_array_index (files, i);
6787 char *s2 = g_path_get_basename (s);
6790 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
6792 class_list = g_slist_prepend (class_list, klass);
6793 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
6795 class_list = g_slist_prepend (class_list, klass);
6796 g_hash_table_insert (info->source_file_to_class, s2, class_list);
6799 /* The _ignorecase hash contains the lowercase path */
6800 s3 = strdup_tolower (s2);
6801 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
6803 class_list = g_slist_prepend (class_list, klass);
6804 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
6806 class_list = g_slist_prepend (class_list, klass);
6807 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
6819 s = strdup_tolower (basename);
6820 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
6823 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
6826 for (l = class_list; l; l = l->next) {
6829 g_ptr_array_add (res_classes, klass);
6830 g_ptr_array_add (res_domains, domain);
6833 mono_loader_unlock ();
6838 buffer_add_int (buf, res_classes->len);
6839 for (i = 0; i < res_classes->len; ++i)
6840 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6841 g_ptr_array_free (res_classes, TRUE);
6842 g_ptr_array_free (res_domains, TRUE);
6845 case CMD_VM_GET_TYPES: {
6846 GHashTableIter iter;
6850 gboolean ignore_case;
6851 GPtrArray *res_classes, *res_domains;
6852 MonoTypeNameParse info;
6854 name = decode_string (p, &p, end);
6855 ignore_case = decode_byte (p, &p, end);
6857 if (!mono_reflection_parse_type (name, &info)) {
6859 mono_reflection_free_type_info (&info);
6860 return ERR_INVALID_ARGUMENT;
6863 res_classes = g_ptr_array_new ();
6864 res_domains = g_ptr_array_new ();
6866 mono_loader_lock ();
6867 g_hash_table_iter_init (&iter, domains);
6868 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6870 gboolean type_resolve;
6874 mono_domain_assemblies_lock (domain);
6875 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6879 type_resolve = TRUE;
6880 t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
6882 g_ptr_array_add (res_classes, mono_type_get_class (t));
6883 g_ptr_array_add (res_domains, domain);
6887 mono_domain_assemblies_unlock (domain);
6889 mono_loader_unlock ();
6892 mono_reflection_free_type_info (&info);
6894 buffer_add_int (buf, res_classes->len);
6895 for (i = 0; i < res_classes->len; ++i)
6896 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6897 g_ptr_array_free (res_classes, TRUE);
6898 g_ptr_array_free (res_domains, TRUE);
6903 return ERR_NOT_IMPLEMENTED;
6910 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6916 case CMD_EVENT_REQUEST_SET: {
6918 int i, event_kind, suspend_policy, nmodifiers, mod;
6921 MonoThread *step_thread;
6922 int size = 0, depth = 0, filter = 0, step_thread_id = 0;
6926 event_kind = decode_byte (p, &p, end);
6927 suspend_policy = decode_byte (p, &p, end);
6928 nmodifiers = decode_byte (p, &p, end);
6930 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
6931 req->id = InterlockedIncrement (&event_request_id);
6932 req->event_kind = event_kind;
6933 req->suspend_policy = suspend_policy;
6934 req->nmodifiers = nmodifiers;
6937 for (i = 0; i < nmodifiers; ++i) {
6938 mod = decode_byte (p, &p, end);
6940 req->modifiers [i].kind = mod;
6941 if (mod == MOD_KIND_COUNT) {
6942 req->modifiers [i].data.count = decode_int (p, &p, end);
6943 } else if (mod == MOD_KIND_LOCATION_ONLY) {
6944 method = decode_methodid (p, &p, end, &domain, &err);
6947 location = decode_long (p, &p, end);
6948 } else if (mod == MOD_KIND_STEP) {
6949 step_thread_id = decode_id (p, &p, end);
6950 size = decode_int (p, &p, end);
6951 depth = decode_int (p, &p, end);
6952 if (CHECK_PROTOCOL_VERSION (2, 16))
6953 filter = decode_int (p, &p, end);
6954 req->modifiers [i].data.filter = filter;
6955 } else if (mod == MOD_KIND_THREAD_ONLY) {
6956 int id = decode_id (p, &p, end);
6958 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
6963 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
6964 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
6968 req->modifiers [i].caught = decode_byte (p, &p, end);
6969 req->modifiers [i].uncaught = decode_byte (p, &p, end);
6970 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" : ""));
6972 req->modifiers [i].data.exc_class = exc_class;
6974 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
6976 return ERR_INVALID_ARGUMENT;
6979 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
6980 int n = decode_int (p, &p, end);
6983 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
6984 for (j = 0; j < n; ++j) {
6985 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
6987 g_free (req->modifiers [i].data.assemblies);
6991 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
6992 int n = decode_int (p, &p, end);
6995 modifier = &req->modifiers [i];
6996 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
6997 for (j = 0; j < n; ++j) {
6998 char *s = decode_string (p, &p, end);
7002 s2 = strdup_tolower (s);
7003 g_hash_table_insert (modifier->data.source_files, s2, s2);
7007 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7008 int n = decode_int (p, &p, end);
7011 modifier = &req->modifiers [i];
7012 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7013 for (j = 0; j < n; ++j) {
7014 char *s = decode_string (p, &p, end);
7017 g_hash_table_insert (modifier->data.type_names, s, s);
7021 return ERR_NOT_IMPLEMENTED;
7025 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7028 req->info = set_breakpoint (method, location, req, &error);
7029 if (!mono_error_ok (&error)) {
7031 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
7032 mono_error_cleanup (&error);
7033 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7035 } else if (req->event_kind == EVENT_KIND_STEP) {
7036 g_assert (step_thread_id);
7038 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7044 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
7049 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7050 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7051 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7052 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7053 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7054 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7056 if (req->nmodifiers) {
7058 return ERR_NOT_IMPLEMENTED;
7062 mono_loader_lock ();
7063 g_ptr_array_add (event_requests, req);
7065 if (agent_config.defer) {
7066 /* Transmit cached data to the client on receipt of the event request */
7067 switch (req->event_kind) {
7068 case EVENT_KIND_APPDOMAIN_CREATE:
7069 /* Emit load events for currently loaded domains */
7070 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7072 case EVENT_KIND_ASSEMBLY_LOAD:
7073 /* Emit load events for currently loaded assemblies */
7074 mono_assembly_foreach (emit_assembly_load, NULL);
7076 case EVENT_KIND_THREAD_START:
7077 /* Emit start events for currently started threads */
7078 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7080 case EVENT_KIND_TYPE_LOAD:
7081 /* Emit type load events for currently loaded types */
7082 mono_domain_foreach (send_types_for_domain, NULL);
7088 mono_loader_unlock ();
7090 buffer_add_int (buf, req->id);
7093 case CMD_EVENT_REQUEST_CLEAR: {
7094 int etype = decode_byte (p, &p, end);
7095 int req_id = decode_int (p, &p, end);
7097 // FIXME: Make a faster mapping from req_id to request
7098 mono_loader_lock ();
7099 clear_event_request (req_id, etype);
7100 mono_loader_unlock ();
7103 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7106 mono_loader_lock ();
7108 while (i < event_requests->len) {
7109 EventRequest *req = g_ptr_array_index (event_requests, i);
7111 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7112 clear_breakpoint (req->info);
7114 g_ptr_array_remove_index_fast (event_requests, i);
7120 mono_loader_unlock ();
7124 return ERR_NOT_IMPLEMENTED;
7131 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7137 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7138 buffer_add_domainid (buf, mono_get_root_domain ());
7141 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7142 domain = decode_domainid (p, &p, end, NULL, &err);
7145 buffer_add_string (buf, domain->friendly_name);
7148 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7153 domain = decode_domainid (p, &p, end, NULL, &err);
7156 mono_loader_lock ();
7158 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7161 buffer_add_int (buf, count);
7162 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7164 buffer_add_assemblyid (buf, domain, ass);
7166 mono_loader_unlock ();
7169 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7170 domain = decode_domainid (p, &p, end, NULL, &err);
7174 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7177 case CMD_APPDOMAIN_GET_CORLIB: {
7178 domain = decode_domainid (p, &p, end, NULL, &err);
7182 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7185 case CMD_APPDOMAIN_CREATE_STRING: {
7189 domain = decode_domainid (p, &p, end, NULL, &err);
7192 s = decode_string (p, &p, end);
7194 o = mono_string_new (domain, s);
7195 buffer_add_objid (buf, (MonoObject*)o);
7198 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7200 MonoDomain *domain2;
7203 domain = decode_domainid (p, &p, end, NULL, &err);
7206 klass = decode_typeid (p, &p, end, &domain2, &err);
7211 g_assert (domain == domain2);
7213 o = mono_object_new (domain, klass);
7215 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
7219 buffer_add_objid (buf, o);
7223 return ERR_NOT_IMPLEMENTED;
7230 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7236 ass = decode_assemblyid (p, &p, end, &domain, &err);
7241 case CMD_ASSEMBLY_GET_LOCATION: {
7242 buffer_add_string (buf, mono_image_get_filename (ass->image));
7245 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7249 if (ass->image->dynamic) {
7250 buffer_add_id (buf, 0);
7252 token = mono_image_get_entry_point (ass->image);
7254 buffer_add_id (buf, 0);
7256 m = mono_get_method (ass->image, token, NULL);
7257 buffer_add_methodid (buf, domain, m);
7262 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7263 buffer_add_moduleid (buf, domain, ass->image);
7266 case CMD_ASSEMBLY_GET_OBJECT: {
7267 MonoObject *o = (MonoObject*)mono_assembly_get_object (domain, ass);
7268 buffer_add_objid (buf, o);
7271 case CMD_ASSEMBLY_GET_TYPE: {
7272 char *s = decode_string (p, &p, end);
7273 gboolean ignorecase = decode_byte (p, &p, end);
7274 MonoTypeNameParse info;
7276 gboolean type_resolve, res;
7277 MonoDomain *d = mono_domain_get ();
7279 /* This is needed to be able to find referenced assemblies */
7280 res = mono_domain_set (domain, FALSE);
7283 if (!mono_reflection_parse_type (s, &info)) {
7286 if (info.assembly.name)
7288 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
7290 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
7291 mono_reflection_free_type_info (&info);
7294 mono_domain_set (d, TRUE);
7298 case CMD_ASSEMBLY_GET_NAME: {
7300 MonoAssembly *mass = ass;
7302 name = g_strdup_printf (
7303 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7305 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7306 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7307 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7308 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7310 buffer_add_string (buf, name);
7315 return ERR_NOT_IMPLEMENTED;
7322 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7328 case CMD_MODULE_GET_INFO: {
7329 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7332 basename = g_path_get_basename (image->name);
7333 buffer_add_string (buf, basename); // name
7334 buffer_add_string (buf, image->module_name); // scopename
7335 buffer_add_string (buf, image->name); // fqname
7336 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7337 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7342 return ERR_NOT_IMPLEMENTED;
7349 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7351 if (val && val->vtable->klass == mono_defaults.monotype_class) {
7352 /* Special case these so the client doesn't have to handle Type objects */
7354 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7355 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7356 } else if (MONO_TYPE_IS_REFERENCE (t))
7357 buffer_add_value (buf, t, &val, domain);
7359 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7363 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7369 buffer_add_int (buf, 0);
7373 for (i = 0; i < cinfo->num_attrs; ++i) {
7374 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7377 buffer_add_int (buf, nattrs);
7379 for (i = 0; i < cinfo->num_attrs; ++i) {
7380 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7381 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7382 MonoArray *typed_args, *named_args;
7384 CattrNamedArg *arginfo = NULL;
7387 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
7388 g_assert (mono_error_ok (&error));
7390 buffer_add_methodid (buf, domain, attr->ctor);
7394 buffer_add_int (buf, mono_array_length (typed_args));
7395 for (j = 0; j < mono_array_length (typed_args); ++j) {
7396 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7398 t = mono_method_signature (attr->ctor)->params [j];
7400 buffer_add_cattr_arg (buf, t, domain, val);
7403 buffer_add_int (buf, 0);
7408 buffer_add_int (buf, mono_array_length (named_args));
7410 for (j = 0; j < mono_array_length (named_args); ++j) {
7411 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7413 if (arginfo [j].prop) {
7414 buffer_add_byte (buf, 0x54);
7415 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7416 } else if (arginfo [j].field) {
7417 buffer_add_byte (buf, 0x53);
7418 buffer_add_fieldid (buf, domain, arginfo [j].field);
7420 g_assert_not_reached ();
7423 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7426 buffer_add_int (buf, 0);
7433 /* FIXME: Code duplication with icall.c */
7435 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7440 mono_class_setup_interfaces (klass, error);
7441 if (!mono_error_ok (error))
7444 for (i = 0; i < klass->interface_count; i++) {
7445 ic = klass->interfaces [i];
7446 g_hash_table_insert (ifaces, ic, ic);
7448 collect_interfaces (ic, ifaces, error);
7449 if (!mono_error_ok (error))
7455 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7465 case CMD_TYPE_GET_INFO: {
7466 buffer_add_string (buf, klass->name_space);
7467 buffer_add_string (buf, klass->name);
7469 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7470 buffer_add_string (buf, name);
7472 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7473 buffer_add_moduleid (buf, domain, klass->image);
7474 buffer_add_typeid (buf, domain, klass->parent);
7475 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7476 buffer_add_typeid (buf, domain, klass->element_class);
7478 buffer_add_id (buf, 0);
7479 buffer_add_int (buf, klass->type_token);
7480 buffer_add_byte (buf, klass->rank);
7481 buffer_add_int (buf, klass->flags);
7483 type = &klass->byval_arg;
7484 // FIXME: Can't decide whenever a class represents a byref type
7487 if (type->type == MONO_TYPE_PTR)
7489 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7491 if (type->type == MONO_TYPE_VALUETYPE)
7493 if (klass->enumtype)
7495 if (klass->generic_container)
7497 if (klass->generic_container || klass->generic_class)
7499 buffer_add_byte (buf, b);
7502 while ((nested = mono_class_get_nested_types (klass, &iter)))
7504 buffer_add_int (buf, nnested);
7506 while ((nested = mono_class_get_nested_types (klass, &iter)))
7507 buffer_add_typeid (buf, domain, nested);
7508 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7509 if (klass->generic_container)
7510 buffer_add_typeid (buf, domain, klass);
7511 else if (klass->generic_class)
7512 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7514 buffer_add_id (buf, 0);
7516 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7519 if (klass->generic_class) {
7520 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7522 count = inst->type_argc;
7523 buffer_add_int (buf, count);
7524 for (i = 0; i < count; i++)
7525 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7526 } else if (klass->generic_container) {
7527 MonoGenericContainer *container = klass->generic_container;
7530 count = container->type_argc;
7531 buffer_add_int (buf, count);
7532 for (i = 0; i < count; i++) {
7533 pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
7534 buffer_add_typeid (buf, domain, pklass);
7537 buffer_add_int (buf, 0);
7542 case CMD_TYPE_GET_METHODS: {
7545 gpointer iter = NULL;
7548 mono_class_setup_methods (klass);
7550 nmethods = mono_class_num_methods (klass);
7552 buffer_add_int (buf, nmethods);
7554 while ((m = mono_class_get_methods (klass, &iter))) {
7555 buffer_add_methodid (buf, domain, m);
7558 g_assert (i == nmethods);
7561 case CMD_TYPE_GET_FIELDS: {
7564 gpointer iter = NULL;
7567 nfields = mono_class_num_fields (klass);
7569 buffer_add_int (buf, nfields);
7571 while ((f = mono_class_get_fields (klass, &iter))) {
7572 buffer_add_fieldid (buf, domain, f);
7573 buffer_add_string (buf, f->name);
7574 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7575 buffer_add_int (buf, f->type->attrs);
7578 g_assert (i == nfields);
7581 case CMD_TYPE_GET_PROPERTIES: {
7584 gpointer iter = NULL;
7587 nprops = mono_class_num_properties (klass);
7589 buffer_add_int (buf, nprops);
7591 while ((p = mono_class_get_properties (klass, &iter))) {
7592 buffer_add_propertyid (buf, domain, p);
7593 buffer_add_string (buf, p->name);
7594 buffer_add_methodid (buf, domain, p->get);
7595 buffer_add_methodid (buf, domain, p->set);
7596 buffer_add_int (buf, p->attrs);
7599 g_assert (i == nprops);
7602 case CMD_TYPE_GET_CATTRS: {
7603 MonoClass *attr_klass;
7604 MonoCustomAttrInfo *cinfo;
7606 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7607 /* attr_klass can be NULL */
7611 cinfo = mono_custom_attrs_from_class (klass);
7613 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7616 case CMD_TYPE_GET_FIELD_CATTRS: {
7617 MonoClass *attr_klass;
7618 MonoCustomAttrInfo *cinfo;
7619 MonoClassField *field;
7621 field = decode_fieldid (p, &p, end, NULL, &err);
7624 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7628 cinfo = mono_custom_attrs_from_field (klass, field);
7630 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7633 case CMD_TYPE_GET_PROPERTY_CATTRS: {
7634 MonoClass *attr_klass;
7635 MonoCustomAttrInfo *cinfo;
7638 prop = decode_propertyid (p, &p, end, NULL, &err);
7641 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7645 cinfo = mono_custom_attrs_from_property (klass, prop);
7647 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7650 case CMD_TYPE_GET_VALUES:
7651 case CMD_TYPE_GET_VALUES_2: {
7658 MonoThread *thread_obj;
7659 MonoInternalThread *thread = NULL;
7660 guint32 special_static_type;
7662 if (command == CMD_TYPE_GET_VALUES_2) {
7663 int objid = decode_objid (p, &p, end);
7666 err = get_object (objid, (MonoObject**)&thread_obj);
7670 thread = THREAD_TO_INTERNAL (thread_obj);
7673 len = decode_int (p, &p, end);
7674 for (i = 0; i < len; ++i) {
7675 f = decode_fieldid (p, &p, end, NULL, &err);
7679 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7680 return ERR_INVALID_FIELDID;
7681 special_static_type = mono_class_field_get_special_static_type (f);
7682 if (special_static_type != SPECIAL_STATIC_NONE) {
7683 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
7684 return ERR_INVALID_FIELDID;
7687 /* Check that the field belongs to the object */
7689 for (k = klass; k; k = k->parent) {
7690 if (k == f->parent) {
7696 return ERR_INVALID_FIELDID;
7698 vtable = mono_class_vtable (domain, f->parent);
7699 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7700 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
7701 buffer_add_value (buf, f->type, val, domain);
7706 case CMD_TYPE_SET_VALUES: {
7714 len = decode_int (p, &p, end);
7715 for (i = 0; i < len; ++i) {
7716 f = decode_fieldid (p, &p, end, NULL, &err);
7720 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7721 return ERR_INVALID_FIELDID;
7722 if (mono_class_field_is_special_static (f))
7723 return ERR_INVALID_FIELDID;
7725 /* Check that the field belongs to the object */
7727 for (k = klass; k; k = k->parent) {
7728 if (k == f->parent) {
7734 return ERR_INVALID_FIELDID;
7736 // FIXME: Check for literal/const
7738 vtable = mono_class_vtable (domain, f->parent);
7739 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7740 err = decode_value (f->type, domain, val, p, &p, end);
7745 if (MONO_TYPE_IS_REFERENCE (f->type))
7746 mono_field_static_set_value (vtable, f, *(gpointer*)val);
7748 mono_field_static_set_value (vtable, f, val);
7753 case CMD_TYPE_GET_OBJECT: {
7754 MonoObject *o = (MonoObject*)mono_type_get_object (domain, &klass->byval_arg);
7755 buffer_add_objid (buf, o);
7758 case CMD_TYPE_GET_SOURCE_FILES:
7759 case CMD_TYPE_GET_SOURCE_FILES_2: {
7760 char *source_file, *base;
7764 files = get_source_files_for_type (klass);
7766 buffer_add_int (buf, files->len);
7767 for (i = 0; i < files->len; ++i) {
7768 source_file = g_ptr_array_index (files, i);
7769 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
7770 buffer_add_string (buf, source_file);
7772 base = g_path_get_basename (source_file);
7773 buffer_add_string (buf, base);
7776 g_free (source_file);
7778 g_ptr_array_free (files, TRUE);
7781 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
7782 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
7786 if (mono_class_is_assignable_from (klass, oklass))
7787 buffer_add_byte (buf, 1);
7789 buffer_add_byte (buf, 0);
7792 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
7793 char *name = decode_string (p, &p, end);
7794 int i, flags = decode_int (p, &p, end);
7795 MonoException *ex = NULL;
7796 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
7799 return ERR_LOADER_ERROR;
7800 buffer_add_int (buf, array->len);
7801 for (i = 0; i < array->len; ++i) {
7802 MonoMethod *method = g_ptr_array_index (array, i);
7803 buffer_add_methodid (buf, domain, method);
7806 g_ptr_array_free (array, TRUE);
7810 case CMD_TYPE_GET_INTERFACES: {
7812 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
7814 MonoClass *tclass, *iface;
7815 GHashTableIter iter;
7819 for (parent = tclass; parent; parent = parent->parent) {
7820 mono_class_setup_interfaces (parent, &error);
7821 if (!mono_error_ok (&error))
7822 return ERR_LOADER_ERROR;
7823 collect_interfaces (parent, iface_hash, &error);
7824 if (!mono_error_ok (&error))
7825 return ERR_LOADER_ERROR;
7828 buffer_add_int (buf, g_hash_table_size (iface_hash));
7830 g_hash_table_iter_init (&iter, iface_hash);
7831 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
7832 buffer_add_typeid (buf, domain, iface);
7833 g_hash_table_destroy (iface_hash);
7836 case CMD_TYPE_GET_INTERFACE_MAP: {
7837 int tindex, ioffset;
7838 gboolean variance_used;
7840 int len, nmethods, i;
7844 len = decode_int (p, &p, end);
7845 mono_class_setup_vtable (klass);
7847 for (tindex = 0; tindex < len; ++tindex) {
7848 iclass = decode_typeid (p, &p, end, NULL, &err);
7852 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
7854 return ERR_INVALID_ARGUMENT;
7856 nmethods = mono_class_num_methods (iclass);
7857 buffer_add_int (buf, nmethods);
7860 while ((method = mono_class_get_methods (iclass, &iter))) {
7861 buffer_add_methodid (buf, domain, method);
7863 for (i = 0; i < nmethods; ++i)
7864 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
7868 case CMD_TYPE_IS_INITIALIZED: {
7869 MonoVTable *vtable = mono_class_vtable (domain, klass);
7872 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
7874 buffer_add_int (buf, 0);
7878 return ERR_NOT_IMPLEMENTED;
7885 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7888 MonoDomain *old_domain;
7892 klass = decode_typeid (p, &p, end, &domain, &err);
7896 old_domain = mono_domain_get ();
7898 mono_domain_set (domain, TRUE);
7900 err = type_commands_internal (command, klass, domain, p, end, buf);
7902 mono_domain_set (old_domain, TRUE);
7908 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7910 MonoMethodHeader *header;
7914 case CMD_METHOD_GET_NAME: {
7915 buffer_add_string (buf, method->name);
7918 case CMD_METHOD_GET_DECLARING_TYPE: {
7919 buffer_add_typeid (buf, domain, method->klass);
7922 case CMD_METHOD_GET_DEBUG_INFO: {
7923 MonoDebugMethodInfo *minfo;
7925 int i, j, n_il_offsets;
7928 int *column_numbers;
7930 GPtrArray *source_file_list;
7932 header = mono_method_get_header (method);
7934 buffer_add_int (buf, 0);
7935 buffer_add_string (buf, "");
7936 buffer_add_int (buf, 0);
7940 minfo = mono_debug_lookup_method (method);
7942 buffer_add_int (buf, header->code_size);
7943 buffer_add_string (buf, "");
7944 buffer_add_int (buf, 0);
7945 mono_metadata_free_mh (header);
7949 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, &n_il_offsets, &il_offsets, &line_numbers, &column_numbers, &source_files);
7950 buffer_add_int (buf, header->code_size);
7951 if (CHECK_PROTOCOL_VERSION (2, 13)) {
7952 buffer_add_int (buf, source_file_list->len);
7953 for (i = 0; i < source_file_list->len; ++i) {
7954 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
7955 buffer_add_string (buf, sinfo->source_file);
7956 if (CHECK_PROTOCOL_VERSION (2, 14)) {
7957 for (j = 0; j < 16; ++j)
7958 buffer_add_byte (buf, sinfo->hash [j]);
7962 buffer_add_string (buf, source_file);
7964 buffer_add_int (buf, n_il_offsets);
7965 DEBUG (10, fprintf (log_file, "Line number table for method %s:\n", mono_method_full_name (method, TRUE)));
7966 for (i = 0; i < n_il_offsets; ++i) {
7967 const char *srcfile = "";
7969 if (source_files [i] != -1) {
7970 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
7971 srcfile = sinfo->source_file;
7973 DEBUG (10, fprintf (log_file, "IL%x -> %s:%d %d\n", il_offsets [i], srcfile, line_numbers [i], column_numbers ? column_numbers [i] : -1));
7974 buffer_add_int (buf, il_offsets [i]);
7975 buffer_add_int (buf, line_numbers [i]);
7976 if (CHECK_PROTOCOL_VERSION (2, 13))
7977 buffer_add_int (buf, source_files [i]);
7978 if (CHECK_PROTOCOL_VERSION (2, 19))
7979 buffer_add_int (buf, column_numbers ? column_numbers [i] : -1);
7981 g_free (source_file);
7982 g_free (il_offsets);
7983 g_free (line_numbers);
7984 g_free (source_files);
7985 g_ptr_array_free (source_file_list, TRUE);
7986 mono_metadata_free_mh (header);
7989 case CMD_METHOD_GET_PARAM_INFO: {
7990 MonoMethodSignature *sig = mono_method_signature (method);
7994 /* FIXME: mono_class_from_mono_type () and byrefs */
7996 /* FIXME: Use a smaller encoding */
7997 buffer_add_int (buf, sig->call_convention);
7998 buffer_add_int (buf, sig->param_count);
7999 buffer_add_int (buf, sig->generic_param_count);
8000 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
8001 for (i = 0; i < sig->param_count; ++i) {
8003 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
8006 /* Emit parameter names */
8007 names = g_new (char *, sig->param_count);
8008 mono_method_get_param_names (method, (const char **) names);
8009 for (i = 0; i < sig->param_count; ++i)
8010 buffer_add_string (buf, names [i]);
8015 case CMD_METHOD_GET_LOCALS_INFO: {
8016 int i, j, num_locals;
8017 MonoDebugLocalsInfo *locals;
8019 header = mono_method_get_header (method);
8021 return ERR_INVALID_ARGUMENT;
8023 buffer_add_int (buf, header->num_locals);
8026 for (i = 0; i < header->num_locals; ++i)
8027 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
8030 locals = mono_debug_lookup_locals (method);
8032 num_locals = locals->num_locals;
8035 for (i = 0; i < header->num_locals; ++i) {
8036 for (j = 0; j < num_locals; ++j)
8037 if (locals->locals [j].index == i)
8040 buffer_add_string (buf, locals->locals [j].name);
8042 buffer_add_string (buf, "");
8046 for (i = 0; i < header->num_locals; ++i) {
8047 for (j = 0; j < num_locals; ++j)
8048 if (locals->locals [j].index == i)
8050 if (j < num_locals && locals->locals [j].block) {
8051 buffer_add_int (buf, locals->locals [j].block->start_offset);
8052 buffer_add_int (buf, locals->locals [j].block->end_offset);
8054 buffer_add_int (buf, 0);
8055 buffer_add_int (buf, header->code_size);
8058 mono_metadata_free_mh (header);
8061 mono_debug_symfile_free_locals (locals);
8065 case CMD_METHOD_GET_INFO:
8066 buffer_add_int (buf, method->flags);
8067 buffer_add_int (buf, method->iflags);
8068 buffer_add_int (buf, method->token);
8069 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8071 if (method->is_generic)
8073 if (mono_method_signature (method)->generic_param_count)
8075 buffer_add_byte (buf, attrs);
8076 if (method->is_generic || method->is_inflated) {
8079 if (method->is_generic) {
8082 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8084 result = imethod->declaring;
8085 if (imethod->context.class_inst) {
8086 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8087 /*Generic methods gets the context of the GTD.*/
8088 if (mono_class_get_context (klass))
8089 result = mono_class_inflate_generic_method_full (result, klass, mono_class_get_context (klass));
8093 buffer_add_methodid (buf, domain, result);
8095 buffer_add_id (buf, 0);
8097 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8098 if (mono_method_signature (method)->generic_param_count) {
8101 if (method->is_inflated) {
8102 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
8104 count = inst->type_argc;
8105 buffer_add_int (buf, count);
8107 for (i = 0; i < count; i++)
8108 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8110 buffer_add_int (buf, 0);
8112 } else if (method->is_generic) {
8113 MonoGenericContainer *container = mono_method_get_generic_container (method);
8115 count = mono_method_signature (method)->generic_param_count;
8116 buffer_add_int (buf, count);
8117 for (i = 0; i < count; i++) {
8118 MonoGenericParam *param = mono_generic_container_get_param (container, i);
8119 MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
8120 buffer_add_typeid (buf, domain, pklass);
8123 buffer_add_int (buf, 0);
8126 buffer_add_int (buf, 0);
8131 case CMD_METHOD_GET_BODY: {
8134 header = mono_method_get_header (method);
8136 buffer_add_int (buf, 0);
8138 if (CHECK_PROTOCOL_VERSION (2, 18))
8139 buffer_add_int (buf, 0);
8141 buffer_add_int (buf, header->code_size);
8142 for (i = 0; i < header->code_size; ++i)
8143 buffer_add_byte (buf, header->code [i]);
8145 if (CHECK_PROTOCOL_VERSION (2, 18)) {
8146 buffer_add_int (buf, header->num_clauses);
8147 for (i = 0; i < header->num_clauses; ++i) {
8148 MonoExceptionClause *clause = &header->clauses [i];
8150 buffer_add_int (buf, clause->flags);
8151 buffer_add_int (buf, clause->try_offset);
8152 buffer_add_int (buf, clause->try_len);
8153 buffer_add_int (buf, clause->handler_offset);
8154 buffer_add_int (buf, clause->handler_len);
8155 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
8156 buffer_add_typeid (buf, domain, clause->data.catch_class);
8157 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8158 buffer_add_int (buf, clause->data.filter_offset);
8162 mono_metadata_free_mh (header);
8167 case CMD_METHOD_RESOLVE_TOKEN: {
8168 guint32 token = decode_int (p, &p, end);
8171 switch (mono_metadata_token_code (token)) {
8172 case MONO_TOKEN_STRING: {
8176 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
8179 s2 = mono_string_to_utf8 (s);
8181 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8182 buffer_add_string (buf, s2);
8188 MonoClass *handle_class;
8190 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8191 val = mono_method_get_wrapper_data (method, token);
8192 handle_class = mono_method_get_wrapper_data (method, token + 1);
8194 if (handle_class == NULL) {
8195 // Can't figure out the token type
8196 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8200 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
8204 if (handle_class == mono_defaults.typehandle_class) {
8205 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8206 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8207 buffer_add_typeid (buf, domain, (MonoClass *) val);
8209 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
8210 } else if (handle_class == mono_defaults.fieldhandle_class) {
8211 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8212 buffer_add_fieldid (buf, domain, val);
8213 } else if (handle_class == mono_defaults.methodhandle_class) {
8214 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8215 buffer_add_methodid (buf, domain, val);
8216 } else if (handle_class == mono_defaults.string_class) {
8219 s = mono_string_to_utf8 (val);
8220 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8221 buffer_add_string (buf, s);
8224 g_assert_not_reached ();
8231 case CMD_METHOD_GET_CATTRS: {
8232 MonoClass *attr_klass;
8233 MonoCustomAttrInfo *cinfo;
8235 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8236 /* attr_klass can be NULL */
8240 cinfo = mono_custom_attrs_from_method (method);
8242 buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
8245 case CMD_METHOD_MAKE_GENERIC_METHOD: {
8246 MonoType **type_argv;
8250 MonoGenericInst *ginst;
8251 MonoGenericContext tmp_context;
8252 MonoMethod *inflated;
8254 type_argc = decode_int (p, &p, end);
8255 type_argv = g_new0 (MonoType*, type_argc);
8256 for (i = 0; i < type_argc; ++i) {
8257 klass = decode_typeid (p, &p, end, &d, &err);
8264 return ERR_INVALID_ARGUMENT;
8266 type_argv [i] = &klass->byval_arg;
8268 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
8270 tmp_context.class_inst = method->klass->generic_class ? method->klass->generic_class->context.class_inst : NULL;
8271 tmp_context.method_inst = ginst;
8273 inflated = mono_class_inflate_generic_method (method, &tmp_context);
8274 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
8275 return ERR_INVALID_ARGUMENT;
8276 buffer_add_methodid (buf, domain, inflated);
8280 return ERR_NOT_IMPLEMENTED;
8287 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8290 MonoDomain *old_domain;
8294 method = decode_methodid (p, &p, end, &domain, &err);
8298 old_domain = mono_domain_get ();
8300 mono_domain_set (domain, TRUE);
8302 err = method_commands_internal (command, method, domain, p, end, buf);
8304 mono_domain_set (old_domain, TRUE);
8310 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8312 int objid = decode_objid (p, &p, end);
8314 MonoThread *thread_obj;
8315 MonoInternalThread *thread;
8317 err = get_object (objid, (MonoObject**)&thread_obj);
8321 thread = THREAD_TO_INTERNAL (thread_obj);
8324 case CMD_THREAD_GET_NAME: {
8326 gunichar2 *s = mono_thread_get_name (thread, &name_len);
8329 buffer_add_int (buf, 0);
8334 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
8336 buffer_add_int (buf, len);
8337 buffer_add_data (buf, (guint8*)name, len);
8342 case CMD_THREAD_GET_FRAME_INFO: {
8343 DebuggerTlsData *tls;
8344 int i, start_frame, length;
8346 // Wait for suspending if it already started
8347 // FIXME: Races with suspend_count
8348 while (!is_suspended ()) {
8350 wait_for_suspend ();
8354 wait_for_suspend ();
8355 if (!is_suspended ())
8356 return ERR_NOT_SUSPENDED;
8359 start_frame = decode_int (p, &p, end);
8360 length = decode_int (p, &p, end);
8362 if (start_frame != 0 || length != -1)
8363 return ERR_NOT_IMPLEMENTED;
8365 mono_loader_lock ();
8366 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8367 mono_loader_unlock ();
8370 compute_frame_info (thread, tls);
8372 buffer_add_int (buf, tls->frame_count);
8373 for (i = 0; i < tls->frame_count; ++i) {
8374 buffer_add_int (buf, tls->frames [i]->id);
8375 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
8376 buffer_add_int (buf, tls->frames [i]->il_offset);
8378 * Instead of passing the frame type directly to the client, we associate
8379 * it with the previous frame using a set of flags. This avoids lots of
8380 * conditional code in the client, since a frame whose type isn't
8381 * FRAME_TYPE_MANAGED has no method, location, etc.
8383 buffer_add_byte (buf, tls->frames [i]->flags);
8388 case CMD_THREAD_GET_STATE:
8389 buffer_add_int (buf, thread->state);
8391 case CMD_THREAD_GET_INFO:
8392 buffer_add_byte (buf, thread->threadpool_thread);
8394 case CMD_THREAD_GET_ID:
8395 buffer_add_long (buf, (guint64)(gsize)thread);
8397 case CMD_THREAD_GET_TID:
8398 buffer_add_long (buf, (guint64)thread->tid);
8401 return ERR_NOT_IMPLEMENTED;
8408 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8412 MonoThread *thread_obj;
8413 MonoInternalThread *thread;
8414 int pos, i, len, frame_idx;
8415 DebuggerTlsData *tls;
8417 MonoDebugMethodJitInfo *jit;
8418 MonoDebugVarInfo *var;
8419 MonoMethodSignature *sig;
8421 MonoMethodHeader *header;
8423 objid = decode_objid (p, &p, end);
8424 err = get_object (objid, (MonoObject**)&thread_obj);
8428 thread = THREAD_TO_INTERNAL (thread_obj);
8430 id = decode_id (p, &p, end);
8432 mono_loader_lock ();
8433 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8434 mono_loader_unlock ();
8437 for (i = 0; i < tls->frame_count; ++i) {
8438 if (tls->frames [i]->id == id)
8441 if (i == tls->frame_count)
8442 return ERR_INVALID_FRAMEID;
8445 frame = tls->frames [frame_idx];
8447 if (!frame->has_ctx)
8448 return ERR_ABSENT_INFORMATION;
8451 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
8452 if (!frame->jit && frame->api_method->is_inflated)
8453 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
8457 /* This could happen for aot images with no jit debug info */
8458 s = mono_method_full_name (frame->api_method, TRUE);
8459 DEBUG (1, fprintf (log_file, "[dbg] No debug information found for '%s'.\n", s));
8461 return ERR_ABSENT_INFORMATION;
8466 sig = mono_method_signature (frame->actual_method);
8468 if (!get_seq_points (frame->domain, frame->actual_method))
8470 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
8472 return ERR_ABSENT_INFORMATION;
8475 case CMD_STACK_FRAME_GET_VALUES: {
8476 len = decode_int (p, &p, end);
8477 header = mono_method_get_header (frame->actual_method);
8479 for (i = 0; i < len; ++i) {
8480 pos = decode_int (p, &p, end);
8485 g_assert (pos >= 0 && pos < jit->num_params);
8487 var = &jit->params [pos];
8489 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
8491 g_assert (pos >= 0 && pos < jit->num_locals);
8493 var = &jit->locals [pos];
8495 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
8498 mono_metadata_free_mh (header);
8501 case CMD_STACK_FRAME_GET_THIS: {
8502 if (frame->api_method->klass->valuetype) {
8503 if (!sig->hasthis) {
8504 MonoObject *p = NULL;
8505 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
8507 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8510 if (!sig->hasthis) {
8511 MonoObject *p = NULL;
8512 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
8514 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8519 case CMD_STACK_FRAME_SET_VALUES: {
8522 MonoDebugVarInfo *var;
8524 len = decode_int (p, &p, end);
8525 header = mono_method_get_header (frame->actual_method);
8527 for (i = 0; i < len; ++i) {
8528 pos = decode_int (p, &p, end);
8533 g_assert (pos >= 0 && pos < jit->num_params);
8535 t = sig->params [pos];
8536 var = &jit->params [pos];
8538 g_assert (pos >= 0 && pos < jit->num_locals);
8540 t = header->locals [pos];
8541 var = &jit->locals [pos];
8544 if (MONO_TYPE_IS_REFERENCE (t))
8545 val_buf = g_alloca (sizeof (MonoObject*));
8547 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
8548 err = decode_value (t, frame->domain, val_buf, p, &p, end);
8552 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_ctx);
8554 mono_metadata_free_mh (header);
8558 return ERR_NOT_IMPLEMENTED;
8565 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8568 int objid, err, index, len, i, esize;
8571 objid = decode_objid (p, &p, end);
8572 err = get_object (objid, (MonoObject**)&arr);
8577 case CMD_ARRAY_REF_GET_LENGTH:
8578 buffer_add_int (buf, arr->obj.vtable->klass->rank);
8580 buffer_add_int (buf, arr->max_length);
8581 buffer_add_int (buf, 0);
8583 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
8584 buffer_add_int (buf, arr->bounds [i].length);
8585 buffer_add_int (buf, arr->bounds [i].lower_bound);
8589 case CMD_ARRAY_REF_GET_VALUES:
8590 index = decode_int (p, &p, end);
8591 len = decode_int (p, &p, end);
8593 g_assert (index >= 0 && len >= 0);
8594 // Reordered to avoid integer overflow
8595 g_assert (!(index > arr->max_length - len));
8597 esize = mono_array_element_size (arr->obj.vtable->klass);
8598 for (i = index; i < index + len; ++i) {
8599 elem = (gpointer*)((char*)arr->vector + (i * esize));
8600 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
8603 case CMD_ARRAY_REF_SET_VALUES:
8604 index = decode_int (p, &p, end);
8605 len = decode_int (p, &p, end);
8607 g_assert (index >= 0 && len >= 0);
8608 // Reordered to avoid integer overflow
8609 g_assert (!(index > arr->max_length - len));
8611 esize = mono_array_element_size (arr->obj.vtable->klass);
8612 for (i = index; i < index + len; ++i) {
8613 elem = (gpointer*)((char*)arr->vector + (i * esize));
8615 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
8619 return ERR_NOT_IMPLEMENTED;
8626 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8631 int i, index, length;
8634 objid = decode_objid (p, &p, end);
8635 err = get_object (objid, (MonoObject**)&str);
8640 case CMD_STRING_REF_GET_VALUE:
8641 s = mono_string_to_utf8 (str);
8642 buffer_add_string (buf, s);
8645 case CMD_STRING_REF_GET_LENGTH:
8646 buffer_add_long (buf, mono_string_length (str));
8648 case CMD_STRING_REF_GET_CHARS:
8649 index = decode_long (p, &p, end);
8650 length = decode_long (p, &p, end);
8651 if (index > mono_string_length (str) - length)
8652 return ERR_INVALID_ARGUMENT;
8653 c = mono_string_chars (str) + index;
8654 for (i = 0; i < length; ++i)
8655 buffer_add_short (buf, c [i]);
8658 return ERR_NOT_IMPLEMENTED;
8665 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8674 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
8675 objid = decode_objid (p, &p, end);
8676 err = get_object (objid, &obj);
8678 buffer_add_int (buf, 1);
8680 buffer_add_int (buf, 0);
8684 objid = decode_objid (p, &p, end);
8685 err = get_object (objid, &obj);
8690 case CMD_OBJECT_REF_GET_TYPE:
8691 /* This handles transparent proxies too */
8692 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8694 case CMD_OBJECT_REF_GET_VALUES:
8695 len = decode_int (p, &p, end);
8697 for (i = 0; i < len; ++i) {
8698 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
8702 /* Check that the field belongs to the object */
8704 for (k = obj->vtable->klass; k; k = k->parent) {
8705 if (k == f->parent) {
8711 return ERR_INVALID_FIELDID;
8713 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8717 if (mono_class_field_is_special_static (f))
8718 return ERR_INVALID_FIELDID;
8720 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8721 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8722 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8723 mono_field_static_get_value (vtable, f, val);
8724 buffer_add_value (buf, f->type, val, obj->vtable->domain);
8727 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
8731 case CMD_OBJECT_REF_SET_VALUES:
8732 len = decode_int (p, &p, end);
8734 for (i = 0; i < len; ++i) {
8735 f = decode_fieldid (p, &p, end, NULL, &err);
8739 /* Check that the field belongs to the object */
8741 for (k = obj->vtable->klass; k; k = k->parent) {
8742 if (k == f->parent) {
8748 return ERR_INVALID_FIELDID;
8750 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8754 if (mono_class_field_is_special_static (f))
8755 return ERR_INVALID_FIELDID;
8757 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8758 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8760 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8761 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
8766 mono_field_static_set_value (vtable, f, val);
8769 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
8775 case CMD_OBJECT_REF_GET_ADDRESS:
8776 buffer_add_long (buf, (gssize)obj);
8778 case CMD_OBJECT_REF_GET_DOMAIN:
8779 buffer_add_domainid (buf, obj->vtable->domain);
8781 case CMD_OBJECT_REF_GET_INFO:
8782 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8783 buffer_add_domainid (buf, obj->vtable->domain);
8786 return ERR_NOT_IMPLEMENTED;
8793 command_set_to_string (CommandSet command_set)
8795 switch (command_set) {
8798 case CMD_SET_OBJECT_REF:
8799 return "OBJECT_REF";
8800 case CMD_SET_STRING_REF:
8801 return "STRING_REF";
8802 case CMD_SET_THREAD:
8804 case CMD_SET_ARRAY_REF:
8806 case CMD_SET_EVENT_REQUEST:
8807 return "EVENT_REQUEST";
8808 case CMD_SET_STACK_FRAME:
8809 return "STACK_FRAME";
8810 case CMD_SET_APPDOMAIN:
8812 case CMD_SET_ASSEMBLY:
8814 case CMD_SET_METHOD:
8818 case CMD_SET_MODULE:
8827 static const char* vm_cmds_str [] = {
8835 "SET_PROTOCOL_VERSION",
8838 "GET_TYPES_FOR_SOURCE_FILE",
8843 static const char* thread_cmds_str[] = {
8852 static const char* event_cmds_str[] = {
8855 "REQUEST_CLEAR_ALL_BREAKPOINTS"
8858 static const char* appdomain_cmds_str[] = {
8860 "GET_FRIENDLY_NAME",
8862 "GET_ENTRY_ASSEMBLY",
8865 "CREATE_BOXED_VALUE"
8868 static const char* assembly_cmds_str[] = {
8871 "GET_MANIFEST_MODULE",
8877 static const char* module_cmds_str[] = {
8881 static const char* method_cmds_str[] = {
8883 "GET_DECLARING_TYPE",
8891 "MAKE_GENERIC_METHOD"
8894 static const char* type_cmds_str[] = {
8902 "IS_ASSIGNABLE_FROM",
8906 "GET_PROPERTY_CATTRS",
8907 "GET_SOURCE_FILES_2",
8909 "GET_METHODS_BY_NAME_FLAGS",
8911 "GET_INTERFACE_MAP",
8915 static const char* stack_frame_cmds_str[] = {
8921 static const char* array_cmds_str[] = {
8927 static const char* string_cmds_str[] = {
8933 static const char* object_cmds_str[] = {
8944 cmd_to_string (CommandSet set, int command)
8952 cmds_len = G_N_ELEMENTS (vm_cmds_str);
8954 case CMD_SET_OBJECT_REF:
8955 cmds = object_cmds_str;
8956 cmds_len = G_N_ELEMENTS (object_cmds_str);
8958 case CMD_SET_STRING_REF:
8959 cmds = string_cmds_str;
8960 cmds_len = G_N_ELEMENTS (string_cmds_str);
8962 case CMD_SET_THREAD:
8963 cmds = thread_cmds_str;
8964 cmds_len = G_N_ELEMENTS (thread_cmds_str);
8966 case CMD_SET_ARRAY_REF:
8967 cmds = array_cmds_str;
8968 cmds_len = G_N_ELEMENTS (array_cmds_str);
8970 case CMD_SET_EVENT_REQUEST:
8971 cmds = event_cmds_str;
8972 cmds_len = G_N_ELEMENTS (event_cmds_str);
8974 case CMD_SET_STACK_FRAME:
8975 cmds = stack_frame_cmds_str;
8976 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
8978 case CMD_SET_APPDOMAIN:
8979 cmds = appdomain_cmds_str;
8980 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
8982 case CMD_SET_ASSEMBLY:
8983 cmds = assembly_cmds_str;
8984 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
8986 case CMD_SET_METHOD:
8987 cmds = method_cmds_str;
8988 cmds_len = G_N_ELEMENTS (method_cmds_str);
8991 cmds = type_cmds_str;
8992 cmds_len = G_N_ELEMENTS (type_cmds_str);
8994 case CMD_SET_MODULE:
8995 cmds = module_cmds_str;
8996 cmds_len = G_N_ELEMENTS (module_cmds_str);
8999 cmds = event_cmds_str;
9000 cmds_len = G_N_ELEMENTS (event_cmds_str);
9005 if (command > 0 && command <= cmds_len)
9006 return cmds [command - 1];
9012 wait_for_attach (void)
9014 #ifndef DISABLE_SOCKET_TRANSPORT
9015 if (listen_fd == -1) {
9016 DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
9020 /* Block and wait for client connection */
9021 conn_fd = socket_transport_accept (listen_fd);
9022 DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
9023 if (conn_fd == -1) {
9024 DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
9028 g_assert_not_reached ();
9032 disconnected = !transport_handshake ();
9034 DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
9044 * This thread handles communication with the debugger client using a JDWP
9047 static guint32 WINAPI
9048 debugger_thread (void *arg)
9050 int res, len, id, flags, command_set = 0, command = 0;
9051 guint8 header [HEADER_LENGTH];
9052 guint8 *data, *p, *end;
9056 gboolean attach_failed = FALSE;
9058 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
9060 debugger_thread_id = GetCurrentThreadId ();
9062 mono_jit_thread_attach (mono_get_root_domain ());
9064 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
9066 mono_set_is_debugger_attached (TRUE);
9068 if (agent_config.defer) {
9069 if (!wait_for_attach ()) {
9070 DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
9071 attach_failed = TRUE; // Don't abort process when we can't listen
9073 /* Send start event to client */
9074 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
9078 while (!attach_failed) {
9079 res = transport_recv (header, HEADER_LENGTH);
9081 /* This will break if the socket is closed during shutdown too */
9082 if (res != HEADER_LENGTH) {
9083 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH));
9088 end = header + HEADER_LENGTH;
9090 len = decode_int (p, &p, end);
9091 id = decode_int (p, &p, end);
9092 flags = decode_byte (p, &p, end);
9093 command_set = decode_byte (p, &p, end);
9094 command = decode_byte (p, &p, end);
9096 g_assert (flags == 0);
9099 const char *cmd_str;
9102 cmd_str = cmd_to_string (command_set, command);
9104 sprintf (cmd_num, "%d", command);
9108 DEBUG (1, fprintf (log_file, "[dbg] Command %s(%s) [%d].\n", command_set_to_string (command_set), cmd_str, id));
9111 data = g_malloc (len - HEADER_LENGTH);
9112 if (len - HEADER_LENGTH > 0)
9114 res = transport_recv (data, len - HEADER_LENGTH);
9115 if (res != len - HEADER_LENGTH) {
9116 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH));
9122 end = data + (len - HEADER_LENGTH);
9124 buffer_init (&buf, 128);
9129 /* Process the request */
9130 switch (command_set) {
9132 err = vm_commands (command, id, p, end, &buf);
9133 if (!err && command == CMD_VM_INVOKE_METHOD)
9134 /* Sent after the invoke is complete */
9137 case CMD_SET_EVENT_REQUEST:
9138 err = event_commands (command, p, end, &buf);
9140 case CMD_SET_APPDOMAIN:
9141 err = domain_commands (command, p, end, &buf);
9143 case CMD_SET_ASSEMBLY:
9144 err = assembly_commands (command, p, end, &buf);
9146 case CMD_SET_MODULE:
9147 err = module_commands (command, p, end, &buf);
9150 err = type_commands (command, p, end, &buf);
9152 case CMD_SET_METHOD:
9153 err = method_commands (command, p, end, &buf);
9155 case CMD_SET_THREAD:
9156 err = thread_commands (command, p, end, &buf);
9158 case CMD_SET_STACK_FRAME:
9159 err = frame_commands (command, p, end, &buf);
9161 case CMD_SET_ARRAY_REF:
9162 err = array_commands (command, p, end, &buf);
9164 case CMD_SET_STRING_REF:
9165 err = string_commands (command, p, end, &buf);
9167 case CMD_SET_OBJECT_REF:
9168 err = object_commands (command, p, end, &buf);
9171 err = ERR_NOT_IMPLEMENTED;
9175 send_reply_packet (id, err, &buf);
9180 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
9184 mono_set_is_debugger_attached (FALSE);
9186 mono_mutex_lock (&debugger_thread_exited_mutex);
9187 debugger_thread_exited = TRUE;
9188 mono_cond_signal (&debugger_thread_exited_cond);
9189 mono_mutex_unlock (&debugger_thread_exited_mutex);
9191 DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
9193 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
9194 DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
9195 start_debugger_thread ();
9201 #else /* DISABLE_DEBUGGER_AGENT */
9204 mono_debugger_agent_parse_options (char *options)
9206 g_error ("This runtime is configured with the debugger agent disabled.");
9210 mono_debugger_agent_init (void)
9215 mono_debugger_agent_breakpoint_hit (void *sigctx)
9220 mono_debugger_agent_single_step_event (void *sigctx)
9225 mono_debugger_agent_free_domain_info (MonoDomain *domain)
9230 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
9236 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
9237 MonoContext *catch_ctx)
9242 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9247 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9252 mono_debugger_agent_user_break (void)
9258 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
9263 mono_debugger_agent_debug_log_is_enabled (void)