2 * debugger-agent.c: Soft Debugger back-end module
5 * Zoltan Varga (vargaz@gmail.com)
7 * Copyright 2009-2010 Novell, Inc.
8 * Copyright 2011 Xamarin Inc.
15 #ifdef HAVE_SYS_TYPES_H
16 #include <sys/types.h>
18 #ifdef HAVE_SYS_SELECT_H
19 #include <sys/select.h>
21 #ifdef HAVE_SYS_SOCKET_H
22 #include <sys/socket.h>
24 #ifdef HAVE_NETINET_TCP_H
25 #include <netinet/tcp.h>
27 #ifdef HAVE_NETINET_IN_H
28 #include <netinet/in.h>
43 #ifdef HAVE_UCONTEXT_H
53 /* cygwin's headers do not seem to define these */
54 void WSAAPI freeaddrinfo (struct addrinfo*);
55 int WSAAPI getaddrinfo (const char*,const char*,const struct addrinfo*,
57 int WSAAPI getnameinfo(const struct sockaddr*,socklen_t,char*,DWORD,
62 #ifdef PLATFORM_ANDROID
64 #include <linux/tcp.h>
65 #include <sys/endian.h>
68 #include <mono/metadata/mono-debug.h>
69 #include <mono/metadata/mono-debug-debugger.h>
70 #include <mono/metadata/debug-mono-symfile.h>
71 #include <mono/metadata/gc-internal.h>
72 #include <mono/metadata/threads-types.h>
73 #include <mono/metadata/socket-io.h>
74 #include <mono/metadata/assembly.h>
75 #include <mono/metadata/runtime.h>
76 #include <mono/metadata/threadpool.h>
77 #include <mono/utils/mono-semaphore.h>
78 #include <mono/utils/mono-error-internals.h>
79 #include <mono/utils/mono-stack-unwinding.h>
80 #include <mono/utils/mono-time.h>
81 #include <mono/utils/mono-threads.h>
82 #include "debugger-agent.h"
86 On iOS we can't use System.Environment.Exit () as it will do the wrong
89 #if !defined (TARGET_IOS)
90 #define TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
94 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
95 #define DISABLE_DEBUGGER_AGENT 1
98 #ifdef DISABLE_SOFT_DEBUG
99 #define DISABLE_DEBUGGER_AGENT 1
102 #ifndef DISABLE_DEBUGGER_AGENT
104 #include <mono/utils/mono-mutex.h>
106 /* Definitions to make backporting to 2.6 easier */
107 //#define MonoInternalThread MonoThread
108 //#define mono_thread_internal_current mono_thread_current
109 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
131 guint32 il_offset, native_offset;
135 * If method is gshared, this is the actual instance, otherwise this is equal to
138 MonoMethod *actual_method;
140 * This is the method which is visible to debugger clients. Same as method,
141 * except for native-to-managed wrappers.
143 MonoMethod *api_method;
145 MonoDebugMethodJitInfo *jit;
148 mgreg_t *reg_locations [MONO_MAX_IREGS];
150 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
151 * the frame can become invalid.
156 typedef struct _InvokeData InvokeData;
164 /* This is the context which needs to be restored after the invoke */
168 * If this is set, invoke this method with the arguments given by ARGS.
172 guint32 suspend_count;
175 InvokeData *last_invoke;
179 MonoThreadUnwindState context;
181 /* This is computed on demand when it is requested using the wire protocol */
182 /* It is freed up when the thread is resumed */
186 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
189 gboolean frames_up_to_date;
191 * Points to data about a pending invoke which needs to be executed after the thread
194 InvokeData *pending_invoke;
196 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
201 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
202 * within a finite amount of time.
206 * Set to TRUE if this thread is suspended in suspend_current ().
208 gboolean really_suspended;
209 /* Used to pass the context to the breakpoint/single step handler */
210 MonoContext handler_ctx;
211 /* Whenever thread_stop () was called for this thread */
214 /* Number of thread interruptions not yet processed */
215 gint32 interrupt_count;
217 /* Whenever to disable breakpoints (used during invokes) */
218 gboolean disable_breakpoints;
221 * Number of times this thread has been resumed using resume_thread ().
223 guint32 resume_count;
225 MonoInternalThread *thread;
228 * Information about the frame which transitioned to native code for running
231 StackFrameInfo async_last_frame;
234 * The context where the stack walk can be started for running threads.
236 MonoThreadUnwindState async_state;
239 * The context used for filter clauses
241 MonoThreadUnwindState filter_state;
244 * The callee address of the last mono_runtime_invoke call
246 gpointer invoke_addr;
248 gboolean abort_requested;
251 * The current mono_runtime_invoke invocation.
256 * The context where single stepping should resume while the thread is suspended because
257 * of an EXCEPTION event.
259 MonoThreadUnwindState catch_state;
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 23
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,
487 CMD_TYPE_IS_INITIALIZED = 18
491 CMD_STACK_FRAME_GET_VALUES = 1,
492 CMD_STACK_FRAME_GET_THIS = 2,
493 CMD_STACK_FRAME_SET_VALUES = 3
497 CMD_ARRAY_REF_GET_LENGTH = 1,
498 CMD_ARRAY_REF_GET_VALUES = 2,
499 CMD_ARRAY_REF_SET_VALUES = 3,
503 CMD_STRING_REF_GET_VALUE = 1,
504 CMD_STRING_REF_GET_LENGTH = 2,
505 CMD_STRING_REF_GET_CHARS = 3
509 CMD_OBJECT_REF_GET_TYPE = 1,
510 CMD_OBJECT_REF_GET_VALUES = 2,
511 CMD_OBJECT_REF_IS_COLLECTED = 3,
512 CMD_OBJECT_REF_GET_ADDRESS = 4,
513 CMD_OBJECT_REF_GET_DOMAIN = 5,
514 CMD_OBJECT_REF_SET_VALUES = 6,
515 CMD_OBJECT_REF_GET_INFO = 7,
521 int count; /* For kind == MOD_KIND_COUNT */
522 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
523 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
524 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
525 GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
526 GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
527 StepFilter filter; /* For kind == MOD_KIND_STEP */
529 gboolean caught, uncaught; /* For kind == MOD_KIND_EXCEPTION_ONLY */
538 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
542 * Describes a single step request.
546 MonoInternalThread *thread;
552 MonoMethod *last_method;
554 /* Whenever single stepping is performed using start/stop_single_stepping () */
556 /* The list of breakpoints used to implement step-over */
561 * Contains additional information for an event
564 /* For EVENT_KIND_EXCEPTION */
566 MonoContext catch_ctx;
568 /* For EVENT_KIND_USER_LOG */
570 char *category, *message;
571 /* For EVENT_KIND_TYPE_LOAD */
575 /* Dummy structure used for the profiler callbacks */
580 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
583 #define get_last_sock_error() WSAGetLastError()
584 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
585 #define MONO_EINTR WSAEINTR
587 #define get_last_sock_error() errno
588 #define MONO_EWOULDBLOCK EWOULDBLOCK
589 #define MONO_EINTR EINTR
592 #define CHECK_PROTOCOL_VERSION(major,minor) \
593 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
599 static AgentConfig agent_config;
602 * Whenever the agent is fully initialized.
603 * When using the onuncaught or onthrow options, only some parts of the agent are
604 * initialized on startup, and the full initialization which includes connection
605 * establishment and the startup of the agent thread is only done in response to
608 static gint32 inited;
610 #ifndef DISABLE_SOCKET_TRANSPORT
612 static int listen_fd;
615 static int packet_id = 0;
617 static int objref_id = 0;
619 static int event_request_id = 0;
621 static int frame_id = 0;
623 static GPtrArray *event_requests;
625 static MonoNativeTlsKey debugger_tls_id;
627 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
629 /* Maps MonoInternalThread -> DebuggerTlsData */
630 static MonoGHashTable *thread_to_tls;
632 /* Maps tid -> MonoInternalThread */
633 static MonoGHashTable *tid_to_thread;
635 /* Maps tid -> MonoThread (not MonoInternalThread) */
636 static MonoGHashTable *tid_to_thread_obj;
638 static gsize debugger_thread_id;
640 static HANDLE debugger_thread_handle;
642 static int log_level;
644 static gboolean embedding;
646 static FILE *log_file;
648 /* Assemblies whose assembly load event has no been sent yet */
649 static GPtrArray *pending_assembly_loads;
651 /* Whenever the debugger thread has exited */
652 static gboolean debugger_thread_exited;
654 /* Cond variable used to wait for debugger_thread_exited becoming true */
655 static mono_cond_t debugger_thread_exited_cond;
657 /* Mutex for the cond var above */
658 static mono_mutex_t debugger_thread_exited_mutex;
660 static DebuggerProfiler debugger_profiler;
662 /* The single step request instance */
663 static SingleStepReq *ss_req = NULL;
664 static gpointer ss_invoke_addr = NULL;
666 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
667 /* Number of single stepping operations in progress */
671 /* The protocol version of the client */
672 static int major_version, minor_version;
674 /* Whenever the variables above are set by the client */
675 static gboolean protocol_version_set;
677 /* A hash table containing all active domains */
678 static GHashTable *domains;
680 /* The number of times the runtime is suspended */
681 static gint32 suspend_count;
683 static void transport_init (void);
684 static void transport_connect (const char *address);
685 static gboolean transport_handshake (void);
686 static void register_transport (DebuggerTransport *trans);
688 static guint32 WINAPI debugger_thread (void *arg);
690 static void runtime_initialized (MonoProfiler *prof);
692 static void runtime_shutdown (MonoProfiler *prof);
694 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
696 static void thread_end (MonoProfiler *prof, uintptr_t tid);
698 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
700 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
702 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
704 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
706 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
708 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
710 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
712 static void emit_assembly_load (gpointer assembly, gpointer user_data);
714 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
716 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
718 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
720 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
722 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
724 static void start_single_stepping (void);
726 static void stop_single_stepping (void);
728 static void suspend_current (void);
730 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
732 static void clear_types_for_assembly (MonoAssembly *assembly);
734 static void clear_breakpoints_for_domain (MonoDomain *domain);
736 static void process_profiler_event (EventKind event, gpointer arg);
738 /* Submodule init/cleanup */
739 static void breakpoints_init (void);
740 static void breakpoints_cleanup (void);
742 static void objrefs_init (void);
743 static void objrefs_cleanup (void);
745 static void ids_init (void);
746 static void ids_cleanup (void);
748 static void suspend_init (void);
750 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch);
751 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
752 static void ss_destroy (SingleStepReq *req);
754 static void start_debugger_thread (void);
755 static void stop_debugger_thread (void);
757 static void finish_agent_init (gboolean on_startup);
759 static void process_profiler_event (EventKind event, gpointer arg);
761 static void invalidate_frames (DebuggerTlsData *tls);
763 #ifndef DISABLE_SOCKET_TRANSPORT
765 register_socket_transport (void);
769 parse_address (char *address, char **host, int *port)
771 char *pos = strchr (address, ':');
773 if (pos == NULL || pos == address)
776 *host = g_malloc (pos - address + 1);
777 strncpy (*host, address, pos - address);
778 (*host) [pos - address] = '\0';
780 *port = atoi (pos + 1);
788 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
789 fprintf (stderr, "Available options:\n");
790 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
791 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
792 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
793 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
794 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
795 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
796 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
797 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
798 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
802 parse_flag (const char *option, char *flag)
804 if (!strcmp (flag, "y"))
806 else if (!strcmp (flag, "n"))
809 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
816 mono_debugger_agent_parse_options (char *options)
823 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
824 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
828 extra = getenv ("MONO_SDB_ENV_OPTIONS");
830 options = g_strdup_printf ("%s,%s", options, extra);
832 agent_config.enabled = TRUE;
833 agent_config.suspend = TRUE;
834 agent_config.server = FALSE;
835 agent_config.defer = FALSE;
836 agent_config.address = NULL;
838 args = g_strsplit (options, ",", -1);
839 for (ptr = args; ptr && *ptr; ptr ++) {
842 if (strncmp (arg, "transport=", 10) == 0) {
843 agent_config.transport = g_strdup (arg + 10);
844 } else if (strncmp (arg, "address=", 8) == 0) {
845 agent_config.address = g_strdup (arg + 8);
846 } else if (strncmp (arg, "loglevel=", 9) == 0) {
847 agent_config.log_level = atoi (arg + 9);
848 } else if (strncmp (arg, "logfile=", 8) == 0) {
849 agent_config.log_file = g_strdup (arg + 8);
850 } else if (strncmp (arg, "suspend=", 8) == 0) {
851 agent_config.suspend = parse_flag ("suspend", arg + 8);
852 } else if (strncmp (arg, "server=", 7) == 0) {
853 agent_config.server = parse_flag ("server", arg + 7);
854 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
855 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
856 } else if (strncmp (arg, "onthrow=", 8) == 0) {
857 /* We support multiple onthrow= options */
858 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
859 } else if (strncmp (arg, "onthrow", 7) == 0) {
860 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
861 } else if (strncmp (arg, "help", 4) == 0) {
864 } else if (strncmp (arg, "timeout=", 8) == 0) {
865 agent_config.timeout = atoi (arg + 8);
866 } else if (strncmp (arg, "launch=", 7) == 0) {
867 agent_config.launch = g_strdup (arg + 7);
868 } else if (strncmp (arg, "embedding=", 10) == 0) {
869 agent_config.embedding = atoi (arg + 10) == 1;
870 } else if (strncmp (arg, "keepalive=", 10) == 0) {
871 agent_config.keepalive = atoi (arg + 10);
878 if (agent_config.server && !agent_config.suspend) {
879 /* Waiting for deferred attachment */
880 agent_config.defer = TRUE;
881 if (agent_config.address == NULL) {
882 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (GetCurrentProcessId () % 1000));
886 //agent_config.log_level = 0;
888 if (agent_config.transport == NULL) {
889 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
893 if (agent_config.address == NULL && !agent_config.server) {
894 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
899 if (!strcmp (agent_config.transport, "dt_socket")) {
900 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
901 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
908 mono_debugger_agent_init (void)
910 if (!agent_config.enabled)
915 /* Need to know whenever a thread has acquired the loader mutex */
916 mono_loader_lock_track_ownership (TRUE);
918 event_requests = g_ptr_array_new ();
920 mono_mutex_init (&debugger_thread_exited_mutex);
921 mono_cond_init (&debugger_thread_exited_cond, NULL);
923 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
924 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
925 mono_profiler_install_runtime_initialized (runtime_initialized);
926 mono_profiler_install_appdomain (NULL, appdomain_load, NULL, appdomain_unload);
927 mono_profiler_install_thread (thread_startup, thread_end);
928 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
929 mono_profiler_install_jit_end (jit_end);
930 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
932 mono_native_tls_alloc (&debugger_tls_id, NULL);
934 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
935 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls);
937 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
938 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread);
940 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
941 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj);
943 pending_assembly_loads = g_ptr_array_new ();
944 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
946 log_level = agent_config.log_level;
948 embedding = agent_config.embedding;
951 if (agent_config.log_file) {
952 log_file = fopen (agent_config.log_file, "w+");
954 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
966 mini_get_debug_options ()->gen_seq_points = TRUE;
968 * This is needed because currently we don't handle liveness info.
970 mini_get_debug_options ()->mdb_optimizations = TRUE;
972 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
973 /* This is needed because we can't set local variables in registers yet */
974 mono_disable_optimizations (MONO_OPT_LINEARS);
978 * The stack walk done from thread_interrupt () needs to be signal safe, but it
979 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
980 * safe (#3411). So load AOT info eagerly when the debugger is running as a
983 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
985 if (!agent_config.onuncaught && !agent_config.onthrow)
986 finish_agent_init (TRUE);
992 * Finish the initialization of the agent. This involves connecting the transport
993 * and starting the agent thread. This is either done at startup, or
994 * in response to some event like an unhandled exception.
997 finish_agent_init (gboolean on_startup)
1001 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
1004 if (agent_config.launch) {
1007 // FIXME: Generated address
1008 // FIXME: Races with transport_connect ()
1010 argv [0] = agent_config.launch;
1011 argv [1] = agent_config.transport;
1012 argv [2] = agent_config.address;
1015 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1017 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1022 transport_connect (agent_config.address);
1025 /* Do some which is usually done after sending the VMStart () event */
1026 vm_start_event_sent = TRUE;
1027 start_debugger_thread ();
1032 mono_debugger_agent_cleanup (void)
1037 stop_debugger_thread ();
1039 breakpoints_cleanup ();
1043 mono_mutex_destroy (&debugger_thread_exited_mutex);
1044 mono_cond_destroy (&debugger_thread_exited_cond);
1051 #ifndef DISABLE_SOCKET_TRANSPORT
1056 * recv() + handle incomplete reads and EINTR
1059 socket_transport_recv (void *buf, int len)
1065 static gint32 last_keepalive;
1070 res = recv (fd, (char *) buf + total, len - total, flags);
1073 if (agent_config.keepalive) {
1074 gboolean need_keepalive = FALSE;
1075 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1076 need_keepalive = TRUE;
1077 } else if (res == -1) {
1078 /* This could happen if recv () is interrupted repeatedly */
1079 msecs = mono_msec_ticks ();
1080 if (msecs - last_keepalive >= agent_config.keepalive) {
1081 need_keepalive = TRUE;
1082 last_keepalive = msecs;
1085 if (need_keepalive) {
1086 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1090 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1095 #define HAVE_GETADDRINFO 1
1099 set_keepalive (void)
1104 if (!agent_config.keepalive || !conn_fd)
1107 tv.tv_sec = agent_config.keepalive / 1000;
1108 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1110 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1111 g_assert (result >= 0);
1115 socket_transport_accept (int socket_fd)
1117 conn_fd = accept (socket_fd, NULL, NULL);
1118 if (conn_fd == -1) {
1119 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1121 DEBUG (1, fprintf (log_file, "Accepted connection from client, connection fd=%d.\n", conn_fd));
1128 socket_transport_send (void *data, int len)
1133 res = send (conn_fd, data, len, 0);
1134 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1142 * socket_transport_connect:
1144 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1147 socket_transport_connect (const char *address)
1149 #ifdef HAVE_GETADDRINFO
1150 struct addrinfo hints;
1151 struct addrinfo *result, *rp;
1153 struct hostent *result;
1155 int sfd = -1, s, res;
1156 char port_string [128];
1160 if (agent_config.address) {
1161 res = parse_address (agent_config.address, &host, &port);
1162 g_assert (res == 0);
1172 sprintf (port_string, "%d", port);
1174 mono_network_init ();
1176 /* Obtain address(es) matching host/port */
1177 #ifdef HAVE_GETADDRINFO
1178 memset (&hints, 0, sizeof (struct addrinfo));
1179 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
1180 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
1182 hints.ai_protocol = 0; /* Any protocol */
1184 s = getaddrinfo (host, port_string, &hints, &result);
1186 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %s\n", host, port, gai_strerror (s));
1190 /* The PS3 doesn't even have _r or hstrerror () */
1191 result = gethostbyname (host);
1193 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, h_errno);
1198 if (agent_config.server) {
1199 #ifdef HAVE_GETADDRINFO
1200 /* Wait for a connection */
1202 struct sockaddr_in addr;
1205 /* No address, generate one */
1206 sfd = socket (AF_INET, SOCK_STREAM, 0);
1209 /* This will bind the socket to a random port */
1210 res = listen (sfd, 16);
1212 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1217 addrlen = sizeof (addr);
1218 memset (&addr, 0, sizeof (addr));
1219 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1220 g_assert (res == 0);
1222 host = (char*)"127.0.0.1";
1223 port = ntohs (addr.sin_port);
1225 /* Emit the address to stdout */
1226 /* FIXME: Should print another interface, not localhost */
1227 printf ("%s:%d\n", host, port);
1229 /* Listen on the provided address */
1230 for (rp = result; rp != NULL; rp = rp->ai_next) {
1233 sfd = socket (rp->ai_family, rp->ai_socktype,
1238 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1241 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
1245 res = listen (sfd, 16);
1254 * this function is not present on win2000 which we still support, and the
1255 * workaround described here:
1256 * http://msdn.microsoft.com/en-us/library/ms737931(VS.85).aspx
1257 * only works with MSVC.
1259 #ifdef HAVE_GETADDRINFO
1260 freeaddrinfo (result);
1265 if (agent_config.defer)
1268 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
1270 if (agent_config.timeout) {
1275 tv.tv_usec = agent_config.timeout * 1000;
1277 FD_SET (sfd, &readfds);
1278 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1280 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1285 conn_fd = socket_transport_accept (sfd);
1289 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
1292 #endif /* HAVE_GETADDRINFO */
1294 /* Connect to the specified address */
1295 #ifdef HAVE_GETADDRINFO
1296 /* FIXME: Respect the timeout */
1297 for (rp = result; rp != NULL; rp = rp->ai_next) {
1298 sfd = socket (rp->ai_family, rp->ai_socktype,
1303 if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
1304 break; /* Success */
1310 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1314 sfd = socket (result->h_addrtype, SOCK_STREAM, 0);
1316 g_assert_not_reached ();
1317 res = connect (sfd, (void*)result->h_addr_list [0], result->h_length);
1319 g_assert_not_reached ();
1325 /* See the comment above */
1326 #ifdef HAVE_GETADDRINFO
1327 freeaddrinfo (result);
1332 if (!transport_handshake ())
1337 socket_transport_close1 (void)
1339 /* This will interrupt the agent thread */
1340 /* Close the read part only so it can still send back replies */
1341 /* Also shut down the connection listener so that we can exit normally */
1343 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1344 shutdown (conn_fd, SD_BOTH);
1345 shutdown (listen_fd, SD_BOTH);
1346 closesocket (listen_fd);
1348 shutdown (conn_fd, SHUT_RD);
1349 shutdown (listen_fd, SHUT_RDWR);
1355 socket_transport_close2 (void)
1358 shutdown (conn_fd, SD_BOTH);
1360 shutdown (conn_fd, SHUT_RDWR);
1365 register_socket_transport (void)
1367 DebuggerTransport trans;
1369 trans.name = "dt_socket";
1370 trans.connect = socket_transport_connect;
1371 trans.close1 = socket_transport_close1;
1372 trans.close2 = socket_transport_close2;
1373 trans.send = socket_transport_send;
1374 trans.recv = socket_transport_recv;
1376 register_transport (&trans);
1379 #endif /* DISABLE_SOCKET_TRANSPORT */
1385 #define MAX_TRANSPORTS 16
1387 static DebuggerTransport *transport;
1389 static DebuggerTransport transports [MAX_TRANSPORTS];
1390 static int ntransports;
1393 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1396 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1398 register_transport (trans);
1402 register_transport (DebuggerTransport *trans)
1404 g_assert (ntransports < MAX_TRANSPORTS);
1406 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1411 transport_init (void)
1415 #ifndef DISABLE_SOCKET_TRANSPORT
1416 register_socket_transport ();
1419 for (i = 0; i < ntransports; ++i) {
1420 if (!strcmp (agent_config.transport, transports [i].name))
1423 if (i == ntransports) {
1424 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1425 for (i = 0; i < ntransports; ++i)
1426 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1427 fprintf (stderr, "\n");
1430 transport = &transports [i];
1434 transport_connect (const char *address)
1436 transport->connect (address);
1440 transport_close1 (void)
1442 transport->close1 ();
1446 transport_close2 (void)
1448 transport->close2 ();
1452 transport_send (void *buf, int len)
1454 return transport->send (buf, len);
1458 transport_recv (void *buf, int len)
1460 return transport->recv (buf, len);
1464 mono_debugger_agent_transport_handshake (void)
1466 return transport_handshake ();
1470 transport_handshake (void)
1472 char handshake_msg [128];
1476 disconnected = TRUE;
1478 /* Write handshake message */
1479 sprintf (handshake_msg, "DWP-Handshake");
1481 res = transport_send (handshake_msg, strlen (handshake_msg));
1482 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1483 g_assert (res != -1);
1486 res = transport_recv (buf, strlen (handshake_msg));
1487 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg) != 0))) {
1488 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1493 * To support older clients, the client sends its protocol version after connecting
1494 * using a command. Until that is received, default to our protocol version.
1496 major_version = MAJOR_VERSION;
1497 minor_version = MINOR_VERSION;
1498 protocol_version_set = FALSE;
1500 #ifndef DISABLE_SOCKET_TRANSPORT
1501 // FIXME: Move this somewhere else
1503 * Set TCP_NODELAY on the socket so the client receives events/command
1504 * results immediately.
1508 int result = setsockopt (conn_fd,
1513 g_assert (result >= 0);
1519 disconnected = FALSE;
1524 stop_debugger_thread (void)
1529 transport_close1 ();
1532 * Wait for the thread to exit.
1534 * If we continue with the shutdown without waiting for it, then the client might
1535 * not receive an answer to its last command like a resume.
1536 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
1539 //WaitForSingleObject (debugger_thread_handle, INFINITE);
1540 if (GetCurrentThreadId () != debugger_thread_id) {
1542 mono_mutex_lock (&debugger_thread_exited_mutex);
1543 if (!debugger_thread_exited) {
1545 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
1546 mono_mutex_unlock (&debugger_thread_exited_mutex);
1548 mono_mutex_lock (&debugger_thread_exited_mutex);
1551 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1554 mono_mutex_unlock (&debugger_thread_exited_mutex);
1555 } while (!debugger_thread_exited);
1558 transport_close2 ();
1562 start_debugger_thread (void)
1566 debugger_thread_handle = mono_create_thread (NULL, 0, debugger_thread, NULL, 0, &tid);
1567 g_assert (debugger_thread_handle);
1571 * Functions to decode protocol data
1575 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1578 g_assert (*endbuf <= limit);
1583 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1586 g_assert (*endbuf <= limit);
1588 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1591 static inline gint64
1592 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1594 guint32 high = decode_int (buf, &buf, limit);
1595 guint32 low = decode_int (buf, &buf, limit);
1599 return ((((guint64)high) << 32) | ((guint64)low));
1603 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1605 return decode_int (buf, endbuf, limit);
1609 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1611 int len = decode_int (buf, &buf, limit);
1619 s = g_malloc (len + 1);
1622 memcpy (s, buf, len);
1631 * Functions to encode protocol data
1635 guint8 *buf, *p, *end;
1639 buffer_init (Buffer *buf, int size)
1641 buf->buf = g_malloc (size);
1643 buf->end = buf->buf + size;
1647 buffer_make_room (Buffer *buf, int size)
1649 if (buf->end - buf->p < size) {
1650 int new_size = buf->end - buf->buf + size + 32;
1651 guint8 *p = g_realloc (buf->buf, new_size);
1652 size = buf->p - buf->buf;
1655 buf->end = buf->buf + new_size;
1660 buffer_add_byte (Buffer *buf, guint8 val)
1662 buffer_make_room (buf, 1);
1668 buffer_add_short (Buffer *buf, guint32 val)
1670 buffer_make_room (buf, 2);
1671 buf->p [0] = (val >> 8) & 0xff;
1672 buf->p [1] = (val >> 0) & 0xff;
1677 buffer_add_int (Buffer *buf, guint32 val)
1679 buffer_make_room (buf, 4);
1680 buf->p [0] = (val >> 24) & 0xff;
1681 buf->p [1] = (val >> 16) & 0xff;
1682 buf->p [2] = (val >> 8) & 0xff;
1683 buf->p [3] = (val >> 0) & 0xff;
1688 buffer_add_long (Buffer *buf, guint64 l)
1690 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1691 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1695 buffer_add_id (Buffer *buf, int id)
1697 buffer_add_int (buf, (guint64)id);
1701 buffer_add_data (Buffer *buf, guint8 *data, int len)
1703 buffer_make_room (buf, len);
1704 memcpy (buf->p, data, len);
1709 buffer_add_string (Buffer *buf, const char *str)
1714 buffer_add_int (buf, 0);
1717 buffer_add_int (buf, len);
1718 buffer_add_data (buf, (guint8*)str, len);
1723 buffer_free (Buffer *buf)
1729 send_packet (int command_set, int command, Buffer *data)
1735 id = InterlockedIncrement (&packet_id);
1737 len = data->p - data->buf + 11;
1738 buffer_init (&buf, len);
1739 buffer_add_int (&buf, len);
1740 buffer_add_int (&buf, id);
1741 buffer_add_byte (&buf, 0); /* flags */
1742 buffer_add_byte (&buf, command_set);
1743 buffer_add_byte (&buf, command);
1744 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1746 res = transport_send (buf.buf, len);
1754 send_reply_packet (int id, int error, Buffer *data)
1760 len = data->p - data->buf + 11;
1761 buffer_init (&buf, len);
1762 buffer_add_int (&buf, len);
1763 buffer_add_int (&buf, id);
1764 buffer_add_byte (&buf, 0x80); /* flags */
1765 buffer_add_byte (&buf, (error >> 8) & 0xff);
1766 buffer_add_byte (&buf, error);
1767 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1769 res = transport_send (buf.buf, len);
1781 * Represents an object accessible by the debugger client.
1784 /* Unique id used in the wire protocol to refer to objects */
1787 * A weakref gc handle pointing to the object. The gc handle is used to
1788 * detect if the object was garbage collected.
1793 /* Maps objid -> ObjRef */
1794 static GHashTable *objrefs;
1797 free_objref (gpointer value)
1801 mono_gchandle_free (o->handle);
1809 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1813 objrefs_cleanup (void)
1815 g_hash_table_destroy (objrefs);
1819 static GHashTable *obj_to_objref;
1820 static MonoGHashTable *suspended_objs;
1823 * Return an ObjRef for OBJ.
1826 get_objref (MonoObject *obj)
1829 GSList *reflist = NULL, *l;
1835 mono_loader_lock ();
1837 if (!obj_to_objref) {
1838 obj_to_objref = g_hash_table_new (NULL, NULL);
1839 suspended_objs = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
1840 MONO_GC_REGISTER_ROOT_FIXED (suspended_objs);
1843 if (suspend_count) {
1845 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1847 mono_g_hash_table_insert (suspended_objs, obj, NULL);
1850 /* FIXME: The tables can grow indefinitely */
1852 if (mono_gc_is_moving ()) {
1854 * Objects can move, so use a hash table mapping hash codes to lists of
1855 * ObjRef structures.
1857 hash = mono_object_hash (obj);
1859 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1860 for (l = reflist; l; l = l->next) {
1862 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1863 mono_loader_unlock ();
1868 /* Use a hash table with masked pointers to internalize object references */
1869 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1870 /* ref might refer to a different object with the same addr which was GCd */
1871 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1872 mono_loader_unlock ();
1877 ref = g_new0 (ObjRef, 1);
1878 ref->id = InterlockedIncrement (&objref_id);
1879 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1881 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
1883 if (mono_gc_is_moving ()) {
1884 reflist = g_slist_append (reflist, ref);
1885 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
1887 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
1890 mono_loader_unlock ();
1896 true_pred (gpointer key, gpointer value, gpointer user_data)
1902 clear_suspended_objs (void)
1904 mono_loader_lock ();
1905 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
1906 mono_loader_unlock ();
1910 get_objid (MonoObject *obj)
1912 return get_objref (obj)->id;
1916 * Set OBJ to the object identified by OBJID.
1917 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
1921 get_object_allow_null (int objid, MonoObject **obj)
1931 return ERR_INVALID_OBJECT;
1933 mono_loader_lock ();
1935 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
1938 *obj = mono_gchandle_get_target (ref->handle);
1939 mono_loader_unlock ();
1941 return ERR_INVALID_OBJECT;
1944 mono_loader_unlock ();
1945 return ERR_INVALID_OBJECT;
1950 get_object (int objid, MonoObject **obj)
1952 int err = get_object_allow_null (objid, obj);
1957 return ERR_INVALID_OBJECT;
1962 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
1964 return decode_id (buf, endbuf, limit);
1968 buffer_add_objid (Buffer *buf, MonoObject *o)
1970 buffer_add_id (buf, get_objid (o));
1989 * Represents a runtime structure accessible to the debugger client
1992 /* Unique id used in the wire protocol */
1994 /* Domain of the runtime structure, NULL if the domain was unloaded */
2001 MonoAssembly *assembly;
2002 MonoClassField *field;
2004 MonoProperty *property;
2009 /* Maps runtime structure -> Id */
2010 GHashTable *val_to_id [ID_NUM];
2011 /* Classes whose class load event has been sent */
2012 GHashTable *loaded_classes;
2013 /* Maps MonoClass->GPtrArray of file names */
2014 GHashTable *source_files;
2015 /* Maps source file basename -> GSList of classes */
2016 GHashTable *source_file_to_class;
2017 /* Same with ignore-case */
2018 GHashTable *source_file_to_class_ignorecase;
2022 static GPtrArray *ids [ID_NUM];
2029 for (i = 0; i < ID_NUM; ++i)
2030 ids [i] = g_ptr_array_new ();
2038 for (i = 0; i < ID_NUM; ++i) {
2040 for (j = 0; j < ids [i]->len; ++j)
2041 g_free (g_ptr_array_index (ids [i], j));
2042 g_ptr_array_free (ids [i], TRUE);
2049 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2051 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
2053 GHashTableIter iter;
2054 GPtrArray *file_names;
2059 for (i = 0; i < ID_NUM; ++i)
2060 if (info->val_to_id [i])
2061 g_hash_table_destroy (info->val_to_id [i]);
2062 g_hash_table_destroy (info->loaded_classes);
2064 g_hash_table_iter_init (&iter, info->source_files);
2065 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2066 for (i = 0; i < file_names->len; ++i)
2067 g_free (g_ptr_array_index (file_names, i));
2068 g_ptr_array_free (file_names, TRUE);
2071 g_hash_table_iter_init (&iter, info->source_file_to_class);
2072 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2077 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2078 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2086 domain_jit_info (domain)->agent_info = NULL;
2088 /* Clear ids referencing structures in the domain */
2089 for (i = 0; i < ID_NUM; ++i) {
2091 for (j = 0; j < ids [i]->len; ++j) {
2092 Id *id = g_ptr_array_index (ids [i], j);
2093 if (id->domain == domain)
2099 mono_loader_lock ();
2100 g_hash_table_remove (domains, domain);
2101 mono_loader_unlock ();
2104 static AgentDomainInfo*
2105 get_agent_domain_info (MonoDomain *domain)
2107 AgentDomainInfo *info = NULL;
2109 mono_domain_lock (domain);
2111 info = domain_jit_info (domain)->agent_info;
2113 info = domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
2114 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2115 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2116 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2117 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2120 mono_domain_unlock (domain);
2126 get_id (MonoDomain *domain, IdType type, gpointer val)
2129 AgentDomainInfo *info;
2134 mono_loader_lock ();
2136 mono_domain_lock (domain);
2138 info = get_agent_domain_info (domain);
2140 if (info->val_to_id [type] == NULL)
2141 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2143 id = g_hash_table_lookup (info->val_to_id [type], val);
2145 mono_domain_unlock (domain);
2146 mono_loader_unlock ();
2150 id = g_new0 (Id, 1);
2152 id->id = ids [type]->len + 1;
2153 id->domain = domain;
2156 g_hash_table_insert (info->val_to_id [type], val, id);
2158 mono_domain_unlock (domain);
2160 g_ptr_array_add (ids [type], id);
2162 mono_loader_unlock ();
2167 static inline gpointer
2168 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
2172 int id = decode_id (buf, endbuf, limit);
2181 // FIXME: error handling
2182 mono_loader_lock ();
2183 g_assert (id > 0 && id <= ids [type]->len);
2185 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2186 mono_loader_unlock ();
2188 if (res->domain == NULL) {
2189 *err = ERR_UNLOADED;
2194 *domain = res->domain;
2196 return res->data.val;
2200 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2202 buffer_add_id (buf, get_id (domain, type, val));
2205 static inline MonoClass*
2206 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2208 return decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2211 static inline MonoAssembly*
2212 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2214 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2217 static inline MonoImage*
2218 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2220 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2223 static inline MonoMethod*
2224 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2226 return decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2229 static inline MonoClassField*
2230 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2232 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2235 static inline MonoDomain*
2236 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2238 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2241 static inline MonoProperty*
2242 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2244 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2248 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2250 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2254 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2256 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2260 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2262 buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2266 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2268 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2272 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2274 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2278 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2280 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2284 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2286 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2289 static void invoke_method (void);
2296 * save_thread_context:
2298 * Set CTX as the current threads context which is used for computing stack traces.
2299 * This function is signal-safe.
2302 save_thread_context (MonoContext *ctx)
2304 DebuggerTlsData *tls;
2306 tls = mono_native_tls_get_value (debugger_tls_id);
2310 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2312 mono_thread_state_init_from_current (&tls->context);
2315 /* Number of threads suspended */
2317 * If this is equal to the size of thread_to_tls, the runtime is considered
2320 static gint32 threads_suspend_count;
2322 static mono_mutex_t suspend_mutex;
2324 /* Cond variable used to wait for suspend_count becoming 0 */
2325 static mono_cond_t suspend_cond;
2327 /* Semaphore used to wait for a thread becoming suspended */
2328 static MonoSemType suspend_sem;
2333 mono_mutex_init (&suspend_mutex);
2334 mono_cond_init (&suspend_cond, NULL);
2335 MONO_SEM_INIT (&suspend_sem, 0);
2340 StackFrameInfo last_frame;
2341 gboolean last_frame_set;
2344 } GetLastFrameUserData;
2347 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2349 GetLastFrameUserData *data = user_data;
2351 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
2354 if (!data->last_frame_set) {
2355 /* Store the last frame */
2356 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2357 data->last_frame_set = TRUE;
2360 /* Store the context/lmf for the frame above the last frame */
2361 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2362 data->lmf = info->lmf;
2370 * Process interruption of a thread. If SIGCTX is set, process the current thread. If
2371 * INFO is set, process the thread described by INFO.
2372 * This should be signal safe.
2375 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, void *sigctx, MonoJitInfo *ji)
2379 MonoNativeThreadId tid;
2382 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2383 * guarantee the signal handler will be called that many times. Instead of tracking
2384 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2385 * has been requested that hasn't been handled yet, otherwise we can have threads
2386 * refuse to die when VM_EXIT is called
2388 #if defined(__APPLE__)
2389 if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
2393 * We use interrupt_count to determine whenever this interrupt should be processed
2394 * by us or the normal interrupt processing code in the signal handler.
2395 * There is no race here with notify_thread (), since the signal is sent after
2396 * incrementing interrupt_count.
2398 if (tls->interrupt_count == 0)
2401 InterlockedDecrement (&tls->interrupt_count);
2405 ip = mono_arch_ip_from_context (sigctx);
2407 ip = MONO_CONTEXT_GET_IP (&info->suspend_state.ctx);
2412 tid = mono_thread_info_get_tid (info);
2414 tid = (MonoNativeThreadId)GetCurrentThreadId ();
2416 // FIXME: Races when the thread leaves managed code before hitting a single step
2420 /* Running managed code, will be suspended by the single step code */
2421 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, ji->method->name, ip));
2425 * Running native code, will be suspended when it returns to/enters
2426 * managed code. Treat it as already suspended.
2427 * This might interrupt the code in process_single_step_inner (), we use the
2428 * tls->suspending flag to avoid races when that happens.
2430 if (!tls->suspended && !tls->suspending) {
2432 GetLastFrameUserData data;
2434 // FIXME: printf is not signal safe, but this is only used during
2435 // debugger debugging
2437 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip));
2438 //save_thread_context (&ctx);
2441 /* Already terminated */
2444 tls->context.valid = FALSE;
2447 * We are in a difficult position: we want to be able to provide stack
2448 * traces for this thread, but we can't use the current ctx+lmf, since
2449 * the thread is still running, so it might return to managed code,
2450 * making these invalid.
2451 * So we start a stack walk and save the first frame, along with the
2452 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2453 * suspended when it returns to managed code, so the parent's ctx should
2456 data.last_frame_set = FALSE;
2458 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
2460 * Don't pass MONO_UNWIND_ACTUAL_METHOD, its not signal safe, and
2461 * get_last_frame () doesn't need it, the last frame cannot be a ginst
2462 * since we are not in a JITted method.
2464 mono_walk_stack_with_ctx (get_last_frame, &ctx, MONO_UNWIND_NONE, &data);
2466 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, &info->suspend_state, MONO_UNWIND_SIGNAL_SAFE, &data);
2468 if (data.last_frame_set) {
2469 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2470 res = mono_thread_state_init_from_monoctx (&tls->async_state, &ctx);
2472 mono_thread_state_init_from_monoctx (&tls->context, &ctx);
2475 memcpy (&tls->async_state.ctx, &data.ctx, sizeof (MonoContext));
2476 tls->async_state.unwind_data [MONO_UNWIND_DATA_LMF] = data.lmf;
2477 tls->async_state.unwind_data [MONO_UNWIND_DATA_JIT_TLS] = tls->thread->jit_data;
2479 /* No managed frames */
2480 tls->async_state.valid = FALSE;
2482 mono_memory_barrier ();
2484 tls->suspended = TRUE;
2485 MONO_SEM_POST (&suspend_sem);
2492 * mono_debugger_agent_thread_interrupt:
2494 * Called by the abort signal handler.
2495 * Should be signal safe.
2498 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
2500 DebuggerTlsData *tls;
2505 tls = mono_native_tls_get_value (debugger_tls_id);
2507 DEBUG (1, fprintf (log_file, "[%p] Received interrupt with no TLS, continuing.\n", (gpointer)GetCurrentThreadId ()));
2511 return thread_interrupt (tls, NULL, sigctx, ji);
2515 static void CALLBACK notify_thread_apc (ULONG_PTR param)
2518 mono_debugger_agent_thread_interrupt (NULL, NULL);
2520 #endif /* HOST_WIN32 */
2523 * reset_native_thread_suspend_state:
2525 * Reset the suspended flag and state on native threads
2528 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2530 DebuggerTlsData *tls = value;
2532 if (!tls->really_suspended && tls->suspended) {
2533 tls->suspended = FALSE;
2535 * The thread might still be running if it was executing native code, so the state won't be invalided by
2536 * suspend_current ().
2538 tls->context.valid = FALSE;
2539 tls->async_state.valid = FALSE;
2540 invalidate_frames (tls);
2547 * Notify a thread that it needs to suspend.
2550 notify_thread (gpointer key, gpointer value, gpointer user_data)
2552 MonoInternalThread *thread = key;
2553 DebuggerTlsData *tls = value;
2554 gsize tid = thread->tid;
2557 if (GetCurrentThreadId () == tid || tls->terminated)
2560 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2563 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2564 * guarantee the signal handler will be called that many times. Instead of tracking
2565 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2566 * has been requested that hasn't been handled yet, otherwise we can have threads
2567 * refuse to die when VM_EXIT is called
2569 #if defined(__APPLE__)
2570 if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
2574 * Maybe we could use the normal interrupt infrastructure, but that does a lot
2575 * of things like breaking waits etc. which we don't want.
2577 InterlockedIncrement (&tls->interrupt_count);
2580 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2582 QueueUserAPC (notify_thread_apc, thread->handle, NULL);
2584 if (mono_thread_info_new_interrupt_enabled ()) {
2585 MonoThreadInfo *info;
2588 info = mono_thread_info_safe_suspend_sync ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE);
2590 DEBUG(1, fprintf (log_file, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2592 * Attached thread which died without detaching.
2594 tls->terminated = TRUE;
2596 ji = mono_jit_info_table_find (info->suspend_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], MONO_CONTEXT_GET_IP (&info->suspend_state.ctx));
2598 thread_interrupt (tls, info, NULL, ji);
2600 mono_thread_info_resume (mono_thread_info_get_tid (info));
2603 res = mono_thread_kill (thread, mono_thread_get_abort_signal ());
2605 DEBUG(1, fprintf (log_file, "[%p] mono_thread_kill () failed for %p: %d...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid, res));
2607 * Attached thread which died without detaching.
2609 tls->terminated = TRUE;
2616 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2618 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2621 if (mono_loader_lock_is_owned_by_self ()) {
2623 * Shortcut for the check in suspend_current (). This speeds up processing
2624 * when executing long running code inside the loader lock, i.e. assembly load
2630 if (debugger_thread_id == GetCurrentThreadId ())
2633 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2634 if (suspend_count - tls->resume_count > 0)
2635 tls->suspending = TRUE;
2637 DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2639 if (suspend_count - tls->resume_count == 0) {
2641 * We are executing a single threaded invoke but the single step for
2642 * suspending is still active.
2643 * FIXME: This slows down single threaded invokes.
2645 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
2649 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2651 /* Can't suspend in these methods */
2652 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
2655 save_thread_context (ctx);
2663 * Increase the suspend count of the VM. While the suspend count is greater
2664 * than 0, runtime threads are suspended at certain points during execution.
2669 mono_loader_lock ();
2671 mono_mutex_lock (&suspend_mutex);
2675 DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
2677 if (suspend_count == 1) {
2678 // FIXME: Is it safe to call this inside the lock ?
2679 start_single_stepping ();
2680 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2683 mono_mutex_unlock (&suspend_mutex);
2685 if (suspend_count == 1)
2687 * Suspend creation of new threadpool threads, since they cannot run
2689 mono_thread_pool_suspend ();
2691 mono_loader_unlock ();
2697 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2705 g_assert (debugger_thread_id == GetCurrentThreadId ());
2707 mono_loader_lock ();
2709 mono_mutex_lock (&suspend_mutex);
2711 g_assert (suspend_count > 0);
2714 DEBUG(1, fprintf (log_file, "[%p] Resuming vm, suspend count=%d...\n", (gpointer)GetCurrentThreadId (), suspend_count));
2716 if (suspend_count == 0) {
2717 // FIXME: Is it safe to call this inside the lock ?
2718 stop_single_stepping ();
2719 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2722 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2723 err = mono_cond_broadcast (&suspend_cond);
2724 g_assert (err == 0);
2726 mono_mutex_unlock (&suspend_mutex);
2727 //g_assert (err == 0);
2729 if (suspend_count == 0)
2730 mono_thread_pool_resume ();
2732 mono_loader_unlock ();
2738 * Resume just one thread.
2741 resume_thread (MonoInternalThread *thread)
2744 DebuggerTlsData *tls;
2746 g_assert (debugger_thread_id == GetCurrentThreadId ());
2748 mono_loader_lock ();
2750 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2753 mono_mutex_lock (&suspend_mutex);
2755 g_assert (suspend_count > 0);
2757 DEBUG(1, fprintf (log_file, "[%p] Resuming thread...\n", (gpointer)(gssize)thread->tid));
2759 tls->resume_count += suspend_count;
2762 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2763 * but only the one whose resume_count field is > 0 will be resumed.
2765 err = mono_cond_broadcast (&suspend_cond);
2766 g_assert (err == 0);
2768 mono_mutex_unlock (&suspend_mutex);
2769 //g_assert (err == 0);
2771 mono_loader_unlock ();
2775 invalidate_frames (DebuggerTlsData *tls)
2780 tls = mono_native_tls_get_value (debugger_tls_id);
2783 for (i = 0; i < tls->frame_count; ++i) {
2784 if (tls->frames [i]->jit)
2785 mono_debug_free_method_jit_info (tls->frames [i]->jit);
2786 g_free (tls->frames [i]);
2788 g_free (tls->frames);
2789 tls->frame_count = 0;
2796 * Suspend the current thread until the runtime is resumed. If the thread has a
2797 * pending invoke, then the invoke is executed before this function returns.
2800 suspend_current (void)
2803 DebuggerTlsData *tls;
2805 g_assert (debugger_thread_id != GetCurrentThreadId ());
2807 if (mono_loader_lock_is_owned_by_self ()) {
2809 * If we own the loader mutex, can't suspend until we release it, since the
2810 * whole runtime can deadlock otherwise.
2815 tls = mono_native_tls_get_value (debugger_tls_id);
2818 mono_mutex_lock (&suspend_mutex);
2820 tls->suspending = FALSE;
2821 tls->really_suspended = TRUE;
2823 if (!tls->suspended) {
2824 tls->suspended = TRUE;
2825 MONO_SEM_POST (&suspend_sem);
2828 DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
2830 while (suspend_count - tls->resume_count > 0) {
2832 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
2834 mono_mutex_unlock (&suspend_mutex);
2836 mono_mutex_lock (&suspend_mutex);
2842 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
2843 g_assert (err == 0);
2847 tls->suspended = FALSE;
2848 tls->really_suspended = FALSE;
2850 threads_suspend_count --;
2852 mono_mutex_unlock (&suspend_mutex);
2854 DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
2856 if (tls->pending_invoke) {
2857 /* Save the original context */
2858 tls->pending_invoke->has_ctx = TRUE;
2859 tls->pending_invoke->ctx = tls->context.ctx;
2864 /* The frame info becomes invalid after a resume */
2865 tls->context.valid = FALSE;
2866 tls->async_state.valid = FALSE;
2867 invalidate_frames (tls);
2871 count_thread (gpointer key, gpointer value, gpointer user_data)
2873 DebuggerTlsData *tls = value;
2875 if (!tls->suspended && !tls->terminated)
2876 *(int*)user_data = *(int*)user_data + 1;
2880 count_threads_to_wait_for (void)
2884 mono_loader_lock ();
2885 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2886 mono_loader_unlock ();
2894 * Wait until the runtime is completely suspended.
2897 wait_for_suspend (void)
2899 int nthreads, nwait, err;
2900 gboolean waited = FALSE;
2902 // FIXME: Threads starting/stopping ?
2903 mono_loader_lock ();
2904 nthreads = mono_g_hash_table_size (thread_to_tls);
2905 mono_loader_unlock ();
2908 nwait = count_threads_to_wait_for ();
2910 DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
2911 err = MONO_SEM_WAIT (&suspend_sem);
2912 g_assert (err == 0);
2920 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
2926 * Return whenever the runtime is suspended.
2931 return count_threads_to_wait_for () == 0;
2934 static MonoSeqPointInfo*
2935 get_seq_points (MonoDomain *domain, MonoMethod *method)
2937 MonoSeqPointInfo *seq_points;
2939 mono_domain_lock (domain);
2940 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2941 if (!seq_points && method->is_inflated) {
2942 /* generic sharing + aot */
2943 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (method));
2945 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mini_get_shared_method (method));
2947 mono_domain_unlock (domain);
2953 no_seq_points_found (MonoMethod *method)
2956 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
2958 printf ("Unable to find seq points for method '%s'.\n", mono_method_full_name (method, TRUE));
2962 * find_next_seq_point_for_native_offset:
2964 * Find the first sequence point after NATIVE_OFFSET.
2967 find_next_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2969 MonoSeqPointInfo *seq_points;
2972 seq_points = get_seq_points (domain, method);
2978 g_assert (seq_points);
2982 for (i = 0; i < seq_points->len; ++i) {
2983 if (seq_points->seq_points [i].native_offset >= native_offset)
2984 return &seq_points->seq_points [i];
2991 * find_prev_seq_point_for_native_offset:
2993 * Find the first sequence point before NATIVE_OFFSET.
2996 find_prev_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2998 MonoSeqPointInfo *seq_points;
3001 seq_points = get_seq_points (domain, method);
3007 for (i = seq_points->len - 1; i >= 0; --i) {
3008 if (seq_points->seq_points [i].native_offset <= native_offset)
3009 return &seq_points->seq_points [i];
3018 * Find the sequence point corresponding to the IL offset IL_OFFSET, which
3019 * should be the location of a sequence point.
3021 static G_GNUC_UNUSED SeqPoint*
3022 find_seq_point (MonoDomain *domain, MonoMethod *method, gint32 il_offset, MonoSeqPointInfo **info)
3024 MonoSeqPointInfo *seq_points;
3029 seq_points = get_seq_points (domain, method);
3034 for (i = 0; i < seq_points->len; ++i) {
3035 if (seq_points->seq_points [i].il_offset == il_offset)
3036 return &seq_points->seq_points [i];
3043 DebuggerTlsData *tls;
3045 } ComputeFramesUserData;
3048 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3050 ComputeFramesUserData *ud = user_data;
3052 MonoMethod *method, *actual_method, *api_method;
3056 if (info->type != FRAME_TYPE_MANAGED) {
3057 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3058 /* Mark the last frame as an invoke frame */
3060 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3066 method = info->ji->method;
3068 method = info->method;
3069 actual_method = info->actual_method;
3070 api_method = method;
3075 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3078 if (info->il_offset == -1) {
3079 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3080 if (ud->frames == NULL) {
3081 sp = find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL);
3083 info->il_offset = sp->il_offset;
3085 if (info->il_offset == -1)
3086 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3089 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));
3091 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3092 if (!CHECK_PROTOCOL_VERSION (2, 17))
3093 /* Older clients can't handle this flag */
3095 api_method = mono_marshal_method_from_wrapper (method);
3098 actual_method = api_method;
3099 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3102 frame = g_new0 (StackFrame, 1);
3103 frame->method = method;
3104 frame->actual_method = actual_method;
3105 frame->api_method = api_method;
3106 frame->il_offset = info->il_offset;
3107 frame->native_offset = info->native_offset;
3108 frame->flags = flags;
3109 frame->ji = info->ji;
3110 if (info->reg_locations)
3111 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3114 frame->has_ctx = TRUE;
3116 frame->domain = info->domain;
3118 ud->frames = g_slist_append (ud->frames, frame);
3124 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3126 ComputeFramesUserData *ud = user_data;
3129 * 'tls->filter_ctx' is the location of the throw site.
3131 * mono_walk_stack() will never actually hit the throw site, but unwind
3132 * directly from the filter to the call site; we abort stack unwinding here
3133 * once this happens and resume from the throw site.
3136 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3139 return process_frame (info, ctx, user_data);
3143 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3145 ComputeFramesUserData user_data;
3147 int i, findex, new_frame_count;
3148 StackFrame **new_frames, *f;
3149 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3151 // FIXME: Locking on tls
3152 if (tls->frames && tls->frames_up_to_date)
3155 DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
3157 user_data.tls = tls;
3158 user_data.frames = NULL;
3159 if (tls->terminated) {
3160 tls->frame_count = 0;
3162 } if (!tls->really_suspended && tls->async_state.valid) {
3163 /* Have to use the state saved by the signal handler */
3164 process_frame (&tls->async_last_frame, NULL, &user_data);
3165 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3166 } else if (tls->filter_state.valid) {
3168 * We are inside an exception filter.
3170 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3172 if (tls->context.valid)
3173 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3175 * After that, we resume unwinding from the location where the exception has been thrown.
3177 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3178 } else if (tls->context.valid) {
3179 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3182 tls->frame_count = 0;
3186 new_frame_count = g_slist_length (user_data.frames);
3187 new_frames = g_new0 (StackFrame*, new_frame_count);
3189 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3193 * Reuse the id for already existing stack frames, so invokes don't invalidate
3194 * the still valid stack frames.
3196 for (i = 0; i < tls->frame_count; ++i) {
3197 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3198 f->id = tls->frames [i]->id;
3203 if (i >= tls->frame_count)
3204 f->id = InterlockedIncrement (&frame_id);
3206 new_frames [findex ++] = f;
3209 g_slist_free (user_data.frames);
3211 invalidate_frames (tls);
3213 tls->frames = new_frames;
3214 tls->frame_count = new_frame_count;
3215 tls->frames_up_to_date = TRUE;
3219 * GHFunc to emit an appdomain creation event
3220 * @param key Don't care
3221 * @param value A loaded appdomain
3222 * @param user_data Don't care
3225 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3227 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3228 g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
3232 * GHFunc to emit a thread start event
3233 * @param key A thread id
3234 * @param value A thread object
3235 * @param user_data Don't care
3238 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3240 if (GPOINTER_TO_INT (key) != debugger_thread_id)
3241 process_profiler_event (EVENT_KIND_THREAD_START, value);
3245 * GFunc to emit an assembly load event
3246 * @param value A loaded assembly
3247 * @param user_data Don't care
3250 emit_assembly_load (gpointer value, gpointer user_data)
3252 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3256 * GFunc to emit a type load event
3257 * @param value A loaded type
3258 * @param user_data Don't care
3261 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3263 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3267 strdup_tolower (char *s)
3272 for (p = s2; *p; ++p)
3282 * create_event_list:
3284 * Return a list of event request ids matching EVENT, starting from REQS, which
3285 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3287 * We return request ids, instead of requests, to simplify threading, since
3288 * requests could be deleted anytime when the loader lock is not held.
3289 * LOCKING: Assumes the loader lock is held.
3292 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3295 GSList *events = NULL;
3297 *suspend_policy = SUSPEND_POLICY_NONE;
3300 reqs = event_requests;
3305 for (i = 0; i < reqs->len; ++i) {
3306 EventRequest *req = g_ptr_array_index (reqs, i);
3307 if (req->event_kind == event) {
3308 gboolean filtered = FALSE;
3311 for (j = 0; j < req->nmodifiers; ++j) {
3312 Modifier *mod = &req->modifiers [j];
3314 if (mod->kind == MOD_KIND_COUNT) {
3316 if (mod->data.count > 0) {
3317 if (mod->data.count > 0) {
3319 if (mod->data.count == 0)
3323 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3324 if (mod->data.thread != mono_thread_internal_current ())
3326 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3327 if (mod->data.exc_class && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3329 if (ei->caught && !mod->caught)
3331 if (!ei->caught && !mod->uncaught)
3333 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3335 gboolean found = FALSE;
3336 MonoAssembly **assemblies = mod->data.assemblies;
3339 for (k = 0; assemblies [k]; ++k)
3340 if (assemblies [k] == ji->method->klass->image->assembly)
3345 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3346 gpointer iter = NULL;
3348 MonoDebugSourceInfo *sinfo;
3349 char *source_file, *s;
3350 gboolean found = FALSE;
3352 GPtrArray *source_file_list;
3354 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3355 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3358 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, NULL, NULL, NULL, NULL, NULL);
3359 for (i = 0; i < source_file_list->len; ++i) {
3360 sinfo = g_ptr_array_index (source_file_list, i);
3362 * Do a case-insesitive match by converting the file name to
3365 s = strdup_tolower (sinfo->source_file);
3366 if (g_hash_table_lookup (mod->data.source_files, s))
3369 char *s2 = g_path_get_basename (sinfo->source_file);
3370 char *s3 = strdup_tolower (s2);
3372 if (g_hash_table_lookup (mod->data.source_files, s3))
3379 g_ptr_array_free (source_file_list, TRUE);
3384 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3387 s = mono_type_full_name (&ei->klass->byval_arg);
3388 if (!g_hash_table_lookup (mod->data.type_names, s))
3391 } else if (mod->kind == MOD_KIND_STEP) {
3392 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3393 (ji->method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3394 !strcmp (ji->method->name, ".cctor"))
3396 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3397 MonoCustomAttrInfo *ainfo;
3398 static MonoClass *klass;
3401 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3404 if (!ji->dbg_hidden_inited) {
3405 ainfo = mono_custom_attrs_from_method (ji->method);
3407 if (mono_custom_attrs_has_attr (ainfo, klass))
3408 ji->dbg_hidden = TRUE;
3409 mono_custom_attrs_free (ainfo);
3411 ji->dbg_hidden_inited = TRUE;
3420 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3421 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3426 /* Send a VM START/DEATH event by default */
3427 if (event == EVENT_KIND_VM_START)
3428 events = g_slist_append (events, GINT_TO_POINTER (0));
3429 if (event == EVENT_KIND_VM_DEATH)
3430 events = g_slist_append (events, GINT_TO_POINTER (0));
3435 static G_GNUC_UNUSED const char*
3436 event_to_string (EventKind event)
3439 case EVENT_KIND_VM_START: return "VM_START";
3440 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3441 case EVENT_KIND_THREAD_START: return "THREAD_START";
3442 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3443 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3444 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3445 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3446 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3447 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3448 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3449 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3450 case EVENT_KIND_STEP: return "STEP";
3451 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3452 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3453 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3454 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3455 case EVENT_KIND_USER_LOG: return "USER_LOG";
3457 g_assert_not_reached ();
3464 * Send an event to the client, suspending the vm if needed.
3465 * LOCKING: Since this can suspend the calling thread, no locks should be held
3467 * The EVENTS list is freed by this function.
3470 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3474 MonoDomain *domain = mono_domain_get ();
3475 MonoThread *thread = NULL;
3476 gboolean send_success = FALSE;
3481 DEBUG (2, fprintf (log_file, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event)));
3485 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3486 // FIXME: We miss those events
3487 DEBUG (2, fprintf (log_file, "VM start event not sent yet: dropping %s\n", event_to_string (event)));
3491 if (vm_death_event_sent) {
3492 DEBUG (2, fprintf (log_file, "VM death event has been sent: dropping %s\n", event_to_string (event)));
3496 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3497 DEBUG (2, fprintf (log_file, "Mono runtime is shutting down: dropping %s\n", event_to_string (event)));
3502 DEBUG (2, fprintf (log_file, "Debugger client is not connected: dropping %s\n", event_to_string (event)));
3506 if (event == EVENT_KIND_KEEPALIVE)
3507 suspend_policy = SUSPEND_POLICY_NONE;
3512 if (agent_config.defer) {
3513 /* Make sure the thread id is always set when doing deferred debugging */
3514 if (debugger_thread_id == GetCurrentThreadId ()) {
3515 /* Don't suspend on events from the debugger thread */
3516 suspend_policy = SUSPEND_POLICY_NONE;
3517 thread = mono_thread_get_main ();
3519 else thread = mono_thread_current ();
3521 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3522 // FIXME: Send these with a NULL thread, don't suspend the current thread
3527 nevents = g_slist_length (events);
3528 buffer_init (&buf, 128);
3529 buffer_add_byte (&buf, suspend_policy);
3530 buffer_add_int (&buf, nevents);
3532 for (l = events; l; l = l->next) {
3533 buffer_add_byte (&buf, event); // event kind
3534 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3539 thread = mono_thread_current ();
3541 if (event == EVENT_KIND_VM_START && arg != NULL)
3544 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3547 case EVENT_KIND_THREAD_START:
3548 case EVENT_KIND_THREAD_DEATH:
3550 case EVENT_KIND_APPDOMAIN_CREATE:
3551 case EVENT_KIND_APPDOMAIN_UNLOAD:
3552 buffer_add_domainid (&buf, arg);
3554 case EVENT_KIND_METHOD_ENTRY:
3555 case EVENT_KIND_METHOD_EXIT:
3556 buffer_add_methodid (&buf, domain, arg);
3558 case EVENT_KIND_ASSEMBLY_LOAD:
3559 case EVENT_KIND_ASSEMBLY_UNLOAD:
3560 buffer_add_assemblyid (&buf, domain, arg);
3562 case EVENT_KIND_TYPE_LOAD:
3563 buffer_add_typeid (&buf, domain, arg);
3565 case EVENT_KIND_BREAKPOINT:
3566 case EVENT_KIND_STEP:
3567 buffer_add_methodid (&buf, domain, arg);
3568 buffer_add_long (&buf, il_offset);
3570 case EVENT_KIND_VM_START:
3571 buffer_add_domainid (&buf, mono_get_root_domain ());
3573 case EVENT_KIND_VM_DEATH:
3575 case EVENT_KIND_EXCEPTION: {
3576 EventInfo *ei = arg;
3577 buffer_add_objid (&buf, ei->exc);
3580 case EVENT_KIND_USER_BREAK:
3582 case EVENT_KIND_USER_LOG: {
3583 EventInfo *ei = arg;
3584 buffer_add_int (&buf, ei->level);
3585 buffer_add_string (&buf, ei->category ? ei->category : "");
3586 buffer_add_string (&buf, ei->message ? ei->message : "");
3589 case EVENT_KIND_KEEPALIVE:
3590 suspend_policy = SUSPEND_POLICY_NONE;
3593 g_assert_not_reached ();
3597 if (event == EVENT_KIND_VM_START) {
3598 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3599 if (!agent_config.defer)
3600 start_debugger_thread ();
3603 if (event == EVENT_KIND_VM_DEATH) {
3604 vm_death_event_sent = TRUE;
3605 suspend_policy = SUSPEND_POLICY_NONE;
3608 if (mono_runtime_is_shutting_down ())
3609 suspend_policy = SUSPEND_POLICY_NONE;
3611 if (suspend_policy != SUSPEND_POLICY_NONE) {
3613 * Save the thread context and start suspending before sending the packet,
3614 * since we could be receiving the resume request before send_packet ()
3617 save_thread_context (ctx);
3621 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3625 g_slist_free (events);
3628 if (!send_success) {
3629 DEBUG (2, fprintf (log_file, "Sending command %s failed.\n", event_to_string (event)));
3633 if (event == EVENT_KIND_VM_START) {
3634 vm_start_event_sent = TRUE;
3637 DEBUG (1, fprintf (log_file, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer)GetCurrentThreadId (), nevents, event_to_string (event), ecount, suspend_policy));
3639 switch (suspend_policy) {
3640 case SUSPEND_POLICY_NONE:
3642 case SUSPEND_POLICY_ALL:
3645 case SUSPEND_POLICY_EVENT_THREAD:
3649 g_assert_not_reached ();
3654 process_profiler_event (EventKind event, gpointer arg)
3658 EventInfo ei, *ei_arg = NULL;
3660 if (event == EVENT_KIND_TYPE_LOAD) {
3665 mono_loader_lock ();
3666 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3667 mono_loader_unlock ();
3669 process_event (event, arg, 0, NULL, events, suspend_policy);
3673 runtime_initialized (MonoProfiler *prof)
3675 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3676 if (agent_config.defer)
3677 start_debugger_thread ();
3681 runtime_shutdown (MonoProfiler *prof)
3683 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3685 mono_debugger_agent_cleanup ();
3689 thread_startup (MonoProfiler *prof, uintptr_t tid)
3691 MonoInternalThread *thread = mono_thread_internal_current ();
3692 MonoInternalThread *old_thread;
3693 DebuggerTlsData *tls;
3695 if (tid == debugger_thread_id)
3698 g_assert (thread->tid == tid);
3700 mono_loader_lock ();
3701 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3702 mono_loader_unlock ();
3704 if (thread == old_thread) {
3706 * For some reason, thread_startup () might be called for the same thread
3707 * multiple times (attach ?).
3709 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
3713 * thread_end () might not be called for some threads, and the tid could
3716 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
3717 mono_loader_lock ();
3718 mono_g_hash_table_remove (thread_to_tls, old_thread);
3719 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3720 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3721 mono_loader_unlock ();
3725 tls = mono_native_tls_get_value (debugger_tls_id);
3727 // FIXME: Free this somewhere
3728 tls = g_new0 (DebuggerTlsData, 1);
3729 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3730 tls->thread = thread;
3731 mono_native_tls_set_value (debugger_tls_id, tls);
3733 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3735 mono_loader_lock ();
3736 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3737 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3738 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3739 mono_loader_unlock ();
3741 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3744 * suspend_vm () could have missed this thread, so wait for a resume.
3750 thread_end (MonoProfiler *prof, uintptr_t tid)
3752 MonoInternalThread *thread;
3753 DebuggerTlsData *tls = NULL;
3755 mono_loader_lock ();
3756 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3758 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3759 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3761 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3762 tls->terminated = TRUE;
3763 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3764 MONO_GC_UNREGISTER_ROOT (tls->thread);
3768 mono_loader_unlock ();
3770 /* We might be called for threads started before we registered the start callback */
3772 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3773 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3778 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3780 mono_loader_lock ();
3781 g_hash_table_insert (domains, domain, domain);
3782 mono_loader_unlock ();
3784 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3788 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3790 clear_breakpoints_for_domain (domain);
3792 mono_loader_lock ();
3793 /* Invalidate each thread's frame stack */
3794 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3795 mono_loader_unlock ();
3797 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3801 * invalidate_each_thread:
3803 * A GHFunc to invalidate frames.
3804 * value must be a DebuggerTlsData*
3807 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3809 invalidate_frames (value);
3813 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3815 /* Sent later in jit_end () */
3816 mono_loader_lock ();
3817 g_ptr_array_add (pending_assembly_loads, assembly);
3818 mono_loader_unlock ();
3822 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3824 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3826 clear_event_requests_for_assembly (assembly);
3827 clear_types_for_assembly (assembly);
3831 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3833 #if defined(HOST_WIN32) && !defined(__GNUC__)
3834 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3836 gpointer stackptr = __builtin_frame_address (1);
3838 MonoInternalThread *thread = mono_thread_internal_current ();
3839 DebuggerTlsData *tls;
3841 mono_loader_lock ();
3843 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3844 /* Could be the debugger thread with assembly/type load hooks */
3846 tls->invoke_addr = stackptr;
3848 mono_loader_unlock ();
3852 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3855 #if defined(HOST_WIN32) && !defined(__GNUC__)
3856 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3858 gpointer stackptr = __builtin_frame_address (1);
3861 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
3865 * We need to stop single stepping when exiting a runtime invoke, since if it is
3866 * a step out, it may return to native code, and thus never end.
3868 mono_loader_lock ();
3869 ss_invoke_addr = NULL;
3871 for (i = 0; i < event_requests->len; ++i) {
3872 EventRequest *req = g_ptr_array_index (event_requests, i);
3874 if (req->event_kind == EVENT_KIND_STEP) {
3875 ss_destroy (req->info);
3876 g_ptr_array_remove_index_fast (event_requests, i);
3881 mono_loader_unlock ();
3885 send_type_load (MonoClass *klass)
3887 gboolean type_load = FALSE;
3888 MonoDomain *domain = mono_domain_get ();
3889 AgentDomainInfo *info = NULL;
3891 mono_loader_lock ();
3892 mono_domain_lock (domain);
3894 info = get_agent_domain_info (domain);
3896 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
3898 g_hash_table_insert (info->loaded_classes, klass, klass);
3901 mono_domain_unlock (domain);
3902 mono_loader_unlock ();
3904 emit_type_load (klass, klass, NULL);
3908 * Emit load events for all types currently loaded in the domain.
3909 * Takes the loader and domain locks.
3910 * user_data is unused.
3913 send_types_for_domain (MonoDomain *domain, void *user_data)
3915 AgentDomainInfo *info = NULL;
3917 mono_loader_lock ();
3918 mono_domain_lock (domain);
3919 info = get_agent_domain_info (domain);
3921 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
3922 mono_domain_unlock (domain);
3923 mono_loader_unlock ();
3927 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
3930 * We emit type load events when the first method of the type is JITted,
3931 * since the class load profiler callbacks might be called with the
3932 * loader lock held. They could also occur in the debugger thread.
3933 * Same for assembly load events.
3936 MonoAssembly *assembly = NULL;
3938 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
3939 mono_loader_lock ();
3940 if (pending_assembly_loads->len > 0) {
3941 assembly = g_ptr_array_index (pending_assembly_loads, 0);
3942 g_ptr_array_remove_index (pending_assembly_loads, 0);
3944 mono_loader_unlock ();
3947 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
3953 send_type_load (method->klass);
3956 add_pending_breakpoints (method, jinfo);
3960 * BREAKPOINTS/SINGLE STEPPING
3964 * Contains information about an inserted breakpoint.
3967 long il_offset, native_offset;
3972 } BreakpointInstance;
3975 * Contains generic information about a breakpoint.
3979 * The method where the breakpoint is placed. Can be NULL in which case it
3980 * is inserted into every method. This is used to implement method entry/
3981 * exit events. Can be a generic method definition, in which case the
3982 * breakpoint is inserted into every instance.
3988 * A list of BreakpointInstance structures describing where the breakpoint
3989 * was inserted. There could be more than one because of
3990 * generics/appdomains/method entry/exit.
3992 GPtrArray *children;
3995 /* List of breakpoints */
3996 static GPtrArray *breakpoints;
3997 /* Maps breakpoint locations to the number of breakpoints at that location */
3998 static GHashTable *bp_locs;
4001 breakpoints_init (void)
4003 breakpoints = g_ptr_array_new ();
4004 bp_locs = g_hash_table_new (NULL, NULL);
4008 * insert_breakpoint:
4010 * Insert the breakpoint described by BP into the method described by
4014 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4017 BreakpointInstance *inst;
4018 SeqPoint *sp = NULL;
4021 mono_error_init (error);
4023 for (i = 0; i < seq_points->len; ++i) {
4024 sp = &seq_points->seq_points [i];
4026 if (sp->il_offset == bp->il_offset)
4030 if (i == seq_points->len) {
4032 * The set of IL offsets with seq points doesn't completely match the
4033 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4035 for (i = 0; i < seq_points->len; ++i) {
4036 sp = &seq_points->seq_points [i];
4038 if (sp->il_offset != METHOD_ENTRY_IL_OFFSET && sp->il_offset != METHOD_EXIT_IL_OFFSET && sp->il_offset + 1 == bp->il_offset)
4043 if (i == seq_points->len) {
4044 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);
4046 for (i = 0; i < seq_points->len; ++i)
4047 DEBUG (1, fprintf (log_file, "%d\n", seq_points->seq_points [i].il_offset));
4050 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4051 g_warning ("%s", s);
4055 g_warning ("%s", s);
4061 inst = g_new0 (BreakpointInstance, 1);
4063 inst->native_offset = sp->native_offset;
4064 inst->ip = (guint8*)ji->code_start + sp->native_offset;
4066 inst->domain = domain;
4068 mono_loader_lock ();
4070 g_ptr_array_add (bp->children, inst);
4072 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4073 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4074 mono_loader_unlock ();
4076 if (sp->native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4077 DEBUG (1, fprintf (log_file, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset));
4078 } else if (count == 0) {
4079 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4080 mono_arch_set_breakpoint (ji, inst->ip);
4086 DEBUG(1, fprintf (log_file, "[dbg] Inserted breakpoint at %s:0x%x.\n", mono_method_full_name (ji->method, TRUE), (int)sp->il_offset));
4090 remove_breakpoint (BreakpointInstance *inst)
4092 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4094 MonoJitInfo *ji = inst->ji;
4095 guint8 *ip = inst->ip;
4097 mono_loader_lock ();
4098 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4099 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4100 mono_loader_unlock ();
4102 g_assert (count > 0);
4104 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4105 mono_arch_clear_breakpoint (ji, ip);
4112 static inline gboolean
4113 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4119 if (method == bp->method)
4121 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4124 if (bp->method->is_inflated && method->is_inflated) {
4125 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4126 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4128 /* Open generic methods should match closed generic methods of the same class */
4129 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4130 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4131 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4133 /* FIXME: Handle !mvar */
4134 if (t1->type != MONO_TYPE_MVAR)
4145 * add_pending_breakpoints:
4147 * Insert pending breakpoints into the newly JITted method METHOD.
4150 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4153 MonoSeqPointInfo *seq_points;
4159 domain = mono_domain_get ();
4161 mono_loader_lock ();
4163 for (i = 0; i < breakpoints->len; ++i) {
4164 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4165 gboolean found = FALSE;
4167 if (!bp_matches_method (bp, method))
4170 for (j = 0; j < bp->children->len; ++j) {
4171 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4178 mono_domain_lock (domain);
4179 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
4180 if (!seq_points && ji->method->is_inflated)
4181 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (ji->method));
4182 mono_domain_unlock (domain);
4184 /* Could be AOT code */
4186 g_assert (seq_points);
4188 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4192 mono_loader_unlock ();
4196 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4202 mono_error_init (error);
4204 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4206 /* Might be AOTed code */
4207 code = mono_aot_get_method (domain, method);
4209 ji = mono_jit_info_table_find (domain, code);
4214 insert_breakpoint (seq_points, domain, ji, bp, error);
4218 clear_breakpoint (MonoBreakpoint *bp);
4223 * Set a breakpoint at IL_OFFSET in METHOD.
4224 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4225 * METHOD can also be a generic method definition, in which case a breakpoint
4226 * is placed in all instances of the method.
4227 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4230 static MonoBreakpoint*
4231 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4234 GHashTableIter iter, iter2;
4237 MonoSeqPointInfo *seq_points;
4240 mono_error_init (error);
4243 // - suspend/resume the vm to prevent code patching problems
4244 // - multiple breakpoints on the same location
4245 // - dynamic methods
4248 bp = g_new0 (MonoBreakpoint, 1);
4249 bp->method = method;
4250 bp->il_offset = il_offset;
4252 bp->children = g_ptr_array_new ();
4254 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));
4256 mono_loader_lock ();
4258 g_hash_table_iter_init (&iter, domains);
4259 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4260 mono_domain_lock (domain);
4262 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4263 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4264 if (bp_matches_method (bp, m))
4265 set_bp_in_method (domain, m, seq_points, bp, error);
4268 mono_domain_unlock (domain);
4271 mono_loader_unlock ();
4273 mono_loader_lock ();
4274 g_ptr_array_add (breakpoints, bp);
4275 mono_loader_unlock ();
4277 if (error && !mono_error_ok (error)) {
4278 clear_breakpoint (bp);
4286 clear_breakpoint (MonoBreakpoint *bp)
4290 // FIXME: locking, races
4291 for (i = 0; i < bp->children->len; ++i) {
4292 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4294 remove_breakpoint (inst);
4299 mono_loader_lock ();
4300 g_ptr_array_remove (breakpoints, bp);
4301 mono_loader_unlock ();
4303 g_ptr_array_free (bp->children, TRUE);
4308 breakpoints_cleanup (void)
4312 mono_loader_lock ();
4314 while (i < event_requests->len) {
4315 EventRequest *req = g_ptr_array_index (event_requests, i);
4317 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4318 clear_breakpoint (req->info);
4319 g_ptr_array_remove_index_fast (event_requests, i);
4326 for (i = 0; i < breakpoints->len; ++i)
4327 g_free (g_ptr_array_index (breakpoints, i));
4329 g_ptr_array_free (breakpoints, TRUE);
4330 g_hash_table_destroy (bp_locs);
4335 mono_loader_unlock ();
4339 * clear_breakpoints_for_domain:
4341 * Clear breakpoint instances which reference DOMAIN.
4344 clear_breakpoints_for_domain (MonoDomain *domain)
4348 /* This could be called after shutdown */
4352 mono_loader_lock ();
4353 for (i = 0; i < breakpoints->len; ++i) {
4354 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4357 while (j < bp->children->len) {
4358 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4360 if (inst->domain == domain) {
4361 remove_breakpoint (inst);
4365 g_ptr_array_remove_index_fast (bp->children, j);
4371 mono_loader_unlock ();
4375 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4377 return bp->method && bp->method->klass->image->assembly == assembly;
4381 process_breakpoint_inner (DebuggerTlsData *tls)
4385 int i, j, suspend_policy;
4386 guint32 native_offset;
4388 BreakpointInstance *inst;
4389 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4390 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4391 EventKind kind = EVENT_KIND_BREAKPOINT;
4392 MonoContext *ctx = &tls->restore_ctx;
4393 MonoSeqPointInfo *info;
4396 // FIXME: Speed this up
4398 ip = MONO_CONTEXT_GET_IP (ctx);
4399 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4401 g_assert (ji->method);
4403 /* Compute the native offset of the breakpoint from the ip */
4404 native_offset = ip - (guint8*)ji->code_start;
4407 * Skip the instruction causing the breakpoint signal.
4409 mono_arch_skip_breakpoint (ctx, ji);
4411 if (ji->method->wrapper_type || tls->disable_breakpoints)
4414 bp_reqs = g_ptr_array_new ();
4415 ss_reqs = g_ptr_array_new ();
4416 ss_reqs_orig = g_ptr_array_new ();
4418 mono_loader_lock ();
4421 * The ip points to the instruction causing the breakpoint event, which is after
4422 * the offset recorded in the seq point map, so find the prev seq point before ip.
4424 sp = find_prev_seq_point_for_native_offset (mono_domain_get (), ji->method, native_offset, &info);
4426 no_seq_points_found (ji->method);
4429 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));
4432 for (i = 0; i < breakpoints->len; ++i) {
4433 bp = g_ptr_array_index (breakpoints, i);
4438 for (j = 0; j < bp->children->len; ++j) {
4439 inst = g_ptr_array_index (bp->children, j);
4440 if (inst->ji == ji && inst->sp == sp) {
4441 if (bp->req->event_kind == EVENT_KIND_STEP) {
4442 g_ptr_array_add (ss_reqs_orig, bp->req);
4444 g_ptr_array_add (bp_reqs, bp->req);
4449 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4450 /* Maybe a method entry/exit event */
4451 if (sp->il_offset == METHOD_ENTRY_IL_OFFSET)
4452 kind = EVENT_KIND_METHOD_ENTRY;
4453 else if (sp->il_offset == METHOD_EXIT_IL_OFFSET)
4454 kind = EVENT_KIND_METHOD_EXIT;
4457 /* Process single step requests */
4458 for (i = 0; i < ss_reqs_orig->len; ++i) {
4459 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4460 SingleStepReq *ss_req = req->info;
4461 gboolean hit = TRUE;
4463 if (ss_req->size == STEP_SIZE_LINE) {
4464 /* Have to check whenever a different source line was reached */
4465 MonoDebugMethodInfo *minfo;
4466 MonoDebugSourceLocation *loc = NULL;
4468 minfo = mono_debug_lookup_method (ji->method);
4471 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4473 if (!loc || (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line)) {
4474 /* Have to continue single stepping */
4475 DEBUG(1, fprintf (log_file, "[%p] Same source line, continuing single stepping.\n", (gpointer)GetCurrentThreadId ()));
4480 ss_req->last_method = ji->method;
4481 ss_req->last_line = loc->row;
4482 mono_debug_free_source_location (loc);
4487 g_ptr_array_add (ss_reqs, req);
4489 /* Start single stepping again from the current sequence point */
4490 ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4493 if (ss_reqs->len > 0)
4494 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4495 if (bp_reqs->len > 0)
4496 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4497 if (kind != EVENT_KIND_BREAKPOINT)
4498 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4500 mono_loader_unlock ();
4502 g_ptr_array_free (bp_reqs, TRUE);
4503 g_ptr_array_free (ss_reqs, TRUE);
4506 * FIXME: The first event will suspend, so the second will only be sent after the
4510 process_event (EVENT_KIND_STEP, ji->method, 0, ctx, ss_events, suspend_policy);
4512 process_event (kind, ji->method, 0, ctx, bp_events, suspend_policy);
4513 if (enter_leave_events)
4514 process_event (kind, ji->method, 0, ctx, enter_leave_events, suspend_policy);
4517 /* Process a breakpoint/single step event after resuming from a signal handler */
4519 process_signal_event (void (*func) (DebuggerTlsData*))
4521 DebuggerTlsData *tls;
4522 MonoContext orig_restore_ctx, ctx;
4523 static void (*restore_context) (void *);
4525 if (!restore_context)
4526 restore_context = mono_get_restore_context ();
4528 tls = mono_native_tls_get_value (debugger_tls_id);
4529 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4530 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4531 memcpy (&tls->restore_ctx, &tls->handler_ctx, sizeof (MonoContext));
4535 /* This is called when resuming from a signal handler, so it shouldn't return */
4536 memcpy (&ctx, &tls->restore_ctx, sizeof (MonoContext));
4537 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4538 restore_context (&ctx);
4539 g_assert_not_reached ();
4543 process_breakpoint (void)
4545 process_signal_event (process_breakpoint_inner);
4549 resume_from_signal_handler (void *sigctx, void *func)
4551 DebuggerTlsData *tls;
4554 /* Save the original context in TLS */
4555 // FIXME: This might not work on an altstack ?
4556 tls = mono_native_tls_get_value (debugger_tls_id);
4558 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer)GetCurrentThreadId ());
4561 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4562 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4563 // clob:c could be added to op_seq_point.
4565 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4566 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4567 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4568 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4570 MONO_CONTEXT_SET_IP (&ctx, func);
4572 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4574 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4575 mono_ppc_set_func_into_sigctx (sigctx, func);
4580 mono_debugger_agent_breakpoint_hit (void *sigctx)
4583 * We are called from a signal handler, and running code there causes all kinds of
4584 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4585 * So set up the signal context to return to the real breakpoint handler function.
4587 resume_from_signal_handler (sigctx, process_breakpoint);
4591 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4593 if (frame->managed) {
4594 *(MonoContext*)data = *ctx;
4603 * Called by System.Diagnostics.Debugger:Break ().
4606 mono_debugger_agent_user_break (void)
4608 if (agent_config.enabled) {
4613 /* Obtain a context */
4614 MONO_CONTEXT_SET_IP (&ctx, NULL);
4615 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4616 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4618 mono_loader_lock ();
4619 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4620 mono_loader_unlock ();
4622 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4629 ss_depth_to_string (StepDepth depth)
4632 case STEP_DEPTH_OVER:
4634 case STEP_DEPTH_OUT:
4636 case STEP_DEPTH_INTO:
4639 g_assert_not_reached ();
4645 process_single_step_inner (DebuggerTlsData *tls)
4650 int il_offset, suspend_policy;
4653 MonoContext *ctx = &tls->restore_ctx;
4655 MonoSeqPointInfo *info;
4657 ip = MONO_CONTEXT_GET_IP (ctx);
4659 /* Skip the instruction causing the single step */
4660 mono_arch_skip_single_step (ctx);
4662 if (suspend_count > 0) {
4663 process_suspend (tls, ctx);
4668 // FIXME: A suspend race
4671 if (mono_thread_internal_current () != ss_req->thread)
4674 if (log_level > 0) {
4675 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4677 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));
4680 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4682 g_assert (ji->method);
4684 if (ji->method->wrapper_type && ji->method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4689 * Stopping in memset makes half-initialized vtypes visible.
4690 * Stopping in memcpy makes half-copied vtypes visible.
4692 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
4696 * The ip points to the instruction causing the single step event, which is before
4697 * the offset recorded in the seq point map, so find the next seq point after ip.
4699 sp = find_next_seq_point_for_native_offset (domain, ji->method, (guint8*)ip - (guint8*)ji->code_start, &info);
4702 il_offset = sp->il_offset;
4704 // FIXME: No tests fail if this is disabled
4706 if (ss_req->size == STEP_SIZE_LINE) {
4710 /* Step until a different source line is reached */
4711 MonoDebugMethodInfo *minfo;
4713 minfo = mono_debug_lookup_method (ji->method);
4716 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4718 if (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line) {
4719 mono_debug_free_source_location (loc);
4724 * Step until we reach a location with line number info,
4725 * otherwise the client can't show a location.
4726 * This can happen for example with statics initialized inline
4727 * outside of a cctor.
4732 ss_req->last_method = ji->method;
4733 ss_req->last_line = loc->row;
4734 mono_debug_free_source_location (loc);
4740 /* Start single stepping again from the current sequence point */
4741 ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4743 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
4744 (ji->method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4745 !strcmp (ji->method->name, ".cctor"))
4748 // FIXME: Has to lock earlier
4750 reqs = g_ptr_array_new ();
4752 mono_loader_lock ();
4754 g_ptr_array_add (reqs, ss_req->req);
4756 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4758 g_ptr_array_free (reqs, TRUE);
4760 mono_loader_unlock ();
4762 process_event (EVENT_KIND_STEP, ji->method, il_offset, ctx, events, suspend_policy);
4766 process_single_step (void)
4768 process_signal_event (process_single_step_inner);
4772 * mono_debugger_agent_single_step_event:
4774 * Called from a signal handler to handle a single step event.
4777 mono_debugger_agent_single_step_event (void *sigctx)
4779 /* Resume to process_single_step through the signal context */
4781 // FIXME: Since step out/over is implemented using step in, the step in case should
4782 // be as fast as possible. Move the relevant code from process_single_step_inner ()
4785 if (GetCurrentThreadId () == debugger_thread_id) {
4787 * This could happen despite our best effors when the runtime calls
4788 * assembly/type resolve hooks.
4789 * FIXME: Breakpoints too.
4793 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4794 mono_arch_skip_single_step (&ctx);
4795 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4799 resume_from_signal_handler (sigctx, process_single_step);
4803 debugger_agent_single_step_from_context (MonoContext *ctx)
4805 DebuggerTlsData *tls;
4806 MonoContext orig_restore_ctx;
4808 tls = mono_native_tls_get_value (debugger_tls_id);
4811 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4812 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4813 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4815 process_single_step_inner (tls);
4817 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4818 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4822 debugger_agent_breakpoint_from_context (MonoContext *ctx)
4824 DebuggerTlsData *tls;
4825 MonoContext orig_restore_ctx;
4827 tls = mono_native_tls_get_value (debugger_tls_id);
4829 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4830 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4832 process_breakpoint_inner (tls);
4834 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4835 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4839 * start_single_stepping:
4841 * Turn on single stepping. Can be called multiple times, for example,
4842 * by a single step event request + a suspend.
4845 start_single_stepping (void)
4847 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4848 int val = InterlockedIncrement (&ss_count);
4851 mono_arch_start_single_stepping ();
4853 if (ss_req != NULL && ss_invoke_addr == NULL) {
4854 DebuggerTlsData *tls;
4856 mono_loader_lock ();
4858 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
4859 ss_invoke_addr = tls->invoke_addr;
4861 mono_loader_unlock ();
4864 g_assert_not_reached ();
4869 stop_single_stepping (void)
4871 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4872 int val = InterlockedDecrement (&ss_count);
4875 mono_arch_stop_single_stepping ();
4877 g_assert_not_reached ();
4884 * Stop the single stepping operation given by SS_REQ.
4887 ss_stop (SingleStepReq *ss_req)
4892 for (l = ss_req->bps; l; l = l->next) {
4893 clear_breakpoint (l->data);
4895 g_slist_free (ss_req->bps);
4899 if (ss_req->global) {
4900 stop_single_stepping ();
4901 ss_req->global = FALSE;
4908 * Start the single stepping operation given by SS_REQ from the sequence point SP.
4909 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
4910 * belong to the same thread as CTX.
4913 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
4915 int i, j, frame_index;
4918 gboolean enable_global = FALSE;
4920 /* Stop the previous operation */
4924 * Implement single stepping using breakpoints if possible.
4926 if (step_to_catch) {
4927 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
4928 ss_req->bps = g_slist_append (ss_req->bps, bp);
4932 if ((!sp || sp->next_len == 0 || ss_req->depth == STEP_DEPTH_OUT || ss_req->depth == STEP_DEPTH_OVER) && ctx) {
4933 /* Need parent frames */
4934 if (!tls->context.valid)
4935 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4936 compute_frame_info (tls->thread, tls);
4940 * Find the first sequence point in the current or in a previous frame which
4941 * is not the last in its method.
4943 if (ss_req->depth == STEP_DEPTH_OUT) {
4944 /* Ignore seq points in current method */
4945 while (frame_index < tls->frame_count) {
4946 StackFrame *frame = tls->frames [frame_index];
4948 method = frame->method;
4949 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4951 if (sp && sp->next_len != 0)
4954 // There could be method calls before the next seq point in the caller when using nested calls
4955 //enable_global = TRUE;
4957 if (sp && sp->next_len == 0) {
4959 while (frame_index < tls->frame_count) {
4960 StackFrame *frame = tls->frames [frame_index];
4962 method = frame->method;
4963 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4964 if (sp && sp->next_len != 0)
4972 if (sp && sp->next_len > 0) {
4973 for (i = 0; i < sp->next_len; ++i) {
4974 next_sp = &info->seq_points [sp->next [i]];
4976 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
4977 ss_req->bps = g_slist_append (ss_req->bps, bp);
4981 if (ss_req->depth == STEP_DEPTH_OVER) {
4982 /* Need to stop in catch clauses as well */
4983 for (i = 0; i < tls->frame_count; ++i) {
4984 StackFrame *frame = tls->frames [i];
4987 MonoJitInfo *jinfo = frame->ji;
4988 for (j = 0; j < jinfo->num_clauses; ++j) {
4989 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
4991 sp = find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL);
4993 bp = set_breakpoint (frame->method, sp->il_offset, ss_req->req, NULL);
4994 ss_req->bps = g_slist_append (ss_req->bps, bp);
5002 if (ss_req->depth == STEP_DEPTH_INTO) {
5003 /* Enable global stepping so we stop at method entry too */
5004 enable_global = TRUE;
5008 * The ctx/frame info computed above will become invalid when we continue.
5010 tls->context.valid = FALSE;
5011 tls->async_state.valid = FALSE;
5012 invalidate_frames (tls);
5015 if (enable_global) {
5016 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
5017 ss_req->global = TRUE;
5018 start_single_stepping ();
5019 } else if (!ss_req->bps) {
5020 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
5021 ss_req->global = TRUE;
5022 start_single_stepping ();
5024 ss_req->global = FALSE;
5029 * Start single stepping of thread THREAD
5032 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
5034 DebuggerTlsData *tls;
5035 MonoSeqPointInfo *info = NULL;
5036 SeqPoint *sp = NULL;
5037 MonoMethod *method = NULL;
5038 MonoDebugMethodInfo *minfo;
5039 gboolean step_to_catch = FALSE;
5041 if (suspend_count == 0)
5042 return ERR_NOT_SUSPENDED;
5044 wait_for_suspend ();
5046 // FIXME: Multiple requests
5048 DEBUG (0, fprintf (log_file, "Received a single step request while the previous one was still active.\n"));
5049 return ERR_NOT_IMPLEMENTED;
5052 DEBUG (1, fprintf (log_file, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
5054 ss_req = g_new0 (SingleStepReq, 1);
5056 ss_req->thread = thread;
5057 ss_req->size = size;
5058 ss_req->depth = depth;
5061 mono_loader_lock ();
5062 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5063 mono_loader_unlock ();
5065 g_assert (tls->context.valid);
5066 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5068 if (tls->catch_state.valid) {
5070 StackFrameInfo frame;
5071 MonoContext new_ctx;
5072 MonoLMF *lmf = NULL;
5075 * We are stopped at a throw site. Stepping should go to the catch site.
5078 /* Find the the jit info for the catch context */
5079 res = mono_find_jit_info_ext (tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], thread->jit_data, NULL, &tls->catch_state.ctx, &new_ctx, NULL, &lmf, NULL, &frame);
5081 g_assert (frame.type == FRAME_TYPE_MANAGED);
5084 * Find the seq point corresponding to the landing site ip, which is the first seq
5087 sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
5089 no_seq_points_found (frame.method);
5092 method = frame.method;
5094 step_to_catch = TRUE;
5095 /* This make sure the seq point is not skipped by process_single_step () */
5096 ss_req->last_sp = NULL;
5099 if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
5102 /* Compute the initial line info */
5103 compute_frame_info (thread, tls);
5105 if (tls->frame_count) {
5106 frame = tls->frames [0];
5108 ss_req->last_method = frame->method;
5109 ss_req->last_line = -1;
5111 minfo = mono_debug_lookup_method (frame->method);
5112 if (minfo && frame->il_offset != -1) {
5113 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
5116 ss_req->last_line = loc->row;
5123 if (!step_to_catch) {
5126 compute_frame_info (thread, tls);
5128 if (tls->frame_count) {
5129 frame = tls->frames [0];
5131 if (!method && frame->il_offset != -1) {
5132 /* FIXME: Sort the table and use a binary search */
5133 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5135 no_seq_points_found (frame->method);
5137 method = frame->method;
5142 ss_start (ss_req, method, sp, info, &tls->context.ctx, tls, step_to_catch);
5148 ss_destroy (SingleStepReq *req)
5151 g_assert (ss_req == req);
5160 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5163 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5169 if (!agent_config.enabled)
5172 mono_loader_lock ();
5173 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5174 mono_loader_unlock ();
5177 ei.category = category ? mono_string_to_utf8 (category) : NULL;
5178 ei.message = message ? mono_string_to_utf8 (message) : NULL;
5180 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5182 g_free (ei.category);
5183 g_free (ei.message);
5187 mono_debugger_agent_debug_log_is_enabled (void)
5189 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5190 return agent_config.enabled;
5193 #ifdef PLATFORM_ANDROID
5195 mono_debugger_agent_unhandled_exception (MonoException *exc)
5204 memset (&ei, 0, sizeof (EventInfo));
5205 ei.exc = (MonoObject*)exc;
5207 mono_loader_lock ();
5208 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5209 mono_loader_unlock ();
5211 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5216 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5217 MonoContext *catch_ctx)
5219 int i, j, suspend_policy;
5221 MonoJitInfo *ji, *catch_ji;
5223 DebuggerTlsData *tls = NULL;
5225 if (thread_to_tls != NULL) {
5226 MonoInternalThread *thread = mono_thread_internal_current ();
5228 mono_loader_lock ();
5229 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5230 mono_loader_unlock ();
5232 if (tls && tls->abort_requested)
5234 if (tls && tls->disable_breakpoints)
5238 memset (&ei, 0, sizeof (EventInfo));
5240 /* Just-In-Time debugging */
5242 if (agent_config.onuncaught && !inited) {
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);
5253 } else if (agent_config.onthrow && !inited) {
5255 gboolean found = FALSE;
5257 for (l = agent_config.onthrow; l; l = l->next) {
5258 char *ex_type = l->data;
5259 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5261 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5268 finish_agent_init (FALSE);
5271 * Send an unsolicited EXCEPTION event with a dummy request id.
5273 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5274 ei.exc = (MonoObject*)exc;
5275 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5283 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5285 catch_ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5289 ei.exc = (MonoObject*)exc;
5290 ei.caught = catch_ctx != NULL;
5292 mono_loader_lock ();
5294 /* Treat exceptions which are caught in non-user code as unhandled */
5295 for (i = 0; i < event_requests->len; ++i) {
5296 EventRequest *req = g_ptr_array_index (event_requests, i);
5297 if (req->event_kind != EVENT_KIND_EXCEPTION)
5300 for (j = 0; j < req->nmodifiers; ++j) {
5301 Modifier *mod = &req->modifiers [j];
5303 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5305 gboolean found = FALSE;
5306 MonoAssembly **assemblies = mod->data.assemblies;
5309 for (k = 0; assemblies [k]; ++k)
5310 if (assemblies [k] == catch_ji->method->klass->image->assembly)
5319 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5320 mono_loader_unlock ();
5322 if (tls && ei.caught && catch_ctx) {
5323 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5324 tls->catch_state.ctx = *catch_ctx;
5325 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5326 tls->catch_state.valid = TRUE;
5329 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5332 tls->catch_state.valid = FALSE;
5336 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5338 DebuggerTlsData *tls;
5343 tls = mono_native_tls_get_value (debugger_tls_id);
5348 * We're about to invoke an exception filter during the first pass of exception handling.
5350 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5351 * 'orig_ctx' is the context where the exception has been thrown.
5354 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5356 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5357 * the call site (line 37) and then continue to Main(), but it would never
5358 * include the throw site (line 32).
5360 * Since exception filters are invoked during the first pass of exception handling,
5361 * the stack frames of the throw site are still intact, so we should include them
5364 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5366 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5367 * but report the location of the 'throw' to the user.
5371 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5375 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5377 DebuggerTlsData *tls;
5382 tls = mono_native_tls_get_value (debugger_tls_id);
5386 tls->filter_state.valid = FALSE;
5390 * buffer_add_value_full:
5392 * Add the encoding of the value at ADDR described by T to the buffer.
5393 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5397 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5403 if (!(*(void**)addr)) {
5404 /* This can happen with compiler generated locals */
5405 //printf ("%s\n", mono_type_full_name (t));
5406 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5409 g_assert (*(void**)addr);
5410 addr = *(void**)addr;
5415 case MONO_TYPE_BOOLEAN:
5418 case MONO_TYPE_CHAR:
5438 case MONO_TYPE_VOID:
5439 buffer_add_byte (buf, t->type);
5441 case MONO_TYPE_BOOLEAN:
5444 buffer_add_byte (buf, t->type);
5445 buffer_add_int (buf, *(gint8*)addr);
5447 case MONO_TYPE_CHAR:
5450 buffer_add_byte (buf, t->type);
5451 buffer_add_int (buf, *(gint16*)addr);
5456 buffer_add_byte (buf, t->type);
5457 buffer_add_int (buf, *(gint32*)addr);
5462 buffer_add_byte (buf, t->type);
5463 buffer_add_long (buf, *(gint64*)addr);
5467 /* Treat it as a vtype */
5469 case MONO_TYPE_PTR: {
5470 gssize val = *(gssize*)addr;
5472 buffer_add_byte (buf, t->type);
5473 buffer_add_long (buf, val);
5477 case MONO_TYPE_STRING:
5478 case MONO_TYPE_SZARRAY:
5479 case MONO_TYPE_OBJECT:
5480 case MONO_TYPE_CLASS:
5481 case MONO_TYPE_ARRAY:
5482 obj = *(MonoObject**)addr;
5485 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5487 if (obj->vtable->klass->valuetype) {
5488 t = &obj->vtable->klass->byval_arg;
5489 addr = mono_object_unbox (obj);
5491 } else if (obj->vtable->klass->rank) {
5492 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5493 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5494 buffer_add_byte (buf, MONO_TYPE_CLASS);
5496 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5498 buffer_add_objid (buf, obj);
5502 case MONO_TYPE_VALUETYPE: {
5506 MonoClass *klass = mono_class_from_mono_type (t);
5508 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5509 buffer_add_byte (buf, klass->enumtype);
5510 buffer_add_typeid (buf, domain, klass);
5514 while ((f = mono_class_get_fields (klass, &iter))) {
5515 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5517 if (mono_field_is_deleted (f))
5521 buffer_add_int (buf, nfields);
5524 while ((f = mono_class_get_fields (klass, &iter))) {
5525 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5527 if (mono_field_is_deleted (f))
5529 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE);
5533 case MONO_TYPE_GENERICINST:
5534 if (mono_type_generic_inst_is_valuetype (t)) {
5546 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5548 buffer_add_value_full (buf, t, addr, domain, FALSE);
5552 obj_is_of_type (MonoObject *obj, MonoType *t)
5554 MonoClass *klass = obj->vtable->klass;
5555 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5556 if (mono_class_is_transparent_proxy (klass)) {
5557 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5558 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5568 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5571 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5575 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5576 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5577 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5578 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5579 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
5580 char *name = mono_type_full_name (t);
5581 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5583 return ERR_INVALID_ARGUMENT;
5587 case MONO_TYPE_BOOLEAN:
5588 *(guint8*)addr = decode_int (buf, &buf, limit);
5590 case MONO_TYPE_CHAR:
5591 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5594 *(gint8*)addr = decode_int (buf, &buf, limit);
5597 *(guint8*)addr = decode_int (buf, &buf, limit);
5600 *(gint16*)addr = decode_int (buf, &buf, limit);
5603 *(guint16*)addr = decode_int (buf, &buf, limit);
5606 *(gint32*)addr = decode_int (buf, &buf, limit);
5609 *(guint32*)addr = decode_int (buf, &buf, limit);
5612 *(gint64*)addr = decode_long (buf, &buf, limit);
5615 *(guint64*)addr = decode_long (buf, &buf, limit);
5618 *(guint32*)addr = decode_int (buf, &buf, limit);
5621 *(guint64*)addr = decode_long (buf, &buf, limit);
5624 /* We send these as I8, so we get them back as such */
5625 g_assert (type == MONO_TYPE_I8);
5626 *(gssize*)addr = decode_long (buf, &buf, limit);
5628 case MONO_TYPE_GENERICINST:
5629 if (MONO_TYPE_ISSTRUCT (t)) {
5630 /* The client sends these as a valuetype */
5638 /* We send these as vtypes, so we get them back as such */
5639 g_assert (type == MONO_TYPE_VALUETYPE);
5642 case MONO_TYPE_VALUETYPE: {
5643 gboolean is_enum = decode_byte (buf, &buf, limit);
5647 gpointer iter = NULL;
5650 /* Enums are sent as a normal vtype */
5652 return ERR_NOT_IMPLEMENTED;
5653 klass = decode_typeid (buf, &buf, limit, &d, &err);
5657 if (klass != mono_class_from_mono_type (t))
5658 return ERR_INVALID_ARGUMENT;
5660 nfields = decode_int (buf, &buf, limit);
5661 while ((f = mono_class_get_fields (klass, &iter))) {
5662 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5664 if (mono_field_is_deleted (f))
5666 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5671 g_assert (nfields == 0);
5676 if (MONO_TYPE_IS_REFERENCE (t)) {
5677 if (type == MONO_TYPE_OBJECT) {
5678 int objid = decode_objid (buf, &buf, limit);
5682 err = get_object (objid, (MonoObject**)&obj);
5687 if (!obj_is_of_type (obj, t)) {
5688 DEBUG (1, fprintf (log_file, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name));
5689 return ERR_INVALID_ARGUMENT;
5692 if (obj && obj->vtable->domain != domain)
5693 return ERR_INVALID_ARGUMENT;
5695 mono_gc_wbarrier_generic_store (addr, obj);
5696 } else if (type == VALUE_TYPE_ID_NULL) {
5697 *(MonoObject**)addr = NULL;
5699 return ERR_INVALID_ARGUMENT;
5713 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5716 int type = decode_byte (buf, &buf, limit);
5718 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
5719 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
5720 guint8 *nullable_buf;
5723 * First try decoding it as a Nullable`1
5725 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5730 * Then try decoding as a primitive value or null.
5732 if (targ->type == type) {
5733 nullable_buf = g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
5734 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
5736 g_free (nullable_buf);
5739 mono_nullable_init (addr, mono_value_box (domain, mono_class_from_mono_type (targ), nullable_buf), mono_class_from_mono_type (t));
5740 g_free (nullable_buf);
5743 } else if (type == VALUE_TYPE_ID_NULL) {
5744 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
5750 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5754 add_var (Buffer *buf, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
5761 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5762 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5765 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
5766 reg_val = mono_arch_context_get_int_reg (ctx, reg);
5768 buffer_add_value_full (buf, t, ®_val, domain, as_vtype);
5770 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5771 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5772 addr += (gint32)var->offset;
5774 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5776 buffer_add_value_full (buf, t, addr, domain, as_vtype);
5778 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5782 g_assert_not_reached ();
5787 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
5793 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5794 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5796 if (MONO_TYPE_IS_REFERENCE (t))
5797 size = sizeof (gpointer);
5799 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
5802 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
5803 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
5805 gboolean is_signed = FALSE;
5807 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
5812 v = is_signed ? *(gint8*)val : *(guint8*)val;
5815 v = is_signed ? *(gint16*)val : *(guint16*)val;
5818 v = is_signed ? *(gint32*)val : *(guint32*)val;
5821 v = is_signed ? *(gint64*)val : *(guint64*)val;
5824 g_assert_not_reached ();
5830 /* Set value on the stack or in the return ctx */
5831 if (reg_locations [reg]) {
5832 /* Saved on the stack */
5833 DEBUG (1, fprintf (log_file, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v));
5834 *(reg_locations [reg]) = v;
5837 DEBUG (1, fprintf (log_file, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v));
5838 mono_arch_context_set_int_reg (restore_ctx, reg, v);
5841 // FIXME: Move these to mono-context.h/c.
5842 mono_arch_context_set_int_reg (ctx, reg, v);
5844 // FIXME: Can't set registers, so we disable linears
5849 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5850 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5851 addr += (gint32)var->offset;
5853 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5856 addr = *(guint8**)addr;
5862 // FIXME: Write barriers
5863 mono_gc_memmove (addr, val, size);
5865 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5869 g_assert_not_reached ();
5874 clear_event_request (int req_id, int etype)
5878 mono_loader_lock ();
5879 for (i = 0; i < event_requests->len; ++i) {
5880 EventRequest *req = g_ptr_array_index (event_requests, i);
5882 if (req->id == req_id && req->event_kind == etype) {
5883 if (req->event_kind == EVENT_KIND_BREAKPOINT)
5884 clear_breakpoint (req->info);
5885 if (req->event_kind == EVENT_KIND_STEP)
5886 ss_destroy (req->info);
5887 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
5888 clear_breakpoint (req->info);
5889 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
5890 clear_breakpoint (req->info);
5891 g_ptr_array_remove_index_fast (event_requests, i);
5896 mono_loader_unlock ();
5900 event_req_matches_assembly (EventRequest *req, MonoAssembly *assembly)
5902 if (req->event_kind == EVENT_KIND_BREAKPOINT)
5903 return breakpoint_matches_assembly (req->info, assembly);
5907 for (i = 0; i < req->nmodifiers; ++i) {
5908 Modifier *m = &req->modifiers [i];
5910 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
5912 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
5913 for (j = 0; m->data.assemblies [j]; ++j)
5914 if (m->data.assemblies [j] == assembly)
5924 * clear_event_requests_for_assembly:
5926 * Clear all events requests which reference ASSEMBLY.
5929 clear_event_requests_for_assembly (MonoAssembly *assembly)
5934 mono_loader_lock ();
5938 for (i = 0; i < event_requests->len; ++i) {
5939 EventRequest *req = g_ptr_array_index (event_requests, i);
5941 if (event_req_matches_assembly (req, assembly)) {
5942 clear_event_request (req->id, req->event_kind);
5948 mono_loader_unlock ();
5952 * type_comes_from_assembly:
5954 * GHRFunc that returns TRUE if klass comes from assembly
5957 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
5959 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
5963 * clear_types_for_assembly:
5965 * Clears types from loaded_classes for a given assembly
5968 clear_types_for_assembly (MonoAssembly *assembly)
5970 MonoDomain *domain = mono_domain_get ();
5971 AgentDomainInfo *info = NULL;
5973 mono_loader_lock ();
5974 info = get_agent_domain_info (domain);
5975 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
5976 mono_loader_unlock ();
5980 add_thread (gpointer key, gpointer value, gpointer user_data)
5982 MonoInternalThread *thread = value;
5983 Buffer *buf = user_data;
5985 buffer_add_objid (buf, (MonoObject*)thread);
5989 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
5991 guint8 *end = invoke->endp;
5994 MonoMethodSignature *sig;
5997 MonoObject *this, *res, *exc;
6000 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6003 MonoStopwatch watch;
6005 if (invoke->method) {
6007 * Invoke this method directly, currently only Environment.Exit () is supported.
6010 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>"));
6011 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
6012 g_assert_not_reached ();
6015 m = decode_methodid (p, &p, end, &domain, &err);
6018 sig = mono_method_signature (m);
6020 if (m->klass->valuetype)
6021 this_buf = g_alloca (mono_class_instance_size (m->klass));
6023 this_buf = g_alloca (sizeof (MonoObject*));
6024 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6025 /* Should be null */
6026 int type = decode_byte (p, &p, end);
6027 if (type != VALUE_TYPE_ID_NULL)
6028 return ERR_INVALID_ARGUMENT;
6029 memset (this_buf, 0, mono_class_instance_size (m->klass));
6031 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6036 if (!m->klass->valuetype)
6037 this = *(MonoObject**)this_buf;
6041 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>"));
6043 if (this && this->vtable->domain != domain)
6046 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
6047 if (!strcmp (m->name, ".ctor")) {
6048 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
6049 return ERR_INVALID_ARGUMENT;
6051 this = mono_object_new (domain, m->klass);
6053 return ERR_INVALID_ARGUMENT;
6057 if (this && !obj_is_of_type (this, &m->klass->byval_arg))
6058 return ERR_INVALID_ARGUMENT;
6060 nargs = decode_int (p, &p, end);
6061 if (nargs != sig->param_count)
6062 return ERR_INVALID_ARGUMENT;
6063 /* Use alloca to get gc tracking */
6064 arg_buf = g_alloca (nargs * sizeof (gpointer));
6065 memset (arg_buf, 0, nargs * sizeof (gpointer));
6066 args = g_alloca (nargs * sizeof (gpointer));
6067 for (i = 0; i < nargs; ++i) {
6068 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6069 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6073 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6076 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6077 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6080 args [i] = arg_buf [i];
6087 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6088 tls->disable_breakpoints = TRUE;
6090 tls->disable_breakpoints = FALSE;
6093 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6095 /* FIXME: Move this to arch specific code */
6096 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6097 if (invoke->has_ctx) {
6100 lmf_addr = mono_get_lmf_addr ();
6103 memset (&ext, 0, sizeof (ext));
6105 ext.lmf.previous_lmf = *(lmf_addr);
6106 /* Mark that this is a MonoLMFExt */
6107 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6108 ext.lmf.rsp = (gssize)&ext;
6109 #elif defined(TARGET_X86)
6110 ext.lmf.previous_lmf = (gsize)*(lmf_addr);
6111 /* Mark that this is a MonoLMFExt */
6112 ext.lmf.previous_lmf = (gsize)(gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6113 ext.lmf.ebp = (gssize)&ext;
6114 #elif defined(TARGET_ARM)
6115 ext.lmf.previous_lmf = *(lmf_addr);
6116 /* Mark that this is a MonoLMFExt */
6117 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6118 ext.lmf.sp = (gssize)&ext;
6119 #elif defined(TARGET_POWERPC)
6120 ext.lmf.previous_lmf = *(lmf_addr);
6121 /* Mark that this is a MonoLMFExt */
6122 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6123 ext.lmf.ebp = (gssize)&ext;
6124 #elif defined(TARGET_S390X)
6125 ext.lmf.previous_lmf = *(lmf_addr);
6126 /* Mark that this is a MonoLMFExt */
6127 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6128 ext.lmf.ebp = (gssize)&ext;
6129 #elif defined(TARGET_MIPS)
6130 ext.lmf.previous_lmf = *(lmf_addr);
6131 /* Mark that this is a MonoLMFExt */
6132 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6133 ext.lmf.iregs [mips_sp] = (gssize)&ext;
6135 g_assert_not_reached ();
6138 ext.debugger_invoke = TRUE;
6139 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6141 mono_set_lmf ((MonoLMF*)&ext);
6145 mono_stopwatch_start (&watch);
6146 if (m->klass->valuetype)
6147 res = mono_runtime_invoke (m, this_buf, args, &exc);
6149 res = mono_runtime_invoke (m, this, args, &exc);
6150 mono_stopwatch_stop (&watch);
6151 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)));
6153 buffer_add_byte (buf, 0);
6154 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6156 buffer_add_byte (buf, 1);
6157 if (sig->ret->type == MONO_TYPE_VOID) {
6158 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
6159 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
6162 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6163 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6164 buffer_add_value (buf, sig->ret, &res, domain);
6165 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6166 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6167 MonoClass *k = mono_class_from_mono_type (sig->ret);
6168 guint8 *nullable_buf = g_alloca (mono_class_value_size (k, NULL));
6170 g_assert (nullable_buf);
6171 mono_nullable_init (nullable_buf, res, k);
6172 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6175 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6182 tls->disable_breakpoints = FALSE;
6184 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6185 if (invoke->has_ctx)
6186 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
6190 // FIXME: byref arguments
6198 * Invoke the method given by tls->pending_invoke in the current thread.
6201 invoke_method (void)
6203 DebuggerTlsData *tls;
6208 static void (*restore_context) (void *);
6209 MonoContext restore_ctx;
6212 if (!restore_context)
6213 restore_context = mono_get_restore_context ();
6215 tls = mono_native_tls_get_value (debugger_tls_id);
6219 * Store the `InvokeData *' in `tls->invoke' until we're done with
6220 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6223 mono_loader_lock ();
6225 invoke = tls->pending_invoke;
6227 tls->pending_invoke = NULL;
6229 invoke->last_invoke = tls->invoke;
6230 tls->invoke = invoke;
6232 mono_loader_unlock ();
6234 tls->frames_up_to_date = FALSE;
6240 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6241 buffer_init (&buf, 128);
6244 /* Fail the other invokes as well */
6246 err = do_invoke_method (tls, &buf, invoke, p, &p);
6249 /* Start suspending before sending the reply */
6250 if (mindex == invoke->nmethods - 1) {
6251 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6252 for (i = 0; i < invoke->suspend_count; ++i)
6257 send_reply_packet (id, err, &buf);
6262 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6264 if (invoke->has_ctx)
6265 save_thread_context (&restore_ctx);
6267 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6268 g_assert (tls->resume_count);
6269 tls->resume_count -= invoke->suspend_count;
6272 DEBUG (1, fprintf (log_file, "[%p] Invoke finished, resume_count = %d.\n", (gpointer)GetCurrentThreadId (), tls->resume_count));
6275 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6277 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
6278 * after the mono_runtime_invoke() already returned, but it doesn't matter
6279 * because we reset the abort here.
6282 mono_loader_lock ();
6284 if (tls->abort_requested)
6285 mono_thread_internal_reset_abort (tls->thread);
6287 tls->invoke = tls->invoke->last_invoke;
6288 tls->abort_requested = FALSE;
6290 mono_loader_unlock ();
6299 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6301 MonoThread *thread = value;
6302 DebuggerTlsData *tls;
6305 mono_loader_lock ();
6306 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6308 res = tls->really_suspended;
6309 mono_loader_unlock ();
6315 get_source_files_for_type (MonoClass *klass)
6317 gpointer iter = NULL;
6319 MonoDebugSourceInfo *sinfo;
6323 files = g_ptr_array_new ();
6325 while ((method = mono_class_get_methods (klass, &iter))) {
6326 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6327 GPtrArray *source_file_list;
6330 mono_debug_symfile_get_line_numbers_full (minfo, NULL, &source_file_list, NULL, NULL, NULL, NULL, NULL);
6331 for (j = 0; j < source_file_list->len; ++j) {
6332 sinfo = g_ptr_array_index (source_file_list, j);
6333 for (i = 0; i < files->len; ++i)
6334 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6336 if (i == files->len)
6337 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6339 g_ptr_array_free (source_file_list, TRUE);
6347 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6350 case CMD_VM_VERSION: {
6351 char *build_info, *version;
6353 build_info = mono_get_runtime_build_info ();
6354 version = g_strdup_printf ("mono %s", build_info);
6356 buffer_add_string (buf, version); /* vm version */
6357 buffer_add_int (buf, MAJOR_VERSION);
6358 buffer_add_int (buf, MINOR_VERSION);
6359 g_free (build_info);
6363 case CMD_VM_SET_PROTOCOL_VERSION: {
6364 major_version = decode_int (p, &p, end);
6365 minor_version = decode_int (p, &p, end);
6366 protocol_version_set = TRUE;
6367 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
6370 case CMD_VM_ALL_THREADS: {
6372 mono_loader_lock ();
6373 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6374 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6375 mono_loader_unlock ();
6378 case CMD_VM_SUSPEND:
6380 wait_for_suspend ();
6383 if (suspend_count == 0)
6384 return ERR_NOT_SUSPENDED;
6386 clear_suspended_objs ();
6388 case CMD_VM_DISPOSE:
6389 /* Clear all event requests */
6390 mono_loader_lock ();
6391 while (event_requests->len > 0) {
6392 EventRequest *req = g_ptr_array_index (event_requests, 0);
6394 clear_event_request (req->id, req->event_kind);
6396 mono_loader_unlock ();
6398 while (suspend_count > 0)
6400 disconnected = TRUE;
6401 vm_start_event_sent = FALSE;
6404 MonoInternalThread *thread;
6405 DebuggerTlsData *tls;
6406 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6407 MonoClass *env_class;
6409 MonoMethod *exit_method = NULL;
6413 exit_code = decode_int (p, &p, end);
6415 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6417 /* Have to send a reply before exiting */
6418 send_reply_packet (id, 0, buf);
6420 /* Clear all event requests */
6421 mono_loader_lock ();
6422 while (event_requests->len > 0) {
6423 EventRequest *req = g_ptr_array_index (event_requests, 0);
6425 clear_event_request (req->id, req->event_kind);
6427 mono_loader_unlock ();
6430 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6431 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6432 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6433 * better than doing the shutdown ourselves, since it avoids various races.
6437 wait_for_suspend ();
6439 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6440 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
6442 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6445 mono_loader_lock ();
6446 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6447 mono_loader_unlock ();
6449 if (thread && exit_method) {
6450 mono_loader_lock ();
6451 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6452 mono_loader_unlock ();
6454 args = g_new0 (gpointer, 1);
6455 args [0] = g_malloc (sizeof (int));
6456 *(int*)(args [0]) = exit_code;
6458 tls->pending_invoke = g_new0 (InvokeData, 1);
6459 tls->pending_invoke->method = exit_method;
6460 tls->pending_invoke->args = args;
6461 tls->pending_invoke->nmethods = 1;
6463 while (suspend_count > 0)
6467 * No thread found, do it ourselves.
6468 * FIXME: This can race with normal shutdown etc.
6470 while (suspend_count > 0)
6473 mono_runtime_shutdown ();
6475 /* Suspend all managed threads since the runtime is going away */
6476 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
6477 mono_thread_suspend_all_other_threads ();
6478 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
6479 mono_runtime_quit ();
6480 transport_close2 ();
6481 DEBUG(1, fprintf (log_file, "Exiting...\n"));
6487 case CMD_VM_INVOKE_METHOD:
6488 case CMD_VM_INVOKE_METHODS: {
6489 int objid = decode_objid (p, &p, end);
6491 DebuggerTlsData *tls;
6492 int i, count, err, flags, nmethods;
6494 err = get_object (objid, (MonoObject**)&thread);
6498 flags = decode_int (p, &p, end);
6500 if (command == CMD_VM_INVOKE_METHODS)
6501 nmethods = decode_int (p, &p, end);
6505 // Wait for suspending if it already started
6507 wait_for_suspend ();
6508 if (!is_suspended ())
6509 return ERR_NOT_SUSPENDED;
6511 mono_loader_lock ();
6512 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6513 mono_loader_unlock ();
6516 if (!tls->really_suspended)
6517 /* The thread is still running native code, can't do invokes */
6518 return ERR_NOT_SUSPENDED;
6521 * Store the invoke data into tls, the thread will execute it after it is
6524 if (tls->pending_invoke)
6525 return ERR_NOT_SUSPENDED;
6526 tls->pending_invoke = g_new0 (InvokeData, 1);
6527 tls->pending_invoke->id = id;
6528 tls->pending_invoke->flags = flags;
6529 tls->pending_invoke->p = g_malloc (end - p);
6530 memcpy (tls->pending_invoke->p, p, end - p);
6531 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
6532 tls->pending_invoke->suspend_count = suspend_count;
6533 tls->pending_invoke->nmethods = nmethods;
6535 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
6536 resume_thread (THREAD_TO_INTERNAL (thread));
6539 count = suspend_count;
6540 for (i = 0; i < count; ++i)
6545 case CMD_VM_ABORT_INVOKE: {
6546 int objid = decode_objid (p, &p, end);
6548 DebuggerTlsData *tls;
6551 err = get_object (objid, (MonoObject**)&thread);
6555 invoke_id = decode_int (p, &p, end);
6557 mono_loader_lock ();
6558 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6561 if (tls->abort_requested) {
6562 mono_loader_unlock ();
6567 * Check whether we're still inside the mono_runtime_invoke() and that it's
6568 * actually the correct invocation.
6570 * Careful, we do not stop the thread that's doing the invocation, so we can't
6571 * inspect its stack. However, invoke_method() also acquires the loader lock
6572 * when it's done, so we're safe here.
6576 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
6577 mono_loader_unlock ();
6578 return ERR_NO_INVOCATION;
6581 tls->abort_requested = TRUE;
6583 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
6584 mono_loader_unlock ();
6588 case CMD_VM_SET_KEEPALIVE: {
6589 int timeout = decode_int (p, &p, end);
6590 agent_config.keepalive = timeout;
6592 #ifndef DISABLE_SOCKET_TRANSPORT
6599 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
6600 GHashTableIter iter, kiter;
6605 char *fname, *basename;
6606 gboolean ignore_case;
6607 GSList *class_list, *l;
6608 GPtrArray *res_classes, *res_domains;
6610 fname = decode_string (p, &p, end);
6611 ignore_case = decode_byte (p, &p, end);
6613 basename = g_path_get_basename (fname);
6615 res_classes = g_ptr_array_new ();
6616 res_domains = g_ptr_array_new ();
6618 mono_loader_lock ();
6619 g_hash_table_iter_init (&iter, domains);
6620 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6621 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
6623 /* Update 'source_file_to_class' cache */
6624 g_hash_table_iter_init (&kiter, info->loaded_classes);
6625 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
6626 if (!g_hash_table_lookup (info->source_files, klass)) {
6627 files = get_source_files_for_type (klass);
6628 g_hash_table_insert (info->source_files, klass, files);
6630 for (i = 0; i < files->len; ++i) {
6631 char *s = g_ptr_array_index (files, i);
6632 char *s2 = g_path_get_basename (s);
6635 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
6637 class_list = g_slist_prepend (class_list, klass);
6638 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
6640 class_list = g_slist_prepend (class_list, klass);
6641 g_hash_table_insert (info->source_file_to_class, s2, class_list);
6644 /* The _ignorecase hash contains the lowercase path */
6645 s3 = strdup_tolower (s2);
6646 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
6648 class_list = g_slist_prepend (class_list, klass);
6649 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
6651 class_list = g_slist_prepend (class_list, klass);
6652 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
6664 s = strdup_tolower (basename);
6665 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
6668 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
6671 for (l = class_list; l; l = l->next) {
6674 g_ptr_array_add (res_classes, klass);
6675 g_ptr_array_add (res_domains, domain);
6678 mono_loader_unlock ();
6683 buffer_add_int (buf, res_classes->len);
6684 for (i = 0; i < res_classes->len; ++i)
6685 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6686 g_ptr_array_free (res_classes, TRUE);
6687 g_ptr_array_free (res_domains, TRUE);
6690 case CMD_VM_GET_TYPES: {
6691 GHashTableIter iter;
6695 gboolean ignore_case;
6696 GPtrArray *res_classes, *res_domains;
6697 MonoTypeNameParse info;
6699 name = decode_string (p, &p, end);
6700 ignore_case = decode_byte (p, &p, end);
6702 if (!mono_reflection_parse_type (name, &info)) {
6704 mono_reflection_free_type_info (&info);
6705 return ERR_INVALID_ARGUMENT;
6708 res_classes = g_ptr_array_new ();
6709 res_domains = g_ptr_array_new ();
6711 mono_loader_lock ();
6712 g_hash_table_iter_init (&iter, domains);
6713 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6715 gboolean type_resolve;
6719 mono_domain_assemblies_lock (domain);
6720 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6724 type_resolve = TRUE;
6725 t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
6727 g_ptr_array_add (res_classes, mono_type_get_class (t));
6728 g_ptr_array_add (res_domains, domain);
6732 mono_domain_assemblies_unlock (domain);
6734 mono_loader_unlock ();
6737 mono_reflection_free_type_info (&info);
6739 buffer_add_int (buf, res_classes->len);
6740 for (i = 0; i < res_classes->len; ++i)
6741 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6742 g_ptr_array_free (res_classes, TRUE);
6743 g_ptr_array_free (res_domains, TRUE);
6748 return ERR_NOT_IMPLEMENTED;
6755 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6761 case CMD_EVENT_REQUEST_SET: {
6763 int i, event_kind, suspend_policy, nmodifiers, mod;
6766 MonoThread *step_thread;
6767 int size = 0, depth = 0, filter = 0, step_thread_id = 0;
6771 event_kind = decode_byte (p, &p, end);
6772 suspend_policy = decode_byte (p, &p, end);
6773 nmodifiers = decode_byte (p, &p, end);
6775 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
6776 req->id = InterlockedIncrement (&event_request_id);
6777 req->event_kind = event_kind;
6778 req->suspend_policy = suspend_policy;
6779 req->nmodifiers = nmodifiers;
6782 for (i = 0; i < nmodifiers; ++i) {
6783 mod = decode_byte (p, &p, end);
6785 req->modifiers [i].kind = mod;
6786 if (mod == MOD_KIND_COUNT) {
6787 req->modifiers [i].data.count = decode_int (p, &p, end);
6788 } else if (mod == MOD_KIND_LOCATION_ONLY) {
6789 method = decode_methodid (p, &p, end, &domain, &err);
6792 location = decode_long (p, &p, end);
6793 } else if (mod == MOD_KIND_STEP) {
6794 step_thread_id = decode_id (p, &p, end);
6795 size = decode_int (p, &p, end);
6796 depth = decode_int (p, &p, end);
6797 if (CHECK_PROTOCOL_VERSION (2, 16))
6798 filter = decode_int (p, &p, end);
6799 req->modifiers [i].data.filter = filter;
6800 } else if (mod == MOD_KIND_THREAD_ONLY) {
6801 int id = decode_id (p, &p, end);
6803 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
6808 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
6809 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
6813 req->modifiers [i].caught = decode_byte (p, &p, end);
6814 req->modifiers [i].uncaught = decode_byte (p, &p, end);
6815 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" : ""));
6817 req->modifiers [i].data.exc_class = exc_class;
6819 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
6821 return ERR_INVALID_ARGUMENT;
6824 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
6825 int n = decode_int (p, &p, end);
6828 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
6829 for (j = 0; j < n; ++j) {
6830 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
6832 g_free (req->modifiers [i].data.assemblies);
6836 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
6837 int n = decode_int (p, &p, end);
6840 modifier = &req->modifiers [i];
6841 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
6842 for (j = 0; j < n; ++j) {
6843 char *s = decode_string (p, &p, end);
6847 s2 = strdup_tolower (s);
6848 g_hash_table_insert (modifier->data.source_files, s2, s2);
6852 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
6853 int n = decode_int (p, &p, end);
6856 modifier = &req->modifiers [i];
6857 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
6858 for (j = 0; j < n; ++j) {
6859 char *s = decode_string (p, &p, end);
6862 g_hash_table_insert (modifier->data.type_names, s, s);
6866 return ERR_NOT_IMPLEMENTED;
6870 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
6873 req->info = set_breakpoint (method, location, req, &error);
6874 if (!mono_error_ok (&error)) {
6876 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
6877 mono_error_cleanup (&error);
6878 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
6880 } else if (req->event_kind == EVENT_KIND_STEP) {
6881 g_assert (step_thread_id);
6883 err = get_object (step_thread_id, (MonoObject**)&step_thread);
6889 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
6894 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
6895 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
6896 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
6897 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
6898 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
6899 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
6901 if (req->nmodifiers) {
6903 return ERR_NOT_IMPLEMENTED;
6907 mono_loader_lock ();
6908 g_ptr_array_add (event_requests, req);
6910 if (agent_config.defer) {
6911 /* Transmit cached data to the client on receipt of the event request */
6912 switch (req->event_kind) {
6913 case EVENT_KIND_APPDOMAIN_CREATE:
6914 /* Emit load events for currently loaded domains */
6915 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
6917 case EVENT_KIND_ASSEMBLY_LOAD:
6918 /* Emit load events for currently loaded assemblies */
6919 mono_assembly_foreach (emit_assembly_load, NULL);
6921 case EVENT_KIND_THREAD_START:
6922 /* Emit start events for currently started threads */
6923 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
6925 case EVENT_KIND_TYPE_LOAD:
6926 /* Emit type load events for currently loaded types */
6927 mono_domain_foreach (send_types_for_domain, NULL);
6933 mono_loader_unlock ();
6935 buffer_add_int (buf, req->id);
6938 case CMD_EVENT_REQUEST_CLEAR: {
6939 int etype = decode_byte (p, &p, end);
6940 int req_id = decode_int (p, &p, end);
6942 // FIXME: Make a faster mapping from req_id to request
6943 mono_loader_lock ();
6944 clear_event_request (req_id, etype);
6945 mono_loader_unlock ();
6948 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
6951 mono_loader_lock ();
6953 while (i < event_requests->len) {
6954 EventRequest *req = g_ptr_array_index (event_requests, i);
6956 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
6957 clear_breakpoint (req->info);
6959 g_ptr_array_remove_index_fast (event_requests, i);
6965 mono_loader_unlock ();
6969 return ERR_NOT_IMPLEMENTED;
6976 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6982 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
6983 buffer_add_domainid (buf, mono_get_root_domain ());
6986 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
6987 domain = decode_domainid (p, &p, end, NULL, &err);
6990 buffer_add_string (buf, domain->friendly_name);
6993 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
6998 domain = decode_domainid (p, &p, end, NULL, &err);
7001 mono_loader_lock ();
7003 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7006 buffer_add_int (buf, count);
7007 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7009 buffer_add_assemblyid (buf, domain, ass);
7011 mono_loader_unlock ();
7014 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7015 domain = decode_domainid (p, &p, end, NULL, &err);
7019 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7022 case CMD_APPDOMAIN_GET_CORLIB: {
7023 domain = decode_domainid (p, &p, end, NULL, &err);
7027 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7030 case CMD_APPDOMAIN_CREATE_STRING: {
7034 domain = decode_domainid (p, &p, end, NULL, &err);
7037 s = decode_string (p, &p, end);
7039 o = mono_string_new (domain, s);
7040 buffer_add_objid (buf, (MonoObject*)o);
7043 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7045 MonoDomain *domain2;
7048 domain = decode_domainid (p, &p, end, NULL, &err);
7051 klass = decode_typeid (p, &p, end, &domain2, &err);
7056 g_assert (domain == domain2);
7058 o = mono_object_new (domain, klass);
7060 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
7064 buffer_add_objid (buf, o);
7068 return ERR_NOT_IMPLEMENTED;
7075 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7081 ass = decode_assemblyid (p, &p, end, &domain, &err);
7086 case CMD_ASSEMBLY_GET_LOCATION: {
7087 buffer_add_string (buf, mono_image_get_filename (ass->image));
7090 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7094 if (ass->image->dynamic) {
7095 buffer_add_id (buf, 0);
7097 token = mono_image_get_entry_point (ass->image);
7099 buffer_add_id (buf, 0);
7101 m = mono_get_method (ass->image, token, NULL);
7102 buffer_add_methodid (buf, domain, m);
7107 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7108 buffer_add_moduleid (buf, domain, ass->image);
7111 case CMD_ASSEMBLY_GET_OBJECT: {
7112 MonoObject *o = (MonoObject*)mono_assembly_get_object (domain, ass);
7113 buffer_add_objid (buf, o);
7116 case CMD_ASSEMBLY_GET_TYPE: {
7117 char *s = decode_string (p, &p, end);
7118 gboolean ignorecase = decode_byte (p, &p, end);
7119 MonoTypeNameParse info;
7121 gboolean type_resolve, res;
7122 MonoDomain *d = mono_domain_get ();
7124 /* This is needed to be able to find referenced assemblies */
7125 res = mono_domain_set (domain, FALSE);
7128 if (!mono_reflection_parse_type (s, &info)) {
7131 if (info.assembly.name)
7133 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
7135 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
7136 mono_reflection_free_type_info (&info);
7139 mono_domain_set (d, TRUE);
7143 case CMD_ASSEMBLY_GET_NAME: {
7145 MonoAssembly *mass = ass;
7147 name = g_strdup_printf (
7148 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7150 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7151 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7152 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7153 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7155 buffer_add_string (buf, name);
7160 return ERR_NOT_IMPLEMENTED;
7167 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7173 case CMD_MODULE_GET_INFO: {
7174 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7177 basename = g_path_get_basename (image->name);
7178 buffer_add_string (buf, basename); // name
7179 buffer_add_string (buf, image->module_name); // scopename
7180 buffer_add_string (buf, image->name); // fqname
7181 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7182 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7187 return ERR_NOT_IMPLEMENTED;
7194 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7196 if (val && val->vtable->klass == mono_defaults.monotype_class) {
7197 /* Special case these so the client doesn't have to handle Type objects */
7199 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7200 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7201 } else if (MONO_TYPE_IS_REFERENCE (t))
7202 buffer_add_value (buf, t, &val, domain);
7204 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7208 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7214 buffer_add_int (buf, 0);
7218 for (i = 0; i < cinfo->num_attrs; ++i) {
7219 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7222 buffer_add_int (buf, nattrs);
7224 for (i = 0; i < cinfo->num_attrs; ++i) {
7225 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7226 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7227 MonoArray *typed_args, *named_args;
7229 CattrNamedArg *arginfo;
7231 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo);
7233 buffer_add_methodid (buf, domain, attr->ctor);
7237 buffer_add_int (buf, mono_array_length (typed_args));
7238 for (j = 0; j < mono_array_length (typed_args); ++j) {
7239 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7241 t = mono_method_signature (attr->ctor)->params [j];
7243 buffer_add_cattr_arg (buf, t, domain, val);
7246 buffer_add_int (buf, 0);
7251 buffer_add_int (buf, mono_array_length (named_args));
7253 for (j = 0; j < mono_array_length (named_args); ++j) {
7254 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7256 if (arginfo [j].prop) {
7257 buffer_add_byte (buf, 0x54);
7258 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7259 } else if (arginfo [j].field) {
7260 buffer_add_byte (buf, 0x53);
7261 buffer_add_fieldid (buf, domain, arginfo [j].field);
7263 g_assert_not_reached ();
7266 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7269 buffer_add_int (buf, 0);
7275 /* FIXME: Code duplication with icall.c */
7277 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7282 mono_class_setup_interfaces (klass, error);
7283 if (!mono_error_ok (error))
7286 for (i = 0; i < klass->interface_count; i++) {
7287 ic = klass->interfaces [i];
7288 g_hash_table_insert (ifaces, ic, ic);
7290 collect_interfaces (ic, ifaces, error);
7291 if (!mono_error_ok (error))
7297 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7307 case CMD_TYPE_GET_INFO: {
7308 buffer_add_string (buf, klass->name_space);
7309 buffer_add_string (buf, klass->name);
7311 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7312 buffer_add_string (buf, name);
7314 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7315 buffer_add_moduleid (buf, domain, klass->image);
7316 buffer_add_typeid (buf, domain, klass->parent);
7317 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7318 buffer_add_typeid (buf, domain, klass->element_class);
7320 buffer_add_id (buf, 0);
7321 buffer_add_int (buf, klass->type_token);
7322 buffer_add_byte (buf, klass->rank);
7323 buffer_add_int (buf, klass->flags);
7325 type = &klass->byval_arg;
7326 // FIXME: Can't decide whenever a class represents a byref type
7329 if (type->type == MONO_TYPE_PTR)
7331 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7333 if (type->type == MONO_TYPE_VALUETYPE)
7335 if (klass->enumtype)
7337 if (klass->generic_container)
7339 if (klass->generic_container || klass->generic_class)
7341 buffer_add_byte (buf, b);
7344 while ((nested = mono_class_get_nested_types (klass, &iter)))
7346 buffer_add_int (buf, nnested);
7348 while ((nested = mono_class_get_nested_types (klass, &iter)))
7349 buffer_add_typeid (buf, domain, nested);
7350 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7351 if (klass->generic_container)
7352 buffer_add_typeid (buf, domain, klass);
7353 else if (klass->generic_class)
7354 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7356 buffer_add_id (buf, 0);
7358 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7361 if (klass->generic_class) {
7362 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7364 count = inst->type_argc;
7365 buffer_add_int (buf, count);
7366 for (i = 0; i < count; i++)
7367 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7368 } else if (klass->generic_container) {
7369 MonoGenericContainer *container = klass->generic_container;
7372 count = container->type_argc;
7373 buffer_add_int (buf, count);
7374 for (i = 0; i < count; i++) {
7375 pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
7376 buffer_add_typeid (buf, domain, pklass);
7379 buffer_add_int (buf, 0);
7384 case CMD_TYPE_GET_METHODS: {
7387 gpointer iter = NULL;
7390 mono_class_setup_methods (klass);
7392 nmethods = mono_class_num_methods (klass);
7394 buffer_add_int (buf, nmethods);
7396 while ((m = mono_class_get_methods (klass, &iter))) {
7397 buffer_add_methodid (buf, domain, m);
7400 g_assert (i == nmethods);
7403 case CMD_TYPE_GET_FIELDS: {
7406 gpointer iter = NULL;
7409 nfields = mono_class_num_fields (klass);
7411 buffer_add_int (buf, nfields);
7413 while ((f = mono_class_get_fields (klass, &iter))) {
7414 buffer_add_fieldid (buf, domain, f);
7415 buffer_add_string (buf, f->name);
7416 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7417 buffer_add_int (buf, f->type->attrs);
7420 g_assert (i == nfields);
7423 case CMD_TYPE_GET_PROPERTIES: {
7426 gpointer iter = NULL;
7429 nprops = mono_class_num_properties (klass);
7431 buffer_add_int (buf, nprops);
7433 while ((p = mono_class_get_properties (klass, &iter))) {
7434 buffer_add_propertyid (buf, domain, p);
7435 buffer_add_string (buf, p->name);
7436 buffer_add_methodid (buf, domain, p->get);
7437 buffer_add_methodid (buf, domain, p->set);
7438 buffer_add_int (buf, p->attrs);
7441 g_assert (i == nprops);
7444 case CMD_TYPE_GET_CATTRS: {
7445 MonoClass *attr_klass;
7446 MonoCustomAttrInfo *cinfo;
7448 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7449 /* attr_klass can be NULL */
7453 cinfo = mono_custom_attrs_from_class (klass);
7455 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7458 case CMD_TYPE_GET_FIELD_CATTRS: {
7459 MonoClass *attr_klass;
7460 MonoCustomAttrInfo *cinfo;
7461 MonoClassField *field;
7463 field = decode_fieldid (p, &p, end, NULL, &err);
7466 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7470 cinfo = mono_custom_attrs_from_field (klass, field);
7472 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7475 case CMD_TYPE_GET_PROPERTY_CATTRS: {
7476 MonoClass *attr_klass;
7477 MonoCustomAttrInfo *cinfo;
7480 prop = decode_propertyid (p, &p, end, NULL, &err);
7483 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7487 cinfo = mono_custom_attrs_from_property (klass, prop);
7489 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7492 case CMD_TYPE_GET_VALUES:
7493 case CMD_TYPE_GET_VALUES_2: {
7500 MonoThread *thread_obj;
7501 MonoInternalThread *thread = NULL;
7502 guint32 special_static_type;
7504 if (command == CMD_TYPE_GET_VALUES_2) {
7505 int objid = decode_objid (p, &p, end);
7508 err = get_object (objid, (MonoObject**)&thread_obj);
7512 thread = THREAD_TO_INTERNAL (thread_obj);
7515 len = decode_int (p, &p, end);
7516 for (i = 0; i < len; ++i) {
7517 f = decode_fieldid (p, &p, end, NULL, &err);
7521 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7522 return ERR_INVALID_FIELDID;
7523 special_static_type = mono_class_field_get_special_static_type (f);
7524 if (special_static_type != SPECIAL_STATIC_NONE) {
7525 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
7526 return ERR_INVALID_FIELDID;
7529 /* Check that the field belongs to the object */
7531 for (k = klass; k; k = k->parent) {
7532 if (k == f->parent) {
7538 return ERR_INVALID_FIELDID;
7540 vtable = mono_class_vtable (domain, f->parent);
7541 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7542 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
7543 buffer_add_value (buf, f->type, val, domain);
7548 case CMD_TYPE_SET_VALUES: {
7556 len = decode_int (p, &p, end);
7557 for (i = 0; i < len; ++i) {
7558 f = decode_fieldid (p, &p, end, NULL, &err);
7562 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7563 return ERR_INVALID_FIELDID;
7564 if (mono_class_field_is_special_static (f))
7565 return ERR_INVALID_FIELDID;
7567 /* Check that the field belongs to the object */
7569 for (k = klass; k; k = k->parent) {
7570 if (k == f->parent) {
7576 return ERR_INVALID_FIELDID;
7578 // FIXME: Check for literal/const
7580 vtable = mono_class_vtable (domain, f->parent);
7581 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7582 err = decode_value (f->type, domain, val, p, &p, end);
7587 if (MONO_TYPE_IS_REFERENCE (f->type))
7588 mono_field_static_set_value (vtable, f, *(gpointer*)val);
7590 mono_field_static_set_value (vtable, f, val);
7595 case CMD_TYPE_GET_OBJECT: {
7596 MonoObject *o = (MonoObject*)mono_type_get_object (domain, &klass->byval_arg);
7597 buffer_add_objid (buf, o);
7600 case CMD_TYPE_GET_SOURCE_FILES:
7601 case CMD_TYPE_GET_SOURCE_FILES_2: {
7602 char *source_file, *base;
7606 files = get_source_files_for_type (klass);
7608 buffer_add_int (buf, files->len);
7609 for (i = 0; i < files->len; ++i) {
7610 source_file = g_ptr_array_index (files, i);
7611 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
7612 buffer_add_string (buf, source_file);
7614 base = g_path_get_basename (source_file);
7615 buffer_add_string (buf, base);
7618 g_free (source_file);
7620 g_ptr_array_free (files, TRUE);
7623 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
7624 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
7628 if (mono_class_is_assignable_from (klass, oklass))
7629 buffer_add_byte (buf, 1);
7631 buffer_add_byte (buf, 0);
7634 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
7635 char *name = decode_string (p, &p, end);
7636 int i, flags = decode_int (p, &p, end);
7637 MonoException *ex = NULL;
7638 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
7641 return ERR_LOADER_ERROR;
7642 buffer_add_int (buf, array->len);
7643 for (i = 0; i < array->len; ++i) {
7644 MonoMethod *method = g_ptr_array_index (array, i);
7645 buffer_add_methodid (buf, domain, method);
7648 g_ptr_array_free (array, TRUE);
7652 case CMD_TYPE_GET_INTERFACES: {
7654 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
7656 MonoClass *tclass, *iface;
7657 GHashTableIter iter;
7661 for (parent = tclass; parent; parent = parent->parent) {
7662 mono_class_setup_interfaces (parent, &error);
7663 if (!mono_error_ok (&error))
7664 return ERR_LOADER_ERROR;
7665 collect_interfaces (parent, iface_hash, &error);
7666 if (!mono_error_ok (&error))
7667 return ERR_LOADER_ERROR;
7670 buffer_add_int (buf, g_hash_table_size (iface_hash));
7672 g_hash_table_iter_init (&iter, iface_hash);
7673 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
7674 buffer_add_typeid (buf, domain, iface);
7675 g_hash_table_destroy (iface_hash);
7678 case CMD_TYPE_GET_INTERFACE_MAP: {
7679 int tindex, ioffset;
7680 gboolean variance_used;
7682 int len, nmethods, i;
7686 len = decode_int (p, &p, end);
7687 mono_class_setup_vtable (klass);
7689 for (tindex = 0; tindex < len; ++tindex) {
7690 iclass = decode_typeid (p, &p, end, NULL, &err);
7694 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
7696 return ERR_INVALID_ARGUMENT;
7698 nmethods = mono_class_num_methods (iclass);
7699 buffer_add_int (buf, nmethods);
7702 while ((method = mono_class_get_methods (iclass, &iter))) {
7703 buffer_add_methodid (buf, domain, method);
7705 for (i = 0; i < nmethods; ++i)
7706 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
7710 case CMD_TYPE_IS_INITIALIZED: {
7711 MonoVTable *vtable = mono_class_vtable (domain, klass);
7714 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
7716 buffer_add_int (buf, 0);
7720 return ERR_NOT_IMPLEMENTED;
7727 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7730 MonoDomain *old_domain;
7734 klass = decode_typeid (p, &p, end, &domain, &err);
7738 old_domain = mono_domain_get ();
7740 mono_domain_set (domain, TRUE);
7742 err = type_commands_internal (command, klass, domain, p, end, buf);
7744 mono_domain_set (old_domain, TRUE);
7750 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7752 MonoMethodHeader *header;
7756 case CMD_METHOD_GET_NAME: {
7757 buffer_add_string (buf, method->name);
7760 case CMD_METHOD_GET_DECLARING_TYPE: {
7761 buffer_add_typeid (buf, domain, method->klass);
7764 case CMD_METHOD_GET_DEBUG_INFO: {
7765 MonoDebugMethodInfo *minfo;
7767 int i, j, n_il_offsets;
7770 int *column_numbers;
7772 GPtrArray *source_file_list;
7774 header = mono_method_get_header (method);
7776 buffer_add_int (buf, 0);
7777 buffer_add_string (buf, "");
7778 buffer_add_int (buf, 0);
7782 minfo = mono_debug_lookup_method (method);
7784 buffer_add_int (buf, header->code_size);
7785 buffer_add_string (buf, "");
7786 buffer_add_int (buf, 0);
7787 mono_metadata_free_mh (header);
7791 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, &n_il_offsets, &il_offsets, &line_numbers, &column_numbers, &source_files);
7792 buffer_add_int (buf, header->code_size);
7793 if (CHECK_PROTOCOL_VERSION (2, 13)) {
7794 buffer_add_int (buf, source_file_list->len);
7795 for (i = 0; i < source_file_list->len; ++i) {
7796 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
7797 buffer_add_string (buf, sinfo->source_file);
7798 if (CHECK_PROTOCOL_VERSION (2, 14)) {
7799 for (j = 0; j < 16; ++j)
7800 buffer_add_byte (buf, sinfo->hash [j]);
7804 buffer_add_string (buf, source_file);
7806 buffer_add_int (buf, n_il_offsets);
7807 DEBUG (10, fprintf (log_file, "Line number table for method %s:\n", mono_method_full_name (method, TRUE)));
7808 for (i = 0; i < n_il_offsets; ++i) {
7809 const char *srcfile = "";
7811 if (source_files [i] != -1) {
7812 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
7813 srcfile = sinfo->source_file;
7815 DEBUG (10, fprintf (log_file, "IL%x -> %s:%d %d\n", il_offsets [i], srcfile, line_numbers [i], column_numbers ? column_numbers [i] : -1));
7816 buffer_add_int (buf, il_offsets [i]);
7817 buffer_add_int (buf, line_numbers [i]);
7818 if (CHECK_PROTOCOL_VERSION (2, 13))
7819 buffer_add_int (buf, source_files [i]);
7820 if (CHECK_PROTOCOL_VERSION (2, 19))
7821 buffer_add_int (buf, column_numbers ? column_numbers [i] : -1);
7823 g_free (source_file);
7824 g_free (il_offsets);
7825 g_free (line_numbers);
7826 g_free (source_files);
7827 g_ptr_array_free (source_file_list, TRUE);
7828 mono_metadata_free_mh (header);
7831 case CMD_METHOD_GET_PARAM_INFO: {
7832 MonoMethodSignature *sig = mono_method_signature (method);
7836 /* FIXME: mono_class_from_mono_type () and byrefs */
7838 /* FIXME: Use a smaller encoding */
7839 buffer_add_int (buf, sig->call_convention);
7840 buffer_add_int (buf, sig->param_count);
7841 buffer_add_int (buf, sig->generic_param_count);
7842 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
7843 for (i = 0; i < sig->param_count; ++i) {
7845 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
7848 /* Emit parameter names */
7849 names = g_new (char *, sig->param_count);
7850 mono_method_get_param_names (method, (const char **) names);
7851 for (i = 0; i < sig->param_count; ++i)
7852 buffer_add_string (buf, names [i]);
7857 case CMD_METHOD_GET_LOCALS_INFO: {
7858 int i, j, num_locals;
7859 MonoDebugLocalsInfo *locals;
7861 header = mono_method_get_header (method);
7863 return ERR_INVALID_ARGUMENT;
7865 buffer_add_int (buf, header->num_locals);
7868 for (i = 0; i < header->num_locals; ++i)
7869 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
7872 locals = mono_debug_lookup_locals (method);
7874 num_locals = locals->num_locals;
7877 for (i = 0; i < header->num_locals; ++i) {
7878 for (j = 0; j < num_locals; ++j)
7879 if (locals->locals [j].index == i)
7882 buffer_add_string (buf, locals->locals [j].name);
7884 buffer_add_string (buf, "");
7888 for (i = 0; i < header->num_locals; ++i) {
7889 for (j = 0; j < num_locals; ++j)
7890 if (locals->locals [j].index == i)
7892 if (j < num_locals && locals->locals [j].block) {
7893 buffer_add_int (buf, locals->locals [j].block->start_offset);
7894 buffer_add_int (buf, locals->locals [j].block->end_offset);
7896 buffer_add_int (buf, 0);
7897 buffer_add_int (buf, header->code_size);
7900 mono_metadata_free_mh (header);
7903 mono_debug_symfile_free_locals (locals);
7907 case CMD_METHOD_GET_INFO:
7908 buffer_add_int (buf, method->flags);
7909 buffer_add_int (buf, method->iflags);
7910 buffer_add_int (buf, method->token);
7911 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7913 if (method->is_generic)
7915 if (mono_method_signature (method)->generic_param_count)
7917 buffer_add_byte (buf, attrs);
7918 if (method->is_generic || method->is_inflated) {
7921 if (method->is_generic) {
7924 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
7926 result = imethod->declaring;
7927 if (imethod->context.class_inst) {
7928 MonoClass *klass = ((MonoMethod *) imethod)->klass;
7929 /*Generic methods gets the context of the GTD.*/
7930 if (mono_class_get_context (klass))
7931 result = mono_class_inflate_generic_method_full (result, klass, mono_class_get_context (klass));
7935 buffer_add_methodid (buf, domain, result);
7937 buffer_add_id (buf, 0);
7939 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7940 if (mono_method_signature (method)->generic_param_count) {
7943 if (method->is_inflated) {
7944 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
7946 count = inst->type_argc;
7947 buffer_add_int (buf, count);
7949 for (i = 0; i < count; i++)
7950 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7952 buffer_add_int (buf, 0);
7954 } else if (method->is_generic) {
7955 MonoGenericContainer *container = mono_method_get_generic_container (method);
7957 count = mono_method_signature (method)->generic_param_count;
7958 buffer_add_int (buf, count);
7959 for (i = 0; i < count; i++) {
7960 MonoGenericParam *param = mono_generic_container_get_param (container, i);
7961 MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
7962 buffer_add_typeid (buf, domain, pklass);
7965 buffer_add_int (buf, 0);
7968 buffer_add_int (buf, 0);
7973 case CMD_METHOD_GET_BODY: {
7976 header = mono_method_get_header (method);
7978 buffer_add_int (buf, 0);
7980 if (CHECK_PROTOCOL_VERSION (2, 18))
7981 buffer_add_int (buf, 0);
7983 buffer_add_int (buf, header->code_size);
7984 for (i = 0; i < header->code_size; ++i)
7985 buffer_add_byte (buf, header->code [i]);
7987 if (CHECK_PROTOCOL_VERSION (2, 18)) {
7988 buffer_add_int (buf, header->num_clauses);
7989 for (i = 0; i < header->num_clauses; ++i) {
7990 MonoExceptionClause *clause = &header->clauses [i];
7992 buffer_add_int (buf, clause->flags);
7993 buffer_add_int (buf, clause->try_offset);
7994 buffer_add_int (buf, clause->try_len);
7995 buffer_add_int (buf, clause->handler_offset);
7996 buffer_add_int (buf, clause->handler_len);
7997 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
7998 buffer_add_typeid (buf, domain, clause->data.catch_class);
7999 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8000 buffer_add_int (buf, clause->data.filter_offset);
8004 mono_metadata_free_mh (header);
8009 case CMD_METHOD_RESOLVE_TOKEN: {
8010 guint32 token = decode_int (p, &p, end);
8013 switch (mono_metadata_token_code (token)) {
8014 case MONO_TOKEN_STRING: {
8018 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
8021 s2 = mono_string_to_utf8 (s);
8023 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8024 buffer_add_string (buf, s2);
8030 MonoClass *handle_class;
8032 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8033 val = mono_method_get_wrapper_data (method, token);
8034 handle_class = mono_method_get_wrapper_data (method, token + 1);
8036 if (handle_class == NULL) {
8037 // Can't figure out the token type
8038 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8042 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
8046 if (handle_class == mono_defaults.typehandle_class) {
8047 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8048 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8049 buffer_add_typeid (buf, domain, (MonoClass *) val);
8051 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
8052 } else if (handle_class == mono_defaults.fieldhandle_class) {
8053 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8054 buffer_add_fieldid (buf, domain, val);
8055 } else if (handle_class == mono_defaults.methodhandle_class) {
8056 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8057 buffer_add_methodid (buf, domain, val);
8058 } else if (handle_class == mono_defaults.string_class) {
8061 s = mono_string_to_utf8 (val);
8062 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8063 buffer_add_string (buf, s);
8066 g_assert_not_reached ();
8073 case CMD_METHOD_GET_CATTRS: {
8074 MonoClass *attr_klass;
8075 MonoCustomAttrInfo *cinfo;
8077 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8078 /* attr_klass can be NULL */
8082 cinfo = mono_custom_attrs_from_method (method);
8084 buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
8088 return ERR_NOT_IMPLEMENTED;
8095 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8098 MonoDomain *old_domain;
8102 method = decode_methodid (p, &p, end, &domain, &err);
8106 old_domain = mono_domain_get ();
8108 mono_domain_set (domain, TRUE);
8110 err = method_commands_internal (command, method, domain, p, end, buf);
8112 mono_domain_set (old_domain, TRUE);
8118 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8120 int objid = decode_objid (p, &p, end);
8122 MonoThread *thread_obj;
8123 MonoInternalThread *thread;
8125 err = get_object (objid, (MonoObject**)&thread_obj);
8129 thread = THREAD_TO_INTERNAL (thread_obj);
8132 case CMD_THREAD_GET_NAME: {
8134 gunichar2 *s = mono_thread_get_name (thread, &name_len);
8137 buffer_add_int (buf, 0);
8142 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
8144 buffer_add_int (buf, len);
8145 buffer_add_data (buf, (guint8*)name, len);
8150 case CMD_THREAD_GET_FRAME_INFO: {
8151 DebuggerTlsData *tls;
8152 int i, start_frame, length;
8154 // Wait for suspending if it already started
8155 // FIXME: Races with suspend_count
8156 while (!is_suspended ()) {
8158 wait_for_suspend ();
8162 wait_for_suspend ();
8163 if (!is_suspended ())
8164 return ERR_NOT_SUSPENDED;
8167 start_frame = decode_int (p, &p, end);
8168 length = decode_int (p, &p, end);
8170 if (start_frame != 0 || length != -1)
8171 return ERR_NOT_IMPLEMENTED;
8173 mono_loader_lock ();
8174 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8175 mono_loader_unlock ();
8178 compute_frame_info (thread, tls);
8180 buffer_add_int (buf, tls->frame_count);
8181 for (i = 0; i < tls->frame_count; ++i) {
8182 buffer_add_int (buf, tls->frames [i]->id);
8183 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
8184 buffer_add_int (buf, tls->frames [i]->il_offset);
8186 * Instead of passing the frame type directly to the client, we associate
8187 * it with the previous frame using a set of flags. This avoids lots of
8188 * conditional code in the client, since a frame whose type isn't
8189 * FRAME_TYPE_MANAGED has no method, location, etc.
8191 buffer_add_byte (buf, tls->frames [i]->flags);
8196 case CMD_THREAD_GET_STATE:
8197 buffer_add_int (buf, thread->state);
8199 case CMD_THREAD_GET_INFO:
8200 buffer_add_byte (buf, thread->threadpool_thread);
8202 case CMD_THREAD_GET_ID:
8203 buffer_add_long (buf, (guint64)(gsize)thread);
8205 case CMD_THREAD_GET_TID:
8206 buffer_add_long (buf, (guint64)thread->tid);
8209 return ERR_NOT_IMPLEMENTED;
8216 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8220 MonoThread *thread_obj;
8221 MonoInternalThread *thread;
8222 int pos, i, len, frame_idx;
8223 DebuggerTlsData *tls;
8225 MonoDebugMethodJitInfo *jit;
8226 MonoDebugVarInfo *var;
8227 MonoMethodSignature *sig;
8229 MonoMethodHeader *header;
8231 objid = decode_objid (p, &p, end);
8232 err = get_object (objid, (MonoObject**)&thread_obj);
8236 thread = THREAD_TO_INTERNAL (thread_obj);
8238 id = decode_id (p, &p, end);
8240 mono_loader_lock ();
8241 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8242 mono_loader_unlock ();
8245 for (i = 0; i < tls->frame_count; ++i) {
8246 if (tls->frames [i]->id == id)
8249 if (i == tls->frame_count)
8250 return ERR_INVALID_FRAMEID;
8253 frame = tls->frames [frame_idx];
8255 if (!frame->has_ctx)
8257 return ERR_INVALID_FRAMEID;
8260 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
8261 if (!frame->jit && frame->api_method->is_inflated)
8262 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
8266 /* This could happen for aot images with no jit debug info */
8267 s = mono_method_full_name (frame->api_method, TRUE);
8268 DEBUG (1, fprintf (log_file, "[dbg] No debug information found for '%s'.\n", s));
8270 return ERR_ABSENT_INFORMATION;
8275 sig = mono_method_signature (frame->actual_method);
8277 if (!get_seq_points (frame->domain, frame->actual_method))
8279 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
8281 return ERR_ABSENT_INFORMATION;
8284 case CMD_STACK_FRAME_GET_VALUES: {
8285 len = decode_int (p, &p, end);
8286 header = mono_method_get_header (frame->actual_method);
8288 for (i = 0; i < len; ++i) {
8289 pos = decode_int (p, &p, end);
8294 g_assert (pos >= 0 && pos < jit->num_params);
8296 var = &jit->params [pos];
8298 add_var (buf, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
8300 g_assert (pos >= 0 && pos < jit->num_locals);
8302 var = &jit->locals [pos];
8304 add_var (buf, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
8307 mono_metadata_free_mh (header);
8310 case CMD_STACK_FRAME_GET_THIS: {
8311 if (frame->api_method->klass->valuetype) {
8312 if (!sig->hasthis) {
8313 MonoObject *p = NULL;
8314 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
8316 add_var (buf, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8319 if (!sig->hasthis) {
8320 MonoObject *p = NULL;
8321 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
8323 add_var (buf, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8328 case CMD_STACK_FRAME_SET_VALUES: {
8331 MonoDebugVarInfo *var;
8333 len = decode_int (p, &p, end);
8334 header = mono_method_get_header (frame->actual_method);
8336 for (i = 0; i < len; ++i) {
8337 pos = decode_int (p, &p, end);
8342 g_assert (pos >= 0 && pos < jit->num_params);
8344 t = sig->params [pos];
8345 var = &jit->params [pos];
8347 g_assert (pos >= 0 && pos < jit->num_locals);
8349 t = header->locals [pos];
8350 var = &jit->locals [pos];
8353 if (MONO_TYPE_IS_REFERENCE (t))
8354 val_buf = g_alloca (sizeof (MonoObject*));
8356 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
8357 err = decode_value (t, frame->domain, val_buf, p, &p, end);
8361 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_ctx);
8363 mono_metadata_free_mh (header);
8367 return ERR_NOT_IMPLEMENTED;
8374 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8377 int objid, err, index, len, i, esize;
8380 objid = decode_objid (p, &p, end);
8381 err = get_object (objid, (MonoObject**)&arr);
8386 case CMD_ARRAY_REF_GET_LENGTH:
8387 buffer_add_int (buf, arr->obj.vtable->klass->rank);
8389 buffer_add_int (buf, arr->max_length);
8390 buffer_add_int (buf, 0);
8392 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
8393 buffer_add_int (buf, arr->bounds [i].length);
8394 buffer_add_int (buf, arr->bounds [i].lower_bound);
8398 case CMD_ARRAY_REF_GET_VALUES:
8399 index = decode_int (p, &p, end);
8400 len = decode_int (p, &p, end);
8402 g_assert (index >= 0 && len >= 0);
8403 // Reordered to avoid integer overflow
8404 g_assert (!(index > arr->max_length - len));
8406 esize = mono_array_element_size (arr->obj.vtable->klass);
8407 for (i = index; i < index + len; ++i) {
8408 elem = (gpointer*)((char*)arr->vector + (i * esize));
8409 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
8412 case CMD_ARRAY_REF_SET_VALUES:
8413 index = decode_int (p, &p, end);
8414 len = decode_int (p, &p, end);
8416 g_assert (index >= 0 && len >= 0);
8417 // Reordered to avoid integer overflow
8418 g_assert (!(index > arr->max_length - len));
8420 esize = mono_array_element_size (arr->obj.vtable->klass);
8421 for (i = index; i < index + len; ++i) {
8422 elem = (gpointer*)((char*)arr->vector + (i * esize));
8424 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
8428 return ERR_NOT_IMPLEMENTED;
8435 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8440 int i, index, length;
8443 objid = decode_objid (p, &p, end);
8444 err = get_object (objid, (MonoObject**)&str);
8449 case CMD_STRING_REF_GET_VALUE:
8450 s = mono_string_to_utf8 (str);
8451 buffer_add_string (buf, s);
8454 case CMD_STRING_REF_GET_LENGTH:
8455 buffer_add_long (buf, mono_string_length (str));
8457 case CMD_STRING_REF_GET_CHARS:
8458 index = decode_long (p, &p, end);
8459 length = decode_long (p, &p, end);
8460 if (index > mono_string_length (str) - length)
8461 return ERR_INVALID_ARGUMENT;
8462 c = mono_string_chars (str) + index;
8463 for (i = 0; i < length; ++i)
8464 buffer_add_short (buf, c [i]);
8467 return ERR_NOT_IMPLEMENTED;
8474 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8483 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
8484 objid = decode_objid (p, &p, end);
8485 err = get_object (objid, &obj);
8487 buffer_add_int (buf, 1);
8489 buffer_add_int (buf, 0);
8493 objid = decode_objid (p, &p, end);
8494 err = get_object (objid, &obj);
8499 case CMD_OBJECT_REF_GET_TYPE:
8500 /* This handles transparent proxies too */
8501 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8503 case CMD_OBJECT_REF_GET_VALUES:
8504 len = decode_int (p, &p, end);
8506 for (i = 0; i < len; ++i) {
8507 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
8511 /* Check that the field belongs to the object */
8513 for (k = obj->vtable->klass; k; k = k->parent) {
8514 if (k == f->parent) {
8520 return ERR_INVALID_FIELDID;
8522 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8526 if (mono_class_field_is_special_static (f))
8527 return ERR_INVALID_FIELDID;
8529 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8530 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8531 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8532 mono_field_static_get_value (vtable, f, val);
8533 buffer_add_value (buf, f->type, val, obj->vtable->domain);
8536 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
8540 case CMD_OBJECT_REF_SET_VALUES:
8541 len = decode_int (p, &p, end);
8543 for (i = 0; i < len; ++i) {
8544 f = decode_fieldid (p, &p, end, NULL, &err);
8548 /* Check that the field belongs to the object */
8550 for (k = obj->vtable->klass; k; k = k->parent) {
8551 if (k == f->parent) {
8557 return ERR_INVALID_FIELDID;
8559 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8563 if (mono_class_field_is_special_static (f))
8564 return ERR_INVALID_FIELDID;
8566 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8567 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8569 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8570 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
8575 mono_field_static_set_value (vtable, f, val);
8578 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
8584 case CMD_OBJECT_REF_GET_ADDRESS:
8585 buffer_add_long (buf, (gssize)obj);
8587 case CMD_OBJECT_REF_GET_DOMAIN:
8588 buffer_add_domainid (buf, obj->vtable->domain);
8590 case CMD_OBJECT_REF_GET_INFO:
8591 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8592 buffer_add_domainid (buf, obj->vtable->domain);
8595 return ERR_NOT_IMPLEMENTED;
8602 command_set_to_string (CommandSet command_set)
8604 switch (command_set) {
8607 case CMD_SET_OBJECT_REF:
8608 return "OBJECT_REF";
8609 case CMD_SET_STRING_REF:
8610 return "STRING_REF";
8611 case CMD_SET_THREAD:
8613 case CMD_SET_ARRAY_REF:
8615 case CMD_SET_EVENT_REQUEST:
8616 return "EVENT_REQUEST";
8617 case CMD_SET_STACK_FRAME:
8618 return "STACK_FRAME";
8619 case CMD_SET_APPDOMAIN:
8621 case CMD_SET_ASSEMBLY:
8623 case CMD_SET_METHOD:
8627 case CMD_SET_MODULE:
8637 cmd_to_string (CommandSet set, int command)
8642 case CMD_VM_VERSION:
8644 case CMD_VM_ALL_THREADS:
8645 return "ALL_THREADS";
8646 case CMD_VM_SUSPEND:
8652 case CMD_VM_DISPOSE:
8654 case CMD_VM_INVOKE_METHOD:
8655 return "INVOKE_METHOD";
8656 case CMD_VM_SET_PROTOCOL_VERSION:
8657 return "SET_PROTOCOL_VERSION";
8658 case CMD_VM_ABORT_INVOKE:
8659 return "ABORT_INVOKE";
8660 case CMD_VM_SET_KEEPALIVE:
8661 return "SET_KEEPALIVE";
8674 wait_for_attach (void)
8676 #ifndef DISABLE_SOCKET_TRANSPORT
8677 if (listen_fd == -1) {
8678 DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
8682 /* Block and wait for client connection */
8683 conn_fd = socket_transport_accept (listen_fd);
8684 DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
8685 if (conn_fd == -1) {
8686 DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
8690 g_assert_not_reached ();
8694 disconnected = !transport_handshake ();
8696 DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
8706 * This thread handles communication with the debugger client using a JDWP
8709 static guint32 WINAPI
8710 debugger_thread (void *arg)
8712 int res, len, id, flags, command_set = 0, command = 0;
8713 guint8 header [HEADER_LENGTH];
8714 guint8 *data, *p, *end;
8718 gboolean attach_failed = FALSE;
8720 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
8722 debugger_thread_id = GetCurrentThreadId ();
8724 mono_jit_thread_attach (mono_get_root_domain ());
8726 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
8728 mono_set_is_debugger_attached (TRUE);
8730 if (agent_config.defer) {
8731 if (!wait_for_attach ()) {
8732 DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
8733 attach_failed = TRUE; // Don't abort process when we can't listen
8735 /* Send start event to client */
8736 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
8740 while (!attach_failed) {
8741 res = transport_recv (header, HEADER_LENGTH);
8743 /* This will break if the socket is closed during shutdown too */
8744 if (res != HEADER_LENGTH) {
8745 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH));
8750 end = header + HEADER_LENGTH;
8752 len = decode_int (p, &p, end);
8753 id = decode_int (p, &p, end);
8754 flags = decode_byte (p, &p, end);
8755 command_set = decode_byte (p, &p, end);
8756 command = decode_byte (p, &p, end);
8758 g_assert (flags == 0);
8761 const char *cmd_str;
8764 cmd_str = cmd_to_string (command_set, command);
8766 sprintf (cmd_num, "%d", command);
8770 DEBUG (1, fprintf (log_file, "[dbg] Received command %s(%s), id=%d.\n", command_set_to_string (command_set), cmd_str, id));
8773 data = g_malloc (len - HEADER_LENGTH);
8774 if (len - HEADER_LENGTH > 0)
8776 res = transport_recv (data, len - HEADER_LENGTH);
8777 if (res != len - HEADER_LENGTH) {
8778 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH));
8784 end = data + (len - HEADER_LENGTH);
8786 buffer_init (&buf, 128);
8791 /* Process the request */
8792 switch (command_set) {
8794 err = vm_commands (command, id, p, end, &buf);
8795 if (!err && command == CMD_VM_INVOKE_METHOD)
8796 /* Sent after the invoke is complete */
8799 case CMD_SET_EVENT_REQUEST:
8800 err = event_commands (command, p, end, &buf);
8802 case CMD_SET_APPDOMAIN:
8803 err = domain_commands (command, p, end, &buf);
8805 case CMD_SET_ASSEMBLY:
8806 err = assembly_commands (command, p, end, &buf);
8808 case CMD_SET_MODULE:
8809 err = module_commands (command, p, end, &buf);
8812 err = type_commands (command, p, end, &buf);
8814 case CMD_SET_METHOD:
8815 err = method_commands (command, p, end, &buf);
8817 case CMD_SET_THREAD:
8818 err = thread_commands (command, p, end, &buf);
8820 case CMD_SET_STACK_FRAME:
8821 err = frame_commands (command, p, end, &buf);
8823 case CMD_SET_ARRAY_REF:
8824 err = array_commands (command, p, end, &buf);
8826 case CMD_SET_STRING_REF:
8827 err = string_commands (command, p, end, &buf);
8829 case CMD_SET_OBJECT_REF:
8830 err = object_commands (command, p, end, &buf);
8833 err = ERR_NOT_IMPLEMENTED;
8837 send_reply_packet (id, err, &buf);
8842 if (command_set == CMD_SET_VM && command == CMD_VM_DISPOSE)
8846 mono_set_is_debugger_attached (FALSE);
8848 mono_mutex_lock (&debugger_thread_exited_mutex);
8849 debugger_thread_exited = TRUE;
8850 mono_cond_signal (&debugger_thread_exited_cond);
8851 mono_mutex_unlock (&debugger_thread_exited_mutex);
8853 DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
8855 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
8856 DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
8857 start_debugger_thread ();
8863 #else /* DISABLE_DEBUGGER_AGENT */
8866 mono_debugger_agent_parse_options (char *options)
8868 g_error ("This runtime is configured with the debugger agent disabled.");
8872 mono_debugger_agent_init (void)
8877 mono_debugger_agent_breakpoint_hit (void *sigctx)
8882 mono_debugger_agent_single_step_event (void *sigctx)
8887 mono_debugger_agent_free_domain_info (MonoDomain *domain)
8892 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
8898 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
8899 MonoContext *catch_ctx)
8904 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
8909 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
8914 mono_debugger_agent_user_break (void)
8920 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
8925 mono_debugger_agent_debug_log_is_enabled (void)