2 * debugger-agent.c: Soft Debugger back-end module
5 * Zoltan Varga (vargaz@gmail.com)
7 * Copyright 2009-2010 Novell, Inc.
8 * Copyright 2011 Xamarin Inc.
15 #ifdef HAVE_SYS_TYPES_H
16 #include <sys/types.h>
18 #ifdef HAVE_SYS_SELECT_H
19 #include <sys/select.h>
21 #ifdef HAVE_SYS_SOCKET_H
22 #include <sys/socket.h>
24 #ifdef HAVE_NETINET_TCP_H
25 #include <netinet/tcp.h>
27 #ifdef HAVE_NETINET_IN_H
28 #include <netinet/in.h>
43 #ifdef HAVE_UCONTEXT_H
53 /* cygwin's headers do not seem to define these */
54 void WSAAPI freeaddrinfo (struct addrinfo*);
55 int WSAAPI getaddrinfo (const char*,const char*,const struct addrinfo*,
57 int WSAAPI getnameinfo(const struct sockaddr*,socklen_t,char*,DWORD,
62 #ifdef PLATFORM_ANDROID
64 #include <linux/tcp.h>
65 #include <sys/endian.h>
68 #include <mono/metadata/mono-debug.h>
69 #include <mono/metadata/mono-debug-debugger.h>
70 #include <mono/metadata/debug-mono-symfile.h>
71 #include <mono/metadata/gc-internal.h>
72 #include <mono/metadata/threads-types.h>
73 #include <mono/metadata/socket-io.h>
74 #include <mono/metadata/assembly.h>
75 #include <mono/utils/mono-semaphore.h>
76 #include <mono/utils/mono-error-internals.h>
77 #include <mono/utils/mono-stack-unwinding.h>
78 #include <mono/utils/mono-time.h>
79 #include <mono/utils/mono-threads.h>
80 #include "debugger-agent.h"
84 On iOS we can't use System.Environment.Exit () as it will do the wrong
87 #if !defined (TARGET_IOS)
88 #define TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
92 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
93 #define DISABLE_DEBUGGER_AGENT 1
96 #ifdef DISABLE_SOFT_DEBUG
97 #define DISABLE_DEBUGGER_AGENT 1
100 #ifndef DISABLE_DEBUGGER_AGENT
102 #include <mono/io-layer/mono-mutex.h>
104 /* Definitions to make backporting to 2.6 easier */
105 //#define MonoInternalThread MonoThread
106 //#define mono_thread_internal_current mono_thread_current
107 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
129 guint32 il_offset, native_offset;
133 * If method is gshared, this is the actual instance, otherwise this is equal to
136 MonoMethod *actual_method;
138 * This is the method which is visible to debugger clients. Same as method,
139 * except for native-to-managed wrappers.
141 MonoMethod *api_method;
143 MonoDebugMethodJitInfo *jit;
146 mgreg_t *reg_locations [MONO_MAX_IREGS];
148 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
149 * the frame can become invalid.
154 typedef struct _InvokeData InvokeData;
162 /* This is the context which needs to be restored after the invoke */
166 * If this is set, invoke this method with the arguments given by ARGS.
170 guint32 suspend_count;
173 InvokeData *last_invoke;
177 MonoThreadUnwindState context;
179 /* This is computed on demand when it is requested using the wire protocol */
180 /* It is freed up when the thread is resumed */
184 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
187 gboolean frames_up_to_date;
189 * Points to data about a pending invoke which needs to be executed after the thread
192 InvokeData *pending_invoke;
194 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
199 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
200 * within a finite amount of time.
204 * Set to TRUE if this thread is suspended in suspend_current ().
206 gboolean really_suspended;
207 /* Used to pass the context to the breakpoint/single step handler */
208 MonoContext handler_ctx;
209 /* Whenever thread_stop () was called for this thread */
212 /* Number of thread interruptions not yet processed */
213 gint32 interrupt_count;
215 /* Whenever to disable breakpoints (used during invokes) */
216 gboolean disable_breakpoints;
219 * Number of times this thread has been resumed using resume_thread ().
221 guint32 resume_count;
223 MonoInternalThread *thread;
226 * Information about the frame which transitioned to native code for running
229 StackFrameInfo async_last_frame;
232 * The context where the stack walk can be started for running threads.
234 MonoThreadUnwindState async_state;
237 * The context used for filter clauses
239 MonoThreadUnwindState filter_state;
242 * The callee address of the last mono_runtime_invoke call
244 gpointer invoke_addr;
246 gboolean abort_requested;
249 * The current mono_runtime_invoke invocation.
254 * The context where single stepping should resume while the thread is suspended because
255 * of an EXCEPTION event.
257 MonoContext catch_ctx;
259 gboolean has_catch_ctx;
262 * The context which needs to be restored after handling a single step/breakpoint
263 * event. This is the same as the ctx at step/breakpoint site, but includes changes
264 * to caller saved registers done by set_var ().
266 MonoContext restore_ctx;
271 void (*connect) (const char *address);
272 void (*close1) (void);
273 void (*close2) (void);
274 gboolean (*send) (void *buf, int len);
275 int (*recv) (void *buf, int len);
279 * Wire Protocol definitions
282 #define HEADER_LENGTH 11
284 #define MAJOR_VERSION 2
285 #define MINOR_VERSION 22
289 CMD_SET_OBJECT_REF = 9,
290 CMD_SET_STRING_REF = 10,
292 CMD_SET_ARRAY_REF = 13,
293 CMD_SET_EVENT_REQUEST = 15,
294 CMD_SET_STACK_FRAME = 16,
295 CMD_SET_APPDOMAIN = 20,
296 CMD_SET_ASSEMBLY = 21,
304 EVENT_KIND_VM_START = 0,
305 EVENT_KIND_VM_DEATH = 1,
306 EVENT_KIND_THREAD_START = 2,
307 EVENT_KIND_THREAD_DEATH = 3,
308 EVENT_KIND_APPDOMAIN_CREATE = 4,
309 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
310 EVENT_KIND_METHOD_ENTRY = 6,
311 EVENT_KIND_METHOD_EXIT = 7,
312 EVENT_KIND_ASSEMBLY_LOAD = 8,
313 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
314 EVENT_KIND_BREAKPOINT = 10,
315 EVENT_KIND_STEP = 11,
316 EVENT_KIND_TYPE_LOAD = 12,
317 EVENT_KIND_EXCEPTION = 13,
318 EVENT_KIND_KEEPALIVE = 14,
319 EVENT_KIND_USER_BREAK = 15,
320 EVENT_KIND_USER_LOG = 16
324 SUSPEND_POLICY_NONE = 0,
325 SUSPEND_POLICY_EVENT_THREAD = 1,
326 SUSPEND_POLICY_ALL = 2
331 ERR_INVALID_OBJECT = 20,
332 ERR_INVALID_FIELDID = 25,
333 ERR_INVALID_FRAMEID = 30,
334 ERR_NOT_IMPLEMENTED = 100,
335 ERR_NOT_SUSPENDED = 101,
336 ERR_INVALID_ARGUMENT = 102,
338 ERR_NO_INVOCATION = 104,
339 ERR_ABSENT_INFORMATION = 105,
340 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
341 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
346 MOD_KIND_THREAD_ONLY = 3,
347 MOD_KIND_LOCATION_ONLY = 7,
348 MOD_KIND_EXCEPTION_ONLY = 8,
350 MOD_KIND_ASSEMBLY_ONLY = 11,
351 MOD_KIND_SOURCE_FILE_ONLY = 12,
352 MOD_KIND_TYPE_NAME_ONLY = 13
367 STEP_FILTER_NONE = 0,
368 STEP_FILTER_STATIC_CTOR = 1,
369 STEP_FILTER_DEBUGGER_HIDDEN = 2
373 TOKEN_TYPE_STRING = 0,
375 TOKEN_TYPE_FIELD = 2,
376 TOKEN_TYPE_METHOD = 3,
377 TOKEN_TYPE_UNKNOWN = 4
381 VALUE_TYPE_ID_NULL = 0xf0,
382 VALUE_TYPE_ID_TYPE = 0xf1
386 FRAME_FLAG_DEBUGGER_INVOKE = 1,
387 FRAME_FLAG_NATIVE_TRANSITION = 2
391 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
392 INVOKE_FLAG_SINGLE_THREADED = 2
396 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
397 } BindingFlagsExtensions;
401 CMD_VM_ALL_THREADS = 2,
406 CMD_VM_INVOKE_METHOD = 7,
407 CMD_VM_SET_PROTOCOL_VERSION = 8,
408 CMD_VM_ABORT_INVOKE = 9,
409 CMD_VM_SET_KEEPALIVE = 10,
410 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
411 CMD_VM_GET_TYPES = 12,
412 CMD_VM_INVOKE_METHODS = 13
416 CMD_THREAD_GET_FRAME_INFO = 1,
417 CMD_THREAD_GET_NAME = 2,
418 CMD_THREAD_GET_STATE = 3,
419 CMD_THREAD_GET_INFO = 4,
420 CMD_THREAD_GET_ID = 5,
421 CMD_THREAD_GET_TID = 6
425 CMD_EVENT_REQUEST_SET = 1,
426 CMD_EVENT_REQUEST_CLEAR = 2,
427 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
435 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
436 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
437 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
438 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
439 CMD_APPDOMAIN_CREATE_STRING = 5,
440 CMD_APPDOMAIN_GET_CORLIB = 6,
441 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
445 CMD_ASSEMBLY_GET_LOCATION = 1,
446 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
447 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
448 CMD_ASSEMBLY_GET_OBJECT = 4,
449 CMD_ASSEMBLY_GET_TYPE = 5,
450 CMD_ASSEMBLY_GET_NAME = 6
454 CMD_MODULE_GET_INFO = 1,
458 CMD_METHOD_GET_NAME = 1,
459 CMD_METHOD_GET_DECLARING_TYPE = 2,
460 CMD_METHOD_GET_DEBUG_INFO = 3,
461 CMD_METHOD_GET_PARAM_INFO = 4,
462 CMD_METHOD_GET_LOCALS_INFO = 5,
463 CMD_METHOD_GET_INFO = 6,
464 CMD_METHOD_GET_BODY = 7,
465 CMD_METHOD_RESOLVE_TOKEN = 8,
466 CMD_METHOD_GET_CATTRS = 9,
470 CMD_TYPE_GET_INFO = 1,
471 CMD_TYPE_GET_METHODS = 2,
472 CMD_TYPE_GET_FIELDS = 3,
473 CMD_TYPE_GET_VALUES = 4,
474 CMD_TYPE_GET_OBJECT = 5,
475 CMD_TYPE_GET_SOURCE_FILES = 6,
476 CMD_TYPE_SET_VALUES = 7,
477 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
478 CMD_TYPE_GET_PROPERTIES = 9,
479 CMD_TYPE_GET_CATTRS = 10,
480 CMD_TYPE_GET_FIELD_CATTRS = 11,
481 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
482 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
483 CMD_TYPE_GET_VALUES_2 = 14,
484 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
485 CMD_TYPE_GET_INTERFACES = 16,
486 CMD_TYPE_GET_INTERFACE_MAP = 17,
490 CMD_STACK_FRAME_GET_VALUES = 1,
491 CMD_STACK_FRAME_GET_THIS = 2,
492 CMD_STACK_FRAME_SET_VALUES = 3
496 CMD_ARRAY_REF_GET_LENGTH = 1,
497 CMD_ARRAY_REF_GET_VALUES = 2,
498 CMD_ARRAY_REF_SET_VALUES = 3,
502 CMD_STRING_REF_GET_VALUE = 1,
503 CMD_STRING_REF_GET_LENGTH = 2,
504 CMD_STRING_REF_GET_CHARS = 3
508 CMD_OBJECT_REF_GET_TYPE = 1,
509 CMD_OBJECT_REF_GET_VALUES = 2,
510 CMD_OBJECT_REF_IS_COLLECTED = 3,
511 CMD_OBJECT_REF_GET_ADDRESS = 4,
512 CMD_OBJECT_REF_GET_DOMAIN = 5,
513 CMD_OBJECT_REF_SET_VALUES = 6,
514 CMD_OBJECT_REF_GET_INFO = 7,
520 int count; /* For kind == MOD_KIND_COUNT */
521 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
522 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
523 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
524 GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
525 GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
526 StepFilter filter; /* For kind == MOD_KIND_STEP */
528 gboolean caught, uncaught; /* For kind == MOD_KIND_EXCEPTION_ONLY */
537 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
541 * Describes a single step request.
545 MonoInternalThread *thread;
551 MonoMethod *last_method;
553 /* Whenever single stepping is performed using start/stop_single_stepping () */
555 /* The list of breakpoints used to implement step-over */
560 * Contains additional information for an event
563 /* For EVENT_KIND_EXCEPTION */
565 MonoContext catch_ctx;
567 /* For EVENT_KIND_USER_LOG */
569 char *category, *message;
570 /* For EVENT_KIND_TYPE_LOAD */
574 /* Dummy structure used for the profiler callbacks */
579 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
582 #define get_last_sock_error() WSAGetLastError()
583 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
584 #define MONO_EINTR WSAEINTR
586 #define get_last_sock_error() errno
587 #define MONO_EWOULDBLOCK EWOULDBLOCK
588 #define MONO_EINTR EINTR
591 #define CHECK_PROTOCOL_VERSION(major,minor) \
592 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
598 static AgentConfig agent_config;
601 * Whenever the agent is fully initialized.
602 * When using the onuncaught or onthrow options, only some parts of the agent are
603 * initialized on startup, and the full initialization which includes connection
604 * establishment and the startup of the agent thread is only done in response to
607 static gint32 inited;
609 #ifndef DISABLE_SOCKET_TRANSPORT
611 static int listen_fd;
614 static int packet_id = 0;
616 static int objref_id = 0;
618 static int event_request_id = 0;
620 static int frame_id = 0;
622 static GPtrArray *event_requests;
624 static MonoNativeTlsKey debugger_tls_id;
626 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
628 /* Maps MonoInternalThread -> DebuggerTlsData */
629 static MonoGHashTable *thread_to_tls;
631 /* Maps tid -> MonoInternalThread */
632 static MonoGHashTable *tid_to_thread;
634 /* Maps tid -> MonoThread (not MonoInternalThread) */
635 static MonoGHashTable *tid_to_thread_obj;
637 static gsize debugger_thread_id;
639 static HANDLE debugger_thread_handle;
641 static int log_level;
643 static gboolean embedding;
645 static FILE *log_file;
647 /* Assemblies whose assembly load event has no been sent yet */
648 static GPtrArray *pending_assembly_loads;
650 /* Whenever the debugger thread has exited */
651 static gboolean debugger_thread_exited;
653 /* Cond variable used to wait for debugger_thread_exited becoming true */
654 static mono_cond_t debugger_thread_exited_cond;
656 /* Mutex for the cond var above */
657 static mono_mutex_t debugger_thread_exited_mutex;
659 static DebuggerProfiler debugger_profiler;
661 /* The single step request instance */
662 static SingleStepReq *ss_req = NULL;
663 static gpointer ss_invoke_addr = NULL;
665 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
666 /* Number of single stepping operations in progress */
670 /* The protocol version of the client */
671 static int major_version, minor_version;
673 /* Whenever the variables above are set by the client */
674 static gboolean protocol_version_set;
676 /* A hash table containing all active domains */
677 static GHashTable *domains;
679 /* The number of times the runtime is suspended */
680 static gint32 suspend_count;
682 static void transport_init (void);
683 static void transport_connect (const char *address);
684 static gboolean transport_handshake (void);
685 static void register_transport (DebuggerTransport *trans);
687 static guint32 WINAPI debugger_thread (void *arg);
689 static void runtime_initialized (MonoProfiler *prof);
691 static void runtime_shutdown (MonoProfiler *prof);
693 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
695 static void thread_end (MonoProfiler *prof, uintptr_t tid);
697 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
699 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
701 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
703 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
705 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
707 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
709 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
711 static void emit_assembly_load (gpointer assembly, gpointer user_data);
713 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
715 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
717 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
719 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
721 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
723 static void start_single_stepping (void);
725 static void stop_single_stepping (void);
727 static void suspend_current (void);
729 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
731 static void clear_types_for_assembly (MonoAssembly *assembly);
733 static void clear_breakpoints_for_domain (MonoDomain *domain);
735 static void process_profiler_event (EventKind event, gpointer arg);
737 /* Submodule init/cleanup */
738 static void breakpoints_init (void);
739 static void breakpoints_cleanup (void);
741 static void objrefs_init (void);
742 static void objrefs_cleanup (void);
744 static void ids_init (void);
745 static void ids_cleanup (void);
747 static void suspend_init (void);
749 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch);
750 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
751 static void ss_destroy (SingleStepReq *req);
753 static void start_debugger_thread (void);
754 static void stop_debugger_thread (void);
756 static void finish_agent_init (gboolean on_startup);
758 static void process_profiler_event (EventKind event, gpointer arg);
760 static void invalidate_frames (DebuggerTlsData *tls);
762 #ifndef DISABLE_SOCKET_TRANSPORT
764 register_socket_transport (void);
768 parse_address (char *address, char **host, int *port)
770 char *pos = strchr (address, ':');
772 if (pos == NULL || pos == address)
775 *host = g_malloc (pos - address + 1);
776 strncpy (*host, address, pos - address);
777 (*host) [pos - address] = '\0';
779 *port = atoi (pos + 1);
787 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
788 fprintf (stderr, "Available options:\n");
789 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
790 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
791 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
792 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
793 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
794 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
795 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
796 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
797 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
801 parse_flag (const char *option, char *flag)
803 if (!strcmp (flag, "y"))
805 else if (!strcmp (flag, "n"))
808 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
815 mono_debugger_agent_parse_options (char *options)
822 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
823 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
827 extra = getenv ("MONO_SDB_ENV_OPTIONS");
829 options = g_strdup_printf ("%s,%s", options, extra);
831 agent_config.enabled = TRUE;
832 agent_config.suspend = TRUE;
833 agent_config.server = FALSE;
834 agent_config.defer = FALSE;
835 agent_config.address = NULL;
837 args = g_strsplit (options, ",", -1);
838 for (ptr = args; ptr && *ptr; ptr ++) {
841 if (strncmp (arg, "transport=", 10) == 0) {
842 agent_config.transport = g_strdup (arg + 10);
843 } else if (strncmp (arg, "address=", 8) == 0) {
844 agent_config.address = g_strdup (arg + 8);
845 } else if (strncmp (arg, "loglevel=", 9) == 0) {
846 agent_config.log_level = atoi (arg + 9);
847 } else if (strncmp (arg, "logfile=", 8) == 0) {
848 agent_config.log_file = g_strdup (arg + 8);
849 } else if (strncmp (arg, "suspend=", 8) == 0) {
850 agent_config.suspend = parse_flag ("suspend", arg + 8);
851 } else if (strncmp (arg, "server=", 7) == 0) {
852 agent_config.server = parse_flag ("server", arg + 7);
853 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
854 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
855 } else if (strncmp (arg, "onthrow=", 8) == 0) {
856 /* We support multiple onthrow= options */
857 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
858 } else if (strncmp (arg, "onthrow", 7) == 0) {
859 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
860 } else if (strncmp (arg, "help", 4) == 0) {
863 } else if (strncmp (arg, "timeout=", 8) == 0) {
864 agent_config.timeout = atoi (arg + 8);
865 } else if (strncmp (arg, "launch=", 7) == 0) {
866 agent_config.launch = g_strdup (arg + 7);
867 } else if (strncmp (arg, "embedding=", 10) == 0) {
868 agent_config.embedding = atoi (arg + 10) == 1;
869 } else if (strncmp (arg, "keepalive=", 10) == 0) {
870 agent_config.keepalive = atoi (arg + 10);
877 if (agent_config.server && !agent_config.suspend) {
878 /* Waiting for deferred attachment */
879 agent_config.defer = TRUE;
880 if (agent_config.address == NULL) {
881 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (GetCurrentProcessId () % 1000));
885 //agent_config.log_level = 0;
887 if (agent_config.transport == NULL) {
888 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
892 if (agent_config.address == NULL && !agent_config.server) {
893 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
898 if (!strcmp (agent_config.transport, "dt_socket")) {
899 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
900 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
907 mono_debugger_agent_init (void)
909 if (!agent_config.enabled)
914 /* Need to know whenever a thread has acquired the loader mutex */
915 mono_loader_lock_track_ownership (TRUE);
917 event_requests = g_ptr_array_new ();
919 mono_mutex_init (&debugger_thread_exited_mutex, NULL);
920 mono_cond_init (&debugger_thread_exited_cond, NULL);
922 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
923 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
924 mono_profiler_install_runtime_initialized (runtime_initialized);
925 mono_profiler_install_appdomain (NULL, appdomain_load, NULL, appdomain_unload);
926 mono_profiler_install_thread (thread_startup, thread_end);
927 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
928 mono_profiler_install_jit_end (jit_end);
929 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
931 mono_native_tls_alloc (&debugger_tls_id, NULL);
933 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
934 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls);
936 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
937 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread);
939 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
940 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj);
942 pending_assembly_loads = g_ptr_array_new ();
943 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
945 log_level = agent_config.log_level;
947 embedding = agent_config.embedding;
950 if (agent_config.log_file) {
951 log_file = fopen (agent_config.log_file, "w+");
953 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
965 mini_get_debug_options ()->gen_seq_points = TRUE;
967 * This is needed because currently we don't handle liveness info.
969 mini_get_debug_options ()->mdb_optimizations = TRUE;
971 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
972 /* This is needed because we can't set local variables in registers yet */
973 mono_disable_optimizations (MONO_OPT_LINEARS);
977 * The stack walk done from thread_interrupt () needs to be signal safe, but it
978 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
979 * safe (#3411). So load AOT info eagerly when the debugger is running as a
982 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
984 if (!agent_config.onuncaught && !agent_config.onthrow)
985 finish_agent_init (TRUE);
991 * Finish the initialization of the agent. This involves connecting the transport
992 * and starting the agent thread. This is either done at startup, or
993 * in response to some event like an unhandled exception.
996 finish_agent_init (gboolean on_startup)
1000 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
1003 if (agent_config.launch) {
1006 // FIXME: Generated address
1007 // FIXME: Races with transport_connect ()
1009 argv [0] = agent_config.launch;
1010 argv [1] = agent_config.transport;
1011 argv [2] = agent_config.address;
1014 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1016 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1021 transport_connect (agent_config.address);
1024 /* Do some which is usually done after sending the VMStart () event */
1025 vm_start_event_sent = TRUE;
1026 start_debugger_thread ();
1031 mono_debugger_agent_cleanup (void)
1036 stop_debugger_thread ();
1038 breakpoints_cleanup ();
1042 mono_mutex_destroy (&debugger_thread_exited_mutex);
1043 mono_cond_destroy (&debugger_thread_exited_cond);
1050 #ifndef DISABLE_SOCKET_TRANSPORT
1055 * recv() + handle incomplete reads and EINTR
1058 socket_transport_recv (void *buf, int len)
1064 static gint32 last_keepalive;
1069 res = recv (fd, (char *) buf + total, len - total, flags);
1072 if (agent_config.keepalive) {
1073 gboolean need_keepalive = FALSE;
1074 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1075 need_keepalive = TRUE;
1076 } else if (res == -1) {
1077 /* This could happen if recv () is interrupted repeatedly */
1078 msecs = mono_msec_ticks ();
1079 if (msecs - last_keepalive >= agent_config.keepalive) {
1080 need_keepalive = TRUE;
1081 last_keepalive = msecs;
1084 if (need_keepalive) {
1085 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1089 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1094 #define HAVE_GETADDRINFO 1
1098 set_keepalive (void)
1103 if (!agent_config.keepalive || !conn_fd)
1106 tv.tv_sec = agent_config.keepalive / 1000;
1107 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1109 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1110 g_assert (result >= 0);
1114 socket_transport_accept (int socket_fd)
1116 conn_fd = accept (socket_fd, NULL, NULL);
1117 if (conn_fd == -1) {
1118 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1120 DEBUG (1, fprintf (log_file, "Accepted connection from client, connection fd=%d.\n", conn_fd));
1127 socket_transport_send (void *data, int len)
1132 res = send (conn_fd, data, len, 0);
1133 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1141 * socket_transport_connect:
1143 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1146 socket_transport_connect (const char *address)
1148 #ifdef HAVE_GETADDRINFO
1149 struct addrinfo hints;
1150 struct addrinfo *result, *rp;
1152 struct hostent *result;
1154 int sfd = -1, s, res;
1155 char port_string [128];
1159 if (agent_config.address) {
1160 res = parse_address (agent_config.address, &host, &port);
1161 g_assert (res == 0);
1171 sprintf (port_string, "%d", port);
1173 mono_network_init ();
1175 /* Obtain address(es) matching host/port */
1176 #ifdef HAVE_GETADDRINFO
1177 memset (&hints, 0, sizeof (struct addrinfo));
1178 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
1179 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
1181 hints.ai_protocol = 0; /* Any protocol */
1183 s = getaddrinfo (host, port_string, &hints, &result);
1185 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %s\n", host, port, gai_strerror (s));
1189 /* The PS3 doesn't even have _r or hstrerror () */
1190 result = gethostbyname (host);
1192 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, h_errno);
1197 if (agent_config.server) {
1198 #ifdef HAVE_GETADDRINFO
1199 /* Wait for a connection */
1201 struct sockaddr_in addr;
1204 /* No address, generate one */
1205 sfd = socket (AF_INET, SOCK_STREAM, 0);
1208 /* This will bind the socket to a random port */
1209 res = listen (sfd, 16);
1211 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1216 addrlen = sizeof (addr);
1217 memset (&addr, 0, sizeof (addr));
1218 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1219 g_assert (res == 0);
1221 host = (char*)"127.0.0.1";
1222 port = ntohs (addr.sin_port);
1224 /* Emit the address to stdout */
1225 /* FIXME: Should print another interface, not localhost */
1226 printf ("%s:%d\n", host, port);
1228 /* Listen on the provided address */
1229 for (rp = result; rp != NULL; rp = rp->ai_next) {
1232 sfd = socket (rp->ai_family, rp->ai_socktype,
1237 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1240 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
1244 res = listen (sfd, 16);
1253 * this function is not present on win2000 which we still support, and the
1254 * workaround described here:
1255 * http://msdn.microsoft.com/en-us/library/ms737931(VS.85).aspx
1256 * only works with MSVC.
1258 #ifdef HAVE_GETADDRINFO
1259 freeaddrinfo (result);
1264 if (agent_config.defer)
1267 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
1269 if (agent_config.timeout) {
1274 tv.tv_usec = agent_config.timeout * 1000;
1276 FD_SET (sfd, &readfds);
1277 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1279 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1284 conn_fd = socket_transport_accept (sfd);
1288 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
1291 #endif /* HAVE_GETADDRINFO */
1293 /* Connect to the specified address */
1294 #ifdef HAVE_GETADDRINFO
1295 /* FIXME: Respect the timeout */
1296 for (rp = result; rp != NULL; rp = rp->ai_next) {
1297 sfd = socket (rp->ai_family, rp->ai_socktype,
1302 if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
1303 break; /* Success */
1309 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1313 sfd = socket (result->h_addrtype, SOCK_STREAM, 0);
1315 g_assert_not_reached ();
1316 res = connect (sfd, (void*)result->h_addr_list [0], result->h_length);
1318 g_assert_not_reached ();
1324 /* See the comment above */
1325 #ifdef HAVE_GETADDRINFO
1326 freeaddrinfo (result);
1331 if (!transport_handshake ())
1336 socket_transport_close1 (void)
1338 /* This will interrupt the agent thread */
1339 /* Close the read part only so it can still send back replies */
1340 /* Also shut down the connection listener so that we can exit normally */
1342 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1343 shutdown (conn_fd, SD_BOTH);
1344 shutdown (listen_fd, SD_BOTH);
1345 closesocket (listen_fd);
1347 shutdown (conn_fd, SHUT_RD);
1348 shutdown (listen_fd, SHUT_RDWR);
1354 socket_transport_close2 (void)
1357 shutdown (conn_fd, SD_BOTH);
1359 shutdown (conn_fd, SHUT_RDWR);
1364 register_socket_transport (void)
1366 DebuggerTransport trans;
1368 trans.name = "dt_socket";
1369 trans.connect = socket_transport_connect;
1370 trans.close1 = socket_transport_close1;
1371 trans.close2 = socket_transport_close2;
1372 trans.send = socket_transport_send;
1373 trans.recv = socket_transport_recv;
1375 register_transport (&trans);
1378 #endif /* DISABLE_SOCKET_TRANSPORT */
1384 #define MAX_TRANSPORTS 16
1386 static DebuggerTransport *transport;
1388 static DebuggerTransport transports [MAX_TRANSPORTS];
1389 static int ntransports;
1392 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1395 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1397 register_transport (trans);
1401 register_transport (DebuggerTransport *trans)
1403 g_assert (ntransports < MAX_TRANSPORTS);
1405 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1410 transport_init (void)
1414 #ifndef DISABLE_SOCKET_TRANSPORT
1415 register_socket_transport ();
1418 for (i = 0; i < ntransports; ++i) {
1419 if (!strcmp (agent_config.transport, transports [i].name))
1422 if (i == ntransports) {
1423 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1424 for (i = 0; i < ntransports; ++i)
1425 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1426 fprintf (stderr, "\n");
1429 transport = &transports [i];
1433 transport_connect (const char *address)
1435 transport->connect (address);
1439 transport_close1 (void)
1441 transport->close1 ();
1445 transport_close2 (void)
1447 transport->close2 ();
1451 transport_send (void *buf, int len)
1453 return transport->send (buf, len);
1457 transport_recv (void *buf, int len)
1459 return transport->recv (buf, len);
1463 mono_debugger_agent_transport_handshake (void)
1465 return transport_handshake ();
1469 transport_handshake (void)
1471 char handshake_msg [128];
1475 disconnected = TRUE;
1477 /* Write handshake message */
1478 sprintf (handshake_msg, "DWP-Handshake");
1480 res = transport_send (handshake_msg, strlen (handshake_msg));
1481 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1482 g_assert (res != -1);
1485 res = transport_recv (buf, strlen (handshake_msg));
1486 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg) != 0))) {
1487 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1492 * To support older clients, the client sends its protocol version after connecting
1493 * using a command. Until that is received, default to our protocol version.
1495 major_version = MAJOR_VERSION;
1496 minor_version = MINOR_VERSION;
1497 protocol_version_set = FALSE;
1499 #ifndef DISABLE_SOCKET_TRANSPORT
1500 // FIXME: Move this somewhere else
1502 * Set TCP_NODELAY on the socket so the client receives events/command
1503 * results immediately.
1507 int result = setsockopt (conn_fd,
1512 g_assert (result >= 0);
1518 disconnected = FALSE;
1523 stop_debugger_thread (void)
1528 transport_close1 ();
1531 * Wait for the thread to exit.
1533 * If we continue with the shutdown without waiting for it, then the client might
1534 * not receive an answer to its last command like a resume.
1535 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
1538 //WaitForSingleObject (debugger_thread_handle, INFINITE);
1539 if (GetCurrentThreadId () != debugger_thread_id) {
1541 mono_mutex_lock (&debugger_thread_exited_mutex);
1542 if (!debugger_thread_exited) {
1544 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
1545 mono_mutex_unlock (&debugger_thread_exited_mutex);
1547 mono_mutex_lock (&debugger_thread_exited_mutex);
1550 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1553 mono_mutex_unlock (&debugger_thread_exited_mutex);
1554 } while (!debugger_thread_exited);
1557 transport_close2 ();
1561 start_debugger_thread (void)
1565 debugger_thread_handle = mono_create_thread (NULL, 0, debugger_thread, NULL, 0, &tid);
1566 g_assert (debugger_thread_handle);
1570 * Functions to decode protocol data
1574 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1577 g_assert (*endbuf <= limit);
1582 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1585 g_assert (*endbuf <= limit);
1587 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1590 static inline gint64
1591 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1593 guint32 high = decode_int (buf, &buf, limit);
1594 guint32 low = decode_int (buf, &buf, limit);
1598 return ((((guint64)high) << 32) | ((guint64)low));
1602 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1604 return decode_int (buf, endbuf, limit);
1608 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1610 int len = decode_int (buf, &buf, limit);
1618 s = g_malloc (len + 1);
1621 memcpy (s, buf, len);
1630 * Functions to encode protocol data
1634 guint8 *buf, *p, *end;
1638 buffer_init (Buffer *buf, int size)
1640 buf->buf = g_malloc (size);
1642 buf->end = buf->buf + size;
1646 buffer_make_room (Buffer *buf, int size)
1648 if (buf->end - buf->p < size) {
1649 int new_size = buf->end - buf->buf + size + 32;
1650 guint8 *p = g_realloc (buf->buf, new_size);
1651 size = buf->p - buf->buf;
1654 buf->end = buf->buf + new_size;
1659 buffer_add_byte (Buffer *buf, guint8 val)
1661 buffer_make_room (buf, 1);
1667 buffer_add_short (Buffer *buf, guint32 val)
1669 buffer_make_room (buf, 2);
1670 buf->p [0] = (val >> 8) & 0xff;
1671 buf->p [1] = (val >> 0) & 0xff;
1676 buffer_add_int (Buffer *buf, guint32 val)
1678 buffer_make_room (buf, 4);
1679 buf->p [0] = (val >> 24) & 0xff;
1680 buf->p [1] = (val >> 16) & 0xff;
1681 buf->p [2] = (val >> 8) & 0xff;
1682 buf->p [3] = (val >> 0) & 0xff;
1687 buffer_add_long (Buffer *buf, guint64 l)
1689 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1690 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1694 buffer_add_id (Buffer *buf, int id)
1696 buffer_add_int (buf, (guint64)id);
1700 buffer_add_data (Buffer *buf, guint8 *data, int len)
1702 buffer_make_room (buf, len);
1703 memcpy (buf->p, data, len);
1708 buffer_add_string (Buffer *buf, const char *str)
1713 buffer_add_int (buf, 0);
1716 buffer_add_int (buf, len);
1717 buffer_add_data (buf, (guint8*)str, len);
1722 buffer_free (Buffer *buf)
1728 send_packet (int command_set, int command, Buffer *data)
1734 id = InterlockedIncrement (&packet_id);
1736 len = data->p - data->buf + 11;
1737 buffer_init (&buf, len);
1738 buffer_add_int (&buf, len);
1739 buffer_add_int (&buf, id);
1740 buffer_add_byte (&buf, 0); /* flags */
1741 buffer_add_byte (&buf, command_set);
1742 buffer_add_byte (&buf, command);
1743 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1745 res = transport_send (buf.buf, len);
1753 send_reply_packet (int id, int error, Buffer *data)
1759 len = data->p - data->buf + 11;
1760 buffer_init (&buf, len);
1761 buffer_add_int (&buf, len);
1762 buffer_add_int (&buf, id);
1763 buffer_add_byte (&buf, 0x80); /* flags */
1764 buffer_add_byte (&buf, (error >> 8) & 0xff);
1765 buffer_add_byte (&buf, error);
1766 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1768 res = transport_send (buf.buf, len);
1780 * Represents an object accessible by the debugger client.
1783 /* Unique id used in the wire protocol to refer to objects */
1786 * A weakref gc handle pointing to the object. The gc handle is used to
1787 * detect if the object was garbage collected.
1792 /* Maps objid -> ObjRef */
1793 static GHashTable *objrefs;
1796 free_objref (gpointer value)
1800 mono_gchandle_free (o->handle);
1808 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1812 objrefs_cleanup (void)
1814 g_hash_table_destroy (objrefs);
1818 static GHashTable *obj_to_objref;
1819 static MonoGHashTable *suspended_objs;
1822 * Return an ObjRef for OBJ.
1825 get_objref (MonoObject *obj)
1828 GSList *reflist = NULL, *l;
1834 mono_loader_lock ();
1836 if (!obj_to_objref) {
1837 obj_to_objref = g_hash_table_new (NULL, NULL);
1838 suspended_objs = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
1839 MONO_GC_REGISTER_ROOT_FIXED (suspended_objs);
1842 if (suspend_count) {
1844 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1846 mono_g_hash_table_insert (suspended_objs, obj, NULL);
1849 /* FIXME: The tables can grow indefinitely */
1851 if (mono_gc_is_moving ()) {
1853 * Objects can move, so use a hash table mapping hash codes to lists of
1854 * ObjRef structures.
1856 hash = mono_object_hash (obj);
1858 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1859 for (l = reflist; l; l = l->next) {
1861 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1862 mono_loader_unlock ();
1867 /* Use a hash table with masked pointers to internalize object references */
1868 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1869 /* ref might refer to a different object with the same addr which was GCd */
1870 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1871 mono_loader_unlock ();
1876 ref = g_new0 (ObjRef, 1);
1877 ref->id = InterlockedIncrement (&objref_id);
1878 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1880 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
1882 if (mono_gc_is_moving ()) {
1883 reflist = g_slist_append (reflist, ref);
1884 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
1886 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
1889 mono_loader_unlock ();
1895 true_pred (gpointer key, gpointer value, gpointer user_data)
1901 clear_suspended_objs (void)
1903 mono_loader_lock ();
1904 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
1905 mono_loader_unlock ();
1909 get_objid (MonoObject *obj)
1911 return get_objref (obj)->id;
1915 * Set OBJ to the object identified by OBJID.
1916 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
1920 get_object_allow_null (int objid, MonoObject **obj)
1930 return ERR_INVALID_OBJECT;
1932 mono_loader_lock ();
1934 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
1937 *obj = mono_gchandle_get_target (ref->handle);
1938 mono_loader_unlock ();
1940 return ERR_INVALID_OBJECT;
1943 mono_loader_unlock ();
1944 return ERR_INVALID_OBJECT;
1949 get_object (int objid, MonoObject **obj)
1951 int err = get_object_allow_null (objid, obj);
1956 return ERR_INVALID_OBJECT;
1961 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
1963 return decode_id (buf, endbuf, limit);
1967 buffer_add_objid (Buffer *buf, MonoObject *o)
1969 buffer_add_id (buf, get_objid (o));
1988 * Represents a runtime structure accessible to the debugger client
1991 /* Unique id used in the wire protocol */
1993 /* Domain of the runtime structure, NULL if the domain was unloaded */
2000 MonoAssembly *assembly;
2001 MonoClassField *field;
2003 MonoProperty *property;
2008 /* Maps runtime structure -> Id */
2009 GHashTable *val_to_id [ID_NUM];
2010 /* Classes whose class load event has been sent */
2011 GHashTable *loaded_classes;
2012 /* Maps MonoClass->GPtrArray of file names */
2013 GHashTable *source_files;
2014 /* Maps source file basename -> GSList of classes */
2015 GHashTable *source_file_to_class;
2016 /* Same with ignore-case */
2017 GHashTable *source_file_to_class_ignorecase;
2021 static GPtrArray *ids [ID_NUM];
2028 for (i = 0; i < ID_NUM; ++i)
2029 ids [i] = g_ptr_array_new ();
2037 for (i = 0; i < ID_NUM; ++i) {
2039 for (j = 0; j < ids [i]->len; ++j)
2040 g_free (g_ptr_array_index (ids [i], j));
2041 g_ptr_array_free (ids [i], TRUE);
2048 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2050 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
2052 GHashTableIter iter;
2053 GPtrArray *file_names;
2058 for (i = 0; i < ID_NUM; ++i)
2059 if (info->val_to_id [i])
2060 g_hash_table_destroy (info->val_to_id [i]);
2061 g_hash_table_destroy (info->loaded_classes);
2063 g_hash_table_iter_init (&iter, info->source_files);
2064 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2065 for (i = 0; i < file_names->len; ++i)
2066 g_free (g_ptr_array_index (file_names, i));
2067 g_ptr_array_free (file_names, TRUE);
2070 g_hash_table_iter_init (&iter, info->source_file_to_class);
2071 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2076 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2077 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2085 domain_jit_info (domain)->agent_info = NULL;
2087 /* Clear ids referencing structures in the domain */
2088 for (i = 0; i < ID_NUM; ++i) {
2090 for (j = 0; j < ids [i]->len; ++j) {
2091 Id *id = g_ptr_array_index (ids [i], j);
2092 if (id->domain == domain)
2098 mono_loader_lock ();
2099 g_hash_table_remove (domains, domain);
2100 mono_loader_unlock ();
2103 static AgentDomainInfo*
2104 get_agent_domain_info (MonoDomain *domain)
2106 AgentDomainInfo *info = NULL;
2108 mono_domain_lock (domain);
2110 info = domain_jit_info (domain)->agent_info;
2112 info = domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
2113 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2114 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2115 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2116 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2119 mono_domain_unlock (domain);
2125 get_id (MonoDomain *domain, IdType type, gpointer val)
2128 AgentDomainInfo *info;
2133 mono_loader_lock ();
2135 mono_domain_lock (domain);
2137 info = get_agent_domain_info (domain);
2139 if (info->val_to_id [type] == NULL)
2140 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2142 id = g_hash_table_lookup (info->val_to_id [type], val);
2144 mono_domain_unlock (domain);
2145 mono_loader_unlock ();
2149 id = g_new0 (Id, 1);
2151 id->id = ids [type]->len + 1;
2152 id->domain = domain;
2155 g_hash_table_insert (info->val_to_id [type], val, id);
2157 mono_domain_unlock (domain);
2159 g_ptr_array_add (ids [type], id);
2161 mono_loader_unlock ();
2166 static inline gpointer
2167 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
2171 int id = decode_id (buf, endbuf, limit);
2180 // FIXME: error handling
2181 mono_loader_lock ();
2182 g_assert (id > 0 && id <= ids [type]->len);
2184 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2185 mono_loader_unlock ();
2187 if (res->domain == NULL) {
2188 *err = ERR_UNLOADED;
2193 *domain = res->domain;
2195 return res->data.val;
2199 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2201 buffer_add_id (buf, get_id (domain, type, val));
2204 static inline MonoClass*
2205 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2207 return decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2210 static inline MonoAssembly*
2211 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2213 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2216 static inline MonoImage*
2217 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2219 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2222 static inline MonoMethod*
2223 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2225 return decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2228 static inline MonoClassField*
2229 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2231 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2234 static inline MonoDomain*
2235 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2237 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2240 static inline MonoProperty*
2241 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2243 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2247 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2249 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2253 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2255 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2259 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2261 buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2265 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2267 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2271 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2273 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2277 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2279 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2283 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2285 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2288 static void invoke_method (void);
2295 * save_thread_context:
2297 * Set CTX as the current threads context which is used for computing stack traces.
2298 * This function is signal-safe.
2301 save_thread_context (MonoContext *ctx)
2303 DebuggerTlsData *tls;
2305 tls = mono_native_tls_get_value (debugger_tls_id);
2309 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2311 mono_thread_state_init_from_current (&tls->context);
2314 /* Number of threads suspended */
2316 * If this is equal to the size of thread_to_tls, the runtime is considered
2319 static gint32 threads_suspend_count;
2321 static mono_mutex_t suspend_mutex;
2323 /* Cond variable used to wait for suspend_count becoming 0 */
2324 static mono_cond_t suspend_cond;
2326 /* Semaphore used to wait for a thread becoming suspended */
2327 static MonoSemType suspend_sem;
2332 mono_mutex_init (&suspend_mutex, NULL);
2333 mono_cond_init (&suspend_cond, NULL);
2334 MONO_SEM_INIT (&suspend_sem, 0);
2339 StackFrameInfo last_frame;
2340 gboolean last_frame_set;
2343 } GetLastFrameUserData;
2346 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2348 GetLastFrameUserData *data = user_data;
2350 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
2353 if (!data->last_frame_set) {
2354 /* Store the last frame */
2355 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2356 data->last_frame_set = TRUE;
2359 /* Store the context/lmf for the frame above the last frame */
2360 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2361 data->lmf = info->lmf;
2369 * Process interruption of a thread. If SIGCTX is set, process the current thread. If
2370 * INFO is set, process the thread described by INFO.
2371 * This should be signal safe.
2374 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, void *sigctx, MonoJitInfo *ji)
2378 MonoNativeThreadId tid;
2381 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2382 * guarantee the signal handler will be called that many times. Instead of tracking
2383 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2384 * has been requested that hasn't been handled yet, otherwise we can have threads
2385 * refuse to die when VM_EXIT is called
2387 #if defined(__APPLE__)
2388 if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
2392 * We use interrupt_count to determine whenever this interrupt should be processed
2393 * by us or the normal interrupt processing code in the signal handler.
2394 * There is no race here with notify_thread (), since the signal is sent after
2395 * incrementing interrupt_count.
2397 if (tls->interrupt_count == 0)
2400 InterlockedDecrement (&tls->interrupt_count);
2404 ip = mono_arch_ip_from_context (sigctx);
2406 ip = MONO_CONTEXT_GET_IP (&info->suspend_state.ctx);
2411 tid = mono_thread_info_get_tid (info);
2413 tid = (MonoNativeThreadId)GetCurrentThreadId ();
2415 // FIXME: Races when the thread leaves managed code before hitting a single step
2419 /* Running managed code, will be suspended by the single step code */
2420 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, ji->method->name, ip));
2424 * Running native code, will be suspended when it returns to/enters
2425 * managed code. Treat it as already suspended.
2426 * This might interrupt the code in process_single_step_inner (), we use the
2427 * tls->suspending flag to avoid races when that happens.
2429 if (!tls->suspended && !tls->suspending) {
2431 GetLastFrameUserData data;
2433 // FIXME: printf is not signal safe, but this is only used during
2434 // debugger debugging
2436 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip));
2437 //save_thread_context (&ctx);
2440 /* Already terminated */
2443 tls->context.valid = FALSE;
2446 * We are in a difficult position: we want to be able to provide stack
2447 * traces for this thread, but we can't use the current ctx+lmf, since
2448 * the thread is still running, so it might return to managed code,
2449 * making these invalid.
2450 * So we start a stack walk and save the first frame, along with the
2451 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2452 * suspended when it returns to managed code, so the parent's ctx should
2455 data.last_frame_set = FALSE;
2457 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
2459 * Don't pass MONO_UNWIND_ACTUAL_METHOD, its not signal safe, and
2460 * get_last_frame () doesn't need it, the last frame cannot be a ginst
2461 * since we are not in a JITted method.
2463 mono_walk_stack_with_ctx (get_last_frame, &ctx, MONO_UNWIND_NONE, &data);
2465 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, &info->suspend_state, MONO_UNWIND_SIGNAL_SAFE, &data);
2467 if (data.last_frame_set) {
2468 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2469 res = mono_thread_state_init_from_monoctx (&tls->async_state, &ctx);
2471 mono_thread_state_init_from_monoctx (&tls->context, &ctx);
2474 memcpy (&tls->async_state.ctx, &data.ctx, sizeof (MonoContext));
2475 tls->async_state.unwind_data [MONO_UNWIND_DATA_LMF] = data.lmf;
2476 tls->async_state.unwind_data [MONO_UNWIND_DATA_JIT_TLS] = tls->thread->jit_data;
2478 /* No managed frames */
2479 tls->async_state.valid = FALSE;
2481 mono_memory_barrier ();
2483 tls->suspended = TRUE;
2484 MONO_SEM_POST (&suspend_sem);
2491 * mono_debugger_agent_thread_interrupt:
2493 * Called by the abort signal handler.
2494 * Should be signal safe.
2497 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
2499 DebuggerTlsData *tls;
2504 tls = mono_native_tls_get_value (debugger_tls_id);
2506 DEBUG (1, fprintf (log_file, "[%p] Received interrupt with no TLS, continuing.\n", (gpointer)GetCurrentThreadId ()));
2510 return thread_interrupt (tls, NULL, sigctx, ji);
2514 static void CALLBACK notify_thread_apc (ULONG_PTR param)
2517 mono_debugger_agent_thread_interrupt (NULL, NULL);
2519 #endif /* HOST_WIN32 */
2522 * reset_native_thread_suspend_state:
2524 * Reset the suspended flag and state on native threads
2527 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2529 DebuggerTlsData *tls = value;
2531 if (!tls->really_suspended && tls->suspended) {
2532 tls->suspended = FALSE;
2534 * The thread might still be running if it was executing native code, so the state won't be invalided by
2535 * suspend_current ().
2537 tls->context.valid = FALSE;
2538 tls->async_state.valid = FALSE;
2539 invalidate_frames (tls);
2546 * Notify a thread that it needs to suspend.
2549 notify_thread (gpointer key, gpointer value, gpointer user_data)
2551 MonoInternalThread *thread = key;
2552 DebuggerTlsData *tls = value;
2553 gsize tid = thread->tid;
2556 if (GetCurrentThreadId () == tid || tls->terminated)
2559 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2562 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2563 * guarantee the signal handler will be called that many times. Instead of tracking
2564 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2565 * has been requested that hasn't been handled yet, otherwise we can have threads
2566 * refuse to die when VM_EXIT is called
2568 #if defined(__APPLE__)
2569 if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
2573 * Maybe we could use the normal interrupt infrastructure, but that does a lot
2574 * of things like breaking waits etc. which we don't want.
2576 InterlockedIncrement (&tls->interrupt_count);
2579 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2581 QueueUserAPC (notify_thread_apc, thread->handle, NULL);
2583 if (mono_thread_info_new_interrupt_enabled ()) {
2584 MonoThreadInfo *info;
2587 info = mono_thread_info_safe_suspend_sync ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE);
2589 DEBUG(1, fprintf (log_file, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2591 * Attached thread which died without detaching.
2593 tls->terminated = TRUE;
2595 ji = mono_jit_info_table_find (info->suspend_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], MONO_CONTEXT_GET_IP (&info->suspend_state.ctx));
2597 thread_interrupt (tls, info, NULL, ji);
2599 mono_thread_info_resume (mono_thread_info_get_tid (info));
2602 res = mono_thread_kill (thread, mono_thread_get_abort_signal ());
2604 DEBUG(1, fprintf (log_file, "[%p] mono_thread_kill () failed for %p: %d...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid, res));
2606 * Attached thread which died without detaching.
2608 tls->terminated = TRUE;
2615 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2617 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2620 if (mono_loader_lock_is_owned_by_self ()) {
2622 * Shortcut for the check in suspend_current (). This speeds up processing
2623 * when executing long running code inside the loader lock, i.e. assembly load
2629 if (debugger_thread_id == GetCurrentThreadId ())
2632 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2633 if (suspend_count - tls->resume_count > 0)
2634 tls->suspending = TRUE;
2636 DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2638 if (suspend_count - tls->resume_count == 0) {
2640 * We are executing a single threaded invoke but the single step for
2641 * suspending is still active.
2642 * FIXME: This slows down single threaded invokes.
2644 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
2648 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2650 /* Can't suspend in these methods */
2651 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
2654 save_thread_context (ctx);
2662 * Increase the suspend count of the VM. While the suspend count is greater
2663 * than 0, runtime threads are suspended at certain points during execution.
2668 mono_loader_lock ();
2670 mono_mutex_lock (&suspend_mutex);
2674 DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
2676 if (suspend_count == 1) {
2677 // FIXME: Is it safe to call this inside the lock ?
2678 start_single_stepping ();
2679 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2682 mono_mutex_unlock (&suspend_mutex);
2684 mono_loader_unlock ();
2690 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2698 g_assert (debugger_thread_id == GetCurrentThreadId ());
2700 mono_loader_lock ();
2702 mono_mutex_lock (&suspend_mutex);
2704 g_assert (suspend_count > 0);
2707 DEBUG(1, fprintf (log_file, "[%p] Resuming vm, suspend count=%d...\n", (gpointer)GetCurrentThreadId (), suspend_count));
2709 if (suspend_count == 0) {
2710 // FIXME: Is it safe to call this inside the lock ?
2711 stop_single_stepping ();
2712 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2715 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2716 err = mono_cond_broadcast (&suspend_cond);
2717 g_assert (err == 0);
2719 mono_mutex_unlock (&suspend_mutex);
2720 //g_assert (err == 0);
2722 mono_loader_unlock ();
2728 * Resume just one thread.
2731 resume_thread (MonoInternalThread *thread)
2734 DebuggerTlsData *tls;
2736 g_assert (debugger_thread_id == GetCurrentThreadId ());
2738 mono_loader_lock ();
2740 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2743 mono_mutex_lock (&suspend_mutex);
2745 g_assert (suspend_count > 0);
2747 DEBUG(1, fprintf (log_file, "[%p] Resuming thread...\n", (gpointer)(gssize)thread->tid));
2749 tls->resume_count += suspend_count;
2752 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2753 * but only the one whose resume_count field is > 0 will be resumed.
2755 err = mono_cond_broadcast (&suspend_cond);
2756 g_assert (err == 0);
2758 mono_mutex_unlock (&suspend_mutex);
2759 //g_assert (err == 0);
2761 mono_loader_unlock ();
2765 invalidate_frames (DebuggerTlsData *tls)
2770 tls = mono_native_tls_get_value (debugger_tls_id);
2773 for (i = 0; i < tls->frame_count; ++i) {
2774 if (tls->frames [i]->jit)
2775 mono_debug_free_method_jit_info (tls->frames [i]->jit);
2776 g_free (tls->frames [i]);
2778 g_free (tls->frames);
2779 tls->frame_count = 0;
2786 * Suspend the current thread until the runtime is resumed. If the thread has a
2787 * pending invoke, then the invoke is executed before this function returns.
2790 suspend_current (void)
2793 DebuggerTlsData *tls;
2795 g_assert (debugger_thread_id != GetCurrentThreadId ());
2797 if (mono_loader_lock_is_owned_by_self ()) {
2799 * If we own the loader mutex, can't suspend until we release it, since the
2800 * whole runtime can deadlock otherwise.
2805 tls = mono_native_tls_get_value (debugger_tls_id);
2808 mono_mutex_lock (&suspend_mutex);
2810 tls->suspending = FALSE;
2811 tls->really_suspended = TRUE;
2813 if (!tls->suspended) {
2814 tls->suspended = TRUE;
2815 MONO_SEM_POST (&suspend_sem);
2818 DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
2820 while (suspend_count - tls->resume_count > 0) {
2822 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
2824 mono_mutex_unlock (&suspend_mutex);
2826 mono_mutex_lock (&suspend_mutex);
2832 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
2833 g_assert (err == 0);
2837 tls->suspended = FALSE;
2838 tls->really_suspended = FALSE;
2840 threads_suspend_count --;
2842 mono_mutex_unlock (&suspend_mutex);
2844 DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
2846 if (tls->pending_invoke) {
2847 /* Save the original context */
2848 tls->pending_invoke->has_ctx = TRUE;
2849 tls->pending_invoke->ctx = tls->context.ctx;
2854 /* The frame info becomes invalid after a resume */
2855 tls->context.valid = FALSE;
2856 tls->async_state.valid = FALSE;
2857 invalidate_frames (tls);
2861 count_thread (gpointer key, gpointer value, gpointer user_data)
2863 DebuggerTlsData *tls = value;
2865 if (!tls->suspended && !tls->terminated)
2866 *(int*)user_data = *(int*)user_data + 1;
2870 count_threads_to_wait_for (void)
2874 mono_loader_lock ();
2875 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2876 mono_loader_unlock ();
2884 * Wait until the runtime is completely suspended.
2887 wait_for_suspend (void)
2889 int nthreads, nwait, err;
2890 gboolean waited = FALSE;
2892 // FIXME: Threads starting/stopping ?
2893 mono_loader_lock ();
2894 nthreads = mono_g_hash_table_size (thread_to_tls);
2895 mono_loader_unlock ();
2898 nwait = count_threads_to_wait_for ();
2900 DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
2901 err = MONO_SEM_WAIT (&suspend_sem);
2902 g_assert (err == 0);
2910 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
2916 * Return whenever the runtime is suspended.
2921 return count_threads_to_wait_for () == 0;
2924 static MonoSeqPointInfo*
2925 get_seq_points (MonoDomain *domain, MonoMethod *method)
2927 MonoSeqPointInfo *seq_points;
2929 mono_domain_lock (domain);
2930 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2931 if (!seq_points && method->is_inflated) {
2932 /* generic sharing + aot */
2933 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (method));
2935 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mini_get_shared_method (method));
2937 mono_domain_unlock (domain);
2942 static MonoSeqPointInfo*
2943 find_seq_points (MonoDomain *domain, MonoMethod *method)
2945 MonoSeqPointInfo *seq_points = get_seq_points (domain, method);
2948 printf ("Unable to find seq points for method '%s'.\n", mono_method_full_name (method, TRUE));
2949 g_assert (seq_points);
2955 * find_next_seq_point_for_native_offset:
2957 * Find the first sequence point after NATIVE_OFFSET.
2960 find_next_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2962 MonoSeqPointInfo *seq_points;
2965 seq_points = find_seq_points (domain, method);
2966 g_assert (seq_points);
2970 for (i = 0; i < seq_points->len; ++i) {
2971 if (seq_points->seq_points [i].native_offset >= native_offset)
2972 return &seq_points->seq_points [i];
2979 * find_prev_seq_point_for_native_offset:
2981 * Find the first sequence point before NATIVE_OFFSET.
2984 find_prev_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2986 MonoSeqPointInfo *seq_points;
2989 seq_points = get_seq_points (domain, method);
2995 for (i = seq_points->len - 1; i >= 0; --i) {
2996 if (seq_points->seq_points [i].native_offset <= native_offset)
2997 return &seq_points->seq_points [i];
3006 * Find the sequence point corresponding to the IL offset IL_OFFSET, which
3007 * should be the location of a sequence point.
3009 static G_GNUC_UNUSED SeqPoint*
3010 find_seq_point (MonoDomain *domain, MonoMethod *method, gint32 il_offset, MonoSeqPointInfo **info)
3012 MonoSeqPointInfo *seq_points;
3017 seq_points = get_seq_points (domain, method);
3022 for (i = 0; i < seq_points->len; ++i) {
3023 if (seq_points->seq_points [i].il_offset == il_offset)
3024 return &seq_points->seq_points [i];
3031 DebuggerTlsData *tls;
3033 } ComputeFramesUserData;
3036 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3038 ComputeFramesUserData *ud = user_data;
3040 MonoMethod *method, *actual_method, *api_method;
3044 if (info->type != FRAME_TYPE_MANAGED) {
3045 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3046 /* Mark the last frame as an invoke frame */
3048 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3054 method = info->ji->method;
3056 method = info->method;
3057 actual_method = info->actual_method;
3058 api_method = method;
3063 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3066 if (info->il_offset == -1) {
3067 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3068 if (ud->frames == NULL) {
3069 sp = find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL);
3071 info->il_offset = sp->il_offset;
3073 if (info->il_offset == -1)
3074 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3077 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));
3079 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3080 if (!CHECK_PROTOCOL_VERSION (2, 17))
3081 /* Older clients can't handle this flag */
3083 api_method = mono_marshal_method_from_wrapper (method);
3086 actual_method = api_method;
3087 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3090 frame = g_new0 (StackFrame, 1);
3091 frame->method = method;
3092 frame->actual_method = actual_method;
3093 frame->api_method = api_method;
3094 frame->il_offset = info->il_offset;
3095 frame->native_offset = info->native_offset;
3096 frame->flags = flags;
3097 frame->ji = info->ji;
3098 if (info->reg_locations)
3099 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3102 frame->has_ctx = TRUE;
3104 frame->domain = info->domain;
3106 ud->frames = g_slist_append (ud->frames, frame);
3112 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3114 ComputeFramesUserData *ud = user_data;
3117 * 'tls->filter_ctx' is the location of the throw site.
3119 * mono_walk_stack() will never actually hit the throw site, but unwind
3120 * directly from the filter to the call site; we abort stack unwinding here
3121 * once this happens and resume from the throw site.
3124 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3127 return process_frame (info, ctx, user_data);
3131 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3133 ComputeFramesUserData user_data;
3135 int i, findex, new_frame_count;
3136 StackFrame **new_frames, *f;
3137 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3139 // FIXME: Locking on tls
3140 if (tls->frames && tls->frames_up_to_date)
3143 DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
3145 user_data.tls = tls;
3146 user_data.frames = NULL;
3147 if (tls->terminated) {
3148 tls->frame_count = 0;
3150 } if (!tls->really_suspended && tls->async_state.valid) {
3151 /* Have to use the state saved by the signal handler */
3152 process_frame (&tls->async_last_frame, NULL, &user_data);
3153 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3154 } else if (tls->filter_state.valid) {
3156 * We are inside an exception filter.
3158 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3160 if (tls->context.valid)
3161 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3163 * After that, we resume unwinding from the location where the exception has been thrown.
3165 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3166 } else if (tls->context.valid) {
3167 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3170 tls->frame_count = 0;
3174 new_frame_count = g_slist_length (user_data.frames);
3175 new_frames = g_new0 (StackFrame*, new_frame_count);
3177 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3181 * Reuse the id for already existing stack frames, so invokes don't invalidate
3182 * the still valid stack frames.
3184 for (i = 0; i < tls->frame_count; ++i) {
3185 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3186 f->id = tls->frames [i]->id;
3191 if (i >= tls->frame_count)
3192 f->id = InterlockedIncrement (&frame_id);
3194 new_frames [findex ++] = f;
3197 g_slist_free (user_data.frames);
3199 invalidate_frames (tls);
3201 tls->frames = new_frames;
3202 tls->frame_count = new_frame_count;
3203 tls->frames_up_to_date = TRUE;
3207 * GHFunc to emit an appdomain creation event
3208 * @param key Don't care
3209 * @param value A loaded appdomain
3210 * @param user_data Don't care
3213 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3215 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3216 g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
3220 * GHFunc to emit a thread start event
3221 * @param key A thread id
3222 * @param value A thread object
3223 * @param user_data Don't care
3226 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3228 if (GPOINTER_TO_INT (key) != debugger_thread_id)
3229 process_profiler_event (EVENT_KIND_THREAD_START, value);
3233 * GFunc to emit an assembly load event
3234 * @param value A loaded assembly
3235 * @param user_data Don't care
3238 emit_assembly_load (gpointer value, gpointer user_data)
3240 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3244 * GFunc to emit a type load event
3245 * @param value A loaded type
3246 * @param user_data Don't care
3249 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3251 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3255 strdup_tolower (char *s)
3260 for (p = s2; *p; ++p)
3270 * create_event_list:
3272 * Return a list of event request ids matching EVENT, starting from REQS, which
3273 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3275 * We return request ids, instead of requests, to simplify threading, since
3276 * requests could be deleted anytime when the loader lock is not held.
3277 * LOCKING: Assumes the loader lock is held.
3280 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3283 GSList *events = NULL;
3285 *suspend_policy = SUSPEND_POLICY_NONE;
3288 reqs = event_requests;
3293 for (i = 0; i < reqs->len; ++i) {
3294 EventRequest *req = g_ptr_array_index (reqs, i);
3295 if (req->event_kind == event) {
3296 gboolean filtered = FALSE;
3299 for (j = 0; j < req->nmodifiers; ++j) {
3300 Modifier *mod = &req->modifiers [j];
3302 if (mod->kind == MOD_KIND_COUNT) {
3304 if (mod->data.count > 0) {
3305 if (mod->data.count > 0) {
3307 if (mod->data.count == 0)
3311 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3312 if (mod->data.thread != mono_thread_internal_current ())
3314 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3315 if (mod->data.exc_class && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3317 if (ei->caught && !mod->caught)
3319 if (!ei->caught && !mod->uncaught)
3321 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3323 gboolean found = FALSE;
3324 MonoAssembly **assemblies = mod->data.assemblies;
3327 for (k = 0; assemblies [k]; ++k)
3328 if (assemblies [k] == ji->method->klass->image->assembly)
3333 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3334 gpointer iter = NULL;
3336 MonoDebugSourceInfo *sinfo;
3337 char *source_file, *s;
3338 gboolean found = FALSE;
3340 GPtrArray *source_file_list;
3342 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3343 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3346 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, NULL, NULL, NULL, NULL, NULL);
3347 for (i = 0; i < source_file_list->len; ++i) {
3348 sinfo = g_ptr_array_index (source_file_list, i);
3350 * Do a case-insesitive match by converting the file name to
3353 s = strdup_tolower (sinfo->source_file);
3354 if (g_hash_table_lookup (mod->data.source_files, s))
3358 g_ptr_array_free (source_file_list, TRUE);
3363 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3366 s = mono_type_full_name (&ei->klass->byval_arg);
3367 if (!g_hash_table_lookup (mod->data.type_names, s))
3370 } else if (mod->kind == MOD_KIND_STEP) {
3371 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3372 (ji->method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3373 !strcmp (ji->method->name, ".cctor"))
3375 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3376 MonoCustomAttrInfo *ainfo;
3377 static MonoClass *klass;
3380 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3383 if (!ji->dbg_hidden_inited) {
3384 ainfo = mono_custom_attrs_from_method (ji->method);
3386 if (mono_custom_attrs_has_attr (ainfo, klass))
3387 ji->dbg_hidden = TRUE;
3388 mono_custom_attrs_free (ainfo);
3390 ji->dbg_hidden_inited = TRUE;
3399 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3400 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3405 /* Send a VM START/DEATH event by default */
3406 if (event == EVENT_KIND_VM_START)
3407 events = g_slist_append (events, GINT_TO_POINTER (0));
3408 if (event == EVENT_KIND_VM_DEATH)
3409 events = g_slist_append (events, GINT_TO_POINTER (0));
3414 static G_GNUC_UNUSED const char*
3415 event_to_string (EventKind event)
3418 case EVENT_KIND_VM_START: return "VM_START";
3419 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3420 case EVENT_KIND_THREAD_START: return "THREAD_START";
3421 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3422 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3423 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3424 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3425 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3426 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3427 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3428 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3429 case EVENT_KIND_STEP: return "STEP";
3430 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3431 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3432 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3433 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3434 case EVENT_KIND_USER_LOG: return "USER_LOG";
3436 g_assert_not_reached ();
3443 * Send an event to the client, suspending the vm if needed.
3444 * LOCKING: Since this can suspend the calling thread, no locks should be held
3446 * The EVENTS list is freed by this function.
3449 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3453 MonoDomain *domain = mono_domain_get ();
3454 MonoThread *thread = NULL;
3455 gboolean send_success = FALSE;
3460 DEBUG (2, fprintf (log_file, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event)));
3464 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3465 // FIXME: We miss those events
3466 DEBUG (2, fprintf (log_file, "VM start event not sent yet: dropping %s\n", event_to_string (event)));
3470 if (vm_death_event_sent) {
3471 DEBUG (2, fprintf (log_file, "VM death event has been sent: dropping %s\n", event_to_string (event)));
3475 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3476 DEBUG (2, fprintf (log_file, "Mono runtime is shutting down: dropping %s\n", event_to_string (event)));
3481 DEBUG (2, fprintf (log_file, "Debugger client is not connected: dropping %s\n", event_to_string (event)));
3485 if (event == EVENT_KIND_KEEPALIVE)
3486 suspend_policy = SUSPEND_POLICY_NONE;
3491 if (agent_config.defer) {
3492 /* Make sure the thread id is always set when doing deferred debugging */
3493 if (debugger_thread_id == GetCurrentThreadId ()) {
3494 /* Don't suspend on events from the debugger thread */
3495 suspend_policy = SUSPEND_POLICY_NONE;
3496 thread = mono_thread_get_main ();
3498 else thread = mono_thread_current ();
3500 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3501 // FIXME: Send these with a NULL thread, don't suspend the current thread
3506 nevents = g_slist_length (events);
3507 buffer_init (&buf, 128);
3508 buffer_add_byte (&buf, suspend_policy);
3509 buffer_add_int (&buf, nevents);
3511 for (l = events; l; l = l->next) {
3512 buffer_add_byte (&buf, event); // event kind
3513 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3518 thread = mono_thread_current ();
3520 if (event == EVENT_KIND_VM_START && arg != NULL)
3523 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3526 case EVENT_KIND_THREAD_START:
3527 case EVENT_KIND_THREAD_DEATH:
3529 case EVENT_KIND_APPDOMAIN_CREATE:
3530 case EVENT_KIND_APPDOMAIN_UNLOAD:
3531 buffer_add_domainid (&buf, arg);
3533 case EVENT_KIND_METHOD_ENTRY:
3534 case EVENT_KIND_METHOD_EXIT:
3535 buffer_add_methodid (&buf, domain, arg);
3537 case EVENT_KIND_ASSEMBLY_LOAD:
3538 case EVENT_KIND_ASSEMBLY_UNLOAD:
3539 buffer_add_assemblyid (&buf, domain, arg);
3541 case EVENT_KIND_TYPE_LOAD:
3542 buffer_add_typeid (&buf, domain, arg);
3544 case EVENT_KIND_BREAKPOINT:
3545 case EVENT_KIND_STEP:
3546 buffer_add_methodid (&buf, domain, arg);
3547 buffer_add_long (&buf, il_offset);
3549 case EVENT_KIND_VM_START:
3550 buffer_add_domainid (&buf, mono_get_root_domain ());
3552 case EVENT_KIND_VM_DEATH:
3554 case EVENT_KIND_EXCEPTION: {
3555 EventInfo *ei = arg;
3556 buffer_add_objid (&buf, ei->exc);
3559 case EVENT_KIND_USER_BREAK:
3561 case EVENT_KIND_USER_LOG: {
3562 EventInfo *ei = arg;
3563 buffer_add_int (&buf, ei->level);
3564 buffer_add_string (&buf, ei->category ? ei->category : "");
3565 buffer_add_string (&buf, ei->message ? ei->message : "");
3568 case EVENT_KIND_KEEPALIVE:
3569 suspend_policy = SUSPEND_POLICY_NONE;
3572 g_assert_not_reached ();
3576 if (event == EVENT_KIND_VM_START) {
3577 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3578 if (!agent_config.defer)
3579 start_debugger_thread ();
3582 if (event == EVENT_KIND_VM_DEATH) {
3583 vm_death_event_sent = TRUE;
3584 suspend_policy = SUSPEND_POLICY_NONE;
3587 if (mono_runtime_is_shutting_down ())
3588 suspend_policy = SUSPEND_POLICY_NONE;
3590 if (suspend_policy != SUSPEND_POLICY_NONE) {
3592 * Save the thread context and start suspending before sending the packet,
3593 * since we could be receiving the resume request before send_packet ()
3596 save_thread_context (ctx);
3600 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3604 g_slist_free (events);
3607 if (!send_success) {
3608 DEBUG (2, fprintf (log_file, "Sending command %s failed.\n", event_to_string (event)));
3612 if (event == EVENT_KIND_VM_START) {
3613 vm_start_event_sent = TRUE;
3616 DEBUG (1, fprintf (log_file, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer)GetCurrentThreadId (), nevents, event_to_string (event), ecount, suspend_policy));
3618 switch (suspend_policy) {
3619 case SUSPEND_POLICY_NONE:
3621 case SUSPEND_POLICY_ALL:
3624 case SUSPEND_POLICY_EVENT_THREAD:
3628 g_assert_not_reached ();
3633 process_profiler_event (EventKind event, gpointer arg)
3637 EventInfo ei, *ei_arg = NULL;
3639 if (event == EVENT_KIND_TYPE_LOAD) {
3644 mono_loader_lock ();
3645 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3646 mono_loader_unlock ();
3648 process_event (event, arg, 0, NULL, events, suspend_policy);
3652 runtime_initialized (MonoProfiler *prof)
3654 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3655 if (agent_config.defer)
3656 start_debugger_thread ();
3660 runtime_shutdown (MonoProfiler *prof)
3662 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3664 mono_debugger_agent_cleanup ();
3668 thread_startup (MonoProfiler *prof, uintptr_t tid)
3670 MonoInternalThread *thread = mono_thread_internal_current ();
3671 MonoInternalThread *old_thread;
3672 DebuggerTlsData *tls;
3674 if (tid == debugger_thread_id)
3677 g_assert (thread->tid == tid);
3679 mono_loader_lock ();
3680 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3681 mono_loader_unlock ();
3683 if (thread == old_thread) {
3685 * For some reason, thread_startup () might be called for the same thread
3686 * multiple times (attach ?).
3688 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
3692 * thread_end () might not be called for some threads, and the tid could
3695 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
3696 mono_loader_lock ();
3697 mono_g_hash_table_remove (thread_to_tls, old_thread);
3698 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3699 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3700 mono_loader_unlock ();
3704 tls = mono_native_tls_get_value (debugger_tls_id);
3706 // FIXME: Free this somewhere
3707 tls = g_new0 (DebuggerTlsData, 1);
3708 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3709 tls->thread = thread;
3710 mono_native_tls_set_value (debugger_tls_id, tls);
3712 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3714 mono_loader_lock ();
3715 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3716 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3717 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3718 mono_loader_unlock ();
3720 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3723 * suspend_vm () could have missed this thread, so wait for a resume.
3729 thread_end (MonoProfiler *prof, uintptr_t tid)
3731 MonoInternalThread *thread;
3732 DebuggerTlsData *tls = NULL;
3734 mono_loader_lock ();
3735 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3737 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3738 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3740 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3741 tls->terminated = TRUE;
3742 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3743 MONO_GC_UNREGISTER_ROOT (tls->thread);
3747 mono_loader_unlock ();
3749 /* We might be called for threads started before we registered the start callback */
3751 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3752 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3757 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3759 mono_loader_lock ();
3760 g_hash_table_insert (domains, domain, domain);
3761 mono_loader_unlock ();
3763 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3767 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3769 clear_breakpoints_for_domain (domain);
3771 mono_loader_lock ();
3772 /* Invalidate each thread's frame stack */
3773 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3774 mono_loader_unlock ();
3776 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3780 * invalidate_each_thread:
3782 * A GHFunc to invalidate frames.
3783 * value must be a DebuggerTlsData*
3786 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3788 invalidate_frames (value);
3792 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3794 /* Sent later in jit_end () */
3795 mono_loader_lock ();
3796 g_ptr_array_add (pending_assembly_loads, assembly);
3797 mono_loader_unlock ();
3801 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3803 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3805 clear_event_requests_for_assembly (assembly);
3806 clear_types_for_assembly (assembly);
3810 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3812 #if defined(HOST_WIN32) && !defined(__GNUC__)
3813 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3815 gpointer stackptr = __builtin_frame_address (1);
3817 MonoInternalThread *thread = mono_thread_internal_current ();
3818 DebuggerTlsData *tls;
3820 mono_loader_lock ();
3822 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3823 /* Could be the debugger thread with assembly/type load hooks */
3825 tls->invoke_addr = stackptr;
3827 mono_loader_unlock ();
3831 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3834 #if defined(HOST_WIN32) && !defined(__GNUC__)
3835 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3837 gpointer stackptr = __builtin_frame_address (1);
3840 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
3844 * We need to stop single stepping when exiting a runtime invoke, since if it is
3845 * a step out, it may return to native code, and thus never end.
3847 mono_loader_lock ();
3848 ss_invoke_addr = NULL;
3850 for (i = 0; i < event_requests->len; ++i) {
3851 EventRequest *req = g_ptr_array_index (event_requests, i);
3853 if (req->event_kind == EVENT_KIND_STEP) {
3854 ss_destroy (req->info);
3855 g_ptr_array_remove_index_fast (event_requests, i);
3860 mono_loader_unlock ();
3864 send_type_load (MonoClass *klass)
3866 gboolean type_load = FALSE;
3867 MonoDomain *domain = mono_domain_get ();
3868 AgentDomainInfo *info = NULL;
3870 mono_loader_lock ();
3871 mono_domain_lock (domain);
3873 info = get_agent_domain_info (domain);
3875 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
3877 g_hash_table_insert (info->loaded_classes, klass, klass);
3880 mono_domain_unlock (domain);
3881 mono_loader_unlock ();
3883 emit_type_load (klass, klass, NULL);
3887 * Emit load events for all types currently loaded in the domain.
3888 * Takes the loader and domain locks.
3889 * user_data is unused.
3892 send_types_for_domain (MonoDomain *domain, void *user_data)
3894 AgentDomainInfo *info = NULL;
3896 mono_loader_lock ();
3897 mono_domain_lock (domain);
3898 info = get_agent_domain_info (domain);
3900 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
3901 mono_domain_unlock (domain);
3902 mono_loader_unlock ();
3906 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
3909 * We emit type load events when the first method of the type is JITted,
3910 * since the class load profiler callbacks might be called with the
3911 * loader lock held. They could also occur in the debugger thread.
3912 * Same for assembly load events.
3915 MonoAssembly *assembly = NULL;
3917 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
3918 mono_loader_lock ();
3919 if (pending_assembly_loads->len > 0) {
3920 assembly = g_ptr_array_index (pending_assembly_loads, 0);
3921 g_ptr_array_remove_index (pending_assembly_loads, 0);
3923 mono_loader_unlock ();
3926 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
3932 send_type_load (method->klass);
3935 add_pending_breakpoints (method, jinfo);
3939 * BREAKPOINTS/SINGLE STEPPING
3943 * Contains information about an inserted breakpoint.
3946 long il_offset, native_offset;
3951 } BreakpointInstance;
3954 * Contains generic information about a breakpoint.
3958 * The method where the breakpoint is placed. Can be NULL in which case it
3959 * is inserted into every method. This is used to implement method entry/
3960 * exit events. Can be a generic method definition, in which case the
3961 * breakpoint is inserted into every instance.
3967 * A list of BreakpointInstance structures describing where the breakpoint
3968 * was inserted. There could be more than one because of
3969 * generics/appdomains/method entry/exit.
3971 GPtrArray *children;
3974 /* List of breakpoints */
3975 static GPtrArray *breakpoints;
3976 /* Maps breakpoint locations to the number of breakpoints at that location */
3977 static GHashTable *bp_locs;
3980 breakpoints_init (void)
3982 breakpoints = g_ptr_array_new ();
3983 bp_locs = g_hash_table_new (NULL, NULL);
3987 * insert_breakpoint:
3989 * Insert the breakpoint described by BP into the method described by
3993 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
3996 BreakpointInstance *inst;
3997 SeqPoint *sp = NULL;
4000 mono_error_init (error);
4002 for (i = 0; i < seq_points->len; ++i) {
4003 sp = &seq_points->seq_points [i];
4005 if (sp->il_offset == bp->il_offset)
4009 if (i == seq_points->len) {
4011 * The set of IL offsets with seq points doesn't completely match the
4012 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4014 for (i = 0; i < seq_points->len; ++i) {
4015 sp = &seq_points->seq_points [i];
4017 if (sp->il_offset != METHOD_ENTRY_IL_OFFSET && sp->il_offset != METHOD_EXIT_IL_OFFSET && sp->il_offset + 1 == bp->il_offset)
4022 if (i == seq_points->len) {
4023 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);
4025 for (i = 0; i < seq_points->len; ++i)
4026 DEBUG (1, fprintf (log_file, "%d\n", seq_points->seq_points [i].il_offset));
4029 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4038 inst = g_new0 (BreakpointInstance, 1);
4040 inst->native_offset = sp->native_offset;
4041 inst->ip = (guint8*)ji->code_start + sp->native_offset;
4043 inst->domain = domain;
4045 mono_loader_lock ();
4047 g_ptr_array_add (bp->children, inst);
4049 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4050 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4051 mono_loader_unlock ();
4054 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4055 mono_arch_set_breakpoint (ji, inst->ip);
4061 DEBUG(1, fprintf (log_file, "[dbg] Inserted breakpoint at %s:0x%x.\n", mono_method_full_name (ji->method, TRUE), (int)sp->il_offset));
4065 remove_breakpoint (BreakpointInstance *inst)
4067 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4069 MonoJitInfo *ji = inst->ji;
4070 guint8 *ip = inst->ip;
4072 mono_loader_lock ();
4073 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4074 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4075 mono_loader_unlock ();
4077 g_assert (count > 0);
4080 mono_arch_clear_breakpoint (ji, ip);
4087 static inline gboolean
4088 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4094 if (method == bp->method)
4096 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4099 if (bp->method->is_inflated && method->is_inflated) {
4100 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4101 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4103 /* Open generic methods should match closed generic methods of the same class */
4104 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4105 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4106 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4108 /* FIXME: Handle !mvar */
4109 if (t1->type != MONO_TYPE_MVAR)
4120 * add_pending_breakpoints:
4122 * Insert pending breakpoints into the newly JITted method METHOD.
4125 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4128 MonoSeqPointInfo *seq_points;
4134 domain = mono_domain_get ();
4136 mono_loader_lock ();
4138 for (i = 0; i < breakpoints->len; ++i) {
4139 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4140 gboolean found = FALSE;
4142 if (!bp_matches_method (bp, method))
4145 for (j = 0; j < bp->children->len; ++j) {
4146 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4153 mono_domain_lock (domain);
4154 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
4155 if (!seq_points && ji->method->is_inflated)
4156 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (ji->method));
4157 mono_domain_unlock (domain);
4159 /* Could be AOT code */
4161 g_assert (seq_points);
4163 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4167 mono_loader_unlock ();
4171 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4177 mono_error_init (error);
4179 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4181 /* Might be AOTed code */
4182 code = mono_aot_get_method (domain, method);
4184 ji = mono_jit_info_table_find (domain, code);
4189 insert_breakpoint (seq_points, domain, ji, bp, error);
4193 clear_breakpoint (MonoBreakpoint *bp);
4198 * Set a breakpoint at IL_OFFSET in METHOD.
4199 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4200 * METHOD can also be a generic method definition, in which case a breakpoint
4201 * is placed in all instances of the method.
4202 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4205 static MonoBreakpoint*
4206 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4209 GHashTableIter iter, iter2;
4212 MonoSeqPointInfo *seq_points;
4215 mono_error_init (error);
4218 // - suspend/resume the vm to prevent code patching problems
4219 // - multiple breakpoints on the same location
4220 // - dynamic methods
4223 bp = g_new0 (MonoBreakpoint, 1);
4224 bp->method = method;
4225 bp->il_offset = il_offset;
4227 bp->children = g_ptr_array_new ();
4229 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));
4231 mono_loader_lock ();
4233 g_hash_table_iter_init (&iter, domains);
4234 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4235 mono_domain_lock (domain);
4237 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4238 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4239 if (bp_matches_method (bp, m))
4240 set_bp_in_method (domain, m, seq_points, bp, error);
4243 mono_domain_unlock (domain);
4246 mono_loader_unlock ();
4248 mono_loader_lock ();
4249 g_ptr_array_add (breakpoints, bp);
4250 mono_loader_unlock ();
4252 if (error && !mono_error_ok (error)) {
4253 clear_breakpoint (bp);
4261 clear_breakpoint (MonoBreakpoint *bp)
4265 // FIXME: locking, races
4266 for (i = 0; i < bp->children->len; ++i) {
4267 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4269 remove_breakpoint (inst);
4274 mono_loader_lock ();
4275 g_ptr_array_remove (breakpoints, bp);
4276 mono_loader_unlock ();
4278 g_ptr_array_free (bp->children, TRUE);
4283 breakpoints_cleanup (void)
4287 mono_loader_lock ();
4289 while (i < event_requests->len) {
4290 EventRequest *req = g_ptr_array_index (event_requests, i);
4292 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4293 clear_breakpoint (req->info);
4294 g_ptr_array_remove_index_fast (event_requests, i);
4301 for (i = 0; i < breakpoints->len; ++i)
4302 g_free (g_ptr_array_index (breakpoints, i));
4304 g_ptr_array_free (breakpoints, TRUE);
4305 g_hash_table_destroy (bp_locs);
4310 mono_loader_unlock ();
4314 * clear_breakpoints_for_domain:
4316 * Clear breakpoint instances which reference DOMAIN.
4319 clear_breakpoints_for_domain (MonoDomain *domain)
4323 /* This could be called after shutdown */
4327 mono_loader_lock ();
4328 for (i = 0; i < breakpoints->len; ++i) {
4329 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4332 while (j < bp->children->len) {
4333 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4335 if (inst->domain == domain) {
4336 remove_breakpoint (inst);
4340 g_ptr_array_remove_index_fast (bp->children, j);
4346 mono_loader_unlock ();
4350 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4352 return bp->method && bp->method->klass->image->assembly == assembly;
4356 process_breakpoint_inner (DebuggerTlsData *tls)
4360 int i, j, suspend_policy;
4361 guint32 native_offset;
4363 BreakpointInstance *inst;
4364 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4365 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4366 EventKind kind = EVENT_KIND_BREAKPOINT;
4367 MonoContext *ctx = &tls->restore_ctx;
4368 MonoSeqPointInfo *info;
4371 // FIXME: Speed this up
4373 ip = MONO_CONTEXT_GET_IP (ctx);
4374 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4376 g_assert (ji->method);
4378 /* Compute the native offset of the breakpoint from the ip */
4379 native_offset = ip - (guint8*)ji->code_start;
4382 * Skip the instruction causing the breakpoint signal.
4384 mono_arch_skip_breakpoint (ctx, ji);
4386 if (ji->method->wrapper_type || tls->disable_breakpoints)
4389 bp_reqs = g_ptr_array_new ();
4390 ss_reqs = g_ptr_array_new ();
4391 ss_reqs_orig = g_ptr_array_new ();
4393 mono_loader_lock ();
4396 * The ip points to the instruction causing the breakpoint event, which is after
4397 * the offset recorded in the seq point map, so find the prev seq point before ip.
4399 sp = find_prev_seq_point_for_native_offset (mono_domain_get (), ji->method, native_offset, &info);
4402 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));
4405 for (i = 0; i < breakpoints->len; ++i) {
4406 bp = g_ptr_array_index (breakpoints, i);
4411 for (j = 0; j < bp->children->len; ++j) {
4412 inst = g_ptr_array_index (bp->children, j);
4413 if (inst->ji == ji && inst->sp == sp) {
4414 if (bp->req->event_kind == EVENT_KIND_STEP) {
4415 g_ptr_array_add (ss_reqs_orig, bp->req);
4417 g_ptr_array_add (bp_reqs, bp->req);
4422 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4423 /* Maybe a method entry/exit event */
4424 if (sp->il_offset == METHOD_ENTRY_IL_OFFSET)
4425 kind = EVENT_KIND_METHOD_ENTRY;
4426 else if (sp->il_offset == METHOD_EXIT_IL_OFFSET)
4427 kind = EVENT_KIND_METHOD_EXIT;
4430 /* Process single step requests */
4431 for (i = 0; i < ss_reqs_orig->len; ++i) {
4432 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4433 SingleStepReq *ss_req = req->info;
4434 gboolean hit = TRUE;
4436 if (ss_req->size == STEP_SIZE_LINE) {
4437 /* Have to check whenever a different source line was reached */
4438 MonoDebugMethodInfo *minfo;
4439 MonoDebugSourceLocation *loc = NULL;
4441 minfo = mono_debug_lookup_method (ji->method);
4444 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4446 if (!loc || (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line)) {
4447 /* Have to continue single stepping */
4448 DEBUG(1, fprintf (log_file, "[%p] Same source line, continuing single stepping.\n", (gpointer)GetCurrentThreadId ()));
4453 ss_req->last_method = ji->method;
4454 ss_req->last_line = loc->row;
4455 mono_debug_free_source_location (loc);
4460 g_ptr_array_add (ss_reqs, req);
4462 /* Start single stepping again from the current sequence point */
4463 ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4466 if (ss_reqs->len > 0)
4467 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4468 if (bp_reqs->len > 0)
4469 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4470 if (kind != EVENT_KIND_BREAKPOINT)
4471 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4473 mono_loader_unlock ();
4475 g_ptr_array_free (bp_reqs, TRUE);
4476 g_ptr_array_free (ss_reqs, TRUE);
4479 * FIXME: The first event will suspend, so the second will only be sent after the
4483 process_event (EVENT_KIND_STEP, ji->method, 0, ctx, ss_events, suspend_policy);
4485 process_event (kind, ji->method, 0, ctx, bp_events, suspend_policy);
4486 if (enter_leave_events)
4487 process_event (kind, ji->method, 0, ctx, enter_leave_events, suspend_policy);
4490 /* Process a breakpoint/single step event after resuming from a signal handler */
4492 process_signal_event (void (*func) (DebuggerTlsData*))
4494 DebuggerTlsData *tls;
4495 MonoContext orig_restore_ctx, ctx;
4496 static void (*restore_context) (void *);
4498 if (!restore_context)
4499 restore_context = mono_get_restore_context ();
4501 tls = mono_native_tls_get_value (debugger_tls_id);
4502 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4503 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4504 memcpy (&tls->restore_ctx, &tls->handler_ctx, sizeof (MonoContext));
4508 /* This is called when resuming from a signal handler, so it shouldn't return */
4509 memcpy (&ctx, &tls->restore_ctx, sizeof (MonoContext));
4510 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4511 restore_context (&ctx);
4512 g_assert_not_reached ();
4516 process_breakpoint (void)
4518 process_signal_event (process_breakpoint_inner);
4522 resume_from_signal_handler (void *sigctx, void *func)
4524 DebuggerTlsData *tls;
4527 /* Save the original context in TLS */
4528 // FIXME: This might not work on an altstack ?
4529 tls = mono_native_tls_get_value (debugger_tls_id);
4532 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4533 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4534 // clob:c could be added to op_seq_point.
4536 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4537 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4538 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4539 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4541 MONO_CONTEXT_SET_IP (&ctx, func);
4543 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4545 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4546 mono_ppc_set_func_into_sigctx (sigctx, func);
4551 mono_debugger_agent_breakpoint_hit (void *sigctx)
4554 * We are called from a signal handler, and running code there causes all kinds of
4555 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4556 * So set up the signal context to return to the real breakpoint handler function.
4558 resume_from_signal_handler (sigctx, process_breakpoint);
4562 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4564 if (frame->managed) {
4565 *(MonoContext*)data = *ctx;
4574 * Called by System.Diagnostics.Debugger:Break ().
4577 mono_debugger_agent_user_break (void)
4579 if (agent_config.enabled) {
4584 /* Obtain a context */
4585 MONO_CONTEXT_SET_IP (&ctx, NULL);
4586 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4587 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4589 mono_loader_lock ();
4590 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4591 mono_loader_unlock ();
4593 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4600 ss_depth_to_string (StepDepth depth)
4603 case STEP_DEPTH_OVER:
4605 case STEP_DEPTH_OUT:
4607 case STEP_DEPTH_INTO:
4610 g_assert_not_reached ();
4616 process_single_step_inner (DebuggerTlsData *tls)
4621 int il_offset, suspend_policy;
4624 MonoContext *ctx = &tls->restore_ctx;
4626 MonoSeqPointInfo *info;
4628 ip = MONO_CONTEXT_GET_IP (ctx);
4630 /* Skip the instruction causing the single step */
4631 mono_arch_skip_single_step (ctx);
4633 if (suspend_count > 0) {
4634 process_suspend (tls, ctx);
4639 // FIXME: A suspend race
4642 if (mono_thread_internal_current () != ss_req->thread)
4645 if (log_level > 0) {
4646 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4648 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));
4651 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4653 g_assert (ji->method);
4655 if (ji->method->wrapper_type && ji->method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4660 * Stopping in memset makes half-initialized vtypes visible.
4661 * Stopping in memcpy makes half-copied vtypes visible.
4663 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
4667 * The ip points to the instruction causing the single step event, which is before
4668 * the offset recorded in the seq point map, so find the next seq point after ip.
4670 sp = find_next_seq_point_for_native_offset (domain, ji->method, (guint8*)ip - (guint8*)ji->code_start, &info);
4673 il_offset = sp->il_offset;
4675 // FIXME: No tests fail if this is disabled
4677 if (ss_req->size == STEP_SIZE_LINE) {
4681 /* Step until a different source line is reached */
4682 MonoDebugMethodInfo *minfo;
4684 minfo = mono_debug_lookup_method (ji->method);
4687 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4689 if (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line) {
4690 mono_debug_free_source_location (loc);
4695 * Step until we reach a location with line number info,
4696 * otherwise the client can't show a location.
4697 * This can happen for example with statics initialized inline
4698 * outside of a cctor.
4703 ss_req->last_method = ji->method;
4704 ss_req->last_line = loc->row;
4705 mono_debug_free_source_location (loc);
4711 /* Start single stepping again from the current sequence point */
4712 ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4714 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
4715 (ji->method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4716 !strcmp (ji->method->name, ".cctor"))
4719 // FIXME: Has to lock earlier
4721 reqs = g_ptr_array_new ();
4723 mono_loader_lock ();
4725 g_ptr_array_add (reqs, ss_req->req);
4727 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4729 g_ptr_array_free (reqs, TRUE);
4731 mono_loader_unlock ();
4733 process_event (EVENT_KIND_STEP, ji->method, il_offset, ctx, events, suspend_policy);
4737 process_single_step (void)
4739 process_signal_event (process_single_step_inner);
4743 * mono_debugger_agent_single_step_event:
4745 * Called from a signal handler to handle a single step event.
4748 mono_debugger_agent_single_step_event (void *sigctx)
4750 /* Resume to process_single_step through the signal context */
4752 // FIXME: Since step out/over is implemented using step in, the step in case should
4753 // be as fast as possible. Move the relevant code from process_single_step_inner ()
4756 if (GetCurrentThreadId () == debugger_thread_id) {
4758 * This could happen despite our best effors when the runtime calls
4759 * assembly/type resolve hooks.
4760 * FIXME: Breakpoints too.
4764 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4765 mono_arch_skip_single_step (&ctx);
4766 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4770 resume_from_signal_handler (sigctx, process_single_step);
4774 debugger_agent_single_step_from_context (MonoContext *ctx)
4776 DebuggerTlsData *tls;
4777 MonoContext orig_restore_ctx;
4779 tls = mono_native_tls_get_value (debugger_tls_id);
4782 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4783 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4784 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4786 process_single_step_inner (tls);
4788 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4789 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4793 debugger_agent_breakpoint_from_context (MonoContext *ctx)
4795 DebuggerTlsData *tls;
4796 MonoContext orig_restore_ctx;
4798 tls = mono_native_tls_get_value (debugger_tls_id);
4800 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4801 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4803 process_breakpoint_inner (tls);
4805 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4806 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4810 * start_single_stepping:
4812 * Turn on single stepping. Can be called multiple times, for example,
4813 * by a single step event request + a suspend.
4816 start_single_stepping (void)
4818 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4819 int val = InterlockedIncrement (&ss_count);
4822 mono_arch_start_single_stepping ();
4824 if (ss_req != NULL && ss_invoke_addr == NULL) {
4825 DebuggerTlsData *tls;
4827 mono_loader_lock ();
4829 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
4830 ss_invoke_addr = tls->invoke_addr;
4832 mono_loader_unlock ();
4835 g_assert_not_reached ();
4840 stop_single_stepping (void)
4842 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4843 int val = InterlockedDecrement (&ss_count);
4846 mono_arch_stop_single_stepping ();
4848 g_assert_not_reached ();
4855 * Stop the single stepping operation given by SS_REQ.
4858 ss_stop (SingleStepReq *ss_req)
4863 for (l = ss_req->bps; l; l = l->next) {
4864 clear_breakpoint (l->data);
4866 g_slist_free (ss_req->bps);
4870 if (ss_req->global) {
4871 stop_single_stepping ();
4872 ss_req->global = FALSE;
4879 * Start the single stepping operation given by SS_REQ from the sequence point SP.
4880 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
4881 * belong to the same thread as CTX.
4884 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
4886 int i, j, frame_index;
4889 gboolean enable_global = FALSE;
4891 /* Stop the previous operation */
4895 * Implement single stepping using breakpoints if possible.
4897 if (step_to_catch) {
4898 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
4899 ss_req->bps = g_slist_append (ss_req->bps, bp);
4903 if ((!sp || sp->next_len == 0 || ss_req->depth == STEP_DEPTH_OUT || ss_req->depth == STEP_DEPTH_OVER) && ctx) {
4904 /* Need parent frames */
4905 if (!tls->context.valid)
4906 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4907 compute_frame_info (tls->thread, tls);
4911 * Find the first sequence point in the current or in a previous frame which
4912 * is not the last in its method.
4914 if (ss_req->depth == STEP_DEPTH_OUT) {
4915 /* Ignore seq points in current method */
4916 while (frame_index < tls->frame_count) {
4917 StackFrame *frame = tls->frames [frame_index];
4919 method = frame->method;
4920 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4922 if (sp && sp->next_len != 0)
4925 // There could be method calls before the next seq point in the caller when using nested calls
4926 //enable_global = TRUE;
4928 while (sp && sp->next_len == 0) {
4930 if (frame_index < tls->frame_count) {
4931 StackFrame *frame = tls->frames [frame_index];
4933 method = frame->method;
4934 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4940 if (sp && sp->next_len > 0) {
4941 for (i = 0; i < sp->next_len; ++i) {
4942 next_sp = &info->seq_points [sp->next [i]];
4944 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
4945 ss_req->bps = g_slist_append (ss_req->bps, bp);
4949 if (ss_req->depth == STEP_DEPTH_OVER) {
4950 /* Need to stop in catch clauses as well */
4951 for (i = 0; i < tls->frame_count; ++i) {
4952 StackFrame *frame = tls->frames [i];
4955 MonoJitInfo *jinfo = frame->ji;
4956 for (j = 0; j < jinfo->num_clauses; ++j) {
4957 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
4959 sp = find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL);
4961 bp = set_breakpoint (frame->method, sp->il_offset, ss_req->req, NULL);
4962 ss_req->bps = g_slist_append (ss_req->bps, bp);
4970 if (ss_req->depth == STEP_DEPTH_INTO) {
4971 /* Enable global stepping so we stop at method entry too */
4972 enable_global = TRUE;
4976 * The ctx/frame info computed above will become invalid when we continue.
4978 tls->context.valid = FALSE;
4979 tls->async_state.valid = FALSE;
4980 invalidate_frames (tls);
4983 if (enable_global) {
4984 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
4985 ss_req->global = TRUE;
4986 start_single_stepping ();
4987 } else if (!ss_req->bps) {
4988 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
4989 ss_req->global = TRUE;
4990 start_single_stepping ();
4992 ss_req->global = FALSE;
4997 * Start single stepping of thread THREAD
5000 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
5002 DebuggerTlsData *tls;
5003 MonoSeqPointInfo *info = NULL;
5004 SeqPoint *sp = NULL;
5005 MonoMethod *method = NULL;
5006 MonoDebugMethodInfo *minfo;
5007 gboolean step_to_catch = FALSE;
5009 if (suspend_count == 0)
5010 return ERR_NOT_SUSPENDED;
5012 wait_for_suspend ();
5014 // FIXME: Multiple requests
5016 DEBUG (0, fprintf (log_file, "Received a single step request while the previous one was still active.\n"));
5017 return ERR_NOT_IMPLEMENTED;
5020 DEBUG (1, fprintf (log_file, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
5022 ss_req = g_new0 (SingleStepReq, 1);
5024 ss_req->thread = thread;
5025 ss_req->size = size;
5026 ss_req->depth = depth;
5029 mono_loader_lock ();
5030 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5031 mono_loader_unlock ();
5033 g_assert (tls->context.valid);
5034 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5036 if (tls->has_catch_ctx) {
5038 StackFrameInfo frame;
5039 MonoContext new_ctx;
5040 MonoLMF *lmf = NULL;
5043 * We are stopped at a throw site. Stepping should go to the catch site.
5046 /* Find the the jit info for the catch context */
5047 res = mono_find_jit_info_ext (mono_domain_get (), thread->jit_data, NULL, &tls->catch_ctx, &new_ctx, NULL, &lmf, NULL, &frame);
5049 g_assert (frame.type == FRAME_TYPE_MANAGED);
5052 * Find the seq point corresponding to the landing site ip, which is the first seq
5055 sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
5058 method = frame.method;
5060 step_to_catch = TRUE;
5061 /* This make sure the seq point is not skipped by process_single_step () */
5062 ss_req->last_sp = NULL;
5065 if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
5068 /* Compute the initial line info */
5069 compute_frame_info (thread, tls);
5071 if (tls->frame_count) {
5072 frame = tls->frames [0];
5074 ss_req->last_method = frame->method;
5075 ss_req->last_line = -1;
5077 minfo = mono_debug_lookup_method (frame->method);
5078 if (minfo && frame->il_offset != -1) {
5079 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
5082 ss_req->last_line = loc->row;
5089 if (!step_to_catch) {
5092 compute_frame_info (thread, tls);
5094 if (tls->frame_count) {
5095 frame = tls->frames [0];
5097 if (!method && frame->il_offset != -1) {
5098 /* FIXME: Sort the table and use a binary search */
5099 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5101 method = frame->method;
5106 ss_start (ss_req, method, sp, info, &tls->context.ctx, tls, step_to_catch);
5112 ss_destroy (SingleStepReq *req)
5115 g_assert (ss_req == req);
5124 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5127 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5133 if (!agent_config.enabled)
5136 mono_loader_lock ();
5137 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5138 mono_loader_unlock ();
5141 ei.category = category ? mono_string_to_utf8 (category) : NULL;
5142 ei.message = message ? mono_string_to_utf8 (message) : NULL;
5144 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5146 g_free (ei.category);
5147 g_free (ei.message);
5151 mono_debugger_agent_debug_log_is_enabled (void)
5153 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5154 return agent_config.enabled;
5157 #ifdef PLATFORM_ANDROID
5159 mono_debugger_agent_unhandled_exception (MonoException *exc)
5168 memset (&ei, 0, sizeof (EventInfo));
5169 ei.exc = (MonoObject*)exc;
5171 mono_loader_lock ();
5172 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5173 mono_loader_unlock ();
5175 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5180 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5181 MonoContext *catch_ctx)
5183 int i, j, suspend_policy;
5185 MonoJitInfo *ji, *catch_ji;
5187 DebuggerTlsData *tls = NULL;
5189 if (thread_to_tls != NULL) {
5190 MonoInternalThread *thread = mono_thread_internal_current ();
5192 mono_loader_lock ();
5193 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5194 mono_loader_unlock ();
5196 if (tls && tls->abort_requested)
5198 if (tls && tls->disable_breakpoints)
5202 memset (&ei, 0, sizeof (EventInfo));
5204 /* Just-In-Time debugging */
5206 if (agent_config.onuncaught && !inited) {
5207 finish_agent_init (FALSE);
5210 * Send an unsolicited EXCEPTION event with a dummy request id.
5212 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5213 ei.exc = (MonoObject*)exc;
5214 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5217 } else if (agent_config.onthrow && !inited) {
5219 gboolean found = FALSE;
5221 for (l = agent_config.onthrow; l; l = l->next) {
5222 char *ex_type = l->data;
5223 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5225 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5232 finish_agent_init (FALSE);
5235 * Send an unsolicited EXCEPTION event with a dummy request id.
5237 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5238 ei.exc = (MonoObject*)exc;
5239 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5247 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5249 catch_ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5253 ei.exc = (MonoObject*)exc;
5254 ei.caught = catch_ctx != NULL;
5256 mono_loader_lock ();
5258 /* Treat exceptions which are caught in non-user code as unhandled */
5259 for (i = 0; i < event_requests->len; ++i) {
5260 EventRequest *req = g_ptr_array_index (event_requests, i);
5261 if (req->event_kind != EVENT_KIND_EXCEPTION)
5264 for (j = 0; j < req->nmodifiers; ++j) {
5265 Modifier *mod = &req->modifiers [j];
5267 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5269 gboolean found = FALSE;
5270 MonoAssembly **assemblies = mod->data.assemblies;
5273 for (k = 0; assemblies [k]; ++k)
5274 if (assemblies [k] == catch_ji->method->klass->image->assembly)
5283 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5284 mono_loader_unlock ();
5286 if (tls && ei.caught && catch_ctx) {
5287 tls->catch_ctx = *catch_ctx;
5288 tls->has_catch_ctx = TRUE;
5291 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5294 tls->has_catch_ctx = FALSE;
5298 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5300 DebuggerTlsData *tls;
5305 tls = mono_native_tls_get_value (debugger_tls_id);
5310 * We're about to invoke an exception filter during the first pass of exception handling.
5312 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5313 * 'orig_ctx' is the context where the exception has been thrown.
5316 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5318 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5319 * the call site (line 37) and then continue to Main(), but it would never
5320 * include the throw site (line 32).
5322 * Since exception filters are invoked during the first pass of exception handling,
5323 * the stack frames of the throw site are still intact, so we should include them
5326 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5328 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5329 * but report the location of the 'throw' to the user.
5333 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5337 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5339 DebuggerTlsData *tls;
5344 tls = mono_native_tls_get_value (debugger_tls_id);
5348 tls->filter_state.valid = FALSE;
5352 * buffer_add_value_full:
5354 * Add the encoding of the value at ADDR described by T to the buffer.
5355 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5359 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5365 g_assert (*(void**)addr);
5366 addr = *(void**)addr;
5371 case MONO_TYPE_BOOLEAN:
5374 case MONO_TYPE_CHAR:
5394 case MONO_TYPE_VOID:
5395 buffer_add_byte (buf, t->type);
5397 case MONO_TYPE_BOOLEAN:
5400 buffer_add_byte (buf, t->type);
5401 buffer_add_int (buf, *(gint8*)addr);
5403 case MONO_TYPE_CHAR:
5406 buffer_add_byte (buf, t->type);
5407 buffer_add_int (buf, *(gint16*)addr);
5412 buffer_add_byte (buf, t->type);
5413 buffer_add_int (buf, *(gint32*)addr);
5418 buffer_add_byte (buf, t->type);
5419 buffer_add_long (buf, *(gint64*)addr);
5423 /* Treat it as a vtype */
5425 case MONO_TYPE_PTR: {
5426 gssize val = *(gssize*)addr;
5428 buffer_add_byte (buf, t->type);
5429 buffer_add_long (buf, val);
5433 case MONO_TYPE_STRING:
5434 case MONO_TYPE_SZARRAY:
5435 case MONO_TYPE_OBJECT:
5436 case MONO_TYPE_CLASS:
5437 case MONO_TYPE_ARRAY:
5438 obj = *(MonoObject**)addr;
5441 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5443 if (obj->vtable->klass->valuetype) {
5444 t = &obj->vtable->klass->byval_arg;
5445 addr = mono_object_unbox (obj);
5447 } else if (obj->vtable->klass->rank) {
5448 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5449 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5450 buffer_add_byte (buf, MONO_TYPE_CLASS);
5452 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5454 buffer_add_objid (buf, obj);
5458 case MONO_TYPE_VALUETYPE: {
5462 MonoClass *klass = mono_class_from_mono_type (t);
5464 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5465 buffer_add_byte (buf, klass->enumtype);
5466 buffer_add_typeid (buf, domain, klass);
5470 while ((f = mono_class_get_fields (klass, &iter))) {
5471 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5473 if (mono_field_is_deleted (f))
5477 buffer_add_int (buf, nfields);
5480 while ((f = mono_class_get_fields (klass, &iter))) {
5481 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5483 if (mono_field_is_deleted (f))
5485 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE);
5489 case MONO_TYPE_GENERICINST:
5490 if (mono_type_generic_inst_is_valuetype (t)) {
5502 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5504 buffer_add_value_full (buf, t, addr, domain, FALSE);
5508 obj_is_of_type (MonoObject *obj, MonoType *t)
5510 MonoClass *klass = obj->vtable->klass;
5511 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5512 if (klass == mono_defaults.transparent_proxy_class) {
5513 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5514 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5524 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5527 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5531 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5532 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5533 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5534 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5535 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
5536 char *name = mono_type_full_name (t);
5537 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5539 return ERR_INVALID_ARGUMENT;
5543 case MONO_TYPE_BOOLEAN:
5544 *(guint8*)addr = decode_int (buf, &buf, limit);
5546 case MONO_TYPE_CHAR:
5547 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5550 *(gint8*)addr = decode_int (buf, &buf, limit);
5553 *(guint8*)addr = decode_int (buf, &buf, limit);
5556 *(gint16*)addr = decode_int (buf, &buf, limit);
5559 *(guint16*)addr = decode_int (buf, &buf, limit);
5562 *(gint32*)addr = decode_int (buf, &buf, limit);
5565 *(guint32*)addr = decode_int (buf, &buf, limit);
5568 *(gint64*)addr = decode_long (buf, &buf, limit);
5571 *(guint64*)addr = decode_long (buf, &buf, limit);
5574 *(guint32*)addr = decode_int (buf, &buf, limit);
5577 *(guint64*)addr = decode_long (buf, &buf, limit);
5580 /* We send these as I8, so we get them back as such */
5581 g_assert (type == MONO_TYPE_I8);
5582 *(gssize*)addr = decode_long (buf, &buf, limit);
5584 case MONO_TYPE_GENERICINST:
5585 if (MONO_TYPE_ISSTRUCT (t)) {
5586 /* The client sends these as a valuetype */
5594 /* We send these as vtypes, so we get them back as such */
5595 g_assert (type == MONO_TYPE_VALUETYPE);
5598 case MONO_TYPE_VALUETYPE: {
5599 gboolean is_enum = decode_byte (buf, &buf, limit);
5603 gpointer iter = NULL;
5606 /* Enums are sent as a normal vtype */
5608 return ERR_NOT_IMPLEMENTED;
5609 klass = decode_typeid (buf, &buf, limit, &d, &err);
5613 if (klass != mono_class_from_mono_type (t))
5614 return ERR_INVALID_ARGUMENT;
5616 nfields = decode_int (buf, &buf, limit);
5617 while ((f = mono_class_get_fields (klass, &iter))) {
5618 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5620 if (mono_field_is_deleted (f))
5622 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5627 g_assert (nfields == 0);
5632 if (MONO_TYPE_IS_REFERENCE (t)) {
5633 if (type == MONO_TYPE_OBJECT) {
5634 int objid = decode_objid (buf, &buf, limit);
5638 err = get_object (objid, (MonoObject**)&obj);
5643 if (!obj_is_of_type (obj, t)) {
5644 DEBUG (1, fprintf (log_file, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name));
5645 return ERR_INVALID_ARGUMENT;
5648 if (obj && obj->vtable->domain != domain)
5649 return ERR_INVALID_ARGUMENT;
5651 mono_gc_wbarrier_generic_store (addr, obj);
5652 } else if (type == VALUE_TYPE_ID_NULL) {
5653 *(MonoObject**)addr = NULL;
5655 return ERR_INVALID_ARGUMENT;
5669 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5672 int type = decode_byte (buf, &buf, limit);
5674 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
5675 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
5676 guint8 *nullable_buf;
5679 * First try decoding it as a Nullable`1
5681 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5686 * Then try decoding as a primitive value or null.
5688 if (targ->type == type) {
5689 nullable_buf = g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
5690 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
5692 g_free (nullable_buf);
5695 mono_nullable_init (addr, mono_value_box (domain, mono_class_from_mono_type (targ), nullable_buf), mono_class_from_mono_type (t));
5696 g_free (nullable_buf);
5699 } else if (type == VALUE_TYPE_ID_NULL) {
5700 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
5706 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5710 add_var (Buffer *buf, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
5717 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5718 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5721 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
5722 reg_val = mono_arch_context_get_int_reg (ctx, reg);
5724 buffer_add_value_full (buf, t, ®_val, domain, as_vtype);
5726 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5727 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5728 addr += (gint32)var->offset;
5730 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5732 buffer_add_value_full (buf, t, addr, domain, as_vtype);
5734 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5738 g_assert_not_reached ();
5743 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
5749 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5750 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5752 if (MONO_TYPE_IS_REFERENCE (t))
5753 size = sizeof (gpointer);
5755 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
5758 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
5759 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
5761 gboolean is_signed = FALSE;
5763 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
5768 v = is_signed ? *(gint8*)val : *(guint8*)val;
5771 v = is_signed ? *(gint16*)val : *(guint16*)val;
5774 v = is_signed ? *(gint32*)val : *(guint32*)val;
5777 v = is_signed ? *(gint64*)val : *(guint64*)val;
5780 g_assert_not_reached ();
5786 /* Set value on the stack or in the return ctx */
5787 if (reg_locations [reg]) {
5788 /* Saved on the stack */
5789 DEBUG (1, fprintf (log_file, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v));
5790 *(reg_locations [reg]) = v;
5793 DEBUG (1, fprintf (log_file, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v));
5794 mono_arch_context_set_int_reg (restore_ctx, reg, v);
5797 // FIXME: Move these to mono-context.h/c.
5798 mono_arch_context_set_int_reg (ctx, reg, v);
5800 // FIXME: Can't set registers, so we disable linears
5805 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5806 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5807 addr += (gint32)var->offset;
5809 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5812 addr = *(guint8**)addr;
5818 // FIXME: Write barriers
5819 mono_gc_memmove (addr, val, size);
5821 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5825 g_assert_not_reached ();
5830 clear_event_request (int req_id, int etype)
5834 mono_loader_lock ();
5835 for (i = 0; i < event_requests->len; ++i) {
5836 EventRequest *req = g_ptr_array_index (event_requests, i);
5838 if (req->id == req_id && req->event_kind == etype) {
5839 if (req->event_kind == EVENT_KIND_BREAKPOINT)
5840 clear_breakpoint (req->info);
5841 if (req->event_kind == EVENT_KIND_STEP)
5842 ss_destroy (req->info);
5843 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
5844 clear_breakpoint (req->info);
5845 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
5846 clear_breakpoint (req->info);
5847 g_ptr_array_remove_index_fast (event_requests, i);
5852 mono_loader_unlock ();
5856 event_req_matches_assembly (EventRequest *req, MonoAssembly *assembly)
5858 if (req->event_kind == EVENT_KIND_BREAKPOINT)
5859 return breakpoint_matches_assembly (req->info, assembly);
5863 for (i = 0; i < req->nmodifiers; ++i) {
5864 Modifier *m = &req->modifiers [i];
5866 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
5868 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
5869 for (j = 0; m->data.assemblies [j]; ++j)
5870 if (m->data.assemblies [j] == assembly)
5880 * clear_event_requests_for_assembly:
5882 * Clear all events requests which reference ASSEMBLY.
5885 clear_event_requests_for_assembly (MonoAssembly *assembly)
5890 mono_loader_lock ();
5894 for (i = 0; i < event_requests->len; ++i) {
5895 EventRequest *req = g_ptr_array_index (event_requests, i);
5897 if (event_req_matches_assembly (req, assembly)) {
5898 clear_event_request (req->id, req->event_kind);
5904 mono_loader_unlock ();
5908 * type_comes_from_assembly:
5910 * GHRFunc that returns TRUE if klass comes from assembly
5913 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
5915 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
5919 * clear_types_for_assembly:
5921 * Clears types from loaded_classes for a given assembly
5924 clear_types_for_assembly (MonoAssembly *assembly)
5926 MonoDomain *domain = mono_domain_get ();
5927 AgentDomainInfo *info = NULL;
5929 mono_loader_lock ();
5930 info = get_agent_domain_info (domain);
5931 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
5932 mono_loader_unlock ();
5936 add_thread (gpointer key, gpointer value, gpointer user_data)
5938 MonoInternalThread *thread = value;
5939 Buffer *buf = user_data;
5941 buffer_add_objid (buf, (MonoObject*)thread);
5945 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
5947 guint8 *end = invoke->endp;
5950 MonoMethodSignature *sig;
5953 MonoObject *this, *res, *exc;
5956 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5959 MonoStopwatch watch;
5961 if (invoke->method) {
5963 * Invoke this method directly, currently only Environment.Exit () is supported.
5966 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>"));
5967 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
5968 g_assert_not_reached ();
5971 m = decode_methodid (p, &p, end, &domain, &err);
5974 sig = mono_method_signature (m);
5976 if (m->klass->valuetype)
5977 this_buf = g_alloca (mono_class_instance_size (m->klass));
5979 this_buf = g_alloca (sizeof (MonoObject*));
5980 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
5981 /* Should be null */
5982 int type = decode_byte (p, &p, end);
5983 if (type != VALUE_TYPE_ID_NULL)
5984 return ERR_INVALID_ARGUMENT;
5985 memset (this_buf, 0, mono_class_instance_size (m->klass));
5987 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
5992 if (!m->klass->valuetype)
5993 this = *(MonoObject**)this_buf;
5997 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>"));
5999 if (this && this->vtable->domain != domain)
6002 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
6003 if (!strcmp (m->name, ".ctor")) {
6004 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
6005 return ERR_INVALID_ARGUMENT;
6007 this = mono_object_new (domain, m->klass);
6009 return ERR_INVALID_ARGUMENT;
6013 if (this && !obj_is_of_type (this, &m->klass->byval_arg))
6014 return ERR_INVALID_ARGUMENT;
6016 nargs = decode_int (p, &p, end);
6017 if (nargs != sig->param_count)
6018 return ERR_INVALID_ARGUMENT;
6019 /* Use alloca to get gc tracking */
6020 arg_buf = g_alloca (nargs * sizeof (gpointer));
6021 memset (arg_buf, 0, nargs * sizeof (gpointer));
6022 args = g_alloca (nargs * sizeof (gpointer));
6023 for (i = 0; i < nargs; ++i) {
6024 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6025 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6029 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6032 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6033 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6036 args [i] = arg_buf [i];
6043 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6044 tls->disable_breakpoints = TRUE;
6046 tls->disable_breakpoints = FALSE;
6049 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6051 /* FIXME: Move this to arch specific code */
6052 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6053 if (invoke->has_ctx) {
6056 lmf_addr = mono_get_lmf_addr ();
6059 memset (&ext, 0, sizeof (ext));
6061 ext.lmf.previous_lmf = *(lmf_addr);
6062 /* Mark that this is a MonoLMFExt */
6063 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6064 ext.lmf.rsp = (gssize)&ext;
6065 #elif defined(TARGET_X86)
6066 ext.lmf.previous_lmf = (gsize)*(lmf_addr);
6067 /* Mark that this is a MonoLMFExt */
6068 ext.lmf.previous_lmf = (gsize)(gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6069 ext.lmf.ebp = (gssize)&ext;
6070 #elif defined(TARGET_ARM)
6071 ext.lmf.previous_lmf = *(lmf_addr);
6072 /* Mark that this is a MonoLMFExt */
6073 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6074 ext.lmf.sp = (gssize)&ext;
6075 #elif defined(TARGET_POWERPC)
6076 ext.lmf.previous_lmf = *(lmf_addr);
6077 /* Mark that this is a MonoLMFExt */
6078 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6079 ext.lmf.ebp = (gssize)&ext;
6080 #elif defined(TARGET_S390X)
6081 ext.lmf.previous_lmf = *(lmf_addr);
6082 /* Mark that this is a MonoLMFExt */
6083 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6084 ext.lmf.ebp = (gssize)&ext;
6085 #elif defined(TARGET_MIPS)
6086 ext.lmf.previous_lmf = *(lmf_addr);
6087 /* Mark that this is a MonoLMFExt */
6088 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6089 ext.lmf.iregs [mips_sp] = (gssize)&ext;
6091 g_assert_not_reached ();
6094 ext.debugger_invoke = TRUE;
6095 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6097 mono_set_lmf ((MonoLMF*)&ext);
6101 mono_stopwatch_start (&watch);
6102 if (m->klass->valuetype)
6103 res = mono_runtime_invoke (m, this_buf, args, &exc);
6105 res = mono_runtime_invoke (m, this, args, &exc);
6106 mono_stopwatch_stop (&watch);
6107 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)));
6109 buffer_add_byte (buf, 0);
6110 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6112 buffer_add_byte (buf, 1);
6113 if (sig->ret->type == MONO_TYPE_VOID) {
6114 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
6115 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
6118 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6119 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6120 buffer_add_value (buf, sig->ret, &res, domain);
6121 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6122 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6123 MonoClass *k = mono_class_from_mono_type (sig->ret);
6124 guint8 *nullable_buf = g_alloca (mono_class_value_size (k, NULL));
6126 g_assert (nullable_buf);
6127 mono_nullable_init (nullable_buf, res, k);
6128 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6131 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6138 tls->disable_breakpoints = FALSE;
6140 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6141 if (invoke->has_ctx)
6142 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
6146 // FIXME: byref arguments
6154 * Invoke the method given by tls->pending_invoke in the current thread.
6157 invoke_method (void)
6159 DebuggerTlsData *tls;
6164 static void (*restore_context) (void *);
6165 MonoContext restore_ctx;
6168 if (!restore_context)
6169 restore_context = mono_get_restore_context ();
6171 tls = mono_native_tls_get_value (debugger_tls_id);
6175 * Store the `InvokeData *' in `tls->invoke' until we're done with
6176 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6179 mono_loader_lock ();
6181 invoke = tls->pending_invoke;
6183 tls->pending_invoke = NULL;
6185 invoke->last_invoke = tls->invoke;
6186 tls->invoke = invoke;
6188 mono_loader_unlock ();
6190 tls->frames_up_to_date = FALSE;
6196 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6197 buffer_init (&buf, 128);
6200 /* Fail the other invokes as well */
6202 err = do_invoke_method (tls, &buf, invoke, p, &p);
6205 /* Start suspending before sending the reply */
6206 if (mindex == invoke->nmethods - 1) {
6207 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6208 for (i = 0; i < invoke->suspend_count; ++i)
6213 send_reply_packet (id, err, &buf);
6218 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6220 if (invoke->has_ctx)
6221 save_thread_context (&restore_ctx);
6223 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6224 g_assert (tls->resume_count);
6225 tls->resume_count -= invoke->suspend_count;
6228 DEBUG (1, fprintf (log_file, "[%p] Invoke finished, resume_count = %d.\n", (gpointer)GetCurrentThreadId (), tls->resume_count));
6231 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6233 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
6234 * after the mono_runtime_invoke() already returned, but it doesn't matter
6235 * because we reset the abort here.
6238 mono_loader_lock ();
6240 if (tls->abort_requested)
6241 mono_thread_internal_reset_abort (tls->thread);
6243 tls->invoke = tls->invoke->last_invoke;
6244 tls->abort_requested = FALSE;
6246 mono_loader_unlock ();
6255 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6257 MonoThread *thread = value;
6258 DebuggerTlsData *tls;
6261 mono_loader_lock ();
6262 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6264 res = tls->really_suspended;
6265 mono_loader_unlock ();
6271 get_source_files_for_type (MonoClass *klass)
6273 gpointer iter = NULL;
6275 MonoDebugSourceInfo *sinfo;
6279 files = g_ptr_array_new ();
6281 while ((method = mono_class_get_methods (klass, &iter))) {
6282 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6283 GPtrArray *source_file_list;
6286 mono_debug_symfile_get_line_numbers_full (minfo, NULL, &source_file_list, NULL, NULL, NULL, NULL, NULL);
6287 for (j = 0; j < source_file_list->len; ++j) {
6288 sinfo = g_ptr_array_index (source_file_list, j);
6289 for (i = 0; i < files->len; ++i)
6290 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6292 if (i == files->len)
6293 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6295 g_ptr_array_free (source_file_list, TRUE);
6303 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6306 case CMD_VM_VERSION: {
6307 char *build_info, *version;
6309 build_info = mono_get_runtime_build_info ();
6310 version = g_strdup_printf ("mono %s", build_info);
6312 buffer_add_string (buf, version); /* vm version */
6313 buffer_add_int (buf, MAJOR_VERSION);
6314 buffer_add_int (buf, MINOR_VERSION);
6315 g_free (build_info);
6319 case CMD_VM_SET_PROTOCOL_VERSION: {
6320 major_version = decode_int (p, &p, end);
6321 minor_version = decode_int (p, &p, end);
6322 protocol_version_set = TRUE;
6323 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
6326 case CMD_VM_ALL_THREADS: {
6328 mono_loader_lock ();
6329 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6330 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6331 mono_loader_unlock ();
6334 case CMD_VM_SUSPEND:
6336 wait_for_suspend ();
6339 if (suspend_count == 0)
6340 return ERR_NOT_SUSPENDED;
6342 clear_suspended_objs ();
6344 case CMD_VM_DISPOSE:
6345 /* Clear all event requests */
6346 mono_loader_lock ();
6347 while (event_requests->len > 0) {
6348 EventRequest *req = g_ptr_array_index (event_requests, 0);
6350 clear_event_request (req->id, req->event_kind);
6352 mono_loader_unlock ();
6354 while (suspend_count > 0)
6356 disconnected = TRUE;
6357 vm_start_event_sent = FALSE;
6360 MonoInternalThread *thread;
6361 DebuggerTlsData *tls;
6362 MonoClass *env_class;
6363 MonoMethod *exit_method = NULL;
6367 exit_code = decode_int (p, &p, end);
6369 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6371 /* Have to send a reply before exiting */
6372 send_reply_packet (id, 0, buf);
6374 /* Clear all event requests */
6375 mono_loader_lock ();
6376 while (event_requests->len > 0) {
6377 EventRequest *req = g_ptr_array_index (event_requests, 0);
6379 clear_event_request (req->id, req->event_kind);
6381 mono_loader_unlock ();
6384 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6385 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6386 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6387 * better than doing the shutdown ourselves, since it avoids various races.
6391 wait_for_suspend ();
6393 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6394 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
6396 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6399 mono_loader_lock ();
6400 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6401 mono_loader_unlock ();
6403 if (thread && exit_method) {
6404 mono_loader_lock ();
6405 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6406 mono_loader_unlock ();
6408 args = g_new0 (gpointer, 1);
6409 args [0] = g_malloc (sizeof (int));
6410 *(int*)(args [0]) = exit_code;
6412 tls->pending_invoke = g_new0 (InvokeData, 1);
6413 tls->pending_invoke->method = exit_method;
6414 tls->pending_invoke->args = args;
6415 tls->pending_invoke->nmethods = 1;
6417 while (suspend_count > 0)
6421 * No thread found, do it ourselves.
6422 * FIXME: This can race with normal shutdown etc.
6424 while (suspend_count > 0)
6427 mono_runtime_set_shutting_down ();
6429 mono_threads_set_shutting_down ();
6431 /* Suspend all managed threads since the runtime is going away */
6432 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
6433 mono_thread_suspend_all_other_threads ();
6434 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
6435 mono_runtime_quit ();
6436 transport_close2 ();
6437 DEBUG(1, fprintf (log_file, "Exiting...\n"));
6443 case CMD_VM_INVOKE_METHOD:
6444 case CMD_VM_INVOKE_METHODS: {
6445 int objid = decode_objid (p, &p, end);
6447 DebuggerTlsData *tls;
6448 int i, count, err, flags, nmethods;
6450 err = get_object (objid, (MonoObject**)&thread);
6454 flags = decode_int (p, &p, end);
6456 if (command == CMD_VM_INVOKE_METHODS)
6457 nmethods = decode_int (p, &p, end);
6461 // Wait for suspending if it already started
6463 wait_for_suspend ();
6464 if (!is_suspended ())
6465 return ERR_NOT_SUSPENDED;
6467 mono_loader_lock ();
6468 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6469 mono_loader_unlock ();
6472 if (!tls->really_suspended)
6473 /* The thread is still running native code, can't do invokes */
6474 return ERR_NOT_SUSPENDED;
6477 * Store the invoke data into tls, the thread will execute it after it is
6480 if (tls->pending_invoke)
6481 return ERR_NOT_SUSPENDED;
6482 tls->pending_invoke = g_new0 (InvokeData, 1);
6483 tls->pending_invoke->id = id;
6484 tls->pending_invoke->flags = flags;
6485 tls->pending_invoke->p = g_malloc (end - p);
6486 memcpy (tls->pending_invoke->p, p, end - p);
6487 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
6488 tls->pending_invoke->suspend_count = suspend_count;
6489 tls->pending_invoke->nmethods = nmethods;
6491 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
6492 resume_thread (THREAD_TO_INTERNAL (thread));
6495 count = suspend_count;
6496 for (i = 0; i < count; ++i)
6501 case CMD_VM_ABORT_INVOKE: {
6502 int objid = decode_objid (p, &p, end);
6504 DebuggerTlsData *tls;
6507 err = get_object (objid, (MonoObject**)&thread);
6511 invoke_id = decode_int (p, &p, end);
6513 mono_loader_lock ();
6514 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6517 if (tls->abort_requested) {
6518 mono_loader_unlock ();
6523 * Check whether we're still inside the mono_runtime_invoke() and that it's
6524 * actually the correct invocation.
6526 * Careful, we do not stop the thread that's doing the invocation, so we can't
6527 * inspect its stack. However, invoke_method() also acquires the loader lock
6528 * when it's done, so we're safe here.
6532 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
6533 mono_loader_unlock ();
6534 return ERR_NO_INVOCATION;
6537 tls->abort_requested = TRUE;
6539 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
6540 mono_loader_unlock ();
6544 case CMD_VM_SET_KEEPALIVE: {
6545 int timeout = decode_int (p, &p, end);
6546 agent_config.keepalive = timeout;
6548 #ifndef DISABLE_SOCKET_TRANSPORT
6555 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
6556 GHashTableIter iter, kiter;
6561 char *fname, *basename;
6562 gboolean ignore_case;
6563 GSList *class_list, *l;
6564 GPtrArray *res_classes, *res_domains;
6566 fname = decode_string (p, &p, end);
6567 ignore_case = decode_byte (p, &p, end);
6569 basename = g_path_get_basename (fname);
6571 res_classes = g_ptr_array_new ();
6572 res_domains = g_ptr_array_new ();
6574 mono_loader_lock ();
6575 g_hash_table_iter_init (&iter, domains);
6576 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6577 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
6579 /* Update 'source_file_to_class' cache */
6580 g_hash_table_iter_init (&kiter, info->loaded_classes);
6581 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
6582 if (!g_hash_table_lookup (info->source_files, klass)) {
6583 files = get_source_files_for_type (klass);
6584 g_hash_table_insert (info->source_files, klass, files);
6586 for (i = 0; i < files->len; ++i) {
6587 char *s = g_ptr_array_index (files, i);
6588 char *s2 = g_path_get_basename (s);
6591 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
6593 class_list = g_slist_prepend (class_list, klass);
6594 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
6596 class_list = g_slist_prepend (class_list, klass);
6597 g_hash_table_insert (info->source_file_to_class, s2, class_list);
6600 /* The _ignorecase hash contains the lowercase path */
6601 s3 = strdup_tolower (s2);
6602 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
6604 class_list = g_slist_prepend (class_list, klass);
6605 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
6607 class_list = g_slist_prepend (class_list, klass);
6608 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
6620 s = strdup_tolower (basename);
6621 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
6624 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
6627 for (l = class_list; l; l = l->next) {
6630 g_ptr_array_add (res_classes, klass);
6631 g_ptr_array_add (res_domains, domain);
6634 mono_loader_unlock ();
6639 buffer_add_int (buf, res_classes->len);
6640 for (i = 0; i < res_classes->len; ++i)
6641 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6642 g_ptr_array_free (res_classes, TRUE);
6643 g_ptr_array_free (res_domains, TRUE);
6646 case CMD_VM_GET_TYPES: {
6647 GHashTableIter iter;
6651 gboolean ignore_case;
6652 GPtrArray *res_classes, *res_domains;
6653 MonoTypeNameParse info;
6655 name = decode_string (p, &p, end);
6656 ignore_case = decode_byte (p, &p, end);
6658 if (!mono_reflection_parse_type (name, &info)) {
6660 mono_reflection_free_type_info (&info);
6661 return ERR_INVALID_ARGUMENT;
6664 res_classes = g_ptr_array_new ();
6665 res_domains = g_ptr_array_new ();
6667 mono_loader_lock ();
6668 g_hash_table_iter_init (&iter, domains);
6669 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6671 gboolean type_resolve;
6675 mono_domain_assemblies_lock (domain);
6676 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6680 type_resolve = TRUE;
6681 t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
6683 g_ptr_array_add (res_classes, mono_type_get_class (t));
6684 g_ptr_array_add (res_domains, domain);
6688 mono_domain_assemblies_unlock (domain);
6690 mono_loader_unlock ();
6693 mono_reflection_free_type_info (&info);
6695 buffer_add_int (buf, res_classes->len);
6696 for (i = 0; i < res_classes->len; ++i)
6697 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6698 g_ptr_array_free (res_classes, TRUE);
6699 g_ptr_array_free (res_domains, TRUE);
6704 return ERR_NOT_IMPLEMENTED;
6711 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6717 case CMD_EVENT_REQUEST_SET: {
6719 int i, event_kind, suspend_policy, nmodifiers, mod;
6722 MonoThread *step_thread;
6723 int size = 0, depth = 0, filter = 0, step_thread_id = 0;
6727 event_kind = decode_byte (p, &p, end);
6728 suspend_policy = decode_byte (p, &p, end);
6729 nmodifiers = decode_byte (p, &p, end);
6731 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
6732 req->id = InterlockedIncrement (&event_request_id);
6733 req->event_kind = event_kind;
6734 req->suspend_policy = suspend_policy;
6735 req->nmodifiers = nmodifiers;
6738 for (i = 0; i < nmodifiers; ++i) {
6739 mod = decode_byte (p, &p, end);
6741 req->modifiers [i].kind = mod;
6742 if (mod == MOD_KIND_COUNT) {
6743 req->modifiers [i].data.count = decode_int (p, &p, end);
6744 } else if (mod == MOD_KIND_LOCATION_ONLY) {
6745 method = decode_methodid (p, &p, end, &domain, &err);
6748 location = decode_long (p, &p, end);
6749 } else if (mod == MOD_KIND_STEP) {
6750 step_thread_id = decode_id (p, &p, end);
6751 size = decode_int (p, &p, end);
6752 depth = decode_int (p, &p, end);
6753 if (CHECK_PROTOCOL_VERSION (2, 16))
6754 filter = decode_int (p, &p, end);
6755 req->modifiers [i].data.filter = filter;
6756 } else if (mod == MOD_KIND_THREAD_ONLY) {
6757 int id = decode_id (p, &p, end);
6759 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
6764 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
6765 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
6769 req->modifiers [i].caught = decode_byte (p, &p, end);
6770 req->modifiers [i].uncaught = decode_byte (p, &p, end);
6771 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" : ""));
6773 req->modifiers [i].data.exc_class = exc_class;
6775 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
6777 return ERR_INVALID_ARGUMENT;
6780 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
6781 int n = decode_int (p, &p, end);
6784 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
6785 for (j = 0; j < n; ++j) {
6786 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
6788 g_free (req->modifiers [i].data.assemblies);
6792 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
6793 int n = decode_int (p, &p, end);
6796 modifier = &req->modifiers [i];
6797 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
6798 for (j = 0; j < n; ++j) {
6799 char *s = decode_string (p, &p, end);
6803 s2 = strdup_tolower (s);
6804 g_hash_table_insert (modifier->data.source_files, s2, s2);
6808 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
6809 int n = decode_int (p, &p, end);
6812 modifier = &req->modifiers [i];
6813 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
6814 for (j = 0; j < n; ++j) {
6815 char *s = decode_string (p, &p, end);
6818 g_hash_table_insert (modifier->data.type_names, s, s);
6822 return ERR_NOT_IMPLEMENTED;
6826 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
6829 req->info = set_breakpoint (method, location, req, &error);
6830 if (!mono_error_ok (&error)) {
6832 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
6833 mono_error_cleanup (&error);
6834 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
6836 } else if (req->event_kind == EVENT_KIND_STEP) {
6837 g_assert (step_thread_id);
6839 err = get_object (step_thread_id, (MonoObject**)&step_thread);
6845 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
6850 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
6851 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
6852 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
6853 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
6854 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
6855 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
6857 if (req->nmodifiers) {
6859 return ERR_NOT_IMPLEMENTED;
6863 mono_loader_lock ();
6864 g_ptr_array_add (event_requests, req);
6866 if (agent_config.defer) {
6867 /* Transmit cached data to the client on receipt of the event request */
6868 switch (req->event_kind) {
6869 case EVENT_KIND_APPDOMAIN_CREATE:
6870 /* Emit load events for currently loaded domains */
6871 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
6873 case EVENT_KIND_ASSEMBLY_LOAD:
6874 /* Emit load events for currently loaded assemblies */
6875 mono_assembly_foreach (emit_assembly_load, NULL);
6877 case EVENT_KIND_THREAD_START:
6878 /* Emit start events for currently started threads */
6879 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
6881 case EVENT_KIND_TYPE_LOAD:
6882 /* Emit type load events for currently loaded types */
6883 mono_domain_foreach (send_types_for_domain, NULL);
6889 mono_loader_unlock ();
6891 buffer_add_int (buf, req->id);
6894 case CMD_EVENT_REQUEST_CLEAR: {
6895 int etype = decode_byte (p, &p, end);
6896 int req_id = decode_int (p, &p, end);
6898 // FIXME: Make a faster mapping from req_id to request
6899 mono_loader_lock ();
6900 clear_event_request (req_id, etype);
6901 mono_loader_unlock ();
6904 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
6907 mono_loader_lock ();
6909 while (i < event_requests->len) {
6910 EventRequest *req = g_ptr_array_index (event_requests, i);
6912 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
6913 clear_breakpoint (req->info);
6915 g_ptr_array_remove_index_fast (event_requests, i);
6921 mono_loader_unlock ();
6925 return ERR_NOT_IMPLEMENTED;
6932 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6938 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
6939 buffer_add_domainid (buf, mono_get_root_domain ());
6942 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
6943 domain = decode_domainid (p, &p, end, NULL, &err);
6946 buffer_add_string (buf, domain->friendly_name);
6949 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
6954 domain = decode_domainid (p, &p, end, NULL, &err);
6957 mono_loader_lock ();
6959 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6962 buffer_add_int (buf, count);
6963 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6965 buffer_add_assemblyid (buf, domain, ass);
6967 mono_loader_unlock ();
6970 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
6971 domain = decode_domainid (p, &p, end, NULL, &err);
6975 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
6978 case CMD_APPDOMAIN_GET_CORLIB: {
6979 domain = decode_domainid (p, &p, end, NULL, &err);
6983 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
6986 case CMD_APPDOMAIN_CREATE_STRING: {
6990 domain = decode_domainid (p, &p, end, NULL, &err);
6993 s = decode_string (p, &p, end);
6995 o = mono_string_new (domain, s);
6996 buffer_add_objid (buf, (MonoObject*)o);
6999 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7001 MonoDomain *domain2;
7004 domain = decode_domainid (p, &p, end, NULL, &err);
7007 klass = decode_typeid (p, &p, end, &domain2, &err);
7012 g_assert (domain == domain2);
7014 o = mono_object_new (domain, klass);
7016 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
7020 buffer_add_objid (buf, o);
7024 return ERR_NOT_IMPLEMENTED;
7031 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7037 ass = decode_assemblyid (p, &p, end, &domain, &err);
7042 case CMD_ASSEMBLY_GET_LOCATION: {
7043 buffer_add_string (buf, mono_image_get_filename (ass->image));
7046 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7050 if (ass->image->dynamic) {
7051 buffer_add_id (buf, 0);
7053 token = mono_image_get_entry_point (ass->image);
7055 buffer_add_id (buf, 0);
7057 m = mono_get_method (ass->image, token, NULL);
7058 buffer_add_methodid (buf, domain, m);
7063 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7064 buffer_add_moduleid (buf, domain, ass->image);
7067 case CMD_ASSEMBLY_GET_OBJECT: {
7068 MonoObject *o = (MonoObject*)mono_assembly_get_object (domain, ass);
7069 buffer_add_objid (buf, o);
7072 case CMD_ASSEMBLY_GET_TYPE: {
7073 char *s = decode_string (p, &p, end);
7074 gboolean ignorecase = decode_byte (p, &p, end);
7075 MonoTypeNameParse info;
7077 gboolean type_resolve, res;
7078 MonoDomain *d = mono_domain_get ();
7080 /* This is needed to be able to find referenced assemblies */
7081 res = mono_domain_set (domain, FALSE);
7084 if (!mono_reflection_parse_type (s, &info)) {
7087 if (info.assembly.name)
7089 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
7091 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
7092 mono_reflection_free_type_info (&info);
7095 mono_domain_set (d, TRUE);
7099 case CMD_ASSEMBLY_GET_NAME: {
7101 MonoAssembly *mass = ass;
7103 name = g_strdup_printf (
7104 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7106 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7107 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7108 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7109 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7111 buffer_add_string (buf, name);
7116 return ERR_NOT_IMPLEMENTED;
7123 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7129 case CMD_MODULE_GET_INFO: {
7130 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7133 basename = g_path_get_basename (image->name);
7134 buffer_add_string (buf, basename); // name
7135 buffer_add_string (buf, image->module_name); // scopename
7136 buffer_add_string (buf, image->name); // fqname
7137 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7138 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7143 return ERR_NOT_IMPLEMENTED;
7150 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7152 if (val && val->vtable->klass == mono_defaults.monotype_class) {
7153 /* Special case these so the client doesn't have to handle Type objects */
7155 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7156 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7157 } else if (MONO_TYPE_IS_REFERENCE (t))
7158 buffer_add_value (buf, t, &val, domain);
7160 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7164 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7170 buffer_add_int (buf, 0);
7174 for (i = 0; i < cinfo->num_attrs; ++i) {
7175 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7178 buffer_add_int (buf, nattrs);
7180 for (i = 0; i < cinfo->num_attrs; ++i) {
7181 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7182 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7183 MonoArray *typed_args, *named_args;
7185 CattrNamedArg *arginfo;
7187 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo);
7189 buffer_add_methodid (buf, domain, attr->ctor);
7193 buffer_add_int (buf, mono_array_length (typed_args));
7194 for (j = 0; j < mono_array_length (typed_args); ++j) {
7195 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7197 t = mono_method_signature (attr->ctor)->params [j];
7199 buffer_add_cattr_arg (buf, t, domain, val);
7202 buffer_add_int (buf, 0);
7207 buffer_add_int (buf, mono_array_length (named_args));
7209 for (j = 0; j < mono_array_length (named_args); ++j) {
7210 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7212 if (arginfo [j].prop) {
7213 buffer_add_byte (buf, 0x54);
7214 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7215 } else if (arginfo [j].field) {
7216 buffer_add_byte (buf, 0x53);
7217 buffer_add_fieldid (buf, domain, arginfo [j].field);
7219 g_assert_not_reached ();
7222 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7225 buffer_add_int (buf, 0);
7231 /* FIXME: Code duplication with icall.c */
7233 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7238 mono_class_setup_interfaces (klass, error);
7239 if (!mono_error_ok (error))
7242 for (i = 0; i < klass->interface_count; i++) {
7243 ic = klass->interfaces [i];
7244 g_hash_table_insert (ifaces, ic, ic);
7246 collect_interfaces (ic, ifaces, error);
7247 if (!mono_error_ok (error))
7253 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7263 case CMD_TYPE_GET_INFO: {
7264 buffer_add_string (buf, klass->name_space);
7265 buffer_add_string (buf, klass->name);
7267 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7268 buffer_add_string (buf, name);
7270 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7271 buffer_add_moduleid (buf, domain, klass->image);
7272 buffer_add_typeid (buf, domain, klass->parent);
7273 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7274 buffer_add_typeid (buf, domain, klass->element_class);
7276 buffer_add_id (buf, 0);
7277 buffer_add_int (buf, klass->type_token);
7278 buffer_add_byte (buf, klass->rank);
7279 buffer_add_int (buf, klass->flags);
7281 type = &klass->byval_arg;
7282 // FIXME: Can't decide whenever a class represents a byref type
7285 if (type->type == MONO_TYPE_PTR)
7287 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7289 if (type->type == MONO_TYPE_VALUETYPE)
7291 if (klass->enumtype)
7293 if (klass->generic_container)
7295 if (klass->generic_container || klass->generic_class)
7297 buffer_add_byte (buf, b);
7300 while ((nested = mono_class_get_nested_types (klass, &iter)))
7302 buffer_add_int (buf, nnested);
7304 while ((nested = mono_class_get_nested_types (klass, &iter)))
7305 buffer_add_typeid (buf, domain, nested);
7306 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7307 if (klass->generic_container)
7308 buffer_add_typeid (buf, domain, klass);
7309 else if (klass->generic_class)
7310 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7312 buffer_add_id (buf, 0);
7314 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7317 if (klass->generic_class) {
7318 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7320 count = inst->type_argc;
7321 buffer_add_int (buf, count);
7322 for (i = 0; i < count; i++)
7323 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7324 } else if (klass->generic_container) {
7325 MonoGenericContainer *container = klass->generic_container;
7328 count = container->type_argc;
7329 buffer_add_int (buf, count);
7330 for (i = 0; i < count; i++) {
7331 pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
7332 buffer_add_typeid (buf, domain, pklass);
7335 buffer_add_int (buf, 0);
7340 case CMD_TYPE_GET_METHODS: {
7343 gpointer iter = NULL;
7346 mono_class_setup_methods (klass);
7348 nmethods = mono_class_num_methods (klass);
7350 buffer_add_int (buf, nmethods);
7352 while ((m = mono_class_get_methods (klass, &iter))) {
7353 buffer_add_methodid (buf, domain, m);
7356 g_assert (i == nmethods);
7359 case CMD_TYPE_GET_FIELDS: {
7362 gpointer iter = NULL;
7365 nfields = mono_class_num_fields (klass);
7367 buffer_add_int (buf, nfields);
7369 while ((f = mono_class_get_fields (klass, &iter))) {
7370 buffer_add_fieldid (buf, domain, f);
7371 buffer_add_string (buf, f->name);
7372 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7373 buffer_add_int (buf, f->type->attrs);
7376 g_assert (i == nfields);
7379 case CMD_TYPE_GET_PROPERTIES: {
7382 gpointer iter = NULL;
7385 nprops = mono_class_num_properties (klass);
7387 buffer_add_int (buf, nprops);
7389 while ((p = mono_class_get_properties (klass, &iter))) {
7390 buffer_add_propertyid (buf, domain, p);
7391 buffer_add_string (buf, p->name);
7392 buffer_add_methodid (buf, domain, p->get);
7393 buffer_add_methodid (buf, domain, p->set);
7394 buffer_add_int (buf, p->attrs);
7397 g_assert (i == nprops);
7400 case CMD_TYPE_GET_CATTRS: {
7401 MonoClass *attr_klass;
7402 MonoCustomAttrInfo *cinfo;
7404 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7405 /* attr_klass can be NULL */
7409 cinfo = mono_custom_attrs_from_class (klass);
7411 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7414 case CMD_TYPE_GET_FIELD_CATTRS: {
7415 MonoClass *attr_klass;
7416 MonoCustomAttrInfo *cinfo;
7417 MonoClassField *field;
7419 field = decode_fieldid (p, &p, end, NULL, &err);
7422 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7426 cinfo = mono_custom_attrs_from_field (klass, field);
7428 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7431 case CMD_TYPE_GET_PROPERTY_CATTRS: {
7432 MonoClass *attr_klass;
7433 MonoCustomAttrInfo *cinfo;
7436 prop = decode_propertyid (p, &p, end, NULL, &err);
7439 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7443 cinfo = mono_custom_attrs_from_property (klass, prop);
7445 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7448 case CMD_TYPE_GET_VALUES:
7449 case CMD_TYPE_GET_VALUES_2: {
7456 MonoThread *thread_obj;
7457 MonoInternalThread *thread = NULL;
7458 guint32 special_static_type;
7460 if (command == CMD_TYPE_GET_VALUES_2) {
7461 int objid = decode_objid (p, &p, end);
7464 err = get_object (objid, (MonoObject**)&thread_obj);
7468 thread = THREAD_TO_INTERNAL (thread_obj);
7471 len = decode_int (p, &p, end);
7472 for (i = 0; i < len; ++i) {
7473 f = decode_fieldid (p, &p, end, NULL, &err);
7477 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7478 return ERR_INVALID_FIELDID;
7479 special_static_type = mono_class_field_get_special_static_type (f);
7480 if (special_static_type != SPECIAL_STATIC_NONE) {
7481 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
7482 return ERR_INVALID_FIELDID;
7485 /* Check that the field belongs to the object */
7487 for (k = klass; k; k = k->parent) {
7488 if (k == f->parent) {
7494 return ERR_INVALID_FIELDID;
7496 vtable = mono_class_vtable (domain, f->parent);
7497 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7498 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
7499 buffer_add_value (buf, f->type, val, domain);
7504 case CMD_TYPE_SET_VALUES: {
7512 len = decode_int (p, &p, end);
7513 for (i = 0; i < len; ++i) {
7514 f = decode_fieldid (p, &p, end, NULL, &err);
7518 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7519 return ERR_INVALID_FIELDID;
7520 if (mono_class_field_is_special_static (f))
7521 return ERR_INVALID_FIELDID;
7523 /* Check that the field belongs to the object */
7525 for (k = klass; k; k = k->parent) {
7526 if (k == f->parent) {
7532 return ERR_INVALID_FIELDID;
7534 // FIXME: Check for literal/const
7536 vtable = mono_class_vtable (domain, f->parent);
7537 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7538 err = decode_value (f->type, domain, val, p, &p, end);
7543 if (MONO_TYPE_IS_REFERENCE (f->type))
7544 mono_field_static_set_value (vtable, f, *(gpointer*)val);
7546 mono_field_static_set_value (vtable, f, val);
7551 case CMD_TYPE_GET_OBJECT: {
7552 MonoObject *o = (MonoObject*)mono_type_get_object (domain, &klass->byval_arg);
7553 buffer_add_objid (buf, o);
7556 case CMD_TYPE_GET_SOURCE_FILES:
7557 case CMD_TYPE_GET_SOURCE_FILES_2: {
7558 char *source_file, *base;
7562 files = get_source_files_for_type (klass);
7564 buffer_add_int (buf, files->len);
7565 for (i = 0; i < files->len; ++i) {
7566 source_file = g_ptr_array_index (files, i);
7567 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
7568 buffer_add_string (buf, source_file);
7570 base = g_path_get_basename (source_file);
7571 buffer_add_string (buf, base);
7574 g_free (source_file);
7576 g_ptr_array_free (files, TRUE);
7579 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
7580 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
7584 if (mono_class_is_assignable_from (klass, oklass))
7585 buffer_add_byte (buf, 1);
7587 buffer_add_byte (buf, 0);
7590 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
7591 char *name = decode_string (p, &p, end);
7592 int i, flags = decode_int (p, &p, end);
7593 MonoException *ex = NULL;
7594 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
7597 return ERR_LOADER_ERROR;
7598 buffer_add_int (buf, array->len);
7599 for (i = 0; i < array->len; ++i) {
7600 MonoMethod *method = g_ptr_array_index (array, i);
7601 buffer_add_methodid (buf, domain, method);
7604 g_ptr_array_free (array, TRUE);
7608 case CMD_TYPE_GET_INTERFACES: {
7610 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
7612 MonoClass *tclass, *iface;
7613 GHashTableIter iter;
7617 for (parent = tclass; parent; parent = parent->parent) {
7618 mono_class_setup_interfaces (parent, &error);
7619 if (!mono_error_ok (&error))
7620 return ERR_LOADER_ERROR;
7621 collect_interfaces (parent, iface_hash, &error);
7622 if (!mono_error_ok (&error))
7623 return ERR_LOADER_ERROR;
7626 buffer_add_int (buf, g_hash_table_size (iface_hash));
7628 g_hash_table_iter_init (&iter, iface_hash);
7629 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
7630 buffer_add_typeid (buf, domain, iface);
7631 g_hash_table_destroy (iface_hash);
7634 case CMD_TYPE_GET_INTERFACE_MAP: {
7635 int tindex, ioffset;
7636 gboolean variance_used;
7638 int len, nmethods, i;
7642 len = decode_int (p, &p, end);
7643 mono_class_setup_vtable (klass);
7645 for (tindex = 0; tindex < len; ++tindex) {
7646 iclass = decode_typeid (p, &p, end, NULL, &err);
7650 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
7652 return ERR_INVALID_ARGUMENT;
7654 nmethods = mono_class_num_methods (iclass);
7655 buffer_add_int (buf, nmethods);
7658 while ((method = mono_class_get_methods (iclass, &iter))) {
7659 buffer_add_methodid (buf, domain, method);
7661 for (i = 0; i < nmethods; ++i)
7662 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
7667 return ERR_NOT_IMPLEMENTED;
7674 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7677 MonoDomain *old_domain;
7681 klass = decode_typeid (p, &p, end, &domain, &err);
7685 old_domain = mono_domain_get ();
7687 mono_domain_set (domain, TRUE);
7689 err = type_commands_internal (command, klass, domain, p, end, buf);
7691 mono_domain_set (old_domain, TRUE);
7697 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7699 MonoMethodHeader *header;
7703 case CMD_METHOD_GET_NAME: {
7704 buffer_add_string (buf, method->name);
7707 case CMD_METHOD_GET_DECLARING_TYPE: {
7708 buffer_add_typeid (buf, domain, method->klass);
7711 case CMD_METHOD_GET_DEBUG_INFO: {
7712 MonoDebugMethodInfo *minfo;
7714 int i, j, n_il_offsets;
7717 int *column_numbers;
7719 GPtrArray *source_file_list;
7721 header = mono_method_get_header (method);
7723 buffer_add_int (buf, 0);
7724 buffer_add_string (buf, "");
7725 buffer_add_int (buf, 0);
7729 minfo = mono_debug_lookup_method (method);
7731 buffer_add_int (buf, header->code_size);
7732 buffer_add_string (buf, "");
7733 buffer_add_int (buf, 0);
7734 mono_metadata_free_mh (header);
7738 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, &n_il_offsets, &il_offsets, &line_numbers, &column_numbers, &source_files);
7739 buffer_add_int (buf, header->code_size);
7740 if (CHECK_PROTOCOL_VERSION (2, 13)) {
7741 buffer_add_int (buf, source_file_list->len);
7742 for (i = 0; i < source_file_list->len; ++i) {
7743 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
7744 buffer_add_string (buf, sinfo->source_file);
7745 if (CHECK_PROTOCOL_VERSION (2, 14)) {
7746 for (j = 0; j < 16; ++j)
7747 buffer_add_byte (buf, sinfo->hash [j]);
7751 buffer_add_string (buf, source_file);
7753 buffer_add_int (buf, n_il_offsets);
7754 DEBUG (10, fprintf (log_file, "Line number table for method %s:\n", mono_method_full_name (method, TRUE)));
7755 for (i = 0; i < n_il_offsets; ++i) {
7756 const char *srcfile = "";
7758 if (source_files [i] != -1) {
7759 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
7760 srcfile = sinfo->source_file;
7762 DEBUG (10, fprintf (log_file, "IL%x -> %s:%d %d\n", il_offsets [i], srcfile, line_numbers [i], column_numbers ? column_numbers [i] : -1));
7763 buffer_add_int (buf, il_offsets [i]);
7764 buffer_add_int (buf, line_numbers [i]);
7765 if (CHECK_PROTOCOL_VERSION (2, 13))
7766 buffer_add_int (buf, source_files [i]);
7767 if (CHECK_PROTOCOL_VERSION (2, 19))
7768 buffer_add_int (buf, column_numbers ? column_numbers [i] : -1);
7770 g_free (source_file);
7771 g_free (il_offsets);
7772 g_free (line_numbers);
7773 g_free (source_files);
7774 g_ptr_array_free (source_file_list, TRUE);
7775 mono_metadata_free_mh (header);
7778 case CMD_METHOD_GET_PARAM_INFO: {
7779 MonoMethodSignature *sig = mono_method_signature (method);
7783 /* FIXME: mono_class_from_mono_type () and byrefs */
7785 /* FIXME: Use a smaller encoding */
7786 buffer_add_int (buf, sig->call_convention);
7787 buffer_add_int (buf, sig->param_count);
7788 buffer_add_int (buf, sig->generic_param_count);
7789 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
7790 for (i = 0; i < sig->param_count; ++i) {
7792 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
7795 /* Emit parameter names */
7796 names = g_new (char *, sig->param_count);
7797 mono_method_get_param_names (method, (const char **) names);
7798 for (i = 0; i < sig->param_count; ++i)
7799 buffer_add_string (buf, names [i]);
7804 case CMD_METHOD_GET_LOCALS_INFO: {
7805 int i, j, num_locals;
7806 MonoDebugLocalsInfo *locals;
7808 header = mono_method_get_header (method);
7810 return ERR_INVALID_ARGUMENT;
7812 buffer_add_int (buf, header->num_locals);
7815 for (i = 0; i < header->num_locals; ++i)
7816 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
7819 locals = mono_debug_lookup_locals (method);
7821 num_locals = locals->num_locals;
7824 for (i = 0; i < header->num_locals; ++i) {
7825 for (j = 0; j < num_locals; ++j)
7826 if (locals->locals [j].index == i)
7829 buffer_add_string (buf, locals->locals [j].name);
7831 buffer_add_string (buf, "");
7835 for (i = 0; i < header->num_locals; ++i) {
7836 for (j = 0; j < num_locals; ++j)
7837 if (locals->locals [j].index == i)
7839 if (j < num_locals && locals->locals [j].block) {
7840 buffer_add_int (buf, locals->locals [j].block->start_offset);
7841 buffer_add_int (buf, locals->locals [j].block->end_offset);
7843 buffer_add_int (buf, 0);
7844 buffer_add_int (buf, header->code_size);
7847 mono_metadata_free_mh (header);
7850 mono_debug_symfile_free_locals (locals);
7854 case CMD_METHOD_GET_INFO:
7855 buffer_add_int (buf, method->flags);
7856 buffer_add_int (buf, method->iflags);
7857 buffer_add_int (buf, method->token);
7858 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7860 if (method->is_generic)
7862 if (mono_method_signature (method)->generic_param_count)
7864 buffer_add_byte (buf, attrs);
7865 if (method->is_generic || method->is_inflated) {
7868 if (method->is_generic) {
7871 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
7873 result = imethod->declaring;
7874 if (imethod->context.class_inst) {
7875 MonoClass *klass = ((MonoMethod *) imethod)->klass;
7876 /*Generic methods gets the context of the GTD.*/
7877 if (mono_class_get_context (klass))
7878 result = mono_class_inflate_generic_method_full (result, klass, mono_class_get_context (klass));
7882 buffer_add_methodid (buf, domain, result);
7884 buffer_add_id (buf, 0);
7886 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7887 if (mono_method_signature (method)->generic_param_count) {
7890 if (method->is_inflated) {
7891 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
7893 count = inst->type_argc;
7894 buffer_add_int (buf, count);
7896 for (i = 0; i < count; i++)
7897 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7899 buffer_add_int (buf, 0);
7901 } else if (method->is_generic) {
7902 MonoGenericContainer *container = mono_method_get_generic_container (method);
7904 count = mono_method_signature (method)->generic_param_count;
7905 buffer_add_int (buf, count);
7906 for (i = 0; i < count; i++) {
7907 MonoGenericParam *param = mono_generic_container_get_param (container, i);
7908 MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
7909 buffer_add_typeid (buf, domain, pklass);
7912 buffer_add_int (buf, 0);
7915 buffer_add_int (buf, 0);
7920 case CMD_METHOD_GET_BODY: {
7923 header = mono_method_get_header (method);
7925 buffer_add_int (buf, 0);
7927 if (CHECK_PROTOCOL_VERSION (2, 18))
7928 buffer_add_int (buf, 0);
7930 buffer_add_int (buf, header->code_size);
7931 for (i = 0; i < header->code_size; ++i)
7932 buffer_add_byte (buf, header->code [i]);
7934 if (CHECK_PROTOCOL_VERSION (2, 18)) {
7935 buffer_add_int (buf, header->num_clauses);
7936 for (i = 0; i < header->num_clauses; ++i) {
7937 MonoExceptionClause *clause = &header->clauses [i];
7939 buffer_add_int (buf, clause->flags);
7940 buffer_add_int (buf, clause->try_offset);
7941 buffer_add_int (buf, clause->try_len);
7942 buffer_add_int (buf, clause->handler_offset);
7943 buffer_add_int (buf, clause->handler_len);
7944 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
7945 buffer_add_typeid (buf, domain, clause->data.catch_class);
7946 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
7947 buffer_add_int (buf, clause->data.filter_offset);
7951 mono_metadata_free_mh (header);
7956 case CMD_METHOD_RESOLVE_TOKEN: {
7957 guint32 token = decode_int (p, &p, end);
7960 switch (mono_metadata_token_code (token)) {
7961 case MONO_TOKEN_STRING: {
7965 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
7968 s2 = mono_string_to_utf8 (s);
7970 buffer_add_byte (buf, TOKEN_TYPE_STRING);
7971 buffer_add_string (buf, s2);
7977 MonoClass *handle_class;
7979 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
7980 val = mono_method_get_wrapper_data (method, token);
7981 handle_class = mono_method_get_wrapper_data (method, token + 1);
7983 if (handle_class == NULL) {
7984 // Can't figure out the token type
7985 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
7989 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
7993 if (handle_class == mono_defaults.typehandle_class) {
7994 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
7995 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
7996 buffer_add_typeid (buf, domain, (MonoClass *) val);
7998 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
7999 } else if (handle_class == mono_defaults.fieldhandle_class) {
8000 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8001 buffer_add_fieldid (buf, domain, val);
8002 } else if (handle_class == mono_defaults.methodhandle_class) {
8003 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8004 buffer_add_methodid (buf, domain, val);
8005 } else if (handle_class == mono_defaults.string_class) {
8008 s = mono_string_to_utf8 (val);
8009 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8010 buffer_add_string (buf, s);
8013 g_assert_not_reached ();
8020 case CMD_METHOD_GET_CATTRS: {
8021 MonoClass *attr_klass;
8022 MonoCustomAttrInfo *cinfo;
8024 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8025 /* attr_klass can be NULL */
8029 cinfo = mono_custom_attrs_from_method (method);
8031 buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
8035 return ERR_NOT_IMPLEMENTED;
8042 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8045 MonoDomain *old_domain;
8049 method = decode_methodid (p, &p, end, &domain, &err);
8053 old_domain = mono_domain_get ();
8055 mono_domain_set (domain, TRUE);
8057 err = method_commands_internal (command, method, domain, p, end, buf);
8059 mono_domain_set (old_domain, TRUE);
8065 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8067 int objid = decode_objid (p, &p, end);
8069 MonoThread *thread_obj;
8070 MonoInternalThread *thread;
8072 err = get_object (objid, (MonoObject**)&thread_obj);
8076 thread = THREAD_TO_INTERNAL (thread_obj);
8079 case CMD_THREAD_GET_NAME: {
8081 gunichar2 *s = mono_thread_get_name (thread, &name_len);
8084 buffer_add_int (buf, 0);
8089 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
8091 buffer_add_int (buf, len);
8092 buffer_add_data (buf, (guint8*)name, len);
8097 case CMD_THREAD_GET_FRAME_INFO: {
8098 DebuggerTlsData *tls;
8099 int i, start_frame, length;
8101 // Wait for suspending if it already started
8102 // FIXME: Races with suspend_count
8103 while (!is_suspended ()) {
8105 wait_for_suspend ();
8109 wait_for_suspend ();
8110 if (!is_suspended ())
8111 return ERR_NOT_SUSPENDED;
8114 start_frame = decode_int (p, &p, end);
8115 length = decode_int (p, &p, end);
8117 if (start_frame != 0 || length != -1)
8118 return ERR_NOT_IMPLEMENTED;
8120 mono_loader_lock ();
8121 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8122 mono_loader_unlock ();
8125 compute_frame_info (thread, tls);
8127 buffer_add_int (buf, tls->frame_count);
8128 for (i = 0; i < tls->frame_count; ++i) {
8129 buffer_add_int (buf, tls->frames [i]->id);
8130 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
8131 buffer_add_int (buf, tls->frames [i]->il_offset);
8133 * Instead of passing the frame type directly to the client, we associate
8134 * it with the previous frame using a set of flags. This avoids lots of
8135 * conditional code in the client, since a frame whose type isn't
8136 * FRAME_TYPE_MANAGED has no method, location, etc.
8138 buffer_add_byte (buf, tls->frames [i]->flags);
8143 case CMD_THREAD_GET_STATE:
8144 buffer_add_int (buf, thread->state);
8146 case CMD_THREAD_GET_INFO:
8147 buffer_add_byte (buf, thread->threadpool_thread);
8149 case CMD_THREAD_GET_ID:
8150 buffer_add_long (buf, (guint64)(gsize)thread);
8152 case CMD_THREAD_GET_TID:
8153 buffer_add_long (buf, (guint64)thread->tid);
8156 return ERR_NOT_IMPLEMENTED;
8163 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8167 MonoThread *thread_obj;
8168 MonoInternalThread *thread;
8169 int pos, i, len, frame_idx;
8170 DebuggerTlsData *tls;
8172 MonoDebugMethodJitInfo *jit;
8173 MonoDebugVarInfo *var;
8174 MonoMethodSignature *sig;
8176 MonoMethodHeader *header;
8178 objid = decode_objid (p, &p, end);
8179 err = get_object (objid, (MonoObject**)&thread_obj);
8183 thread = THREAD_TO_INTERNAL (thread_obj);
8185 id = decode_id (p, &p, end);
8187 mono_loader_lock ();
8188 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8189 mono_loader_unlock ();
8192 for (i = 0; i < tls->frame_count; ++i) {
8193 if (tls->frames [i]->id == id)
8196 if (i == tls->frame_count)
8197 return ERR_INVALID_FRAMEID;
8200 frame = tls->frames [frame_idx];
8202 if (!frame->has_ctx)
8204 return ERR_INVALID_FRAMEID;
8207 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
8208 if (!frame->jit && frame->api_method->is_inflated)
8209 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
8213 /* This could happen for aot images with no jit debug info */
8214 s = mono_method_full_name (frame->api_method, TRUE);
8215 DEBUG (1, fprintf (log_file, "[dbg] No debug information found for '%s'.\n", s));
8217 return ERR_ABSENT_INFORMATION;
8222 sig = mono_method_signature (frame->actual_method);
8224 if (!get_seq_points (frame->domain, frame->actual_method))
8226 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
8228 return ERR_ABSENT_INFORMATION;
8231 case CMD_STACK_FRAME_GET_VALUES: {
8232 len = decode_int (p, &p, end);
8233 header = mono_method_get_header (frame->actual_method);
8235 for (i = 0; i < len; ++i) {
8236 pos = decode_int (p, &p, end);
8241 g_assert (pos >= 0 && pos < jit->num_params);
8243 var = &jit->params [pos];
8245 add_var (buf, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
8247 g_assert (pos >= 0 && pos < jit->num_locals);
8249 var = &jit->locals [pos];
8251 add_var (buf, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
8254 mono_metadata_free_mh (header);
8257 case CMD_STACK_FRAME_GET_THIS: {
8258 if (frame->api_method->klass->valuetype) {
8259 if (!sig->hasthis) {
8260 MonoObject *p = NULL;
8261 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
8263 add_var (buf, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8266 if (!sig->hasthis) {
8267 MonoObject *p = NULL;
8268 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
8270 add_var (buf, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8275 case CMD_STACK_FRAME_SET_VALUES: {
8278 MonoDebugVarInfo *var;
8280 len = decode_int (p, &p, end);
8281 header = mono_method_get_header (frame->actual_method);
8283 for (i = 0; i < len; ++i) {
8284 pos = decode_int (p, &p, end);
8289 g_assert (pos >= 0 && pos < jit->num_params);
8291 t = sig->params [pos];
8292 var = &jit->params [pos];
8294 g_assert (pos >= 0 && pos < jit->num_locals);
8296 t = header->locals [pos];
8297 var = &jit->locals [pos];
8300 if (MONO_TYPE_IS_REFERENCE (t))
8301 val_buf = g_alloca (sizeof (MonoObject*));
8303 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
8304 err = decode_value (t, frame->domain, val_buf, p, &p, end);
8308 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_ctx);
8310 mono_metadata_free_mh (header);
8314 return ERR_NOT_IMPLEMENTED;
8321 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8324 int objid, err, index, len, i, esize;
8327 objid = decode_objid (p, &p, end);
8328 err = get_object (objid, (MonoObject**)&arr);
8333 case CMD_ARRAY_REF_GET_LENGTH:
8334 buffer_add_int (buf, arr->obj.vtable->klass->rank);
8336 buffer_add_int (buf, arr->max_length);
8337 buffer_add_int (buf, 0);
8339 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
8340 buffer_add_int (buf, arr->bounds [i].length);
8341 buffer_add_int (buf, arr->bounds [i].lower_bound);
8345 case CMD_ARRAY_REF_GET_VALUES:
8346 index = decode_int (p, &p, end);
8347 len = decode_int (p, &p, end);
8349 g_assert (index >= 0 && len >= 0);
8350 // Reordered to avoid integer overflow
8351 g_assert (!(index > arr->max_length - len));
8353 esize = mono_array_element_size (arr->obj.vtable->klass);
8354 for (i = index; i < index + len; ++i) {
8355 elem = (gpointer*)((char*)arr->vector + (i * esize));
8356 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
8359 case CMD_ARRAY_REF_SET_VALUES:
8360 index = decode_int (p, &p, end);
8361 len = decode_int (p, &p, end);
8363 g_assert (index >= 0 && len >= 0);
8364 // Reordered to avoid integer overflow
8365 g_assert (!(index > arr->max_length - len));
8367 esize = mono_array_element_size (arr->obj.vtable->klass);
8368 for (i = index; i < index + len; ++i) {
8369 elem = (gpointer*)((char*)arr->vector + (i * esize));
8371 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
8375 return ERR_NOT_IMPLEMENTED;
8382 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8387 int i, index, length;
8390 objid = decode_objid (p, &p, end);
8391 err = get_object (objid, (MonoObject**)&str);
8396 case CMD_STRING_REF_GET_VALUE:
8397 s = mono_string_to_utf8 (str);
8398 buffer_add_string (buf, s);
8401 case CMD_STRING_REF_GET_LENGTH:
8402 buffer_add_long (buf, mono_string_length (str));
8404 case CMD_STRING_REF_GET_CHARS:
8405 index = decode_long (p, &p, end);
8406 length = decode_long (p, &p, end);
8407 if (index > mono_string_length (str) - length)
8408 return ERR_INVALID_ARGUMENT;
8409 c = mono_string_chars (str) + index;
8410 for (i = 0; i < length; ++i)
8411 buffer_add_short (buf, c [i]);
8414 return ERR_NOT_IMPLEMENTED;
8421 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8430 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
8431 objid = decode_objid (p, &p, end);
8432 err = get_object (objid, &obj);
8434 buffer_add_int (buf, 1);
8436 buffer_add_int (buf, 0);
8440 objid = decode_objid (p, &p, end);
8441 err = get_object (objid, &obj);
8446 case CMD_OBJECT_REF_GET_TYPE:
8447 /* This handles transparent proxies too */
8448 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8450 case CMD_OBJECT_REF_GET_VALUES:
8451 len = decode_int (p, &p, end);
8453 for (i = 0; i < len; ++i) {
8454 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
8458 /* Check that the field belongs to the object */
8460 for (k = obj->vtable->klass; k; k = k->parent) {
8461 if (k == f->parent) {
8467 return ERR_INVALID_FIELDID;
8469 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8473 if (mono_class_field_is_special_static (f))
8474 return ERR_INVALID_FIELDID;
8476 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8477 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8478 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8479 mono_field_static_get_value (vtable, f, val);
8480 buffer_add_value (buf, f->type, val, obj->vtable->domain);
8483 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
8487 case CMD_OBJECT_REF_SET_VALUES:
8488 len = decode_int (p, &p, end);
8490 for (i = 0; i < len; ++i) {
8491 f = decode_fieldid (p, &p, end, NULL, &err);
8495 /* Check that the field belongs to the object */
8497 for (k = obj->vtable->klass; k; k = k->parent) {
8498 if (k == f->parent) {
8504 return ERR_INVALID_FIELDID;
8506 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8510 if (mono_class_field_is_special_static (f))
8511 return ERR_INVALID_FIELDID;
8513 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8514 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8516 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8517 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
8522 mono_field_static_set_value (vtable, f, val);
8525 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
8531 case CMD_OBJECT_REF_GET_ADDRESS:
8532 buffer_add_long (buf, (gssize)obj);
8534 case CMD_OBJECT_REF_GET_DOMAIN:
8535 buffer_add_domainid (buf, obj->vtable->domain);
8537 case CMD_OBJECT_REF_GET_INFO:
8538 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8539 buffer_add_domainid (buf, obj->vtable->domain);
8542 return ERR_NOT_IMPLEMENTED;
8549 command_set_to_string (CommandSet command_set)
8551 switch (command_set) {
8554 case CMD_SET_OBJECT_REF:
8555 return "OBJECT_REF";
8556 case CMD_SET_STRING_REF:
8557 return "STRING_REF";
8558 case CMD_SET_THREAD:
8560 case CMD_SET_ARRAY_REF:
8562 case CMD_SET_EVENT_REQUEST:
8563 return "EVENT_REQUEST";
8564 case CMD_SET_STACK_FRAME:
8565 return "STACK_FRAME";
8566 case CMD_SET_APPDOMAIN:
8568 case CMD_SET_ASSEMBLY:
8570 case CMD_SET_METHOD:
8574 case CMD_SET_MODULE:
8584 cmd_to_string (CommandSet set, int command)
8589 case CMD_VM_VERSION:
8591 case CMD_VM_ALL_THREADS:
8592 return "ALL_THREADS";
8593 case CMD_VM_SUSPEND:
8599 case CMD_VM_DISPOSE:
8601 case CMD_VM_INVOKE_METHOD:
8602 return "INVOKE_METHOD";
8603 case CMD_VM_SET_PROTOCOL_VERSION:
8604 return "SET_PROTOCOL_VERSION";
8605 case CMD_VM_ABORT_INVOKE:
8606 return "ABORT_INVOKE";
8607 case CMD_VM_SET_KEEPALIVE:
8608 return "SET_KEEPALIVE";
8621 wait_for_attach (void)
8623 #ifndef DISABLE_SOCKET_TRANSPORT
8624 if (listen_fd == -1) {
8625 DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
8629 /* Block and wait for client connection */
8630 conn_fd = socket_transport_accept (listen_fd);
8631 DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
8632 if (conn_fd == -1) {
8633 DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
8637 g_assert_not_reached ();
8641 disconnected = !transport_handshake ();
8643 DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
8653 * This thread handles communication with the debugger client using a JDWP
8656 static guint32 WINAPI
8657 debugger_thread (void *arg)
8659 int res, len, id, flags, command_set = 0, command = 0;
8660 guint8 header [HEADER_LENGTH];
8661 guint8 *data, *p, *end;
8665 gboolean attach_failed = FALSE;
8667 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
8669 debugger_thread_id = GetCurrentThreadId ();
8671 mono_jit_thread_attach (mono_get_root_domain ());
8673 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
8675 mono_set_is_debugger_attached (TRUE);
8677 if (agent_config.defer) {
8678 if (!wait_for_attach ()) {
8679 DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
8680 attach_failed = TRUE; // Don't abort process when we can't listen
8682 /* Send start event to client */
8683 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
8687 while (!attach_failed) {
8688 res = transport_recv (header, HEADER_LENGTH);
8690 /* This will break if the socket is closed during shutdown too */
8691 if (res != HEADER_LENGTH) {
8692 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH));
8697 end = header + HEADER_LENGTH;
8699 len = decode_int (p, &p, end);
8700 id = decode_int (p, &p, end);
8701 flags = decode_byte (p, &p, end);
8702 command_set = decode_byte (p, &p, end);
8703 command = decode_byte (p, &p, end);
8705 g_assert (flags == 0);
8708 const char *cmd_str;
8711 cmd_str = cmd_to_string (command_set, command);
8713 sprintf (cmd_num, "%d", command);
8717 DEBUG (1, fprintf (log_file, "[dbg] Received command %s(%s), id=%d.\n", command_set_to_string (command_set), cmd_str, id));
8720 data = g_malloc (len - HEADER_LENGTH);
8721 if (len - HEADER_LENGTH > 0)
8723 res = transport_recv (data, len - HEADER_LENGTH);
8724 if (res != len - HEADER_LENGTH) {
8725 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH));
8731 end = data + (len - HEADER_LENGTH);
8733 buffer_init (&buf, 128);
8738 /* Process the request */
8739 switch (command_set) {
8741 err = vm_commands (command, id, p, end, &buf);
8742 if (!err && command == CMD_VM_INVOKE_METHOD)
8743 /* Sent after the invoke is complete */
8746 case CMD_SET_EVENT_REQUEST:
8747 err = event_commands (command, p, end, &buf);
8749 case CMD_SET_APPDOMAIN:
8750 err = domain_commands (command, p, end, &buf);
8752 case CMD_SET_ASSEMBLY:
8753 err = assembly_commands (command, p, end, &buf);
8755 case CMD_SET_MODULE:
8756 err = module_commands (command, p, end, &buf);
8759 err = type_commands (command, p, end, &buf);
8761 case CMD_SET_METHOD:
8762 err = method_commands (command, p, end, &buf);
8764 case CMD_SET_THREAD:
8765 err = thread_commands (command, p, end, &buf);
8767 case CMD_SET_STACK_FRAME:
8768 err = frame_commands (command, p, end, &buf);
8770 case CMD_SET_ARRAY_REF:
8771 err = array_commands (command, p, end, &buf);
8773 case CMD_SET_STRING_REF:
8774 err = string_commands (command, p, end, &buf);
8776 case CMD_SET_OBJECT_REF:
8777 err = object_commands (command, p, end, &buf);
8780 err = ERR_NOT_IMPLEMENTED;
8784 send_reply_packet (id, err, &buf);
8789 if (command_set == CMD_SET_VM && command == CMD_VM_DISPOSE)
8793 mono_set_is_debugger_attached (FALSE);
8795 mono_mutex_lock (&debugger_thread_exited_mutex);
8796 debugger_thread_exited = TRUE;
8797 mono_cond_signal (&debugger_thread_exited_cond);
8798 mono_mutex_unlock (&debugger_thread_exited_mutex);
8800 DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
8802 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
8803 DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
8804 start_debugger_thread ();
8810 #else /* DISABLE_DEBUGGER_AGENT */
8813 mono_debugger_agent_parse_options (char *options)
8815 g_error ("This runtime is configured with the debugger agent disabled.");
8819 mono_debugger_agent_init (void)
8824 mono_debugger_agent_breakpoint_hit (void *sigctx)
8829 mono_debugger_agent_single_step_event (void *sigctx)
8834 mono_debugger_agent_free_domain_info (MonoDomain *domain)
8839 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
8845 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
8846 MonoContext *catch_ctx)
8851 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
8856 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
8861 mono_debugger_agent_user_break (void)
8867 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
8872 mono_debugger_agent_debug_log_is_enabled (void)