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))
3357 char *s2 = g_path_get_basename (sinfo->source_file);
3358 char *s3 = strdup_tolower (s2);
3360 if (g_hash_table_lookup (mod->data.source_files, s3))
3367 g_ptr_array_free (source_file_list, TRUE);
3372 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3375 s = mono_type_full_name (&ei->klass->byval_arg);
3376 if (!g_hash_table_lookup (mod->data.type_names, s))
3379 } else if (mod->kind == MOD_KIND_STEP) {
3380 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3381 (ji->method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3382 !strcmp (ji->method->name, ".cctor"))
3384 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3385 MonoCustomAttrInfo *ainfo;
3386 static MonoClass *klass;
3389 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3392 if (!ji->dbg_hidden_inited) {
3393 ainfo = mono_custom_attrs_from_method (ji->method);
3395 if (mono_custom_attrs_has_attr (ainfo, klass))
3396 ji->dbg_hidden = TRUE;
3397 mono_custom_attrs_free (ainfo);
3399 ji->dbg_hidden_inited = TRUE;
3408 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3409 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3414 /* Send a VM START/DEATH event by default */
3415 if (event == EVENT_KIND_VM_START)
3416 events = g_slist_append (events, GINT_TO_POINTER (0));
3417 if (event == EVENT_KIND_VM_DEATH)
3418 events = g_slist_append (events, GINT_TO_POINTER (0));
3423 static G_GNUC_UNUSED const char*
3424 event_to_string (EventKind event)
3427 case EVENT_KIND_VM_START: return "VM_START";
3428 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3429 case EVENT_KIND_THREAD_START: return "THREAD_START";
3430 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3431 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3432 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3433 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3434 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3435 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3436 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3437 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3438 case EVENT_KIND_STEP: return "STEP";
3439 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3440 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3441 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3442 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3443 case EVENT_KIND_USER_LOG: return "USER_LOG";
3445 g_assert_not_reached ();
3452 * Send an event to the client, suspending the vm if needed.
3453 * LOCKING: Since this can suspend the calling thread, no locks should be held
3455 * The EVENTS list is freed by this function.
3458 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3462 MonoDomain *domain = mono_domain_get ();
3463 MonoThread *thread = NULL;
3464 gboolean send_success = FALSE;
3469 DEBUG (2, fprintf (log_file, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event)));
3473 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3474 // FIXME: We miss those events
3475 DEBUG (2, fprintf (log_file, "VM start event not sent yet: dropping %s\n", event_to_string (event)));
3479 if (vm_death_event_sent) {
3480 DEBUG (2, fprintf (log_file, "VM death event has been sent: dropping %s\n", event_to_string (event)));
3484 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3485 DEBUG (2, fprintf (log_file, "Mono runtime is shutting down: dropping %s\n", event_to_string (event)));
3490 DEBUG (2, fprintf (log_file, "Debugger client is not connected: dropping %s\n", event_to_string (event)));
3494 if (event == EVENT_KIND_KEEPALIVE)
3495 suspend_policy = SUSPEND_POLICY_NONE;
3500 if (agent_config.defer) {
3501 /* Make sure the thread id is always set when doing deferred debugging */
3502 if (debugger_thread_id == GetCurrentThreadId ()) {
3503 /* Don't suspend on events from the debugger thread */
3504 suspend_policy = SUSPEND_POLICY_NONE;
3505 thread = mono_thread_get_main ();
3507 else thread = mono_thread_current ();
3509 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3510 // FIXME: Send these with a NULL thread, don't suspend the current thread
3515 nevents = g_slist_length (events);
3516 buffer_init (&buf, 128);
3517 buffer_add_byte (&buf, suspend_policy);
3518 buffer_add_int (&buf, nevents);
3520 for (l = events; l; l = l->next) {
3521 buffer_add_byte (&buf, event); // event kind
3522 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3527 thread = mono_thread_current ();
3529 if (event == EVENT_KIND_VM_START && arg != NULL)
3532 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3535 case EVENT_KIND_THREAD_START:
3536 case EVENT_KIND_THREAD_DEATH:
3538 case EVENT_KIND_APPDOMAIN_CREATE:
3539 case EVENT_KIND_APPDOMAIN_UNLOAD:
3540 buffer_add_domainid (&buf, arg);
3542 case EVENT_KIND_METHOD_ENTRY:
3543 case EVENT_KIND_METHOD_EXIT:
3544 buffer_add_methodid (&buf, domain, arg);
3546 case EVENT_KIND_ASSEMBLY_LOAD:
3547 case EVENT_KIND_ASSEMBLY_UNLOAD:
3548 buffer_add_assemblyid (&buf, domain, arg);
3550 case EVENT_KIND_TYPE_LOAD:
3551 buffer_add_typeid (&buf, domain, arg);
3553 case EVENT_KIND_BREAKPOINT:
3554 case EVENT_KIND_STEP:
3555 buffer_add_methodid (&buf, domain, arg);
3556 buffer_add_long (&buf, il_offset);
3558 case EVENT_KIND_VM_START:
3559 buffer_add_domainid (&buf, mono_get_root_domain ());
3561 case EVENT_KIND_VM_DEATH:
3563 case EVENT_KIND_EXCEPTION: {
3564 EventInfo *ei = arg;
3565 buffer_add_objid (&buf, ei->exc);
3568 case EVENT_KIND_USER_BREAK:
3570 case EVENT_KIND_USER_LOG: {
3571 EventInfo *ei = arg;
3572 buffer_add_int (&buf, ei->level);
3573 buffer_add_string (&buf, ei->category ? ei->category : "");
3574 buffer_add_string (&buf, ei->message ? ei->message : "");
3577 case EVENT_KIND_KEEPALIVE:
3578 suspend_policy = SUSPEND_POLICY_NONE;
3581 g_assert_not_reached ();
3585 if (event == EVENT_KIND_VM_START) {
3586 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3587 if (!agent_config.defer)
3588 start_debugger_thread ();
3591 if (event == EVENT_KIND_VM_DEATH) {
3592 vm_death_event_sent = TRUE;
3593 suspend_policy = SUSPEND_POLICY_NONE;
3596 if (mono_runtime_is_shutting_down ())
3597 suspend_policy = SUSPEND_POLICY_NONE;
3599 if (suspend_policy != SUSPEND_POLICY_NONE) {
3601 * Save the thread context and start suspending before sending the packet,
3602 * since we could be receiving the resume request before send_packet ()
3605 save_thread_context (ctx);
3609 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3613 g_slist_free (events);
3616 if (!send_success) {
3617 DEBUG (2, fprintf (log_file, "Sending command %s failed.\n", event_to_string (event)));
3621 if (event == EVENT_KIND_VM_START) {
3622 vm_start_event_sent = TRUE;
3625 DEBUG (1, fprintf (log_file, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer)GetCurrentThreadId (), nevents, event_to_string (event), ecount, suspend_policy));
3627 switch (suspend_policy) {
3628 case SUSPEND_POLICY_NONE:
3630 case SUSPEND_POLICY_ALL:
3633 case SUSPEND_POLICY_EVENT_THREAD:
3637 g_assert_not_reached ();
3642 process_profiler_event (EventKind event, gpointer arg)
3646 EventInfo ei, *ei_arg = NULL;
3648 if (event == EVENT_KIND_TYPE_LOAD) {
3653 mono_loader_lock ();
3654 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3655 mono_loader_unlock ();
3657 process_event (event, arg, 0, NULL, events, suspend_policy);
3661 runtime_initialized (MonoProfiler *prof)
3663 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3664 if (agent_config.defer)
3665 start_debugger_thread ();
3669 runtime_shutdown (MonoProfiler *prof)
3671 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3673 mono_debugger_agent_cleanup ();
3677 thread_startup (MonoProfiler *prof, uintptr_t tid)
3679 MonoInternalThread *thread = mono_thread_internal_current ();
3680 MonoInternalThread *old_thread;
3681 DebuggerTlsData *tls;
3683 if (tid == debugger_thread_id)
3686 g_assert (thread->tid == tid);
3688 mono_loader_lock ();
3689 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3690 mono_loader_unlock ();
3692 if (thread == old_thread) {
3694 * For some reason, thread_startup () might be called for the same thread
3695 * multiple times (attach ?).
3697 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
3701 * thread_end () might not be called for some threads, and the tid could
3704 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
3705 mono_loader_lock ();
3706 mono_g_hash_table_remove (thread_to_tls, old_thread);
3707 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3708 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3709 mono_loader_unlock ();
3713 tls = mono_native_tls_get_value (debugger_tls_id);
3715 // FIXME: Free this somewhere
3716 tls = g_new0 (DebuggerTlsData, 1);
3717 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3718 tls->thread = thread;
3719 mono_native_tls_set_value (debugger_tls_id, tls);
3721 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3723 mono_loader_lock ();
3724 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3725 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3726 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3727 mono_loader_unlock ();
3729 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3732 * suspend_vm () could have missed this thread, so wait for a resume.
3738 thread_end (MonoProfiler *prof, uintptr_t tid)
3740 MonoInternalThread *thread;
3741 DebuggerTlsData *tls = NULL;
3743 mono_loader_lock ();
3744 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3746 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3747 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3749 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3750 tls->terminated = TRUE;
3751 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3752 MONO_GC_UNREGISTER_ROOT (tls->thread);
3756 mono_loader_unlock ();
3758 /* We might be called for threads started before we registered the start callback */
3760 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3761 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3766 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3768 mono_loader_lock ();
3769 g_hash_table_insert (domains, domain, domain);
3770 mono_loader_unlock ();
3772 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3776 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3778 clear_breakpoints_for_domain (domain);
3780 mono_loader_lock ();
3781 /* Invalidate each thread's frame stack */
3782 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3783 mono_loader_unlock ();
3785 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3789 * invalidate_each_thread:
3791 * A GHFunc to invalidate frames.
3792 * value must be a DebuggerTlsData*
3795 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3797 invalidate_frames (value);
3801 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3803 /* Sent later in jit_end () */
3804 mono_loader_lock ();
3805 g_ptr_array_add (pending_assembly_loads, assembly);
3806 mono_loader_unlock ();
3810 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3812 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3814 clear_event_requests_for_assembly (assembly);
3815 clear_types_for_assembly (assembly);
3819 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3821 #if defined(HOST_WIN32) && !defined(__GNUC__)
3822 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3824 gpointer stackptr = __builtin_frame_address (1);
3826 MonoInternalThread *thread = mono_thread_internal_current ();
3827 DebuggerTlsData *tls;
3829 mono_loader_lock ();
3831 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3832 /* Could be the debugger thread with assembly/type load hooks */
3834 tls->invoke_addr = stackptr;
3836 mono_loader_unlock ();
3840 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3843 #if defined(HOST_WIN32) && !defined(__GNUC__)
3844 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3846 gpointer stackptr = __builtin_frame_address (1);
3849 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
3853 * We need to stop single stepping when exiting a runtime invoke, since if it is
3854 * a step out, it may return to native code, and thus never end.
3856 mono_loader_lock ();
3857 ss_invoke_addr = NULL;
3859 for (i = 0; i < event_requests->len; ++i) {
3860 EventRequest *req = g_ptr_array_index (event_requests, i);
3862 if (req->event_kind == EVENT_KIND_STEP) {
3863 ss_destroy (req->info);
3864 g_ptr_array_remove_index_fast (event_requests, i);
3869 mono_loader_unlock ();
3873 send_type_load (MonoClass *klass)
3875 gboolean type_load = FALSE;
3876 MonoDomain *domain = mono_domain_get ();
3877 AgentDomainInfo *info = NULL;
3879 mono_loader_lock ();
3880 mono_domain_lock (domain);
3882 info = get_agent_domain_info (domain);
3884 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
3886 g_hash_table_insert (info->loaded_classes, klass, klass);
3889 mono_domain_unlock (domain);
3890 mono_loader_unlock ();
3892 emit_type_load (klass, klass, NULL);
3896 * Emit load events for all types currently loaded in the domain.
3897 * Takes the loader and domain locks.
3898 * user_data is unused.
3901 send_types_for_domain (MonoDomain *domain, void *user_data)
3903 AgentDomainInfo *info = NULL;
3905 mono_loader_lock ();
3906 mono_domain_lock (domain);
3907 info = get_agent_domain_info (domain);
3909 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
3910 mono_domain_unlock (domain);
3911 mono_loader_unlock ();
3915 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
3918 * We emit type load events when the first method of the type is JITted,
3919 * since the class load profiler callbacks might be called with the
3920 * loader lock held. They could also occur in the debugger thread.
3921 * Same for assembly load events.
3924 MonoAssembly *assembly = NULL;
3926 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
3927 mono_loader_lock ();
3928 if (pending_assembly_loads->len > 0) {
3929 assembly = g_ptr_array_index (pending_assembly_loads, 0);
3930 g_ptr_array_remove_index (pending_assembly_loads, 0);
3932 mono_loader_unlock ();
3935 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
3941 send_type_load (method->klass);
3944 add_pending_breakpoints (method, jinfo);
3948 * BREAKPOINTS/SINGLE STEPPING
3952 * Contains information about an inserted breakpoint.
3955 long il_offset, native_offset;
3960 } BreakpointInstance;
3963 * Contains generic information about a breakpoint.
3967 * The method where the breakpoint is placed. Can be NULL in which case it
3968 * is inserted into every method. This is used to implement method entry/
3969 * exit events. Can be a generic method definition, in which case the
3970 * breakpoint is inserted into every instance.
3976 * A list of BreakpointInstance structures describing where the breakpoint
3977 * was inserted. There could be more than one because of
3978 * generics/appdomains/method entry/exit.
3980 GPtrArray *children;
3983 /* List of breakpoints */
3984 static GPtrArray *breakpoints;
3985 /* Maps breakpoint locations to the number of breakpoints at that location */
3986 static GHashTable *bp_locs;
3989 breakpoints_init (void)
3991 breakpoints = g_ptr_array_new ();
3992 bp_locs = g_hash_table_new (NULL, NULL);
3996 * insert_breakpoint:
3998 * Insert the breakpoint described by BP into the method described by
4002 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4005 BreakpointInstance *inst;
4006 SeqPoint *sp = NULL;
4009 mono_error_init (error);
4011 for (i = 0; i < seq_points->len; ++i) {
4012 sp = &seq_points->seq_points [i];
4014 if (sp->il_offset == bp->il_offset)
4018 if (i == seq_points->len) {
4020 * The set of IL offsets with seq points doesn't completely match the
4021 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4023 for (i = 0; i < seq_points->len; ++i) {
4024 sp = &seq_points->seq_points [i];
4026 if (sp->il_offset != METHOD_ENTRY_IL_OFFSET && sp->il_offset != METHOD_EXIT_IL_OFFSET && sp->il_offset + 1 == bp->il_offset)
4031 if (i == seq_points->len) {
4032 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);
4034 for (i = 0; i < seq_points->len; ++i)
4035 DEBUG (1, fprintf (log_file, "%d\n", seq_points->seq_points [i].il_offset));
4038 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4047 inst = g_new0 (BreakpointInstance, 1);
4049 inst->native_offset = sp->native_offset;
4050 inst->ip = (guint8*)ji->code_start + sp->native_offset;
4052 inst->domain = domain;
4054 mono_loader_lock ();
4056 g_ptr_array_add (bp->children, inst);
4058 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4059 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4060 mono_loader_unlock ();
4063 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4064 mono_arch_set_breakpoint (ji, inst->ip);
4070 DEBUG(1, fprintf (log_file, "[dbg] Inserted breakpoint at %s:0x%x.\n", mono_method_full_name (ji->method, TRUE), (int)sp->il_offset));
4074 remove_breakpoint (BreakpointInstance *inst)
4076 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4078 MonoJitInfo *ji = inst->ji;
4079 guint8 *ip = inst->ip;
4081 mono_loader_lock ();
4082 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4083 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4084 mono_loader_unlock ();
4086 g_assert (count > 0);
4089 mono_arch_clear_breakpoint (ji, ip);
4096 static inline gboolean
4097 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4103 if (method == bp->method)
4105 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4108 if (bp->method->is_inflated && method->is_inflated) {
4109 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4110 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4112 /* Open generic methods should match closed generic methods of the same class */
4113 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4114 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4115 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4117 /* FIXME: Handle !mvar */
4118 if (t1->type != MONO_TYPE_MVAR)
4129 * add_pending_breakpoints:
4131 * Insert pending breakpoints into the newly JITted method METHOD.
4134 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4137 MonoSeqPointInfo *seq_points;
4143 domain = mono_domain_get ();
4145 mono_loader_lock ();
4147 for (i = 0; i < breakpoints->len; ++i) {
4148 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4149 gboolean found = FALSE;
4151 if (!bp_matches_method (bp, method))
4154 for (j = 0; j < bp->children->len; ++j) {
4155 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4162 mono_domain_lock (domain);
4163 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
4164 if (!seq_points && ji->method->is_inflated)
4165 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (ji->method));
4166 mono_domain_unlock (domain);
4168 /* Could be AOT code */
4170 g_assert (seq_points);
4172 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4176 mono_loader_unlock ();
4180 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4186 mono_error_init (error);
4188 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4190 /* Might be AOTed code */
4191 code = mono_aot_get_method (domain, method);
4193 ji = mono_jit_info_table_find (domain, code);
4198 insert_breakpoint (seq_points, domain, ji, bp, error);
4202 clear_breakpoint (MonoBreakpoint *bp);
4207 * Set a breakpoint at IL_OFFSET in METHOD.
4208 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4209 * METHOD can also be a generic method definition, in which case a breakpoint
4210 * is placed in all instances of the method.
4211 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4214 static MonoBreakpoint*
4215 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4218 GHashTableIter iter, iter2;
4221 MonoSeqPointInfo *seq_points;
4224 mono_error_init (error);
4227 // - suspend/resume the vm to prevent code patching problems
4228 // - multiple breakpoints on the same location
4229 // - dynamic methods
4232 bp = g_new0 (MonoBreakpoint, 1);
4233 bp->method = method;
4234 bp->il_offset = il_offset;
4236 bp->children = g_ptr_array_new ();
4238 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));
4240 mono_loader_lock ();
4242 g_hash_table_iter_init (&iter, domains);
4243 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4244 mono_domain_lock (domain);
4246 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4247 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4248 if (bp_matches_method (bp, m))
4249 set_bp_in_method (domain, m, seq_points, bp, error);
4252 mono_domain_unlock (domain);
4255 mono_loader_unlock ();
4257 mono_loader_lock ();
4258 g_ptr_array_add (breakpoints, bp);
4259 mono_loader_unlock ();
4261 if (error && !mono_error_ok (error)) {
4262 clear_breakpoint (bp);
4270 clear_breakpoint (MonoBreakpoint *bp)
4274 // FIXME: locking, races
4275 for (i = 0; i < bp->children->len; ++i) {
4276 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4278 remove_breakpoint (inst);
4283 mono_loader_lock ();
4284 g_ptr_array_remove (breakpoints, bp);
4285 mono_loader_unlock ();
4287 g_ptr_array_free (bp->children, TRUE);
4292 breakpoints_cleanup (void)
4296 mono_loader_lock ();
4298 while (i < event_requests->len) {
4299 EventRequest *req = g_ptr_array_index (event_requests, i);
4301 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4302 clear_breakpoint (req->info);
4303 g_ptr_array_remove_index_fast (event_requests, i);
4310 for (i = 0; i < breakpoints->len; ++i)
4311 g_free (g_ptr_array_index (breakpoints, i));
4313 g_ptr_array_free (breakpoints, TRUE);
4314 g_hash_table_destroy (bp_locs);
4319 mono_loader_unlock ();
4323 * clear_breakpoints_for_domain:
4325 * Clear breakpoint instances which reference DOMAIN.
4328 clear_breakpoints_for_domain (MonoDomain *domain)
4332 /* This could be called after shutdown */
4336 mono_loader_lock ();
4337 for (i = 0; i < breakpoints->len; ++i) {
4338 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4341 while (j < bp->children->len) {
4342 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4344 if (inst->domain == domain) {
4345 remove_breakpoint (inst);
4349 g_ptr_array_remove_index_fast (bp->children, j);
4355 mono_loader_unlock ();
4359 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4361 return bp->method && bp->method->klass->image->assembly == assembly;
4365 process_breakpoint_inner (DebuggerTlsData *tls)
4369 int i, j, suspend_policy;
4370 guint32 native_offset;
4372 BreakpointInstance *inst;
4373 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4374 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4375 EventKind kind = EVENT_KIND_BREAKPOINT;
4376 MonoContext *ctx = &tls->restore_ctx;
4377 MonoSeqPointInfo *info;
4380 // FIXME: Speed this up
4382 ip = MONO_CONTEXT_GET_IP (ctx);
4383 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4385 g_assert (ji->method);
4387 /* Compute the native offset of the breakpoint from the ip */
4388 native_offset = ip - (guint8*)ji->code_start;
4391 * Skip the instruction causing the breakpoint signal.
4393 mono_arch_skip_breakpoint (ctx, ji);
4395 if (ji->method->wrapper_type || tls->disable_breakpoints)
4398 bp_reqs = g_ptr_array_new ();
4399 ss_reqs = g_ptr_array_new ();
4400 ss_reqs_orig = g_ptr_array_new ();
4402 mono_loader_lock ();
4405 * The ip points to the instruction causing the breakpoint event, which is after
4406 * the offset recorded in the seq point map, so find the prev seq point before ip.
4408 sp = find_prev_seq_point_for_native_offset (mono_domain_get (), ji->method, native_offset, &info);
4411 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));
4414 for (i = 0; i < breakpoints->len; ++i) {
4415 bp = g_ptr_array_index (breakpoints, i);
4420 for (j = 0; j < bp->children->len; ++j) {
4421 inst = g_ptr_array_index (bp->children, j);
4422 if (inst->ji == ji && inst->sp == sp) {
4423 if (bp->req->event_kind == EVENT_KIND_STEP) {
4424 g_ptr_array_add (ss_reqs_orig, bp->req);
4426 g_ptr_array_add (bp_reqs, bp->req);
4431 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4432 /* Maybe a method entry/exit event */
4433 if (sp->il_offset == METHOD_ENTRY_IL_OFFSET)
4434 kind = EVENT_KIND_METHOD_ENTRY;
4435 else if (sp->il_offset == METHOD_EXIT_IL_OFFSET)
4436 kind = EVENT_KIND_METHOD_EXIT;
4439 /* Process single step requests */
4440 for (i = 0; i < ss_reqs_orig->len; ++i) {
4441 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4442 SingleStepReq *ss_req = req->info;
4443 gboolean hit = TRUE;
4445 if (ss_req->size == STEP_SIZE_LINE) {
4446 /* Have to check whenever a different source line was reached */
4447 MonoDebugMethodInfo *minfo;
4448 MonoDebugSourceLocation *loc = NULL;
4450 minfo = mono_debug_lookup_method (ji->method);
4453 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4455 if (!loc || (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line)) {
4456 /* Have to continue single stepping */
4457 DEBUG(1, fprintf (log_file, "[%p] Same source line, continuing single stepping.\n", (gpointer)GetCurrentThreadId ()));
4462 ss_req->last_method = ji->method;
4463 ss_req->last_line = loc->row;
4464 mono_debug_free_source_location (loc);
4469 g_ptr_array_add (ss_reqs, req);
4471 /* Start single stepping again from the current sequence point */
4472 ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4475 if (ss_reqs->len > 0)
4476 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4477 if (bp_reqs->len > 0)
4478 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4479 if (kind != EVENT_KIND_BREAKPOINT)
4480 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4482 mono_loader_unlock ();
4484 g_ptr_array_free (bp_reqs, TRUE);
4485 g_ptr_array_free (ss_reqs, TRUE);
4488 * FIXME: The first event will suspend, so the second will only be sent after the
4492 process_event (EVENT_KIND_STEP, ji->method, 0, ctx, ss_events, suspend_policy);
4494 process_event (kind, ji->method, 0, ctx, bp_events, suspend_policy);
4495 if (enter_leave_events)
4496 process_event (kind, ji->method, 0, ctx, enter_leave_events, suspend_policy);
4499 /* Process a breakpoint/single step event after resuming from a signal handler */
4501 process_signal_event (void (*func) (DebuggerTlsData*))
4503 DebuggerTlsData *tls;
4504 MonoContext orig_restore_ctx, ctx;
4505 static void (*restore_context) (void *);
4507 if (!restore_context)
4508 restore_context = mono_get_restore_context ();
4510 tls = mono_native_tls_get_value (debugger_tls_id);
4511 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4512 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4513 memcpy (&tls->restore_ctx, &tls->handler_ctx, sizeof (MonoContext));
4517 /* This is called when resuming from a signal handler, so it shouldn't return */
4518 memcpy (&ctx, &tls->restore_ctx, sizeof (MonoContext));
4519 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4520 restore_context (&ctx);
4521 g_assert_not_reached ();
4525 process_breakpoint (void)
4527 process_signal_event (process_breakpoint_inner);
4531 resume_from_signal_handler (void *sigctx, void *func)
4533 DebuggerTlsData *tls;
4536 /* Save the original context in TLS */
4537 // FIXME: This might not work on an altstack ?
4538 tls = mono_native_tls_get_value (debugger_tls_id);
4540 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer)GetCurrentThreadId ());
4543 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4544 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4545 // clob:c could be added to op_seq_point.
4547 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4548 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4549 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4550 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4552 MONO_CONTEXT_SET_IP (&ctx, func);
4554 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4556 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4557 mono_ppc_set_func_into_sigctx (sigctx, func);
4562 mono_debugger_agent_breakpoint_hit (void *sigctx)
4565 * We are called from a signal handler, and running code there causes all kinds of
4566 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4567 * So set up the signal context to return to the real breakpoint handler function.
4569 resume_from_signal_handler (sigctx, process_breakpoint);
4573 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4575 if (frame->managed) {
4576 *(MonoContext*)data = *ctx;
4585 * Called by System.Diagnostics.Debugger:Break ().
4588 mono_debugger_agent_user_break (void)
4590 if (agent_config.enabled) {
4595 /* Obtain a context */
4596 MONO_CONTEXT_SET_IP (&ctx, NULL);
4597 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4598 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4600 mono_loader_lock ();
4601 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4602 mono_loader_unlock ();
4604 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4611 ss_depth_to_string (StepDepth depth)
4614 case STEP_DEPTH_OVER:
4616 case STEP_DEPTH_OUT:
4618 case STEP_DEPTH_INTO:
4621 g_assert_not_reached ();
4627 process_single_step_inner (DebuggerTlsData *tls)
4632 int il_offset, suspend_policy;
4635 MonoContext *ctx = &tls->restore_ctx;
4637 MonoSeqPointInfo *info;
4639 ip = MONO_CONTEXT_GET_IP (ctx);
4641 /* Skip the instruction causing the single step */
4642 mono_arch_skip_single_step (ctx);
4644 if (suspend_count > 0) {
4645 process_suspend (tls, ctx);
4650 // FIXME: A suspend race
4653 if (mono_thread_internal_current () != ss_req->thread)
4656 if (log_level > 0) {
4657 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4659 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));
4662 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4664 g_assert (ji->method);
4666 if (ji->method->wrapper_type && ji->method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4671 * Stopping in memset makes half-initialized vtypes visible.
4672 * Stopping in memcpy makes half-copied vtypes visible.
4674 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
4678 * The ip points to the instruction causing the single step event, which is before
4679 * the offset recorded in the seq point map, so find the next seq point after ip.
4681 sp = find_next_seq_point_for_native_offset (domain, ji->method, (guint8*)ip - (guint8*)ji->code_start, &info);
4684 il_offset = sp->il_offset;
4686 // FIXME: No tests fail if this is disabled
4688 if (ss_req->size == STEP_SIZE_LINE) {
4692 /* Step until a different source line is reached */
4693 MonoDebugMethodInfo *minfo;
4695 minfo = mono_debug_lookup_method (ji->method);
4698 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4700 if (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line) {
4701 mono_debug_free_source_location (loc);
4706 * Step until we reach a location with line number info,
4707 * otherwise the client can't show a location.
4708 * This can happen for example with statics initialized inline
4709 * outside of a cctor.
4714 ss_req->last_method = ji->method;
4715 ss_req->last_line = loc->row;
4716 mono_debug_free_source_location (loc);
4722 /* Start single stepping again from the current sequence point */
4723 ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4725 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
4726 (ji->method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4727 !strcmp (ji->method->name, ".cctor"))
4730 // FIXME: Has to lock earlier
4732 reqs = g_ptr_array_new ();
4734 mono_loader_lock ();
4736 g_ptr_array_add (reqs, ss_req->req);
4738 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4740 g_ptr_array_free (reqs, TRUE);
4742 mono_loader_unlock ();
4744 process_event (EVENT_KIND_STEP, ji->method, il_offset, ctx, events, suspend_policy);
4748 process_single_step (void)
4750 process_signal_event (process_single_step_inner);
4754 * mono_debugger_agent_single_step_event:
4756 * Called from a signal handler to handle a single step event.
4759 mono_debugger_agent_single_step_event (void *sigctx)
4761 /* Resume to process_single_step through the signal context */
4763 // FIXME: Since step out/over is implemented using step in, the step in case should
4764 // be as fast as possible. Move the relevant code from process_single_step_inner ()
4767 if (GetCurrentThreadId () == debugger_thread_id) {
4769 * This could happen despite our best effors when the runtime calls
4770 * assembly/type resolve hooks.
4771 * FIXME: Breakpoints too.
4775 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4776 mono_arch_skip_single_step (&ctx);
4777 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4781 resume_from_signal_handler (sigctx, process_single_step);
4785 debugger_agent_single_step_from_context (MonoContext *ctx)
4787 DebuggerTlsData *tls;
4788 MonoContext orig_restore_ctx;
4790 tls = mono_native_tls_get_value (debugger_tls_id);
4793 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4794 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4795 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4797 process_single_step_inner (tls);
4799 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4800 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4804 debugger_agent_breakpoint_from_context (MonoContext *ctx)
4806 DebuggerTlsData *tls;
4807 MonoContext orig_restore_ctx;
4809 tls = mono_native_tls_get_value (debugger_tls_id);
4811 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4812 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4814 process_breakpoint_inner (tls);
4816 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4817 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4821 * start_single_stepping:
4823 * Turn on single stepping. Can be called multiple times, for example,
4824 * by a single step event request + a suspend.
4827 start_single_stepping (void)
4829 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4830 int val = InterlockedIncrement (&ss_count);
4833 mono_arch_start_single_stepping ();
4835 if (ss_req != NULL && ss_invoke_addr == NULL) {
4836 DebuggerTlsData *tls;
4838 mono_loader_lock ();
4840 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
4841 ss_invoke_addr = tls->invoke_addr;
4843 mono_loader_unlock ();
4846 g_assert_not_reached ();
4851 stop_single_stepping (void)
4853 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4854 int val = InterlockedDecrement (&ss_count);
4857 mono_arch_stop_single_stepping ();
4859 g_assert_not_reached ();
4866 * Stop the single stepping operation given by SS_REQ.
4869 ss_stop (SingleStepReq *ss_req)
4874 for (l = ss_req->bps; l; l = l->next) {
4875 clear_breakpoint (l->data);
4877 g_slist_free (ss_req->bps);
4881 if (ss_req->global) {
4882 stop_single_stepping ();
4883 ss_req->global = FALSE;
4890 * Start the single stepping operation given by SS_REQ from the sequence point SP.
4891 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
4892 * belong to the same thread as CTX.
4895 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
4897 int i, j, frame_index;
4900 gboolean enable_global = FALSE;
4902 /* Stop the previous operation */
4906 * Implement single stepping using breakpoints if possible.
4908 if (step_to_catch) {
4909 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
4910 ss_req->bps = g_slist_append (ss_req->bps, bp);
4914 if ((!sp || sp->next_len == 0 || ss_req->depth == STEP_DEPTH_OUT || ss_req->depth == STEP_DEPTH_OVER) && ctx) {
4915 /* Need parent frames */
4916 if (!tls->context.valid)
4917 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4918 compute_frame_info (tls->thread, tls);
4922 * Find the first sequence point in the current or in a previous frame which
4923 * is not the last in its method.
4925 if (ss_req->depth == STEP_DEPTH_OUT) {
4926 /* Ignore seq points in current method */
4927 while (frame_index < tls->frame_count) {
4928 StackFrame *frame = tls->frames [frame_index];
4930 method = frame->method;
4931 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4933 if (sp && sp->next_len != 0)
4936 // There could be method calls before the next seq point in the caller when using nested calls
4937 //enable_global = TRUE;
4939 while (sp && sp->next_len == 0) {
4941 if (frame_index < tls->frame_count) {
4942 StackFrame *frame = tls->frames [frame_index];
4944 method = frame->method;
4945 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4951 if (sp && sp->next_len > 0) {
4952 for (i = 0; i < sp->next_len; ++i) {
4953 next_sp = &info->seq_points [sp->next [i]];
4955 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
4956 ss_req->bps = g_slist_append (ss_req->bps, bp);
4960 if (ss_req->depth == STEP_DEPTH_OVER) {
4961 /* Need to stop in catch clauses as well */
4962 for (i = 0; i < tls->frame_count; ++i) {
4963 StackFrame *frame = tls->frames [i];
4966 MonoJitInfo *jinfo = frame->ji;
4967 for (j = 0; j < jinfo->num_clauses; ++j) {
4968 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
4970 sp = find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL);
4972 bp = set_breakpoint (frame->method, sp->il_offset, ss_req->req, NULL);
4973 ss_req->bps = g_slist_append (ss_req->bps, bp);
4981 if (ss_req->depth == STEP_DEPTH_INTO) {
4982 /* Enable global stepping so we stop at method entry too */
4983 enable_global = TRUE;
4987 * The ctx/frame info computed above will become invalid when we continue.
4989 tls->context.valid = FALSE;
4990 tls->async_state.valid = FALSE;
4991 invalidate_frames (tls);
4994 if (enable_global) {
4995 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
4996 ss_req->global = TRUE;
4997 start_single_stepping ();
4998 } else if (!ss_req->bps) {
4999 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
5000 ss_req->global = TRUE;
5001 start_single_stepping ();
5003 ss_req->global = FALSE;
5008 * Start single stepping of thread THREAD
5011 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
5013 DebuggerTlsData *tls;
5014 MonoSeqPointInfo *info = NULL;
5015 SeqPoint *sp = NULL;
5016 MonoMethod *method = NULL;
5017 MonoDebugMethodInfo *minfo;
5018 gboolean step_to_catch = FALSE;
5020 if (suspend_count == 0)
5021 return ERR_NOT_SUSPENDED;
5023 wait_for_suspend ();
5025 // FIXME: Multiple requests
5027 DEBUG (0, fprintf (log_file, "Received a single step request while the previous one was still active.\n"));
5028 return ERR_NOT_IMPLEMENTED;
5031 DEBUG (1, fprintf (log_file, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
5033 ss_req = g_new0 (SingleStepReq, 1);
5035 ss_req->thread = thread;
5036 ss_req->size = size;
5037 ss_req->depth = depth;
5040 mono_loader_lock ();
5041 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5042 mono_loader_unlock ();
5044 g_assert (tls->context.valid);
5045 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5047 if (tls->has_catch_ctx) {
5049 StackFrameInfo frame;
5050 MonoContext new_ctx;
5051 MonoLMF *lmf = NULL;
5054 * We are stopped at a throw site. Stepping should go to the catch site.
5057 /* Find the the jit info for the catch context */
5058 res = mono_find_jit_info_ext (mono_domain_get (), thread->jit_data, NULL, &tls->catch_ctx, &new_ctx, NULL, &lmf, NULL, &frame);
5060 g_assert (frame.type == FRAME_TYPE_MANAGED);
5063 * Find the seq point corresponding to the landing site ip, which is the first seq
5066 sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
5069 method = frame.method;
5071 step_to_catch = TRUE;
5072 /* This make sure the seq point is not skipped by process_single_step () */
5073 ss_req->last_sp = NULL;
5076 if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
5079 /* Compute the initial line info */
5080 compute_frame_info (thread, tls);
5082 if (tls->frame_count) {
5083 frame = tls->frames [0];
5085 ss_req->last_method = frame->method;
5086 ss_req->last_line = -1;
5088 minfo = mono_debug_lookup_method (frame->method);
5089 if (minfo && frame->il_offset != -1) {
5090 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
5093 ss_req->last_line = loc->row;
5100 if (!step_to_catch) {
5103 compute_frame_info (thread, tls);
5105 if (tls->frame_count) {
5106 frame = tls->frames [0];
5108 if (!method && frame->il_offset != -1) {
5109 /* FIXME: Sort the table and use a binary search */
5110 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5112 method = frame->method;
5117 ss_start (ss_req, method, sp, info, &tls->context.ctx, tls, step_to_catch);
5123 ss_destroy (SingleStepReq *req)
5126 g_assert (ss_req == req);
5135 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5138 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5144 if (!agent_config.enabled)
5147 mono_loader_lock ();
5148 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5149 mono_loader_unlock ();
5152 ei.category = category ? mono_string_to_utf8 (category) : NULL;
5153 ei.message = message ? mono_string_to_utf8 (message) : NULL;
5155 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5157 g_free (ei.category);
5158 g_free (ei.message);
5162 mono_debugger_agent_debug_log_is_enabled (void)
5164 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5165 return agent_config.enabled;
5168 #ifdef PLATFORM_ANDROID
5170 mono_debugger_agent_unhandled_exception (MonoException *exc)
5179 memset (&ei, 0, sizeof (EventInfo));
5180 ei.exc = (MonoObject*)exc;
5182 mono_loader_lock ();
5183 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5184 mono_loader_unlock ();
5186 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5191 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5192 MonoContext *catch_ctx)
5194 int i, j, suspend_policy;
5196 MonoJitInfo *ji, *catch_ji;
5198 DebuggerTlsData *tls = NULL;
5200 if (thread_to_tls != NULL) {
5201 MonoInternalThread *thread = mono_thread_internal_current ();
5203 mono_loader_lock ();
5204 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5205 mono_loader_unlock ();
5207 if (tls && tls->abort_requested)
5209 if (tls && tls->disable_breakpoints)
5213 memset (&ei, 0, sizeof (EventInfo));
5215 /* Just-In-Time debugging */
5217 if (agent_config.onuncaught && !inited) {
5218 finish_agent_init (FALSE);
5221 * Send an unsolicited EXCEPTION event with a dummy request id.
5223 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5224 ei.exc = (MonoObject*)exc;
5225 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5228 } else if (agent_config.onthrow && !inited) {
5230 gboolean found = FALSE;
5232 for (l = agent_config.onthrow; l; l = l->next) {
5233 char *ex_type = l->data;
5234 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5236 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5243 finish_agent_init (FALSE);
5246 * Send an unsolicited EXCEPTION event with a dummy request id.
5248 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5249 ei.exc = (MonoObject*)exc;
5250 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5258 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5260 catch_ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5264 ei.exc = (MonoObject*)exc;
5265 ei.caught = catch_ctx != NULL;
5267 mono_loader_lock ();
5269 /* Treat exceptions which are caught in non-user code as unhandled */
5270 for (i = 0; i < event_requests->len; ++i) {
5271 EventRequest *req = g_ptr_array_index (event_requests, i);
5272 if (req->event_kind != EVENT_KIND_EXCEPTION)
5275 for (j = 0; j < req->nmodifiers; ++j) {
5276 Modifier *mod = &req->modifiers [j];
5278 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5280 gboolean found = FALSE;
5281 MonoAssembly **assemblies = mod->data.assemblies;
5284 for (k = 0; assemblies [k]; ++k)
5285 if (assemblies [k] == catch_ji->method->klass->image->assembly)
5294 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5295 mono_loader_unlock ();
5297 if (tls && ei.caught && catch_ctx) {
5298 tls->catch_ctx = *catch_ctx;
5299 tls->has_catch_ctx = TRUE;
5302 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5305 tls->has_catch_ctx = FALSE;
5309 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5311 DebuggerTlsData *tls;
5316 tls = mono_native_tls_get_value (debugger_tls_id);
5321 * We're about to invoke an exception filter during the first pass of exception handling.
5323 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5324 * 'orig_ctx' is the context where the exception has been thrown.
5327 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5329 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5330 * the call site (line 37) and then continue to Main(), but it would never
5331 * include the throw site (line 32).
5333 * Since exception filters are invoked during the first pass of exception handling,
5334 * the stack frames of the throw site are still intact, so we should include them
5337 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5339 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5340 * but report the location of the 'throw' to the user.
5344 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5348 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5350 DebuggerTlsData *tls;
5355 tls = mono_native_tls_get_value (debugger_tls_id);
5359 tls->filter_state.valid = FALSE;
5363 * buffer_add_value_full:
5365 * Add the encoding of the value at ADDR described by T to the buffer.
5366 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5370 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5376 if (!(*(void**)addr))
5377 printf ("%s\n", mono_type_full_name (t));
5378 g_assert (*(void**)addr);
5379 addr = *(void**)addr;
5384 case MONO_TYPE_BOOLEAN:
5387 case MONO_TYPE_CHAR:
5407 case MONO_TYPE_VOID:
5408 buffer_add_byte (buf, t->type);
5410 case MONO_TYPE_BOOLEAN:
5413 buffer_add_byte (buf, t->type);
5414 buffer_add_int (buf, *(gint8*)addr);
5416 case MONO_TYPE_CHAR:
5419 buffer_add_byte (buf, t->type);
5420 buffer_add_int (buf, *(gint16*)addr);
5425 buffer_add_byte (buf, t->type);
5426 buffer_add_int (buf, *(gint32*)addr);
5431 buffer_add_byte (buf, t->type);
5432 buffer_add_long (buf, *(gint64*)addr);
5436 /* Treat it as a vtype */
5438 case MONO_TYPE_PTR: {
5439 gssize val = *(gssize*)addr;
5441 buffer_add_byte (buf, t->type);
5442 buffer_add_long (buf, val);
5446 case MONO_TYPE_STRING:
5447 case MONO_TYPE_SZARRAY:
5448 case MONO_TYPE_OBJECT:
5449 case MONO_TYPE_CLASS:
5450 case MONO_TYPE_ARRAY:
5451 obj = *(MonoObject**)addr;
5454 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5456 if (obj->vtable->klass->valuetype) {
5457 t = &obj->vtable->klass->byval_arg;
5458 addr = mono_object_unbox (obj);
5460 } else if (obj->vtable->klass->rank) {
5461 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5462 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5463 buffer_add_byte (buf, MONO_TYPE_CLASS);
5465 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5467 buffer_add_objid (buf, obj);
5471 case MONO_TYPE_VALUETYPE: {
5475 MonoClass *klass = mono_class_from_mono_type (t);
5477 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5478 buffer_add_byte (buf, klass->enumtype);
5479 buffer_add_typeid (buf, domain, klass);
5483 while ((f = mono_class_get_fields (klass, &iter))) {
5484 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5486 if (mono_field_is_deleted (f))
5490 buffer_add_int (buf, nfields);
5493 while ((f = mono_class_get_fields (klass, &iter))) {
5494 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5496 if (mono_field_is_deleted (f))
5498 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE);
5502 case MONO_TYPE_GENERICINST:
5503 if (mono_type_generic_inst_is_valuetype (t)) {
5515 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5517 buffer_add_value_full (buf, t, addr, domain, FALSE);
5521 obj_is_of_type (MonoObject *obj, MonoType *t)
5523 MonoClass *klass = obj->vtable->klass;
5524 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5525 if (klass == mono_defaults.transparent_proxy_class) {
5526 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5527 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5537 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5540 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5544 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5545 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5546 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5547 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5548 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
5549 char *name = mono_type_full_name (t);
5550 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5552 return ERR_INVALID_ARGUMENT;
5556 case MONO_TYPE_BOOLEAN:
5557 *(guint8*)addr = decode_int (buf, &buf, limit);
5559 case MONO_TYPE_CHAR:
5560 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5563 *(gint8*)addr = decode_int (buf, &buf, limit);
5566 *(guint8*)addr = decode_int (buf, &buf, limit);
5569 *(gint16*)addr = decode_int (buf, &buf, limit);
5572 *(guint16*)addr = decode_int (buf, &buf, limit);
5575 *(gint32*)addr = decode_int (buf, &buf, limit);
5578 *(guint32*)addr = decode_int (buf, &buf, limit);
5581 *(gint64*)addr = decode_long (buf, &buf, limit);
5584 *(guint64*)addr = decode_long (buf, &buf, limit);
5587 *(guint32*)addr = decode_int (buf, &buf, limit);
5590 *(guint64*)addr = decode_long (buf, &buf, limit);
5593 /* We send these as I8, so we get them back as such */
5594 g_assert (type == MONO_TYPE_I8);
5595 *(gssize*)addr = decode_long (buf, &buf, limit);
5597 case MONO_TYPE_GENERICINST:
5598 if (MONO_TYPE_ISSTRUCT (t)) {
5599 /* The client sends these as a valuetype */
5607 /* We send these as vtypes, so we get them back as such */
5608 g_assert (type == MONO_TYPE_VALUETYPE);
5611 case MONO_TYPE_VALUETYPE: {
5612 gboolean is_enum = decode_byte (buf, &buf, limit);
5616 gpointer iter = NULL;
5619 /* Enums are sent as a normal vtype */
5621 return ERR_NOT_IMPLEMENTED;
5622 klass = decode_typeid (buf, &buf, limit, &d, &err);
5626 if (klass != mono_class_from_mono_type (t))
5627 return ERR_INVALID_ARGUMENT;
5629 nfields = decode_int (buf, &buf, limit);
5630 while ((f = mono_class_get_fields (klass, &iter))) {
5631 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5633 if (mono_field_is_deleted (f))
5635 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5640 g_assert (nfields == 0);
5645 if (MONO_TYPE_IS_REFERENCE (t)) {
5646 if (type == MONO_TYPE_OBJECT) {
5647 int objid = decode_objid (buf, &buf, limit);
5651 err = get_object (objid, (MonoObject**)&obj);
5656 if (!obj_is_of_type (obj, t)) {
5657 DEBUG (1, fprintf (log_file, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name));
5658 return ERR_INVALID_ARGUMENT;
5661 if (obj && obj->vtable->domain != domain)
5662 return ERR_INVALID_ARGUMENT;
5664 mono_gc_wbarrier_generic_store (addr, obj);
5665 } else if (type == VALUE_TYPE_ID_NULL) {
5666 *(MonoObject**)addr = NULL;
5668 return ERR_INVALID_ARGUMENT;
5682 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5685 int type = decode_byte (buf, &buf, limit);
5687 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
5688 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
5689 guint8 *nullable_buf;
5692 * First try decoding it as a Nullable`1
5694 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5699 * Then try decoding as a primitive value or null.
5701 if (targ->type == type) {
5702 nullable_buf = g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
5703 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
5705 g_free (nullable_buf);
5708 mono_nullable_init (addr, mono_value_box (domain, mono_class_from_mono_type (targ), nullable_buf), mono_class_from_mono_type (t));
5709 g_free (nullable_buf);
5712 } else if (type == VALUE_TYPE_ID_NULL) {
5713 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
5719 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5723 add_var (Buffer *buf, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
5730 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5731 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5734 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
5735 reg_val = mono_arch_context_get_int_reg (ctx, reg);
5737 buffer_add_value_full (buf, t, ®_val, domain, as_vtype);
5739 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5740 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5741 addr += (gint32)var->offset;
5743 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5745 buffer_add_value_full (buf, t, addr, domain, as_vtype);
5747 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5751 g_assert_not_reached ();
5756 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
5762 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5763 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5765 if (MONO_TYPE_IS_REFERENCE (t))
5766 size = sizeof (gpointer);
5768 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
5771 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
5772 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
5774 gboolean is_signed = FALSE;
5776 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
5781 v = is_signed ? *(gint8*)val : *(guint8*)val;
5784 v = is_signed ? *(gint16*)val : *(guint16*)val;
5787 v = is_signed ? *(gint32*)val : *(guint32*)val;
5790 v = is_signed ? *(gint64*)val : *(guint64*)val;
5793 g_assert_not_reached ();
5799 /* Set value on the stack or in the return ctx */
5800 if (reg_locations [reg]) {
5801 /* Saved on the stack */
5802 DEBUG (1, fprintf (log_file, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v));
5803 *(reg_locations [reg]) = v;
5806 DEBUG (1, fprintf (log_file, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v));
5807 mono_arch_context_set_int_reg (restore_ctx, reg, v);
5810 // FIXME: Move these to mono-context.h/c.
5811 mono_arch_context_set_int_reg (ctx, reg, v);
5813 // FIXME: Can't set registers, so we disable linears
5818 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5819 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5820 addr += (gint32)var->offset;
5822 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5825 addr = *(guint8**)addr;
5831 // FIXME: Write barriers
5832 mono_gc_memmove (addr, val, size);
5834 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5838 g_assert_not_reached ();
5843 clear_event_request (int req_id, int etype)
5847 mono_loader_lock ();
5848 for (i = 0; i < event_requests->len; ++i) {
5849 EventRequest *req = g_ptr_array_index (event_requests, i);
5851 if (req->id == req_id && req->event_kind == etype) {
5852 if (req->event_kind == EVENT_KIND_BREAKPOINT)
5853 clear_breakpoint (req->info);
5854 if (req->event_kind == EVENT_KIND_STEP)
5855 ss_destroy (req->info);
5856 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
5857 clear_breakpoint (req->info);
5858 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
5859 clear_breakpoint (req->info);
5860 g_ptr_array_remove_index_fast (event_requests, i);
5865 mono_loader_unlock ();
5869 event_req_matches_assembly (EventRequest *req, MonoAssembly *assembly)
5871 if (req->event_kind == EVENT_KIND_BREAKPOINT)
5872 return breakpoint_matches_assembly (req->info, assembly);
5876 for (i = 0; i < req->nmodifiers; ++i) {
5877 Modifier *m = &req->modifiers [i];
5879 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
5881 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
5882 for (j = 0; m->data.assemblies [j]; ++j)
5883 if (m->data.assemblies [j] == assembly)
5893 * clear_event_requests_for_assembly:
5895 * Clear all events requests which reference ASSEMBLY.
5898 clear_event_requests_for_assembly (MonoAssembly *assembly)
5903 mono_loader_lock ();
5907 for (i = 0; i < event_requests->len; ++i) {
5908 EventRequest *req = g_ptr_array_index (event_requests, i);
5910 if (event_req_matches_assembly (req, assembly)) {
5911 clear_event_request (req->id, req->event_kind);
5917 mono_loader_unlock ();
5921 * type_comes_from_assembly:
5923 * GHRFunc that returns TRUE if klass comes from assembly
5926 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
5928 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
5932 * clear_types_for_assembly:
5934 * Clears types from loaded_classes for a given assembly
5937 clear_types_for_assembly (MonoAssembly *assembly)
5939 MonoDomain *domain = mono_domain_get ();
5940 AgentDomainInfo *info = NULL;
5942 mono_loader_lock ();
5943 info = get_agent_domain_info (domain);
5944 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
5945 mono_loader_unlock ();
5949 add_thread (gpointer key, gpointer value, gpointer user_data)
5951 MonoInternalThread *thread = value;
5952 Buffer *buf = user_data;
5954 buffer_add_objid (buf, (MonoObject*)thread);
5958 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
5960 guint8 *end = invoke->endp;
5963 MonoMethodSignature *sig;
5966 MonoObject *this, *res, *exc;
5969 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5972 MonoStopwatch watch;
5974 if (invoke->method) {
5976 * Invoke this method directly, currently only Environment.Exit () is supported.
5979 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>"));
5980 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
5981 g_assert_not_reached ();
5984 m = decode_methodid (p, &p, end, &domain, &err);
5987 sig = mono_method_signature (m);
5989 if (m->klass->valuetype)
5990 this_buf = g_alloca (mono_class_instance_size (m->klass));
5992 this_buf = g_alloca (sizeof (MonoObject*));
5993 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
5994 /* Should be null */
5995 int type = decode_byte (p, &p, end);
5996 if (type != VALUE_TYPE_ID_NULL)
5997 return ERR_INVALID_ARGUMENT;
5998 memset (this_buf, 0, mono_class_instance_size (m->klass));
6000 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6005 if (!m->klass->valuetype)
6006 this = *(MonoObject**)this_buf;
6010 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>"));
6012 if (this && this->vtable->domain != domain)
6015 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
6016 if (!strcmp (m->name, ".ctor")) {
6017 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
6018 return ERR_INVALID_ARGUMENT;
6020 this = mono_object_new (domain, m->klass);
6022 return ERR_INVALID_ARGUMENT;
6026 if (this && !obj_is_of_type (this, &m->klass->byval_arg))
6027 return ERR_INVALID_ARGUMENT;
6029 nargs = decode_int (p, &p, end);
6030 if (nargs != sig->param_count)
6031 return ERR_INVALID_ARGUMENT;
6032 /* Use alloca to get gc tracking */
6033 arg_buf = g_alloca (nargs * sizeof (gpointer));
6034 memset (arg_buf, 0, nargs * sizeof (gpointer));
6035 args = g_alloca (nargs * sizeof (gpointer));
6036 for (i = 0; i < nargs; ++i) {
6037 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6038 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6042 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6045 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6046 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6049 args [i] = arg_buf [i];
6056 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6057 tls->disable_breakpoints = TRUE;
6059 tls->disable_breakpoints = FALSE;
6062 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6064 /* FIXME: Move this to arch specific code */
6065 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6066 if (invoke->has_ctx) {
6069 lmf_addr = mono_get_lmf_addr ();
6072 memset (&ext, 0, sizeof (ext));
6074 ext.lmf.previous_lmf = *(lmf_addr);
6075 /* Mark that this is a MonoLMFExt */
6076 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6077 ext.lmf.rsp = (gssize)&ext;
6078 #elif defined(TARGET_X86)
6079 ext.lmf.previous_lmf = (gsize)*(lmf_addr);
6080 /* Mark that this is a MonoLMFExt */
6081 ext.lmf.previous_lmf = (gsize)(gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6082 ext.lmf.ebp = (gssize)&ext;
6083 #elif defined(TARGET_ARM)
6084 ext.lmf.previous_lmf = *(lmf_addr);
6085 /* Mark that this is a MonoLMFExt */
6086 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6087 ext.lmf.sp = (gssize)&ext;
6088 #elif defined(TARGET_POWERPC)
6089 ext.lmf.previous_lmf = *(lmf_addr);
6090 /* Mark that this is a MonoLMFExt */
6091 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6092 ext.lmf.ebp = (gssize)&ext;
6093 #elif defined(TARGET_S390X)
6094 ext.lmf.previous_lmf = *(lmf_addr);
6095 /* Mark that this is a MonoLMFExt */
6096 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6097 ext.lmf.ebp = (gssize)&ext;
6098 #elif defined(TARGET_MIPS)
6099 ext.lmf.previous_lmf = *(lmf_addr);
6100 /* Mark that this is a MonoLMFExt */
6101 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6102 ext.lmf.iregs [mips_sp] = (gssize)&ext;
6104 g_assert_not_reached ();
6107 ext.debugger_invoke = TRUE;
6108 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6110 mono_set_lmf ((MonoLMF*)&ext);
6114 mono_stopwatch_start (&watch);
6115 if (m->klass->valuetype)
6116 res = mono_runtime_invoke (m, this_buf, args, &exc);
6118 res = mono_runtime_invoke (m, this, args, &exc);
6119 mono_stopwatch_stop (&watch);
6120 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)));
6122 buffer_add_byte (buf, 0);
6123 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6125 buffer_add_byte (buf, 1);
6126 if (sig->ret->type == MONO_TYPE_VOID) {
6127 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
6128 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
6131 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6132 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6133 buffer_add_value (buf, sig->ret, &res, domain);
6134 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6135 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6136 MonoClass *k = mono_class_from_mono_type (sig->ret);
6137 guint8 *nullable_buf = g_alloca (mono_class_value_size (k, NULL));
6139 g_assert (nullable_buf);
6140 mono_nullable_init (nullable_buf, res, k);
6141 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6144 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6151 tls->disable_breakpoints = FALSE;
6153 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6154 if (invoke->has_ctx)
6155 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
6159 // FIXME: byref arguments
6167 * Invoke the method given by tls->pending_invoke in the current thread.
6170 invoke_method (void)
6172 DebuggerTlsData *tls;
6177 static void (*restore_context) (void *);
6178 MonoContext restore_ctx;
6181 if (!restore_context)
6182 restore_context = mono_get_restore_context ();
6184 tls = mono_native_tls_get_value (debugger_tls_id);
6188 * Store the `InvokeData *' in `tls->invoke' until we're done with
6189 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6192 mono_loader_lock ();
6194 invoke = tls->pending_invoke;
6196 tls->pending_invoke = NULL;
6198 invoke->last_invoke = tls->invoke;
6199 tls->invoke = invoke;
6201 mono_loader_unlock ();
6203 tls->frames_up_to_date = FALSE;
6209 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6210 buffer_init (&buf, 128);
6213 /* Fail the other invokes as well */
6215 err = do_invoke_method (tls, &buf, invoke, p, &p);
6218 /* Start suspending before sending the reply */
6219 if (mindex == invoke->nmethods - 1) {
6220 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6221 for (i = 0; i < invoke->suspend_count; ++i)
6226 send_reply_packet (id, err, &buf);
6231 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6233 if (invoke->has_ctx)
6234 save_thread_context (&restore_ctx);
6236 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6237 g_assert (tls->resume_count);
6238 tls->resume_count -= invoke->suspend_count;
6241 DEBUG (1, fprintf (log_file, "[%p] Invoke finished, resume_count = %d.\n", (gpointer)GetCurrentThreadId (), tls->resume_count));
6244 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6246 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
6247 * after the mono_runtime_invoke() already returned, but it doesn't matter
6248 * because we reset the abort here.
6251 mono_loader_lock ();
6253 if (tls->abort_requested)
6254 mono_thread_internal_reset_abort (tls->thread);
6256 tls->invoke = tls->invoke->last_invoke;
6257 tls->abort_requested = FALSE;
6259 mono_loader_unlock ();
6268 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6270 MonoThread *thread = value;
6271 DebuggerTlsData *tls;
6274 mono_loader_lock ();
6275 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6277 res = tls->really_suspended;
6278 mono_loader_unlock ();
6284 get_source_files_for_type (MonoClass *klass)
6286 gpointer iter = NULL;
6288 MonoDebugSourceInfo *sinfo;
6292 files = g_ptr_array_new ();
6294 while ((method = mono_class_get_methods (klass, &iter))) {
6295 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6296 GPtrArray *source_file_list;
6299 mono_debug_symfile_get_line_numbers_full (minfo, NULL, &source_file_list, NULL, NULL, NULL, NULL, NULL);
6300 for (j = 0; j < source_file_list->len; ++j) {
6301 sinfo = g_ptr_array_index (source_file_list, j);
6302 for (i = 0; i < files->len; ++i)
6303 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6305 if (i == files->len)
6306 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6308 g_ptr_array_free (source_file_list, TRUE);
6316 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6319 case CMD_VM_VERSION: {
6320 char *build_info, *version;
6322 build_info = mono_get_runtime_build_info ();
6323 version = g_strdup_printf ("mono %s", build_info);
6325 buffer_add_string (buf, version); /* vm version */
6326 buffer_add_int (buf, MAJOR_VERSION);
6327 buffer_add_int (buf, MINOR_VERSION);
6328 g_free (build_info);
6332 case CMD_VM_SET_PROTOCOL_VERSION: {
6333 major_version = decode_int (p, &p, end);
6334 minor_version = decode_int (p, &p, end);
6335 protocol_version_set = TRUE;
6336 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
6339 case CMD_VM_ALL_THREADS: {
6341 mono_loader_lock ();
6342 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6343 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6344 mono_loader_unlock ();
6347 case CMD_VM_SUSPEND:
6349 wait_for_suspend ();
6352 if (suspend_count == 0)
6353 return ERR_NOT_SUSPENDED;
6355 clear_suspended_objs ();
6357 case CMD_VM_DISPOSE:
6358 /* Clear all event requests */
6359 mono_loader_lock ();
6360 while (event_requests->len > 0) {
6361 EventRequest *req = g_ptr_array_index (event_requests, 0);
6363 clear_event_request (req->id, req->event_kind);
6365 mono_loader_unlock ();
6367 while (suspend_count > 0)
6369 disconnected = TRUE;
6370 vm_start_event_sent = FALSE;
6373 MonoInternalThread *thread;
6374 DebuggerTlsData *tls;
6375 MonoClass *env_class;
6376 MonoMethod *exit_method = NULL;
6380 exit_code = decode_int (p, &p, end);
6382 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6384 /* Have to send a reply before exiting */
6385 send_reply_packet (id, 0, buf);
6387 /* Clear all event requests */
6388 mono_loader_lock ();
6389 while (event_requests->len > 0) {
6390 EventRequest *req = g_ptr_array_index (event_requests, 0);
6392 clear_event_request (req->id, req->event_kind);
6394 mono_loader_unlock ();
6397 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6398 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6399 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6400 * better than doing the shutdown ourselves, since it avoids various races.
6404 wait_for_suspend ();
6406 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6407 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
6409 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6412 mono_loader_lock ();
6413 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6414 mono_loader_unlock ();
6416 if (thread && exit_method) {
6417 mono_loader_lock ();
6418 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6419 mono_loader_unlock ();
6421 args = g_new0 (gpointer, 1);
6422 args [0] = g_malloc (sizeof (int));
6423 *(int*)(args [0]) = exit_code;
6425 tls->pending_invoke = g_new0 (InvokeData, 1);
6426 tls->pending_invoke->method = exit_method;
6427 tls->pending_invoke->args = args;
6428 tls->pending_invoke->nmethods = 1;
6430 while (suspend_count > 0)
6434 * No thread found, do it ourselves.
6435 * FIXME: This can race with normal shutdown etc.
6437 while (suspend_count > 0)
6440 mono_runtime_set_shutting_down ();
6442 mono_threads_set_shutting_down ();
6444 /* Suspend all managed threads since the runtime is going away */
6445 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
6446 mono_thread_suspend_all_other_threads ();
6447 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
6448 mono_runtime_quit ();
6449 transport_close2 ();
6450 DEBUG(1, fprintf (log_file, "Exiting...\n"));
6456 case CMD_VM_INVOKE_METHOD:
6457 case CMD_VM_INVOKE_METHODS: {
6458 int objid = decode_objid (p, &p, end);
6460 DebuggerTlsData *tls;
6461 int i, count, err, flags, nmethods;
6463 err = get_object (objid, (MonoObject**)&thread);
6467 flags = decode_int (p, &p, end);
6469 if (command == CMD_VM_INVOKE_METHODS)
6470 nmethods = decode_int (p, &p, end);
6474 // Wait for suspending if it already started
6476 wait_for_suspend ();
6477 if (!is_suspended ())
6478 return ERR_NOT_SUSPENDED;
6480 mono_loader_lock ();
6481 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6482 mono_loader_unlock ();
6485 if (!tls->really_suspended)
6486 /* The thread is still running native code, can't do invokes */
6487 return ERR_NOT_SUSPENDED;
6490 * Store the invoke data into tls, the thread will execute it after it is
6493 if (tls->pending_invoke)
6494 return ERR_NOT_SUSPENDED;
6495 tls->pending_invoke = g_new0 (InvokeData, 1);
6496 tls->pending_invoke->id = id;
6497 tls->pending_invoke->flags = flags;
6498 tls->pending_invoke->p = g_malloc (end - p);
6499 memcpy (tls->pending_invoke->p, p, end - p);
6500 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
6501 tls->pending_invoke->suspend_count = suspend_count;
6502 tls->pending_invoke->nmethods = nmethods;
6504 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
6505 resume_thread (THREAD_TO_INTERNAL (thread));
6508 count = suspend_count;
6509 for (i = 0; i < count; ++i)
6514 case CMD_VM_ABORT_INVOKE: {
6515 int objid = decode_objid (p, &p, end);
6517 DebuggerTlsData *tls;
6520 err = get_object (objid, (MonoObject**)&thread);
6524 invoke_id = decode_int (p, &p, end);
6526 mono_loader_lock ();
6527 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6530 if (tls->abort_requested) {
6531 mono_loader_unlock ();
6536 * Check whether we're still inside the mono_runtime_invoke() and that it's
6537 * actually the correct invocation.
6539 * Careful, we do not stop the thread that's doing the invocation, so we can't
6540 * inspect its stack. However, invoke_method() also acquires the loader lock
6541 * when it's done, so we're safe here.
6545 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
6546 mono_loader_unlock ();
6547 return ERR_NO_INVOCATION;
6550 tls->abort_requested = TRUE;
6552 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
6553 mono_loader_unlock ();
6557 case CMD_VM_SET_KEEPALIVE: {
6558 int timeout = decode_int (p, &p, end);
6559 agent_config.keepalive = timeout;
6561 #ifndef DISABLE_SOCKET_TRANSPORT
6568 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
6569 GHashTableIter iter, kiter;
6574 char *fname, *basename;
6575 gboolean ignore_case;
6576 GSList *class_list, *l;
6577 GPtrArray *res_classes, *res_domains;
6579 fname = decode_string (p, &p, end);
6580 ignore_case = decode_byte (p, &p, end);
6582 basename = g_path_get_basename (fname);
6584 res_classes = g_ptr_array_new ();
6585 res_domains = g_ptr_array_new ();
6587 mono_loader_lock ();
6588 g_hash_table_iter_init (&iter, domains);
6589 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6590 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
6592 /* Update 'source_file_to_class' cache */
6593 g_hash_table_iter_init (&kiter, info->loaded_classes);
6594 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
6595 if (!g_hash_table_lookup (info->source_files, klass)) {
6596 files = get_source_files_for_type (klass);
6597 g_hash_table_insert (info->source_files, klass, files);
6599 for (i = 0; i < files->len; ++i) {
6600 char *s = g_ptr_array_index (files, i);
6601 char *s2 = g_path_get_basename (s);
6604 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
6606 class_list = g_slist_prepend (class_list, klass);
6607 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
6609 class_list = g_slist_prepend (class_list, klass);
6610 g_hash_table_insert (info->source_file_to_class, s2, class_list);
6613 /* The _ignorecase hash contains the lowercase path */
6614 s3 = strdup_tolower (s2);
6615 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
6617 class_list = g_slist_prepend (class_list, klass);
6618 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
6620 class_list = g_slist_prepend (class_list, klass);
6621 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
6633 s = strdup_tolower (basename);
6634 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
6637 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
6640 for (l = class_list; l; l = l->next) {
6643 g_ptr_array_add (res_classes, klass);
6644 g_ptr_array_add (res_domains, domain);
6647 mono_loader_unlock ();
6652 buffer_add_int (buf, res_classes->len);
6653 for (i = 0; i < res_classes->len; ++i)
6654 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6655 g_ptr_array_free (res_classes, TRUE);
6656 g_ptr_array_free (res_domains, TRUE);
6659 case CMD_VM_GET_TYPES: {
6660 GHashTableIter iter;
6664 gboolean ignore_case;
6665 GPtrArray *res_classes, *res_domains;
6666 MonoTypeNameParse info;
6668 name = decode_string (p, &p, end);
6669 ignore_case = decode_byte (p, &p, end);
6671 if (!mono_reflection_parse_type (name, &info)) {
6673 mono_reflection_free_type_info (&info);
6674 return ERR_INVALID_ARGUMENT;
6677 res_classes = g_ptr_array_new ();
6678 res_domains = g_ptr_array_new ();
6680 mono_loader_lock ();
6681 g_hash_table_iter_init (&iter, domains);
6682 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6684 gboolean type_resolve;
6688 mono_domain_assemblies_lock (domain);
6689 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6693 type_resolve = TRUE;
6694 t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
6696 g_ptr_array_add (res_classes, mono_type_get_class (t));
6697 g_ptr_array_add (res_domains, domain);
6701 mono_domain_assemblies_unlock (domain);
6703 mono_loader_unlock ();
6706 mono_reflection_free_type_info (&info);
6708 buffer_add_int (buf, res_classes->len);
6709 for (i = 0; i < res_classes->len; ++i)
6710 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6711 g_ptr_array_free (res_classes, TRUE);
6712 g_ptr_array_free (res_domains, TRUE);
6717 return ERR_NOT_IMPLEMENTED;
6724 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6730 case CMD_EVENT_REQUEST_SET: {
6732 int i, event_kind, suspend_policy, nmodifiers, mod;
6735 MonoThread *step_thread;
6736 int size = 0, depth = 0, filter = 0, step_thread_id = 0;
6740 event_kind = decode_byte (p, &p, end);
6741 suspend_policy = decode_byte (p, &p, end);
6742 nmodifiers = decode_byte (p, &p, end);
6744 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
6745 req->id = InterlockedIncrement (&event_request_id);
6746 req->event_kind = event_kind;
6747 req->suspend_policy = suspend_policy;
6748 req->nmodifiers = nmodifiers;
6751 for (i = 0; i < nmodifiers; ++i) {
6752 mod = decode_byte (p, &p, end);
6754 req->modifiers [i].kind = mod;
6755 if (mod == MOD_KIND_COUNT) {
6756 req->modifiers [i].data.count = decode_int (p, &p, end);
6757 } else if (mod == MOD_KIND_LOCATION_ONLY) {
6758 method = decode_methodid (p, &p, end, &domain, &err);
6761 location = decode_long (p, &p, end);
6762 } else if (mod == MOD_KIND_STEP) {
6763 step_thread_id = decode_id (p, &p, end);
6764 size = decode_int (p, &p, end);
6765 depth = decode_int (p, &p, end);
6766 if (CHECK_PROTOCOL_VERSION (2, 16))
6767 filter = decode_int (p, &p, end);
6768 req->modifiers [i].data.filter = filter;
6769 } else if (mod == MOD_KIND_THREAD_ONLY) {
6770 int id = decode_id (p, &p, end);
6772 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
6777 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
6778 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
6782 req->modifiers [i].caught = decode_byte (p, &p, end);
6783 req->modifiers [i].uncaught = decode_byte (p, &p, end);
6784 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" : ""));
6786 req->modifiers [i].data.exc_class = exc_class;
6788 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
6790 return ERR_INVALID_ARGUMENT;
6793 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
6794 int n = decode_int (p, &p, end);
6797 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
6798 for (j = 0; j < n; ++j) {
6799 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
6801 g_free (req->modifiers [i].data.assemblies);
6805 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
6806 int n = decode_int (p, &p, end);
6809 modifier = &req->modifiers [i];
6810 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
6811 for (j = 0; j < n; ++j) {
6812 char *s = decode_string (p, &p, end);
6816 s2 = strdup_tolower (s);
6817 g_hash_table_insert (modifier->data.source_files, s2, s2);
6821 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
6822 int n = decode_int (p, &p, end);
6825 modifier = &req->modifiers [i];
6826 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
6827 for (j = 0; j < n; ++j) {
6828 char *s = decode_string (p, &p, end);
6831 g_hash_table_insert (modifier->data.type_names, s, s);
6835 return ERR_NOT_IMPLEMENTED;
6839 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
6842 req->info = set_breakpoint (method, location, req, &error);
6843 if (!mono_error_ok (&error)) {
6845 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
6846 mono_error_cleanup (&error);
6847 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
6849 } else if (req->event_kind == EVENT_KIND_STEP) {
6850 g_assert (step_thread_id);
6852 err = get_object (step_thread_id, (MonoObject**)&step_thread);
6858 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
6863 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
6864 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
6865 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
6866 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
6867 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
6868 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
6870 if (req->nmodifiers) {
6872 return ERR_NOT_IMPLEMENTED;
6876 mono_loader_lock ();
6877 g_ptr_array_add (event_requests, req);
6879 if (agent_config.defer) {
6880 /* Transmit cached data to the client on receipt of the event request */
6881 switch (req->event_kind) {
6882 case EVENT_KIND_APPDOMAIN_CREATE:
6883 /* Emit load events for currently loaded domains */
6884 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
6886 case EVENT_KIND_ASSEMBLY_LOAD:
6887 /* Emit load events for currently loaded assemblies */
6888 mono_assembly_foreach (emit_assembly_load, NULL);
6890 case EVENT_KIND_THREAD_START:
6891 /* Emit start events for currently started threads */
6892 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
6894 case EVENT_KIND_TYPE_LOAD:
6895 /* Emit type load events for currently loaded types */
6896 mono_domain_foreach (send_types_for_domain, NULL);
6902 mono_loader_unlock ();
6904 buffer_add_int (buf, req->id);
6907 case CMD_EVENT_REQUEST_CLEAR: {
6908 int etype = decode_byte (p, &p, end);
6909 int req_id = decode_int (p, &p, end);
6911 // FIXME: Make a faster mapping from req_id to request
6912 mono_loader_lock ();
6913 clear_event_request (req_id, etype);
6914 mono_loader_unlock ();
6917 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
6920 mono_loader_lock ();
6922 while (i < event_requests->len) {
6923 EventRequest *req = g_ptr_array_index (event_requests, i);
6925 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
6926 clear_breakpoint (req->info);
6928 g_ptr_array_remove_index_fast (event_requests, i);
6934 mono_loader_unlock ();
6938 return ERR_NOT_IMPLEMENTED;
6945 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6951 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
6952 buffer_add_domainid (buf, mono_get_root_domain ());
6955 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
6956 domain = decode_domainid (p, &p, end, NULL, &err);
6959 buffer_add_string (buf, domain->friendly_name);
6962 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
6967 domain = decode_domainid (p, &p, end, NULL, &err);
6970 mono_loader_lock ();
6972 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6975 buffer_add_int (buf, count);
6976 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6978 buffer_add_assemblyid (buf, domain, ass);
6980 mono_loader_unlock ();
6983 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
6984 domain = decode_domainid (p, &p, end, NULL, &err);
6988 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
6991 case CMD_APPDOMAIN_GET_CORLIB: {
6992 domain = decode_domainid (p, &p, end, NULL, &err);
6996 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
6999 case CMD_APPDOMAIN_CREATE_STRING: {
7003 domain = decode_domainid (p, &p, end, NULL, &err);
7006 s = decode_string (p, &p, end);
7008 o = mono_string_new (domain, s);
7009 buffer_add_objid (buf, (MonoObject*)o);
7012 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7014 MonoDomain *domain2;
7017 domain = decode_domainid (p, &p, end, NULL, &err);
7020 klass = decode_typeid (p, &p, end, &domain2, &err);
7025 g_assert (domain == domain2);
7027 o = mono_object_new (domain, klass);
7029 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
7033 buffer_add_objid (buf, o);
7037 return ERR_NOT_IMPLEMENTED;
7044 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7050 ass = decode_assemblyid (p, &p, end, &domain, &err);
7055 case CMD_ASSEMBLY_GET_LOCATION: {
7056 buffer_add_string (buf, mono_image_get_filename (ass->image));
7059 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7063 if (ass->image->dynamic) {
7064 buffer_add_id (buf, 0);
7066 token = mono_image_get_entry_point (ass->image);
7068 buffer_add_id (buf, 0);
7070 m = mono_get_method (ass->image, token, NULL);
7071 buffer_add_methodid (buf, domain, m);
7076 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7077 buffer_add_moduleid (buf, domain, ass->image);
7080 case CMD_ASSEMBLY_GET_OBJECT: {
7081 MonoObject *o = (MonoObject*)mono_assembly_get_object (domain, ass);
7082 buffer_add_objid (buf, o);
7085 case CMD_ASSEMBLY_GET_TYPE: {
7086 char *s = decode_string (p, &p, end);
7087 gboolean ignorecase = decode_byte (p, &p, end);
7088 MonoTypeNameParse info;
7090 gboolean type_resolve, res;
7091 MonoDomain *d = mono_domain_get ();
7093 /* This is needed to be able to find referenced assemblies */
7094 res = mono_domain_set (domain, FALSE);
7097 if (!mono_reflection_parse_type (s, &info)) {
7100 if (info.assembly.name)
7102 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
7104 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
7105 mono_reflection_free_type_info (&info);
7108 mono_domain_set (d, TRUE);
7112 case CMD_ASSEMBLY_GET_NAME: {
7114 MonoAssembly *mass = ass;
7116 name = g_strdup_printf (
7117 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7119 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7120 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7121 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7122 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7124 buffer_add_string (buf, name);
7129 return ERR_NOT_IMPLEMENTED;
7136 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7142 case CMD_MODULE_GET_INFO: {
7143 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7146 basename = g_path_get_basename (image->name);
7147 buffer_add_string (buf, basename); // name
7148 buffer_add_string (buf, image->module_name); // scopename
7149 buffer_add_string (buf, image->name); // fqname
7150 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7151 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7156 return ERR_NOT_IMPLEMENTED;
7163 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7165 if (val && val->vtable->klass == mono_defaults.monotype_class) {
7166 /* Special case these so the client doesn't have to handle Type objects */
7168 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7169 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7170 } else if (MONO_TYPE_IS_REFERENCE (t))
7171 buffer_add_value (buf, t, &val, domain);
7173 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7177 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7183 buffer_add_int (buf, 0);
7187 for (i = 0; i < cinfo->num_attrs; ++i) {
7188 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7191 buffer_add_int (buf, nattrs);
7193 for (i = 0; i < cinfo->num_attrs; ++i) {
7194 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7195 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7196 MonoArray *typed_args, *named_args;
7198 CattrNamedArg *arginfo;
7200 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo);
7202 buffer_add_methodid (buf, domain, attr->ctor);
7206 buffer_add_int (buf, mono_array_length (typed_args));
7207 for (j = 0; j < mono_array_length (typed_args); ++j) {
7208 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7210 t = mono_method_signature (attr->ctor)->params [j];
7212 buffer_add_cattr_arg (buf, t, domain, val);
7215 buffer_add_int (buf, 0);
7220 buffer_add_int (buf, mono_array_length (named_args));
7222 for (j = 0; j < mono_array_length (named_args); ++j) {
7223 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7225 if (arginfo [j].prop) {
7226 buffer_add_byte (buf, 0x54);
7227 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7228 } else if (arginfo [j].field) {
7229 buffer_add_byte (buf, 0x53);
7230 buffer_add_fieldid (buf, domain, arginfo [j].field);
7232 g_assert_not_reached ();
7235 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7238 buffer_add_int (buf, 0);
7244 /* FIXME: Code duplication with icall.c */
7246 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7251 mono_class_setup_interfaces (klass, error);
7252 if (!mono_error_ok (error))
7255 for (i = 0; i < klass->interface_count; i++) {
7256 ic = klass->interfaces [i];
7257 g_hash_table_insert (ifaces, ic, ic);
7259 collect_interfaces (ic, ifaces, error);
7260 if (!mono_error_ok (error))
7266 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7276 case CMD_TYPE_GET_INFO: {
7277 buffer_add_string (buf, klass->name_space);
7278 buffer_add_string (buf, klass->name);
7280 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7281 buffer_add_string (buf, name);
7283 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7284 buffer_add_moduleid (buf, domain, klass->image);
7285 buffer_add_typeid (buf, domain, klass->parent);
7286 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7287 buffer_add_typeid (buf, domain, klass->element_class);
7289 buffer_add_id (buf, 0);
7290 buffer_add_int (buf, klass->type_token);
7291 buffer_add_byte (buf, klass->rank);
7292 buffer_add_int (buf, klass->flags);
7294 type = &klass->byval_arg;
7295 // FIXME: Can't decide whenever a class represents a byref type
7298 if (type->type == MONO_TYPE_PTR)
7300 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7302 if (type->type == MONO_TYPE_VALUETYPE)
7304 if (klass->enumtype)
7306 if (klass->generic_container)
7308 if (klass->generic_container || klass->generic_class)
7310 buffer_add_byte (buf, b);
7313 while ((nested = mono_class_get_nested_types (klass, &iter)))
7315 buffer_add_int (buf, nnested);
7317 while ((nested = mono_class_get_nested_types (klass, &iter)))
7318 buffer_add_typeid (buf, domain, nested);
7319 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7320 if (klass->generic_container)
7321 buffer_add_typeid (buf, domain, klass);
7322 else if (klass->generic_class)
7323 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7325 buffer_add_id (buf, 0);
7327 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7330 if (klass->generic_class) {
7331 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7333 count = inst->type_argc;
7334 buffer_add_int (buf, count);
7335 for (i = 0; i < count; i++)
7336 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7337 } else if (klass->generic_container) {
7338 MonoGenericContainer *container = klass->generic_container;
7341 count = container->type_argc;
7342 buffer_add_int (buf, count);
7343 for (i = 0; i < count; i++) {
7344 pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
7345 buffer_add_typeid (buf, domain, pklass);
7348 buffer_add_int (buf, 0);
7353 case CMD_TYPE_GET_METHODS: {
7356 gpointer iter = NULL;
7359 mono_class_setup_methods (klass);
7361 nmethods = mono_class_num_methods (klass);
7363 buffer_add_int (buf, nmethods);
7365 while ((m = mono_class_get_methods (klass, &iter))) {
7366 buffer_add_methodid (buf, domain, m);
7369 g_assert (i == nmethods);
7372 case CMD_TYPE_GET_FIELDS: {
7375 gpointer iter = NULL;
7378 nfields = mono_class_num_fields (klass);
7380 buffer_add_int (buf, nfields);
7382 while ((f = mono_class_get_fields (klass, &iter))) {
7383 buffer_add_fieldid (buf, domain, f);
7384 buffer_add_string (buf, f->name);
7385 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7386 buffer_add_int (buf, f->type->attrs);
7389 g_assert (i == nfields);
7392 case CMD_TYPE_GET_PROPERTIES: {
7395 gpointer iter = NULL;
7398 nprops = mono_class_num_properties (klass);
7400 buffer_add_int (buf, nprops);
7402 while ((p = mono_class_get_properties (klass, &iter))) {
7403 buffer_add_propertyid (buf, domain, p);
7404 buffer_add_string (buf, p->name);
7405 buffer_add_methodid (buf, domain, p->get);
7406 buffer_add_methodid (buf, domain, p->set);
7407 buffer_add_int (buf, p->attrs);
7410 g_assert (i == nprops);
7413 case CMD_TYPE_GET_CATTRS: {
7414 MonoClass *attr_klass;
7415 MonoCustomAttrInfo *cinfo;
7417 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7418 /* attr_klass can be NULL */
7422 cinfo = mono_custom_attrs_from_class (klass);
7424 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7427 case CMD_TYPE_GET_FIELD_CATTRS: {
7428 MonoClass *attr_klass;
7429 MonoCustomAttrInfo *cinfo;
7430 MonoClassField *field;
7432 field = decode_fieldid (p, &p, end, NULL, &err);
7435 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7439 cinfo = mono_custom_attrs_from_field (klass, field);
7441 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7444 case CMD_TYPE_GET_PROPERTY_CATTRS: {
7445 MonoClass *attr_klass;
7446 MonoCustomAttrInfo *cinfo;
7449 prop = decode_propertyid (p, &p, end, NULL, &err);
7452 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7456 cinfo = mono_custom_attrs_from_property (klass, prop);
7458 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7461 case CMD_TYPE_GET_VALUES:
7462 case CMD_TYPE_GET_VALUES_2: {
7469 MonoThread *thread_obj;
7470 MonoInternalThread *thread = NULL;
7471 guint32 special_static_type;
7473 if (command == CMD_TYPE_GET_VALUES_2) {
7474 int objid = decode_objid (p, &p, end);
7477 err = get_object (objid, (MonoObject**)&thread_obj);
7481 thread = THREAD_TO_INTERNAL (thread_obj);
7484 len = decode_int (p, &p, end);
7485 for (i = 0; i < len; ++i) {
7486 f = decode_fieldid (p, &p, end, NULL, &err);
7490 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7491 return ERR_INVALID_FIELDID;
7492 special_static_type = mono_class_field_get_special_static_type (f);
7493 if (special_static_type != SPECIAL_STATIC_NONE) {
7494 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
7495 return ERR_INVALID_FIELDID;
7498 /* Check that the field belongs to the object */
7500 for (k = klass; k; k = k->parent) {
7501 if (k == f->parent) {
7507 return ERR_INVALID_FIELDID;
7509 vtable = mono_class_vtable (domain, f->parent);
7510 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7511 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
7512 buffer_add_value (buf, f->type, val, domain);
7517 case CMD_TYPE_SET_VALUES: {
7525 len = decode_int (p, &p, end);
7526 for (i = 0; i < len; ++i) {
7527 f = decode_fieldid (p, &p, end, NULL, &err);
7531 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7532 return ERR_INVALID_FIELDID;
7533 if (mono_class_field_is_special_static (f))
7534 return ERR_INVALID_FIELDID;
7536 /* Check that the field belongs to the object */
7538 for (k = klass; k; k = k->parent) {
7539 if (k == f->parent) {
7545 return ERR_INVALID_FIELDID;
7547 // FIXME: Check for literal/const
7549 vtable = mono_class_vtable (domain, f->parent);
7550 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7551 err = decode_value (f->type, domain, val, p, &p, end);
7556 if (MONO_TYPE_IS_REFERENCE (f->type))
7557 mono_field_static_set_value (vtable, f, *(gpointer*)val);
7559 mono_field_static_set_value (vtable, f, val);
7564 case CMD_TYPE_GET_OBJECT: {
7565 MonoObject *o = (MonoObject*)mono_type_get_object (domain, &klass->byval_arg);
7566 buffer_add_objid (buf, o);
7569 case CMD_TYPE_GET_SOURCE_FILES:
7570 case CMD_TYPE_GET_SOURCE_FILES_2: {
7571 char *source_file, *base;
7575 files = get_source_files_for_type (klass);
7577 buffer_add_int (buf, files->len);
7578 for (i = 0; i < files->len; ++i) {
7579 source_file = g_ptr_array_index (files, i);
7580 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
7581 buffer_add_string (buf, source_file);
7583 base = g_path_get_basename (source_file);
7584 buffer_add_string (buf, base);
7587 g_free (source_file);
7589 g_ptr_array_free (files, TRUE);
7592 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
7593 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
7597 if (mono_class_is_assignable_from (klass, oklass))
7598 buffer_add_byte (buf, 1);
7600 buffer_add_byte (buf, 0);
7603 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
7604 char *name = decode_string (p, &p, end);
7605 int i, flags = decode_int (p, &p, end);
7606 MonoException *ex = NULL;
7607 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
7610 return ERR_LOADER_ERROR;
7611 buffer_add_int (buf, array->len);
7612 for (i = 0; i < array->len; ++i) {
7613 MonoMethod *method = g_ptr_array_index (array, i);
7614 buffer_add_methodid (buf, domain, method);
7617 g_ptr_array_free (array, TRUE);
7621 case CMD_TYPE_GET_INTERFACES: {
7623 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
7625 MonoClass *tclass, *iface;
7626 GHashTableIter iter;
7630 for (parent = tclass; parent; parent = parent->parent) {
7631 mono_class_setup_interfaces (parent, &error);
7632 if (!mono_error_ok (&error))
7633 return ERR_LOADER_ERROR;
7634 collect_interfaces (parent, iface_hash, &error);
7635 if (!mono_error_ok (&error))
7636 return ERR_LOADER_ERROR;
7639 buffer_add_int (buf, g_hash_table_size (iface_hash));
7641 g_hash_table_iter_init (&iter, iface_hash);
7642 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
7643 buffer_add_typeid (buf, domain, iface);
7644 g_hash_table_destroy (iface_hash);
7647 case CMD_TYPE_GET_INTERFACE_MAP: {
7648 int tindex, ioffset;
7649 gboolean variance_used;
7651 int len, nmethods, i;
7655 len = decode_int (p, &p, end);
7656 mono_class_setup_vtable (klass);
7658 for (tindex = 0; tindex < len; ++tindex) {
7659 iclass = decode_typeid (p, &p, end, NULL, &err);
7663 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
7665 return ERR_INVALID_ARGUMENT;
7667 nmethods = mono_class_num_methods (iclass);
7668 buffer_add_int (buf, nmethods);
7671 while ((method = mono_class_get_methods (iclass, &iter))) {
7672 buffer_add_methodid (buf, domain, method);
7674 for (i = 0; i < nmethods; ++i)
7675 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
7680 return ERR_NOT_IMPLEMENTED;
7687 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7690 MonoDomain *old_domain;
7694 klass = decode_typeid (p, &p, end, &domain, &err);
7698 old_domain = mono_domain_get ();
7700 mono_domain_set (domain, TRUE);
7702 err = type_commands_internal (command, klass, domain, p, end, buf);
7704 mono_domain_set (old_domain, TRUE);
7710 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7712 MonoMethodHeader *header;
7716 case CMD_METHOD_GET_NAME: {
7717 buffer_add_string (buf, method->name);
7720 case CMD_METHOD_GET_DECLARING_TYPE: {
7721 buffer_add_typeid (buf, domain, method->klass);
7724 case CMD_METHOD_GET_DEBUG_INFO: {
7725 MonoDebugMethodInfo *minfo;
7727 int i, j, n_il_offsets;
7730 int *column_numbers;
7732 GPtrArray *source_file_list;
7734 header = mono_method_get_header (method);
7736 buffer_add_int (buf, 0);
7737 buffer_add_string (buf, "");
7738 buffer_add_int (buf, 0);
7742 minfo = mono_debug_lookup_method (method);
7744 buffer_add_int (buf, header->code_size);
7745 buffer_add_string (buf, "");
7746 buffer_add_int (buf, 0);
7747 mono_metadata_free_mh (header);
7751 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, &n_il_offsets, &il_offsets, &line_numbers, &column_numbers, &source_files);
7752 buffer_add_int (buf, header->code_size);
7753 if (CHECK_PROTOCOL_VERSION (2, 13)) {
7754 buffer_add_int (buf, source_file_list->len);
7755 for (i = 0; i < source_file_list->len; ++i) {
7756 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
7757 buffer_add_string (buf, sinfo->source_file);
7758 if (CHECK_PROTOCOL_VERSION (2, 14)) {
7759 for (j = 0; j < 16; ++j)
7760 buffer_add_byte (buf, sinfo->hash [j]);
7764 buffer_add_string (buf, source_file);
7766 buffer_add_int (buf, n_il_offsets);
7767 DEBUG (10, fprintf (log_file, "Line number table for method %s:\n", mono_method_full_name (method, TRUE)));
7768 for (i = 0; i < n_il_offsets; ++i) {
7769 const char *srcfile = "";
7771 if (source_files [i] != -1) {
7772 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
7773 srcfile = sinfo->source_file;
7775 DEBUG (10, fprintf (log_file, "IL%x -> %s:%d %d\n", il_offsets [i], srcfile, line_numbers [i], column_numbers ? column_numbers [i] : -1));
7776 buffer_add_int (buf, il_offsets [i]);
7777 buffer_add_int (buf, line_numbers [i]);
7778 if (CHECK_PROTOCOL_VERSION (2, 13))
7779 buffer_add_int (buf, source_files [i]);
7780 if (CHECK_PROTOCOL_VERSION (2, 19))
7781 buffer_add_int (buf, column_numbers ? column_numbers [i] : -1);
7783 g_free (source_file);
7784 g_free (il_offsets);
7785 g_free (line_numbers);
7786 g_free (source_files);
7787 g_ptr_array_free (source_file_list, TRUE);
7788 mono_metadata_free_mh (header);
7791 case CMD_METHOD_GET_PARAM_INFO: {
7792 MonoMethodSignature *sig = mono_method_signature (method);
7796 /* FIXME: mono_class_from_mono_type () and byrefs */
7798 /* FIXME: Use a smaller encoding */
7799 buffer_add_int (buf, sig->call_convention);
7800 buffer_add_int (buf, sig->param_count);
7801 buffer_add_int (buf, sig->generic_param_count);
7802 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
7803 for (i = 0; i < sig->param_count; ++i) {
7805 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
7808 /* Emit parameter names */
7809 names = g_new (char *, sig->param_count);
7810 mono_method_get_param_names (method, (const char **) names);
7811 for (i = 0; i < sig->param_count; ++i)
7812 buffer_add_string (buf, names [i]);
7817 case CMD_METHOD_GET_LOCALS_INFO: {
7818 int i, j, num_locals;
7819 MonoDebugLocalsInfo *locals;
7821 header = mono_method_get_header (method);
7823 return ERR_INVALID_ARGUMENT;
7825 buffer_add_int (buf, header->num_locals);
7828 for (i = 0; i < header->num_locals; ++i)
7829 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
7832 locals = mono_debug_lookup_locals (method);
7834 num_locals = locals->num_locals;
7837 for (i = 0; i < header->num_locals; ++i) {
7838 for (j = 0; j < num_locals; ++j)
7839 if (locals->locals [j].index == i)
7842 buffer_add_string (buf, locals->locals [j].name);
7844 buffer_add_string (buf, "");
7848 for (i = 0; i < header->num_locals; ++i) {
7849 for (j = 0; j < num_locals; ++j)
7850 if (locals->locals [j].index == i)
7852 if (j < num_locals && locals->locals [j].block) {
7853 buffer_add_int (buf, locals->locals [j].block->start_offset);
7854 buffer_add_int (buf, locals->locals [j].block->end_offset);
7856 buffer_add_int (buf, 0);
7857 buffer_add_int (buf, header->code_size);
7860 mono_metadata_free_mh (header);
7863 mono_debug_symfile_free_locals (locals);
7867 case CMD_METHOD_GET_INFO:
7868 buffer_add_int (buf, method->flags);
7869 buffer_add_int (buf, method->iflags);
7870 buffer_add_int (buf, method->token);
7871 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7873 if (method->is_generic)
7875 if (mono_method_signature (method)->generic_param_count)
7877 buffer_add_byte (buf, attrs);
7878 if (method->is_generic || method->is_inflated) {
7881 if (method->is_generic) {
7884 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
7886 result = imethod->declaring;
7887 if (imethod->context.class_inst) {
7888 MonoClass *klass = ((MonoMethod *) imethod)->klass;
7889 /*Generic methods gets the context of the GTD.*/
7890 if (mono_class_get_context (klass))
7891 result = mono_class_inflate_generic_method_full (result, klass, mono_class_get_context (klass));
7895 buffer_add_methodid (buf, domain, result);
7897 buffer_add_id (buf, 0);
7899 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7900 if (mono_method_signature (method)->generic_param_count) {
7903 if (method->is_inflated) {
7904 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
7906 count = inst->type_argc;
7907 buffer_add_int (buf, count);
7909 for (i = 0; i < count; i++)
7910 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7912 buffer_add_int (buf, 0);
7914 } else if (method->is_generic) {
7915 MonoGenericContainer *container = mono_method_get_generic_container (method);
7917 count = mono_method_signature (method)->generic_param_count;
7918 buffer_add_int (buf, count);
7919 for (i = 0; i < count; i++) {
7920 MonoGenericParam *param = mono_generic_container_get_param (container, i);
7921 MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
7922 buffer_add_typeid (buf, domain, pklass);
7925 buffer_add_int (buf, 0);
7928 buffer_add_int (buf, 0);
7933 case CMD_METHOD_GET_BODY: {
7936 header = mono_method_get_header (method);
7938 buffer_add_int (buf, 0);
7940 if (CHECK_PROTOCOL_VERSION (2, 18))
7941 buffer_add_int (buf, 0);
7943 buffer_add_int (buf, header->code_size);
7944 for (i = 0; i < header->code_size; ++i)
7945 buffer_add_byte (buf, header->code [i]);
7947 if (CHECK_PROTOCOL_VERSION (2, 18)) {
7948 buffer_add_int (buf, header->num_clauses);
7949 for (i = 0; i < header->num_clauses; ++i) {
7950 MonoExceptionClause *clause = &header->clauses [i];
7952 buffer_add_int (buf, clause->flags);
7953 buffer_add_int (buf, clause->try_offset);
7954 buffer_add_int (buf, clause->try_len);
7955 buffer_add_int (buf, clause->handler_offset);
7956 buffer_add_int (buf, clause->handler_len);
7957 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
7958 buffer_add_typeid (buf, domain, clause->data.catch_class);
7959 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
7960 buffer_add_int (buf, clause->data.filter_offset);
7964 mono_metadata_free_mh (header);
7969 case CMD_METHOD_RESOLVE_TOKEN: {
7970 guint32 token = decode_int (p, &p, end);
7973 switch (mono_metadata_token_code (token)) {
7974 case MONO_TOKEN_STRING: {
7978 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
7981 s2 = mono_string_to_utf8 (s);
7983 buffer_add_byte (buf, TOKEN_TYPE_STRING);
7984 buffer_add_string (buf, s2);
7990 MonoClass *handle_class;
7992 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
7993 val = mono_method_get_wrapper_data (method, token);
7994 handle_class = mono_method_get_wrapper_data (method, token + 1);
7996 if (handle_class == NULL) {
7997 // Can't figure out the token type
7998 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8002 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
8006 if (handle_class == mono_defaults.typehandle_class) {
8007 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8008 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8009 buffer_add_typeid (buf, domain, (MonoClass *) val);
8011 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
8012 } else if (handle_class == mono_defaults.fieldhandle_class) {
8013 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8014 buffer_add_fieldid (buf, domain, val);
8015 } else if (handle_class == mono_defaults.methodhandle_class) {
8016 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8017 buffer_add_methodid (buf, domain, val);
8018 } else if (handle_class == mono_defaults.string_class) {
8021 s = mono_string_to_utf8 (val);
8022 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8023 buffer_add_string (buf, s);
8026 g_assert_not_reached ();
8033 case CMD_METHOD_GET_CATTRS: {
8034 MonoClass *attr_klass;
8035 MonoCustomAttrInfo *cinfo;
8037 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8038 /* attr_klass can be NULL */
8042 cinfo = mono_custom_attrs_from_method (method);
8044 buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
8048 return ERR_NOT_IMPLEMENTED;
8055 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8058 MonoDomain *old_domain;
8062 method = decode_methodid (p, &p, end, &domain, &err);
8066 old_domain = mono_domain_get ();
8068 mono_domain_set (domain, TRUE);
8070 err = method_commands_internal (command, method, domain, p, end, buf);
8072 mono_domain_set (old_domain, TRUE);
8078 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8080 int objid = decode_objid (p, &p, end);
8082 MonoThread *thread_obj;
8083 MonoInternalThread *thread;
8085 err = get_object (objid, (MonoObject**)&thread_obj);
8089 thread = THREAD_TO_INTERNAL (thread_obj);
8092 case CMD_THREAD_GET_NAME: {
8094 gunichar2 *s = mono_thread_get_name (thread, &name_len);
8097 buffer_add_int (buf, 0);
8102 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
8104 buffer_add_int (buf, len);
8105 buffer_add_data (buf, (guint8*)name, len);
8110 case CMD_THREAD_GET_FRAME_INFO: {
8111 DebuggerTlsData *tls;
8112 int i, start_frame, length;
8114 // Wait for suspending if it already started
8115 // FIXME: Races with suspend_count
8116 while (!is_suspended ()) {
8118 wait_for_suspend ();
8122 wait_for_suspend ();
8123 if (!is_suspended ())
8124 return ERR_NOT_SUSPENDED;
8127 start_frame = decode_int (p, &p, end);
8128 length = decode_int (p, &p, end);
8130 if (start_frame != 0 || length != -1)
8131 return ERR_NOT_IMPLEMENTED;
8133 mono_loader_lock ();
8134 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8135 mono_loader_unlock ();
8138 compute_frame_info (thread, tls);
8140 buffer_add_int (buf, tls->frame_count);
8141 for (i = 0; i < tls->frame_count; ++i) {
8142 buffer_add_int (buf, tls->frames [i]->id);
8143 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
8144 buffer_add_int (buf, tls->frames [i]->il_offset);
8146 * Instead of passing the frame type directly to the client, we associate
8147 * it with the previous frame using a set of flags. This avoids lots of
8148 * conditional code in the client, since a frame whose type isn't
8149 * FRAME_TYPE_MANAGED has no method, location, etc.
8151 buffer_add_byte (buf, tls->frames [i]->flags);
8156 case CMD_THREAD_GET_STATE:
8157 buffer_add_int (buf, thread->state);
8159 case CMD_THREAD_GET_INFO:
8160 buffer_add_byte (buf, thread->threadpool_thread);
8162 case CMD_THREAD_GET_ID:
8163 buffer_add_long (buf, (guint64)(gsize)thread);
8165 case CMD_THREAD_GET_TID:
8166 buffer_add_long (buf, (guint64)thread->tid);
8169 return ERR_NOT_IMPLEMENTED;
8176 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8180 MonoThread *thread_obj;
8181 MonoInternalThread *thread;
8182 int pos, i, len, frame_idx;
8183 DebuggerTlsData *tls;
8185 MonoDebugMethodJitInfo *jit;
8186 MonoDebugVarInfo *var;
8187 MonoMethodSignature *sig;
8189 MonoMethodHeader *header;
8191 objid = decode_objid (p, &p, end);
8192 err = get_object (objid, (MonoObject**)&thread_obj);
8196 thread = THREAD_TO_INTERNAL (thread_obj);
8198 id = decode_id (p, &p, end);
8200 mono_loader_lock ();
8201 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8202 mono_loader_unlock ();
8205 for (i = 0; i < tls->frame_count; ++i) {
8206 if (tls->frames [i]->id == id)
8209 if (i == tls->frame_count)
8210 return ERR_INVALID_FRAMEID;
8213 frame = tls->frames [frame_idx];
8215 if (!frame->has_ctx)
8217 return ERR_INVALID_FRAMEID;
8220 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
8221 if (!frame->jit && frame->api_method->is_inflated)
8222 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
8226 /* This could happen for aot images with no jit debug info */
8227 s = mono_method_full_name (frame->api_method, TRUE);
8228 DEBUG (1, fprintf (log_file, "[dbg] No debug information found for '%s'.\n", s));
8230 return ERR_ABSENT_INFORMATION;
8235 sig = mono_method_signature (frame->actual_method);
8237 if (!get_seq_points (frame->domain, frame->actual_method))
8239 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
8241 return ERR_ABSENT_INFORMATION;
8244 case CMD_STACK_FRAME_GET_VALUES: {
8245 len = decode_int (p, &p, end);
8246 header = mono_method_get_header (frame->actual_method);
8248 for (i = 0; i < len; ++i) {
8249 pos = decode_int (p, &p, end);
8254 g_assert (pos >= 0 && pos < jit->num_params);
8256 var = &jit->params [pos];
8258 add_var (buf, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
8260 g_assert (pos >= 0 && pos < jit->num_locals);
8262 var = &jit->locals [pos];
8264 add_var (buf, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
8267 mono_metadata_free_mh (header);
8270 case CMD_STACK_FRAME_GET_THIS: {
8271 if (frame->api_method->klass->valuetype) {
8272 if (!sig->hasthis) {
8273 MonoObject *p = NULL;
8274 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
8276 add_var (buf, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8279 if (!sig->hasthis) {
8280 MonoObject *p = NULL;
8281 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
8283 add_var (buf, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8288 case CMD_STACK_FRAME_SET_VALUES: {
8291 MonoDebugVarInfo *var;
8293 len = decode_int (p, &p, end);
8294 header = mono_method_get_header (frame->actual_method);
8296 for (i = 0; i < len; ++i) {
8297 pos = decode_int (p, &p, end);
8302 g_assert (pos >= 0 && pos < jit->num_params);
8304 t = sig->params [pos];
8305 var = &jit->params [pos];
8307 g_assert (pos >= 0 && pos < jit->num_locals);
8309 t = header->locals [pos];
8310 var = &jit->locals [pos];
8313 if (MONO_TYPE_IS_REFERENCE (t))
8314 val_buf = g_alloca (sizeof (MonoObject*));
8316 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
8317 err = decode_value (t, frame->domain, val_buf, p, &p, end);
8321 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_ctx);
8323 mono_metadata_free_mh (header);
8327 return ERR_NOT_IMPLEMENTED;
8334 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8337 int objid, err, index, len, i, esize;
8340 objid = decode_objid (p, &p, end);
8341 err = get_object (objid, (MonoObject**)&arr);
8346 case CMD_ARRAY_REF_GET_LENGTH:
8347 buffer_add_int (buf, arr->obj.vtable->klass->rank);
8349 buffer_add_int (buf, arr->max_length);
8350 buffer_add_int (buf, 0);
8352 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
8353 buffer_add_int (buf, arr->bounds [i].length);
8354 buffer_add_int (buf, arr->bounds [i].lower_bound);
8358 case CMD_ARRAY_REF_GET_VALUES:
8359 index = decode_int (p, &p, end);
8360 len = decode_int (p, &p, end);
8362 g_assert (index >= 0 && len >= 0);
8363 // Reordered to avoid integer overflow
8364 g_assert (!(index > arr->max_length - len));
8366 esize = mono_array_element_size (arr->obj.vtable->klass);
8367 for (i = index; i < index + len; ++i) {
8368 elem = (gpointer*)((char*)arr->vector + (i * esize));
8369 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
8372 case CMD_ARRAY_REF_SET_VALUES:
8373 index = decode_int (p, &p, end);
8374 len = decode_int (p, &p, end);
8376 g_assert (index >= 0 && len >= 0);
8377 // Reordered to avoid integer overflow
8378 g_assert (!(index > arr->max_length - len));
8380 esize = mono_array_element_size (arr->obj.vtable->klass);
8381 for (i = index; i < index + len; ++i) {
8382 elem = (gpointer*)((char*)arr->vector + (i * esize));
8384 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
8388 return ERR_NOT_IMPLEMENTED;
8395 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8400 int i, index, length;
8403 objid = decode_objid (p, &p, end);
8404 err = get_object (objid, (MonoObject**)&str);
8409 case CMD_STRING_REF_GET_VALUE:
8410 s = mono_string_to_utf8 (str);
8411 buffer_add_string (buf, s);
8414 case CMD_STRING_REF_GET_LENGTH:
8415 buffer_add_long (buf, mono_string_length (str));
8417 case CMD_STRING_REF_GET_CHARS:
8418 index = decode_long (p, &p, end);
8419 length = decode_long (p, &p, end);
8420 if (index > mono_string_length (str) - length)
8421 return ERR_INVALID_ARGUMENT;
8422 c = mono_string_chars (str) + index;
8423 for (i = 0; i < length; ++i)
8424 buffer_add_short (buf, c [i]);
8427 return ERR_NOT_IMPLEMENTED;
8434 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8443 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
8444 objid = decode_objid (p, &p, end);
8445 err = get_object (objid, &obj);
8447 buffer_add_int (buf, 1);
8449 buffer_add_int (buf, 0);
8453 objid = decode_objid (p, &p, end);
8454 err = get_object (objid, &obj);
8459 case CMD_OBJECT_REF_GET_TYPE:
8460 /* This handles transparent proxies too */
8461 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8463 case CMD_OBJECT_REF_GET_VALUES:
8464 len = decode_int (p, &p, end);
8466 for (i = 0; i < len; ++i) {
8467 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
8471 /* Check that the field belongs to the object */
8473 for (k = obj->vtable->klass; k; k = k->parent) {
8474 if (k == f->parent) {
8480 return ERR_INVALID_FIELDID;
8482 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8486 if (mono_class_field_is_special_static (f))
8487 return ERR_INVALID_FIELDID;
8489 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8490 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8491 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8492 mono_field_static_get_value (vtable, f, val);
8493 buffer_add_value (buf, f->type, val, obj->vtable->domain);
8496 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
8500 case CMD_OBJECT_REF_SET_VALUES:
8501 len = decode_int (p, &p, end);
8503 for (i = 0; i < len; ++i) {
8504 f = decode_fieldid (p, &p, end, NULL, &err);
8508 /* Check that the field belongs to the object */
8510 for (k = obj->vtable->klass; k; k = k->parent) {
8511 if (k == f->parent) {
8517 return ERR_INVALID_FIELDID;
8519 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8523 if (mono_class_field_is_special_static (f))
8524 return ERR_INVALID_FIELDID;
8526 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8527 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8529 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8530 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
8535 mono_field_static_set_value (vtable, f, val);
8538 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
8544 case CMD_OBJECT_REF_GET_ADDRESS:
8545 buffer_add_long (buf, (gssize)obj);
8547 case CMD_OBJECT_REF_GET_DOMAIN:
8548 buffer_add_domainid (buf, obj->vtable->domain);
8550 case CMD_OBJECT_REF_GET_INFO:
8551 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8552 buffer_add_domainid (buf, obj->vtable->domain);
8555 return ERR_NOT_IMPLEMENTED;
8562 command_set_to_string (CommandSet command_set)
8564 switch (command_set) {
8567 case CMD_SET_OBJECT_REF:
8568 return "OBJECT_REF";
8569 case CMD_SET_STRING_REF:
8570 return "STRING_REF";
8571 case CMD_SET_THREAD:
8573 case CMD_SET_ARRAY_REF:
8575 case CMD_SET_EVENT_REQUEST:
8576 return "EVENT_REQUEST";
8577 case CMD_SET_STACK_FRAME:
8578 return "STACK_FRAME";
8579 case CMD_SET_APPDOMAIN:
8581 case CMD_SET_ASSEMBLY:
8583 case CMD_SET_METHOD:
8587 case CMD_SET_MODULE:
8597 cmd_to_string (CommandSet set, int command)
8602 case CMD_VM_VERSION:
8604 case CMD_VM_ALL_THREADS:
8605 return "ALL_THREADS";
8606 case CMD_VM_SUSPEND:
8612 case CMD_VM_DISPOSE:
8614 case CMD_VM_INVOKE_METHOD:
8615 return "INVOKE_METHOD";
8616 case CMD_VM_SET_PROTOCOL_VERSION:
8617 return "SET_PROTOCOL_VERSION";
8618 case CMD_VM_ABORT_INVOKE:
8619 return "ABORT_INVOKE";
8620 case CMD_VM_SET_KEEPALIVE:
8621 return "SET_KEEPALIVE";
8634 wait_for_attach (void)
8636 #ifndef DISABLE_SOCKET_TRANSPORT
8637 if (listen_fd == -1) {
8638 DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
8642 /* Block and wait for client connection */
8643 conn_fd = socket_transport_accept (listen_fd);
8644 DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
8645 if (conn_fd == -1) {
8646 DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
8650 g_assert_not_reached ();
8654 disconnected = !transport_handshake ();
8656 DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
8666 * This thread handles communication with the debugger client using a JDWP
8669 static guint32 WINAPI
8670 debugger_thread (void *arg)
8672 int res, len, id, flags, command_set = 0, command = 0;
8673 guint8 header [HEADER_LENGTH];
8674 guint8 *data, *p, *end;
8678 gboolean attach_failed = FALSE;
8680 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
8682 debugger_thread_id = GetCurrentThreadId ();
8684 mono_jit_thread_attach (mono_get_root_domain ());
8686 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
8688 mono_set_is_debugger_attached (TRUE);
8690 if (agent_config.defer) {
8691 if (!wait_for_attach ()) {
8692 DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
8693 attach_failed = TRUE; // Don't abort process when we can't listen
8695 /* Send start event to client */
8696 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
8700 while (!attach_failed) {
8701 res = transport_recv (header, HEADER_LENGTH);
8703 /* This will break if the socket is closed during shutdown too */
8704 if (res != HEADER_LENGTH) {
8705 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH));
8710 end = header + HEADER_LENGTH;
8712 len = decode_int (p, &p, end);
8713 id = decode_int (p, &p, end);
8714 flags = decode_byte (p, &p, end);
8715 command_set = decode_byte (p, &p, end);
8716 command = decode_byte (p, &p, end);
8718 g_assert (flags == 0);
8721 const char *cmd_str;
8724 cmd_str = cmd_to_string (command_set, command);
8726 sprintf (cmd_num, "%d", command);
8730 DEBUG (1, fprintf (log_file, "[dbg] Received command %s(%s), id=%d.\n", command_set_to_string (command_set), cmd_str, id));
8733 data = g_malloc (len - HEADER_LENGTH);
8734 if (len - HEADER_LENGTH > 0)
8736 res = transport_recv (data, len - HEADER_LENGTH);
8737 if (res != len - HEADER_LENGTH) {
8738 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH));
8744 end = data + (len - HEADER_LENGTH);
8746 buffer_init (&buf, 128);
8751 /* Process the request */
8752 switch (command_set) {
8754 err = vm_commands (command, id, p, end, &buf);
8755 if (!err && command == CMD_VM_INVOKE_METHOD)
8756 /* Sent after the invoke is complete */
8759 case CMD_SET_EVENT_REQUEST:
8760 err = event_commands (command, p, end, &buf);
8762 case CMD_SET_APPDOMAIN:
8763 err = domain_commands (command, p, end, &buf);
8765 case CMD_SET_ASSEMBLY:
8766 err = assembly_commands (command, p, end, &buf);
8768 case CMD_SET_MODULE:
8769 err = module_commands (command, p, end, &buf);
8772 err = type_commands (command, p, end, &buf);
8774 case CMD_SET_METHOD:
8775 err = method_commands (command, p, end, &buf);
8777 case CMD_SET_THREAD:
8778 err = thread_commands (command, p, end, &buf);
8780 case CMD_SET_STACK_FRAME:
8781 err = frame_commands (command, p, end, &buf);
8783 case CMD_SET_ARRAY_REF:
8784 err = array_commands (command, p, end, &buf);
8786 case CMD_SET_STRING_REF:
8787 err = string_commands (command, p, end, &buf);
8789 case CMD_SET_OBJECT_REF:
8790 err = object_commands (command, p, end, &buf);
8793 err = ERR_NOT_IMPLEMENTED;
8797 send_reply_packet (id, err, &buf);
8802 if (command_set == CMD_SET_VM && command == CMD_VM_DISPOSE)
8806 mono_set_is_debugger_attached (FALSE);
8808 mono_mutex_lock (&debugger_thread_exited_mutex);
8809 debugger_thread_exited = TRUE;
8810 mono_cond_signal (&debugger_thread_exited_cond);
8811 mono_mutex_unlock (&debugger_thread_exited_mutex);
8813 DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
8815 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
8816 DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
8817 start_debugger_thread ();
8823 #else /* DISABLE_DEBUGGER_AGENT */
8826 mono_debugger_agent_parse_options (char *options)
8828 g_error ("This runtime is configured with the debugger agent disabled.");
8832 mono_debugger_agent_init (void)
8837 mono_debugger_agent_breakpoint_hit (void *sigctx)
8842 mono_debugger_agent_single_step_event (void *sigctx)
8847 mono_debugger_agent_free_domain_info (MonoDomain *domain)
8852 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
8858 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
8859 MonoContext *catch_ctx)
8864 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
8869 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
8874 mono_debugger_agent_user_break (void)
8880 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
8885 mono_debugger_agent_debug_log_is_enabled (void)