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 ();
4077 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4078 mono_arch_set_breakpoint (ji, inst->ip);
4084 DEBUG(1, fprintf (log_file, "[dbg] Inserted breakpoint at %s:0x%x.\n", mono_method_full_name (ji->method, TRUE), (int)sp->il_offset));
4088 remove_breakpoint (BreakpointInstance *inst)
4090 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4092 MonoJitInfo *ji = inst->ji;
4093 guint8 *ip = inst->ip;
4095 mono_loader_lock ();
4096 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4097 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4098 mono_loader_unlock ();
4100 g_assert (count > 0);
4103 mono_arch_clear_breakpoint (ji, ip);
4110 static inline gboolean
4111 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4117 if (method == bp->method)
4119 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4122 if (bp->method->is_inflated && method->is_inflated) {
4123 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4124 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4126 /* Open generic methods should match closed generic methods of the same class */
4127 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4128 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4129 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4131 /* FIXME: Handle !mvar */
4132 if (t1->type != MONO_TYPE_MVAR)
4143 * add_pending_breakpoints:
4145 * Insert pending breakpoints into the newly JITted method METHOD.
4148 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4151 MonoSeqPointInfo *seq_points;
4157 domain = mono_domain_get ();
4159 mono_loader_lock ();
4161 for (i = 0; i < breakpoints->len; ++i) {
4162 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4163 gboolean found = FALSE;
4165 if (!bp_matches_method (bp, method))
4168 for (j = 0; j < bp->children->len; ++j) {
4169 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4176 mono_domain_lock (domain);
4177 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
4178 if (!seq_points && ji->method->is_inflated)
4179 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (ji->method));
4180 mono_domain_unlock (domain);
4182 /* Could be AOT code */
4184 g_assert (seq_points);
4186 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4190 mono_loader_unlock ();
4194 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4200 mono_error_init (error);
4202 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4204 /* Might be AOTed code */
4205 code = mono_aot_get_method (domain, method);
4207 ji = mono_jit_info_table_find (domain, code);
4212 insert_breakpoint (seq_points, domain, ji, bp, error);
4216 clear_breakpoint (MonoBreakpoint *bp);
4221 * Set a breakpoint at IL_OFFSET in METHOD.
4222 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4223 * METHOD can also be a generic method definition, in which case a breakpoint
4224 * is placed in all instances of the method.
4225 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4228 static MonoBreakpoint*
4229 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4232 GHashTableIter iter, iter2;
4235 MonoSeqPointInfo *seq_points;
4238 mono_error_init (error);
4241 // - suspend/resume the vm to prevent code patching problems
4242 // - multiple breakpoints on the same location
4243 // - dynamic methods
4246 bp = g_new0 (MonoBreakpoint, 1);
4247 bp->method = method;
4248 bp->il_offset = il_offset;
4250 bp->children = g_ptr_array_new ();
4252 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));
4254 mono_loader_lock ();
4256 g_hash_table_iter_init (&iter, domains);
4257 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4258 mono_domain_lock (domain);
4260 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4261 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4262 if (bp_matches_method (bp, m))
4263 set_bp_in_method (domain, m, seq_points, bp, error);
4266 mono_domain_unlock (domain);
4269 mono_loader_unlock ();
4271 mono_loader_lock ();
4272 g_ptr_array_add (breakpoints, bp);
4273 mono_loader_unlock ();
4275 if (error && !mono_error_ok (error)) {
4276 clear_breakpoint (bp);
4284 clear_breakpoint (MonoBreakpoint *bp)
4288 // FIXME: locking, races
4289 for (i = 0; i < bp->children->len; ++i) {
4290 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4292 remove_breakpoint (inst);
4297 mono_loader_lock ();
4298 g_ptr_array_remove (breakpoints, bp);
4299 mono_loader_unlock ();
4301 g_ptr_array_free (bp->children, TRUE);
4306 breakpoints_cleanup (void)
4310 mono_loader_lock ();
4312 while (i < event_requests->len) {
4313 EventRequest *req = g_ptr_array_index (event_requests, i);
4315 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4316 clear_breakpoint (req->info);
4317 g_ptr_array_remove_index_fast (event_requests, i);
4324 for (i = 0; i < breakpoints->len; ++i)
4325 g_free (g_ptr_array_index (breakpoints, i));
4327 g_ptr_array_free (breakpoints, TRUE);
4328 g_hash_table_destroy (bp_locs);
4333 mono_loader_unlock ();
4337 * clear_breakpoints_for_domain:
4339 * Clear breakpoint instances which reference DOMAIN.
4342 clear_breakpoints_for_domain (MonoDomain *domain)
4346 /* This could be called after shutdown */
4350 mono_loader_lock ();
4351 for (i = 0; i < breakpoints->len; ++i) {
4352 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4355 while (j < bp->children->len) {
4356 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4358 if (inst->domain == domain) {
4359 remove_breakpoint (inst);
4363 g_ptr_array_remove_index_fast (bp->children, j);
4369 mono_loader_unlock ();
4373 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4375 return bp->method && bp->method->klass->image->assembly == assembly;
4379 process_breakpoint_inner (DebuggerTlsData *tls)
4383 int i, j, suspend_policy;
4384 guint32 native_offset;
4386 BreakpointInstance *inst;
4387 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4388 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4389 EventKind kind = EVENT_KIND_BREAKPOINT;
4390 MonoContext *ctx = &tls->restore_ctx;
4391 MonoSeqPointInfo *info;
4394 // FIXME: Speed this up
4396 ip = MONO_CONTEXT_GET_IP (ctx);
4397 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4399 g_assert (ji->method);
4401 /* Compute the native offset of the breakpoint from the ip */
4402 native_offset = ip - (guint8*)ji->code_start;
4405 * Skip the instruction causing the breakpoint signal.
4407 mono_arch_skip_breakpoint (ctx, ji);
4409 if (ji->method->wrapper_type || tls->disable_breakpoints)
4412 bp_reqs = g_ptr_array_new ();
4413 ss_reqs = g_ptr_array_new ();
4414 ss_reqs_orig = g_ptr_array_new ();
4416 mono_loader_lock ();
4419 * The ip points to the instruction causing the breakpoint event, which is after
4420 * the offset recorded in the seq point map, so find the prev seq point before ip.
4422 sp = find_prev_seq_point_for_native_offset (mono_domain_get (), ji->method, native_offset, &info);
4424 no_seq_points_found (ji->method);
4427 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));
4430 for (i = 0; i < breakpoints->len; ++i) {
4431 bp = g_ptr_array_index (breakpoints, i);
4436 for (j = 0; j < bp->children->len; ++j) {
4437 inst = g_ptr_array_index (bp->children, j);
4438 if (inst->ji == ji && inst->sp == sp) {
4439 if (bp->req->event_kind == EVENT_KIND_STEP) {
4440 g_ptr_array_add (ss_reqs_orig, bp->req);
4442 g_ptr_array_add (bp_reqs, bp->req);
4447 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4448 /* Maybe a method entry/exit event */
4449 if (sp->il_offset == METHOD_ENTRY_IL_OFFSET)
4450 kind = EVENT_KIND_METHOD_ENTRY;
4451 else if (sp->il_offset == METHOD_EXIT_IL_OFFSET)
4452 kind = EVENT_KIND_METHOD_EXIT;
4455 /* Process single step requests */
4456 for (i = 0; i < ss_reqs_orig->len; ++i) {
4457 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4458 SingleStepReq *ss_req = req->info;
4459 gboolean hit = TRUE;
4461 if (ss_req->size == STEP_SIZE_LINE) {
4462 /* Have to check whenever a different source line was reached */
4463 MonoDebugMethodInfo *minfo;
4464 MonoDebugSourceLocation *loc = NULL;
4466 minfo = mono_debug_lookup_method (ji->method);
4469 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4471 if (!loc || (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line)) {
4472 /* Have to continue single stepping */
4473 DEBUG(1, fprintf (log_file, "[%p] Same source line, continuing single stepping.\n", (gpointer)GetCurrentThreadId ()));
4478 ss_req->last_method = ji->method;
4479 ss_req->last_line = loc->row;
4480 mono_debug_free_source_location (loc);
4485 g_ptr_array_add (ss_reqs, req);
4487 /* Start single stepping again from the current sequence point */
4488 ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4491 if (ss_reqs->len > 0)
4492 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4493 if (bp_reqs->len > 0)
4494 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4495 if (kind != EVENT_KIND_BREAKPOINT)
4496 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4498 mono_loader_unlock ();
4500 g_ptr_array_free (bp_reqs, TRUE);
4501 g_ptr_array_free (ss_reqs, TRUE);
4504 * FIXME: The first event will suspend, so the second will only be sent after the
4508 process_event (EVENT_KIND_STEP, ji->method, 0, ctx, ss_events, suspend_policy);
4510 process_event (kind, ji->method, 0, ctx, bp_events, suspend_policy);
4511 if (enter_leave_events)
4512 process_event (kind, ji->method, 0, ctx, enter_leave_events, suspend_policy);
4515 /* Process a breakpoint/single step event after resuming from a signal handler */
4517 process_signal_event (void (*func) (DebuggerTlsData*))
4519 DebuggerTlsData *tls;
4520 MonoContext orig_restore_ctx, ctx;
4521 static void (*restore_context) (void *);
4523 if (!restore_context)
4524 restore_context = mono_get_restore_context ();
4526 tls = mono_native_tls_get_value (debugger_tls_id);
4527 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4528 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4529 memcpy (&tls->restore_ctx, &tls->handler_ctx, sizeof (MonoContext));
4533 /* This is called when resuming from a signal handler, so it shouldn't return */
4534 memcpy (&ctx, &tls->restore_ctx, sizeof (MonoContext));
4535 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4536 restore_context (&ctx);
4537 g_assert_not_reached ();
4541 process_breakpoint (void)
4543 process_signal_event (process_breakpoint_inner);
4547 resume_from_signal_handler (void *sigctx, void *func)
4549 DebuggerTlsData *tls;
4552 /* Save the original context in TLS */
4553 // FIXME: This might not work on an altstack ?
4554 tls = mono_native_tls_get_value (debugger_tls_id);
4556 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer)GetCurrentThreadId ());
4559 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4560 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4561 // clob:c could be added to op_seq_point.
4563 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4564 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4565 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4566 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4568 MONO_CONTEXT_SET_IP (&ctx, func);
4570 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4572 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4573 mono_ppc_set_func_into_sigctx (sigctx, func);
4578 mono_debugger_agent_breakpoint_hit (void *sigctx)
4581 * We are called from a signal handler, and running code there causes all kinds of
4582 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4583 * So set up the signal context to return to the real breakpoint handler function.
4585 resume_from_signal_handler (sigctx, process_breakpoint);
4589 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4591 if (frame->managed) {
4592 *(MonoContext*)data = *ctx;
4601 * Called by System.Diagnostics.Debugger:Break ().
4604 mono_debugger_agent_user_break (void)
4606 if (agent_config.enabled) {
4611 /* Obtain a context */
4612 MONO_CONTEXT_SET_IP (&ctx, NULL);
4613 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4614 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4616 mono_loader_lock ();
4617 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4618 mono_loader_unlock ();
4620 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4627 ss_depth_to_string (StepDepth depth)
4630 case STEP_DEPTH_OVER:
4632 case STEP_DEPTH_OUT:
4634 case STEP_DEPTH_INTO:
4637 g_assert_not_reached ();
4643 process_single_step_inner (DebuggerTlsData *tls)
4648 int il_offset, suspend_policy;
4651 MonoContext *ctx = &tls->restore_ctx;
4653 MonoSeqPointInfo *info;
4655 ip = MONO_CONTEXT_GET_IP (ctx);
4657 /* Skip the instruction causing the single step */
4658 mono_arch_skip_single_step (ctx);
4660 if (suspend_count > 0) {
4661 process_suspend (tls, ctx);
4666 // FIXME: A suspend race
4669 if (mono_thread_internal_current () != ss_req->thread)
4672 if (log_level > 0) {
4673 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4675 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));
4678 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4680 g_assert (ji->method);
4682 if (ji->method->wrapper_type && ji->method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4687 * Stopping in memset makes half-initialized vtypes visible.
4688 * Stopping in memcpy makes half-copied vtypes visible.
4690 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
4694 * The ip points to the instruction causing the single step event, which is before
4695 * the offset recorded in the seq point map, so find the next seq point after ip.
4697 sp = find_next_seq_point_for_native_offset (domain, ji->method, (guint8*)ip - (guint8*)ji->code_start, &info);
4700 il_offset = sp->il_offset;
4702 // FIXME: No tests fail if this is disabled
4704 if (ss_req->size == STEP_SIZE_LINE) {
4708 /* Step until a different source line is reached */
4709 MonoDebugMethodInfo *minfo;
4711 minfo = mono_debug_lookup_method (ji->method);
4714 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4716 if (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line) {
4717 mono_debug_free_source_location (loc);
4722 * Step until we reach a location with line number info,
4723 * otherwise the client can't show a location.
4724 * This can happen for example with statics initialized inline
4725 * outside of a cctor.
4730 ss_req->last_method = ji->method;
4731 ss_req->last_line = loc->row;
4732 mono_debug_free_source_location (loc);
4738 /* Start single stepping again from the current sequence point */
4739 ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4741 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
4742 (ji->method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4743 !strcmp (ji->method->name, ".cctor"))
4746 // FIXME: Has to lock earlier
4748 reqs = g_ptr_array_new ();
4750 mono_loader_lock ();
4752 g_ptr_array_add (reqs, ss_req->req);
4754 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4756 g_ptr_array_free (reqs, TRUE);
4758 mono_loader_unlock ();
4760 process_event (EVENT_KIND_STEP, ji->method, il_offset, ctx, events, suspend_policy);
4764 process_single_step (void)
4766 process_signal_event (process_single_step_inner);
4770 * mono_debugger_agent_single_step_event:
4772 * Called from a signal handler to handle a single step event.
4775 mono_debugger_agent_single_step_event (void *sigctx)
4777 /* Resume to process_single_step through the signal context */
4779 // FIXME: Since step out/over is implemented using step in, the step in case should
4780 // be as fast as possible. Move the relevant code from process_single_step_inner ()
4783 if (GetCurrentThreadId () == debugger_thread_id) {
4785 * This could happen despite our best effors when the runtime calls
4786 * assembly/type resolve hooks.
4787 * FIXME: Breakpoints too.
4791 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4792 mono_arch_skip_single_step (&ctx);
4793 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4797 resume_from_signal_handler (sigctx, process_single_step);
4801 debugger_agent_single_step_from_context (MonoContext *ctx)
4803 DebuggerTlsData *tls;
4804 MonoContext orig_restore_ctx;
4806 tls = mono_native_tls_get_value (debugger_tls_id);
4809 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4810 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4811 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4813 process_single_step_inner (tls);
4815 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4816 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4820 debugger_agent_breakpoint_from_context (MonoContext *ctx)
4822 DebuggerTlsData *tls;
4823 MonoContext orig_restore_ctx;
4825 tls = mono_native_tls_get_value (debugger_tls_id);
4827 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4828 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4830 process_breakpoint_inner (tls);
4832 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4833 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4837 * start_single_stepping:
4839 * Turn on single stepping. Can be called multiple times, for example,
4840 * by a single step event request + a suspend.
4843 start_single_stepping (void)
4845 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4846 int val = InterlockedIncrement (&ss_count);
4849 mono_arch_start_single_stepping ();
4851 if (ss_req != NULL && ss_invoke_addr == NULL) {
4852 DebuggerTlsData *tls;
4854 mono_loader_lock ();
4856 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
4857 ss_invoke_addr = tls->invoke_addr;
4859 mono_loader_unlock ();
4862 g_assert_not_reached ();
4867 stop_single_stepping (void)
4869 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4870 int val = InterlockedDecrement (&ss_count);
4873 mono_arch_stop_single_stepping ();
4875 g_assert_not_reached ();
4882 * Stop the single stepping operation given by SS_REQ.
4885 ss_stop (SingleStepReq *ss_req)
4890 for (l = ss_req->bps; l; l = l->next) {
4891 clear_breakpoint (l->data);
4893 g_slist_free (ss_req->bps);
4897 if (ss_req->global) {
4898 stop_single_stepping ();
4899 ss_req->global = FALSE;
4906 * Start the single stepping operation given by SS_REQ from the sequence point SP.
4907 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
4908 * belong to the same thread as CTX.
4911 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
4913 int i, j, frame_index;
4916 gboolean enable_global = FALSE;
4918 /* Stop the previous operation */
4922 * Implement single stepping using breakpoints if possible.
4924 if (step_to_catch) {
4925 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
4926 ss_req->bps = g_slist_append (ss_req->bps, bp);
4930 if ((!sp || sp->next_len == 0 || ss_req->depth == STEP_DEPTH_OUT || ss_req->depth == STEP_DEPTH_OVER) && ctx) {
4931 /* Need parent frames */
4932 if (!tls->context.valid)
4933 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4934 compute_frame_info (tls->thread, tls);
4938 * Find the first sequence point in the current or in a previous frame which
4939 * is not the last in its method.
4941 if (ss_req->depth == STEP_DEPTH_OUT) {
4942 /* Ignore seq points in current method */
4943 while (frame_index < tls->frame_count) {
4944 StackFrame *frame = tls->frames [frame_index];
4946 method = frame->method;
4947 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4949 if (sp && sp->next_len != 0)
4952 // There could be method calls before the next seq point in the caller when using nested calls
4953 //enable_global = TRUE;
4955 if (sp && sp->next_len == 0) {
4957 while (frame_index < tls->frame_count) {
4958 StackFrame *frame = tls->frames [frame_index];
4960 method = frame->method;
4961 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4962 if (sp && sp->next_len != 0)
4970 if (sp && sp->next_len > 0) {
4971 for (i = 0; i < sp->next_len; ++i) {
4972 next_sp = &info->seq_points [sp->next [i]];
4974 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
4975 ss_req->bps = g_slist_append (ss_req->bps, bp);
4979 if (ss_req->depth == STEP_DEPTH_OVER) {
4980 /* Need to stop in catch clauses as well */
4981 for (i = 0; i < tls->frame_count; ++i) {
4982 StackFrame *frame = tls->frames [i];
4985 MonoJitInfo *jinfo = frame->ji;
4986 for (j = 0; j < jinfo->num_clauses; ++j) {
4987 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
4989 sp = find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL);
4991 bp = set_breakpoint (frame->method, sp->il_offset, ss_req->req, NULL);
4992 ss_req->bps = g_slist_append (ss_req->bps, bp);
5000 if (ss_req->depth == STEP_DEPTH_INTO) {
5001 /* Enable global stepping so we stop at method entry too */
5002 enable_global = TRUE;
5006 * The ctx/frame info computed above will become invalid when we continue.
5008 tls->context.valid = FALSE;
5009 tls->async_state.valid = FALSE;
5010 invalidate_frames (tls);
5013 if (enable_global) {
5014 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
5015 ss_req->global = TRUE;
5016 start_single_stepping ();
5017 } else if (!ss_req->bps) {
5018 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
5019 ss_req->global = TRUE;
5020 start_single_stepping ();
5022 ss_req->global = FALSE;
5027 * Start single stepping of thread THREAD
5030 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
5032 DebuggerTlsData *tls;
5033 MonoSeqPointInfo *info = NULL;
5034 SeqPoint *sp = NULL;
5035 MonoMethod *method = NULL;
5036 MonoDebugMethodInfo *minfo;
5037 gboolean step_to_catch = FALSE;
5039 if (suspend_count == 0)
5040 return ERR_NOT_SUSPENDED;
5042 wait_for_suspend ();
5044 // FIXME: Multiple requests
5046 DEBUG (0, fprintf (log_file, "Received a single step request while the previous one was still active.\n"));
5047 return ERR_NOT_IMPLEMENTED;
5050 DEBUG (1, fprintf (log_file, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
5052 ss_req = g_new0 (SingleStepReq, 1);
5054 ss_req->thread = thread;
5055 ss_req->size = size;
5056 ss_req->depth = depth;
5059 mono_loader_lock ();
5060 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5061 mono_loader_unlock ();
5063 g_assert (tls->context.valid);
5064 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5066 if (tls->catch_state.valid) {
5068 StackFrameInfo frame;
5069 MonoContext new_ctx;
5070 MonoLMF *lmf = NULL;
5073 * We are stopped at a throw site. Stepping should go to the catch site.
5076 /* Find the the jit info for the catch context */
5077 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);
5079 g_assert (frame.type == FRAME_TYPE_MANAGED);
5082 * Find the seq point corresponding to the landing site ip, which is the first seq
5085 sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
5087 no_seq_points_found (frame.method);
5090 method = frame.method;
5092 step_to_catch = TRUE;
5093 /* This make sure the seq point is not skipped by process_single_step () */
5094 ss_req->last_sp = NULL;
5097 if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
5100 /* Compute the initial line info */
5101 compute_frame_info (thread, tls);
5103 if (tls->frame_count) {
5104 frame = tls->frames [0];
5106 ss_req->last_method = frame->method;
5107 ss_req->last_line = -1;
5109 minfo = mono_debug_lookup_method (frame->method);
5110 if (minfo && frame->il_offset != -1) {
5111 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
5114 ss_req->last_line = loc->row;
5121 if (!step_to_catch) {
5124 compute_frame_info (thread, tls);
5126 if (tls->frame_count) {
5127 frame = tls->frames [0];
5129 if (!method && frame->il_offset != -1) {
5130 /* FIXME: Sort the table and use a binary search */
5131 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5133 no_seq_points_found (frame->method);
5135 method = frame->method;
5140 ss_start (ss_req, method, sp, info, &tls->context.ctx, tls, step_to_catch);
5146 ss_destroy (SingleStepReq *req)
5149 g_assert (ss_req == req);
5158 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5161 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5167 if (!agent_config.enabled)
5170 mono_loader_lock ();
5171 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5172 mono_loader_unlock ();
5175 ei.category = category ? mono_string_to_utf8 (category) : NULL;
5176 ei.message = message ? mono_string_to_utf8 (message) : NULL;
5178 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5180 g_free (ei.category);
5181 g_free (ei.message);
5185 mono_debugger_agent_debug_log_is_enabled (void)
5187 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5188 return agent_config.enabled;
5191 #ifdef PLATFORM_ANDROID
5193 mono_debugger_agent_unhandled_exception (MonoException *exc)
5202 memset (&ei, 0, sizeof (EventInfo));
5203 ei.exc = (MonoObject*)exc;
5205 mono_loader_lock ();
5206 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5207 mono_loader_unlock ();
5209 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5214 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5215 MonoContext *catch_ctx)
5217 int i, j, suspend_policy;
5219 MonoJitInfo *ji, *catch_ji;
5221 DebuggerTlsData *tls = NULL;
5223 if (thread_to_tls != NULL) {
5224 MonoInternalThread *thread = mono_thread_internal_current ();
5226 mono_loader_lock ();
5227 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5228 mono_loader_unlock ();
5230 if (tls && tls->abort_requested)
5232 if (tls && tls->disable_breakpoints)
5236 memset (&ei, 0, sizeof (EventInfo));
5238 /* Just-In-Time debugging */
5240 if (agent_config.onuncaught && !inited) {
5241 finish_agent_init (FALSE);
5244 * Send an unsolicited EXCEPTION event with a dummy request id.
5246 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5247 ei.exc = (MonoObject*)exc;
5248 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5251 } else if (agent_config.onthrow && !inited) {
5253 gboolean found = FALSE;
5255 for (l = agent_config.onthrow; l; l = l->next) {
5256 char *ex_type = l->data;
5257 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5259 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5266 finish_agent_init (FALSE);
5269 * Send an unsolicited EXCEPTION event with a dummy request id.
5271 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5272 ei.exc = (MonoObject*)exc;
5273 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5281 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5283 catch_ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5287 ei.exc = (MonoObject*)exc;
5288 ei.caught = catch_ctx != NULL;
5290 mono_loader_lock ();
5292 /* Treat exceptions which are caught in non-user code as unhandled */
5293 for (i = 0; i < event_requests->len; ++i) {
5294 EventRequest *req = g_ptr_array_index (event_requests, i);
5295 if (req->event_kind != EVENT_KIND_EXCEPTION)
5298 for (j = 0; j < req->nmodifiers; ++j) {
5299 Modifier *mod = &req->modifiers [j];
5301 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5303 gboolean found = FALSE;
5304 MonoAssembly **assemblies = mod->data.assemblies;
5307 for (k = 0; assemblies [k]; ++k)
5308 if (assemblies [k] == catch_ji->method->klass->image->assembly)
5317 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5318 mono_loader_unlock ();
5320 if (tls && ei.caught && catch_ctx) {
5321 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5322 tls->catch_state.ctx = *catch_ctx;
5323 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5324 tls->catch_state.valid = TRUE;
5327 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5330 tls->catch_state.valid = FALSE;
5334 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5336 DebuggerTlsData *tls;
5341 tls = mono_native_tls_get_value (debugger_tls_id);
5346 * We're about to invoke an exception filter during the first pass of exception handling.
5348 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5349 * 'orig_ctx' is the context where the exception has been thrown.
5352 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5354 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5355 * the call site (line 37) and then continue to Main(), but it would never
5356 * include the throw site (line 32).
5358 * Since exception filters are invoked during the first pass of exception handling,
5359 * the stack frames of the throw site are still intact, so we should include them
5362 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5364 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5365 * but report the location of the 'throw' to the user.
5369 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5373 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5375 DebuggerTlsData *tls;
5380 tls = mono_native_tls_get_value (debugger_tls_id);
5384 tls->filter_state.valid = FALSE;
5388 * buffer_add_value_full:
5390 * Add the encoding of the value at ADDR described by T to the buffer.
5391 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5395 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5401 if (!(*(void**)addr)) {
5402 /* This can happen with compiler generated locals */
5403 //printf ("%s\n", mono_type_full_name (t));
5404 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5407 g_assert (*(void**)addr);
5408 addr = *(void**)addr;
5413 case MONO_TYPE_BOOLEAN:
5416 case MONO_TYPE_CHAR:
5436 case MONO_TYPE_VOID:
5437 buffer_add_byte (buf, t->type);
5439 case MONO_TYPE_BOOLEAN:
5442 buffer_add_byte (buf, t->type);
5443 buffer_add_int (buf, *(gint8*)addr);
5445 case MONO_TYPE_CHAR:
5448 buffer_add_byte (buf, t->type);
5449 buffer_add_int (buf, *(gint16*)addr);
5454 buffer_add_byte (buf, t->type);
5455 buffer_add_int (buf, *(gint32*)addr);
5460 buffer_add_byte (buf, t->type);
5461 buffer_add_long (buf, *(gint64*)addr);
5465 /* Treat it as a vtype */
5467 case MONO_TYPE_PTR: {
5468 gssize val = *(gssize*)addr;
5470 buffer_add_byte (buf, t->type);
5471 buffer_add_long (buf, val);
5475 case MONO_TYPE_STRING:
5476 case MONO_TYPE_SZARRAY:
5477 case MONO_TYPE_OBJECT:
5478 case MONO_TYPE_CLASS:
5479 case MONO_TYPE_ARRAY:
5480 obj = *(MonoObject**)addr;
5483 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5485 if (obj->vtable->klass->valuetype) {
5486 t = &obj->vtable->klass->byval_arg;
5487 addr = mono_object_unbox (obj);
5489 } else if (obj->vtable->klass->rank) {
5490 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5491 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5492 buffer_add_byte (buf, MONO_TYPE_CLASS);
5494 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5496 buffer_add_objid (buf, obj);
5500 case MONO_TYPE_VALUETYPE: {
5504 MonoClass *klass = mono_class_from_mono_type (t);
5506 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5507 buffer_add_byte (buf, klass->enumtype);
5508 buffer_add_typeid (buf, domain, klass);
5512 while ((f = mono_class_get_fields (klass, &iter))) {
5513 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5515 if (mono_field_is_deleted (f))
5519 buffer_add_int (buf, nfields);
5522 while ((f = mono_class_get_fields (klass, &iter))) {
5523 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5525 if (mono_field_is_deleted (f))
5527 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE);
5531 case MONO_TYPE_GENERICINST:
5532 if (mono_type_generic_inst_is_valuetype (t)) {
5544 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5546 buffer_add_value_full (buf, t, addr, domain, FALSE);
5550 obj_is_of_type (MonoObject *obj, MonoType *t)
5552 MonoClass *klass = obj->vtable->klass;
5553 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5554 if (mono_class_is_transparent_proxy (klass)) {
5555 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5556 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5566 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5569 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5573 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5574 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5575 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5576 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5577 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
5578 char *name = mono_type_full_name (t);
5579 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5581 return ERR_INVALID_ARGUMENT;
5585 case MONO_TYPE_BOOLEAN:
5586 *(guint8*)addr = decode_int (buf, &buf, limit);
5588 case MONO_TYPE_CHAR:
5589 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5592 *(gint8*)addr = decode_int (buf, &buf, limit);
5595 *(guint8*)addr = decode_int (buf, &buf, limit);
5598 *(gint16*)addr = decode_int (buf, &buf, limit);
5601 *(guint16*)addr = decode_int (buf, &buf, limit);
5604 *(gint32*)addr = decode_int (buf, &buf, limit);
5607 *(guint32*)addr = decode_int (buf, &buf, limit);
5610 *(gint64*)addr = decode_long (buf, &buf, limit);
5613 *(guint64*)addr = decode_long (buf, &buf, limit);
5616 *(guint32*)addr = decode_int (buf, &buf, limit);
5619 *(guint64*)addr = decode_long (buf, &buf, limit);
5622 /* We send these as I8, so we get them back as such */
5623 g_assert (type == MONO_TYPE_I8);
5624 *(gssize*)addr = decode_long (buf, &buf, limit);
5626 case MONO_TYPE_GENERICINST:
5627 if (MONO_TYPE_ISSTRUCT (t)) {
5628 /* The client sends these as a valuetype */
5636 /* We send these as vtypes, so we get them back as such */
5637 g_assert (type == MONO_TYPE_VALUETYPE);
5640 case MONO_TYPE_VALUETYPE: {
5641 gboolean is_enum = decode_byte (buf, &buf, limit);
5645 gpointer iter = NULL;
5648 /* Enums are sent as a normal vtype */
5650 return ERR_NOT_IMPLEMENTED;
5651 klass = decode_typeid (buf, &buf, limit, &d, &err);
5655 if (klass != mono_class_from_mono_type (t))
5656 return ERR_INVALID_ARGUMENT;
5658 nfields = decode_int (buf, &buf, limit);
5659 while ((f = mono_class_get_fields (klass, &iter))) {
5660 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5662 if (mono_field_is_deleted (f))
5664 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5669 g_assert (nfields == 0);
5674 if (MONO_TYPE_IS_REFERENCE (t)) {
5675 if (type == MONO_TYPE_OBJECT) {
5676 int objid = decode_objid (buf, &buf, limit);
5680 err = get_object (objid, (MonoObject**)&obj);
5685 if (!obj_is_of_type (obj, t)) {
5686 DEBUG (1, fprintf (log_file, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name));
5687 return ERR_INVALID_ARGUMENT;
5690 if (obj && obj->vtable->domain != domain)
5691 return ERR_INVALID_ARGUMENT;
5693 mono_gc_wbarrier_generic_store (addr, obj);
5694 } else if (type == VALUE_TYPE_ID_NULL) {
5695 *(MonoObject**)addr = NULL;
5697 return ERR_INVALID_ARGUMENT;
5711 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5714 int type = decode_byte (buf, &buf, limit);
5716 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
5717 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
5718 guint8 *nullable_buf;
5721 * First try decoding it as a Nullable`1
5723 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5728 * Then try decoding as a primitive value or null.
5730 if (targ->type == type) {
5731 nullable_buf = g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
5732 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
5734 g_free (nullable_buf);
5737 mono_nullable_init (addr, mono_value_box (domain, mono_class_from_mono_type (targ), nullable_buf), mono_class_from_mono_type (t));
5738 g_free (nullable_buf);
5741 } else if (type == VALUE_TYPE_ID_NULL) {
5742 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
5748 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5752 add_var (Buffer *buf, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
5759 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5760 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5763 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
5764 reg_val = mono_arch_context_get_int_reg (ctx, reg);
5766 buffer_add_value_full (buf, t, ®_val, domain, as_vtype);
5768 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5769 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5770 addr += (gint32)var->offset;
5772 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5774 buffer_add_value_full (buf, t, addr, domain, as_vtype);
5776 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5780 g_assert_not_reached ();
5785 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
5791 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5792 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5794 if (MONO_TYPE_IS_REFERENCE (t))
5795 size = sizeof (gpointer);
5797 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
5800 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
5801 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
5803 gboolean is_signed = FALSE;
5805 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
5810 v = is_signed ? *(gint8*)val : *(guint8*)val;
5813 v = is_signed ? *(gint16*)val : *(guint16*)val;
5816 v = is_signed ? *(gint32*)val : *(guint32*)val;
5819 v = is_signed ? *(gint64*)val : *(guint64*)val;
5822 g_assert_not_reached ();
5828 /* Set value on the stack or in the return ctx */
5829 if (reg_locations [reg]) {
5830 /* Saved on the stack */
5831 DEBUG (1, fprintf (log_file, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v));
5832 *(reg_locations [reg]) = v;
5835 DEBUG (1, fprintf (log_file, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v));
5836 mono_arch_context_set_int_reg (restore_ctx, reg, v);
5839 // FIXME: Move these to mono-context.h/c.
5840 mono_arch_context_set_int_reg (ctx, reg, v);
5842 // FIXME: Can't set registers, so we disable linears
5847 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5848 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5849 addr += (gint32)var->offset;
5851 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5854 addr = *(guint8**)addr;
5860 // FIXME: Write barriers
5861 mono_gc_memmove (addr, val, size);
5863 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5867 g_assert_not_reached ();
5872 clear_event_request (int req_id, int etype)
5876 mono_loader_lock ();
5877 for (i = 0; i < event_requests->len; ++i) {
5878 EventRequest *req = g_ptr_array_index (event_requests, i);
5880 if (req->id == req_id && req->event_kind == etype) {
5881 if (req->event_kind == EVENT_KIND_BREAKPOINT)
5882 clear_breakpoint (req->info);
5883 if (req->event_kind == EVENT_KIND_STEP)
5884 ss_destroy (req->info);
5885 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
5886 clear_breakpoint (req->info);
5887 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
5888 clear_breakpoint (req->info);
5889 g_ptr_array_remove_index_fast (event_requests, i);
5894 mono_loader_unlock ();
5898 event_req_matches_assembly (EventRequest *req, MonoAssembly *assembly)
5900 if (req->event_kind == EVENT_KIND_BREAKPOINT)
5901 return breakpoint_matches_assembly (req->info, assembly);
5905 for (i = 0; i < req->nmodifiers; ++i) {
5906 Modifier *m = &req->modifiers [i];
5908 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
5910 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
5911 for (j = 0; m->data.assemblies [j]; ++j)
5912 if (m->data.assemblies [j] == assembly)
5922 * clear_event_requests_for_assembly:
5924 * Clear all events requests which reference ASSEMBLY.
5927 clear_event_requests_for_assembly (MonoAssembly *assembly)
5932 mono_loader_lock ();
5936 for (i = 0; i < event_requests->len; ++i) {
5937 EventRequest *req = g_ptr_array_index (event_requests, i);
5939 if (event_req_matches_assembly (req, assembly)) {
5940 clear_event_request (req->id, req->event_kind);
5946 mono_loader_unlock ();
5950 * type_comes_from_assembly:
5952 * GHRFunc that returns TRUE if klass comes from assembly
5955 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
5957 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
5961 * clear_types_for_assembly:
5963 * Clears types from loaded_classes for a given assembly
5966 clear_types_for_assembly (MonoAssembly *assembly)
5968 MonoDomain *domain = mono_domain_get ();
5969 AgentDomainInfo *info = NULL;
5971 mono_loader_lock ();
5972 info = get_agent_domain_info (domain);
5973 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
5974 mono_loader_unlock ();
5978 add_thread (gpointer key, gpointer value, gpointer user_data)
5980 MonoInternalThread *thread = value;
5981 Buffer *buf = user_data;
5983 buffer_add_objid (buf, (MonoObject*)thread);
5987 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
5989 guint8 *end = invoke->endp;
5992 MonoMethodSignature *sig;
5995 MonoObject *this, *res, *exc;
5998 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6001 MonoStopwatch watch;
6003 if (invoke->method) {
6005 * Invoke this method directly, currently only Environment.Exit () is supported.
6008 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>"));
6009 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
6010 g_assert_not_reached ();
6013 m = decode_methodid (p, &p, end, &domain, &err);
6016 sig = mono_method_signature (m);
6018 if (m->klass->valuetype)
6019 this_buf = g_alloca (mono_class_instance_size (m->klass));
6021 this_buf = g_alloca (sizeof (MonoObject*));
6022 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6023 /* Should be null */
6024 int type = decode_byte (p, &p, end);
6025 if (type != VALUE_TYPE_ID_NULL)
6026 return ERR_INVALID_ARGUMENT;
6027 memset (this_buf, 0, mono_class_instance_size (m->klass));
6029 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6034 if (!m->klass->valuetype)
6035 this = *(MonoObject**)this_buf;
6039 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>"));
6041 if (this && this->vtable->domain != domain)
6044 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
6045 if (!strcmp (m->name, ".ctor")) {
6046 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
6047 return ERR_INVALID_ARGUMENT;
6049 this = mono_object_new (domain, m->klass);
6051 return ERR_INVALID_ARGUMENT;
6055 if (this && !obj_is_of_type (this, &m->klass->byval_arg))
6056 return ERR_INVALID_ARGUMENT;
6058 nargs = decode_int (p, &p, end);
6059 if (nargs != sig->param_count)
6060 return ERR_INVALID_ARGUMENT;
6061 /* Use alloca to get gc tracking */
6062 arg_buf = g_alloca (nargs * sizeof (gpointer));
6063 memset (arg_buf, 0, nargs * sizeof (gpointer));
6064 args = g_alloca (nargs * sizeof (gpointer));
6065 for (i = 0; i < nargs; ++i) {
6066 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6067 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6071 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6074 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6075 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6078 args [i] = arg_buf [i];
6085 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6086 tls->disable_breakpoints = TRUE;
6088 tls->disable_breakpoints = FALSE;
6091 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6093 /* FIXME: Move this to arch specific code */
6094 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6095 if (invoke->has_ctx) {
6098 lmf_addr = mono_get_lmf_addr ();
6101 memset (&ext, 0, sizeof (ext));
6103 ext.lmf.previous_lmf = *(lmf_addr);
6104 /* Mark that this is a MonoLMFExt */
6105 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6106 ext.lmf.rsp = (gssize)&ext;
6107 #elif defined(TARGET_X86)
6108 ext.lmf.previous_lmf = (gsize)*(lmf_addr);
6109 /* Mark that this is a MonoLMFExt */
6110 ext.lmf.previous_lmf = (gsize)(gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6111 ext.lmf.ebp = (gssize)&ext;
6112 #elif defined(TARGET_ARM)
6113 ext.lmf.previous_lmf = *(lmf_addr);
6114 /* Mark that this is a MonoLMFExt */
6115 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6116 ext.lmf.sp = (gssize)&ext;
6117 #elif defined(TARGET_POWERPC)
6118 ext.lmf.previous_lmf = *(lmf_addr);
6119 /* Mark that this is a MonoLMFExt */
6120 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6121 ext.lmf.ebp = (gssize)&ext;
6122 #elif defined(TARGET_S390X)
6123 ext.lmf.previous_lmf = *(lmf_addr);
6124 /* Mark that this is a MonoLMFExt */
6125 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6126 ext.lmf.ebp = (gssize)&ext;
6127 #elif defined(TARGET_MIPS)
6128 ext.lmf.previous_lmf = *(lmf_addr);
6129 /* Mark that this is a MonoLMFExt */
6130 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6131 ext.lmf.iregs [mips_sp] = (gssize)&ext;
6133 g_assert_not_reached ();
6136 ext.debugger_invoke = TRUE;
6137 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6139 mono_set_lmf ((MonoLMF*)&ext);
6143 mono_stopwatch_start (&watch);
6144 if (m->klass->valuetype)
6145 res = mono_runtime_invoke (m, this_buf, args, &exc);
6147 res = mono_runtime_invoke (m, this, args, &exc);
6148 mono_stopwatch_stop (&watch);
6149 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)));
6151 buffer_add_byte (buf, 0);
6152 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6154 buffer_add_byte (buf, 1);
6155 if (sig->ret->type == MONO_TYPE_VOID) {
6156 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
6157 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
6160 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6161 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6162 buffer_add_value (buf, sig->ret, &res, domain);
6163 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6164 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6165 MonoClass *k = mono_class_from_mono_type (sig->ret);
6166 guint8 *nullable_buf = g_alloca (mono_class_value_size (k, NULL));
6168 g_assert (nullable_buf);
6169 mono_nullable_init (nullable_buf, res, k);
6170 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6173 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6180 tls->disable_breakpoints = FALSE;
6182 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6183 if (invoke->has_ctx)
6184 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
6188 // FIXME: byref arguments
6196 * Invoke the method given by tls->pending_invoke in the current thread.
6199 invoke_method (void)
6201 DebuggerTlsData *tls;
6206 static void (*restore_context) (void *);
6207 MonoContext restore_ctx;
6210 if (!restore_context)
6211 restore_context = mono_get_restore_context ();
6213 tls = mono_native_tls_get_value (debugger_tls_id);
6217 * Store the `InvokeData *' in `tls->invoke' until we're done with
6218 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6221 mono_loader_lock ();
6223 invoke = tls->pending_invoke;
6225 tls->pending_invoke = NULL;
6227 invoke->last_invoke = tls->invoke;
6228 tls->invoke = invoke;
6230 mono_loader_unlock ();
6232 tls->frames_up_to_date = FALSE;
6238 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6239 buffer_init (&buf, 128);
6242 /* Fail the other invokes as well */
6244 err = do_invoke_method (tls, &buf, invoke, p, &p);
6247 /* Start suspending before sending the reply */
6248 if (mindex == invoke->nmethods - 1) {
6249 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6250 for (i = 0; i < invoke->suspend_count; ++i)
6255 send_reply_packet (id, err, &buf);
6260 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6262 if (invoke->has_ctx)
6263 save_thread_context (&restore_ctx);
6265 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6266 g_assert (tls->resume_count);
6267 tls->resume_count -= invoke->suspend_count;
6270 DEBUG (1, fprintf (log_file, "[%p] Invoke finished, resume_count = %d.\n", (gpointer)GetCurrentThreadId (), tls->resume_count));
6273 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6275 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
6276 * after the mono_runtime_invoke() already returned, but it doesn't matter
6277 * because we reset the abort here.
6280 mono_loader_lock ();
6282 if (tls->abort_requested)
6283 mono_thread_internal_reset_abort (tls->thread);
6285 tls->invoke = tls->invoke->last_invoke;
6286 tls->abort_requested = FALSE;
6288 mono_loader_unlock ();
6297 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6299 MonoThread *thread = value;
6300 DebuggerTlsData *tls;
6303 mono_loader_lock ();
6304 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6306 res = tls->really_suspended;
6307 mono_loader_unlock ();
6313 get_source_files_for_type (MonoClass *klass)
6315 gpointer iter = NULL;
6317 MonoDebugSourceInfo *sinfo;
6321 files = g_ptr_array_new ();
6323 while ((method = mono_class_get_methods (klass, &iter))) {
6324 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6325 GPtrArray *source_file_list;
6328 mono_debug_symfile_get_line_numbers_full (minfo, NULL, &source_file_list, NULL, NULL, NULL, NULL, NULL);
6329 for (j = 0; j < source_file_list->len; ++j) {
6330 sinfo = g_ptr_array_index (source_file_list, j);
6331 for (i = 0; i < files->len; ++i)
6332 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6334 if (i == files->len)
6335 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6337 g_ptr_array_free (source_file_list, TRUE);
6345 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6348 case CMD_VM_VERSION: {
6349 char *build_info, *version;
6351 build_info = mono_get_runtime_build_info ();
6352 version = g_strdup_printf ("mono %s", build_info);
6354 buffer_add_string (buf, version); /* vm version */
6355 buffer_add_int (buf, MAJOR_VERSION);
6356 buffer_add_int (buf, MINOR_VERSION);
6357 g_free (build_info);
6361 case CMD_VM_SET_PROTOCOL_VERSION: {
6362 major_version = decode_int (p, &p, end);
6363 minor_version = decode_int (p, &p, end);
6364 protocol_version_set = TRUE;
6365 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
6368 case CMD_VM_ALL_THREADS: {
6370 mono_loader_lock ();
6371 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6372 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6373 mono_loader_unlock ();
6376 case CMD_VM_SUSPEND:
6378 wait_for_suspend ();
6381 if (suspend_count == 0)
6382 return ERR_NOT_SUSPENDED;
6384 clear_suspended_objs ();
6386 case CMD_VM_DISPOSE:
6387 /* Clear all event requests */
6388 mono_loader_lock ();
6389 while (event_requests->len > 0) {
6390 EventRequest *req = g_ptr_array_index (event_requests, 0);
6392 clear_event_request (req->id, req->event_kind);
6394 mono_loader_unlock ();
6396 while (suspend_count > 0)
6398 disconnected = TRUE;
6399 vm_start_event_sent = FALSE;
6402 MonoInternalThread *thread;
6403 DebuggerTlsData *tls;
6404 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6405 MonoClass *env_class;
6407 MonoMethod *exit_method = NULL;
6411 exit_code = decode_int (p, &p, end);
6413 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6415 /* Have to send a reply before exiting */
6416 send_reply_packet (id, 0, buf);
6418 /* Clear all event requests */
6419 mono_loader_lock ();
6420 while (event_requests->len > 0) {
6421 EventRequest *req = g_ptr_array_index (event_requests, 0);
6423 clear_event_request (req->id, req->event_kind);
6425 mono_loader_unlock ();
6428 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6429 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6430 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6431 * better than doing the shutdown ourselves, since it avoids various races.
6435 wait_for_suspend ();
6437 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6438 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
6440 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6443 mono_loader_lock ();
6444 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6445 mono_loader_unlock ();
6447 if (thread && exit_method) {
6448 mono_loader_lock ();
6449 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6450 mono_loader_unlock ();
6452 args = g_new0 (gpointer, 1);
6453 args [0] = g_malloc (sizeof (int));
6454 *(int*)(args [0]) = exit_code;
6456 tls->pending_invoke = g_new0 (InvokeData, 1);
6457 tls->pending_invoke->method = exit_method;
6458 tls->pending_invoke->args = args;
6459 tls->pending_invoke->nmethods = 1;
6461 while (suspend_count > 0)
6465 * No thread found, do it ourselves.
6466 * FIXME: This can race with normal shutdown etc.
6468 while (suspend_count > 0)
6471 mono_runtime_shutdown ();
6473 /* Suspend all managed threads since the runtime is going away */
6474 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
6475 mono_thread_suspend_all_other_threads ();
6476 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
6477 mono_runtime_quit ();
6478 transport_close2 ();
6479 DEBUG(1, fprintf (log_file, "Exiting...\n"));
6485 case CMD_VM_INVOKE_METHOD:
6486 case CMD_VM_INVOKE_METHODS: {
6487 int objid = decode_objid (p, &p, end);
6489 DebuggerTlsData *tls;
6490 int i, count, err, flags, nmethods;
6492 err = get_object (objid, (MonoObject**)&thread);
6496 flags = decode_int (p, &p, end);
6498 if (command == CMD_VM_INVOKE_METHODS)
6499 nmethods = decode_int (p, &p, end);
6503 // Wait for suspending if it already started
6505 wait_for_suspend ();
6506 if (!is_suspended ())
6507 return ERR_NOT_SUSPENDED;
6509 mono_loader_lock ();
6510 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6511 mono_loader_unlock ();
6514 if (!tls->really_suspended)
6515 /* The thread is still running native code, can't do invokes */
6516 return ERR_NOT_SUSPENDED;
6519 * Store the invoke data into tls, the thread will execute it after it is
6522 if (tls->pending_invoke)
6523 return ERR_NOT_SUSPENDED;
6524 tls->pending_invoke = g_new0 (InvokeData, 1);
6525 tls->pending_invoke->id = id;
6526 tls->pending_invoke->flags = flags;
6527 tls->pending_invoke->p = g_malloc (end - p);
6528 memcpy (tls->pending_invoke->p, p, end - p);
6529 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
6530 tls->pending_invoke->suspend_count = suspend_count;
6531 tls->pending_invoke->nmethods = nmethods;
6533 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
6534 resume_thread (THREAD_TO_INTERNAL (thread));
6537 count = suspend_count;
6538 for (i = 0; i < count; ++i)
6543 case CMD_VM_ABORT_INVOKE: {
6544 int objid = decode_objid (p, &p, end);
6546 DebuggerTlsData *tls;
6549 err = get_object (objid, (MonoObject**)&thread);
6553 invoke_id = decode_int (p, &p, end);
6555 mono_loader_lock ();
6556 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6559 if (tls->abort_requested) {
6560 mono_loader_unlock ();
6565 * Check whether we're still inside the mono_runtime_invoke() and that it's
6566 * actually the correct invocation.
6568 * Careful, we do not stop the thread that's doing the invocation, so we can't
6569 * inspect its stack. However, invoke_method() also acquires the loader lock
6570 * when it's done, so we're safe here.
6574 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
6575 mono_loader_unlock ();
6576 return ERR_NO_INVOCATION;
6579 tls->abort_requested = TRUE;
6581 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
6582 mono_loader_unlock ();
6586 case CMD_VM_SET_KEEPALIVE: {
6587 int timeout = decode_int (p, &p, end);
6588 agent_config.keepalive = timeout;
6590 #ifndef DISABLE_SOCKET_TRANSPORT
6597 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
6598 GHashTableIter iter, kiter;
6603 char *fname, *basename;
6604 gboolean ignore_case;
6605 GSList *class_list, *l;
6606 GPtrArray *res_classes, *res_domains;
6608 fname = decode_string (p, &p, end);
6609 ignore_case = decode_byte (p, &p, end);
6611 basename = g_path_get_basename (fname);
6613 res_classes = g_ptr_array_new ();
6614 res_domains = g_ptr_array_new ();
6616 mono_loader_lock ();
6617 g_hash_table_iter_init (&iter, domains);
6618 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6619 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
6621 /* Update 'source_file_to_class' cache */
6622 g_hash_table_iter_init (&kiter, info->loaded_classes);
6623 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
6624 if (!g_hash_table_lookup (info->source_files, klass)) {
6625 files = get_source_files_for_type (klass);
6626 g_hash_table_insert (info->source_files, klass, files);
6628 for (i = 0; i < files->len; ++i) {
6629 char *s = g_ptr_array_index (files, i);
6630 char *s2 = g_path_get_basename (s);
6633 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
6635 class_list = g_slist_prepend (class_list, klass);
6636 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
6638 class_list = g_slist_prepend (class_list, klass);
6639 g_hash_table_insert (info->source_file_to_class, s2, class_list);
6642 /* The _ignorecase hash contains the lowercase path */
6643 s3 = strdup_tolower (s2);
6644 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
6646 class_list = g_slist_prepend (class_list, klass);
6647 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
6649 class_list = g_slist_prepend (class_list, klass);
6650 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
6662 s = strdup_tolower (basename);
6663 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
6666 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
6669 for (l = class_list; l; l = l->next) {
6672 g_ptr_array_add (res_classes, klass);
6673 g_ptr_array_add (res_domains, domain);
6676 mono_loader_unlock ();
6681 buffer_add_int (buf, res_classes->len);
6682 for (i = 0; i < res_classes->len; ++i)
6683 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6684 g_ptr_array_free (res_classes, TRUE);
6685 g_ptr_array_free (res_domains, TRUE);
6688 case CMD_VM_GET_TYPES: {
6689 GHashTableIter iter;
6693 gboolean ignore_case;
6694 GPtrArray *res_classes, *res_domains;
6695 MonoTypeNameParse info;
6697 name = decode_string (p, &p, end);
6698 ignore_case = decode_byte (p, &p, end);
6700 if (!mono_reflection_parse_type (name, &info)) {
6702 mono_reflection_free_type_info (&info);
6703 return ERR_INVALID_ARGUMENT;
6706 res_classes = g_ptr_array_new ();
6707 res_domains = g_ptr_array_new ();
6709 mono_loader_lock ();
6710 g_hash_table_iter_init (&iter, domains);
6711 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6713 gboolean type_resolve;
6717 mono_domain_assemblies_lock (domain);
6718 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6722 type_resolve = TRUE;
6723 t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
6725 g_ptr_array_add (res_classes, mono_type_get_class (t));
6726 g_ptr_array_add (res_domains, domain);
6730 mono_domain_assemblies_unlock (domain);
6732 mono_loader_unlock ();
6735 mono_reflection_free_type_info (&info);
6737 buffer_add_int (buf, res_classes->len);
6738 for (i = 0; i < res_classes->len; ++i)
6739 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6740 g_ptr_array_free (res_classes, TRUE);
6741 g_ptr_array_free (res_domains, TRUE);
6746 return ERR_NOT_IMPLEMENTED;
6753 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6759 case CMD_EVENT_REQUEST_SET: {
6761 int i, event_kind, suspend_policy, nmodifiers, mod;
6764 MonoThread *step_thread;
6765 int size = 0, depth = 0, filter = 0, step_thread_id = 0;
6769 event_kind = decode_byte (p, &p, end);
6770 suspend_policy = decode_byte (p, &p, end);
6771 nmodifiers = decode_byte (p, &p, end);
6773 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
6774 req->id = InterlockedIncrement (&event_request_id);
6775 req->event_kind = event_kind;
6776 req->suspend_policy = suspend_policy;
6777 req->nmodifiers = nmodifiers;
6780 for (i = 0; i < nmodifiers; ++i) {
6781 mod = decode_byte (p, &p, end);
6783 req->modifiers [i].kind = mod;
6784 if (mod == MOD_KIND_COUNT) {
6785 req->modifiers [i].data.count = decode_int (p, &p, end);
6786 } else if (mod == MOD_KIND_LOCATION_ONLY) {
6787 method = decode_methodid (p, &p, end, &domain, &err);
6790 location = decode_long (p, &p, end);
6791 } else if (mod == MOD_KIND_STEP) {
6792 step_thread_id = decode_id (p, &p, end);
6793 size = decode_int (p, &p, end);
6794 depth = decode_int (p, &p, end);
6795 if (CHECK_PROTOCOL_VERSION (2, 16))
6796 filter = decode_int (p, &p, end);
6797 req->modifiers [i].data.filter = filter;
6798 } else if (mod == MOD_KIND_THREAD_ONLY) {
6799 int id = decode_id (p, &p, end);
6801 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
6806 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
6807 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
6811 req->modifiers [i].caught = decode_byte (p, &p, end);
6812 req->modifiers [i].uncaught = decode_byte (p, &p, end);
6813 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" : ""));
6815 req->modifiers [i].data.exc_class = exc_class;
6817 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
6819 return ERR_INVALID_ARGUMENT;
6822 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
6823 int n = decode_int (p, &p, end);
6826 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
6827 for (j = 0; j < n; ++j) {
6828 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
6830 g_free (req->modifiers [i].data.assemblies);
6834 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
6835 int n = decode_int (p, &p, end);
6838 modifier = &req->modifiers [i];
6839 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
6840 for (j = 0; j < n; ++j) {
6841 char *s = decode_string (p, &p, end);
6845 s2 = strdup_tolower (s);
6846 g_hash_table_insert (modifier->data.source_files, s2, s2);
6850 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
6851 int n = decode_int (p, &p, end);
6854 modifier = &req->modifiers [i];
6855 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
6856 for (j = 0; j < n; ++j) {
6857 char *s = decode_string (p, &p, end);
6860 g_hash_table_insert (modifier->data.type_names, s, s);
6864 return ERR_NOT_IMPLEMENTED;
6868 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
6871 req->info = set_breakpoint (method, location, req, &error);
6872 if (!mono_error_ok (&error)) {
6874 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
6875 mono_error_cleanup (&error);
6876 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
6878 } else if (req->event_kind == EVENT_KIND_STEP) {
6879 g_assert (step_thread_id);
6881 err = get_object (step_thread_id, (MonoObject**)&step_thread);
6887 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
6892 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
6893 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
6894 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
6895 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
6896 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
6897 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
6899 if (req->nmodifiers) {
6901 return ERR_NOT_IMPLEMENTED;
6905 mono_loader_lock ();
6906 g_ptr_array_add (event_requests, req);
6908 if (agent_config.defer) {
6909 /* Transmit cached data to the client on receipt of the event request */
6910 switch (req->event_kind) {
6911 case EVENT_KIND_APPDOMAIN_CREATE:
6912 /* Emit load events for currently loaded domains */
6913 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
6915 case EVENT_KIND_ASSEMBLY_LOAD:
6916 /* Emit load events for currently loaded assemblies */
6917 mono_assembly_foreach (emit_assembly_load, NULL);
6919 case EVENT_KIND_THREAD_START:
6920 /* Emit start events for currently started threads */
6921 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
6923 case EVENT_KIND_TYPE_LOAD:
6924 /* Emit type load events for currently loaded types */
6925 mono_domain_foreach (send_types_for_domain, NULL);
6931 mono_loader_unlock ();
6933 buffer_add_int (buf, req->id);
6936 case CMD_EVENT_REQUEST_CLEAR: {
6937 int etype = decode_byte (p, &p, end);
6938 int req_id = decode_int (p, &p, end);
6940 // FIXME: Make a faster mapping from req_id to request
6941 mono_loader_lock ();
6942 clear_event_request (req_id, etype);
6943 mono_loader_unlock ();
6946 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
6949 mono_loader_lock ();
6951 while (i < event_requests->len) {
6952 EventRequest *req = g_ptr_array_index (event_requests, i);
6954 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
6955 clear_breakpoint (req->info);
6957 g_ptr_array_remove_index_fast (event_requests, i);
6963 mono_loader_unlock ();
6967 return ERR_NOT_IMPLEMENTED;
6974 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6980 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
6981 buffer_add_domainid (buf, mono_get_root_domain ());
6984 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
6985 domain = decode_domainid (p, &p, end, NULL, &err);
6988 buffer_add_string (buf, domain->friendly_name);
6991 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
6996 domain = decode_domainid (p, &p, end, NULL, &err);
6999 mono_loader_lock ();
7001 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7004 buffer_add_int (buf, count);
7005 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7007 buffer_add_assemblyid (buf, domain, ass);
7009 mono_loader_unlock ();
7012 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7013 domain = decode_domainid (p, &p, end, NULL, &err);
7017 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7020 case CMD_APPDOMAIN_GET_CORLIB: {
7021 domain = decode_domainid (p, &p, end, NULL, &err);
7025 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7028 case CMD_APPDOMAIN_CREATE_STRING: {
7032 domain = decode_domainid (p, &p, end, NULL, &err);
7035 s = decode_string (p, &p, end);
7037 o = mono_string_new (domain, s);
7038 buffer_add_objid (buf, (MonoObject*)o);
7041 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7043 MonoDomain *domain2;
7046 domain = decode_domainid (p, &p, end, NULL, &err);
7049 klass = decode_typeid (p, &p, end, &domain2, &err);
7054 g_assert (domain == domain2);
7056 o = mono_object_new (domain, klass);
7058 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
7062 buffer_add_objid (buf, o);
7066 return ERR_NOT_IMPLEMENTED;
7073 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7079 ass = decode_assemblyid (p, &p, end, &domain, &err);
7084 case CMD_ASSEMBLY_GET_LOCATION: {
7085 buffer_add_string (buf, mono_image_get_filename (ass->image));
7088 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7092 if (ass->image->dynamic) {
7093 buffer_add_id (buf, 0);
7095 token = mono_image_get_entry_point (ass->image);
7097 buffer_add_id (buf, 0);
7099 m = mono_get_method (ass->image, token, NULL);
7100 buffer_add_methodid (buf, domain, m);
7105 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7106 buffer_add_moduleid (buf, domain, ass->image);
7109 case CMD_ASSEMBLY_GET_OBJECT: {
7110 MonoObject *o = (MonoObject*)mono_assembly_get_object (domain, ass);
7111 buffer_add_objid (buf, o);
7114 case CMD_ASSEMBLY_GET_TYPE: {
7115 char *s = decode_string (p, &p, end);
7116 gboolean ignorecase = decode_byte (p, &p, end);
7117 MonoTypeNameParse info;
7119 gboolean type_resolve, res;
7120 MonoDomain *d = mono_domain_get ();
7122 /* This is needed to be able to find referenced assemblies */
7123 res = mono_domain_set (domain, FALSE);
7126 if (!mono_reflection_parse_type (s, &info)) {
7129 if (info.assembly.name)
7131 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
7133 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
7134 mono_reflection_free_type_info (&info);
7137 mono_domain_set (d, TRUE);
7141 case CMD_ASSEMBLY_GET_NAME: {
7143 MonoAssembly *mass = ass;
7145 name = g_strdup_printf (
7146 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7148 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7149 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7150 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7151 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7153 buffer_add_string (buf, name);
7158 return ERR_NOT_IMPLEMENTED;
7165 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7171 case CMD_MODULE_GET_INFO: {
7172 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7175 basename = g_path_get_basename (image->name);
7176 buffer_add_string (buf, basename); // name
7177 buffer_add_string (buf, image->module_name); // scopename
7178 buffer_add_string (buf, image->name); // fqname
7179 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7180 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7185 return ERR_NOT_IMPLEMENTED;
7192 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7194 if (val && val->vtable->klass == mono_defaults.monotype_class) {
7195 /* Special case these so the client doesn't have to handle Type objects */
7197 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7198 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7199 } else if (MONO_TYPE_IS_REFERENCE (t))
7200 buffer_add_value (buf, t, &val, domain);
7202 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7206 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7212 buffer_add_int (buf, 0);
7216 for (i = 0; i < cinfo->num_attrs; ++i) {
7217 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7220 buffer_add_int (buf, nattrs);
7222 for (i = 0; i < cinfo->num_attrs; ++i) {
7223 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7224 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7225 MonoArray *typed_args, *named_args;
7227 CattrNamedArg *arginfo;
7229 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo);
7231 buffer_add_methodid (buf, domain, attr->ctor);
7235 buffer_add_int (buf, mono_array_length (typed_args));
7236 for (j = 0; j < mono_array_length (typed_args); ++j) {
7237 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7239 t = mono_method_signature (attr->ctor)->params [j];
7241 buffer_add_cattr_arg (buf, t, domain, val);
7244 buffer_add_int (buf, 0);
7249 buffer_add_int (buf, mono_array_length (named_args));
7251 for (j = 0; j < mono_array_length (named_args); ++j) {
7252 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7254 if (arginfo [j].prop) {
7255 buffer_add_byte (buf, 0x54);
7256 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7257 } else if (arginfo [j].field) {
7258 buffer_add_byte (buf, 0x53);
7259 buffer_add_fieldid (buf, domain, arginfo [j].field);
7261 g_assert_not_reached ();
7264 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7267 buffer_add_int (buf, 0);
7273 /* FIXME: Code duplication with icall.c */
7275 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7280 mono_class_setup_interfaces (klass, error);
7281 if (!mono_error_ok (error))
7284 for (i = 0; i < klass->interface_count; i++) {
7285 ic = klass->interfaces [i];
7286 g_hash_table_insert (ifaces, ic, ic);
7288 collect_interfaces (ic, ifaces, error);
7289 if (!mono_error_ok (error))
7295 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7305 case CMD_TYPE_GET_INFO: {
7306 buffer_add_string (buf, klass->name_space);
7307 buffer_add_string (buf, klass->name);
7309 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7310 buffer_add_string (buf, name);
7312 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7313 buffer_add_moduleid (buf, domain, klass->image);
7314 buffer_add_typeid (buf, domain, klass->parent);
7315 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7316 buffer_add_typeid (buf, domain, klass->element_class);
7318 buffer_add_id (buf, 0);
7319 buffer_add_int (buf, klass->type_token);
7320 buffer_add_byte (buf, klass->rank);
7321 buffer_add_int (buf, klass->flags);
7323 type = &klass->byval_arg;
7324 // FIXME: Can't decide whenever a class represents a byref type
7327 if (type->type == MONO_TYPE_PTR)
7329 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7331 if (type->type == MONO_TYPE_VALUETYPE)
7333 if (klass->enumtype)
7335 if (klass->generic_container)
7337 if (klass->generic_container || klass->generic_class)
7339 buffer_add_byte (buf, b);
7342 while ((nested = mono_class_get_nested_types (klass, &iter)))
7344 buffer_add_int (buf, nnested);
7346 while ((nested = mono_class_get_nested_types (klass, &iter)))
7347 buffer_add_typeid (buf, domain, nested);
7348 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7349 if (klass->generic_container)
7350 buffer_add_typeid (buf, domain, klass);
7351 else if (klass->generic_class)
7352 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7354 buffer_add_id (buf, 0);
7356 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7359 if (klass->generic_class) {
7360 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7362 count = inst->type_argc;
7363 buffer_add_int (buf, count);
7364 for (i = 0; i < count; i++)
7365 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7366 } else if (klass->generic_container) {
7367 MonoGenericContainer *container = klass->generic_container;
7370 count = container->type_argc;
7371 buffer_add_int (buf, count);
7372 for (i = 0; i < count; i++) {
7373 pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
7374 buffer_add_typeid (buf, domain, pklass);
7377 buffer_add_int (buf, 0);
7382 case CMD_TYPE_GET_METHODS: {
7385 gpointer iter = NULL;
7388 mono_class_setup_methods (klass);
7390 nmethods = mono_class_num_methods (klass);
7392 buffer_add_int (buf, nmethods);
7394 while ((m = mono_class_get_methods (klass, &iter))) {
7395 buffer_add_methodid (buf, domain, m);
7398 g_assert (i == nmethods);
7401 case CMD_TYPE_GET_FIELDS: {
7404 gpointer iter = NULL;
7407 nfields = mono_class_num_fields (klass);
7409 buffer_add_int (buf, nfields);
7411 while ((f = mono_class_get_fields (klass, &iter))) {
7412 buffer_add_fieldid (buf, domain, f);
7413 buffer_add_string (buf, f->name);
7414 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7415 buffer_add_int (buf, f->type->attrs);
7418 g_assert (i == nfields);
7421 case CMD_TYPE_GET_PROPERTIES: {
7424 gpointer iter = NULL;
7427 nprops = mono_class_num_properties (klass);
7429 buffer_add_int (buf, nprops);
7431 while ((p = mono_class_get_properties (klass, &iter))) {
7432 buffer_add_propertyid (buf, domain, p);
7433 buffer_add_string (buf, p->name);
7434 buffer_add_methodid (buf, domain, p->get);
7435 buffer_add_methodid (buf, domain, p->set);
7436 buffer_add_int (buf, p->attrs);
7439 g_assert (i == nprops);
7442 case CMD_TYPE_GET_CATTRS: {
7443 MonoClass *attr_klass;
7444 MonoCustomAttrInfo *cinfo;
7446 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7447 /* attr_klass can be NULL */
7451 cinfo = mono_custom_attrs_from_class (klass);
7453 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7456 case CMD_TYPE_GET_FIELD_CATTRS: {
7457 MonoClass *attr_klass;
7458 MonoCustomAttrInfo *cinfo;
7459 MonoClassField *field;
7461 field = decode_fieldid (p, &p, end, NULL, &err);
7464 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7468 cinfo = mono_custom_attrs_from_field (klass, field);
7470 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7473 case CMD_TYPE_GET_PROPERTY_CATTRS: {
7474 MonoClass *attr_klass;
7475 MonoCustomAttrInfo *cinfo;
7478 prop = decode_propertyid (p, &p, end, NULL, &err);
7481 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7485 cinfo = mono_custom_attrs_from_property (klass, prop);
7487 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7490 case CMD_TYPE_GET_VALUES:
7491 case CMD_TYPE_GET_VALUES_2: {
7498 MonoThread *thread_obj;
7499 MonoInternalThread *thread = NULL;
7500 guint32 special_static_type;
7502 if (command == CMD_TYPE_GET_VALUES_2) {
7503 int objid = decode_objid (p, &p, end);
7506 err = get_object (objid, (MonoObject**)&thread_obj);
7510 thread = THREAD_TO_INTERNAL (thread_obj);
7513 len = decode_int (p, &p, end);
7514 for (i = 0; i < len; ++i) {
7515 f = decode_fieldid (p, &p, end, NULL, &err);
7519 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7520 return ERR_INVALID_FIELDID;
7521 special_static_type = mono_class_field_get_special_static_type (f);
7522 if (special_static_type != SPECIAL_STATIC_NONE) {
7523 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
7524 return ERR_INVALID_FIELDID;
7527 /* Check that the field belongs to the object */
7529 for (k = klass; k; k = k->parent) {
7530 if (k == f->parent) {
7536 return ERR_INVALID_FIELDID;
7538 vtable = mono_class_vtable (domain, f->parent);
7539 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7540 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
7541 buffer_add_value (buf, f->type, val, domain);
7546 case CMD_TYPE_SET_VALUES: {
7554 len = decode_int (p, &p, end);
7555 for (i = 0; i < len; ++i) {
7556 f = decode_fieldid (p, &p, end, NULL, &err);
7560 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7561 return ERR_INVALID_FIELDID;
7562 if (mono_class_field_is_special_static (f))
7563 return ERR_INVALID_FIELDID;
7565 /* Check that the field belongs to the object */
7567 for (k = klass; k; k = k->parent) {
7568 if (k == f->parent) {
7574 return ERR_INVALID_FIELDID;
7576 // FIXME: Check for literal/const
7578 vtable = mono_class_vtable (domain, f->parent);
7579 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7580 err = decode_value (f->type, domain, val, p, &p, end);
7585 if (MONO_TYPE_IS_REFERENCE (f->type))
7586 mono_field_static_set_value (vtable, f, *(gpointer*)val);
7588 mono_field_static_set_value (vtable, f, val);
7593 case CMD_TYPE_GET_OBJECT: {
7594 MonoObject *o = (MonoObject*)mono_type_get_object (domain, &klass->byval_arg);
7595 buffer_add_objid (buf, o);
7598 case CMD_TYPE_GET_SOURCE_FILES:
7599 case CMD_TYPE_GET_SOURCE_FILES_2: {
7600 char *source_file, *base;
7604 files = get_source_files_for_type (klass);
7606 buffer_add_int (buf, files->len);
7607 for (i = 0; i < files->len; ++i) {
7608 source_file = g_ptr_array_index (files, i);
7609 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
7610 buffer_add_string (buf, source_file);
7612 base = g_path_get_basename (source_file);
7613 buffer_add_string (buf, base);
7616 g_free (source_file);
7618 g_ptr_array_free (files, TRUE);
7621 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
7622 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
7626 if (mono_class_is_assignable_from (klass, oklass))
7627 buffer_add_byte (buf, 1);
7629 buffer_add_byte (buf, 0);
7632 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
7633 char *name = decode_string (p, &p, end);
7634 int i, flags = decode_int (p, &p, end);
7635 MonoException *ex = NULL;
7636 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
7639 return ERR_LOADER_ERROR;
7640 buffer_add_int (buf, array->len);
7641 for (i = 0; i < array->len; ++i) {
7642 MonoMethod *method = g_ptr_array_index (array, i);
7643 buffer_add_methodid (buf, domain, method);
7646 g_ptr_array_free (array, TRUE);
7650 case CMD_TYPE_GET_INTERFACES: {
7652 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
7654 MonoClass *tclass, *iface;
7655 GHashTableIter iter;
7659 for (parent = tclass; parent; parent = parent->parent) {
7660 mono_class_setup_interfaces (parent, &error);
7661 if (!mono_error_ok (&error))
7662 return ERR_LOADER_ERROR;
7663 collect_interfaces (parent, iface_hash, &error);
7664 if (!mono_error_ok (&error))
7665 return ERR_LOADER_ERROR;
7668 buffer_add_int (buf, g_hash_table_size (iface_hash));
7670 g_hash_table_iter_init (&iter, iface_hash);
7671 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
7672 buffer_add_typeid (buf, domain, iface);
7673 g_hash_table_destroy (iface_hash);
7676 case CMD_TYPE_GET_INTERFACE_MAP: {
7677 int tindex, ioffset;
7678 gboolean variance_used;
7680 int len, nmethods, i;
7684 len = decode_int (p, &p, end);
7685 mono_class_setup_vtable (klass);
7687 for (tindex = 0; tindex < len; ++tindex) {
7688 iclass = decode_typeid (p, &p, end, NULL, &err);
7692 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
7694 return ERR_INVALID_ARGUMENT;
7696 nmethods = mono_class_num_methods (iclass);
7697 buffer_add_int (buf, nmethods);
7700 while ((method = mono_class_get_methods (iclass, &iter))) {
7701 buffer_add_methodid (buf, domain, method);
7703 for (i = 0; i < nmethods; ++i)
7704 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
7708 case CMD_TYPE_IS_INITIALIZED: {
7709 MonoVTable *vtable = mono_class_vtable (domain, klass);
7712 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
7714 buffer_add_int (buf, 0);
7718 return ERR_NOT_IMPLEMENTED;
7725 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7728 MonoDomain *old_domain;
7732 klass = decode_typeid (p, &p, end, &domain, &err);
7736 old_domain = mono_domain_get ();
7738 mono_domain_set (domain, TRUE);
7740 err = type_commands_internal (command, klass, domain, p, end, buf);
7742 mono_domain_set (old_domain, TRUE);
7748 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7750 MonoMethodHeader *header;
7754 case CMD_METHOD_GET_NAME: {
7755 buffer_add_string (buf, method->name);
7758 case CMD_METHOD_GET_DECLARING_TYPE: {
7759 buffer_add_typeid (buf, domain, method->klass);
7762 case CMD_METHOD_GET_DEBUG_INFO: {
7763 MonoDebugMethodInfo *minfo;
7765 int i, j, n_il_offsets;
7768 int *column_numbers;
7770 GPtrArray *source_file_list;
7772 header = mono_method_get_header (method);
7774 buffer_add_int (buf, 0);
7775 buffer_add_string (buf, "");
7776 buffer_add_int (buf, 0);
7780 minfo = mono_debug_lookup_method (method);
7782 buffer_add_int (buf, header->code_size);
7783 buffer_add_string (buf, "");
7784 buffer_add_int (buf, 0);
7785 mono_metadata_free_mh (header);
7789 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, &n_il_offsets, &il_offsets, &line_numbers, &column_numbers, &source_files);
7790 buffer_add_int (buf, header->code_size);
7791 if (CHECK_PROTOCOL_VERSION (2, 13)) {
7792 buffer_add_int (buf, source_file_list->len);
7793 for (i = 0; i < source_file_list->len; ++i) {
7794 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
7795 buffer_add_string (buf, sinfo->source_file);
7796 if (CHECK_PROTOCOL_VERSION (2, 14)) {
7797 for (j = 0; j < 16; ++j)
7798 buffer_add_byte (buf, sinfo->hash [j]);
7802 buffer_add_string (buf, source_file);
7804 buffer_add_int (buf, n_il_offsets);
7805 DEBUG (10, fprintf (log_file, "Line number table for method %s:\n", mono_method_full_name (method, TRUE)));
7806 for (i = 0; i < n_il_offsets; ++i) {
7807 const char *srcfile = "";
7809 if (source_files [i] != -1) {
7810 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
7811 srcfile = sinfo->source_file;
7813 DEBUG (10, fprintf (log_file, "IL%x -> %s:%d %d\n", il_offsets [i], srcfile, line_numbers [i], column_numbers ? column_numbers [i] : -1));
7814 buffer_add_int (buf, il_offsets [i]);
7815 buffer_add_int (buf, line_numbers [i]);
7816 if (CHECK_PROTOCOL_VERSION (2, 13))
7817 buffer_add_int (buf, source_files [i]);
7818 if (CHECK_PROTOCOL_VERSION (2, 19))
7819 buffer_add_int (buf, column_numbers ? column_numbers [i] : -1);
7821 g_free (source_file);
7822 g_free (il_offsets);
7823 g_free (line_numbers);
7824 g_free (source_files);
7825 g_ptr_array_free (source_file_list, TRUE);
7826 mono_metadata_free_mh (header);
7829 case CMD_METHOD_GET_PARAM_INFO: {
7830 MonoMethodSignature *sig = mono_method_signature (method);
7834 /* FIXME: mono_class_from_mono_type () and byrefs */
7836 /* FIXME: Use a smaller encoding */
7837 buffer_add_int (buf, sig->call_convention);
7838 buffer_add_int (buf, sig->param_count);
7839 buffer_add_int (buf, sig->generic_param_count);
7840 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
7841 for (i = 0; i < sig->param_count; ++i) {
7843 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
7846 /* Emit parameter names */
7847 names = g_new (char *, sig->param_count);
7848 mono_method_get_param_names (method, (const char **) names);
7849 for (i = 0; i < sig->param_count; ++i)
7850 buffer_add_string (buf, names [i]);
7855 case CMD_METHOD_GET_LOCALS_INFO: {
7856 int i, j, num_locals;
7857 MonoDebugLocalsInfo *locals;
7859 header = mono_method_get_header (method);
7861 return ERR_INVALID_ARGUMENT;
7863 buffer_add_int (buf, header->num_locals);
7866 for (i = 0; i < header->num_locals; ++i)
7867 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
7870 locals = mono_debug_lookup_locals (method);
7872 num_locals = locals->num_locals;
7875 for (i = 0; i < header->num_locals; ++i) {
7876 for (j = 0; j < num_locals; ++j)
7877 if (locals->locals [j].index == i)
7880 buffer_add_string (buf, locals->locals [j].name);
7882 buffer_add_string (buf, "");
7886 for (i = 0; i < header->num_locals; ++i) {
7887 for (j = 0; j < num_locals; ++j)
7888 if (locals->locals [j].index == i)
7890 if (j < num_locals && locals->locals [j].block) {
7891 buffer_add_int (buf, locals->locals [j].block->start_offset);
7892 buffer_add_int (buf, locals->locals [j].block->end_offset);
7894 buffer_add_int (buf, 0);
7895 buffer_add_int (buf, header->code_size);
7898 mono_metadata_free_mh (header);
7901 mono_debug_symfile_free_locals (locals);
7905 case CMD_METHOD_GET_INFO:
7906 buffer_add_int (buf, method->flags);
7907 buffer_add_int (buf, method->iflags);
7908 buffer_add_int (buf, method->token);
7909 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7911 if (method->is_generic)
7913 if (mono_method_signature (method)->generic_param_count)
7915 buffer_add_byte (buf, attrs);
7916 if (method->is_generic || method->is_inflated) {
7919 if (method->is_generic) {
7922 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
7924 result = imethod->declaring;
7925 if (imethod->context.class_inst) {
7926 MonoClass *klass = ((MonoMethod *) imethod)->klass;
7927 /*Generic methods gets the context of the GTD.*/
7928 if (mono_class_get_context (klass))
7929 result = mono_class_inflate_generic_method_full (result, klass, mono_class_get_context (klass));
7933 buffer_add_methodid (buf, domain, result);
7935 buffer_add_id (buf, 0);
7937 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7938 if (mono_method_signature (method)->generic_param_count) {
7941 if (method->is_inflated) {
7942 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
7944 count = inst->type_argc;
7945 buffer_add_int (buf, count);
7947 for (i = 0; i < count; i++)
7948 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7950 buffer_add_int (buf, 0);
7952 } else if (method->is_generic) {
7953 MonoGenericContainer *container = mono_method_get_generic_container (method);
7955 count = mono_method_signature (method)->generic_param_count;
7956 buffer_add_int (buf, count);
7957 for (i = 0; i < count; i++) {
7958 MonoGenericParam *param = mono_generic_container_get_param (container, i);
7959 MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
7960 buffer_add_typeid (buf, domain, pklass);
7963 buffer_add_int (buf, 0);
7966 buffer_add_int (buf, 0);
7971 case CMD_METHOD_GET_BODY: {
7974 header = mono_method_get_header (method);
7976 buffer_add_int (buf, 0);
7978 if (CHECK_PROTOCOL_VERSION (2, 18))
7979 buffer_add_int (buf, 0);
7981 buffer_add_int (buf, header->code_size);
7982 for (i = 0; i < header->code_size; ++i)
7983 buffer_add_byte (buf, header->code [i]);
7985 if (CHECK_PROTOCOL_VERSION (2, 18)) {
7986 buffer_add_int (buf, header->num_clauses);
7987 for (i = 0; i < header->num_clauses; ++i) {
7988 MonoExceptionClause *clause = &header->clauses [i];
7990 buffer_add_int (buf, clause->flags);
7991 buffer_add_int (buf, clause->try_offset);
7992 buffer_add_int (buf, clause->try_len);
7993 buffer_add_int (buf, clause->handler_offset);
7994 buffer_add_int (buf, clause->handler_len);
7995 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
7996 buffer_add_typeid (buf, domain, clause->data.catch_class);
7997 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
7998 buffer_add_int (buf, clause->data.filter_offset);
8002 mono_metadata_free_mh (header);
8007 case CMD_METHOD_RESOLVE_TOKEN: {
8008 guint32 token = decode_int (p, &p, end);
8011 switch (mono_metadata_token_code (token)) {
8012 case MONO_TOKEN_STRING: {
8016 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
8019 s2 = mono_string_to_utf8 (s);
8021 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8022 buffer_add_string (buf, s2);
8028 MonoClass *handle_class;
8030 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8031 val = mono_method_get_wrapper_data (method, token);
8032 handle_class = mono_method_get_wrapper_data (method, token + 1);
8034 if (handle_class == NULL) {
8035 // Can't figure out the token type
8036 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8040 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
8044 if (handle_class == mono_defaults.typehandle_class) {
8045 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8046 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8047 buffer_add_typeid (buf, domain, (MonoClass *) val);
8049 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
8050 } else if (handle_class == mono_defaults.fieldhandle_class) {
8051 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8052 buffer_add_fieldid (buf, domain, val);
8053 } else if (handle_class == mono_defaults.methodhandle_class) {
8054 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8055 buffer_add_methodid (buf, domain, val);
8056 } else if (handle_class == mono_defaults.string_class) {
8059 s = mono_string_to_utf8 (val);
8060 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8061 buffer_add_string (buf, s);
8064 g_assert_not_reached ();
8071 case CMD_METHOD_GET_CATTRS: {
8072 MonoClass *attr_klass;
8073 MonoCustomAttrInfo *cinfo;
8075 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8076 /* attr_klass can be NULL */
8080 cinfo = mono_custom_attrs_from_method (method);
8082 buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
8086 return ERR_NOT_IMPLEMENTED;
8093 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8096 MonoDomain *old_domain;
8100 method = decode_methodid (p, &p, end, &domain, &err);
8104 old_domain = mono_domain_get ();
8106 mono_domain_set (domain, TRUE);
8108 err = method_commands_internal (command, method, domain, p, end, buf);
8110 mono_domain_set (old_domain, TRUE);
8116 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8118 int objid = decode_objid (p, &p, end);
8120 MonoThread *thread_obj;
8121 MonoInternalThread *thread;
8123 err = get_object (objid, (MonoObject**)&thread_obj);
8127 thread = THREAD_TO_INTERNAL (thread_obj);
8130 case CMD_THREAD_GET_NAME: {
8132 gunichar2 *s = mono_thread_get_name (thread, &name_len);
8135 buffer_add_int (buf, 0);
8140 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
8142 buffer_add_int (buf, len);
8143 buffer_add_data (buf, (guint8*)name, len);
8148 case CMD_THREAD_GET_FRAME_INFO: {
8149 DebuggerTlsData *tls;
8150 int i, start_frame, length;
8152 // Wait for suspending if it already started
8153 // FIXME: Races with suspend_count
8154 while (!is_suspended ()) {
8156 wait_for_suspend ();
8160 wait_for_suspend ();
8161 if (!is_suspended ())
8162 return ERR_NOT_SUSPENDED;
8165 start_frame = decode_int (p, &p, end);
8166 length = decode_int (p, &p, end);
8168 if (start_frame != 0 || length != -1)
8169 return ERR_NOT_IMPLEMENTED;
8171 mono_loader_lock ();
8172 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8173 mono_loader_unlock ();
8176 compute_frame_info (thread, tls);
8178 buffer_add_int (buf, tls->frame_count);
8179 for (i = 0; i < tls->frame_count; ++i) {
8180 buffer_add_int (buf, tls->frames [i]->id);
8181 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
8182 buffer_add_int (buf, tls->frames [i]->il_offset);
8184 * Instead of passing the frame type directly to the client, we associate
8185 * it with the previous frame using a set of flags. This avoids lots of
8186 * conditional code in the client, since a frame whose type isn't
8187 * FRAME_TYPE_MANAGED has no method, location, etc.
8189 buffer_add_byte (buf, tls->frames [i]->flags);
8194 case CMD_THREAD_GET_STATE:
8195 buffer_add_int (buf, thread->state);
8197 case CMD_THREAD_GET_INFO:
8198 buffer_add_byte (buf, thread->threadpool_thread);
8200 case CMD_THREAD_GET_ID:
8201 buffer_add_long (buf, (guint64)(gsize)thread);
8203 case CMD_THREAD_GET_TID:
8204 buffer_add_long (buf, (guint64)thread->tid);
8207 return ERR_NOT_IMPLEMENTED;
8214 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8218 MonoThread *thread_obj;
8219 MonoInternalThread *thread;
8220 int pos, i, len, frame_idx;
8221 DebuggerTlsData *tls;
8223 MonoDebugMethodJitInfo *jit;
8224 MonoDebugVarInfo *var;
8225 MonoMethodSignature *sig;
8227 MonoMethodHeader *header;
8229 objid = decode_objid (p, &p, end);
8230 err = get_object (objid, (MonoObject**)&thread_obj);
8234 thread = THREAD_TO_INTERNAL (thread_obj);
8236 id = decode_id (p, &p, end);
8238 mono_loader_lock ();
8239 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8240 mono_loader_unlock ();
8243 for (i = 0; i < tls->frame_count; ++i) {
8244 if (tls->frames [i]->id == id)
8247 if (i == tls->frame_count)
8248 return ERR_INVALID_FRAMEID;
8251 frame = tls->frames [frame_idx];
8253 if (!frame->has_ctx)
8255 return ERR_INVALID_FRAMEID;
8258 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
8259 if (!frame->jit && frame->api_method->is_inflated)
8260 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
8264 /* This could happen for aot images with no jit debug info */
8265 s = mono_method_full_name (frame->api_method, TRUE);
8266 DEBUG (1, fprintf (log_file, "[dbg] No debug information found for '%s'.\n", s));
8268 return ERR_ABSENT_INFORMATION;
8273 sig = mono_method_signature (frame->actual_method);
8275 if (!get_seq_points (frame->domain, frame->actual_method))
8277 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
8279 return ERR_ABSENT_INFORMATION;
8282 case CMD_STACK_FRAME_GET_VALUES: {
8283 len = decode_int (p, &p, end);
8284 header = mono_method_get_header (frame->actual_method);
8286 for (i = 0; i < len; ++i) {
8287 pos = decode_int (p, &p, end);
8292 g_assert (pos >= 0 && pos < jit->num_params);
8294 var = &jit->params [pos];
8296 add_var (buf, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
8298 g_assert (pos >= 0 && pos < jit->num_locals);
8300 var = &jit->locals [pos];
8302 add_var (buf, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
8305 mono_metadata_free_mh (header);
8308 case CMD_STACK_FRAME_GET_THIS: {
8309 if (frame->api_method->klass->valuetype) {
8310 if (!sig->hasthis) {
8311 MonoObject *p = NULL;
8312 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
8314 add_var (buf, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8317 if (!sig->hasthis) {
8318 MonoObject *p = NULL;
8319 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
8321 add_var (buf, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8326 case CMD_STACK_FRAME_SET_VALUES: {
8329 MonoDebugVarInfo *var;
8331 len = decode_int (p, &p, end);
8332 header = mono_method_get_header (frame->actual_method);
8334 for (i = 0; i < len; ++i) {
8335 pos = decode_int (p, &p, end);
8340 g_assert (pos >= 0 && pos < jit->num_params);
8342 t = sig->params [pos];
8343 var = &jit->params [pos];
8345 g_assert (pos >= 0 && pos < jit->num_locals);
8347 t = header->locals [pos];
8348 var = &jit->locals [pos];
8351 if (MONO_TYPE_IS_REFERENCE (t))
8352 val_buf = g_alloca (sizeof (MonoObject*));
8354 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
8355 err = decode_value (t, frame->domain, val_buf, p, &p, end);
8359 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_ctx);
8361 mono_metadata_free_mh (header);
8365 return ERR_NOT_IMPLEMENTED;
8372 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8375 int objid, err, index, len, i, esize;
8378 objid = decode_objid (p, &p, end);
8379 err = get_object (objid, (MonoObject**)&arr);
8384 case CMD_ARRAY_REF_GET_LENGTH:
8385 buffer_add_int (buf, arr->obj.vtable->klass->rank);
8387 buffer_add_int (buf, arr->max_length);
8388 buffer_add_int (buf, 0);
8390 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
8391 buffer_add_int (buf, arr->bounds [i].length);
8392 buffer_add_int (buf, arr->bounds [i].lower_bound);
8396 case CMD_ARRAY_REF_GET_VALUES:
8397 index = decode_int (p, &p, end);
8398 len = decode_int (p, &p, end);
8400 g_assert (index >= 0 && len >= 0);
8401 // Reordered to avoid integer overflow
8402 g_assert (!(index > arr->max_length - len));
8404 esize = mono_array_element_size (arr->obj.vtable->klass);
8405 for (i = index; i < index + len; ++i) {
8406 elem = (gpointer*)((char*)arr->vector + (i * esize));
8407 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
8410 case CMD_ARRAY_REF_SET_VALUES:
8411 index = decode_int (p, &p, end);
8412 len = decode_int (p, &p, end);
8414 g_assert (index >= 0 && len >= 0);
8415 // Reordered to avoid integer overflow
8416 g_assert (!(index > arr->max_length - len));
8418 esize = mono_array_element_size (arr->obj.vtable->klass);
8419 for (i = index; i < index + len; ++i) {
8420 elem = (gpointer*)((char*)arr->vector + (i * esize));
8422 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
8426 return ERR_NOT_IMPLEMENTED;
8433 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8438 int i, index, length;
8441 objid = decode_objid (p, &p, end);
8442 err = get_object (objid, (MonoObject**)&str);
8447 case CMD_STRING_REF_GET_VALUE:
8448 s = mono_string_to_utf8 (str);
8449 buffer_add_string (buf, s);
8452 case CMD_STRING_REF_GET_LENGTH:
8453 buffer_add_long (buf, mono_string_length (str));
8455 case CMD_STRING_REF_GET_CHARS:
8456 index = decode_long (p, &p, end);
8457 length = decode_long (p, &p, end);
8458 if (index > mono_string_length (str) - length)
8459 return ERR_INVALID_ARGUMENT;
8460 c = mono_string_chars (str) + index;
8461 for (i = 0; i < length; ++i)
8462 buffer_add_short (buf, c [i]);
8465 return ERR_NOT_IMPLEMENTED;
8472 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8481 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
8482 objid = decode_objid (p, &p, end);
8483 err = get_object (objid, &obj);
8485 buffer_add_int (buf, 1);
8487 buffer_add_int (buf, 0);
8491 objid = decode_objid (p, &p, end);
8492 err = get_object (objid, &obj);
8497 case CMD_OBJECT_REF_GET_TYPE:
8498 /* This handles transparent proxies too */
8499 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8501 case CMD_OBJECT_REF_GET_VALUES:
8502 len = decode_int (p, &p, end);
8504 for (i = 0; i < len; ++i) {
8505 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
8509 /* Check that the field belongs to the object */
8511 for (k = obj->vtable->klass; k; k = k->parent) {
8512 if (k == f->parent) {
8518 return ERR_INVALID_FIELDID;
8520 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8524 if (mono_class_field_is_special_static (f))
8525 return ERR_INVALID_FIELDID;
8527 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8528 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8529 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8530 mono_field_static_get_value (vtable, f, val);
8531 buffer_add_value (buf, f->type, val, obj->vtable->domain);
8534 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
8538 case CMD_OBJECT_REF_SET_VALUES:
8539 len = decode_int (p, &p, end);
8541 for (i = 0; i < len; ++i) {
8542 f = decode_fieldid (p, &p, end, NULL, &err);
8546 /* Check that the field belongs to the object */
8548 for (k = obj->vtable->klass; k; k = k->parent) {
8549 if (k == f->parent) {
8555 return ERR_INVALID_FIELDID;
8557 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8561 if (mono_class_field_is_special_static (f))
8562 return ERR_INVALID_FIELDID;
8564 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8565 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8567 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8568 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
8573 mono_field_static_set_value (vtable, f, val);
8576 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
8582 case CMD_OBJECT_REF_GET_ADDRESS:
8583 buffer_add_long (buf, (gssize)obj);
8585 case CMD_OBJECT_REF_GET_DOMAIN:
8586 buffer_add_domainid (buf, obj->vtable->domain);
8588 case CMD_OBJECT_REF_GET_INFO:
8589 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8590 buffer_add_domainid (buf, obj->vtable->domain);
8593 return ERR_NOT_IMPLEMENTED;
8600 command_set_to_string (CommandSet command_set)
8602 switch (command_set) {
8605 case CMD_SET_OBJECT_REF:
8606 return "OBJECT_REF";
8607 case CMD_SET_STRING_REF:
8608 return "STRING_REF";
8609 case CMD_SET_THREAD:
8611 case CMD_SET_ARRAY_REF:
8613 case CMD_SET_EVENT_REQUEST:
8614 return "EVENT_REQUEST";
8615 case CMD_SET_STACK_FRAME:
8616 return "STACK_FRAME";
8617 case CMD_SET_APPDOMAIN:
8619 case CMD_SET_ASSEMBLY:
8621 case CMD_SET_METHOD:
8625 case CMD_SET_MODULE:
8635 cmd_to_string (CommandSet set, int command)
8640 case CMD_VM_VERSION:
8642 case CMD_VM_ALL_THREADS:
8643 return "ALL_THREADS";
8644 case CMD_VM_SUSPEND:
8650 case CMD_VM_DISPOSE:
8652 case CMD_VM_INVOKE_METHOD:
8653 return "INVOKE_METHOD";
8654 case CMD_VM_SET_PROTOCOL_VERSION:
8655 return "SET_PROTOCOL_VERSION";
8656 case CMD_VM_ABORT_INVOKE:
8657 return "ABORT_INVOKE";
8658 case CMD_VM_SET_KEEPALIVE:
8659 return "SET_KEEPALIVE";
8672 wait_for_attach (void)
8674 #ifndef DISABLE_SOCKET_TRANSPORT
8675 if (listen_fd == -1) {
8676 DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
8680 /* Block and wait for client connection */
8681 conn_fd = socket_transport_accept (listen_fd);
8682 DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
8683 if (conn_fd == -1) {
8684 DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
8688 g_assert_not_reached ();
8692 disconnected = !transport_handshake ();
8694 DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
8704 * This thread handles communication with the debugger client using a JDWP
8707 static guint32 WINAPI
8708 debugger_thread (void *arg)
8710 int res, len, id, flags, command_set = 0, command = 0;
8711 guint8 header [HEADER_LENGTH];
8712 guint8 *data, *p, *end;
8716 gboolean attach_failed = FALSE;
8718 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
8720 debugger_thread_id = GetCurrentThreadId ();
8722 mono_jit_thread_attach (mono_get_root_domain ());
8724 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
8726 mono_set_is_debugger_attached (TRUE);
8728 if (agent_config.defer) {
8729 if (!wait_for_attach ()) {
8730 DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
8731 attach_failed = TRUE; // Don't abort process when we can't listen
8733 /* Send start event to client */
8734 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
8738 while (!attach_failed) {
8739 res = transport_recv (header, HEADER_LENGTH);
8741 /* This will break if the socket is closed during shutdown too */
8742 if (res != HEADER_LENGTH) {
8743 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH));
8748 end = header + HEADER_LENGTH;
8750 len = decode_int (p, &p, end);
8751 id = decode_int (p, &p, end);
8752 flags = decode_byte (p, &p, end);
8753 command_set = decode_byte (p, &p, end);
8754 command = decode_byte (p, &p, end);
8756 g_assert (flags == 0);
8759 const char *cmd_str;
8762 cmd_str = cmd_to_string (command_set, command);
8764 sprintf (cmd_num, "%d", command);
8768 DEBUG (1, fprintf (log_file, "[dbg] Received command %s(%s), id=%d.\n", command_set_to_string (command_set), cmd_str, id));
8771 data = g_malloc (len - HEADER_LENGTH);
8772 if (len - HEADER_LENGTH > 0)
8774 res = transport_recv (data, len - HEADER_LENGTH);
8775 if (res != len - HEADER_LENGTH) {
8776 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH));
8782 end = data + (len - HEADER_LENGTH);
8784 buffer_init (&buf, 128);
8789 /* Process the request */
8790 switch (command_set) {
8792 err = vm_commands (command, id, p, end, &buf);
8793 if (!err && command == CMD_VM_INVOKE_METHOD)
8794 /* Sent after the invoke is complete */
8797 case CMD_SET_EVENT_REQUEST:
8798 err = event_commands (command, p, end, &buf);
8800 case CMD_SET_APPDOMAIN:
8801 err = domain_commands (command, p, end, &buf);
8803 case CMD_SET_ASSEMBLY:
8804 err = assembly_commands (command, p, end, &buf);
8806 case CMD_SET_MODULE:
8807 err = module_commands (command, p, end, &buf);
8810 err = type_commands (command, p, end, &buf);
8812 case CMD_SET_METHOD:
8813 err = method_commands (command, p, end, &buf);
8815 case CMD_SET_THREAD:
8816 err = thread_commands (command, p, end, &buf);
8818 case CMD_SET_STACK_FRAME:
8819 err = frame_commands (command, p, end, &buf);
8821 case CMD_SET_ARRAY_REF:
8822 err = array_commands (command, p, end, &buf);
8824 case CMD_SET_STRING_REF:
8825 err = string_commands (command, p, end, &buf);
8827 case CMD_SET_OBJECT_REF:
8828 err = object_commands (command, p, end, &buf);
8831 err = ERR_NOT_IMPLEMENTED;
8835 send_reply_packet (id, err, &buf);
8840 if (command_set == CMD_SET_VM && command == CMD_VM_DISPOSE)
8844 mono_set_is_debugger_attached (FALSE);
8846 mono_mutex_lock (&debugger_thread_exited_mutex);
8847 debugger_thread_exited = TRUE;
8848 mono_cond_signal (&debugger_thread_exited_cond);
8849 mono_mutex_unlock (&debugger_thread_exited_mutex);
8851 DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
8853 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
8854 DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
8855 start_debugger_thread ();
8861 #else /* DISABLE_DEBUGGER_AGENT */
8864 mono_debugger_agent_parse_options (char *options)
8866 g_error ("This runtime is configured with the debugger agent disabled.");
8870 mono_debugger_agent_init (void)
8875 mono_debugger_agent_breakpoint_hit (void *sigctx)
8880 mono_debugger_agent_single_step_event (void *sigctx)
8885 mono_debugger_agent_free_domain_info (MonoDomain *domain)
8890 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
8896 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
8897 MonoContext *catch_ctx)
8902 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
8907 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
8912 mono_debugger_agent_user_break (void)
8918 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
8923 mono_debugger_agent_debug_log_is_enabled (void)