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 ();
3503 * Send an event to the client, suspending the vm if needed.
3504 * LOCKING: Since this can suspend the calling thread, no locks should be held
3506 * The EVENTS list is freed by this function.
3509 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3513 MonoDomain *domain = mono_domain_get ();
3514 MonoThread *thread = NULL;
3515 MonoObject *keepalive_obj = NULL;
3516 gboolean send_success = FALSE;
3521 DEBUG (2, fprintf (log_file, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event)));
3525 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3526 // FIXME: We miss those events
3527 DEBUG (2, fprintf (log_file, "VM start event not sent yet: dropping %s\n", event_to_string (event)));
3531 if (vm_death_event_sent) {
3532 DEBUG (2, fprintf (log_file, "VM death event has been sent: dropping %s\n", event_to_string (event)));
3536 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3537 DEBUG (2, fprintf (log_file, "Mono runtime is shutting down: dropping %s\n", event_to_string (event)));
3542 DEBUG (2, fprintf (log_file, "Debugger client is not connected: dropping %s\n", event_to_string (event)));
3546 if (event == EVENT_KIND_KEEPALIVE)
3547 suspend_policy = SUSPEND_POLICY_NONE;
3552 if (agent_config.defer) {
3553 /* Make sure the thread id is always set when doing deferred debugging */
3554 if (debugger_thread_id == GetCurrentThreadId ()) {
3555 /* Don't suspend on events from the debugger thread */
3556 suspend_policy = SUSPEND_POLICY_NONE;
3557 thread = mono_thread_get_main ();
3559 else thread = mono_thread_current ();
3561 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3562 // FIXME: Send these with a NULL thread, don't suspend the current thread
3567 nevents = g_slist_length (events);
3568 buffer_init (&buf, 128);
3569 buffer_add_byte (&buf, suspend_policy);
3570 buffer_add_int (&buf, nevents);
3572 for (l = events; l; l = l->next) {
3573 buffer_add_byte (&buf, event); // event kind
3574 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3579 thread = mono_thread_current ();
3581 if (event == EVENT_KIND_VM_START && arg != NULL)
3584 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3587 case EVENT_KIND_THREAD_START:
3588 case EVENT_KIND_THREAD_DEATH:
3590 case EVENT_KIND_APPDOMAIN_CREATE:
3591 case EVENT_KIND_APPDOMAIN_UNLOAD:
3592 buffer_add_domainid (&buf, arg);
3594 case EVENT_KIND_METHOD_ENTRY:
3595 case EVENT_KIND_METHOD_EXIT:
3596 buffer_add_methodid (&buf, domain, arg);
3598 case EVENT_KIND_ASSEMBLY_LOAD:
3599 case EVENT_KIND_ASSEMBLY_UNLOAD:
3600 buffer_add_assemblyid (&buf, domain, arg);
3602 case EVENT_KIND_TYPE_LOAD:
3603 buffer_add_typeid (&buf, domain, arg);
3605 case EVENT_KIND_BREAKPOINT:
3606 case EVENT_KIND_STEP:
3607 buffer_add_methodid (&buf, domain, arg);
3608 buffer_add_long (&buf, il_offset);
3610 case EVENT_KIND_VM_START:
3611 buffer_add_domainid (&buf, mono_get_root_domain ());
3613 case EVENT_KIND_VM_DEATH:
3615 case EVENT_KIND_EXCEPTION: {
3616 EventInfo *ei = arg;
3617 buffer_add_objid (&buf, ei->exc);
3619 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3620 * later after the suspension. (#12494).
3622 keepalive_obj = ei->exc;
3625 case EVENT_KIND_USER_BREAK:
3627 case EVENT_KIND_USER_LOG: {
3628 EventInfo *ei = arg;
3629 buffer_add_int (&buf, ei->level);
3630 buffer_add_string (&buf, ei->category ? ei->category : "");
3631 buffer_add_string (&buf, ei->message ? ei->message : "");
3634 case EVENT_KIND_KEEPALIVE:
3635 suspend_policy = SUSPEND_POLICY_NONE;
3638 g_assert_not_reached ();
3642 if (event == EVENT_KIND_VM_START) {
3643 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3644 if (!agent_config.defer)
3645 start_debugger_thread ();
3648 if (event == EVENT_KIND_VM_DEATH) {
3649 vm_death_event_sent = TRUE;
3650 suspend_policy = SUSPEND_POLICY_NONE;
3653 if (mono_runtime_is_shutting_down ())
3654 suspend_policy = SUSPEND_POLICY_NONE;
3656 if (suspend_policy != SUSPEND_POLICY_NONE) {
3658 * Save the thread context and start suspending before sending the packet,
3659 * since we could be receiving the resume request before send_packet ()
3662 save_thread_context (ctx);
3666 /* This will keep this object alive */
3667 get_objref (keepalive_obj);
3670 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3674 g_slist_free (events);
3677 if (!send_success) {
3678 DEBUG (2, fprintf (log_file, "Sending command %s failed.\n", event_to_string (event)));
3682 if (event == EVENT_KIND_VM_START) {
3683 vm_start_event_sent = TRUE;
3686 DEBUG (1, fprintf (log_file, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer)GetCurrentThreadId (), nevents, event_to_string (event), ecount, suspend_policy));
3688 switch (suspend_policy) {
3689 case SUSPEND_POLICY_NONE:
3691 case SUSPEND_POLICY_ALL:
3694 case SUSPEND_POLICY_EVENT_THREAD:
3698 g_assert_not_reached ();
3703 process_profiler_event (EventKind event, gpointer arg)
3707 EventInfo ei, *ei_arg = NULL;
3709 if (event == EVENT_KIND_TYPE_LOAD) {
3714 mono_loader_lock ();
3715 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3716 mono_loader_unlock ();
3718 process_event (event, arg, 0, NULL, events, suspend_policy);
3722 runtime_initialized (MonoProfiler *prof)
3724 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3725 if (agent_config.defer)
3726 start_debugger_thread ();
3730 runtime_shutdown (MonoProfiler *prof)
3732 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3734 mono_debugger_agent_cleanup ();
3738 thread_startup (MonoProfiler *prof, uintptr_t tid)
3740 MonoInternalThread *thread = mono_thread_internal_current ();
3741 MonoInternalThread *old_thread;
3742 DebuggerTlsData *tls;
3744 if (tid == debugger_thread_id)
3747 g_assert (thread->tid == tid);
3749 mono_loader_lock ();
3750 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3751 mono_loader_unlock ();
3753 if (thread == old_thread) {
3755 * For some reason, thread_startup () might be called for the same thread
3756 * multiple times (attach ?).
3758 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
3762 * thread_end () might not be called for some threads, and the tid could
3765 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
3766 mono_loader_lock ();
3767 mono_g_hash_table_remove (thread_to_tls, old_thread);
3768 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3769 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3770 mono_loader_unlock ();
3774 tls = mono_native_tls_get_value (debugger_tls_id);
3776 // FIXME: Free this somewhere
3777 tls = g_new0 (DebuggerTlsData, 1);
3778 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3779 tls->thread = thread;
3780 mono_native_tls_set_value (debugger_tls_id, tls);
3782 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3784 mono_loader_lock ();
3785 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3786 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3787 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3788 mono_loader_unlock ();
3790 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3793 * suspend_vm () could have missed this thread, so wait for a resume.
3799 thread_end (MonoProfiler *prof, uintptr_t tid)
3801 MonoInternalThread *thread;
3802 DebuggerTlsData *tls = NULL;
3804 mono_loader_lock ();
3805 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3807 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3808 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3810 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3811 tls->terminated = TRUE;
3812 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3813 MONO_GC_UNREGISTER_ROOT (tls->thread);
3817 mono_loader_unlock ();
3819 /* We might be called for threads started before we registered the start callback */
3821 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3822 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3827 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3829 mono_loader_lock ();
3830 g_hash_table_insert (domains, domain, domain);
3831 mono_loader_unlock ();
3833 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3837 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3839 clear_breakpoints_for_domain (domain);
3841 mono_loader_lock ();
3842 /* Invalidate each thread's frame stack */
3843 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3844 mono_loader_unlock ();
3846 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3850 * invalidate_each_thread:
3852 * A GHFunc to invalidate frames.
3853 * value must be a DebuggerTlsData*
3856 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3858 invalidate_frames (value);
3862 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3864 /* Sent later in jit_end () */
3865 mono_loader_lock ();
3866 g_ptr_array_add (pending_assembly_loads, assembly);
3867 mono_loader_unlock ();
3871 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3873 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3875 clear_event_requests_for_assembly (assembly);
3876 clear_types_for_assembly (assembly);
3880 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3882 #if defined(HOST_WIN32) && !defined(__GNUC__)
3883 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3885 gpointer stackptr = __builtin_frame_address (1);
3887 MonoInternalThread *thread = mono_thread_internal_current ();
3888 DebuggerTlsData *tls;
3890 mono_loader_lock ();
3892 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3893 /* Could be the debugger thread with assembly/type load hooks */
3895 tls->invoke_addr = stackptr;
3897 mono_loader_unlock ();
3901 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3904 #if defined(HOST_WIN32) && !defined(__GNUC__)
3905 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3907 gpointer stackptr = __builtin_frame_address (1);
3910 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
3914 * We need to stop single stepping when exiting a runtime invoke, since if it is
3915 * a step out, it may return to native code, and thus never end.
3917 mono_loader_lock ();
3918 ss_invoke_addr = NULL;
3920 for (i = 0; i < event_requests->len; ++i) {
3921 EventRequest *req = g_ptr_array_index (event_requests, i);
3923 if (req->event_kind == EVENT_KIND_STEP) {
3924 ss_destroy (req->info);
3925 g_ptr_array_remove_index_fast (event_requests, i);
3930 mono_loader_unlock ();
3934 send_type_load (MonoClass *klass)
3936 gboolean type_load = FALSE;
3937 MonoDomain *domain = mono_domain_get ();
3938 AgentDomainInfo *info = NULL;
3940 mono_loader_lock ();
3941 mono_domain_lock (domain);
3943 info = get_agent_domain_info (domain);
3945 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
3947 g_hash_table_insert (info->loaded_classes, klass, klass);
3950 mono_domain_unlock (domain);
3951 mono_loader_unlock ();
3953 emit_type_load (klass, klass, NULL);
3957 * Emit load events for all types currently loaded in the domain.
3958 * Takes the loader and domain locks.
3959 * user_data is unused.
3962 send_types_for_domain (MonoDomain *domain, void *user_data)
3964 AgentDomainInfo *info = NULL;
3966 mono_loader_lock ();
3967 mono_domain_lock (domain);
3968 info = get_agent_domain_info (domain);
3970 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
3971 mono_domain_unlock (domain);
3972 mono_loader_unlock ();
3976 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
3979 * We emit type load events when the first method of the type is JITted,
3980 * since the class load profiler callbacks might be called with the
3981 * loader lock held. They could also occur in the debugger thread.
3982 * Same for assembly load events.
3985 MonoAssembly *assembly = NULL;
3987 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
3988 mono_loader_lock ();
3989 if (pending_assembly_loads->len > 0) {
3990 assembly = g_ptr_array_index (pending_assembly_loads, 0);
3991 g_ptr_array_remove_index (pending_assembly_loads, 0);
3993 mono_loader_unlock ();
3996 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4002 send_type_load (method->klass);
4005 add_pending_breakpoints (method, jinfo);
4009 * BREAKPOINTS/SINGLE STEPPING
4013 * Contains information about an inserted breakpoint.
4016 long il_offset, native_offset;
4021 } BreakpointInstance;
4024 * Contains generic information about a breakpoint.
4028 * The method where the breakpoint is placed. Can be NULL in which case it
4029 * is inserted into every method. This is used to implement method entry/
4030 * exit events. Can be a generic method definition, in which case the
4031 * breakpoint is inserted into every instance.
4037 * A list of BreakpointInstance structures describing where the breakpoint
4038 * was inserted. There could be more than one because of
4039 * generics/appdomains/method entry/exit.
4041 GPtrArray *children;
4044 /* List of breakpoints */
4045 static GPtrArray *breakpoints;
4046 /* Maps breakpoint locations to the number of breakpoints at that location */
4047 static GHashTable *bp_locs;
4050 breakpoints_init (void)
4052 breakpoints = g_ptr_array_new ();
4053 bp_locs = g_hash_table_new (NULL, NULL);
4057 * insert_breakpoint:
4059 * Insert the breakpoint described by BP into the method described by
4063 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4066 BreakpointInstance *inst;
4067 SeqPoint *sp = NULL;
4070 mono_error_init (error);
4072 for (i = 0; i < seq_points->len; ++i) {
4073 sp = &seq_points->seq_points [i];
4075 if (sp->il_offset == bp->il_offset)
4079 if (i == seq_points->len) {
4081 * The set of IL offsets with seq points doesn't completely match the
4082 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4084 for (i = 0; i < seq_points->len; ++i) {
4085 sp = &seq_points->seq_points [i];
4087 if (sp->il_offset != METHOD_ENTRY_IL_OFFSET && sp->il_offset != METHOD_EXIT_IL_OFFSET && sp->il_offset + 1 == bp->il_offset)
4092 if (i == seq_points->len) {
4093 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);
4095 for (i = 0; i < seq_points->len; ++i)
4096 DEBUG (1, fprintf (log_file, "%d\n", seq_points->seq_points [i].il_offset));
4099 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4100 g_warning ("%s", s);
4104 g_warning ("%s", s);
4110 inst = g_new0 (BreakpointInstance, 1);
4112 inst->native_offset = sp->native_offset;
4113 inst->ip = (guint8*)ji->code_start + sp->native_offset;
4115 inst->domain = domain;
4117 mono_loader_lock ();
4119 g_ptr_array_add (bp->children, inst);
4121 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4122 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4123 mono_loader_unlock ();
4125 if (sp->native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4126 DEBUG (1, fprintf (log_file, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset));
4127 } else if (count == 0) {
4128 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4129 mono_arch_set_breakpoint (ji, inst->ip);
4135 DEBUG(1, fprintf (log_file, "[dbg] Inserted breakpoint at %s:0x%x.\n", mono_method_full_name (ji->method, TRUE), (int)sp->il_offset));
4139 remove_breakpoint (BreakpointInstance *inst)
4141 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4143 MonoJitInfo *ji = inst->ji;
4144 guint8 *ip = inst->ip;
4146 mono_loader_lock ();
4147 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4148 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4149 mono_loader_unlock ();
4151 g_assert (count > 0);
4153 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4154 mono_arch_clear_breakpoint (ji, ip);
4161 static inline gboolean
4162 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4168 if (method == bp->method)
4170 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4173 if (bp->method->is_inflated && method->is_inflated) {
4174 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4175 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4177 /* Open generic methods should match closed generic methods of the same class */
4178 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4179 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4180 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4182 /* FIXME: Handle !mvar */
4183 if (t1->type != MONO_TYPE_MVAR)
4194 * add_pending_breakpoints:
4196 * Insert pending breakpoints into the newly JITted method METHOD.
4199 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4202 MonoSeqPointInfo *seq_points;
4208 domain = mono_domain_get ();
4210 mono_loader_lock ();
4212 for (i = 0; i < breakpoints->len; ++i) {
4213 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4214 gboolean found = FALSE;
4216 if (!bp_matches_method (bp, method))
4219 for (j = 0; j < bp->children->len; ++j) {
4220 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4227 mono_domain_lock (domain);
4228 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
4229 if (!seq_points && ji->method->is_inflated)
4230 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (ji->method));
4231 mono_domain_unlock (domain);
4233 /* Could be AOT code */
4235 g_assert (seq_points);
4237 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4241 mono_loader_unlock ();
4245 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4251 mono_error_init (error);
4253 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4255 /* Might be AOTed code */
4256 code = mono_aot_get_method (domain, method);
4258 ji = mono_jit_info_table_find (domain, code);
4263 insert_breakpoint (seq_points, domain, ji, bp, error);
4267 clear_breakpoint (MonoBreakpoint *bp);
4272 * Set a breakpoint at IL_OFFSET in METHOD.
4273 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4274 * METHOD can also be a generic method definition, in which case a breakpoint
4275 * is placed in all instances of the method.
4276 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4279 static MonoBreakpoint*
4280 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4283 GHashTableIter iter, iter2;
4286 MonoSeqPointInfo *seq_points;
4289 mono_error_init (error);
4292 // - suspend/resume the vm to prevent code patching problems
4293 // - multiple breakpoints on the same location
4294 // - dynamic methods
4297 bp = g_new0 (MonoBreakpoint, 1);
4298 bp->method = method;
4299 bp->il_offset = il_offset;
4301 bp->children = g_ptr_array_new ();
4303 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));
4305 mono_loader_lock ();
4307 g_hash_table_iter_init (&iter, domains);
4308 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4309 mono_domain_lock (domain);
4311 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4312 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4313 if (bp_matches_method (bp, m))
4314 set_bp_in_method (domain, m, seq_points, bp, error);
4317 mono_domain_unlock (domain);
4320 mono_loader_unlock ();
4322 mono_loader_lock ();
4323 g_ptr_array_add (breakpoints, bp);
4324 mono_loader_unlock ();
4326 if (error && !mono_error_ok (error)) {
4327 clear_breakpoint (bp);
4335 clear_breakpoint (MonoBreakpoint *bp)
4339 // FIXME: locking, races
4340 for (i = 0; i < bp->children->len; ++i) {
4341 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4343 remove_breakpoint (inst);
4348 mono_loader_lock ();
4349 g_ptr_array_remove (breakpoints, bp);
4350 mono_loader_unlock ();
4352 g_ptr_array_free (bp->children, TRUE);
4357 breakpoints_cleanup (void)
4361 mono_loader_lock ();
4363 while (i < event_requests->len) {
4364 EventRequest *req = g_ptr_array_index (event_requests, i);
4366 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4367 clear_breakpoint (req->info);
4368 g_ptr_array_remove_index_fast (event_requests, i);
4375 for (i = 0; i < breakpoints->len; ++i)
4376 g_free (g_ptr_array_index (breakpoints, i));
4378 g_ptr_array_free (breakpoints, TRUE);
4379 g_hash_table_destroy (bp_locs);
4384 mono_loader_unlock ();
4388 * clear_breakpoints_for_domain:
4390 * Clear breakpoint instances which reference DOMAIN.
4393 clear_breakpoints_for_domain (MonoDomain *domain)
4397 /* This could be called after shutdown */
4401 mono_loader_lock ();
4402 for (i = 0; i < breakpoints->len; ++i) {
4403 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4406 while (j < bp->children->len) {
4407 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4409 if (inst->domain == domain) {
4410 remove_breakpoint (inst);
4414 g_ptr_array_remove_index_fast (bp->children, j);
4420 mono_loader_unlock ();
4426 * Return FALSE if single stepping needs to continue because we are at the same line.
4429 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp)
4431 MonoDebugMethodInfo *minfo;
4432 MonoDebugSourceLocation *loc = NULL;
4433 gboolean hit = TRUE;
4435 if (req->size != STEP_SIZE_LINE)
4438 /* Have to check whenever a different source line was reached */
4439 minfo = mono_debug_lookup_method (ji->method);
4442 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4444 if (!loc || (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line)) {
4445 /* Have to continue single stepping */
4447 DEBUG(1, fprintf (log_file, "[%p] No line number info for il offset %x, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset));
4449 DEBUG(1, fprintf (log_file, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer)GetCurrentThreadId (), loc->row));
4454 ss_req->last_method = ji->method;
4455 ss_req->last_line = loc->row;
4456 mono_debug_free_source_location (loc);
4463 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4465 return bp->method && bp->method->klass->image->assembly == assembly;
4469 process_breakpoint_inner (DebuggerTlsData *tls)
4473 int i, j, suspend_policy;
4474 guint32 native_offset;
4476 BreakpointInstance *inst;
4477 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4478 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4479 EventKind kind = EVENT_KIND_BREAKPOINT;
4480 MonoContext *ctx = &tls->restore_ctx;
4481 MonoSeqPointInfo *info;
4484 // FIXME: Speed this up
4486 ip = MONO_CONTEXT_GET_IP (ctx);
4487 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4489 g_assert (ji->method);
4491 /* Compute the native offset of the breakpoint from the ip */
4492 native_offset = ip - (guint8*)ji->code_start;
4495 * Skip the instruction causing the breakpoint signal.
4497 mono_arch_skip_breakpoint (ctx, ji);
4499 if (ji->method->wrapper_type || tls->disable_breakpoints)
4502 bp_reqs = g_ptr_array_new ();
4503 ss_reqs = g_ptr_array_new ();
4504 ss_reqs_orig = g_ptr_array_new ();
4506 mono_loader_lock ();
4509 * The ip points to the instruction causing the breakpoint event, which is after
4510 * the offset recorded in the seq point map, so find the prev seq point before ip.
4512 sp = find_prev_seq_point_for_native_offset (mono_domain_get (), ji->method, native_offset, &info);
4514 no_seq_points_found (ji->method);
4517 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));
4520 for (i = 0; i < breakpoints->len; ++i) {
4521 bp = g_ptr_array_index (breakpoints, i);
4526 for (j = 0; j < bp->children->len; ++j) {
4527 inst = g_ptr_array_index (bp->children, j);
4528 if (inst->ji == ji && inst->sp == sp) {
4529 if (bp->req->event_kind == EVENT_KIND_STEP) {
4530 g_ptr_array_add (ss_reqs_orig, bp->req);
4532 g_ptr_array_add (bp_reqs, bp->req);
4537 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4538 /* Maybe a method entry/exit event */
4539 if (sp->il_offset == METHOD_ENTRY_IL_OFFSET)
4540 kind = EVENT_KIND_METHOD_ENTRY;
4541 else if (sp->il_offset == METHOD_EXIT_IL_OFFSET)
4542 kind = EVENT_KIND_METHOD_EXIT;
4545 /* Process single step requests */
4546 for (i = 0; i < ss_reqs_orig->len; ++i) {
4547 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4548 SingleStepReq *ss_req = req->info;
4551 hit = ss_update (ss_req, ji, sp);
4553 g_ptr_array_add (ss_reqs, req);
4555 /* Start single stepping again from the current sequence point */
4556 ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4559 if (ss_reqs->len > 0)
4560 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4561 if (bp_reqs->len > 0)
4562 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4563 if (kind != EVENT_KIND_BREAKPOINT)
4564 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4566 mono_loader_unlock ();
4568 g_ptr_array_free (bp_reqs, TRUE);
4569 g_ptr_array_free (ss_reqs, TRUE);
4572 * FIXME: The first event will suspend, so the second will only be sent after the
4576 process_event (EVENT_KIND_STEP, ji->method, 0, ctx, ss_events, suspend_policy);
4578 process_event (kind, ji->method, 0, ctx, bp_events, suspend_policy);
4579 if (enter_leave_events)
4580 process_event (kind, ji->method, 0, ctx, enter_leave_events, suspend_policy);
4583 /* Process a breakpoint/single step event after resuming from a signal handler */
4585 process_signal_event (void (*func) (DebuggerTlsData*))
4587 DebuggerTlsData *tls;
4588 MonoContext orig_restore_ctx, ctx;
4589 static void (*restore_context) (void *);
4591 if (!restore_context)
4592 restore_context = mono_get_restore_context ();
4594 tls = mono_native_tls_get_value (debugger_tls_id);
4595 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4596 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4597 memcpy (&tls->restore_ctx, &tls->handler_ctx, sizeof (MonoContext));
4601 /* This is called when resuming from a signal handler, so it shouldn't return */
4602 memcpy (&ctx, &tls->restore_ctx, sizeof (MonoContext));
4603 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4604 restore_context (&ctx);
4605 g_assert_not_reached ();
4609 process_breakpoint (void)
4611 process_signal_event (process_breakpoint_inner);
4615 resume_from_signal_handler (void *sigctx, void *func)
4617 DebuggerTlsData *tls;
4620 /* Save the original context in TLS */
4621 // FIXME: This might not work on an altstack ?
4622 tls = mono_native_tls_get_value (debugger_tls_id);
4624 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer)GetCurrentThreadId ());
4627 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4628 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4629 // clob:c could be added to op_seq_point.
4631 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4632 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4633 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4634 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4636 MONO_CONTEXT_SET_IP (&ctx, func);
4638 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4640 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4641 mono_ppc_set_func_into_sigctx (sigctx, func);
4646 mono_debugger_agent_breakpoint_hit (void *sigctx)
4649 * We are called from a signal handler, and running code there causes all kinds of
4650 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4651 * So set up the signal context to return to the real breakpoint handler function.
4653 resume_from_signal_handler (sigctx, process_breakpoint);
4657 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4659 if (frame->managed) {
4660 *(MonoContext*)data = *ctx;
4669 * Called by System.Diagnostics.Debugger:Break ().
4672 mono_debugger_agent_user_break (void)
4674 if (agent_config.enabled) {
4679 /* Obtain a context */
4680 MONO_CONTEXT_SET_IP (&ctx, NULL);
4681 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4682 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4684 mono_loader_lock ();
4685 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4686 mono_loader_unlock ();
4688 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4695 ss_depth_to_string (StepDepth depth)
4698 case STEP_DEPTH_OVER:
4700 case STEP_DEPTH_OUT:
4702 case STEP_DEPTH_INTO:
4705 g_assert_not_reached ();
4711 process_single_step_inner (DebuggerTlsData *tls)
4716 int il_offset, suspend_policy;
4719 MonoContext *ctx = &tls->restore_ctx;
4721 MonoSeqPointInfo *info;
4723 ip = MONO_CONTEXT_GET_IP (ctx);
4725 /* Skip the instruction causing the single step */
4726 mono_arch_skip_single_step (ctx);
4728 if (suspend_count > 0) {
4729 process_suspend (tls, ctx);
4734 // FIXME: A suspend race
4737 if (mono_thread_internal_current () != ss_req->thread)
4740 if (log_level > 0) {
4741 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4743 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));
4746 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4748 g_assert (ji->method);
4750 if (ji->method->wrapper_type && ji->method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4755 * Stopping in memset makes half-initialized vtypes visible.
4756 * Stopping in memcpy makes half-copied vtypes visible.
4758 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
4762 * The ip points to the instruction causing the single step event, which is before
4763 * the offset recorded in the seq point map, so find the next seq point after ip.
4765 sp = find_next_seq_point_for_native_offset (domain, ji->method, (guint8*)ip - (guint8*)ji->code_start, &info);
4768 il_offset = sp->il_offset;
4770 if (!ss_update (ss_req, ji, sp))
4773 /* Start single stepping again from the current sequence point */
4774 ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4776 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
4777 (ji->method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4778 !strcmp (ji->method->name, ".cctor"))
4781 // FIXME: Has to lock earlier
4783 reqs = g_ptr_array_new ();
4785 mono_loader_lock ();
4787 g_ptr_array_add (reqs, ss_req->req);
4789 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4791 g_ptr_array_free (reqs, TRUE);
4793 mono_loader_unlock ();
4795 process_event (EVENT_KIND_STEP, ji->method, il_offset, ctx, events, suspend_policy);
4799 process_single_step (void)
4801 process_signal_event (process_single_step_inner);
4805 * mono_debugger_agent_single_step_event:
4807 * Called from a signal handler to handle a single step event.
4810 mono_debugger_agent_single_step_event (void *sigctx)
4812 /* Resume to process_single_step through the signal context */
4814 // FIXME: Since step out/over is implemented using step in, the step in case should
4815 // be as fast as possible. Move the relevant code from process_single_step_inner ()
4818 if (GetCurrentThreadId () == debugger_thread_id) {
4820 * This could happen despite our best effors when the runtime calls
4821 * assembly/type resolve hooks.
4822 * FIXME: Breakpoints too.
4826 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4827 mono_arch_skip_single_step (&ctx);
4828 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4832 resume_from_signal_handler (sigctx, process_single_step);
4836 debugger_agent_single_step_from_context (MonoContext *ctx)
4838 DebuggerTlsData *tls;
4839 MonoContext orig_restore_ctx;
4841 tls = mono_native_tls_get_value (debugger_tls_id);
4844 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4845 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4846 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4848 process_single_step_inner (tls);
4850 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4851 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4855 debugger_agent_breakpoint_from_context (MonoContext *ctx)
4857 DebuggerTlsData *tls;
4858 MonoContext orig_restore_ctx;
4860 tls = mono_native_tls_get_value (debugger_tls_id);
4862 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4863 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4865 process_breakpoint_inner (tls);
4867 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4868 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4872 * start_single_stepping:
4874 * Turn on single stepping. Can be called multiple times, for example,
4875 * by a single step event request + a suspend.
4878 start_single_stepping (void)
4880 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4881 int val = InterlockedIncrement (&ss_count);
4884 mono_arch_start_single_stepping ();
4886 if (ss_req != NULL && ss_invoke_addr == NULL) {
4887 DebuggerTlsData *tls;
4889 mono_loader_lock ();
4891 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
4892 ss_invoke_addr = tls->invoke_addr;
4894 mono_loader_unlock ();
4897 g_assert_not_reached ();
4902 stop_single_stepping (void)
4904 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4905 int val = InterlockedDecrement (&ss_count);
4908 mono_arch_stop_single_stepping ();
4910 ss_invoke_addr = NULL;
4912 g_assert_not_reached ();
4919 * Stop the single stepping operation given by SS_REQ.
4922 ss_stop (SingleStepReq *ss_req)
4927 for (l = ss_req->bps; l; l = l->next) {
4928 clear_breakpoint (l->data);
4930 g_slist_free (ss_req->bps);
4934 if (ss_req->global) {
4935 stop_single_stepping ();
4936 ss_req->global = FALSE;
4943 * Start the single stepping operation given by SS_REQ from the sequence point SP.
4944 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
4945 * belong to the same thread as CTX.
4948 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
4950 int i, j, frame_index;
4953 gboolean enable_global = FALSE;
4955 /* Stop the previous operation */
4959 * Implement single stepping using breakpoints if possible.
4961 if (step_to_catch) {
4962 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
4963 ss_req->bps = g_slist_append (ss_req->bps, bp);
4967 if ((!sp || sp->next_len == 0 || ss_req->depth == STEP_DEPTH_OUT || ss_req->depth == STEP_DEPTH_OVER) && ctx) {
4968 /* Need parent frames */
4969 if (!tls->context.valid)
4970 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4971 compute_frame_info (tls->thread, tls);
4975 * Find the first sequence point in the current or in a previous frame which
4976 * is not the last in its method.
4978 if (ss_req->depth == STEP_DEPTH_OUT) {
4979 /* Ignore seq points in current method */
4980 while (frame_index < tls->frame_count) {
4981 StackFrame *frame = tls->frames [frame_index];
4983 method = frame->method;
4984 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4986 if (sp && sp->next_len != 0)
4989 // There could be method calls before the next seq point in the caller when using nested calls
4990 //enable_global = TRUE;
4992 if (sp && sp->next_len == 0) {
4994 while (frame_index < tls->frame_count) {
4995 StackFrame *frame = tls->frames [frame_index];
4997 method = frame->method;
4998 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4999 if (sp && sp->next_len != 0)
5007 if (sp && sp->next_len > 0) {
5008 for (i = 0; i < sp->next_len; ++i) {
5009 next_sp = &info->seq_points [sp->next [i]];
5011 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
5012 ss_req->bps = g_slist_append (ss_req->bps, bp);
5016 if (ss_req->depth == STEP_DEPTH_OVER) {
5017 /* Need to stop in catch clauses as well */
5018 for (i = 0; i < tls->frame_count; ++i) {
5019 StackFrame *frame = tls->frames [i];
5022 MonoJitInfo *jinfo = frame->ji;
5023 for (j = 0; j < jinfo->num_clauses; ++j) {
5024 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5026 sp = find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL);
5028 bp = set_breakpoint (frame->method, sp->il_offset, ss_req->req, NULL);
5029 ss_req->bps = g_slist_append (ss_req->bps, bp);
5037 if (ss_req->depth == STEP_DEPTH_INTO) {
5038 /* Enable global stepping so we stop at method entry too */
5039 enable_global = TRUE;
5043 * The ctx/frame info computed above will become invalid when we continue.
5045 tls->context.valid = FALSE;
5046 tls->async_state.valid = FALSE;
5047 invalidate_frames (tls);
5050 if (enable_global) {
5051 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
5052 ss_req->global = TRUE;
5053 start_single_stepping ();
5054 } else if (!ss_req->bps) {
5055 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
5056 ss_req->global = TRUE;
5057 start_single_stepping ();
5059 ss_req->global = FALSE;
5064 * Start single stepping of thread THREAD
5067 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
5069 DebuggerTlsData *tls;
5070 MonoSeqPointInfo *info = NULL;
5071 SeqPoint *sp = NULL;
5072 MonoMethod *method = NULL;
5073 MonoDebugMethodInfo *minfo;
5074 gboolean step_to_catch = FALSE;
5076 if (suspend_count == 0)
5077 return ERR_NOT_SUSPENDED;
5079 wait_for_suspend ();
5081 // FIXME: Multiple requests
5083 DEBUG (0, fprintf (log_file, "Received a single step request while the previous one was still active.\n"));
5084 return ERR_NOT_IMPLEMENTED;
5087 DEBUG (1, fprintf (log_file, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
5089 ss_req = g_new0 (SingleStepReq, 1);
5091 ss_req->thread = thread;
5092 ss_req->size = size;
5093 ss_req->depth = depth;
5096 mono_loader_lock ();
5097 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5098 mono_loader_unlock ();
5100 g_assert (tls->context.valid);
5101 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5103 if (tls->catch_state.valid) {
5105 StackFrameInfo frame;
5106 MonoContext new_ctx;
5107 MonoLMF *lmf = NULL;
5110 * We are stopped at a throw site. Stepping should go to the catch site.
5113 /* Find the the jit info for the catch context */
5114 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);
5116 g_assert (frame.type == FRAME_TYPE_MANAGED);
5119 * Find the seq point corresponding to the landing site ip, which is the first seq
5122 sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
5124 no_seq_points_found (frame.method);
5127 method = frame.method;
5129 step_to_catch = TRUE;
5130 /* This make sure the seq point is not skipped by process_single_step () */
5131 ss_req->last_sp = NULL;
5134 if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
5137 /* Compute the initial line info */
5138 compute_frame_info (thread, tls);
5140 if (tls->frame_count) {
5141 frame = tls->frames [0];
5143 ss_req->last_method = frame->method;
5144 ss_req->last_line = -1;
5146 minfo = mono_debug_lookup_method (frame->method);
5147 if (minfo && frame->il_offset != -1) {
5148 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
5151 ss_req->last_line = loc->row;
5158 if (!step_to_catch) {
5161 compute_frame_info (thread, tls);
5163 if (tls->frame_count) {
5164 frame = tls->frames [0];
5166 if (!method && frame->il_offset != -1) {
5167 /* FIXME: Sort the table and use a binary search */
5168 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5170 no_seq_points_found (frame->method);
5172 method = frame->method;
5177 ss_start (ss_req, method, sp, info, &tls->context.ctx, tls, step_to_catch);
5183 ss_destroy (SingleStepReq *req)
5186 g_assert (ss_req == req);
5195 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5198 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5204 if (!agent_config.enabled)
5207 mono_loader_lock ();
5208 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5209 mono_loader_unlock ();
5212 ei.category = category ? mono_string_to_utf8 (category) : NULL;
5213 ei.message = message ? mono_string_to_utf8 (message) : NULL;
5215 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5217 g_free (ei.category);
5218 g_free (ei.message);
5222 mono_debugger_agent_debug_log_is_enabled (void)
5224 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5225 return agent_config.enabled;
5228 #ifdef PLATFORM_ANDROID
5230 mono_debugger_agent_unhandled_exception (MonoException *exc)
5239 memset (&ei, 0, sizeof (EventInfo));
5240 ei.exc = (MonoObject*)exc;
5242 mono_loader_lock ();
5243 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5244 mono_loader_unlock ();
5246 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5251 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5252 MonoContext *catch_ctx)
5254 int i, j, suspend_policy;
5256 MonoJitInfo *ji, *catch_ji;
5258 DebuggerTlsData *tls = NULL;
5260 if (thread_to_tls != NULL) {
5261 MonoInternalThread *thread = mono_thread_internal_current ();
5263 mono_loader_lock ();
5264 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5265 mono_loader_unlock ();
5267 if (tls && tls->abort_requested)
5269 if (tls && tls->disable_breakpoints)
5273 memset (&ei, 0, sizeof (EventInfo));
5275 /* Just-In-Time debugging */
5277 if (agent_config.onuncaught && !inited) {
5278 finish_agent_init (FALSE);
5281 * Send an unsolicited EXCEPTION event with a dummy request id.
5283 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5284 ei.exc = (MonoObject*)exc;
5285 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5288 } else if (agent_config.onthrow && !inited) {
5290 gboolean found = FALSE;
5292 for (l = agent_config.onthrow; l; l = l->next) {
5293 char *ex_type = l->data;
5294 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5296 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5303 finish_agent_init (FALSE);
5306 * Send an unsolicited EXCEPTION event with a dummy request id.
5308 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5309 ei.exc = (MonoObject*)exc;
5310 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5318 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5320 catch_ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5324 ei.exc = (MonoObject*)exc;
5325 ei.caught = catch_ctx != NULL;
5327 mono_loader_lock ();
5329 /* Treat exceptions which are caught in non-user code as unhandled */
5330 for (i = 0; i < event_requests->len; ++i) {
5331 EventRequest *req = g_ptr_array_index (event_requests, i);
5332 if (req->event_kind != EVENT_KIND_EXCEPTION)
5335 for (j = 0; j < req->nmodifiers; ++j) {
5336 Modifier *mod = &req->modifiers [j];
5338 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5340 gboolean found = FALSE;
5341 MonoAssembly **assemblies = mod->data.assemblies;
5344 for (k = 0; assemblies [k]; ++k)
5345 if (assemblies [k] == catch_ji->method->klass->image->assembly)
5354 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5355 mono_loader_unlock ();
5357 if (tls && ei.caught && catch_ctx) {
5358 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5359 tls->catch_state.ctx = *catch_ctx;
5360 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5361 tls->catch_state.valid = TRUE;
5364 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5367 tls->catch_state.valid = FALSE;
5371 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5373 DebuggerTlsData *tls;
5378 tls = mono_native_tls_get_value (debugger_tls_id);
5383 * We're about to invoke an exception filter during the first pass of exception handling.
5385 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5386 * 'orig_ctx' is the context where the exception has been thrown.
5389 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5391 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5392 * the call site (line 37) and then continue to Main(), but it would never
5393 * include the throw site (line 32).
5395 * Since exception filters are invoked during the first pass of exception handling,
5396 * the stack frames of the throw site are still intact, so we should include them
5399 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5401 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5402 * but report the location of the 'throw' to the user.
5406 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5410 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5412 DebuggerTlsData *tls;
5417 tls = mono_native_tls_get_value (debugger_tls_id);
5421 tls->filter_state.valid = FALSE;
5425 * buffer_add_value_full:
5427 * Add the encoding of the value at ADDR described by T to the buffer.
5428 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5432 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5438 if (!(*(void**)addr)) {
5439 /* This can happen with compiler generated locals */
5440 //printf ("%s\n", mono_type_full_name (t));
5441 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5444 g_assert (*(void**)addr);
5445 addr = *(void**)addr;
5450 case MONO_TYPE_BOOLEAN:
5453 case MONO_TYPE_CHAR:
5473 case MONO_TYPE_VOID:
5474 buffer_add_byte (buf, t->type);
5476 case MONO_TYPE_BOOLEAN:
5479 buffer_add_byte (buf, t->type);
5480 buffer_add_int (buf, *(gint8*)addr);
5482 case MONO_TYPE_CHAR:
5485 buffer_add_byte (buf, t->type);
5486 buffer_add_int (buf, *(gint16*)addr);
5491 buffer_add_byte (buf, t->type);
5492 buffer_add_int (buf, *(gint32*)addr);
5497 buffer_add_byte (buf, t->type);
5498 buffer_add_long (buf, *(gint64*)addr);
5502 /* Treat it as a vtype */
5504 case MONO_TYPE_PTR: {
5505 gssize val = *(gssize*)addr;
5507 buffer_add_byte (buf, t->type);
5508 buffer_add_long (buf, val);
5512 case MONO_TYPE_STRING:
5513 case MONO_TYPE_SZARRAY:
5514 case MONO_TYPE_OBJECT:
5515 case MONO_TYPE_CLASS:
5516 case MONO_TYPE_ARRAY:
5517 obj = *(MonoObject**)addr;
5520 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5522 if (obj->vtable->klass->valuetype) {
5523 t = &obj->vtable->klass->byval_arg;
5524 addr = mono_object_unbox (obj);
5526 } else if (obj->vtable->klass->rank) {
5527 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5528 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5529 buffer_add_byte (buf, MONO_TYPE_CLASS);
5531 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5533 buffer_add_objid (buf, obj);
5537 case MONO_TYPE_VALUETYPE: {
5541 MonoClass *klass = mono_class_from_mono_type (t);
5543 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5544 buffer_add_byte (buf, klass->enumtype);
5545 buffer_add_typeid (buf, domain, klass);
5549 while ((f = mono_class_get_fields (klass, &iter))) {
5550 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5552 if (mono_field_is_deleted (f))
5556 buffer_add_int (buf, nfields);
5559 while ((f = mono_class_get_fields (klass, &iter))) {
5560 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5562 if (mono_field_is_deleted (f))
5564 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE);
5568 case MONO_TYPE_GENERICINST:
5569 if (mono_type_generic_inst_is_valuetype (t)) {
5581 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5583 buffer_add_value_full (buf, t, addr, domain, FALSE);
5587 obj_is_of_type (MonoObject *obj, MonoType *t)
5589 MonoClass *klass = obj->vtable->klass;
5590 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5591 if (mono_class_is_transparent_proxy (klass)) {
5592 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5593 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5603 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5606 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5612 gpointer iter = NULL;
5616 is_enum = decode_byte (buf, &buf, limit);
5617 /* Enums are sent as a normal vtype */
5619 return ERR_NOT_IMPLEMENTED;
5620 klass = decode_typeid (buf, &buf, limit, &d, &err);
5624 if (t && klass != mono_class_from_mono_type (t)) {
5625 char *name = mono_type_full_name (t);
5626 char *name2 = mono_type_full_name (&klass->byval_arg);
5627 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got %s.\n", (gpointer)GetCurrentThreadId (), name, name2));
5630 return ERR_INVALID_ARGUMENT;
5633 nfields = decode_int (buf, &buf, limit);
5634 while ((f = mono_class_get_fields (klass, &iter))) {
5635 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5637 if (mono_field_is_deleted (f))
5639 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5644 g_assert (nfields == 0);
5649 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5653 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5654 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5655 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5656 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5657 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
5658 char *name = mono_type_full_name (t);
5659 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5661 return ERR_INVALID_ARGUMENT;
5665 case MONO_TYPE_BOOLEAN:
5666 *(guint8*)addr = decode_int (buf, &buf, limit);
5668 case MONO_TYPE_CHAR:
5669 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5672 *(gint8*)addr = decode_int (buf, &buf, limit);
5675 *(guint8*)addr = decode_int (buf, &buf, limit);
5678 *(gint16*)addr = decode_int (buf, &buf, limit);
5681 *(guint16*)addr = decode_int (buf, &buf, limit);
5684 *(gint32*)addr = decode_int (buf, &buf, limit);
5687 *(guint32*)addr = decode_int (buf, &buf, limit);
5690 *(gint64*)addr = decode_long (buf, &buf, limit);
5693 *(guint64*)addr = decode_long (buf, &buf, limit);
5696 *(guint32*)addr = decode_int (buf, &buf, limit);
5699 *(guint64*)addr = decode_long (buf, &buf, limit);
5702 /* We send these as I8, so we get them back as such */
5703 g_assert (type == MONO_TYPE_I8);
5704 *(gssize*)addr = decode_long (buf, &buf, limit);
5706 case MONO_TYPE_GENERICINST:
5707 if (MONO_TYPE_ISSTRUCT (t)) {
5708 /* The client sends these as a valuetype */
5716 /* We send these as vtypes, so we get them back as such */
5717 g_assert (type == MONO_TYPE_VALUETYPE);
5720 case MONO_TYPE_VALUETYPE:
5721 err = decode_vtype (t, domain, addr,buf, &buf, limit);
5727 if (MONO_TYPE_IS_REFERENCE (t)) {
5728 if (type == MONO_TYPE_OBJECT) {
5729 int objid = decode_objid (buf, &buf, limit);
5733 err = get_object (objid, (MonoObject**)&obj);
5738 if (!obj_is_of_type (obj, t)) {
5739 DEBUG (1, fprintf (log_file, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name));
5740 return ERR_INVALID_ARGUMENT;
5743 if (obj && obj->vtable->domain != domain)
5744 return ERR_INVALID_ARGUMENT;
5746 mono_gc_wbarrier_generic_store (addr, obj);
5747 } else if (type == VALUE_TYPE_ID_NULL) {
5748 *(MonoObject**)addr = NULL;
5749 } else if (type == MONO_TYPE_VALUETYPE) {
5757 /* This can happen when round-tripping boxed vtypes */
5759 * Obtain vtype class.
5760 * Same as the beginning of the handle_vtype case above.
5763 is_enum = decode_byte (buf, &buf, limit);
5765 return ERR_NOT_IMPLEMENTED;
5766 klass = decode_typeid (buf, &buf, limit, &d, &err);
5770 /* Decode the vtype into a temporary buffer, then box it. */
5771 vtype_buf_size = mono_class_value_size (klass, NULL);
5772 vtype_buf = g_malloc0 (vtype_buf_size);
5773 g_assert (vtype_buf);
5776 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
5781 *(MonoObject**)addr = mono_value_box (d, klass, vtype_buf);
5784 char *name = mono_type_full_name (t);
5785 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5787 return ERR_INVALID_ARGUMENT;
5801 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5804 int type = decode_byte (buf, &buf, limit);
5806 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
5807 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
5808 guint8 *nullable_buf;
5811 * First try decoding it as a Nullable`1
5813 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5818 * Then try decoding as a primitive value or null.
5820 if (targ->type == type) {
5821 nullable_buf = g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
5822 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
5824 g_free (nullable_buf);
5827 mono_nullable_init (addr, mono_value_box (domain, mono_class_from_mono_type (targ), nullable_buf), mono_class_from_mono_type (t));
5828 g_free (nullable_buf);
5831 } else if (type == VALUE_TYPE_ID_NULL) {
5832 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
5838 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5842 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
5846 guint8 *addr, *gaddr;
5849 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5850 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5853 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
5854 reg_val = mono_arch_context_get_int_reg (ctx, reg);
5856 buffer_add_value_full (buf, t, ®_val, domain, as_vtype);
5858 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5859 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5860 addr += (gint32)var->offset;
5862 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5864 buffer_add_value_full (buf, t, addr, domain, as_vtype);
5866 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5869 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
5870 /* Same as regoffset, but with an indirection */
5871 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5872 addr += (gint32)var->offset;
5874 gaddr = *(gpointer*)addr;
5876 buffer_add_value_full (buf, t, gaddr, domain, as_vtype);
5878 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
5879 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
5880 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
5881 MonoGSharedVtMethodRuntimeInfo *info;
5887 g_assert (info_var);
5888 g_assert (locals_var);
5890 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5891 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5892 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
5893 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5894 addr += (gint32)info_var->offset;
5895 info = *(gpointer*)addr;
5896 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
5897 info = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5899 g_assert_not_reached ();
5903 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5904 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5905 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
5906 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5907 addr += (gint32)locals_var->offset;
5908 locals = *(gpointer*)addr;
5909 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
5910 locals = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5912 g_assert_not_reached ();
5916 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
5918 buffer_add_value_full (buf, t, addr, domain, as_vtype);
5923 g_assert_not_reached ();
5928 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
5932 guint8 *addr, *gaddr;
5934 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5935 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5937 if (MONO_TYPE_IS_REFERENCE (t))
5938 size = sizeof (gpointer);
5940 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
5943 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
5944 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
5946 gboolean is_signed = FALSE;
5948 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
5953 v = is_signed ? *(gint8*)val : *(guint8*)val;
5956 v = is_signed ? *(gint16*)val : *(guint16*)val;
5959 v = is_signed ? *(gint32*)val : *(guint32*)val;
5962 v = is_signed ? *(gint64*)val : *(guint64*)val;
5965 g_assert_not_reached ();
5971 /* Set value on the stack or in the return ctx */
5972 if (reg_locations [reg]) {
5973 /* Saved on the stack */
5974 DEBUG (1, fprintf (log_file, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v));
5975 *(reg_locations [reg]) = v;
5978 DEBUG (1, fprintf (log_file, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v));
5979 mono_arch_context_set_int_reg (restore_ctx, reg, v);
5982 // FIXME: Move these to mono-context.h/c.
5983 mono_arch_context_set_int_reg (ctx, reg, v);
5985 // FIXME: Can't set registers, so we disable linears
5990 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5991 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5992 addr += (gint32)var->offset;
5994 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5997 addr = *(guint8**)addr;
6003 // FIXME: Write barriers
6004 mono_gc_memmove (addr, val, size);
6006 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6007 /* Same as regoffset, but with an indirection */
6008 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6009 addr += (gint32)var->offset;
6011 gaddr = *(gpointer*)addr;
6013 // FIXME: Write barriers
6014 mono_gc_memmove (gaddr, val, size);
6016 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6020 g_assert_not_reached ();
6025 clear_event_request (int req_id, int etype)
6029 mono_loader_lock ();
6030 for (i = 0; i < event_requests->len; ++i) {
6031 EventRequest *req = g_ptr_array_index (event_requests, i);
6033 if (req->id == req_id && req->event_kind == etype) {
6034 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6035 clear_breakpoint (req->info);
6036 if (req->event_kind == EVENT_KIND_STEP)
6037 ss_destroy (req->info);
6038 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6039 clear_breakpoint (req->info);
6040 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6041 clear_breakpoint (req->info);
6042 g_ptr_array_remove_index_fast (event_requests, i);
6047 mono_loader_unlock ();
6051 event_req_matches_assembly (EventRequest *req, MonoAssembly *assembly)
6053 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6054 return breakpoint_matches_assembly (req->info, assembly);
6058 for (i = 0; i < req->nmodifiers; ++i) {
6059 Modifier *m = &req->modifiers [i];
6061 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6063 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6064 for (j = 0; m->data.assemblies [j]; ++j)
6065 if (m->data.assemblies [j] == assembly)
6075 * clear_event_requests_for_assembly:
6077 * Clear all events requests which reference ASSEMBLY.
6080 clear_event_requests_for_assembly (MonoAssembly *assembly)
6085 mono_loader_lock ();
6089 for (i = 0; i < event_requests->len; ++i) {
6090 EventRequest *req = g_ptr_array_index (event_requests, i);
6092 if (event_req_matches_assembly (req, assembly)) {
6093 clear_event_request (req->id, req->event_kind);
6099 mono_loader_unlock ();
6103 * type_comes_from_assembly:
6105 * GHRFunc that returns TRUE if klass comes from assembly
6108 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6110 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6114 * clear_types_for_assembly:
6116 * Clears types from loaded_classes for a given assembly
6119 clear_types_for_assembly (MonoAssembly *assembly)
6121 MonoDomain *domain = mono_domain_get ();
6122 AgentDomainInfo *info = NULL;
6124 mono_loader_lock ();
6125 info = get_agent_domain_info (domain);
6126 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6127 mono_loader_unlock ();
6131 add_thread (gpointer key, gpointer value, gpointer user_data)
6133 MonoInternalThread *thread = value;
6134 Buffer *buf = user_data;
6136 buffer_add_objid (buf, (MonoObject*)thread);
6140 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6142 guint8 *end = invoke->endp;
6145 MonoMethodSignature *sig;
6148 MonoObject *this, *res, *exc;
6151 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6154 MonoStopwatch watch;
6156 if (invoke->method) {
6158 * Invoke this method directly, currently only Environment.Exit () is supported.
6161 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>"));
6162 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
6163 g_assert_not_reached ();
6166 m = decode_methodid (p, &p, end, &domain, &err);
6169 sig = mono_method_signature (m);
6171 if (m->klass->valuetype)
6172 this_buf = g_alloca (mono_class_instance_size (m->klass));
6174 this_buf = g_alloca (sizeof (MonoObject*));
6175 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6176 /* Should be null */
6177 int type = decode_byte (p, &p, end);
6178 if (type != VALUE_TYPE_ID_NULL) {
6179 DEBUG (1, fprintf (log_file, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer)GetCurrentThreadId ()));
6180 return ERR_INVALID_ARGUMENT;
6182 memset (this_buf, 0, mono_class_instance_size (m->klass));
6184 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6189 if (!m->klass->valuetype)
6190 this = *(MonoObject**)this_buf;
6194 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>"));
6196 if (this && this->vtable->domain != domain)
6199 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
6200 if (!strcmp (m->name, ".ctor")) {
6201 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
6202 return ERR_INVALID_ARGUMENT;
6204 this = mono_object_new (domain, m->klass);
6206 return ERR_INVALID_ARGUMENT;
6210 if (this && !obj_is_of_type (this, &m->klass->byval_arg))
6211 return ERR_INVALID_ARGUMENT;
6213 nargs = decode_int (p, &p, end);
6214 if (nargs != sig->param_count)
6215 return ERR_INVALID_ARGUMENT;
6216 /* Use alloca to get gc tracking */
6217 arg_buf = g_alloca (nargs * sizeof (gpointer));
6218 memset (arg_buf, 0, nargs * sizeof (gpointer));
6219 args = g_alloca (nargs * sizeof (gpointer));
6220 for (i = 0; i < nargs; ++i) {
6221 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6222 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6226 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6229 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6230 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6233 args [i] = arg_buf [i];
6240 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6241 tls->disable_breakpoints = TRUE;
6243 tls->disable_breakpoints = FALSE;
6246 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6248 /* FIXME: Move this to arch specific code */
6249 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6250 if (invoke->has_ctx) {
6253 lmf_addr = mono_get_lmf_addr ();
6256 memset (&ext, 0, sizeof (ext));
6258 ext.lmf.previous_lmf = *(lmf_addr);
6259 /* Mark that this is a MonoLMFExt */
6260 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6261 ext.lmf.rsp = (gssize)&ext;
6262 #elif defined(TARGET_X86)
6263 ext.lmf.previous_lmf = (gsize)*(lmf_addr);
6264 /* Mark that this is a MonoLMFExt */
6265 ext.lmf.previous_lmf = (gsize)(gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6266 ext.lmf.ebp = (gssize)&ext;
6267 #elif defined(TARGET_ARM)
6268 ext.lmf.previous_lmf = *(lmf_addr);
6269 /* Mark that this is a MonoLMFExt */
6270 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6271 ext.lmf.sp = (gssize)&ext;
6272 #elif defined(TARGET_POWERPC)
6273 ext.lmf.previous_lmf = *(lmf_addr);
6274 /* Mark that this is a MonoLMFExt */
6275 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6276 ext.lmf.ebp = (gssize)&ext;
6277 #elif defined(TARGET_S390X)
6278 ext.lmf.previous_lmf = *(lmf_addr);
6279 /* Mark that this is a MonoLMFExt */
6280 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6281 ext.lmf.ebp = (gssize)&ext;
6282 #elif defined(TARGET_MIPS)
6283 ext.lmf.previous_lmf = *(lmf_addr);
6284 /* Mark that this is a MonoLMFExt */
6285 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6286 ext.lmf.iregs [mips_sp] = (gssize)&ext;
6288 g_assert_not_reached ();
6291 ext.debugger_invoke = TRUE;
6292 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6294 mono_set_lmf ((MonoLMF*)&ext);
6298 mono_stopwatch_start (&watch);
6299 if (m->klass->valuetype)
6300 res = mono_runtime_invoke (m, this_buf, args, &exc);
6302 res = mono_runtime_invoke (m, this, args, &exc);
6303 mono_stopwatch_stop (&watch);
6304 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)));
6306 buffer_add_byte (buf, 0);
6307 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6309 buffer_add_byte (buf, 1);
6310 if (sig->ret->type == MONO_TYPE_VOID) {
6311 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
6312 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
6315 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6316 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6317 buffer_add_value (buf, sig->ret, &res, domain);
6318 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6319 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6320 MonoClass *k = mono_class_from_mono_type (sig->ret);
6321 guint8 *nullable_buf = g_alloca (mono_class_value_size (k, NULL));
6323 g_assert (nullable_buf);
6324 mono_nullable_init (nullable_buf, res, k);
6325 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6328 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6335 tls->disable_breakpoints = FALSE;
6337 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6338 if (invoke->has_ctx)
6339 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
6343 // FIXME: byref arguments
6351 * Invoke the method given by tls->pending_invoke in the current thread.
6354 invoke_method (void)
6356 DebuggerTlsData *tls;
6361 static void (*restore_context) (void *);
6362 MonoContext restore_ctx;
6365 if (!restore_context)
6366 restore_context = mono_get_restore_context ();
6368 tls = mono_native_tls_get_value (debugger_tls_id);
6372 * Store the `InvokeData *' in `tls->invoke' until we're done with
6373 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6376 mono_loader_lock ();
6378 invoke = tls->pending_invoke;
6380 tls->pending_invoke = NULL;
6382 invoke->last_invoke = tls->invoke;
6383 tls->invoke = invoke;
6385 mono_loader_unlock ();
6387 tls->frames_up_to_date = FALSE;
6393 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6394 buffer_init (&buf, 128);
6397 /* Fail the other invokes as well */
6399 err = do_invoke_method (tls, &buf, invoke, p, &p);
6402 /* Start suspending before sending the reply */
6403 if (mindex == invoke->nmethods - 1) {
6404 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6405 for (i = 0; i < invoke->suspend_count; ++i)
6410 send_reply_packet (id, err, &buf);
6415 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6417 if (invoke->has_ctx)
6418 save_thread_context (&restore_ctx);
6420 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6421 g_assert (tls->resume_count);
6422 tls->resume_count -= invoke->suspend_count;
6425 DEBUG (1, fprintf (log_file, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer)GetCurrentThreadId (), err, tls->resume_count));
6428 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6430 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
6431 * after the mono_runtime_invoke() already returned, but it doesn't matter
6432 * because we reset the abort here.
6435 mono_loader_lock ();
6437 if (tls->abort_requested)
6438 mono_thread_internal_reset_abort (tls->thread);
6440 tls->invoke = tls->invoke->last_invoke;
6441 tls->abort_requested = FALSE;
6443 mono_loader_unlock ();
6452 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6454 MonoThread *thread = value;
6455 DebuggerTlsData *tls;
6458 mono_loader_lock ();
6459 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6461 res = tls->really_suspended;
6462 mono_loader_unlock ();
6468 get_source_files_for_type (MonoClass *klass)
6470 gpointer iter = NULL;
6472 MonoDebugSourceInfo *sinfo;
6476 files = g_ptr_array_new ();
6478 while ((method = mono_class_get_methods (klass, &iter))) {
6479 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6480 GPtrArray *source_file_list;
6483 mono_debug_symfile_get_line_numbers_full (minfo, NULL, &source_file_list, NULL, NULL, NULL, NULL, NULL);
6484 for (j = 0; j < source_file_list->len; ++j) {
6485 sinfo = g_ptr_array_index (source_file_list, j);
6486 for (i = 0; i < files->len; ++i)
6487 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6489 if (i == files->len)
6490 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6492 g_ptr_array_free (source_file_list, TRUE);
6500 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6503 case CMD_VM_VERSION: {
6504 char *build_info, *version;
6506 build_info = mono_get_runtime_build_info ();
6507 version = g_strdup_printf ("mono %s", build_info);
6509 buffer_add_string (buf, version); /* vm version */
6510 buffer_add_int (buf, MAJOR_VERSION);
6511 buffer_add_int (buf, MINOR_VERSION);
6512 g_free (build_info);
6516 case CMD_VM_SET_PROTOCOL_VERSION: {
6517 major_version = decode_int (p, &p, end);
6518 minor_version = decode_int (p, &p, end);
6519 protocol_version_set = TRUE;
6520 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
6523 case CMD_VM_ALL_THREADS: {
6525 mono_loader_lock ();
6526 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6527 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6528 mono_loader_unlock ();
6531 case CMD_VM_SUSPEND:
6533 wait_for_suspend ();
6536 if (suspend_count == 0)
6537 return ERR_NOT_SUSPENDED;
6539 clear_suspended_objs ();
6541 case CMD_VM_DISPOSE:
6542 /* Clear all event requests */
6543 mono_loader_lock ();
6544 while (event_requests->len > 0) {
6545 EventRequest *req = g_ptr_array_index (event_requests, 0);
6547 clear_event_request (req->id, req->event_kind);
6549 mono_loader_unlock ();
6551 while (suspend_count > 0)
6553 disconnected = TRUE;
6554 vm_start_event_sent = FALSE;
6557 MonoInternalThread *thread;
6558 DebuggerTlsData *tls;
6559 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6560 MonoClass *env_class;
6562 MonoMethod *exit_method = NULL;
6566 exit_code = decode_int (p, &p, end);
6568 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6570 /* Have to send a reply before exiting */
6571 send_reply_packet (id, 0, buf);
6573 /* Clear all event requests */
6574 mono_loader_lock ();
6575 while (event_requests->len > 0) {
6576 EventRequest *req = g_ptr_array_index (event_requests, 0);
6578 clear_event_request (req->id, req->event_kind);
6580 mono_loader_unlock ();
6583 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6584 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6585 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6586 * better than doing the shutdown ourselves, since it avoids various races.
6590 wait_for_suspend ();
6592 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6593 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
6595 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6598 mono_loader_lock ();
6599 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6600 mono_loader_unlock ();
6602 if (thread && exit_method) {
6603 mono_loader_lock ();
6604 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6605 mono_loader_unlock ();
6607 args = g_new0 (gpointer, 1);
6608 args [0] = g_malloc (sizeof (int));
6609 *(int*)(args [0]) = exit_code;
6611 tls->pending_invoke = g_new0 (InvokeData, 1);
6612 tls->pending_invoke->method = exit_method;
6613 tls->pending_invoke->args = args;
6614 tls->pending_invoke->nmethods = 1;
6616 while (suspend_count > 0)
6620 * No thread found, do it ourselves.
6621 * FIXME: This can race with normal shutdown etc.
6623 while (suspend_count > 0)
6626 if (!mono_runtime_try_shutdown ())
6629 /* Suspend all managed threads since the runtime is going away */
6630 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
6631 mono_thread_suspend_all_other_threads ();
6632 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
6633 mono_runtime_quit ();
6634 transport_close2 ();
6635 DEBUG(1, fprintf (log_file, "Exiting...\n"));
6641 case CMD_VM_INVOKE_METHOD:
6642 case CMD_VM_INVOKE_METHODS: {
6643 int objid = decode_objid (p, &p, end);
6645 DebuggerTlsData *tls;
6646 int i, count, err, flags, nmethods;
6648 err = get_object (objid, (MonoObject**)&thread);
6652 flags = decode_int (p, &p, end);
6654 if (command == CMD_VM_INVOKE_METHODS)
6655 nmethods = decode_int (p, &p, end);
6659 // Wait for suspending if it already started
6661 wait_for_suspend ();
6662 if (!is_suspended ())
6663 return ERR_NOT_SUSPENDED;
6665 mono_loader_lock ();
6666 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6667 mono_loader_unlock ();
6670 if (!tls->really_suspended)
6671 /* The thread is still running native code, can't do invokes */
6672 return ERR_NOT_SUSPENDED;
6675 * Store the invoke data into tls, the thread will execute it after it is
6678 if (tls->pending_invoke)
6679 return ERR_NOT_SUSPENDED;
6680 tls->pending_invoke = g_new0 (InvokeData, 1);
6681 tls->pending_invoke->id = id;
6682 tls->pending_invoke->flags = flags;
6683 tls->pending_invoke->p = g_malloc (end - p);
6684 memcpy (tls->pending_invoke->p, p, end - p);
6685 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
6686 tls->pending_invoke->suspend_count = suspend_count;
6687 tls->pending_invoke->nmethods = nmethods;
6689 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
6690 resume_thread (THREAD_TO_INTERNAL (thread));
6693 count = suspend_count;
6694 for (i = 0; i < count; ++i)
6699 case CMD_VM_ABORT_INVOKE: {
6700 int objid = decode_objid (p, &p, end);
6702 DebuggerTlsData *tls;
6705 err = get_object (objid, (MonoObject**)&thread);
6709 invoke_id = decode_int (p, &p, end);
6711 mono_loader_lock ();
6712 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6715 if (tls->abort_requested) {
6716 mono_loader_unlock ();
6721 * Check whether we're still inside the mono_runtime_invoke() and that it's
6722 * actually the correct invocation.
6724 * Careful, we do not stop the thread that's doing the invocation, so we can't
6725 * inspect its stack. However, invoke_method() also acquires the loader lock
6726 * when it's done, so we're safe here.
6730 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
6731 mono_loader_unlock ();
6732 return ERR_NO_INVOCATION;
6735 tls->abort_requested = TRUE;
6737 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
6738 mono_loader_unlock ();
6742 case CMD_VM_SET_KEEPALIVE: {
6743 int timeout = decode_int (p, &p, end);
6744 agent_config.keepalive = timeout;
6746 #ifndef DISABLE_SOCKET_TRANSPORT
6753 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
6754 GHashTableIter iter, kiter;
6759 char *fname, *basename;
6760 gboolean ignore_case;
6761 GSList *class_list, *l;
6762 GPtrArray *res_classes, *res_domains;
6764 fname = decode_string (p, &p, end);
6765 ignore_case = decode_byte (p, &p, end);
6767 basename = g_path_get_basename (fname);
6769 res_classes = g_ptr_array_new ();
6770 res_domains = g_ptr_array_new ();
6772 mono_loader_lock ();
6773 g_hash_table_iter_init (&iter, domains);
6774 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6775 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
6777 /* Update 'source_file_to_class' cache */
6778 g_hash_table_iter_init (&kiter, info->loaded_classes);
6779 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
6780 if (!g_hash_table_lookup (info->source_files, klass)) {
6781 files = get_source_files_for_type (klass);
6782 g_hash_table_insert (info->source_files, klass, files);
6784 for (i = 0; i < files->len; ++i) {
6785 char *s = g_ptr_array_index (files, i);
6786 char *s2 = g_path_get_basename (s);
6789 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
6791 class_list = g_slist_prepend (class_list, klass);
6792 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
6794 class_list = g_slist_prepend (class_list, klass);
6795 g_hash_table_insert (info->source_file_to_class, s2, class_list);
6798 /* The _ignorecase hash contains the lowercase path */
6799 s3 = strdup_tolower (s2);
6800 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
6802 class_list = g_slist_prepend (class_list, klass);
6803 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
6805 class_list = g_slist_prepend (class_list, klass);
6806 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
6818 s = strdup_tolower (basename);
6819 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
6822 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
6825 for (l = class_list; l; l = l->next) {
6828 g_ptr_array_add (res_classes, klass);
6829 g_ptr_array_add (res_domains, domain);
6832 mono_loader_unlock ();
6837 buffer_add_int (buf, res_classes->len);
6838 for (i = 0; i < res_classes->len; ++i)
6839 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6840 g_ptr_array_free (res_classes, TRUE);
6841 g_ptr_array_free (res_domains, TRUE);
6844 case CMD_VM_GET_TYPES: {
6845 GHashTableIter iter;
6849 gboolean ignore_case;
6850 GPtrArray *res_classes, *res_domains;
6851 MonoTypeNameParse info;
6853 name = decode_string (p, &p, end);
6854 ignore_case = decode_byte (p, &p, end);
6856 if (!mono_reflection_parse_type (name, &info)) {
6858 mono_reflection_free_type_info (&info);
6859 return ERR_INVALID_ARGUMENT;
6862 res_classes = g_ptr_array_new ();
6863 res_domains = g_ptr_array_new ();
6865 mono_loader_lock ();
6866 g_hash_table_iter_init (&iter, domains);
6867 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6869 gboolean type_resolve;
6873 mono_domain_assemblies_lock (domain);
6874 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6878 type_resolve = TRUE;
6879 t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
6881 g_ptr_array_add (res_classes, mono_type_get_class (t));
6882 g_ptr_array_add (res_domains, domain);
6886 mono_domain_assemblies_unlock (domain);
6888 mono_loader_unlock ();
6891 mono_reflection_free_type_info (&info);
6893 buffer_add_int (buf, res_classes->len);
6894 for (i = 0; i < res_classes->len; ++i)
6895 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6896 g_ptr_array_free (res_classes, TRUE);
6897 g_ptr_array_free (res_domains, TRUE);
6902 return ERR_NOT_IMPLEMENTED;
6909 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6915 case CMD_EVENT_REQUEST_SET: {
6917 int i, event_kind, suspend_policy, nmodifiers, mod;
6920 MonoThread *step_thread;
6921 int size = 0, depth = 0, filter = 0, step_thread_id = 0;
6925 event_kind = decode_byte (p, &p, end);
6926 suspend_policy = decode_byte (p, &p, end);
6927 nmodifiers = decode_byte (p, &p, end);
6929 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
6930 req->id = InterlockedIncrement (&event_request_id);
6931 req->event_kind = event_kind;
6932 req->suspend_policy = suspend_policy;
6933 req->nmodifiers = nmodifiers;
6936 for (i = 0; i < nmodifiers; ++i) {
6937 mod = decode_byte (p, &p, end);
6939 req->modifiers [i].kind = mod;
6940 if (mod == MOD_KIND_COUNT) {
6941 req->modifiers [i].data.count = decode_int (p, &p, end);
6942 } else if (mod == MOD_KIND_LOCATION_ONLY) {
6943 method = decode_methodid (p, &p, end, &domain, &err);
6946 location = decode_long (p, &p, end);
6947 } else if (mod == MOD_KIND_STEP) {
6948 step_thread_id = decode_id (p, &p, end);
6949 size = decode_int (p, &p, end);
6950 depth = decode_int (p, &p, end);
6951 if (CHECK_PROTOCOL_VERSION (2, 16))
6952 filter = decode_int (p, &p, end);
6953 req->modifiers [i].data.filter = filter;
6954 } else if (mod == MOD_KIND_THREAD_ONLY) {
6955 int id = decode_id (p, &p, end);
6957 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
6962 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
6963 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
6967 req->modifiers [i].caught = decode_byte (p, &p, end);
6968 req->modifiers [i].uncaught = decode_byte (p, &p, end);
6969 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" : ""));
6971 req->modifiers [i].data.exc_class = exc_class;
6973 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
6975 return ERR_INVALID_ARGUMENT;
6978 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
6979 int n = decode_int (p, &p, end);
6982 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
6983 for (j = 0; j < n; ++j) {
6984 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
6986 g_free (req->modifiers [i].data.assemblies);
6990 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
6991 int n = decode_int (p, &p, end);
6994 modifier = &req->modifiers [i];
6995 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
6996 for (j = 0; j < n; ++j) {
6997 char *s = decode_string (p, &p, end);
7001 s2 = strdup_tolower (s);
7002 g_hash_table_insert (modifier->data.source_files, s2, s2);
7006 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7007 int n = decode_int (p, &p, end);
7010 modifier = &req->modifiers [i];
7011 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7012 for (j = 0; j < n; ++j) {
7013 char *s = decode_string (p, &p, end);
7016 g_hash_table_insert (modifier->data.type_names, s, s);
7020 return ERR_NOT_IMPLEMENTED;
7024 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7027 req->info = set_breakpoint (method, location, req, &error);
7028 if (!mono_error_ok (&error)) {
7030 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
7031 mono_error_cleanup (&error);
7032 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7034 } else if (req->event_kind == EVENT_KIND_STEP) {
7035 g_assert (step_thread_id);
7037 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7043 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
7048 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7049 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7050 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7051 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7052 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7053 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7055 if (req->nmodifiers) {
7057 return ERR_NOT_IMPLEMENTED;
7061 mono_loader_lock ();
7062 g_ptr_array_add (event_requests, req);
7064 if (agent_config.defer) {
7065 /* Transmit cached data to the client on receipt of the event request */
7066 switch (req->event_kind) {
7067 case EVENT_KIND_APPDOMAIN_CREATE:
7068 /* Emit load events for currently loaded domains */
7069 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7071 case EVENT_KIND_ASSEMBLY_LOAD:
7072 /* Emit load events for currently loaded assemblies */
7073 mono_assembly_foreach (emit_assembly_load, NULL);
7075 case EVENT_KIND_THREAD_START:
7076 /* Emit start events for currently started threads */
7077 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7079 case EVENT_KIND_TYPE_LOAD:
7080 /* Emit type load events for currently loaded types */
7081 mono_domain_foreach (send_types_for_domain, NULL);
7087 mono_loader_unlock ();
7089 buffer_add_int (buf, req->id);
7092 case CMD_EVENT_REQUEST_CLEAR: {
7093 int etype = decode_byte (p, &p, end);
7094 int req_id = decode_int (p, &p, end);
7096 // FIXME: Make a faster mapping from req_id to request
7097 mono_loader_lock ();
7098 clear_event_request (req_id, etype);
7099 mono_loader_unlock ();
7102 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7105 mono_loader_lock ();
7107 while (i < event_requests->len) {
7108 EventRequest *req = g_ptr_array_index (event_requests, i);
7110 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7111 clear_breakpoint (req->info);
7113 g_ptr_array_remove_index_fast (event_requests, i);
7119 mono_loader_unlock ();
7123 return ERR_NOT_IMPLEMENTED;
7130 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7136 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7137 buffer_add_domainid (buf, mono_get_root_domain ());
7140 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7141 domain = decode_domainid (p, &p, end, NULL, &err);
7144 buffer_add_string (buf, domain->friendly_name);
7147 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7152 domain = decode_domainid (p, &p, end, NULL, &err);
7155 mono_loader_lock ();
7157 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7160 buffer_add_int (buf, count);
7161 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7163 buffer_add_assemblyid (buf, domain, ass);
7165 mono_loader_unlock ();
7168 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7169 domain = decode_domainid (p, &p, end, NULL, &err);
7173 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7176 case CMD_APPDOMAIN_GET_CORLIB: {
7177 domain = decode_domainid (p, &p, end, NULL, &err);
7181 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7184 case CMD_APPDOMAIN_CREATE_STRING: {
7188 domain = decode_domainid (p, &p, end, NULL, &err);
7191 s = decode_string (p, &p, end);
7193 o = mono_string_new (domain, s);
7194 buffer_add_objid (buf, (MonoObject*)o);
7197 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7199 MonoDomain *domain2;
7202 domain = decode_domainid (p, &p, end, NULL, &err);
7205 klass = decode_typeid (p, &p, end, &domain2, &err);
7210 g_assert (domain == domain2);
7212 o = mono_object_new (domain, klass);
7214 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
7218 buffer_add_objid (buf, o);
7222 return ERR_NOT_IMPLEMENTED;
7229 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7235 ass = decode_assemblyid (p, &p, end, &domain, &err);
7240 case CMD_ASSEMBLY_GET_LOCATION: {
7241 buffer_add_string (buf, mono_image_get_filename (ass->image));
7244 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7248 if (ass->image->dynamic) {
7249 buffer_add_id (buf, 0);
7251 token = mono_image_get_entry_point (ass->image);
7253 buffer_add_id (buf, 0);
7255 m = mono_get_method (ass->image, token, NULL);
7256 buffer_add_methodid (buf, domain, m);
7261 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7262 buffer_add_moduleid (buf, domain, ass->image);
7265 case CMD_ASSEMBLY_GET_OBJECT: {
7266 MonoObject *o = (MonoObject*)mono_assembly_get_object (domain, ass);
7267 buffer_add_objid (buf, o);
7270 case CMD_ASSEMBLY_GET_TYPE: {
7271 char *s = decode_string (p, &p, end);
7272 gboolean ignorecase = decode_byte (p, &p, end);
7273 MonoTypeNameParse info;
7275 gboolean type_resolve, res;
7276 MonoDomain *d = mono_domain_get ();
7278 /* This is needed to be able to find referenced assemblies */
7279 res = mono_domain_set (domain, FALSE);
7282 if (!mono_reflection_parse_type (s, &info)) {
7285 if (info.assembly.name)
7287 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
7289 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
7290 mono_reflection_free_type_info (&info);
7293 mono_domain_set (d, TRUE);
7297 case CMD_ASSEMBLY_GET_NAME: {
7299 MonoAssembly *mass = ass;
7301 name = g_strdup_printf (
7302 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7304 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7305 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7306 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7307 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7309 buffer_add_string (buf, name);
7314 return ERR_NOT_IMPLEMENTED;
7321 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7327 case CMD_MODULE_GET_INFO: {
7328 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7331 basename = g_path_get_basename (image->name);
7332 buffer_add_string (buf, basename); // name
7333 buffer_add_string (buf, image->module_name); // scopename
7334 buffer_add_string (buf, image->name); // fqname
7335 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7336 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7341 return ERR_NOT_IMPLEMENTED;
7348 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7350 if (val && val->vtable->klass == mono_defaults.monotype_class) {
7351 /* Special case these so the client doesn't have to handle Type objects */
7353 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7354 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7355 } else if (MONO_TYPE_IS_REFERENCE (t))
7356 buffer_add_value (buf, t, &val, domain);
7358 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7362 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7368 buffer_add_int (buf, 0);
7372 for (i = 0; i < cinfo->num_attrs; ++i) {
7373 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7376 buffer_add_int (buf, nattrs);
7378 for (i = 0; i < cinfo->num_attrs; ++i) {
7379 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7380 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7381 MonoArray *typed_args, *named_args;
7383 CattrNamedArg *arginfo;
7386 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
7387 g_assert (mono_error_ok (&error));
7389 buffer_add_methodid (buf, domain, attr->ctor);
7393 buffer_add_int (buf, mono_array_length (typed_args));
7394 for (j = 0; j < mono_array_length (typed_args); ++j) {
7395 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7397 t = mono_method_signature (attr->ctor)->params [j];
7399 buffer_add_cattr_arg (buf, t, domain, val);
7402 buffer_add_int (buf, 0);
7407 buffer_add_int (buf, mono_array_length (named_args));
7409 for (j = 0; j < mono_array_length (named_args); ++j) {
7410 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7412 if (arginfo [j].prop) {
7413 buffer_add_byte (buf, 0x54);
7414 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7415 } else if (arginfo [j].field) {
7416 buffer_add_byte (buf, 0x53);
7417 buffer_add_fieldid (buf, domain, arginfo [j].field);
7419 g_assert_not_reached ();
7422 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7425 buffer_add_int (buf, 0);
7431 /* FIXME: Code duplication with icall.c */
7433 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7438 mono_class_setup_interfaces (klass, error);
7439 if (!mono_error_ok (error))
7442 for (i = 0; i < klass->interface_count; i++) {
7443 ic = klass->interfaces [i];
7444 g_hash_table_insert (ifaces, ic, ic);
7446 collect_interfaces (ic, ifaces, error);
7447 if (!mono_error_ok (error))
7453 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7463 case CMD_TYPE_GET_INFO: {
7464 buffer_add_string (buf, klass->name_space);
7465 buffer_add_string (buf, klass->name);
7467 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7468 buffer_add_string (buf, name);
7470 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7471 buffer_add_moduleid (buf, domain, klass->image);
7472 buffer_add_typeid (buf, domain, klass->parent);
7473 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7474 buffer_add_typeid (buf, domain, klass->element_class);
7476 buffer_add_id (buf, 0);
7477 buffer_add_int (buf, klass->type_token);
7478 buffer_add_byte (buf, klass->rank);
7479 buffer_add_int (buf, klass->flags);
7481 type = &klass->byval_arg;
7482 // FIXME: Can't decide whenever a class represents a byref type
7485 if (type->type == MONO_TYPE_PTR)
7487 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7489 if (type->type == MONO_TYPE_VALUETYPE)
7491 if (klass->enumtype)
7493 if (klass->generic_container)
7495 if (klass->generic_container || klass->generic_class)
7497 buffer_add_byte (buf, b);
7500 while ((nested = mono_class_get_nested_types (klass, &iter)))
7502 buffer_add_int (buf, nnested);
7504 while ((nested = mono_class_get_nested_types (klass, &iter)))
7505 buffer_add_typeid (buf, domain, nested);
7506 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7507 if (klass->generic_container)
7508 buffer_add_typeid (buf, domain, klass);
7509 else if (klass->generic_class)
7510 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7512 buffer_add_id (buf, 0);
7514 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7517 if (klass->generic_class) {
7518 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7520 count = inst->type_argc;
7521 buffer_add_int (buf, count);
7522 for (i = 0; i < count; i++)
7523 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7524 } else if (klass->generic_container) {
7525 MonoGenericContainer *container = klass->generic_container;
7528 count = container->type_argc;
7529 buffer_add_int (buf, count);
7530 for (i = 0; i < count; i++) {
7531 pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
7532 buffer_add_typeid (buf, domain, pklass);
7535 buffer_add_int (buf, 0);
7540 case CMD_TYPE_GET_METHODS: {
7543 gpointer iter = NULL;
7546 mono_class_setup_methods (klass);
7548 nmethods = mono_class_num_methods (klass);
7550 buffer_add_int (buf, nmethods);
7552 while ((m = mono_class_get_methods (klass, &iter))) {
7553 buffer_add_methodid (buf, domain, m);
7556 g_assert (i == nmethods);
7559 case CMD_TYPE_GET_FIELDS: {
7562 gpointer iter = NULL;
7565 nfields = mono_class_num_fields (klass);
7567 buffer_add_int (buf, nfields);
7569 while ((f = mono_class_get_fields (klass, &iter))) {
7570 buffer_add_fieldid (buf, domain, f);
7571 buffer_add_string (buf, f->name);
7572 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7573 buffer_add_int (buf, f->type->attrs);
7576 g_assert (i == nfields);
7579 case CMD_TYPE_GET_PROPERTIES: {
7582 gpointer iter = NULL;
7585 nprops = mono_class_num_properties (klass);
7587 buffer_add_int (buf, nprops);
7589 while ((p = mono_class_get_properties (klass, &iter))) {
7590 buffer_add_propertyid (buf, domain, p);
7591 buffer_add_string (buf, p->name);
7592 buffer_add_methodid (buf, domain, p->get);
7593 buffer_add_methodid (buf, domain, p->set);
7594 buffer_add_int (buf, p->attrs);
7597 g_assert (i == nprops);
7600 case CMD_TYPE_GET_CATTRS: {
7601 MonoClass *attr_klass;
7602 MonoCustomAttrInfo *cinfo;
7604 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7605 /* attr_klass can be NULL */
7609 cinfo = mono_custom_attrs_from_class (klass);
7611 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7614 case CMD_TYPE_GET_FIELD_CATTRS: {
7615 MonoClass *attr_klass;
7616 MonoCustomAttrInfo *cinfo;
7617 MonoClassField *field;
7619 field = decode_fieldid (p, &p, end, NULL, &err);
7622 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7626 cinfo = mono_custom_attrs_from_field (klass, field);
7628 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7631 case CMD_TYPE_GET_PROPERTY_CATTRS: {
7632 MonoClass *attr_klass;
7633 MonoCustomAttrInfo *cinfo;
7636 prop = decode_propertyid (p, &p, end, NULL, &err);
7639 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7643 cinfo = mono_custom_attrs_from_property (klass, prop);
7645 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7648 case CMD_TYPE_GET_VALUES:
7649 case CMD_TYPE_GET_VALUES_2: {
7656 MonoThread *thread_obj;
7657 MonoInternalThread *thread = NULL;
7658 guint32 special_static_type;
7660 if (command == CMD_TYPE_GET_VALUES_2) {
7661 int objid = decode_objid (p, &p, end);
7664 err = get_object (objid, (MonoObject**)&thread_obj);
7668 thread = THREAD_TO_INTERNAL (thread_obj);
7671 len = decode_int (p, &p, end);
7672 for (i = 0; i < len; ++i) {
7673 f = decode_fieldid (p, &p, end, NULL, &err);
7677 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7678 return ERR_INVALID_FIELDID;
7679 special_static_type = mono_class_field_get_special_static_type (f);
7680 if (special_static_type != SPECIAL_STATIC_NONE) {
7681 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
7682 return ERR_INVALID_FIELDID;
7685 /* Check that the field belongs to the object */
7687 for (k = klass; k; k = k->parent) {
7688 if (k == f->parent) {
7694 return ERR_INVALID_FIELDID;
7696 vtable = mono_class_vtable (domain, f->parent);
7697 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7698 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
7699 buffer_add_value (buf, f->type, val, domain);
7704 case CMD_TYPE_SET_VALUES: {
7712 len = decode_int (p, &p, end);
7713 for (i = 0; i < len; ++i) {
7714 f = decode_fieldid (p, &p, end, NULL, &err);
7718 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7719 return ERR_INVALID_FIELDID;
7720 if (mono_class_field_is_special_static (f))
7721 return ERR_INVALID_FIELDID;
7723 /* Check that the field belongs to the object */
7725 for (k = klass; k; k = k->parent) {
7726 if (k == f->parent) {
7732 return ERR_INVALID_FIELDID;
7734 // FIXME: Check for literal/const
7736 vtable = mono_class_vtable (domain, f->parent);
7737 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7738 err = decode_value (f->type, domain, val, p, &p, end);
7743 if (MONO_TYPE_IS_REFERENCE (f->type))
7744 mono_field_static_set_value (vtable, f, *(gpointer*)val);
7746 mono_field_static_set_value (vtable, f, val);
7751 case CMD_TYPE_GET_OBJECT: {
7752 MonoObject *o = (MonoObject*)mono_type_get_object (domain, &klass->byval_arg);
7753 buffer_add_objid (buf, o);
7756 case CMD_TYPE_GET_SOURCE_FILES:
7757 case CMD_TYPE_GET_SOURCE_FILES_2: {
7758 char *source_file, *base;
7762 files = get_source_files_for_type (klass);
7764 buffer_add_int (buf, files->len);
7765 for (i = 0; i < files->len; ++i) {
7766 source_file = g_ptr_array_index (files, i);
7767 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
7768 buffer_add_string (buf, source_file);
7770 base = g_path_get_basename (source_file);
7771 buffer_add_string (buf, base);
7774 g_free (source_file);
7776 g_ptr_array_free (files, TRUE);
7779 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
7780 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
7784 if (mono_class_is_assignable_from (klass, oklass))
7785 buffer_add_byte (buf, 1);
7787 buffer_add_byte (buf, 0);
7790 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
7791 char *name = decode_string (p, &p, end);
7792 int i, flags = decode_int (p, &p, end);
7793 MonoException *ex = NULL;
7794 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
7797 return ERR_LOADER_ERROR;
7798 buffer_add_int (buf, array->len);
7799 for (i = 0; i < array->len; ++i) {
7800 MonoMethod *method = g_ptr_array_index (array, i);
7801 buffer_add_methodid (buf, domain, method);
7804 g_ptr_array_free (array, TRUE);
7808 case CMD_TYPE_GET_INTERFACES: {
7810 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
7812 MonoClass *tclass, *iface;
7813 GHashTableIter iter;
7817 for (parent = tclass; parent; parent = parent->parent) {
7818 mono_class_setup_interfaces (parent, &error);
7819 if (!mono_error_ok (&error))
7820 return ERR_LOADER_ERROR;
7821 collect_interfaces (parent, iface_hash, &error);
7822 if (!mono_error_ok (&error))
7823 return ERR_LOADER_ERROR;
7826 buffer_add_int (buf, g_hash_table_size (iface_hash));
7828 g_hash_table_iter_init (&iter, iface_hash);
7829 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
7830 buffer_add_typeid (buf, domain, iface);
7831 g_hash_table_destroy (iface_hash);
7834 case CMD_TYPE_GET_INTERFACE_MAP: {
7835 int tindex, ioffset;
7836 gboolean variance_used;
7838 int len, nmethods, i;
7842 len = decode_int (p, &p, end);
7843 mono_class_setup_vtable (klass);
7845 for (tindex = 0; tindex < len; ++tindex) {
7846 iclass = decode_typeid (p, &p, end, NULL, &err);
7850 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
7852 return ERR_INVALID_ARGUMENT;
7854 nmethods = mono_class_num_methods (iclass);
7855 buffer_add_int (buf, nmethods);
7858 while ((method = mono_class_get_methods (iclass, &iter))) {
7859 buffer_add_methodid (buf, domain, method);
7861 for (i = 0; i < nmethods; ++i)
7862 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
7866 case CMD_TYPE_IS_INITIALIZED: {
7867 MonoVTable *vtable = mono_class_vtable (domain, klass);
7870 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
7872 buffer_add_int (buf, 0);
7876 return ERR_NOT_IMPLEMENTED;
7883 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7886 MonoDomain *old_domain;
7890 klass = decode_typeid (p, &p, end, &domain, &err);
7894 old_domain = mono_domain_get ();
7896 mono_domain_set (domain, TRUE);
7898 err = type_commands_internal (command, klass, domain, p, end, buf);
7900 mono_domain_set (old_domain, TRUE);
7906 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7908 MonoMethodHeader *header;
7912 case CMD_METHOD_GET_NAME: {
7913 buffer_add_string (buf, method->name);
7916 case CMD_METHOD_GET_DECLARING_TYPE: {
7917 buffer_add_typeid (buf, domain, method->klass);
7920 case CMD_METHOD_GET_DEBUG_INFO: {
7921 MonoDebugMethodInfo *minfo;
7923 int i, j, n_il_offsets;
7926 int *column_numbers;
7928 GPtrArray *source_file_list;
7930 header = mono_method_get_header (method);
7932 buffer_add_int (buf, 0);
7933 buffer_add_string (buf, "");
7934 buffer_add_int (buf, 0);
7938 minfo = mono_debug_lookup_method (method);
7940 buffer_add_int (buf, header->code_size);
7941 buffer_add_string (buf, "");
7942 buffer_add_int (buf, 0);
7943 mono_metadata_free_mh (header);
7947 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, &n_il_offsets, &il_offsets, &line_numbers, &column_numbers, &source_files);
7948 buffer_add_int (buf, header->code_size);
7949 if (CHECK_PROTOCOL_VERSION (2, 13)) {
7950 buffer_add_int (buf, source_file_list->len);
7951 for (i = 0; i < source_file_list->len; ++i) {
7952 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
7953 buffer_add_string (buf, sinfo->source_file);
7954 if (CHECK_PROTOCOL_VERSION (2, 14)) {
7955 for (j = 0; j < 16; ++j)
7956 buffer_add_byte (buf, sinfo->hash [j]);
7960 buffer_add_string (buf, source_file);
7962 buffer_add_int (buf, n_il_offsets);
7963 DEBUG (10, fprintf (log_file, "Line number table for method %s:\n", mono_method_full_name (method, TRUE)));
7964 for (i = 0; i < n_il_offsets; ++i) {
7965 const char *srcfile = "";
7967 if (source_files [i] != -1) {
7968 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
7969 srcfile = sinfo->source_file;
7971 DEBUG (10, fprintf (log_file, "IL%x -> %s:%d %d\n", il_offsets [i], srcfile, line_numbers [i], column_numbers ? column_numbers [i] : -1));
7972 buffer_add_int (buf, il_offsets [i]);
7973 buffer_add_int (buf, line_numbers [i]);
7974 if (CHECK_PROTOCOL_VERSION (2, 13))
7975 buffer_add_int (buf, source_files [i]);
7976 if (CHECK_PROTOCOL_VERSION (2, 19))
7977 buffer_add_int (buf, column_numbers ? column_numbers [i] : -1);
7979 g_free (source_file);
7980 g_free (il_offsets);
7981 g_free (line_numbers);
7982 g_free (source_files);
7983 g_ptr_array_free (source_file_list, TRUE);
7984 mono_metadata_free_mh (header);
7987 case CMD_METHOD_GET_PARAM_INFO: {
7988 MonoMethodSignature *sig = mono_method_signature (method);
7992 /* FIXME: mono_class_from_mono_type () and byrefs */
7994 /* FIXME: Use a smaller encoding */
7995 buffer_add_int (buf, sig->call_convention);
7996 buffer_add_int (buf, sig->param_count);
7997 buffer_add_int (buf, sig->generic_param_count);
7998 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
7999 for (i = 0; i < sig->param_count; ++i) {
8001 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
8004 /* Emit parameter names */
8005 names = g_new (char *, sig->param_count);
8006 mono_method_get_param_names (method, (const char **) names);
8007 for (i = 0; i < sig->param_count; ++i)
8008 buffer_add_string (buf, names [i]);
8013 case CMD_METHOD_GET_LOCALS_INFO: {
8014 int i, j, num_locals;
8015 MonoDebugLocalsInfo *locals;
8017 header = mono_method_get_header (method);
8019 return ERR_INVALID_ARGUMENT;
8021 buffer_add_int (buf, header->num_locals);
8024 for (i = 0; i < header->num_locals; ++i)
8025 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
8028 locals = mono_debug_lookup_locals (method);
8030 num_locals = locals->num_locals;
8033 for (i = 0; i < header->num_locals; ++i) {
8034 for (j = 0; j < num_locals; ++j)
8035 if (locals->locals [j].index == i)
8038 buffer_add_string (buf, locals->locals [j].name);
8040 buffer_add_string (buf, "");
8044 for (i = 0; i < header->num_locals; ++i) {
8045 for (j = 0; j < num_locals; ++j)
8046 if (locals->locals [j].index == i)
8048 if (j < num_locals && locals->locals [j].block) {
8049 buffer_add_int (buf, locals->locals [j].block->start_offset);
8050 buffer_add_int (buf, locals->locals [j].block->end_offset);
8052 buffer_add_int (buf, 0);
8053 buffer_add_int (buf, header->code_size);
8056 mono_metadata_free_mh (header);
8059 mono_debug_symfile_free_locals (locals);
8063 case CMD_METHOD_GET_INFO:
8064 buffer_add_int (buf, method->flags);
8065 buffer_add_int (buf, method->iflags);
8066 buffer_add_int (buf, method->token);
8067 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8069 if (method->is_generic)
8071 if (mono_method_signature (method)->generic_param_count)
8073 buffer_add_byte (buf, attrs);
8074 if (method->is_generic || method->is_inflated) {
8077 if (method->is_generic) {
8080 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8082 result = imethod->declaring;
8083 if (imethod->context.class_inst) {
8084 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8085 /*Generic methods gets the context of the GTD.*/
8086 if (mono_class_get_context (klass))
8087 result = mono_class_inflate_generic_method_full (result, klass, mono_class_get_context (klass));
8091 buffer_add_methodid (buf, domain, result);
8093 buffer_add_id (buf, 0);
8095 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8096 if (mono_method_signature (method)->generic_param_count) {
8099 if (method->is_inflated) {
8100 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
8102 count = inst->type_argc;
8103 buffer_add_int (buf, count);
8105 for (i = 0; i < count; i++)
8106 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8108 buffer_add_int (buf, 0);
8110 } else if (method->is_generic) {
8111 MonoGenericContainer *container = mono_method_get_generic_container (method);
8113 count = mono_method_signature (method)->generic_param_count;
8114 buffer_add_int (buf, count);
8115 for (i = 0; i < count; i++) {
8116 MonoGenericParam *param = mono_generic_container_get_param (container, i);
8117 MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
8118 buffer_add_typeid (buf, domain, pklass);
8121 buffer_add_int (buf, 0);
8124 buffer_add_int (buf, 0);
8129 case CMD_METHOD_GET_BODY: {
8132 header = mono_method_get_header (method);
8134 buffer_add_int (buf, 0);
8136 if (CHECK_PROTOCOL_VERSION (2, 18))
8137 buffer_add_int (buf, 0);
8139 buffer_add_int (buf, header->code_size);
8140 for (i = 0; i < header->code_size; ++i)
8141 buffer_add_byte (buf, header->code [i]);
8143 if (CHECK_PROTOCOL_VERSION (2, 18)) {
8144 buffer_add_int (buf, header->num_clauses);
8145 for (i = 0; i < header->num_clauses; ++i) {
8146 MonoExceptionClause *clause = &header->clauses [i];
8148 buffer_add_int (buf, clause->flags);
8149 buffer_add_int (buf, clause->try_offset);
8150 buffer_add_int (buf, clause->try_len);
8151 buffer_add_int (buf, clause->handler_offset);
8152 buffer_add_int (buf, clause->handler_len);
8153 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
8154 buffer_add_typeid (buf, domain, clause->data.catch_class);
8155 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8156 buffer_add_int (buf, clause->data.filter_offset);
8160 mono_metadata_free_mh (header);
8165 case CMD_METHOD_RESOLVE_TOKEN: {
8166 guint32 token = decode_int (p, &p, end);
8169 switch (mono_metadata_token_code (token)) {
8170 case MONO_TOKEN_STRING: {
8174 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
8177 s2 = mono_string_to_utf8 (s);
8179 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8180 buffer_add_string (buf, s2);
8186 MonoClass *handle_class;
8188 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8189 val = mono_method_get_wrapper_data (method, token);
8190 handle_class = mono_method_get_wrapper_data (method, token + 1);
8192 if (handle_class == NULL) {
8193 // Can't figure out the token type
8194 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8198 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
8202 if (handle_class == mono_defaults.typehandle_class) {
8203 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8204 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8205 buffer_add_typeid (buf, domain, (MonoClass *) val);
8207 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
8208 } else if (handle_class == mono_defaults.fieldhandle_class) {
8209 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8210 buffer_add_fieldid (buf, domain, val);
8211 } else if (handle_class == mono_defaults.methodhandle_class) {
8212 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8213 buffer_add_methodid (buf, domain, val);
8214 } else if (handle_class == mono_defaults.string_class) {
8217 s = mono_string_to_utf8 (val);
8218 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8219 buffer_add_string (buf, s);
8222 g_assert_not_reached ();
8229 case CMD_METHOD_GET_CATTRS: {
8230 MonoClass *attr_klass;
8231 MonoCustomAttrInfo *cinfo;
8233 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8234 /* attr_klass can be NULL */
8238 cinfo = mono_custom_attrs_from_method (method);
8240 buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
8243 case CMD_METHOD_MAKE_GENERIC_METHOD: {
8244 MonoType **type_argv;
8248 MonoGenericInst *ginst;
8249 MonoGenericContext tmp_context;
8250 MonoMethod *inflated;
8252 type_argc = decode_int (p, &p, end);
8253 type_argv = g_new0 (MonoType*, type_argc);
8254 for (i = 0; i < type_argc; ++i) {
8255 klass = decode_typeid (p, &p, end, &d, &err);
8262 return ERR_INVALID_ARGUMENT;
8264 type_argv [i] = &klass->byval_arg;
8266 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
8268 tmp_context.class_inst = method->klass->generic_class ? method->klass->generic_class->context.class_inst : NULL;
8269 tmp_context.method_inst = ginst;
8271 inflated = mono_class_inflate_generic_method (method, &tmp_context);
8272 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
8273 return ERR_INVALID_ARGUMENT;
8274 buffer_add_methodid (buf, domain, inflated);
8278 return ERR_NOT_IMPLEMENTED;
8285 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8288 MonoDomain *old_domain;
8292 method = decode_methodid (p, &p, end, &domain, &err);
8296 old_domain = mono_domain_get ();
8298 mono_domain_set (domain, TRUE);
8300 err = method_commands_internal (command, method, domain, p, end, buf);
8302 mono_domain_set (old_domain, TRUE);
8308 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8310 int objid = decode_objid (p, &p, end);
8312 MonoThread *thread_obj;
8313 MonoInternalThread *thread;
8315 err = get_object (objid, (MonoObject**)&thread_obj);
8319 thread = THREAD_TO_INTERNAL (thread_obj);
8322 case CMD_THREAD_GET_NAME: {
8324 gunichar2 *s = mono_thread_get_name (thread, &name_len);
8327 buffer_add_int (buf, 0);
8332 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
8334 buffer_add_int (buf, len);
8335 buffer_add_data (buf, (guint8*)name, len);
8340 case CMD_THREAD_GET_FRAME_INFO: {
8341 DebuggerTlsData *tls;
8342 int i, start_frame, length;
8344 // Wait for suspending if it already started
8345 // FIXME: Races with suspend_count
8346 while (!is_suspended ()) {
8348 wait_for_suspend ();
8352 wait_for_suspend ();
8353 if (!is_suspended ())
8354 return ERR_NOT_SUSPENDED;
8357 start_frame = decode_int (p, &p, end);
8358 length = decode_int (p, &p, end);
8360 if (start_frame != 0 || length != -1)
8361 return ERR_NOT_IMPLEMENTED;
8363 mono_loader_lock ();
8364 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8365 mono_loader_unlock ();
8368 compute_frame_info (thread, tls);
8370 buffer_add_int (buf, tls->frame_count);
8371 for (i = 0; i < tls->frame_count; ++i) {
8372 buffer_add_int (buf, tls->frames [i]->id);
8373 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
8374 buffer_add_int (buf, tls->frames [i]->il_offset);
8376 * Instead of passing the frame type directly to the client, we associate
8377 * it with the previous frame using a set of flags. This avoids lots of
8378 * conditional code in the client, since a frame whose type isn't
8379 * FRAME_TYPE_MANAGED has no method, location, etc.
8381 buffer_add_byte (buf, tls->frames [i]->flags);
8386 case CMD_THREAD_GET_STATE:
8387 buffer_add_int (buf, thread->state);
8389 case CMD_THREAD_GET_INFO:
8390 buffer_add_byte (buf, thread->threadpool_thread);
8392 case CMD_THREAD_GET_ID:
8393 buffer_add_long (buf, (guint64)(gsize)thread);
8395 case CMD_THREAD_GET_TID:
8396 buffer_add_long (buf, (guint64)thread->tid);
8399 return ERR_NOT_IMPLEMENTED;
8406 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8410 MonoThread *thread_obj;
8411 MonoInternalThread *thread;
8412 int pos, i, len, frame_idx;
8413 DebuggerTlsData *tls;
8415 MonoDebugMethodJitInfo *jit;
8416 MonoDebugVarInfo *var;
8417 MonoMethodSignature *sig;
8419 MonoMethodHeader *header;
8421 objid = decode_objid (p, &p, end);
8422 err = get_object (objid, (MonoObject**)&thread_obj);
8426 thread = THREAD_TO_INTERNAL (thread_obj);
8428 id = decode_id (p, &p, end);
8430 mono_loader_lock ();
8431 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8432 mono_loader_unlock ();
8435 for (i = 0; i < tls->frame_count; ++i) {
8436 if (tls->frames [i]->id == id)
8439 if (i == tls->frame_count)
8440 return ERR_INVALID_FRAMEID;
8443 frame = tls->frames [frame_idx];
8445 if (!frame->has_ctx)
8446 return ERR_ABSENT_INFORMATION;
8449 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
8450 if (!frame->jit && frame->api_method->is_inflated)
8451 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
8455 /* This could happen for aot images with no jit debug info */
8456 s = mono_method_full_name (frame->api_method, TRUE);
8457 DEBUG (1, fprintf (log_file, "[dbg] No debug information found for '%s'.\n", s));
8459 return ERR_ABSENT_INFORMATION;
8464 sig = mono_method_signature (frame->actual_method);
8466 if (!get_seq_points (frame->domain, frame->actual_method))
8468 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
8470 return ERR_ABSENT_INFORMATION;
8473 case CMD_STACK_FRAME_GET_VALUES: {
8474 len = decode_int (p, &p, end);
8475 header = mono_method_get_header (frame->actual_method);
8477 for (i = 0; i < len; ++i) {
8478 pos = decode_int (p, &p, end);
8483 g_assert (pos >= 0 && pos < jit->num_params);
8485 var = &jit->params [pos];
8487 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
8489 g_assert (pos >= 0 && pos < jit->num_locals);
8491 var = &jit->locals [pos];
8493 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
8496 mono_metadata_free_mh (header);
8499 case CMD_STACK_FRAME_GET_THIS: {
8500 if (frame->api_method->klass->valuetype) {
8501 if (!sig->hasthis) {
8502 MonoObject *p = NULL;
8503 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
8505 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8508 if (!sig->hasthis) {
8509 MonoObject *p = NULL;
8510 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
8512 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8517 case CMD_STACK_FRAME_SET_VALUES: {
8520 MonoDebugVarInfo *var;
8522 len = decode_int (p, &p, end);
8523 header = mono_method_get_header (frame->actual_method);
8525 for (i = 0; i < len; ++i) {
8526 pos = decode_int (p, &p, end);
8531 g_assert (pos >= 0 && pos < jit->num_params);
8533 t = sig->params [pos];
8534 var = &jit->params [pos];
8536 g_assert (pos >= 0 && pos < jit->num_locals);
8538 t = header->locals [pos];
8539 var = &jit->locals [pos];
8542 if (MONO_TYPE_IS_REFERENCE (t))
8543 val_buf = g_alloca (sizeof (MonoObject*));
8545 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
8546 err = decode_value (t, frame->domain, val_buf, p, &p, end);
8550 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_ctx);
8552 mono_metadata_free_mh (header);
8556 return ERR_NOT_IMPLEMENTED;
8563 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8566 int objid, err, index, len, i, esize;
8569 objid = decode_objid (p, &p, end);
8570 err = get_object (objid, (MonoObject**)&arr);
8575 case CMD_ARRAY_REF_GET_LENGTH:
8576 buffer_add_int (buf, arr->obj.vtable->klass->rank);
8578 buffer_add_int (buf, arr->max_length);
8579 buffer_add_int (buf, 0);
8581 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
8582 buffer_add_int (buf, arr->bounds [i].length);
8583 buffer_add_int (buf, arr->bounds [i].lower_bound);
8587 case CMD_ARRAY_REF_GET_VALUES:
8588 index = decode_int (p, &p, end);
8589 len = decode_int (p, &p, end);
8591 g_assert (index >= 0 && len >= 0);
8592 // Reordered to avoid integer overflow
8593 g_assert (!(index > arr->max_length - len));
8595 esize = mono_array_element_size (arr->obj.vtable->klass);
8596 for (i = index; i < index + len; ++i) {
8597 elem = (gpointer*)((char*)arr->vector + (i * esize));
8598 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
8601 case CMD_ARRAY_REF_SET_VALUES:
8602 index = decode_int (p, &p, end);
8603 len = decode_int (p, &p, end);
8605 g_assert (index >= 0 && len >= 0);
8606 // Reordered to avoid integer overflow
8607 g_assert (!(index > arr->max_length - len));
8609 esize = mono_array_element_size (arr->obj.vtable->klass);
8610 for (i = index; i < index + len; ++i) {
8611 elem = (gpointer*)((char*)arr->vector + (i * esize));
8613 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
8617 return ERR_NOT_IMPLEMENTED;
8624 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8629 int i, index, length;
8632 objid = decode_objid (p, &p, end);
8633 err = get_object (objid, (MonoObject**)&str);
8638 case CMD_STRING_REF_GET_VALUE:
8639 s = mono_string_to_utf8 (str);
8640 buffer_add_string (buf, s);
8643 case CMD_STRING_REF_GET_LENGTH:
8644 buffer_add_long (buf, mono_string_length (str));
8646 case CMD_STRING_REF_GET_CHARS:
8647 index = decode_long (p, &p, end);
8648 length = decode_long (p, &p, end);
8649 if (index > mono_string_length (str) - length)
8650 return ERR_INVALID_ARGUMENT;
8651 c = mono_string_chars (str) + index;
8652 for (i = 0; i < length; ++i)
8653 buffer_add_short (buf, c [i]);
8656 return ERR_NOT_IMPLEMENTED;
8663 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8672 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
8673 objid = decode_objid (p, &p, end);
8674 err = get_object (objid, &obj);
8676 buffer_add_int (buf, 1);
8678 buffer_add_int (buf, 0);
8682 objid = decode_objid (p, &p, end);
8683 err = get_object (objid, &obj);
8688 case CMD_OBJECT_REF_GET_TYPE:
8689 /* This handles transparent proxies too */
8690 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8692 case CMD_OBJECT_REF_GET_VALUES:
8693 len = decode_int (p, &p, end);
8695 for (i = 0; i < len; ++i) {
8696 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
8700 /* Check that the field belongs to the object */
8702 for (k = obj->vtable->klass; k; k = k->parent) {
8703 if (k == f->parent) {
8709 return ERR_INVALID_FIELDID;
8711 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8715 if (mono_class_field_is_special_static (f))
8716 return ERR_INVALID_FIELDID;
8718 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8719 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8720 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8721 mono_field_static_get_value (vtable, f, val);
8722 buffer_add_value (buf, f->type, val, obj->vtable->domain);
8725 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
8729 case CMD_OBJECT_REF_SET_VALUES:
8730 len = decode_int (p, &p, end);
8732 for (i = 0; i < len; ++i) {
8733 f = decode_fieldid (p, &p, end, NULL, &err);
8737 /* Check that the field belongs to the object */
8739 for (k = obj->vtable->klass; k; k = k->parent) {
8740 if (k == f->parent) {
8746 return ERR_INVALID_FIELDID;
8748 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8752 if (mono_class_field_is_special_static (f))
8753 return ERR_INVALID_FIELDID;
8755 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8756 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8758 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8759 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
8764 mono_field_static_set_value (vtable, f, val);
8767 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
8773 case CMD_OBJECT_REF_GET_ADDRESS:
8774 buffer_add_long (buf, (gssize)obj);
8776 case CMD_OBJECT_REF_GET_DOMAIN:
8777 buffer_add_domainid (buf, obj->vtable->domain);
8779 case CMD_OBJECT_REF_GET_INFO:
8780 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8781 buffer_add_domainid (buf, obj->vtable->domain);
8784 return ERR_NOT_IMPLEMENTED;
8791 command_set_to_string (CommandSet command_set)
8793 switch (command_set) {
8796 case CMD_SET_OBJECT_REF:
8797 return "OBJECT_REF";
8798 case CMD_SET_STRING_REF:
8799 return "STRING_REF";
8800 case CMD_SET_THREAD:
8802 case CMD_SET_ARRAY_REF:
8804 case CMD_SET_EVENT_REQUEST:
8805 return "EVENT_REQUEST";
8806 case CMD_SET_STACK_FRAME:
8807 return "STACK_FRAME";
8808 case CMD_SET_APPDOMAIN:
8810 case CMD_SET_ASSEMBLY:
8812 case CMD_SET_METHOD:
8816 case CMD_SET_MODULE:
8825 static const char* vm_cmds_str [] = {
8833 "SET_PROTOCOL_VERSION",
8836 "GET_TYPES_FOR_SOURCE_FILE",
8841 static const char* thread_cmds_str[] = {
8850 static const char* event_cmds_str[] = {
8853 "REQUEST_CLEAR_ALL_BREAKPOINTS"
8856 static const char* appdomain_cmds_str[] = {
8858 "GET_FRIENDLY_NAME",
8860 "GET_ENTRY_ASSEMBLY",
8863 "CREATE_BOXED_VALUE"
8866 static const char* assembly_cmds_str[] = {
8869 "GET_MANIFEST_MODULE",
8875 static const char* module_cmds_str[] = {
8879 static const char* method_cmds_str[] = {
8881 "GET_DECLARING_TYPE",
8889 "MAKE_GENERIC_METHOD"
8892 static const char* type_cmds_str[] = {
8900 "IS_ASSIGNABLE_FROM",
8904 "GET_PROPERTY_CATTRS",
8905 "GET_SOURCE_FILES_2",
8907 "GET_METHODS_BY_NAME_FLAGS",
8909 "GET_INTERFACE_MAP",
8913 static const char* stack_frame_cmds_str[] = {
8919 static const char* array_cmds_str[] = {
8925 static const char* string_cmds_str[] = {
8931 static const char* object_cmds_str[] = {
8942 cmd_to_string (CommandSet set, int command)
8950 cmds_len = G_N_ELEMENTS (vm_cmds_str);
8952 case CMD_SET_OBJECT_REF:
8953 cmds = object_cmds_str;
8954 cmds_len = G_N_ELEMENTS (object_cmds_str);
8956 case CMD_SET_STRING_REF:
8957 cmds = string_cmds_str;
8958 cmds_len = G_N_ELEMENTS (string_cmds_str);
8960 case CMD_SET_THREAD:
8961 cmds = thread_cmds_str;
8962 cmds_len = G_N_ELEMENTS (thread_cmds_str);
8964 case CMD_SET_ARRAY_REF:
8965 cmds = array_cmds_str;
8966 cmds_len = G_N_ELEMENTS (array_cmds_str);
8968 case CMD_SET_EVENT_REQUEST:
8969 cmds = event_cmds_str;
8970 cmds_len = G_N_ELEMENTS (event_cmds_str);
8972 case CMD_SET_STACK_FRAME:
8973 cmds = stack_frame_cmds_str;
8974 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
8976 case CMD_SET_APPDOMAIN:
8977 cmds = appdomain_cmds_str;
8978 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
8980 case CMD_SET_ASSEMBLY:
8981 cmds = assembly_cmds_str;
8982 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
8984 case CMD_SET_METHOD:
8985 cmds = method_cmds_str;
8986 cmds_len = G_N_ELEMENTS (method_cmds_str);
8989 cmds = type_cmds_str;
8990 cmds_len = G_N_ELEMENTS (type_cmds_str);
8992 case CMD_SET_MODULE:
8993 cmds = module_cmds_str;
8994 cmds_len = G_N_ELEMENTS (module_cmds_str);
8997 cmds = event_cmds_str;
8998 cmds_len = G_N_ELEMENTS (event_cmds_str);
9003 if (command > 0 && command <= cmds_len)
9004 return cmds [command - 1];
9010 wait_for_attach (void)
9012 #ifndef DISABLE_SOCKET_TRANSPORT
9013 if (listen_fd == -1) {
9014 DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
9018 /* Block and wait for client connection */
9019 conn_fd = socket_transport_accept (listen_fd);
9020 DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
9021 if (conn_fd == -1) {
9022 DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
9026 g_assert_not_reached ();
9030 disconnected = !transport_handshake ();
9032 DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
9042 * This thread handles communication with the debugger client using a JDWP
9045 static guint32 WINAPI
9046 debugger_thread (void *arg)
9048 int res, len, id, flags, command_set = 0, command = 0;
9049 guint8 header [HEADER_LENGTH];
9050 guint8 *data, *p, *end;
9054 gboolean attach_failed = FALSE;
9056 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
9058 debugger_thread_id = GetCurrentThreadId ();
9060 mono_jit_thread_attach (mono_get_root_domain ());
9062 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
9064 mono_set_is_debugger_attached (TRUE);
9066 if (agent_config.defer) {
9067 if (!wait_for_attach ()) {
9068 DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
9069 attach_failed = TRUE; // Don't abort process when we can't listen
9071 /* Send start event to client */
9072 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
9076 while (!attach_failed) {
9077 res = transport_recv (header, HEADER_LENGTH);
9079 /* This will break if the socket is closed during shutdown too */
9080 if (res != HEADER_LENGTH) {
9081 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH));
9086 end = header + HEADER_LENGTH;
9088 len = decode_int (p, &p, end);
9089 id = decode_int (p, &p, end);
9090 flags = decode_byte (p, &p, end);
9091 command_set = decode_byte (p, &p, end);
9092 command = decode_byte (p, &p, end);
9094 g_assert (flags == 0);
9097 const char *cmd_str;
9100 cmd_str = cmd_to_string (command_set, command);
9102 sprintf (cmd_num, "%d", command);
9106 DEBUG (1, fprintf (log_file, "[dbg] Command %s(%s) [%d].\n", command_set_to_string (command_set), cmd_str, id));
9109 data = g_malloc (len - HEADER_LENGTH);
9110 if (len - HEADER_LENGTH > 0)
9112 res = transport_recv (data, len - HEADER_LENGTH);
9113 if (res != len - HEADER_LENGTH) {
9114 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH));
9120 end = data + (len - HEADER_LENGTH);
9122 buffer_init (&buf, 128);
9127 /* Process the request */
9128 switch (command_set) {
9130 err = vm_commands (command, id, p, end, &buf);
9131 if (!err && command == CMD_VM_INVOKE_METHOD)
9132 /* Sent after the invoke is complete */
9135 case CMD_SET_EVENT_REQUEST:
9136 err = event_commands (command, p, end, &buf);
9138 case CMD_SET_APPDOMAIN:
9139 err = domain_commands (command, p, end, &buf);
9141 case CMD_SET_ASSEMBLY:
9142 err = assembly_commands (command, p, end, &buf);
9144 case CMD_SET_MODULE:
9145 err = module_commands (command, p, end, &buf);
9148 err = type_commands (command, p, end, &buf);
9150 case CMD_SET_METHOD:
9151 err = method_commands (command, p, end, &buf);
9153 case CMD_SET_THREAD:
9154 err = thread_commands (command, p, end, &buf);
9156 case CMD_SET_STACK_FRAME:
9157 err = frame_commands (command, p, end, &buf);
9159 case CMD_SET_ARRAY_REF:
9160 err = array_commands (command, p, end, &buf);
9162 case CMD_SET_STRING_REF:
9163 err = string_commands (command, p, end, &buf);
9165 case CMD_SET_OBJECT_REF:
9166 err = object_commands (command, p, end, &buf);
9169 err = ERR_NOT_IMPLEMENTED;
9173 send_reply_packet (id, err, &buf);
9178 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
9182 mono_set_is_debugger_attached (FALSE);
9184 mono_mutex_lock (&debugger_thread_exited_mutex);
9185 debugger_thread_exited = TRUE;
9186 mono_cond_signal (&debugger_thread_exited_cond);
9187 mono_mutex_unlock (&debugger_thread_exited_mutex);
9189 DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
9191 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
9192 DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
9193 start_debugger_thread ();
9199 #else /* DISABLE_DEBUGGER_AGENT */
9202 mono_debugger_agent_parse_options (char *options)
9204 g_error ("This runtime is configured with the debugger agent disabled.");
9208 mono_debugger_agent_init (void)
9213 mono_debugger_agent_breakpoint_hit (void *sigctx)
9218 mono_debugger_agent_single_step_event (void *sigctx)
9223 mono_debugger_agent_free_domain_info (MonoDomain *domain)
9228 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
9234 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
9235 MonoContext *catch_ctx)
9240 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9245 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9250 mono_debugger_agent_user_break (void)
9256 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
9261 mono_debugger_agent_debug_log_is_enabled (void)