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/environment.h>
73 #include <mono/metadata/threads-types.h>
74 #include <mono/metadata/socket-io.h>
75 #include <mono/metadata/assembly.h>
76 #include <mono/metadata/runtime.h>
77 #include <mono/metadata/threadpool.h>
78 #include <mono/metadata/verify-internals.h>
79 #include <mono/utils/mono-semaphore.h>
80 #include <mono/utils/mono-error-internals.h>
81 #include <mono/utils/mono-stack-unwinding.h>
82 #include <mono/utils/mono-time.h>
83 #include <mono/utils/mono-threads.h>
84 #include "debugger-agent.h"
88 On iOS we can't use System.Environment.Exit () as it will do the wrong
91 #if !defined (TARGET_IOS)
92 #define TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
96 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
97 #define DISABLE_DEBUGGER_AGENT 1
100 #ifdef DISABLE_SOFT_DEBUG
101 #define DISABLE_DEBUGGER_AGENT 1
104 #ifndef DISABLE_DEBUGGER_AGENT
106 #include <mono/utils/mono-mutex.h>
108 /* Definitions to make backporting to 2.6 easier */
109 //#define MonoInternalThread MonoThread
110 //#define mono_thread_internal_current mono_thread_current
111 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
134 guint32 il_offset, native_offset;
138 * If method is gshared, this is the actual instance, otherwise this is equal to
141 MonoMethod *actual_method;
143 * This is the method which is visible to debugger clients. Same as method,
144 * except for native-to-managed wrappers.
146 MonoMethod *api_method;
148 MonoDebugMethodJitInfo *jit;
151 mgreg_t *reg_locations [MONO_MAX_IREGS];
153 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
154 * the frame can become invalid.
159 typedef struct _InvokeData InvokeData;
167 /* This is the context which needs to be restored after the invoke */
171 * If this is set, invoke this method with the arguments given by ARGS.
175 guint32 suspend_count;
178 InvokeData *last_invoke;
182 MonoThreadUnwindState context;
184 /* This is computed on demand when it is requested using the wire protocol */
185 /* It is freed up when the thread is resumed */
189 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
192 gboolean frames_up_to_date;
194 * Points to data about a pending invoke which needs to be executed after the thread
197 InvokeData *pending_invoke;
199 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
204 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
205 * within a finite amount of time.
209 * Set to TRUE if this thread is suspended in suspend_current ().
211 gboolean really_suspended;
212 /* Used to pass the context to the breakpoint/single step handler */
213 MonoContext handler_ctx;
214 /* Whenever thread_stop () was called for this thread */
217 /* Number of thread interruptions not yet processed */
218 gint32 interrupt_count;
220 /* Whenever to disable breakpoints (used during invokes) */
221 gboolean disable_breakpoints;
224 * Number of times this thread has been resumed using resume_thread ().
226 guint32 resume_count;
228 MonoInternalThread *thread;
231 * Information about the frame which transitioned to native code for running
234 StackFrameInfo async_last_frame;
237 * The context where the stack walk can be started for running threads.
239 MonoThreadUnwindState async_state;
242 * The context used for filter clauses
244 MonoThreadUnwindState filter_state;
247 * The callee address of the last mono_runtime_invoke call
249 gpointer invoke_addr;
251 gboolean abort_requested;
254 * The current mono_runtime_invoke invocation.
259 * The context where single stepping should resume while the thread is suspended because
260 * of an EXCEPTION event.
262 MonoThreadUnwindState catch_state;
265 * The context which needs to be restored after handling a single step/breakpoint
266 * event. This is the same as the ctx at step/breakpoint site, but includes changes
267 * to caller saved registers done by set_var ().
269 MonoContext restore_ctx;
271 /* The currently unloading appdomain */
272 MonoDomain *domain_unloading;
277 void (*connect) (const char *address);
278 void (*close1) (void);
279 void (*close2) (void);
280 gboolean (*send) (void *buf, int len);
281 int (*recv) (void *buf, int len);
285 * Wire Protocol definitions
288 #define HEADER_LENGTH 11
290 #define MAJOR_VERSION 2
291 #define MINOR_VERSION 34
295 CMD_SET_OBJECT_REF = 9,
296 CMD_SET_STRING_REF = 10,
298 CMD_SET_ARRAY_REF = 13,
299 CMD_SET_EVENT_REQUEST = 15,
300 CMD_SET_STACK_FRAME = 16,
301 CMD_SET_APPDOMAIN = 20,
302 CMD_SET_ASSEMBLY = 21,
311 EVENT_KIND_VM_START = 0,
312 EVENT_KIND_VM_DEATH = 1,
313 EVENT_KIND_THREAD_START = 2,
314 EVENT_KIND_THREAD_DEATH = 3,
315 EVENT_KIND_APPDOMAIN_CREATE = 4,
316 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
317 EVENT_KIND_METHOD_ENTRY = 6,
318 EVENT_KIND_METHOD_EXIT = 7,
319 EVENT_KIND_ASSEMBLY_LOAD = 8,
320 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
321 EVENT_KIND_BREAKPOINT = 10,
322 EVENT_KIND_STEP = 11,
323 EVENT_KIND_TYPE_LOAD = 12,
324 EVENT_KIND_EXCEPTION = 13,
325 EVENT_KIND_KEEPALIVE = 14,
326 EVENT_KIND_USER_BREAK = 15,
327 EVENT_KIND_USER_LOG = 16
331 SUSPEND_POLICY_NONE = 0,
332 SUSPEND_POLICY_EVENT_THREAD = 1,
333 SUSPEND_POLICY_ALL = 2
338 ERR_INVALID_OBJECT = 20,
339 ERR_INVALID_FIELDID = 25,
340 ERR_INVALID_FRAMEID = 30,
341 ERR_NOT_IMPLEMENTED = 100,
342 ERR_NOT_SUSPENDED = 101,
343 ERR_INVALID_ARGUMENT = 102,
345 ERR_NO_INVOCATION = 104,
346 ERR_ABSENT_INFORMATION = 105,
347 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
348 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
353 MOD_KIND_THREAD_ONLY = 3,
354 MOD_KIND_LOCATION_ONLY = 7,
355 MOD_KIND_EXCEPTION_ONLY = 8,
357 MOD_KIND_ASSEMBLY_ONLY = 11,
358 MOD_KIND_SOURCE_FILE_ONLY = 12,
359 MOD_KIND_TYPE_NAME_ONLY = 13,
375 STEP_FILTER_NONE = 0,
376 STEP_FILTER_STATIC_CTOR = 1,
377 STEP_FILTER_DEBUGGER_HIDDEN = 2,
378 STEP_FILTER_DEBUGGER_STEP_THROUGH = 4,
379 STEP_FILTER_DEBUGGER_NON_USER_CODE = 8
383 TOKEN_TYPE_STRING = 0,
385 TOKEN_TYPE_FIELD = 2,
386 TOKEN_TYPE_METHOD = 3,
387 TOKEN_TYPE_UNKNOWN = 4
391 VALUE_TYPE_ID_NULL = 0xf0,
392 VALUE_TYPE_ID_TYPE = 0xf1,
393 VALUE_TYPE_ID_PARENT_VTYPE = 0xf2
397 FRAME_FLAG_DEBUGGER_INVOKE = 1,
398 FRAME_FLAG_NATIVE_TRANSITION = 2
402 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
403 INVOKE_FLAG_SINGLE_THREADED = 2
407 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
408 } BindingFlagsExtensions;
412 CMD_VM_ALL_THREADS = 2,
417 CMD_VM_INVOKE_METHOD = 7,
418 CMD_VM_SET_PROTOCOL_VERSION = 8,
419 CMD_VM_ABORT_INVOKE = 9,
420 CMD_VM_SET_KEEPALIVE = 10,
421 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
422 CMD_VM_GET_TYPES = 12,
423 CMD_VM_INVOKE_METHODS = 13,
424 CMD_VM_START_BUFFERING = 14,
425 CMD_VM_STOP_BUFFERING = 15
429 CMD_THREAD_GET_FRAME_INFO = 1,
430 CMD_THREAD_GET_NAME = 2,
431 CMD_THREAD_GET_STATE = 3,
432 CMD_THREAD_GET_INFO = 4,
433 CMD_THREAD_GET_ID = 5,
434 CMD_THREAD_GET_TID = 6,
435 CMD_THREAD_SET_IP = 7
439 CMD_EVENT_REQUEST_SET = 1,
440 CMD_EVENT_REQUEST_CLEAR = 2,
441 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
449 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
450 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
451 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
452 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
453 CMD_APPDOMAIN_CREATE_STRING = 5,
454 CMD_APPDOMAIN_GET_CORLIB = 6,
455 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
459 CMD_ASSEMBLY_GET_LOCATION = 1,
460 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
461 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
462 CMD_ASSEMBLY_GET_OBJECT = 4,
463 CMD_ASSEMBLY_GET_TYPE = 5,
464 CMD_ASSEMBLY_GET_NAME = 6
468 CMD_MODULE_GET_INFO = 1,
472 CMD_FIELD_GET_INFO = 1,
476 CMD_METHOD_GET_NAME = 1,
477 CMD_METHOD_GET_DECLARING_TYPE = 2,
478 CMD_METHOD_GET_DEBUG_INFO = 3,
479 CMD_METHOD_GET_PARAM_INFO = 4,
480 CMD_METHOD_GET_LOCALS_INFO = 5,
481 CMD_METHOD_GET_INFO = 6,
482 CMD_METHOD_GET_BODY = 7,
483 CMD_METHOD_RESOLVE_TOKEN = 8,
484 CMD_METHOD_GET_CATTRS = 9,
485 CMD_METHOD_MAKE_GENERIC_METHOD = 10
489 CMD_TYPE_GET_INFO = 1,
490 CMD_TYPE_GET_METHODS = 2,
491 CMD_TYPE_GET_FIELDS = 3,
492 CMD_TYPE_GET_VALUES = 4,
493 CMD_TYPE_GET_OBJECT = 5,
494 CMD_TYPE_GET_SOURCE_FILES = 6,
495 CMD_TYPE_SET_VALUES = 7,
496 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
497 CMD_TYPE_GET_PROPERTIES = 9,
498 CMD_TYPE_GET_CATTRS = 10,
499 CMD_TYPE_GET_FIELD_CATTRS = 11,
500 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
501 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
502 CMD_TYPE_GET_VALUES_2 = 14,
503 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
504 CMD_TYPE_GET_INTERFACES = 16,
505 CMD_TYPE_GET_INTERFACE_MAP = 17,
506 CMD_TYPE_IS_INITIALIZED = 18,
507 CMD_TYPE_CREATE_INSTANCE = 19
511 CMD_STACK_FRAME_GET_VALUES = 1,
512 CMD_STACK_FRAME_GET_THIS = 2,
513 CMD_STACK_FRAME_SET_VALUES = 3
517 CMD_ARRAY_REF_GET_LENGTH = 1,
518 CMD_ARRAY_REF_GET_VALUES = 2,
519 CMD_ARRAY_REF_SET_VALUES = 3,
523 CMD_STRING_REF_GET_VALUE = 1,
524 CMD_STRING_REF_GET_LENGTH = 2,
525 CMD_STRING_REF_GET_CHARS = 3
529 CMD_OBJECT_REF_GET_TYPE = 1,
530 CMD_OBJECT_REF_GET_VALUES = 2,
531 CMD_OBJECT_REF_IS_COLLECTED = 3,
532 CMD_OBJECT_REF_GET_ADDRESS = 4,
533 CMD_OBJECT_REF_GET_DOMAIN = 5,
534 CMD_OBJECT_REF_SET_VALUES = 6,
535 CMD_OBJECT_REF_GET_INFO = 7,
541 int count; /* For kind == MOD_KIND_COUNT */
542 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
543 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
544 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
545 GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
546 GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
547 StepFilter filter; /* For kind == MOD_KIND_STEP */
549 gboolean caught, uncaught, subclasses; /* For kind == MOD_KIND_EXCEPTION_ONLY */
558 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
562 * Describes a single step request.
566 MonoInternalThread *thread;
572 MonoMethod *last_method;
574 /* Whenever single stepping is performed using start/stop_single_stepping () */
576 /* The list of breakpoints used to implement step-over */
578 /* The number of frames at the start of a step-over */
583 * Contains additional information for an event
586 /* For EVENT_KIND_EXCEPTION */
588 MonoContext catch_ctx;
590 /* For EVENT_KIND_USER_LOG */
592 char *category, *message;
593 /* For EVENT_KIND_TYPE_LOAD */
597 /* Dummy structure used for the profiler callbacks */
603 guint8 *buf, *p, *end;
606 typedef struct ReplyPacket {
612 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
615 #define get_last_sock_error() WSAGetLastError()
616 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
617 #define MONO_EINTR WSAEINTR
619 #define get_last_sock_error() errno
620 #define MONO_EWOULDBLOCK EWOULDBLOCK
621 #define MONO_EINTR EINTR
624 #define CHECK_PROTOCOL_VERSION(major,minor) \
625 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
631 static AgentConfig agent_config;
634 * Whenever the agent is fully initialized.
635 * When using the onuncaught or onthrow options, only some parts of the agent are
636 * initialized on startup, and the full initialization which includes connection
637 * establishment and the startup of the agent thread is only done in response to
640 static gint32 inited;
642 #ifndef DISABLE_SOCKET_TRANSPORT
644 static int listen_fd;
647 static int packet_id = 0;
649 static int objref_id = 0;
651 static int event_request_id = 0;
653 static int frame_id = 0;
655 static GPtrArray *event_requests;
657 static MonoNativeTlsKey debugger_tls_id;
659 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
661 /* Maps MonoInternalThread -> DebuggerTlsData */
662 static MonoGHashTable *thread_to_tls;
664 /* Maps tid -> MonoInternalThread */
665 static MonoGHashTable *tid_to_thread;
667 /* Maps tid -> MonoThread (not MonoInternalThread) */
668 static MonoGHashTable *tid_to_thread_obj;
670 static gsize debugger_thread_id;
672 static HANDLE debugger_thread_handle;
674 static int log_level;
676 static gboolean embedding;
678 static FILE *log_file;
680 /* Assemblies whose assembly load event has no been sent yet */
681 /* Protected by the dbg lock */
682 static GPtrArray *pending_assembly_loads;
684 /* Whenever the debugger thread has exited */
685 static gboolean debugger_thread_exited;
687 /* Cond variable used to wait for debugger_thread_exited becoming true */
688 static mono_cond_t debugger_thread_exited_cond;
690 /* Mutex for the cond var above */
691 static mono_mutex_t debugger_thread_exited_mutex;
693 static DebuggerProfiler debugger_profiler;
695 /* The single step request instance */
696 static SingleStepReq *ss_req = NULL;
697 static gpointer ss_invoke_addr = NULL;
699 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
700 /* Number of single stepping operations in progress */
704 /* The protocol version of the client */
705 static int major_version, minor_version;
707 /* Whenever the variables above are set by the client */
708 static gboolean protocol_version_set;
710 /* A hash table containing all active domains */
711 static GHashTable *domains;
713 /* The number of times the runtime is suspended */
714 static gint32 suspend_count;
716 /* Whenever to buffer reply messages and send them together */
717 static gboolean buffer_replies;
719 /* Buffered reply packets */
720 static ReplyPacket reply_packets [128];
723 #define dbg_lock() EnterCriticalSection (&debug_mutex)
724 #define dbg_unlock() LeaveCriticalSection (&debug_mutex)
725 static CRITICAL_SECTION debug_mutex;
727 static void transport_init (void);
728 static void transport_connect (const char *address);
729 static gboolean transport_handshake (void);
730 static void register_transport (DebuggerTransport *trans);
732 static guint32 WINAPI debugger_thread (void *arg);
734 static void runtime_initialized (MonoProfiler *prof);
736 static void runtime_shutdown (MonoProfiler *prof);
738 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
740 static void thread_end (MonoProfiler *prof, uintptr_t tid);
742 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
744 static void appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain);
746 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
748 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
750 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
752 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
754 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
756 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
758 static void emit_assembly_load (gpointer assembly, gpointer user_data);
760 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
762 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
764 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
766 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
768 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
770 static void start_single_stepping (void);
772 static void stop_single_stepping (void);
774 static void suspend_current (void);
776 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
778 static void clear_types_for_assembly (MonoAssembly *assembly);
780 static void clear_breakpoints_for_domain (MonoDomain *domain);
782 static void process_profiler_event (EventKind event, gpointer arg);
784 /* Submodule init/cleanup */
785 static void breakpoints_init (void);
786 static void breakpoints_cleanup (void);
788 static void objrefs_init (void);
789 static void objrefs_cleanup (void);
791 static void ids_init (void);
792 static void ids_cleanup (void);
794 static void suspend_init (void);
796 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch);
797 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
798 static void ss_destroy (SingleStepReq *req);
800 static void start_debugger_thread (void);
801 static void stop_debugger_thread (void);
803 static void finish_agent_init (gboolean on_startup);
805 static void process_profiler_event (EventKind event, gpointer arg);
807 static void invalidate_frames (DebuggerTlsData *tls);
809 #ifndef DISABLE_SOCKET_TRANSPORT
811 register_socket_transport (void);
815 parse_address (char *address, char **host, int *port)
817 char *pos = strchr (address, ':');
819 if (pos == NULL || pos == address)
822 *host = g_malloc (pos - address + 1);
823 strncpy (*host, address, pos - address);
824 (*host) [pos - address] = '\0';
826 *port = atoi (pos + 1);
834 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
835 fprintf (stderr, "Available options:\n");
836 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
837 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
838 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
839 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
840 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
841 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
842 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
843 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
844 fprintf (stderr, " setpgid=y/n\t\t\tWhether to call setpid(0, 0) after startup.\n");
845 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
849 parse_flag (const char *option, char *flag)
851 if (!strcmp (flag, "y"))
853 else if (!strcmp (flag, "n"))
856 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
863 mono_debugger_agent_parse_options (char *options)
870 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
871 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
875 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
877 options = g_strdup_printf ("%s,%s", options, extra);
879 agent_config.enabled = TRUE;
880 agent_config.suspend = TRUE;
881 agent_config.server = FALSE;
882 agent_config.defer = FALSE;
883 agent_config.address = NULL;
885 //agent_config.log_level = 10;
887 args = g_strsplit (options, ",", -1);
888 for (ptr = args; ptr && *ptr; ptr ++) {
891 if (strncmp (arg, "transport=", 10) == 0) {
892 agent_config.transport = g_strdup (arg + 10);
893 } else if (strncmp (arg, "address=", 8) == 0) {
894 agent_config.address = g_strdup (arg + 8);
895 } else if (strncmp (arg, "loglevel=", 9) == 0) {
896 agent_config.log_level = atoi (arg + 9);
897 } else if (strncmp (arg, "logfile=", 8) == 0) {
898 agent_config.log_file = g_strdup (arg + 8);
899 } else if (strncmp (arg, "suspend=", 8) == 0) {
900 agent_config.suspend = parse_flag ("suspend", arg + 8);
901 } else if (strncmp (arg, "server=", 7) == 0) {
902 agent_config.server = parse_flag ("server", arg + 7);
903 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
904 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
905 } else if (strncmp (arg, "onthrow=", 8) == 0) {
906 /* We support multiple onthrow= options */
907 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
908 } else if (strncmp (arg, "onthrow", 7) == 0) {
909 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
910 } else if (strncmp (arg, "help", 4) == 0) {
913 } else if (strncmp (arg, "timeout=", 8) == 0) {
914 agent_config.timeout = atoi (arg + 8);
915 } else if (strncmp (arg, "launch=", 7) == 0) {
916 agent_config.launch = g_strdup (arg + 7);
917 } else if (strncmp (arg, "embedding=", 10) == 0) {
918 agent_config.embedding = atoi (arg + 10) == 1;
919 } else if (strncmp (arg, "keepalive=", 10) == 0) {
920 agent_config.keepalive = atoi (arg + 10);
921 } else if (strncmp (arg, "setpgid=", 8) == 0) {
922 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
929 if (agent_config.server && !agent_config.suspend) {
930 /* Waiting for deferred attachment */
931 agent_config.defer = TRUE;
932 if (agent_config.address == NULL) {
933 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (getpid () % 1000));
937 //agent_config.log_level = 0;
939 if (agent_config.transport == NULL) {
940 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
944 if (agent_config.address == NULL && !agent_config.server) {
945 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
950 if (!strcmp (agent_config.transport, "dt_socket")) {
951 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
952 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
959 mono_debugger_agent_init (void)
961 InitializeCriticalSection (&debug_mutex);
963 if (!agent_config.enabled)
968 /* Need to know whenever a thread has acquired the loader mutex */
969 mono_loader_lock_track_ownership (TRUE);
971 event_requests = g_ptr_array_new ();
973 mono_mutex_init (&debugger_thread_exited_mutex);
974 mono_cond_init (&debugger_thread_exited_cond, NULL);
976 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
977 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
978 mono_profiler_install_runtime_initialized (runtime_initialized);
979 mono_profiler_install_appdomain (NULL, appdomain_load, appdomain_start_unload, appdomain_unload);
980 mono_profiler_install_thread (thread_startup, thread_end);
981 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
982 mono_profiler_install_jit_end (jit_end);
983 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
985 mono_native_tls_alloc (&debugger_tls_id, NULL);
987 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
988 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls);
990 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
991 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread);
993 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
994 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj);
996 pending_assembly_loads = g_ptr_array_new ();
997 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
999 log_level = agent_config.log_level;
1001 embedding = agent_config.embedding;
1002 disconnected = TRUE;
1004 if (agent_config.log_file) {
1005 log_file = fopen (agent_config.log_file, "w+");
1007 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
1016 breakpoints_init ();
1019 mini_get_debug_options ()->gen_seq_points = TRUE;
1021 * This is needed because currently we don't handle liveness info.
1023 mini_get_debug_options ()->mdb_optimizations = TRUE;
1025 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
1026 /* This is needed because we can't set local variables in registers yet */
1027 mono_disable_optimizations (MONO_OPT_LINEARS);
1031 * The stack walk done from thread_interrupt () needs to be signal safe, but it
1032 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
1033 * safe (#3411). So load AOT info eagerly when the debugger is running as a
1036 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
1039 if (agent_config.setpgid)
1043 if (!agent_config.onuncaught && !agent_config.onthrow)
1044 finish_agent_init (TRUE);
1048 * finish_agent_init:
1050 * Finish the initialization of the agent. This involves connecting the transport
1051 * and starting the agent thread. This is either done at startup, or
1052 * in response to some event like an unhandled exception.
1055 finish_agent_init (gboolean on_startup)
1059 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
1062 if (agent_config.launch) {
1065 // FIXME: Generated address
1066 // FIXME: Races with transport_connect ()
1068 argv [0] = agent_config.launch;
1069 argv [1] = agent_config.transport;
1070 argv [2] = agent_config.address;
1073 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1075 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1080 transport_connect (agent_config.address);
1083 /* Do some which is usually done after sending the VMStart () event */
1084 vm_start_event_sent = TRUE;
1085 start_debugger_thread ();
1090 mono_debugger_agent_cleanup (void)
1095 stop_debugger_thread ();
1097 breakpoints_cleanup ();
1101 mono_mutex_destroy (&debugger_thread_exited_mutex);
1102 mono_cond_destroy (&debugger_thread_exited_cond);
1109 #ifndef DISABLE_SOCKET_TRANSPORT
1114 * recv() + handle incomplete reads and EINTR
1117 socket_transport_recv (void *buf, int len)
1123 static gint32 last_keepalive;
1128 res = recv (fd, (char *) buf + total, len - total, flags);
1131 if (agent_config.keepalive) {
1132 gboolean need_keepalive = FALSE;
1133 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1134 need_keepalive = TRUE;
1135 } else if (res == -1) {
1136 /* This could happen if recv () is interrupted repeatedly */
1137 msecs = mono_msec_ticks ();
1138 if (msecs - last_keepalive >= agent_config.keepalive) {
1139 need_keepalive = TRUE;
1140 last_keepalive = msecs;
1143 if (need_keepalive) {
1144 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1148 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1153 #define HAVE_GETADDRINFO 1
1157 set_keepalive (void)
1162 if (!agent_config.keepalive || !conn_fd)
1165 tv.tv_sec = agent_config.keepalive / 1000;
1166 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1168 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1169 g_assert (result >= 0);
1173 socket_transport_accept (int socket_fd)
1175 conn_fd = accept (socket_fd, NULL, NULL);
1176 if (conn_fd == -1) {
1177 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1179 DEBUG (1, fprintf (log_file, "Accepted connection from client, connection fd=%d.\n", conn_fd));
1186 socket_transport_send (void *data, int len)
1191 res = send (conn_fd, data, len, 0);
1192 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1200 * socket_transport_connect:
1202 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1205 socket_transport_connect (const char *address)
1207 #ifdef HAVE_GETADDRINFO
1208 struct addrinfo hints;
1209 struct addrinfo *result, *rp;
1211 struct hostent *result;
1213 int sfd = -1, s, res;
1214 char port_string [128];
1218 if (agent_config.address) {
1219 res = parse_address (agent_config.address, &host, &port);
1220 g_assert (res == 0);
1230 sprintf (port_string, "%d", port);
1232 mono_network_init ();
1234 /* Obtain address(es) matching host/port */
1235 #ifdef HAVE_GETADDRINFO
1236 memset (&hints, 0, sizeof (struct addrinfo));
1237 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
1238 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
1240 hints.ai_protocol = 0; /* Any protocol */
1242 s = getaddrinfo (host, port_string, &hints, &result);
1244 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %s\n", host, port, gai_strerror (s));
1248 /* The PS3 doesn't even have _r or hstrerror () */
1249 result = gethostbyname (host);
1251 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, h_errno);
1256 if (agent_config.server) {
1257 #ifdef HAVE_GETADDRINFO
1258 /* Wait for a connection */
1260 struct sockaddr_in addr;
1263 /* No address, generate one */
1264 sfd = socket (AF_INET, SOCK_STREAM, 0);
1267 /* This will bind the socket to a random port */
1268 res = listen (sfd, 16);
1270 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1275 addrlen = sizeof (addr);
1276 memset (&addr, 0, sizeof (addr));
1277 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1278 g_assert (res == 0);
1280 host = (char*)"127.0.0.1";
1281 port = ntohs (addr.sin_port);
1283 /* Emit the address to stdout */
1284 /* FIXME: Should print another interface, not localhost */
1285 printf ("%s:%d\n", host, port);
1287 /* Listen on the provided address */
1288 for (rp = result; rp != NULL; rp = rp->ai_next) {
1291 sfd = socket (rp->ai_family, rp->ai_socktype,
1296 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1299 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
1303 res = listen (sfd, 16);
1312 * this function is not present on win2000 which we still support, and the
1313 * workaround described here:
1314 * http://msdn.microsoft.com/en-us/library/ms737931(VS.85).aspx
1315 * only works with MSVC.
1317 #ifdef HAVE_GETADDRINFO
1318 freeaddrinfo (result);
1323 if (agent_config.defer)
1326 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
1328 if (agent_config.timeout) {
1333 tv.tv_usec = agent_config.timeout * 1000;
1335 FD_SET (sfd, &readfds);
1336 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1338 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1343 conn_fd = socket_transport_accept (sfd);
1347 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
1350 #endif /* HAVE_GETADDRINFO */
1352 /* Connect to the specified address */
1353 #ifdef HAVE_GETADDRINFO
1354 /* FIXME: Respect the timeout */
1355 for (rp = result; rp != NULL; rp = rp->ai_next) {
1356 sfd = socket (rp->ai_family, rp->ai_socktype,
1361 if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
1362 break; /* Success */
1368 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1372 sfd = socket (result->h_addrtype, SOCK_STREAM, 0);
1374 g_assert_not_reached ();
1375 res = connect (sfd, (void*)result->h_addr_list [0], result->h_length);
1377 g_assert_not_reached ();
1383 /* See the comment above */
1384 #ifdef HAVE_GETADDRINFO
1385 freeaddrinfo (result);
1390 if (!transport_handshake ())
1395 socket_transport_close1 (void)
1397 /* This will interrupt the agent thread */
1398 /* Close the read part only so it can still send back replies */
1399 /* Also shut down the connection listener so that we can exit normally */
1401 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1402 shutdown (conn_fd, SD_BOTH);
1403 shutdown (listen_fd, SD_BOTH);
1404 closesocket (listen_fd);
1406 shutdown (conn_fd, SHUT_RD);
1407 shutdown (listen_fd, SHUT_RDWR);
1413 socket_transport_close2 (void)
1416 shutdown (conn_fd, SD_BOTH);
1418 shutdown (conn_fd, SHUT_RDWR);
1423 register_socket_transport (void)
1425 DebuggerTransport trans;
1427 trans.name = "dt_socket";
1428 trans.connect = socket_transport_connect;
1429 trans.close1 = socket_transport_close1;
1430 trans.close2 = socket_transport_close2;
1431 trans.send = socket_transport_send;
1432 trans.recv = socket_transport_recv;
1434 register_transport (&trans);
1437 #endif /* DISABLE_SOCKET_TRANSPORT */
1443 #define MAX_TRANSPORTS 16
1445 static DebuggerTransport *transport;
1447 static DebuggerTransport transports [MAX_TRANSPORTS];
1448 static int ntransports;
1451 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1454 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1456 register_transport (trans);
1460 register_transport (DebuggerTransport *trans)
1462 g_assert (ntransports < MAX_TRANSPORTS);
1464 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1469 transport_init (void)
1473 #ifndef DISABLE_SOCKET_TRANSPORT
1474 register_socket_transport ();
1477 for (i = 0; i < ntransports; ++i) {
1478 if (!strcmp (agent_config.transport, transports [i].name))
1481 if (i == ntransports) {
1482 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1483 for (i = 0; i < ntransports; ++i)
1484 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1485 fprintf (stderr, "\n");
1488 transport = &transports [i];
1492 transport_connect (const char *address)
1494 transport->connect (address);
1498 transport_close1 (void)
1500 transport->close1 ();
1504 transport_close2 (void)
1506 transport->close2 ();
1510 transport_send (void *buf, int len)
1512 return transport->send (buf, len);
1516 transport_recv (void *buf, int len)
1518 return transport->recv (buf, len);
1522 mono_debugger_agent_transport_handshake (void)
1524 return transport_handshake ();
1528 transport_handshake (void)
1530 char handshake_msg [128];
1534 disconnected = TRUE;
1536 /* Write handshake message */
1537 sprintf (handshake_msg, "DWP-Handshake");
1539 res = transport_send (handshake_msg, strlen (handshake_msg));
1540 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1541 g_assert (res != -1);
1544 res = transport_recv (buf, strlen (handshake_msg));
1545 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg) != 0))) {
1546 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1551 * To support older clients, the client sends its protocol version after connecting
1552 * using a command. Until that is received, default to our protocol version.
1554 major_version = MAJOR_VERSION;
1555 minor_version = MINOR_VERSION;
1556 protocol_version_set = FALSE;
1558 #ifndef DISABLE_SOCKET_TRANSPORT
1559 // FIXME: Move this somewhere else
1561 * Set TCP_NODELAY on the socket so the client receives events/command
1562 * results immediately.
1566 int result = setsockopt (conn_fd,
1571 g_assert (result >= 0);
1577 disconnected = FALSE;
1582 stop_debugger_thread (void)
1587 transport_close1 ();
1590 * Wait for the thread to exit.
1592 * If we continue with the shutdown without waiting for it, then the client might
1593 * not receive an answer to its last command like a resume.
1594 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
1597 //WaitForSingleObject (debugger_thread_handle, INFINITE);
1598 if (GetCurrentThreadId () != debugger_thread_id) {
1600 mono_mutex_lock (&debugger_thread_exited_mutex);
1601 if (!debugger_thread_exited) {
1603 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
1604 mono_mutex_unlock (&debugger_thread_exited_mutex);
1606 mono_mutex_lock (&debugger_thread_exited_mutex);
1609 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1612 mono_mutex_unlock (&debugger_thread_exited_mutex);
1613 } while (!debugger_thread_exited);
1616 transport_close2 ();
1620 start_debugger_thread (void)
1622 debugger_thread_handle = mono_threads_create_thread (debugger_thread, NULL, 0, 0, NULL);
1623 g_assert (debugger_thread_handle);
1627 * Functions to decode protocol data
1631 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1634 g_assert (*endbuf <= limit);
1639 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1642 g_assert (*endbuf <= limit);
1644 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1647 static inline gint64
1648 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1650 guint32 high = decode_int (buf, &buf, limit);
1651 guint32 low = decode_int (buf, &buf, limit);
1655 return ((((guint64)high) << 32) | ((guint64)low));
1659 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1661 return decode_int (buf, endbuf, limit);
1665 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1667 int len = decode_int (buf, &buf, limit);
1675 s = g_malloc (len + 1);
1678 memcpy (s, buf, len);
1687 * Functions to encode protocol data
1691 buffer_init (Buffer *buf, int size)
1693 buf->buf = g_malloc (size);
1695 buf->end = buf->buf + size;
1699 buffer_len (Buffer *buf)
1701 return buf->p - buf->buf;
1705 buffer_make_room (Buffer *buf, int size)
1707 if (buf->end - buf->p < size) {
1708 int new_size = buf->end - buf->buf + size + 32;
1709 guint8 *p = g_realloc (buf->buf, new_size);
1710 size = buf->p - buf->buf;
1713 buf->end = buf->buf + new_size;
1718 buffer_add_byte (Buffer *buf, guint8 val)
1720 buffer_make_room (buf, 1);
1726 buffer_add_short (Buffer *buf, guint32 val)
1728 buffer_make_room (buf, 2);
1729 buf->p [0] = (val >> 8) & 0xff;
1730 buf->p [1] = (val >> 0) & 0xff;
1735 buffer_add_int (Buffer *buf, guint32 val)
1737 buffer_make_room (buf, 4);
1738 buf->p [0] = (val >> 24) & 0xff;
1739 buf->p [1] = (val >> 16) & 0xff;
1740 buf->p [2] = (val >> 8) & 0xff;
1741 buf->p [3] = (val >> 0) & 0xff;
1746 buffer_add_long (Buffer *buf, guint64 l)
1748 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1749 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1753 buffer_add_id (Buffer *buf, int id)
1755 buffer_add_int (buf, (guint64)id);
1759 buffer_add_data (Buffer *buf, guint8 *data, int len)
1761 buffer_make_room (buf, len);
1762 memcpy (buf->p, data, len);
1767 buffer_add_string (Buffer *buf, const char *str)
1772 buffer_add_int (buf, 0);
1775 buffer_add_int (buf, len);
1776 buffer_add_data (buf, (guint8*)str, len);
1781 buffer_add_buffer (Buffer *buf, Buffer *data)
1783 buffer_add_data (buf, data->buf, buffer_len (data));
1787 buffer_free (Buffer *buf)
1793 send_packet (int command_set, int command, Buffer *data)
1799 id = InterlockedIncrement (&packet_id);
1801 len = data->p - data->buf + 11;
1802 buffer_init (&buf, len);
1803 buffer_add_int (&buf, len);
1804 buffer_add_int (&buf, id);
1805 buffer_add_byte (&buf, 0); /* flags */
1806 buffer_add_byte (&buf, command_set);
1807 buffer_add_byte (&buf, command);
1808 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1810 res = transport_send (buf.buf, len);
1818 send_reply_packets (int npackets, ReplyPacket *packets)
1825 for (i = 0; i < npackets; ++i)
1826 len += buffer_len (packets [i].data) + 11;
1827 buffer_init (&buf, len);
1828 for (i = 0; i < npackets; ++i) {
1829 buffer_add_int (&buf, buffer_len (packets [i].data) + 11);
1830 buffer_add_int (&buf, packets [i].id);
1831 buffer_add_byte (&buf, 0x80); /* flags */
1832 buffer_add_byte (&buf, (packets [i].error >> 8) & 0xff);
1833 buffer_add_byte (&buf, packets [i].error);
1834 buffer_add_buffer (&buf, packets [i].data);
1836 res = transport_send (buf.buf, len);
1844 send_reply_packet (int id, int error, Buffer *data)
1848 memset (&packet, 0, sizeof (ReplyPacket));
1850 packet.error = error;
1853 return send_reply_packets (1, &packet);
1857 send_buffered_reply_packets (void)
1861 send_reply_packets (nreply_packets, reply_packets);
1862 for (i = 0; i < nreply_packets; ++i)
1863 buffer_free (reply_packets [i].data);
1864 DEBUG (1, fprintf (log_file, "[dbg] Sent %d buffered reply packets [at=%lx].\n", nreply_packets, (long)mono_100ns_ticks () / 10000));
1869 buffer_reply_packet (int id, int error, Buffer *data)
1873 if (nreply_packets == 128)
1874 send_buffered_reply_packets ();
1876 p = &reply_packets [nreply_packets];
1879 p->data = g_new0 (Buffer, 1);
1880 buffer_init (p->data, buffer_len (data));
1881 buffer_add_buffer (p->data, data);
1890 * Represents an object accessible by the debugger client.
1893 /* Unique id used in the wire protocol to refer to objects */
1896 * A weakref gc handle pointing to the object. The gc handle is used to
1897 * detect if the object was garbage collected.
1902 /* Maps objid -> ObjRef */
1903 static GHashTable *objrefs;
1904 static GHashTable *obj_to_objref;
1905 /* Protected by the dbg lock */
1906 static MonoGHashTable *suspended_objs;
1909 free_objref (gpointer value)
1913 mono_gchandle_free (o->handle);
1921 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1922 obj_to_objref = g_hash_table_new (NULL, NULL);
1923 suspended_objs = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
1924 MONO_GC_REGISTER_ROOT_FIXED (suspended_objs);
1928 objrefs_cleanup (void)
1930 g_hash_table_destroy (objrefs);
1935 * Return an ObjRef for OBJ.
1938 get_objref (MonoObject *obj)
1941 GSList *reflist = NULL, *l;
1947 if (suspend_count) {
1949 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1952 mono_g_hash_table_insert (suspended_objs, obj, NULL);
1956 mono_loader_lock ();
1958 /* FIXME: The tables can grow indefinitely */
1960 if (mono_gc_is_moving ()) {
1962 * Objects can move, so use a hash table mapping hash codes to lists of
1963 * ObjRef structures.
1965 hash = mono_object_hash (obj);
1967 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1968 for (l = reflist; l; l = l->next) {
1970 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1971 mono_loader_unlock ();
1976 /* Use a hash table with masked pointers to internalize object references */
1977 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1978 /* ref might refer to a different object with the same addr which was GCd */
1979 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1980 mono_loader_unlock ();
1985 ref = g_new0 (ObjRef, 1);
1986 ref->id = InterlockedIncrement (&objref_id);
1987 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1989 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
1991 if (mono_gc_is_moving ()) {
1992 reflist = g_slist_append (reflist, ref);
1993 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
1995 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
1998 mono_loader_unlock ();
2004 true_pred (gpointer key, gpointer value, gpointer user_data)
2010 clear_suspended_objs (void)
2013 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
2018 get_objid (MonoObject *obj)
2020 return get_objref (obj)->id;
2024 * Set OBJ to the object identified by OBJID.
2025 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
2029 get_object_allow_null (int objid, MonoObject **obj)
2039 return ERR_INVALID_OBJECT;
2041 mono_loader_lock ();
2043 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
2046 *obj = mono_gchandle_get_target (ref->handle);
2047 mono_loader_unlock ();
2049 return ERR_INVALID_OBJECT;
2052 mono_loader_unlock ();
2053 return ERR_INVALID_OBJECT;
2058 get_object (int objid, MonoObject **obj)
2060 int err = get_object_allow_null (objid, obj);
2065 return ERR_INVALID_OBJECT;
2070 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
2072 return decode_id (buf, endbuf, limit);
2076 buffer_add_objid (Buffer *buf, MonoObject *o)
2078 buffer_add_id (buf, get_objid (o));
2097 * Represents a runtime structure accessible to the debugger client
2100 /* Unique id used in the wire protocol */
2102 /* Domain of the runtime structure, NULL if the domain was unloaded */
2109 MonoAssembly *assembly;
2110 MonoClassField *field;
2112 MonoProperty *property;
2117 /* Maps runtime structure -> Id */
2118 GHashTable *val_to_id [ID_NUM];
2119 /* Classes whose class load event has been sent */
2120 GHashTable *loaded_classes;
2121 /* Maps MonoClass->GPtrArray of file names */
2122 GHashTable *source_files;
2123 /* Maps source file basename -> GSList of classes */
2124 GHashTable *source_file_to_class;
2125 /* Same with ignore-case */
2126 GHashTable *source_file_to_class_ignorecase;
2130 /* Protected by the dbg lock */
2131 static GPtrArray *ids [ID_NUM];
2138 for (i = 0; i < ID_NUM; ++i)
2139 ids [i] = g_ptr_array_new ();
2147 for (i = 0; i < ID_NUM; ++i) {
2149 for (j = 0; j < ids [i]->len; ++j)
2150 g_free (g_ptr_array_index (ids [i], j));
2151 g_ptr_array_free (ids [i], TRUE);
2158 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2160 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
2162 GHashTableIter iter;
2163 GPtrArray *file_names;
2168 for (i = 0; i < ID_NUM; ++i)
2169 if (info->val_to_id [i])
2170 g_hash_table_destroy (info->val_to_id [i]);
2171 g_hash_table_destroy (info->loaded_classes);
2173 g_hash_table_iter_init (&iter, info->source_files);
2174 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2175 for (i = 0; i < file_names->len; ++i)
2176 g_free (g_ptr_array_index (file_names, i));
2177 g_ptr_array_free (file_names, TRUE);
2180 g_hash_table_iter_init (&iter, info->source_file_to_class);
2181 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2186 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2187 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2195 domain_jit_info (domain)->agent_info = NULL;
2197 /* Clear ids referencing structures in the domain */
2199 for (i = 0; i < ID_NUM; ++i) {
2201 for (j = 0; j < ids [i]->len; ++j) {
2202 Id *id = g_ptr_array_index (ids [i], j);
2203 if (id->domain == domain)
2210 mono_loader_lock ();
2211 g_hash_table_remove (domains, domain);
2212 mono_loader_unlock ();
2215 static AgentDomainInfo*
2216 get_agent_domain_info (MonoDomain *domain)
2218 AgentDomainInfo *info = NULL;
2220 mono_domain_lock (domain);
2222 info = domain_jit_info (domain)->agent_info;
2224 info = domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
2225 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2226 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2227 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2228 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2231 mono_domain_unlock (domain);
2237 get_id (MonoDomain *domain, IdType type, gpointer val)
2240 AgentDomainInfo *info;
2245 mono_loader_lock ();
2247 mono_domain_lock (domain);
2249 info = get_agent_domain_info (domain);
2251 if (info->val_to_id [type] == NULL)
2252 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2254 id = g_hash_table_lookup (info->val_to_id [type], val);
2256 mono_domain_unlock (domain);
2257 mono_loader_unlock ();
2263 id = g_new0 (Id, 1);
2265 id->id = ids [type]->len + 1;
2266 id->domain = domain;
2269 g_hash_table_insert (info->val_to_id [type], val, id);
2270 g_ptr_array_add (ids [type], id);
2274 mono_domain_unlock (domain);
2276 mono_loader_unlock ();
2281 static inline gpointer
2282 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
2286 int id = decode_id (buf, endbuf, limit);
2295 // FIXME: error handling
2297 g_assert (id > 0 && id <= ids [type]->len);
2299 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2302 if (res->domain == NULL) {
2303 DEBUG (0, fprintf (log_file, "ERR_UNLOADED, id=%d, type=%d.\n", id, type));
2304 *err = ERR_UNLOADED;
2309 *domain = res->domain;
2311 return res->data.val;
2315 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2317 int id = get_id (domain, type, val);
2319 buffer_add_id (buf, id);
2323 static inline MonoClass*
2324 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2328 klass = decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2329 if (G_UNLIKELY (log_level >= 2) && klass) {
2332 s = mono_type_full_name (&klass->byval_arg);
2333 DEBUG(2, fprintf (log_file, "[dbg] recv class [%s]\n", s));
2339 static inline MonoAssembly*
2340 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2342 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2345 static inline MonoImage*
2346 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2348 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2351 static inline MonoMethod*
2352 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2356 m = decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2357 if (G_UNLIKELY (log_level >= 2) && m) {
2360 s = mono_method_full_name (m, TRUE);
2361 DEBUG(2, fprintf (log_file, "[dbg] recv method [%s]\n", s));
2367 static inline MonoClassField*
2368 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2370 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2373 static inline MonoDomain*
2374 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2376 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2379 static inline MonoProperty*
2380 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2382 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2386 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2388 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2389 if (G_UNLIKELY (log_level >= 2) && klass) {
2392 s = mono_type_full_name (&klass->byval_arg);
2393 if (GetCurrentThreadId () == debugger_thread_id)
2394 DEBUG(2, fprintf (log_file, "[dbg] send class [%s]\n", s));
2396 DEBUG(2, fprintf (log_file, "[%p] send class [%s]\n", (gpointer)GetCurrentThreadId (), s));
2402 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2404 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2405 if (G_UNLIKELY (log_level >= 2) && method) {
2408 s = mono_method_full_name (method, 1);
2409 DEBUG(2, fprintf (log_file, "[dbg] send method [%s]\n", s));
2415 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2419 id = buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2420 if (G_UNLIKELY (log_level >= 2) && assembly)
2421 DEBUG(2, fprintf (log_file, "[dbg] send assembly [%s][%s][%d]\n", assembly->aname.name, domain->friendly_name, id));
2425 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2427 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2431 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2433 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2437 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2439 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2443 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2445 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2448 static void invoke_method (void);
2455 * save_thread_context:
2457 * Set CTX as the current threads context which is used for computing stack traces.
2458 * This function is signal-safe.
2461 save_thread_context (MonoContext *ctx)
2463 DebuggerTlsData *tls;
2465 tls = mono_native_tls_get_value (debugger_tls_id);
2469 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2471 mono_thread_state_init_from_current (&tls->context);
2474 /* Number of threads suspended */
2476 * If this is equal to the size of thread_to_tls, the runtime is considered
2479 static gint32 threads_suspend_count;
2481 static mono_mutex_t suspend_mutex;
2483 /* Cond variable used to wait for suspend_count becoming 0 */
2484 static mono_cond_t suspend_cond;
2486 /* Semaphore used to wait for a thread becoming suspended */
2487 static MonoSemType suspend_sem;
2492 mono_mutex_init (&suspend_mutex);
2493 mono_cond_init (&suspend_cond, NULL);
2494 MONO_SEM_INIT (&suspend_sem, 0);
2499 StackFrameInfo last_frame;
2500 gboolean last_frame_set;
2503 } GetLastFrameUserData;
2506 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2508 GetLastFrameUserData *data = user_data;
2510 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
2513 if (!data->last_frame_set) {
2514 /* Store the last frame */
2515 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2516 data->last_frame_set = TRUE;
2519 /* Store the context/lmf for the frame above the last frame */
2520 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2521 data->lmf = info->lmf;
2529 * Process interruption of a thread. If SIGCTX is set, process the current thread. If
2530 * INFO is set, process the thread described by INFO.
2531 * This should be signal safe.
2534 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, void *sigctx, MonoJitInfo *ji)
2538 MonoNativeThreadId tid;
2541 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2542 * guarantee the signal handler will be called that many times. Instead of tracking
2543 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2544 * has been requested that hasn't been handled yet, otherwise we can have threads
2545 * refuse to die when VM_EXIT is called
2547 #if defined(__APPLE__)
2548 if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
2552 * We use interrupt_count to determine whenever this interrupt should be processed
2553 * by us or the normal interrupt processing code in the signal handler.
2554 * There is no race here with notify_thread (), since the signal is sent after
2555 * incrementing interrupt_count.
2557 if (tls->interrupt_count == 0)
2560 InterlockedDecrement (&tls->interrupt_count);
2564 ip = mono_arch_ip_from_context (sigctx);
2566 ip = MONO_CONTEXT_GET_IP (&info->suspend_state.ctx);
2571 tid = mono_thread_info_get_tid (info);
2573 tid = (MonoNativeThreadId)GetCurrentThreadId ();
2575 // FIXME: Races when the thread leaves managed code before hitting a single step
2579 /* Running managed code, will be suspended by the single step code */
2580 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip));
2584 * Running native code, will be suspended when it returns to/enters
2585 * managed code. Treat it as already suspended.
2586 * This might interrupt the code in process_single_step_inner (), we use the
2587 * tls->suspending flag to avoid races when that happens.
2589 if (!tls->suspended && !tls->suspending) {
2591 GetLastFrameUserData data;
2593 // FIXME: printf is not signal safe, but this is only used during
2594 // debugger debugging
2596 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip));
2597 //save_thread_context (&ctx);
2600 /* Already terminated */
2604 * We are in a difficult position: we want to be able to provide stack
2605 * traces for this thread, but we can't use the current ctx+lmf, since
2606 * the thread is still running, so it might return to managed code,
2607 * making these invalid.
2608 * So we start a stack walk and save the first frame, along with the
2609 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2610 * suspended when it returns to managed code, so the parent's ctx should
2613 data.last_frame_set = FALSE;
2615 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
2617 * Don't pass MONO_UNWIND_ACTUAL_METHOD, its not signal safe, and
2618 * get_last_frame () doesn't need it, the last frame cannot be a ginst
2619 * since we are not in a JITted method.
2621 mono_walk_stack_with_ctx (get_last_frame, &ctx, MONO_UNWIND_NONE, &data);
2623 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, &info->suspend_state, MONO_UNWIND_SIGNAL_SAFE, &data);
2625 if (data.last_frame_set) {
2626 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2627 res = mono_thread_state_init_from_monoctx (&tls->async_state, &ctx);
2629 mono_thread_state_init_from_monoctx (&tls->context, &ctx);
2632 memcpy (&tls->async_state.ctx, &data.ctx, sizeof (MonoContext));
2633 tls->async_state.unwind_data [MONO_UNWIND_DATA_LMF] = data.lmf;
2634 tls->async_state.unwind_data [MONO_UNWIND_DATA_JIT_TLS] = tls->thread->jit_data;
2636 tls->async_state.valid = FALSE;
2639 mono_memory_barrier ();
2641 tls->suspended = TRUE;
2642 MONO_SEM_POST (&suspend_sem);
2649 * mono_debugger_agent_thread_interrupt:
2651 * Called by the abort signal handler.
2652 * Should be signal safe.
2655 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
2657 DebuggerTlsData *tls;
2662 tls = mono_native_tls_get_value (debugger_tls_id);
2664 DEBUG (1, fprintf (log_file, "[%p] Received interrupt with no TLS, continuing.\n", (gpointer)GetCurrentThreadId ()));
2668 return thread_interrupt (tls, NULL, sigctx, ji);
2672 static void CALLBACK notify_thread_apc (ULONG_PTR param)
2675 mono_debugger_agent_thread_interrupt (NULL, NULL);
2677 #endif /* HOST_WIN32 */
2680 * reset_native_thread_suspend_state:
2682 * Reset the suspended flag and state on native threads
2685 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2687 DebuggerTlsData *tls = value;
2689 if (!tls->really_suspended && tls->suspended) {
2690 tls->suspended = FALSE;
2692 * The thread might still be running if it was executing native code, so the state won't be invalided by
2693 * suspend_current ().
2695 tls->context.valid = FALSE;
2696 tls->async_state.valid = FALSE;
2697 invalidate_frames (tls);
2704 * Notify a thread that it needs to suspend.
2707 notify_thread (gpointer key, gpointer value, gpointer user_data)
2709 MonoInternalThread *thread = key;
2710 DebuggerTlsData *tls = value;
2711 gsize tid = thread->tid;
2714 if (GetCurrentThreadId () == tid || tls->terminated)
2717 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2720 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2721 * guarantee the signal handler will be called that many times. Instead of tracking
2722 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2723 * has been requested that hasn't been handled yet, otherwise we can have threads
2724 * refuse to die when VM_EXIT is called
2726 #if defined(__APPLE__)
2727 if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
2731 * Maybe we could use the normal interrupt infrastructure, but that does a lot
2732 * of things like breaking waits etc. which we don't want.
2734 InterlockedIncrement (&tls->interrupt_count);
2737 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2739 QueueUserAPC (notify_thread_apc, thread->handle, NULL);
2741 if (mono_thread_info_new_interrupt_enabled ()) {
2742 MonoThreadInfo *info;
2745 info = mono_thread_info_safe_suspend_sync ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE);
2747 DEBUG(1, fprintf (log_file, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2749 * Attached thread which died without detaching.
2751 tls->terminated = TRUE;
2753 ji = mono_jit_info_table_find (info->suspend_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], MONO_CONTEXT_GET_IP (&info->suspend_state.ctx));
2755 thread_interrupt (tls, info, NULL, ji);
2757 mono_thread_info_finish_suspend_and_resume (info);
2760 res = mono_thread_kill (thread, mono_thread_get_abort_signal ());
2762 DEBUG(1, fprintf (log_file, "[%p] mono_thread_kill () failed for %p: %d...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid, res));
2764 * Attached thread which died without detaching.
2766 tls->terminated = TRUE;
2773 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2775 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2779 if (mono_loader_lock_is_owned_by_self ()) {
2781 * Shortcut for the check in suspend_current (). This speeds up processing
2782 * when executing long running code inside the loader lock, i.e. assembly load
2788 if (debugger_thread_id == GetCurrentThreadId ())
2791 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2792 if (suspend_count - tls->resume_count > 0)
2793 tls->suspending = TRUE;
2795 DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2797 if (suspend_count - tls->resume_count == 0) {
2799 * We are executing a single threaded invoke but the single step for
2800 * suspending is still active.
2801 * FIXME: This slows down single threaded invokes.
2803 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
2807 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2809 /* Can't suspend in these methods */
2810 method = jinfo_get_method (ji);
2811 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2814 save_thread_context (ctx);
2822 * Increase the suspend count of the VM. While the suspend count is greater
2823 * than 0, runtime threads are suspended at certain points during execution.
2828 mono_loader_lock ();
2830 mono_mutex_lock (&suspend_mutex);
2834 DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
2836 if (suspend_count == 1) {
2837 // FIXME: Is it safe to call this inside the lock ?
2838 start_single_stepping ();
2839 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2842 mono_mutex_unlock (&suspend_mutex);
2844 if (suspend_count == 1)
2846 * Suspend creation of new threadpool threads, since they cannot run
2848 mono_thread_pool_suspend ();
2850 mono_loader_unlock ();
2856 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2864 g_assert (debugger_thread_id == GetCurrentThreadId ());
2866 mono_loader_lock ();
2868 mono_mutex_lock (&suspend_mutex);
2870 g_assert (suspend_count > 0);
2873 DEBUG(1, fprintf (log_file, "[%p] Resuming vm, suspend count=%d...\n", (gpointer)GetCurrentThreadId (), suspend_count));
2875 if (suspend_count == 0) {
2876 // FIXME: Is it safe to call this inside the lock ?
2877 stop_single_stepping ();
2878 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2881 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2882 err = mono_cond_broadcast (&suspend_cond);
2883 g_assert (err == 0);
2885 mono_mutex_unlock (&suspend_mutex);
2886 //g_assert (err == 0);
2888 if (suspend_count == 0)
2889 mono_thread_pool_resume ();
2891 mono_loader_unlock ();
2897 * Resume just one thread.
2900 resume_thread (MonoInternalThread *thread)
2903 DebuggerTlsData *tls;
2905 g_assert (debugger_thread_id == GetCurrentThreadId ());
2907 mono_loader_lock ();
2909 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2912 mono_mutex_lock (&suspend_mutex);
2914 g_assert (suspend_count > 0);
2916 DEBUG(1, fprintf (log_file, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid));
2918 tls->resume_count += suspend_count;
2921 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2922 * but only the one whose resume_count field is > 0 will be resumed.
2924 err = mono_cond_broadcast (&suspend_cond);
2925 g_assert (err == 0);
2927 mono_mutex_unlock (&suspend_mutex);
2928 //g_assert (err == 0);
2930 mono_loader_unlock ();
2934 invalidate_frames (DebuggerTlsData *tls)
2939 tls = mono_native_tls_get_value (debugger_tls_id);
2942 for (i = 0; i < tls->frame_count; ++i) {
2943 if (tls->frames [i]->jit)
2944 mono_debug_free_method_jit_info (tls->frames [i]->jit);
2945 g_free (tls->frames [i]);
2947 g_free (tls->frames);
2948 tls->frame_count = 0;
2955 * Suspend the current thread until the runtime is resumed. If the thread has a
2956 * pending invoke, then the invoke is executed before this function returns.
2959 suspend_current (void)
2962 DebuggerTlsData *tls;
2964 g_assert (debugger_thread_id != GetCurrentThreadId ());
2966 if (mono_loader_lock_is_owned_by_self ()) {
2968 * If we own the loader mutex, can't suspend until we release it, since the
2969 * whole runtime can deadlock otherwise.
2974 tls = mono_native_tls_get_value (debugger_tls_id);
2977 mono_mutex_lock (&suspend_mutex);
2979 tls->suspending = FALSE;
2980 tls->really_suspended = TRUE;
2982 if (!tls->suspended) {
2983 tls->suspended = TRUE;
2984 MONO_SEM_POST (&suspend_sem);
2987 DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
2989 while (suspend_count - tls->resume_count > 0) {
2991 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
2993 mono_mutex_unlock (&suspend_mutex);
2995 mono_mutex_lock (&suspend_mutex);
3001 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
3002 g_assert (err == 0);
3006 tls->suspended = FALSE;
3007 tls->really_suspended = FALSE;
3009 threads_suspend_count --;
3011 mono_mutex_unlock (&suspend_mutex);
3013 DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
3015 if (tls->pending_invoke) {
3016 /* Save the original context */
3017 tls->pending_invoke->has_ctx = TRUE;
3018 tls->pending_invoke->ctx = tls->context.ctx;
3023 /* The frame info becomes invalid after a resume */
3024 tls->context.valid = FALSE;
3025 tls->async_state.valid = FALSE;
3026 invalidate_frames (tls);
3030 count_thread (gpointer key, gpointer value, gpointer user_data)
3032 DebuggerTlsData *tls = value;
3034 if (!tls->suspended && !tls->terminated)
3035 *(int*)user_data = *(int*)user_data + 1;
3039 count_threads_to_wait_for (void)
3043 mono_loader_lock ();
3044 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
3045 mono_loader_unlock ();
3053 * Wait until the runtime is completely suspended.
3056 wait_for_suspend (void)
3058 int nthreads, nwait, err;
3059 gboolean waited = FALSE;
3061 // FIXME: Threads starting/stopping ?
3062 mono_loader_lock ();
3063 nthreads = mono_g_hash_table_size (thread_to_tls);
3064 mono_loader_unlock ();
3067 nwait = count_threads_to_wait_for ();
3069 DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
3070 err = MONO_SEM_WAIT (&suspend_sem);
3071 g_assert (err == 0);
3079 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
3085 * Return whenever the runtime is suspended.
3090 return count_threads_to_wait_for () == 0;
3093 static MonoSeqPointInfo*
3094 get_seq_points (MonoDomain *domain, MonoMethod *method)
3096 MonoSeqPointInfo *seq_points;
3098 mono_domain_lock (domain);
3099 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
3100 if (!seq_points && method->is_inflated) {
3101 /* generic sharing + aot */
3102 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (method));
3104 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mini_get_shared_method (method));
3106 mono_domain_unlock (domain);
3112 no_seq_points_found (MonoMethod *method)
3115 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3117 printf ("Unable to find seq points for method '%s'.\n", mono_method_full_name (method, TRUE));
3121 * find_next_seq_point_for_native_offset:
3123 * Find the first sequence point after NATIVE_OFFSET.
3126 find_next_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
3128 MonoSeqPointInfo *seq_points;
3131 seq_points = get_seq_points (domain, method);
3137 g_assert (seq_points);
3141 for (i = 0; i < seq_points->len; ++i) {
3142 if (seq_points->seq_points [i].native_offset >= native_offset)
3143 return &seq_points->seq_points [i];
3150 * find_prev_seq_point_for_native_offset:
3152 * Find the first sequence point before NATIVE_OFFSET.
3155 find_prev_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
3157 MonoSeqPointInfo *seq_points;
3160 seq_points = get_seq_points (domain, method);
3166 for (i = seq_points->len - 1; i >= 0; --i) {
3167 if (seq_points->seq_points [i].native_offset <= native_offset)
3168 return &seq_points->seq_points [i];
3177 * Find the sequence point corresponding to the IL offset IL_OFFSET, which
3178 * should be the location of a sequence point.
3180 static G_GNUC_UNUSED SeqPoint*
3181 find_seq_point (MonoDomain *domain, MonoMethod *method, gint32 il_offset, MonoSeqPointInfo **info)
3183 MonoSeqPointInfo *seq_points;
3188 seq_points = get_seq_points (domain, method);
3193 for (i = 0; i < seq_points->len; ++i) {
3194 if (seq_points->seq_points [i].il_offset == il_offset)
3195 return &seq_points->seq_points [i];
3202 DebuggerTlsData *tls;
3204 } ComputeFramesUserData;
3207 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3209 ComputeFramesUserData *ud = user_data;
3211 MonoMethod *method, *actual_method, *api_method;
3215 if (info->type != FRAME_TYPE_MANAGED) {
3216 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3217 /* Mark the last frame as an invoke frame */
3219 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3225 method = jinfo_get_method (info->ji);
3227 method = info->method;
3228 actual_method = info->actual_method;
3229 api_method = method;
3234 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3237 if (info->il_offset == -1) {
3238 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3239 if (ud->frames == NULL) {
3240 sp = find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL);
3242 info->il_offset = sp->il_offset;
3244 if (info->il_offset == -1)
3245 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3248 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));
3250 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3251 if (!CHECK_PROTOCOL_VERSION (2, 17))
3252 /* Older clients can't handle this flag */
3254 api_method = mono_marshal_method_from_wrapper (method);
3257 actual_method = api_method;
3258 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3261 frame = g_new0 (StackFrame, 1);
3262 frame->method = method;
3263 frame->actual_method = actual_method;
3264 frame->api_method = api_method;
3265 frame->il_offset = info->il_offset;
3266 frame->native_offset = info->native_offset;
3267 frame->flags = flags;
3268 frame->ji = info->ji;
3269 if (info->reg_locations)
3270 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3273 frame->has_ctx = TRUE;
3275 frame->domain = info->domain;
3277 ud->frames = g_slist_append (ud->frames, frame);
3283 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3285 ComputeFramesUserData *ud = user_data;
3288 * 'tls->filter_ctx' is the location of the throw site.
3290 * mono_walk_stack() will never actually hit the throw site, but unwind
3291 * directly from the filter to the call site; we abort stack unwinding here
3292 * once this happens and resume from the throw site.
3295 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3298 return process_frame (info, ctx, user_data);
3302 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3304 ComputeFramesUserData user_data;
3306 int i, findex, new_frame_count;
3307 StackFrame **new_frames, *f;
3308 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3310 // FIXME: Locking on tls
3311 if (tls->frames && tls->frames_up_to_date)
3314 DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
3316 user_data.tls = tls;
3317 user_data.frames = NULL;
3318 if (tls->terminated) {
3319 tls->frame_count = 0;
3321 } if (!tls->really_suspended && tls->async_state.valid) {
3322 /* Have to use the state saved by the signal handler */
3323 process_frame (&tls->async_last_frame, NULL, &user_data);
3324 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3325 } else if (tls->filter_state.valid) {
3327 * We are inside an exception filter.
3329 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3331 if (tls->context.valid)
3332 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3334 * After that, we resume unwinding from the location where the exception has been thrown.
3336 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3337 } else if (tls->context.valid) {
3338 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3341 tls->frame_count = 0;
3345 new_frame_count = g_slist_length (user_data.frames);
3346 new_frames = g_new0 (StackFrame*, new_frame_count);
3348 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3352 * Reuse the id for already existing stack frames, so invokes don't invalidate
3353 * the still valid stack frames.
3355 for (i = 0; i < tls->frame_count; ++i) {
3356 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3357 f->id = tls->frames [i]->id;
3362 if (i >= tls->frame_count)
3363 f->id = InterlockedIncrement (&frame_id);
3365 new_frames [findex ++] = f;
3368 g_slist_free (user_data.frames);
3370 invalidate_frames (tls);
3372 tls->frames = new_frames;
3373 tls->frame_count = new_frame_count;
3374 tls->frames_up_to_date = TRUE;
3378 * GHFunc to emit an appdomain creation event
3379 * @param key Don't care
3380 * @param value A loaded appdomain
3381 * @param user_data Don't care
3384 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3386 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3387 g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
3391 * GHFunc to emit a thread start event
3392 * @param key A thread id
3393 * @param value A thread object
3394 * @param user_data Don't care
3397 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3399 if (GPOINTER_TO_INT (key) != debugger_thread_id)
3400 process_profiler_event (EVENT_KIND_THREAD_START, value);
3404 * GFunc to emit an assembly load event
3405 * @param value A loaded assembly
3406 * @param user_data Don't care
3409 emit_assembly_load (gpointer value, gpointer user_data)
3411 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3415 * GFunc to emit a type load event
3416 * @param value A loaded type
3417 * @param user_data Don't care
3420 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3422 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3426 strdup_tolower (char *s)
3431 for (p = s2; *p; ++p)
3441 * create_event_list:
3443 * Return a list of event request ids matching EVENT, starting from REQS, which
3444 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3446 * We return request ids, instead of requests, to simplify threading, since
3447 * requests could be deleted anytime when the loader lock is not held.
3448 * LOCKING: Assumes the loader lock is held.
3451 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3454 GSList *events = NULL;
3456 *suspend_policy = SUSPEND_POLICY_NONE;
3459 reqs = event_requests;
3464 for (i = 0; i < reqs->len; ++i) {
3465 EventRequest *req = g_ptr_array_index (reqs, i);
3466 if (req->event_kind == event) {
3467 gboolean filtered = FALSE;
3470 for (j = 0; j < req->nmodifiers; ++j) {
3471 Modifier *mod = &req->modifiers [j];
3473 if (mod->kind == MOD_KIND_COUNT) {
3475 if (mod->data.count > 0) {
3476 if (mod->data.count > 0) {
3478 if (mod->data.count == 0)
3482 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3483 if (mod->data.thread != mono_thread_internal_current ())
3485 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3486 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3488 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3490 if (ei->caught && !mod->caught)
3492 if (!ei->caught && !mod->uncaught)
3494 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3496 gboolean found = FALSE;
3497 MonoAssembly **assemblies = mod->data.assemblies;
3500 for (k = 0; assemblies [k]; ++k)
3501 if (assemblies [k] == jinfo_get_method (ji)->klass->image->assembly)
3506 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3507 gpointer iter = NULL;
3509 MonoDebugSourceInfo *sinfo;
3510 char *source_file, *s;
3511 gboolean found = FALSE;
3513 GPtrArray *source_file_list;
3515 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3516 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3519 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
3520 for (i = 0; i < source_file_list->len; ++i) {
3521 sinfo = g_ptr_array_index (source_file_list, i);
3523 * Do a case-insesitive match by converting the file name to
3526 s = strdup_tolower (sinfo->source_file);
3527 if (g_hash_table_lookup (mod->data.source_files, s))
3530 char *s2 = g_path_get_basename (sinfo->source_file);
3531 char *s3 = strdup_tolower (s2);
3533 if (g_hash_table_lookup (mod->data.source_files, s3))
3540 g_ptr_array_free (source_file_list, TRUE);
3545 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3548 s = mono_type_full_name (&ei->klass->byval_arg);
3549 if (!g_hash_table_lookup (mod->data.type_names, s))
3552 } else if (mod->kind == MOD_KIND_STEP) {
3553 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3554 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3555 !strcmp (jinfo_get_method (ji)->name, ".cctor"))
3557 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3558 MonoCustomAttrInfo *ainfo;
3559 static MonoClass *klass;
3562 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3565 if (!ji->dbg_hidden_inited) {
3566 ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji));
3568 if (mono_custom_attrs_has_attr (ainfo, klass))
3569 ji->dbg_hidden = TRUE;
3570 mono_custom_attrs_free (ainfo);
3572 ji->dbg_hidden_inited = TRUE;
3577 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3578 MonoCustomAttrInfo *ainfo;
3579 static MonoClass *klass;
3582 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3585 if (!ji->dbg_step_through_inited) {
3586 ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji));
3588 if (mono_custom_attrs_has_attr (ainfo, klass))
3589 ji->dbg_step_through = TRUE;
3590 mono_custom_attrs_free (ainfo);
3592 ainfo = mono_custom_attrs_from_class (jinfo_get_method (ji)->klass);
3594 if (mono_custom_attrs_has_attr (ainfo, klass))
3595 ji->dbg_step_through = TRUE;
3596 mono_custom_attrs_free (ainfo);
3598 ji->dbg_step_through_inited = TRUE;
3600 if (ji->dbg_step_through)
3603 if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3604 MonoCustomAttrInfo *ainfo;
3605 static MonoClass *klass;
3608 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute");
3611 if (!ji->dbg_non_user_code_inited) {
3612 ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji));
3614 if (mono_custom_attrs_has_attr (ainfo, klass))
3615 ji->dbg_non_user_code = TRUE;
3616 mono_custom_attrs_free (ainfo);
3618 ainfo = mono_custom_attrs_from_class (jinfo_get_method (ji)->klass);
3620 if (mono_custom_attrs_has_attr (ainfo, klass))
3621 ji->dbg_non_user_code = TRUE;
3622 mono_custom_attrs_free (ainfo);
3624 ji->dbg_non_user_code_inited = TRUE;
3626 if (ji->dbg_non_user_code)
3633 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3634 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3639 /* Send a VM START/DEATH event by default */
3640 if (event == EVENT_KIND_VM_START)
3641 events = g_slist_append (events, GINT_TO_POINTER (0));
3642 if (event == EVENT_KIND_VM_DEATH)
3643 events = g_slist_append (events, GINT_TO_POINTER (0));
3648 static G_GNUC_UNUSED const char*
3649 event_to_string (EventKind event)
3652 case EVENT_KIND_VM_START: return "VM_START";
3653 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3654 case EVENT_KIND_THREAD_START: return "THREAD_START";
3655 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3656 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3657 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3658 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3659 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3660 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3661 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3662 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3663 case EVENT_KIND_STEP: return "STEP";
3664 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3665 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3666 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3667 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3668 case EVENT_KIND_USER_LOG: return "USER_LOG";
3670 g_assert_not_reached ();
3678 * Send an event to the client, suspending the vm if needed.
3679 * LOCKING: Since this can suspend the calling thread, no locks should be held
3681 * The EVENTS list is freed by this function.
3684 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3688 MonoDomain *domain = mono_domain_get ();
3689 MonoThread *thread = NULL;
3690 MonoObject *keepalive_obj = NULL;
3691 gboolean send_success = FALSE;
3696 DEBUG (2, fprintf (log_file, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event)));
3700 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3701 // FIXME: We miss those events
3702 DEBUG (2, fprintf (log_file, "VM start event not sent yet: dropping %s\n", event_to_string (event)));
3706 if (vm_death_event_sent) {
3707 DEBUG (2, fprintf (log_file, "VM death event has been sent: dropping %s\n", event_to_string (event)));
3711 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3712 DEBUG (2, fprintf (log_file, "Mono runtime is shutting down: dropping %s\n", event_to_string (event)));
3717 DEBUG (2, fprintf (log_file, "Debugger client is not connected: dropping %s\n", event_to_string (event)));
3721 if (event == EVENT_KIND_KEEPALIVE)
3722 suspend_policy = SUSPEND_POLICY_NONE;
3727 if (agent_config.defer) {
3728 /* Make sure the thread id is always set when doing deferred debugging */
3729 if (debugger_thread_id == GetCurrentThreadId ()) {
3730 /* Don't suspend on events from the debugger thread */
3731 suspend_policy = SUSPEND_POLICY_NONE;
3732 thread = mono_thread_get_main ();
3734 else thread = mono_thread_current ();
3736 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3737 // FIXME: Send these with a NULL thread, don't suspend the current thread
3742 nevents = g_slist_length (events);
3743 buffer_init (&buf, 128);
3744 buffer_add_byte (&buf, suspend_policy);
3745 buffer_add_int (&buf, nevents);
3747 for (l = events; l; l = l->next) {
3748 buffer_add_byte (&buf, event); // event kind
3749 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3754 thread = mono_thread_current ();
3756 if (event == EVENT_KIND_VM_START && arg != NULL)
3759 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3762 case EVENT_KIND_THREAD_START:
3763 case EVENT_KIND_THREAD_DEATH:
3765 case EVENT_KIND_APPDOMAIN_CREATE:
3766 case EVENT_KIND_APPDOMAIN_UNLOAD:
3767 buffer_add_domainid (&buf, arg);
3769 case EVENT_KIND_METHOD_ENTRY:
3770 case EVENT_KIND_METHOD_EXIT:
3771 buffer_add_methodid (&buf, domain, arg);
3773 case EVENT_KIND_ASSEMBLY_LOAD:
3774 buffer_add_assemblyid (&buf, domain, arg);
3776 case EVENT_KIND_ASSEMBLY_UNLOAD: {
3777 DebuggerTlsData *tls;
3779 /* The domain the assembly belonged to is not equal to the current domain */
3780 tls = mono_native_tls_get_value (debugger_tls_id);
3782 g_assert (tls->domain_unloading);
3784 buffer_add_assemblyid (&buf, tls->domain_unloading, arg);
3787 case EVENT_KIND_TYPE_LOAD:
3788 buffer_add_typeid (&buf, domain, arg);
3790 case EVENT_KIND_BREAKPOINT:
3791 case EVENT_KIND_STEP:
3792 buffer_add_methodid (&buf, domain, arg);
3793 buffer_add_long (&buf, il_offset);
3795 case EVENT_KIND_VM_START:
3796 buffer_add_domainid (&buf, mono_get_root_domain ());
3798 case EVENT_KIND_VM_DEATH:
3799 if (CHECK_PROTOCOL_VERSION (2, 27))
3800 buffer_add_int (&buf, mono_environment_exitcode_get ());
3802 case EVENT_KIND_EXCEPTION: {
3803 EventInfo *ei = arg;
3804 buffer_add_objid (&buf, ei->exc);
3806 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3807 * later after the suspension. (#12494).
3809 keepalive_obj = ei->exc;
3812 case EVENT_KIND_USER_BREAK:
3814 case EVENT_KIND_USER_LOG: {
3815 EventInfo *ei = arg;
3816 buffer_add_int (&buf, ei->level);
3817 buffer_add_string (&buf, ei->category ? ei->category : "");
3818 buffer_add_string (&buf, ei->message ? ei->message : "");
3821 case EVENT_KIND_KEEPALIVE:
3822 suspend_policy = SUSPEND_POLICY_NONE;
3825 g_assert_not_reached ();
3829 if (event == EVENT_KIND_VM_START) {
3830 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3831 if (!agent_config.defer)
3832 start_debugger_thread ();
3835 if (event == EVENT_KIND_VM_DEATH) {
3836 vm_death_event_sent = TRUE;
3837 suspend_policy = SUSPEND_POLICY_NONE;
3840 if (mono_runtime_is_shutting_down ())
3841 suspend_policy = SUSPEND_POLICY_NONE;
3843 if (suspend_policy != SUSPEND_POLICY_NONE) {
3845 * Save the thread context and start suspending before sending the packet,
3846 * since we could be receiving the resume request before send_packet ()
3849 save_thread_context (ctx);
3853 /* This will keep this object alive */
3854 get_objref (keepalive_obj);
3857 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3861 g_slist_free (events);
3864 if (!send_success) {
3865 DEBUG (2, fprintf (log_file, "Sending command %s failed.\n", event_to_string (event)));
3869 if (event == EVENT_KIND_VM_START) {
3870 vm_start_event_sent = TRUE;
3873 DEBUG (1, fprintf (log_file, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer)GetCurrentThreadId (), nevents, event_to_string (event), ecount, suspend_policy));
3875 switch (suspend_policy) {
3876 case SUSPEND_POLICY_NONE:
3878 case SUSPEND_POLICY_ALL:
3881 case SUSPEND_POLICY_EVENT_THREAD:
3885 g_assert_not_reached ();
3890 process_profiler_event (EventKind event, gpointer arg)
3894 EventInfo ei, *ei_arg = NULL;
3896 if (event == EVENT_KIND_TYPE_LOAD) {
3901 mono_loader_lock ();
3902 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3903 mono_loader_unlock ();
3905 process_event (event, arg, 0, NULL, events, suspend_policy);
3909 runtime_initialized (MonoProfiler *prof)
3911 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3912 if (agent_config.defer)
3913 start_debugger_thread ();
3917 runtime_shutdown (MonoProfiler *prof)
3919 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3921 mono_debugger_agent_cleanup ();
3925 thread_startup (MonoProfiler *prof, uintptr_t tid)
3927 MonoInternalThread *thread = mono_thread_internal_current ();
3928 MonoInternalThread *old_thread;
3929 DebuggerTlsData *tls;
3931 if (tid == debugger_thread_id)
3934 g_assert (thread->tid == tid);
3936 mono_loader_lock ();
3937 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3938 mono_loader_unlock ();
3940 if (thread == old_thread) {
3942 * For some reason, thread_startup () might be called for the same thread
3943 * multiple times (attach ?).
3945 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
3949 * thread_end () might not be called for some threads, and the tid could
3952 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
3953 mono_loader_lock ();
3954 mono_g_hash_table_remove (thread_to_tls, old_thread);
3955 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3956 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3957 mono_loader_unlock ();
3961 tls = mono_native_tls_get_value (debugger_tls_id);
3963 // FIXME: Free this somewhere
3964 tls = g_new0 (DebuggerTlsData, 1);
3965 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3966 tls->thread = thread;
3967 mono_native_tls_set_value (debugger_tls_id, tls);
3969 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3971 mono_loader_lock ();
3972 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3973 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3974 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3975 mono_loader_unlock ();
3977 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3980 * suspend_vm () could have missed this thread, so wait for a resume.
3986 thread_end (MonoProfiler *prof, uintptr_t tid)
3988 MonoInternalThread *thread;
3989 DebuggerTlsData *tls = NULL;
3991 mono_loader_lock ();
3992 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3994 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3995 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3997 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3998 tls->terminated = TRUE;
3999 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
4000 MONO_GC_UNREGISTER_ROOT (tls->thread);
4004 mono_loader_unlock ();
4006 /* We might be called for threads started before we registered the start callback */
4008 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
4009 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
4014 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
4016 mono_loader_lock ();
4017 g_hash_table_insert (domains, domain, domain);
4018 mono_loader_unlock ();
4020 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
4024 appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain)
4026 DebuggerTlsData *tls;
4029 * Remember the currently unloading appdomain as it is needed to generate
4030 * proper ids for unloading assemblies.
4032 tls = mono_native_tls_get_value (debugger_tls_id);
4034 tls->domain_unloading = domain;
4038 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
4040 DebuggerTlsData *tls;
4042 tls = mono_native_tls_get_value (debugger_tls_id);
4044 tls->domain_unloading = NULL;
4046 clear_breakpoints_for_domain (domain);
4048 mono_loader_lock ();
4049 /* Invalidate each thread's frame stack */
4050 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
4051 mono_loader_unlock ();
4053 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
4057 * invalidate_each_thread:
4059 * A GHFunc to invalidate frames.
4060 * value must be a DebuggerTlsData*
4063 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
4065 invalidate_frames (value);
4069 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
4071 /* Sent later in jit_end () */
4073 g_ptr_array_add (pending_assembly_loads, assembly);
4078 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
4080 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
4082 clear_event_requests_for_assembly (assembly);
4083 clear_types_for_assembly (assembly);
4087 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
4089 #if defined(HOST_WIN32) && !defined(__GNUC__)
4090 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
4092 gpointer stackptr = __builtin_frame_address (1);
4094 MonoInternalThread *thread = mono_thread_internal_current ();
4095 DebuggerTlsData *tls;
4097 mono_loader_lock ();
4099 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4100 /* Could be the debugger thread with assembly/type load hooks */
4102 tls->invoke_addr = stackptr;
4104 mono_loader_unlock ();
4108 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
4111 #if defined(HOST_WIN32) && !defined(__GNUC__)
4112 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
4114 gpointer stackptr = __builtin_frame_address (1);
4117 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
4121 * We need to stop single stepping when exiting a runtime invoke, since if it is
4122 * a step out, it may return to native code, and thus never end.
4124 mono_loader_lock ();
4125 ss_invoke_addr = NULL;
4127 for (i = 0; i < event_requests->len; ++i) {
4128 EventRequest *req = g_ptr_array_index (event_requests, i);
4130 if (req->event_kind == EVENT_KIND_STEP) {
4131 ss_destroy (req->info);
4132 g_ptr_array_remove_index_fast (event_requests, i);
4137 mono_loader_unlock ();
4141 send_type_load (MonoClass *klass)
4143 gboolean type_load = FALSE;
4144 MonoDomain *domain = mono_domain_get ();
4145 AgentDomainInfo *info = NULL;
4147 mono_loader_lock ();
4148 mono_domain_lock (domain);
4150 info = get_agent_domain_info (domain);
4152 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
4154 g_hash_table_insert (info->loaded_classes, klass, klass);
4157 mono_domain_unlock (domain);
4158 mono_loader_unlock ();
4160 emit_type_load (klass, klass, NULL);
4164 * Emit load events for all types currently loaded in the domain.
4165 * Takes the loader and domain locks.
4166 * user_data is unused.
4169 send_types_for_domain (MonoDomain *domain, void *user_data)
4171 AgentDomainInfo *info = NULL;
4173 mono_loader_lock ();
4174 mono_domain_lock (domain);
4175 info = get_agent_domain_info (domain);
4177 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4178 mono_domain_unlock (domain);
4179 mono_loader_unlock ();
4183 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
4186 * We emit type load events when the first method of the type is JITted,
4187 * since the class load profiler callbacks might be called with the
4188 * loader lock held. They could also occur in the debugger thread.
4189 * Same for assembly load events.
4192 MonoAssembly *assembly = NULL;
4194 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4196 if (pending_assembly_loads->len > 0) {
4197 assembly = g_ptr_array_index (pending_assembly_loads, 0);
4198 g_ptr_array_remove_index (pending_assembly_loads, 0);
4203 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4209 send_type_load (method->klass);
4212 add_pending_breakpoints (method, jinfo);
4216 * BREAKPOINTS/SINGLE STEPPING
4220 * Contains information about an inserted breakpoint.
4223 long il_offset, native_offset;
4228 } BreakpointInstance;
4231 * Contains generic information about a breakpoint.
4235 * The method where the breakpoint is placed. Can be NULL in which case it
4236 * is inserted into every method. This is used to implement method entry/
4237 * exit events. Can be a generic method definition, in which case the
4238 * breakpoint is inserted into every instance.
4244 * A list of BreakpointInstance structures describing where the breakpoint
4245 * was inserted. There could be more than one because of
4246 * generics/appdomains/method entry/exit.
4248 GPtrArray *children;
4251 /* List of breakpoints */
4252 static GPtrArray *breakpoints;
4253 /* Maps breakpoint locations to the number of breakpoints at that location */
4254 static GHashTable *bp_locs;
4257 breakpoints_init (void)
4259 breakpoints = g_ptr_array_new ();
4260 bp_locs = g_hash_table_new (NULL, NULL);
4264 * insert_breakpoint:
4266 * Insert the breakpoint described by BP into the method described by
4270 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4273 BreakpointInstance *inst;
4274 SeqPoint *sp = NULL;
4277 mono_error_init (error);
4279 for (i = 0; i < seq_points->len; ++i) {
4280 sp = &seq_points->seq_points [i];
4282 if (sp->il_offset == bp->il_offset)
4286 if (i == seq_points->len) {
4288 * The set of IL offsets with seq points doesn't completely match the
4289 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4291 for (i = 0; i < seq_points->len; ++i) {
4292 sp = &seq_points->seq_points [i];
4294 if (sp->il_offset != METHOD_ENTRY_IL_OFFSET && sp->il_offset != METHOD_EXIT_IL_OFFSET && sp->il_offset + 1 == bp->il_offset)
4299 if (i == seq_points->len) {
4300 char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d, seq_points=%d\n", mono_method_full_name (jinfo_get_method (ji), TRUE), bp->il_offset, seq_points->len);
4302 for (i = 0; i < seq_points->len; ++i)
4303 DEBUG (1, fprintf (log_file, "%d\n", seq_points->seq_points [i].il_offset));
4306 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4307 g_warning ("%s", s);
4311 g_warning ("%s", s);
4317 inst = g_new0 (BreakpointInstance, 1);
4319 inst->native_offset = sp->native_offset;
4320 inst->ip = (guint8*)ji->code_start + sp->native_offset;
4322 inst->domain = domain;
4324 mono_loader_lock ();
4326 g_ptr_array_add (bp->children, inst);
4328 mono_loader_unlock ();
4331 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4332 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4335 if (sp->native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4336 DEBUG (1, fprintf (log_file, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset));
4337 } else if (count == 0) {
4338 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4339 mono_arch_set_breakpoint (ji, inst->ip);
4345 DEBUG(1, fprintf (log_file, "[dbg] Inserted breakpoint at %s:0x%x [%p](%d).\n", mono_method_full_name (jinfo_get_method (ji), TRUE), (int)sp->il_offset, inst->ip, count));
4349 remove_breakpoint (BreakpointInstance *inst)
4351 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4353 MonoJitInfo *ji = inst->ji;
4354 guint8 *ip = inst->ip;
4357 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4358 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4361 g_assert (count > 0);
4363 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4364 mono_arch_clear_breakpoint (ji, ip);
4365 DEBUG(1, fprintf (log_file, "[dbg] Clear breakpoint at %s [%p].\n", mono_method_full_name (jinfo_get_method (ji), TRUE), ip));
4372 static inline gboolean
4373 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4379 if (method == bp->method)
4381 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4384 if (bp->method->is_inflated && method->is_inflated) {
4385 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4386 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4388 /* Open generic methods should match closed generic methods of the same class */
4389 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4390 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4391 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4393 /* FIXME: Handle !mvar */
4394 if (t1->type != MONO_TYPE_MVAR)
4405 * add_pending_breakpoints:
4407 * Insert pending breakpoints into the newly JITted method METHOD.
4410 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4413 MonoSeqPointInfo *seq_points;
4415 MonoMethod *jmethod;
4420 domain = mono_domain_get ();
4422 mono_loader_lock ();
4424 for (i = 0; i < breakpoints->len; ++i) {
4425 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4426 gboolean found = FALSE;
4428 if (!bp_matches_method (bp, method))
4431 for (j = 0; j < bp->children->len; ++j) {
4432 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4439 jmethod = jinfo_get_method (ji);
4440 mono_domain_lock (domain);
4441 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, jmethod);
4442 if (!seq_points && jmethod->is_inflated)
4443 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (jmethod));
4444 mono_domain_unlock (domain);
4446 /* Could be AOT code */
4448 g_assert (seq_points);
4450 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4454 mono_loader_unlock ();
4458 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4464 mono_error_init (error);
4466 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4468 /* Might be AOTed code */
4469 code = mono_aot_get_method (domain, method);
4471 ji = mono_jit_info_table_find (domain, code);
4476 insert_breakpoint (seq_points, domain, ji, bp, error);
4480 clear_breakpoint (MonoBreakpoint *bp);
4485 * Set a breakpoint at IL_OFFSET in METHOD.
4486 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4487 * METHOD can also be a generic method definition, in which case a breakpoint
4488 * is placed in all instances of the method.
4489 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4492 static MonoBreakpoint*
4493 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4496 GHashTableIter iter, iter2;
4499 MonoSeqPointInfo *seq_points;
4502 mono_error_init (error);
4505 // - suspend/resume the vm to prevent code patching problems
4506 // - multiple breakpoints on the same location
4507 // - dynamic methods
4510 bp = g_new0 (MonoBreakpoint, 1);
4511 bp->method = method;
4512 bp->il_offset = il_offset;
4514 bp->children = g_ptr_array_new ();
4516 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));
4518 mono_loader_lock ();
4520 g_hash_table_iter_init (&iter, domains);
4521 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4522 mono_domain_lock (domain);
4524 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4525 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4526 if (bp_matches_method (bp, m))
4527 set_bp_in_method (domain, m, seq_points, bp, error);
4530 mono_domain_unlock (domain);
4533 mono_loader_unlock ();
4535 mono_loader_lock ();
4536 g_ptr_array_add (breakpoints, bp);
4537 mono_loader_unlock ();
4539 if (error && !mono_error_ok (error)) {
4540 clear_breakpoint (bp);
4548 clear_breakpoint (MonoBreakpoint *bp)
4552 // FIXME: locking, races
4553 for (i = 0; i < bp->children->len; ++i) {
4554 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4556 remove_breakpoint (inst);
4561 mono_loader_lock ();
4562 g_ptr_array_remove (breakpoints, bp);
4563 mono_loader_unlock ();
4565 g_ptr_array_free (bp->children, TRUE);
4570 breakpoints_cleanup (void)
4574 mono_loader_lock ();
4576 while (i < event_requests->len) {
4577 EventRequest *req = g_ptr_array_index (event_requests, i);
4579 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4580 clear_breakpoint (req->info);
4581 g_ptr_array_remove_index_fast (event_requests, i);
4588 for (i = 0; i < breakpoints->len; ++i)
4589 g_free (g_ptr_array_index (breakpoints, i));
4591 g_ptr_array_free (breakpoints, TRUE);
4592 g_hash_table_destroy (bp_locs);
4597 mono_loader_unlock ();
4601 * clear_breakpoints_for_domain:
4603 * Clear breakpoint instances which reference DOMAIN.
4606 clear_breakpoints_for_domain (MonoDomain *domain)
4610 /* This could be called after shutdown */
4614 mono_loader_lock ();
4615 for (i = 0; i < breakpoints->len; ++i) {
4616 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4619 while (j < bp->children->len) {
4620 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4622 if (inst->domain == domain) {
4623 remove_breakpoint (inst);
4627 g_ptr_array_remove_index_fast (bp->children, j);
4633 mono_loader_unlock ();
4639 * Return FALSE if single stepping needs to continue.
4642 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp, DebuggerTlsData *tls, MonoContext *ctx)
4644 MonoDebugMethodInfo *minfo;
4645 MonoDebugSourceLocation *loc = NULL;
4646 gboolean hit = TRUE;
4649 if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK)) {
4651 * These seq points are inserted by the JIT after calls, step over needs to skip them.
4653 DEBUG (1, fprintf (log_file, "[%p] Seq point at nonempty stack %x while stepping over, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset));
4657 if (req->depth == STEP_DEPTH_OVER && hit) {
4658 if (!tls->context.valid)
4659 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4660 compute_frame_info (tls->thread, tls);
4661 if (req->nframes && tls->frame_count && tls->frame_count > req->nframes) {
4662 /* Hit the breakpoint in a recursive call */
4663 DEBUG (1, fprintf (log_file, "[%p] Breakpoint at lower frame while stepping over, continuing single stepping.\n", (gpointer)GetCurrentThreadId ()));
4668 if (req->size != STEP_SIZE_LINE)
4671 /* Have to check whenever a different source line was reached */
4672 method = jinfo_get_method (ji);
4673 minfo = mono_debug_lookup_method (method);
4676 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4678 if (!loc || (loc && method == ss_req->last_method && loc->row == ss_req->last_line)) {
4679 /* Have to continue single stepping */
4681 DEBUG(1, fprintf (log_file, "[%p] No line number info for il offset %x, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset));
4683 DEBUG(1, fprintf (log_file, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer)GetCurrentThreadId (), loc->row));
4688 ss_req->last_method = method;
4689 ss_req->last_line = loc->row;
4690 mono_debug_free_source_location (loc);
4697 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4699 return bp->method && bp->method->klass->image->assembly == assembly;
4703 process_breakpoint_inner (DebuggerTlsData *tls)
4707 int i, j, suspend_policy;
4708 guint32 native_offset;
4710 BreakpointInstance *inst;
4711 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4712 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4713 EventKind kind = EVENT_KIND_BREAKPOINT;
4714 MonoContext *ctx = &tls->restore_ctx;
4716 MonoSeqPointInfo *info;
4719 // FIXME: Speed this up
4721 ip = MONO_CONTEXT_GET_IP (ctx);
4722 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4724 method = jinfo_get_method (ji);
4726 /* Compute the native offset of the breakpoint from the ip */
4727 native_offset = ip - (guint8*)ji->code_start;
4730 * Skip the instruction causing the breakpoint signal.
4732 mono_arch_skip_breakpoint (ctx, ji);
4734 if (method->wrapper_type || tls->disable_breakpoints)
4737 bp_reqs = g_ptr_array_new ();
4738 ss_reqs = g_ptr_array_new ();
4739 ss_reqs_orig = g_ptr_array_new ();
4741 mono_loader_lock ();
4744 * The ip points to the instruction causing the breakpoint event, which is after
4745 * the offset recorded in the seq point map, so find the prev seq point before ip.
4747 sp = find_prev_seq_point_for_native_offset (mono_domain_get (), method, native_offset, &info);
4749 no_seq_points_found (method);
4752 DEBUG(1, fprintf (log_file, "[%p] Breakpoint hit, method=%s, ip=%p, offset=0x%x, sp il offset=0x%x.\n", (gpointer)GetCurrentThreadId (), method->name, ip, native_offset, sp ? sp->il_offset : -1));
4755 for (i = 0; i < breakpoints->len; ++i) {
4756 bp = g_ptr_array_index (breakpoints, i);
4761 for (j = 0; j < bp->children->len; ++j) {
4762 inst = g_ptr_array_index (bp->children, j);
4763 if (inst->ji == ji && inst->sp == sp) {
4764 if (bp->req->event_kind == EVENT_KIND_STEP) {
4765 g_ptr_array_add (ss_reqs_orig, bp->req);
4767 g_ptr_array_add (bp_reqs, bp->req);
4772 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4773 /* Maybe a method entry/exit event */
4774 if (sp->il_offset == METHOD_ENTRY_IL_OFFSET)
4775 kind = EVENT_KIND_METHOD_ENTRY;
4776 else if (sp->il_offset == METHOD_EXIT_IL_OFFSET)
4777 kind = EVENT_KIND_METHOD_EXIT;
4780 /* Process single step requests */
4781 for (i = 0; i < ss_reqs_orig->len; ++i) {
4782 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4783 SingleStepReq *ss_req = req->info;
4786 if (mono_thread_internal_current () != ss_req->thread)
4789 hit = ss_update (ss_req, ji, sp, tls, ctx);
4791 g_ptr_array_add (ss_reqs, req);
4793 /* Start single stepping again from the current sequence point */
4794 ss_start (ss_req, method, sp, info, ctx, tls, FALSE);
4797 if (ss_reqs->len > 0)
4798 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4799 if (bp_reqs->len > 0)
4800 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4801 if (kind != EVENT_KIND_BREAKPOINT)
4802 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4804 mono_loader_unlock ();
4806 g_ptr_array_free (bp_reqs, TRUE);
4807 g_ptr_array_free (ss_reqs, TRUE);
4810 * FIXME: The first event will suspend, so the second will only be sent after the
4814 process_event (EVENT_KIND_STEP, method, 0, ctx, ss_events, suspend_policy);
4816 process_event (kind, method, 0, ctx, bp_events, suspend_policy);
4817 if (enter_leave_events)
4818 process_event (kind, method, 0, ctx, enter_leave_events, suspend_policy);
4821 /* Process a breakpoint/single step event after resuming from a signal handler */
4823 process_signal_event (void (*func) (DebuggerTlsData*))
4825 DebuggerTlsData *tls;
4826 MonoContext orig_restore_ctx, ctx;
4828 tls = mono_native_tls_get_value (debugger_tls_id);
4829 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4830 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4831 memcpy (&tls->restore_ctx, &tls->handler_ctx, sizeof (MonoContext));
4835 /* This is called when resuming from a signal handler, so it shouldn't return */
4836 memcpy (&ctx, &tls->restore_ctx, sizeof (MonoContext));
4837 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4838 mono_restore_context (&ctx);
4839 g_assert_not_reached ();
4843 process_breakpoint (void)
4845 process_signal_event (process_breakpoint_inner);
4849 resume_from_signal_handler (void *sigctx, void *func)
4851 DebuggerTlsData *tls;
4854 /* Save the original context in TLS */
4855 // FIXME: This might not work on an altstack ?
4856 tls = mono_native_tls_get_value (debugger_tls_id);
4858 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer)GetCurrentThreadId ());
4861 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4862 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4863 // clob:c could be added to op_seq_point.
4865 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4866 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4867 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4868 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4870 MONO_CONTEXT_SET_IP (&ctx, func);
4872 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4874 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4875 mono_ppc_set_func_into_sigctx (sigctx, func);
4880 mono_debugger_agent_breakpoint_hit (void *sigctx)
4883 * We are called from a signal handler, and running code there causes all kinds of
4884 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4885 * So set up the signal context to return to the real breakpoint handler function.
4887 resume_from_signal_handler (sigctx, process_breakpoint);
4891 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4893 if (frame->managed) {
4894 *(MonoContext*)data = *ctx;
4903 * Called by System.Diagnostics.Debugger:Break ().
4906 mono_debugger_agent_user_break (void)
4908 if (agent_config.enabled) {
4913 /* Obtain a context */
4914 MONO_CONTEXT_SET_IP (&ctx, NULL);
4915 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4916 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4918 mono_loader_lock ();
4919 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4920 mono_loader_unlock ();
4922 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4929 ss_depth_to_string (StepDepth depth)
4932 case STEP_DEPTH_OVER:
4934 case STEP_DEPTH_OUT:
4936 case STEP_DEPTH_INTO:
4939 g_assert_not_reached ();
4945 process_single_step_inner (DebuggerTlsData *tls)
4950 int il_offset, suspend_policy;
4953 MonoContext *ctx = &tls->restore_ctx;
4956 MonoSeqPointInfo *info;
4958 ip = MONO_CONTEXT_GET_IP (ctx);
4960 /* Skip the instruction causing the single step */
4961 mono_arch_skip_single_step (ctx);
4963 if (suspend_count > 0) {
4964 process_suspend (tls, ctx);
4969 // FIXME: A suspend race
4972 if (mono_thread_internal_current () != ss_req->thread)
4975 if (log_level > 0) {
4976 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4978 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 (jinfo_get_method (ji), TRUE), MONO_CONTEXT_GET_IP (ctx), MONO_CONTEXT_GET_SP (ctx), ss_req->last_sp));
4981 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4983 method = jinfo_get_method (ji);
4986 if (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4991 * Stopping in memset makes half-initialized vtypes visible.
4992 * Stopping in memcpy makes half-copied vtypes visible.
4994 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
4998 * The ip points to the instruction causing the single step event, which is before
4999 * the offset recorded in the seq point map, so find the next seq point after ip.
5001 sp = find_next_seq_point_for_native_offset (domain, method, (guint8*)ip - (guint8*)ji->code_start, &info);
5004 il_offset = sp->il_offset;
5006 if (!ss_update (ss_req, ji, sp, tls, ctx))
5009 /* Start single stepping again from the current sequence point */
5010 ss_start (ss_req, method, sp, info, ctx, tls, FALSE);
5012 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
5013 (method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
5014 !strcmp (method->name, ".cctor"))
5017 // FIXME: Has to lock earlier
5019 reqs = g_ptr_array_new ();
5021 mono_loader_lock ();
5023 g_ptr_array_add (reqs, ss_req->req);
5025 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
5027 g_ptr_array_free (reqs, TRUE);
5029 mono_loader_unlock ();
5031 process_event (EVENT_KIND_STEP, jinfo_get_method (ji), il_offset, ctx, events, suspend_policy);
5035 process_single_step (void)
5037 process_signal_event (process_single_step_inner);
5041 * mono_debugger_agent_single_step_event:
5043 * Called from a signal handler to handle a single step event.
5046 mono_debugger_agent_single_step_event (void *sigctx)
5048 /* Resume to process_single_step through the signal context */
5050 // FIXME: Since step out/over is implemented using step in, the step in case should
5051 // be as fast as possible. Move the relevant code from process_single_step_inner ()
5054 if (GetCurrentThreadId () == debugger_thread_id) {
5056 * This could happen despite our best effors when the runtime calls
5057 * assembly/type resolve hooks.
5058 * FIXME: Breakpoints too.
5062 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
5063 mono_arch_skip_single_step (&ctx);
5064 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
5068 resume_from_signal_handler (sigctx, process_single_step);
5072 debugger_agent_single_step_from_context (MonoContext *ctx)
5074 DebuggerTlsData *tls;
5075 MonoContext orig_restore_ctx;
5077 tls = mono_native_tls_get_value (debugger_tls_id);
5080 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
5081 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
5082 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
5084 process_single_step_inner (tls);
5086 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
5087 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
5091 debugger_agent_breakpoint_from_context (MonoContext *ctx)
5093 DebuggerTlsData *tls;
5094 MonoContext orig_restore_ctx;
5096 tls = mono_native_tls_get_value (debugger_tls_id);
5098 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
5099 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
5101 process_breakpoint_inner (tls);
5103 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
5104 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
5108 * start_single_stepping:
5110 * Turn on single stepping. Can be called multiple times, for example,
5111 * by a single step event request + a suspend.
5114 start_single_stepping (void)
5116 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5117 int val = InterlockedIncrement (&ss_count);
5120 mono_arch_start_single_stepping ();
5122 if (ss_req != NULL && ss_invoke_addr == NULL) {
5123 DebuggerTlsData *tls;
5125 mono_loader_lock ();
5127 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
5128 ss_invoke_addr = tls->invoke_addr;
5130 mono_loader_unlock ();
5133 g_assert_not_reached ();
5138 stop_single_stepping (void)
5140 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5141 int val = InterlockedDecrement (&ss_count);
5144 mono_arch_stop_single_stepping ();
5146 ss_invoke_addr = NULL;
5148 g_assert_not_reached ();
5155 * Stop the single stepping operation given by SS_REQ.
5158 ss_stop (SingleStepReq *ss_req)
5163 for (l = ss_req->bps; l; l = l->next) {
5164 clear_breakpoint (l->data);
5166 g_slist_free (ss_req->bps);
5170 if (ss_req->global) {
5171 stop_single_stepping ();
5172 ss_req->global = FALSE;
5179 * Start the single stepping operation given by SS_REQ from the sequence point SP.
5180 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
5181 * belong to the same thread as CTX.
5184 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
5186 int i, j, frame_index;
5189 gboolean enable_global = FALSE;
5191 /* Stop the previous operation */
5195 * Implement single stepping using breakpoints if possible.
5197 if (step_to_catch) {
5198 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
5199 ss_req->bps = g_slist_append (ss_req->bps, bp);
5203 if ((!sp || sp->next_len == 0 || ss_req->depth == STEP_DEPTH_OUT || ss_req->depth == STEP_DEPTH_OVER) && ctx) {
5204 /* Need parent frames */
5205 if (!tls->context.valid)
5206 mono_thread_state_init_from_monoctx (&tls->context, ctx);
5207 compute_frame_info (tls->thread, tls);
5211 * Find the first sequence point in the current or in a previous frame which
5212 * is not the last in its method.
5214 if (ss_req->depth == STEP_DEPTH_OUT) {
5215 /* Ignore seq points in current method */
5216 while (frame_index < tls->frame_count) {
5217 StackFrame *frame = tls->frames [frame_index];
5219 method = frame->method;
5220 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5222 if (sp && sp->next_len != 0)
5225 // There could be method calls before the next seq point in the caller when using nested calls
5226 //enable_global = TRUE;
5228 if (sp && sp->next_len == 0) {
5230 while (frame_index < tls->frame_count) {
5231 StackFrame *frame = tls->frames [frame_index];
5233 method = frame->method;
5234 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5235 if (sp && sp->next_len != 0)
5243 if (sp && sp->next_len > 0) {
5244 for (i = 0; i < sp->next_len; ++i) {
5245 next_sp = &info->seq_points [sp->next [i]];
5247 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
5248 ss_req->bps = g_slist_append (ss_req->bps, bp);
5252 if (ss_req->depth == STEP_DEPTH_OVER) {
5253 if (ss_req->nframes == 0)
5254 ss_req->nframes = tls->frame_count;
5255 /* Need to stop in catch clauses as well */
5256 for (i = 0; i < tls->frame_count; ++i) {
5257 StackFrame *frame = tls->frames [i];
5260 MonoJitInfo *jinfo = frame->ji;
5261 for (j = 0; j < jinfo->num_clauses; ++j) {
5262 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5264 sp = find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL);
5266 bp = set_breakpoint (frame->method, sp->il_offset, ss_req->req, NULL);
5267 ss_req->bps = g_slist_append (ss_req->bps, bp);
5275 if (ss_req->depth == STEP_DEPTH_INTO) {
5276 /* Enable global stepping so we stop at method entry too */
5277 enable_global = TRUE;
5281 * The ctx/frame info computed above will become invalid when we continue.
5283 tls->context.valid = FALSE;
5284 tls->async_state.valid = FALSE;
5285 invalidate_frames (tls);
5288 if (enable_global) {
5289 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
5290 ss_req->global = TRUE;
5291 start_single_stepping ();
5292 } else if (!ss_req->bps) {
5293 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
5294 ss_req->global = TRUE;
5295 start_single_stepping ();
5297 ss_req->global = FALSE;
5302 * Start single stepping of thread THREAD
5305 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
5307 DebuggerTlsData *tls;
5308 MonoSeqPointInfo *info = NULL;
5309 SeqPoint *sp = NULL;
5310 MonoMethod *method = NULL;
5311 MonoDebugMethodInfo *minfo;
5312 gboolean step_to_catch = FALSE;
5314 if (suspend_count == 0)
5315 return ERR_NOT_SUSPENDED;
5317 wait_for_suspend ();
5319 // FIXME: Multiple requests
5321 DEBUG (0, fprintf (log_file, "Received a single step request while the previous one was still active.\n"));
5322 return ERR_NOT_IMPLEMENTED;
5325 DEBUG (1, fprintf (log_file, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
5327 ss_req = g_new0 (SingleStepReq, 1);
5329 ss_req->thread = thread;
5330 ss_req->size = size;
5331 ss_req->depth = depth;
5334 mono_loader_lock ();
5335 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5336 mono_loader_unlock ();
5338 g_assert (tls->context.valid);
5339 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5341 if (tls->catch_state.valid) {
5343 StackFrameInfo frame;
5344 MonoContext new_ctx;
5345 MonoLMF *lmf = NULL;
5348 * We are stopped at a throw site. Stepping should go to the catch site.
5351 /* Find the the jit info for the catch context */
5352 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);
5354 g_assert (frame.type == FRAME_TYPE_MANAGED);
5357 * Find the seq point corresponding to the landing site ip, which is the first seq
5360 sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
5362 no_seq_points_found (frame.method);
5365 method = frame.method;
5367 step_to_catch = TRUE;
5368 /* This make sure the seq point is not skipped by process_single_step () */
5369 ss_req->last_sp = NULL;
5372 if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
5375 /* Compute the initial line info */
5376 compute_frame_info (thread, tls);
5378 if (tls->frame_count) {
5379 frame = tls->frames [0];
5381 ss_req->last_method = frame->method;
5382 ss_req->last_line = -1;
5384 minfo = mono_debug_lookup_method (frame->method);
5385 if (minfo && frame->il_offset != -1) {
5386 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
5389 ss_req->last_line = loc->row;
5396 if (!step_to_catch) {
5399 compute_frame_info (thread, tls);
5401 if (tls->frame_count) {
5402 frame = tls->frames [0];
5404 if (!method && frame->il_offset != -1) {
5405 /* FIXME: Sort the table and use a binary search */
5406 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5408 no_seq_points_found (frame->method);
5410 method = frame->method;
5415 ss_start (ss_req, method, sp, info, &tls->context.ctx, tls, step_to_catch);
5421 ss_destroy (SingleStepReq *req)
5424 g_assert (ss_req == req);
5433 ss_clear_for_assembly (SingleStepReq *req, MonoAssembly *assembly)
5436 gboolean found = TRUE;
5440 for (l = ss_req->bps; l; l = l->next) {
5441 if (breakpoint_matches_assembly (l->data, assembly)) {
5442 clear_breakpoint (l->data);
5443 ss_req->bps = g_slist_delete_link (ss_req->bps, l);
5452 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5455 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5461 if (!agent_config.enabled)
5464 mono_loader_lock ();
5465 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5466 mono_loader_unlock ();
5469 ei.category = category ? mono_string_to_utf8 (category) : NULL;
5470 ei.message = message ? mono_string_to_utf8 (message) : NULL;
5472 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5474 g_free (ei.category);
5475 g_free (ei.message);
5479 mono_debugger_agent_debug_log_is_enabled (void)
5481 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5482 return agent_config.enabled;
5485 #if defined(PLATFORM_ANDROID) || defined(TARGET_ANDROID)
5487 mono_debugger_agent_unhandled_exception (MonoException *exc)
5496 memset (&ei, 0, sizeof (EventInfo));
5497 ei.exc = (MonoObject*)exc;
5499 mono_loader_lock ();
5500 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5501 mono_loader_unlock ();
5503 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5508 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5509 MonoContext *catch_ctx)
5511 int i, j, suspend_policy;
5513 MonoJitInfo *ji, *catch_ji;
5515 DebuggerTlsData *tls = NULL;
5517 if (thread_to_tls != NULL) {
5518 MonoInternalThread *thread = mono_thread_internal_current ();
5520 mono_loader_lock ();
5521 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5522 mono_loader_unlock ();
5524 if (tls && tls->abort_requested)
5526 if (tls && tls->disable_breakpoints)
5530 memset (&ei, 0, sizeof (EventInfo));
5532 /* Just-In-Time debugging */
5534 if (agent_config.onuncaught && !inited) {
5535 finish_agent_init (FALSE);
5538 * Send an unsolicited EXCEPTION event with a dummy request id.
5540 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5541 ei.exc = (MonoObject*)exc;
5542 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5545 } else if (agent_config.onthrow && !inited) {
5547 gboolean found = FALSE;
5549 for (l = agent_config.onthrow; l; l = l->next) {
5550 char *ex_type = l->data;
5551 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5553 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5560 finish_agent_init (FALSE);
5563 * Send an unsolicited EXCEPTION event with a dummy request id.
5565 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5566 ei.exc = (MonoObject*)exc;
5567 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5575 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5577 catch_ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5581 ei.exc = (MonoObject*)exc;
5582 ei.caught = catch_ctx != NULL;
5584 mono_loader_lock ();
5586 /* Treat exceptions which are caught in non-user code as unhandled */
5587 for (i = 0; i < event_requests->len; ++i) {
5588 EventRequest *req = g_ptr_array_index (event_requests, i);
5589 if (req->event_kind != EVENT_KIND_EXCEPTION)
5592 for (j = 0; j < req->nmodifiers; ++j) {
5593 Modifier *mod = &req->modifiers [j];
5595 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5597 gboolean found = FALSE;
5598 MonoAssembly **assemblies = mod->data.assemblies;
5601 for (k = 0; assemblies [k]; ++k)
5602 if (assemblies [k] == jinfo_get_method (catch_ji)->klass->image->assembly)
5611 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5612 mono_loader_unlock ();
5614 if (tls && ei.caught && catch_ctx) {
5615 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5616 tls->catch_state.ctx = *catch_ctx;
5617 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5618 tls->catch_state.valid = TRUE;
5621 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5624 tls->catch_state.valid = FALSE;
5628 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5630 DebuggerTlsData *tls;
5635 tls = mono_native_tls_get_value (debugger_tls_id);
5640 * We're about to invoke an exception filter during the first pass of exception handling.
5642 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5643 * 'orig_ctx' is the context where the exception has been thrown.
5646 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5648 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5649 * the call site (line 37) and then continue to Main(), but it would never
5650 * include the throw site (line 32).
5652 * Since exception filters are invoked during the first pass of exception handling,
5653 * the stack frames of the throw site are still intact, so we should include them
5656 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5658 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5659 * but report the location of the 'throw' to the user.
5663 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5667 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5669 DebuggerTlsData *tls;
5674 tls = mono_native_tls_get_value (debugger_tls_id);
5678 tls->filter_state.valid = FALSE;
5682 * buffer_add_value_full:
5684 * Add the encoding of the value at ADDR described by T to the buffer.
5685 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5689 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5690 gboolean as_vtype, GHashTable *parent_vtypes)
5693 gboolean boxed_vtype = FALSE;
5696 if (!(*(void**)addr)) {
5697 /* This can happen with compiler generated locals */
5698 //printf ("%s\n", mono_type_full_name (t));
5699 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5702 g_assert (*(void**)addr);
5703 addr = *(void**)addr;
5708 case MONO_TYPE_BOOLEAN:
5711 case MONO_TYPE_CHAR:
5731 case MONO_TYPE_VOID:
5732 buffer_add_byte (buf, t->type);
5734 case MONO_TYPE_BOOLEAN:
5737 buffer_add_byte (buf, t->type);
5738 buffer_add_int (buf, *(gint8*)addr);
5740 case MONO_TYPE_CHAR:
5743 buffer_add_byte (buf, t->type);
5744 buffer_add_int (buf, *(gint16*)addr);
5749 buffer_add_byte (buf, t->type);
5750 buffer_add_int (buf, *(gint32*)addr);
5755 buffer_add_byte (buf, t->type);
5756 buffer_add_long (buf, *(gint64*)addr);
5760 /* Treat it as a vtype */
5762 case MONO_TYPE_PTR: {
5763 gssize val = *(gssize*)addr;
5765 buffer_add_byte (buf, t->type);
5766 buffer_add_long (buf, val);
5770 case MONO_TYPE_STRING:
5771 case MONO_TYPE_SZARRAY:
5772 case MONO_TYPE_OBJECT:
5773 case MONO_TYPE_CLASS:
5774 case MONO_TYPE_ARRAY:
5775 obj = *(MonoObject**)addr;
5778 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5780 if (obj->vtable->klass->valuetype) {
5781 t = &obj->vtable->klass->byval_arg;
5782 addr = mono_object_unbox (obj);
5785 } else if (obj->vtable->klass->rank) {
5786 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5787 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5788 buffer_add_byte (buf, MONO_TYPE_CLASS);
5790 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5792 buffer_add_objid (buf, obj);
5796 case MONO_TYPE_VALUETYPE: {
5800 MonoClass *klass = mono_class_from_mono_type (t);
5805 * Handle boxed vtypes recursively referencing themselves using fields.
5808 parent_vtypes = g_hash_table_new (NULL, NULL);
5809 vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
5811 if (CHECK_PROTOCOL_VERSION (2, 33)) {
5812 buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
5813 buffer_add_int (buf, vtype_index - 1);
5815 /* The client can't handle PARENT_VTYPE */
5816 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5820 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
5824 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5825 buffer_add_byte (buf, klass->enumtype);
5826 buffer_add_typeid (buf, domain, klass);
5830 while ((f = mono_class_get_fields (klass, &iter))) {
5831 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5833 if (mono_field_is_deleted (f))
5837 buffer_add_int (buf, nfields);
5840 while ((f = mono_class_get_fields (klass, &iter))) {
5841 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5843 if (mono_field_is_deleted (f))
5845 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE, parent_vtypes);
5849 g_hash_table_remove (parent_vtypes, addr);
5850 if (g_hash_table_size (parent_vtypes) == 0) {
5851 g_hash_table_destroy (parent_vtypes);
5852 parent_vtypes = NULL;
5857 case MONO_TYPE_GENERICINST:
5858 if (mono_type_generic_inst_is_valuetype (t)) {
5870 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5872 buffer_add_value_full (buf, t, addr, domain, FALSE, NULL);
5876 obj_is_of_type (MonoObject *obj, MonoType *t)
5878 MonoClass *klass = obj->vtable->klass;
5879 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5880 if (mono_class_is_transparent_proxy (klass)) {
5881 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5882 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5892 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5895 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5901 gpointer iter = NULL;
5905 is_enum = decode_byte (buf, &buf, limit);
5906 /* Enums are sent as a normal vtype */
5908 return ERR_NOT_IMPLEMENTED;
5909 klass = decode_typeid (buf, &buf, limit, &d, &err);
5913 if (t && klass != mono_class_from_mono_type (t)) {
5914 char *name = mono_type_full_name (t);
5915 char *name2 = mono_type_full_name (&klass->byval_arg);
5916 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got %s.\n", (gpointer)GetCurrentThreadId (), name, name2));
5919 return ERR_INVALID_ARGUMENT;
5922 nfields = decode_int (buf, &buf, limit);
5923 while ((f = mono_class_get_fields (klass, &iter))) {
5924 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5926 if (mono_field_is_deleted (f))
5928 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5933 g_assert (nfields == 0);
5941 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5945 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5946 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5947 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5948 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5949 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
5950 char *name = mono_type_full_name (t);
5951 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5953 return ERR_INVALID_ARGUMENT;
5957 case MONO_TYPE_BOOLEAN:
5958 *(guint8*)addr = decode_int (buf, &buf, limit);
5960 case MONO_TYPE_CHAR:
5961 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5964 *(gint8*)addr = decode_int (buf, &buf, limit);
5967 *(guint8*)addr = decode_int (buf, &buf, limit);
5970 *(gint16*)addr = decode_int (buf, &buf, limit);
5973 *(guint16*)addr = decode_int (buf, &buf, limit);
5976 *(gint32*)addr = decode_int (buf, &buf, limit);
5979 *(guint32*)addr = decode_int (buf, &buf, limit);
5982 *(gint64*)addr = decode_long (buf, &buf, limit);
5985 *(guint64*)addr = decode_long (buf, &buf, limit);
5988 *(guint32*)addr = decode_int (buf, &buf, limit);
5991 *(guint64*)addr = decode_long (buf, &buf, limit);
5994 /* We send these as I8, so we get them back as such */
5995 g_assert (type == MONO_TYPE_I8);
5996 *(gssize*)addr = decode_long (buf, &buf, limit);
5998 case MONO_TYPE_GENERICINST:
5999 if (MONO_TYPE_ISSTRUCT (t)) {
6000 /* The client sends these as a valuetype */
6008 /* We send these as vtypes, so we get them back as such */
6009 g_assert (type == MONO_TYPE_VALUETYPE);
6012 case MONO_TYPE_VALUETYPE:
6013 err = decode_vtype (t, domain, addr,buf, &buf, limit);
6019 if (MONO_TYPE_IS_REFERENCE (t)) {
6020 if (type == MONO_TYPE_OBJECT) {
6021 int objid = decode_objid (buf, &buf, limit);
6025 err = get_object (objid, (MonoObject**)&obj);
6030 if (!obj_is_of_type (obj, t)) {
6031 DEBUG (1, fprintf (log_file, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name));
6032 return ERR_INVALID_ARGUMENT;
6035 if (obj && obj->vtable->domain != domain)
6036 return ERR_INVALID_ARGUMENT;
6038 mono_gc_wbarrier_generic_store (addr, obj);
6039 } else if (type == VALUE_TYPE_ID_NULL) {
6040 *(MonoObject**)addr = NULL;
6041 } else if (type == MONO_TYPE_VALUETYPE) {
6049 /* This can happen when round-tripping boxed vtypes */
6051 * Obtain vtype class.
6052 * Same as the beginning of the handle_vtype case above.
6055 is_enum = decode_byte (buf, &buf, limit);
6057 return ERR_NOT_IMPLEMENTED;
6058 klass = decode_typeid (buf, &buf, limit, &d, &err);
6062 /* Decode the vtype into a temporary buffer, then box it. */
6063 vtype_buf_size = mono_class_value_size (klass, NULL);
6064 vtype_buf = g_malloc0 (vtype_buf_size);
6065 g_assert (vtype_buf);
6068 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
6073 *(MonoObject**)addr = mono_value_box (d, klass, vtype_buf);
6076 char *name = mono_type_full_name (t);
6077 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
6079 return ERR_INVALID_ARGUMENT;
6093 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6096 int type = decode_byte (buf, &buf, limit);
6098 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
6099 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
6100 guint8 *nullable_buf;
6103 * First try decoding it as a Nullable`1
6105 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6110 * Then try decoding as a primitive value or null.
6112 if (targ->type == type) {
6113 nullable_buf = g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
6114 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
6116 g_free (nullable_buf);
6119 mono_nullable_init (addr, mono_value_box (domain, mono_class_from_mono_type (targ), nullable_buf), mono_class_from_mono_type (t));
6120 g_free (nullable_buf);
6123 } else if (type == VALUE_TYPE_ID_NULL) {
6124 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
6130 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6134 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
6138 guint8 *addr, *gaddr;
6141 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6142 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6145 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
6146 reg_val = mono_arch_context_get_int_reg (ctx, reg);
6148 buffer_add_value_full (buf, t, ®_val, domain, as_vtype, NULL);
6150 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6151 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6152 addr += (gint32)var->offset;
6154 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6156 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6158 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6161 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6162 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
6163 /* Same as regoffset, but with an indirection */
6164 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6165 addr += (gint32)var->offset;
6167 gaddr = *(gpointer*)addr;
6169 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL);
6171 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
6172 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
6173 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
6174 MonoGSharedVtMethodRuntimeInfo *info;
6180 g_assert (info_var);
6181 g_assert (locals_var);
6183 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6184 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6185 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6186 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6187 addr += (gint32)info_var->offset;
6188 info = *(gpointer*)addr;
6189 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6190 info = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6192 g_assert_not_reached ();
6196 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6197 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6198 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6199 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6200 addr += (gint32)locals_var->offset;
6201 locals = *(gpointer*)addr;
6202 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6203 locals = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6205 g_assert_not_reached ();
6209 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6211 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6216 g_assert_not_reached ();
6221 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
6225 guint8 *addr, *gaddr;
6227 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6228 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6230 if (MONO_TYPE_IS_REFERENCE (t))
6231 size = sizeof (gpointer);
6233 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6236 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6237 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6239 gboolean is_signed = FALSE;
6242 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6245 // FIXME: Write barriers
6246 mono_gc_memmove_atomic (addr, val, size);
6251 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6256 v = is_signed ? *(gint8*)val : *(guint8*)val;
6259 v = is_signed ? *(gint16*)val : *(guint16*)val;
6262 v = is_signed ? *(gint32*)val : *(guint32*)val;
6265 v = is_signed ? *(gint64*)val : *(guint64*)val;
6268 g_assert_not_reached ();
6271 /* Set value on the stack or in the return ctx */
6272 if (reg_locations [reg]) {
6273 /* Saved on the stack */
6274 DEBUG (1, fprintf (log_file, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v));
6275 *(reg_locations [reg]) = v;
6278 DEBUG (1, fprintf (log_file, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v));
6279 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6282 // FIXME: Move these to mono-context.h/c.
6283 mono_arch_context_set_int_reg (ctx, reg, v);
6285 // FIXME: Can't set registers, so we disable linears
6290 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6291 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6292 addr += (gint32)var->offset;
6294 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6297 addr = *(guint8**)addr;
6303 // FIXME: Write barriers
6304 mono_gc_memmove_atomic (addr, val, size);
6306 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6307 /* Same as regoffset, but with an indirection */
6308 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6309 addr += (gint32)var->offset;
6311 gaddr = *(gpointer*)addr;
6313 // FIXME: Write barriers
6314 mono_gc_memmove_atomic (gaddr, val, size);
6316 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6320 g_assert_not_reached ();
6325 clear_event_request (int req_id, int etype)
6329 mono_loader_lock ();
6330 for (i = 0; i < event_requests->len; ++i) {
6331 EventRequest *req = g_ptr_array_index (event_requests, i);
6333 if (req->id == req_id && req->event_kind == etype) {
6334 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6335 clear_breakpoint (req->info);
6336 if (req->event_kind == EVENT_KIND_STEP)
6337 ss_destroy (req->info);
6338 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6339 clear_breakpoint (req->info);
6340 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6341 clear_breakpoint (req->info);
6342 g_ptr_array_remove_index_fast (event_requests, i);
6347 mono_loader_unlock ();
6351 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
6355 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6356 m->kind = MOD_KIND_NONE;
6357 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6358 int count = 0, match_count = 0, pos;
6359 MonoAssembly **newassemblies;
6361 for (i = 0; m->data.assemblies [i]; ++i) {
6363 if (m->data.assemblies [i] == assembly)
6368 newassemblies = g_new0 (MonoAssembly*, count - match_count);
6371 for (i = 0; i < count; ++i)
6372 if (m->data.assemblies [i] != assembly)
6373 newassemblies [pos ++] = m->data.assemblies [i];
6374 g_assert (pos == count - match_count);
6375 g_free (m->data.assemblies);
6376 m->data.assemblies = newassemblies;
6382 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
6386 for (i = 0; i < req->nmodifiers; ++i) {
6387 Modifier *m = &req->modifiers [i];
6389 clear_assembly_from_modifier (req, m, assembly);
6394 * clear_event_requests_for_assembly:
6396 * Clear all events requests which reference ASSEMBLY.
6399 clear_event_requests_for_assembly (MonoAssembly *assembly)
6404 mono_loader_lock ();
6408 for (i = 0; i < event_requests->len; ++i) {
6409 EventRequest *req = g_ptr_array_index (event_requests, i);
6411 clear_assembly_from_modifiers (req, assembly);
6413 if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly (req->info, assembly)) {
6414 clear_event_request (req->id, req->event_kind);
6419 if (req->event_kind == EVENT_KIND_STEP)
6420 ss_clear_for_assembly (req->info, assembly);
6423 mono_loader_unlock ();
6427 * type_comes_from_assembly:
6429 * GHRFunc that returns TRUE if klass comes from assembly
6432 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6434 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6438 * clear_types_for_assembly:
6440 * Clears types from loaded_classes for a given assembly
6443 clear_types_for_assembly (MonoAssembly *assembly)
6445 MonoDomain *domain = mono_domain_get ();
6446 AgentDomainInfo *info = NULL;
6448 mono_loader_lock ();
6449 info = get_agent_domain_info (domain);
6450 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6451 mono_loader_unlock ();
6455 add_thread (gpointer key, gpointer value, gpointer user_data)
6457 MonoInternalThread *thread = value;
6458 Buffer *buf = user_data;
6460 buffer_add_objid (buf, (MonoObject*)thread);
6464 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6466 guint8 *end = invoke->endp;
6469 MonoMethodSignature *sig;
6472 MonoObject *this, *res, *exc;
6475 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6478 MonoStopwatch watch;
6480 if (invoke->method) {
6482 * Invoke this method directly, currently only Environment.Exit () is supported.
6485 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>"));
6486 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
6487 g_assert_not_reached ();
6490 m = decode_methodid (p, &p, end, &domain, &err);
6493 sig = mono_method_signature (m);
6495 if (m->klass->valuetype)
6496 this_buf = g_alloca (mono_class_instance_size (m->klass));
6498 this_buf = g_alloca (sizeof (MonoObject*));
6499 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6500 /* Should be null */
6501 int type = decode_byte (p, &p, end);
6502 if (type != VALUE_TYPE_ID_NULL) {
6503 DEBUG (1, fprintf (log_file, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer)GetCurrentThreadId ()));
6504 return ERR_INVALID_ARGUMENT;
6506 memset (this_buf, 0, mono_class_instance_size (m->klass));
6508 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6513 if (!m->klass->valuetype)
6514 this = *(MonoObject**)this_buf;
6518 if (MONO_CLASS_IS_INTERFACE (m->klass)) {
6520 DEBUG (1, fprintf (log_file, "[%p] Error: Interface method invoked without this argument.\n", (gpointer)GetCurrentThreadId ()));
6521 return ERR_INVALID_ARGUMENT;
6523 m = mono_object_get_virtual_method (this, m);
6526 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>"));
6528 if (this && this->vtable->domain != domain)
6531 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
6532 if (!strcmp (m->name, ".ctor")) {
6533 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
6534 return ERR_INVALID_ARGUMENT;
6536 this = mono_object_new (domain, m->klass);
6538 return ERR_INVALID_ARGUMENT;
6542 if (this && !obj_is_of_type (this, &m->klass->byval_arg))
6543 return ERR_INVALID_ARGUMENT;
6545 nargs = decode_int (p, &p, end);
6546 if (nargs != sig->param_count)
6547 return ERR_INVALID_ARGUMENT;
6548 /* Use alloca to get gc tracking */
6549 arg_buf = g_alloca (nargs * sizeof (gpointer));
6550 memset (arg_buf, 0, nargs * sizeof (gpointer));
6551 args = g_alloca (nargs * sizeof (gpointer));
6552 for (i = 0; i < nargs; ++i) {
6553 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6554 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6558 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6561 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6562 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6565 args [i] = arg_buf [i];
6572 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6573 tls->disable_breakpoints = TRUE;
6575 tls->disable_breakpoints = FALSE;
6578 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6580 /* FIXME: Move this to arch specific code */
6581 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6582 if (invoke->has_ctx) {
6585 lmf_addr = mono_get_lmf_addr ();
6588 memset (&ext, 0, sizeof (ext));
6589 mono_arch_init_lmf_ext (&ext, *lmf_addr);
6591 ext.debugger_invoke = TRUE;
6592 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6594 mono_set_lmf ((MonoLMF*)&ext);
6598 mono_stopwatch_start (&watch);
6599 if (m->klass->valuetype)
6600 res = mono_runtime_invoke (m, this_buf, args, &exc);
6602 res = mono_runtime_invoke (m, this, args, &exc);
6603 mono_stopwatch_stop (&watch);
6604 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)));
6606 buffer_add_byte (buf, 0);
6607 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6609 buffer_add_byte (buf, 1);
6610 if (sig->ret->type == MONO_TYPE_VOID) {
6611 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
6612 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
6615 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6616 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6617 buffer_add_value (buf, sig->ret, &res, domain);
6618 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6619 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6620 MonoClass *k = mono_class_from_mono_type (sig->ret);
6621 guint8 *nullable_buf = g_alloca (mono_class_value_size (k, NULL));
6623 g_assert (nullable_buf);
6624 mono_nullable_init (nullable_buf, res, k);
6625 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6628 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6635 tls->disable_breakpoints = FALSE;
6637 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6638 if (invoke->has_ctx)
6639 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
6643 // FIXME: byref arguments
6651 * Invoke the method given by tls->pending_invoke in the current thread.
6654 invoke_method (void)
6656 DebuggerTlsData *tls;
6661 MonoContext restore_ctx;
6664 tls = mono_native_tls_get_value (debugger_tls_id);
6668 * Store the `InvokeData *' in `tls->invoke' until we're done with
6669 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6672 mono_loader_lock ();
6674 invoke = tls->pending_invoke;
6676 tls->pending_invoke = NULL;
6678 invoke->last_invoke = tls->invoke;
6679 tls->invoke = invoke;
6681 mono_loader_unlock ();
6683 tls->frames_up_to_date = FALSE;
6689 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6690 buffer_init (&buf, 128);
6693 /* Fail the other invokes as well */
6695 err = do_invoke_method (tls, &buf, invoke, p, &p);
6698 /* Start suspending before sending the reply */
6699 if (mindex == invoke->nmethods - 1) {
6700 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6701 for (i = 0; i < invoke->suspend_count; ++i)
6706 send_reply_packet (id, err, &buf);
6711 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6713 if (invoke->has_ctx)
6714 save_thread_context (&restore_ctx);
6716 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6717 g_assert (tls->resume_count);
6718 tls->resume_count -= invoke->suspend_count;
6721 DEBUG (1, fprintf (log_file, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer)GetCurrentThreadId (), err, tls->resume_count));
6724 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6726 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
6727 * after the mono_runtime_invoke() already returned, but it doesn't matter
6728 * because we reset the abort here.
6731 mono_loader_lock ();
6733 if (tls->abort_requested)
6734 mono_thread_internal_reset_abort (tls->thread);
6736 tls->invoke = tls->invoke->last_invoke;
6737 tls->abort_requested = FALSE;
6739 mono_loader_unlock ();
6748 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6750 MonoThread *thread = value;
6751 DebuggerTlsData *tls;
6754 mono_loader_lock ();
6755 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6757 res = tls->really_suspended;
6758 mono_loader_unlock ();
6764 get_source_files_for_type (MonoClass *klass)
6766 gpointer iter = NULL;
6768 MonoDebugSourceInfo *sinfo;
6772 files = g_ptr_array_new ();
6774 while ((method = mono_class_get_methods (klass, &iter))) {
6775 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6776 GPtrArray *source_file_list;
6779 mono_debug_symfile_get_line_numbers_full (minfo, NULL, &source_file_list, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
6780 for (j = 0; j < source_file_list->len; ++j) {
6781 sinfo = g_ptr_array_index (source_file_list, j);
6782 for (i = 0; i < files->len; ++i)
6783 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6785 if (i == files->len)
6786 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6788 g_ptr_array_free (source_file_list, TRUE);
6796 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6799 case CMD_VM_VERSION: {
6800 char *build_info, *version;
6802 build_info = mono_get_runtime_build_info ();
6803 version = g_strdup_printf ("mono %s", build_info);
6805 buffer_add_string (buf, version); /* vm version */
6806 buffer_add_int (buf, MAJOR_VERSION);
6807 buffer_add_int (buf, MINOR_VERSION);
6808 g_free (build_info);
6812 case CMD_VM_SET_PROTOCOL_VERSION: {
6813 major_version = decode_int (p, &p, end);
6814 minor_version = decode_int (p, &p, end);
6815 protocol_version_set = TRUE;
6816 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
6819 case CMD_VM_ALL_THREADS: {
6821 mono_loader_lock ();
6822 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6823 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6824 mono_loader_unlock ();
6827 case CMD_VM_SUSPEND:
6829 wait_for_suspend ();
6832 if (suspend_count == 0)
6833 return ERR_NOT_SUSPENDED;
6835 clear_suspended_objs ();
6837 case CMD_VM_DISPOSE:
6838 /* Clear all event requests */
6839 mono_loader_lock ();
6840 while (event_requests->len > 0) {
6841 EventRequest *req = g_ptr_array_index (event_requests, 0);
6843 clear_event_request (req->id, req->event_kind);
6845 mono_loader_unlock ();
6847 while (suspend_count > 0)
6849 disconnected = TRUE;
6850 vm_start_event_sent = FALSE;
6853 MonoInternalThread *thread;
6854 DebuggerTlsData *tls;
6855 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6856 MonoClass *env_class;
6858 MonoMethod *exit_method = NULL;
6862 exit_code = decode_int (p, &p, end);
6864 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6866 /* Have to send a reply before exiting */
6867 send_reply_packet (id, 0, buf);
6869 /* Clear all event requests */
6870 mono_loader_lock ();
6871 while (event_requests->len > 0) {
6872 EventRequest *req = g_ptr_array_index (event_requests, 0);
6874 clear_event_request (req->id, req->event_kind);
6876 mono_loader_unlock ();
6879 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6880 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6881 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6882 * better than doing the shutdown ourselves, since it avoids various races.
6886 wait_for_suspend ();
6888 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6889 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
6891 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6894 mono_loader_lock ();
6895 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6896 mono_loader_unlock ();
6898 if (thread && exit_method) {
6899 mono_loader_lock ();
6900 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6901 mono_loader_unlock ();
6903 args = g_new0 (gpointer, 1);
6904 args [0] = g_malloc (sizeof (int));
6905 *(int*)(args [0]) = exit_code;
6907 tls->pending_invoke = g_new0 (InvokeData, 1);
6908 tls->pending_invoke->method = exit_method;
6909 tls->pending_invoke->args = args;
6910 tls->pending_invoke->nmethods = 1;
6912 while (suspend_count > 0)
6916 * No thread found, do it ourselves.
6917 * FIXME: This can race with normal shutdown etc.
6919 while (suspend_count > 0)
6922 if (!mono_runtime_try_shutdown ())
6925 mono_environment_exitcode_set (exit_code);
6927 /* Suspend all managed threads since the runtime is going away */
6928 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
6929 mono_thread_suspend_all_other_threads ();
6930 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
6931 mono_runtime_quit ();
6932 transport_close2 ();
6933 DEBUG(1, fprintf (log_file, "Exiting...\n"));
6939 case CMD_VM_INVOKE_METHOD:
6940 case CMD_VM_INVOKE_METHODS: {
6941 int objid = decode_objid (p, &p, end);
6943 DebuggerTlsData *tls;
6944 int i, count, err, flags, nmethods;
6946 err = get_object (objid, (MonoObject**)&thread);
6950 flags = decode_int (p, &p, end);
6952 if (command == CMD_VM_INVOKE_METHODS)
6953 nmethods = decode_int (p, &p, end);
6957 // Wait for suspending if it already started
6959 wait_for_suspend ();
6960 if (!is_suspended ())
6961 return ERR_NOT_SUSPENDED;
6963 mono_loader_lock ();
6964 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6965 mono_loader_unlock ();
6968 if (!tls->really_suspended)
6969 /* The thread is still running native code, can't do invokes */
6970 return ERR_NOT_SUSPENDED;
6973 * Store the invoke data into tls, the thread will execute it after it is
6976 if (tls->pending_invoke)
6977 return ERR_NOT_SUSPENDED;
6978 tls->pending_invoke = g_new0 (InvokeData, 1);
6979 tls->pending_invoke->id = id;
6980 tls->pending_invoke->flags = flags;
6981 tls->pending_invoke->p = g_malloc (end - p);
6982 memcpy (tls->pending_invoke->p, p, end - p);
6983 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
6984 tls->pending_invoke->suspend_count = suspend_count;
6985 tls->pending_invoke->nmethods = nmethods;
6987 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
6988 resume_thread (THREAD_TO_INTERNAL (thread));
6991 count = suspend_count;
6992 for (i = 0; i < count; ++i)
6997 case CMD_VM_ABORT_INVOKE: {
6998 int objid = decode_objid (p, &p, end);
7000 DebuggerTlsData *tls;
7003 err = get_object (objid, (MonoObject**)&thread);
7007 invoke_id = decode_int (p, &p, end);
7009 mono_loader_lock ();
7010 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7013 if (tls->abort_requested) {
7014 mono_loader_unlock ();
7019 * Check whether we're still inside the mono_runtime_invoke() and that it's
7020 * actually the correct invocation.
7022 * Careful, we do not stop the thread that's doing the invocation, so we can't
7023 * inspect its stack. However, invoke_method() also acquires the loader lock
7024 * when it's done, so we're safe here.
7028 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
7029 mono_loader_unlock ();
7030 return ERR_NO_INVOCATION;
7033 tls->abort_requested = TRUE;
7035 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
7036 mono_loader_unlock ();
7040 case CMD_VM_SET_KEEPALIVE: {
7041 int timeout = decode_int (p, &p, end);
7042 agent_config.keepalive = timeout;
7044 #ifndef DISABLE_SOCKET_TRANSPORT
7051 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
7052 GHashTableIter iter, kiter;
7057 char *fname, *basename;
7058 gboolean ignore_case;
7059 GSList *class_list, *l;
7060 GPtrArray *res_classes, *res_domains;
7062 fname = decode_string (p, &p, end);
7063 ignore_case = decode_byte (p, &p, end);
7065 basename = g_path_get_basename (fname);
7067 res_classes = g_ptr_array_new ();
7068 res_domains = g_ptr_array_new ();
7070 mono_loader_lock ();
7071 g_hash_table_iter_init (&iter, domains);
7072 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7073 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
7075 /* Update 'source_file_to_class' cache */
7076 g_hash_table_iter_init (&kiter, info->loaded_classes);
7077 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
7078 if (!g_hash_table_lookup (info->source_files, klass)) {
7079 files = get_source_files_for_type (klass);
7080 g_hash_table_insert (info->source_files, klass, files);
7082 for (i = 0; i < files->len; ++i) {
7083 char *s = g_ptr_array_index (files, i);
7084 char *s2 = g_path_get_basename (s);
7087 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
7089 class_list = g_slist_prepend (class_list, klass);
7090 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
7092 class_list = g_slist_prepend (class_list, klass);
7093 g_hash_table_insert (info->source_file_to_class, s2, class_list);
7096 /* The _ignorecase hash contains the lowercase path */
7097 s3 = strdup_tolower (s2);
7098 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
7100 class_list = g_slist_prepend (class_list, klass);
7101 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
7103 class_list = g_slist_prepend (class_list, klass);
7104 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
7116 s = strdup_tolower (basename);
7117 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
7120 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
7123 for (l = class_list; l; l = l->next) {
7126 g_ptr_array_add (res_classes, klass);
7127 g_ptr_array_add (res_domains, domain);
7130 mono_loader_unlock ();
7135 buffer_add_int (buf, res_classes->len);
7136 for (i = 0; i < res_classes->len; ++i)
7137 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
7138 g_ptr_array_free (res_classes, TRUE);
7139 g_ptr_array_free (res_domains, TRUE);
7142 case CMD_VM_GET_TYPES: {
7143 GHashTableIter iter;
7147 gboolean ignore_case;
7148 GPtrArray *res_classes, *res_domains;
7149 MonoTypeNameParse info;
7151 name = decode_string (p, &p, end);
7152 ignore_case = decode_byte (p, &p, end);
7154 if (!mono_reflection_parse_type (name, &info)) {
7156 mono_reflection_free_type_info (&info);
7157 return ERR_INVALID_ARGUMENT;
7160 res_classes = g_ptr_array_new ();
7161 res_domains = g_ptr_array_new ();
7163 mono_loader_lock ();
7164 g_hash_table_iter_init (&iter, domains);
7165 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7167 gboolean type_resolve;
7171 mono_domain_assemblies_lock (domain);
7172 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7176 type_resolve = TRUE;
7177 t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
7179 g_ptr_array_add (res_classes, mono_type_get_class (t));
7180 g_ptr_array_add (res_domains, domain);
7184 mono_domain_assemblies_unlock (domain);
7186 mono_loader_unlock ();
7189 mono_reflection_free_type_info (&info);
7191 buffer_add_int (buf, res_classes->len);
7192 for (i = 0; i < res_classes->len; ++i)
7193 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
7194 g_ptr_array_free (res_classes, TRUE);
7195 g_ptr_array_free (res_domains, TRUE);
7198 case CMD_VM_START_BUFFERING:
7199 case CMD_VM_STOP_BUFFERING:
7200 /* Handled in the main loop */
7203 return ERR_NOT_IMPLEMENTED;
7210 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7216 case CMD_EVENT_REQUEST_SET: {
7218 int i, event_kind, suspend_policy, nmodifiers, mod;
7221 MonoThread *step_thread;
7222 int size = 0, depth = 0, filter = 0, step_thread_id = 0;
7226 event_kind = decode_byte (p, &p, end);
7227 suspend_policy = decode_byte (p, &p, end);
7228 nmodifiers = decode_byte (p, &p, end);
7230 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7231 req->id = InterlockedIncrement (&event_request_id);
7232 req->event_kind = event_kind;
7233 req->suspend_policy = suspend_policy;
7234 req->nmodifiers = nmodifiers;
7237 for (i = 0; i < nmodifiers; ++i) {
7238 mod = decode_byte (p, &p, end);
7240 req->modifiers [i].kind = mod;
7241 if (mod == MOD_KIND_COUNT) {
7242 req->modifiers [i].data.count = decode_int (p, &p, end);
7243 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7244 method = decode_methodid (p, &p, end, &domain, &err);
7247 location = decode_long (p, &p, end);
7248 } else if (mod == MOD_KIND_STEP) {
7249 step_thread_id = decode_id (p, &p, end);
7250 size = decode_int (p, &p, end);
7251 depth = decode_int (p, &p, end);
7252 if (CHECK_PROTOCOL_VERSION (2, 16))
7253 filter = decode_int (p, &p, end);
7254 req->modifiers [i].data.filter = filter;
7255 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7256 /* Treat STEP_THOUGH the same as HIDDEN */
7257 req->modifiers [i].data.filter |= STEP_FILTER_DEBUGGER_STEP_THROUGH;
7258 } else if (mod == MOD_KIND_THREAD_ONLY) {
7259 int id = decode_id (p, &p, end);
7261 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7266 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7267 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7271 req->modifiers [i].caught = decode_byte (p, &p, end);
7272 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7273 if (CHECK_PROTOCOL_VERSION (2, 25))
7274 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7276 req->modifiers [i].subclasses = TRUE;
7277 DEBUG(1, fprintf (log_file, "[dbg] \tEXCEPTION_ONLY filter (%s%s%s%s).\n", exc_class ? exc_class->name : "all", req->modifiers [i].caught ? ", caught" : "", req->modifiers [i].uncaught ? ", uncaught" : "", req->modifiers [i].subclasses ? ", include-subclasses" : ""));
7279 req->modifiers [i].data.exc_class = exc_class;
7281 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
7283 return ERR_INVALID_ARGUMENT;
7286 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7287 int n = decode_int (p, &p, end);
7290 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
7291 for (j = 0; j < n; ++j) {
7292 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7294 g_free (req->modifiers [i].data.assemblies);
7298 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7299 int n = decode_int (p, &p, end);
7302 modifier = &req->modifiers [i];
7303 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7304 for (j = 0; j < n; ++j) {
7305 char *s = decode_string (p, &p, end);
7309 s2 = strdup_tolower (s);
7310 g_hash_table_insert (modifier->data.source_files, s2, s2);
7314 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7315 int n = decode_int (p, &p, end);
7318 modifier = &req->modifiers [i];
7319 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7320 for (j = 0; j < n; ++j) {
7321 char *s = decode_string (p, &p, end);
7324 g_hash_table_insert (modifier->data.type_names, s, s);
7328 return ERR_NOT_IMPLEMENTED;
7332 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7335 req->info = set_breakpoint (method, location, req, &error);
7336 if (!mono_error_ok (&error)) {
7338 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
7339 mono_error_cleanup (&error);
7340 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7342 } else if (req->event_kind == EVENT_KIND_STEP) {
7343 g_assert (step_thread_id);
7345 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7351 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
7356 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7357 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7358 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7359 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7360 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7361 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7363 if (req->nmodifiers) {
7365 return ERR_NOT_IMPLEMENTED;
7369 mono_loader_lock ();
7370 g_ptr_array_add (event_requests, req);
7372 if (agent_config.defer) {
7373 /* Transmit cached data to the client on receipt of the event request */
7374 switch (req->event_kind) {
7375 case EVENT_KIND_APPDOMAIN_CREATE:
7376 /* Emit load events for currently loaded domains */
7377 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7379 case EVENT_KIND_ASSEMBLY_LOAD:
7380 /* Emit load events for currently loaded assemblies */
7381 mono_assembly_foreach (emit_assembly_load, NULL);
7383 case EVENT_KIND_THREAD_START:
7384 /* Emit start events for currently started threads */
7385 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7387 case EVENT_KIND_TYPE_LOAD:
7388 /* Emit type load events for currently loaded types */
7389 mono_domain_foreach (send_types_for_domain, NULL);
7395 mono_loader_unlock ();
7397 buffer_add_int (buf, req->id);
7400 case CMD_EVENT_REQUEST_CLEAR: {
7401 int etype = decode_byte (p, &p, end);
7402 int req_id = decode_int (p, &p, end);
7404 // FIXME: Make a faster mapping from req_id to request
7405 mono_loader_lock ();
7406 clear_event_request (req_id, etype);
7407 mono_loader_unlock ();
7410 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7413 mono_loader_lock ();
7415 while (i < event_requests->len) {
7416 EventRequest *req = g_ptr_array_index (event_requests, i);
7418 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7419 clear_breakpoint (req->info);
7421 g_ptr_array_remove_index_fast (event_requests, i);
7427 mono_loader_unlock ();
7431 return ERR_NOT_IMPLEMENTED;
7438 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7444 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7445 buffer_add_domainid (buf, mono_get_root_domain ());
7448 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7449 domain = decode_domainid (p, &p, end, NULL, &err);
7452 buffer_add_string (buf, domain->friendly_name);
7455 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7460 domain = decode_domainid (p, &p, end, NULL, &err);
7463 mono_loader_lock ();
7465 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7468 buffer_add_int (buf, count);
7469 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7471 buffer_add_assemblyid (buf, domain, ass);
7473 mono_loader_unlock ();
7476 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7477 domain = decode_domainid (p, &p, end, NULL, &err);
7481 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7484 case CMD_APPDOMAIN_GET_CORLIB: {
7485 domain = decode_domainid (p, &p, end, NULL, &err);
7489 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7492 case CMD_APPDOMAIN_CREATE_STRING: {
7496 domain = decode_domainid (p, &p, end, NULL, &err);
7499 s = decode_string (p, &p, end);
7501 o = mono_string_new (domain, s);
7502 buffer_add_objid (buf, (MonoObject*)o);
7505 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7507 MonoDomain *domain2;
7510 domain = decode_domainid (p, &p, end, NULL, &err);
7513 klass = decode_typeid (p, &p, end, &domain2, &err);
7518 g_assert (domain == domain2);
7520 o = mono_object_new (domain, klass);
7522 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
7526 buffer_add_objid (buf, o);
7530 return ERR_NOT_IMPLEMENTED;
7537 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7543 ass = decode_assemblyid (p, &p, end, &domain, &err);
7548 case CMD_ASSEMBLY_GET_LOCATION: {
7549 buffer_add_string (buf, mono_image_get_filename (ass->image));
7552 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7556 if (ass->image->dynamic) {
7557 buffer_add_id (buf, 0);
7559 token = mono_image_get_entry_point (ass->image);
7561 buffer_add_id (buf, 0);
7563 m = mono_get_method (ass->image, token, NULL);
7564 buffer_add_methodid (buf, domain, m);
7569 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7570 buffer_add_moduleid (buf, domain, ass->image);
7573 case CMD_ASSEMBLY_GET_OBJECT: {
7574 MonoObject *o = (MonoObject*)mono_assembly_get_object (domain, ass);
7575 buffer_add_objid (buf, o);
7578 case CMD_ASSEMBLY_GET_TYPE: {
7579 char *s = decode_string (p, &p, end);
7580 gboolean ignorecase = decode_byte (p, &p, end);
7581 MonoTypeNameParse info;
7583 gboolean type_resolve, res;
7584 MonoDomain *d = mono_domain_get ();
7586 /* This is needed to be able to find referenced assemblies */
7587 res = mono_domain_set (domain, FALSE);
7590 if (!mono_reflection_parse_type (s, &info)) {
7593 if (info.assembly.name)
7595 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
7597 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
7598 mono_reflection_free_type_info (&info);
7601 mono_domain_set (d, TRUE);
7605 case CMD_ASSEMBLY_GET_NAME: {
7607 MonoAssembly *mass = ass;
7609 name = g_strdup_printf (
7610 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7612 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7613 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7614 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7615 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7617 buffer_add_string (buf, name);
7622 return ERR_NOT_IMPLEMENTED;
7629 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7635 case CMD_MODULE_GET_INFO: {
7636 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7639 basename = g_path_get_basename (image->name);
7640 buffer_add_string (buf, basename); // name
7641 buffer_add_string (buf, image->module_name); // scopename
7642 buffer_add_string (buf, image->name); // fqname
7643 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7644 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7649 return ERR_NOT_IMPLEMENTED;
7656 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7662 case CMD_FIELD_GET_INFO: {
7663 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
7665 buffer_add_string (buf, f->name);
7666 buffer_add_typeid (buf, domain, f->parent);
7667 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7668 buffer_add_int (buf, f->type->attrs);
7672 return ERR_NOT_IMPLEMENTED;
7679 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7681 if (val && val->vtable->klass == mono_defaults.monotype_class) {
7682 /* Special case these so the client doesn't have to handle Type objects */
7684 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7685 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7686 } else if (MONO_TYPE_IS_REFERENCE (t))
7687 buffer_add_value (buf, t, &val, domain);
7689 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7693 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7699 buffer_add_int (buf, 0);
7703 for (i = 0; i < cinfo->num_attrs; ++i) {
7704 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7707 buffer_add_int (buf, nattrs);
7709 for (i = 0; i < cinfo->num_attrs; ++i) {
7710 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7711 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7712 MonoArray *typed_args, *named_args;
7714 CattrNamedArg *arginfo = NULL;
7717 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
7718 g_assert (mono_error_ok (&error));
7720 buffer_add_methodid (buf, domain, attr->ctor);
7724 buffer_add_int (buf, mono_array_length (typed_args));
7725 for (j = 0; j < mono_array_length (typed_args); ++j) {
7726 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7728 t = mono_method_signature (attr->ctor)->params [j];
7730 buffer_add_cattr_arg (buf, t, domain, val);
7733 buffer_add_int (buf, 0);
7738 buffer_add_int (buf, mono_array_length (named_args));
7740 for (j = 0; j < mono_array_length (named_args); ++j) {
7741 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7743 if (arginfo [j].prop) {
7744 buffer_add_byte (buf, 0x54);
7745 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7746 } else if (arginfo [j].field) {
7747 buffer_add_byte (buf, 0x53);
7748 buffer_add_fieldid (buf, domain, arginfo [j].field);
7750 g_assert_not_reached ();
7753 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7756 buffer_add_int (buf, 0);
7763 /* FIXME: Code duplication with icall.c */
7765 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7770 mono_class_setup_interfaces (klass, error);
7771 if (!mono_error_ok (error))
7774 for (i = 0; i < klass->interface_count; i++) {
7775 ic = klass->interfaces [i];
7776 g_hash_table_insert (ifaces, ic, ic);
7778 collect_interfaces (ic, ifaces, error);
7779 if (!mono_error_ok (error))
7785 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7795 case CMD_TYPE_GET_INFO: {
7796 buffer_add_string (buf, klass->name_space);
7797 buffer_add_string (buf, klass->name);
7799 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7800 buffer_add_string (buf, name);
7802 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7803 buffer_add_moduleid (buf, domain, klass->image);
7804 buffer_add_typeid (buf, domain, klass->parent);
7805 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7806 buffer_add_typeid (buf, domain, klass->element_class);
7808 buffer_add_id (buf, 0);
7809 buffer_add_int (buf, klass->type_token);
7810 buffer_add_byte (buf, klass->rank);
7811 buffer_add_int (buf, klass->flags);
7813 type = &klass->byval_arg;
7814 // FIXME: Can't decide whenever a class represents a byref type
7817 if (type->type == MONO_TYPE_PTR)
7819 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7821 if (type->type == MONO_TYPE_VALUETYPE)
7823 if (klass->enumtype)
7825 if (klass->generic_container)
7827 if (klass->generic_container || klass->generic_class)
7829 buffer_add_byte (buf, b);
7832 while ((nested = mono_class_get_nested_types (klass, &iter)))
7834 buffer_add_int (buf, nnested);
7836 while ((nested = mono_class_get_nested_types (klass, &iter)))
7837 buffer_add_typeid (buf, domain, nested);
7838 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7839 if (klass->generic_container)
7840 buffer_add_typeid (buf, domain, klass);
7841 else if (klass->generic_class)
7842 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7844 buffer_add_id (buf, 0);
7846 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7849 if (klass->generic_class) {
7850 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7852 count = inst->type_argc;
7853 buffer_add_int (buf, count);
7854 for (i = 0; i < count; i++)
7855 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7856 } else if (klass->generic_container) {
7857 MonoGenericContainer *container = klass->generic_container;
7860 count = container->type_argc;
7861 buffer_add_int (buf, count);
7862 for (i = 0; i < count; i++) {
7863 pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
7864 buffer_add_typeid (buf, domain, pklass);
7867 buffer_add_int (buf, 0);
7872 case CMD_TYPE_GET_METHODS: {
7875 gpointer iter = NULL;
7878 mono_class_setup_methods (klass);
7880 nmethods = mono_class_num_methods (klass);
7882 buffer_add_int (buf, nmethods);
7884 while ((m = mono_class_get_methods (klass, &iter))) {
7885 buffer_add_methodid (buf, domain, m);
7888 g_assert (i == nmethods);
7891 case CMD_TYPE_GET_FIELDS: {
7894 gpointer iter = NULL;
7897 nfields = mono_class_num_fields (klass);
7899 buffer_add_int (buf, nfields);
7901 while ((f = mono_class_get_fields (klass, &iter))) {
7902 buffer_add_fieldid (buf, domain, f);
7903 buffer_add_string (buf, f->name);
7904 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7905 buffer_add_int (buf, f->type->attrs);
7908 g_assert (i == nfields);
7911 case CMD_TYPE_GET_PROPERTIES: {
7914 gpointer iter = NULL;
7917 nprops = mono_class_num_properties (klass);
7919 buffer_add_int (buf, nprops);
7921 while ((p = mono_class_get_properties (klass, &iter))) {
7922 buffer_add_propertyid (buf, domain, p);
7923 buffer_add_string (buf, p->name);
7924 buffer_add_methodid (buf, domain, p->get);
7925 buffer_add_methodid (buf, domain, p->set);
7926 buffer_add_int (buf, p->attrs);
7929 g_assert (i == nprops);
7932 case CMD_TYPE_GET_CATTRS: {
7933 MonoClass *attr_klass;
7934 MonoCustomAttrInfo *cinfo;
7936 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7937 /* attr_klass can be NULL */
7941 cinfo = mono_custom_attrs_from_class (klass);
7943 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7946 case CMD_TYPE_GET_FIELD_CATTRS: {
7947 MonoClass *attr_klass;
7948 MonoCustomAttrInfo *cinfo;
7949 MonoClassField *field;
7951 field = decode_fieldid (p, &p, end, NULL, &err);
7954 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7958 cinfo = mono_custom_attrs_from_field (klass, field);
7960 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7963 case CMD_TYPE_GET_PROPERTY_CATTRS: {
7964 MonoClass *attr_klass;
7965 MonoCustomAttrInfo *cinfo;
7968 prop = decode_propertyid (p, &p, end, NULL, &err);
7971 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7975 cinfo = mono_custom_attrs_from_property (klass, prop);
7977 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7980 case CMD_TYPE_GET_VALUES:
7981 case CMD_TYPE_GET_VALUES_2: {
7988 MonoThread *thread_obj;
7989 MonoInternalThread *thread = NULL;
7990 guint32 special_static_type;
7992 if (command == CMD_TYPE_GET_VALUES_2) {
7993 int objid = decode_objid (p, &p, end);
7996 err = get_object (objid, (MonoObject**)&thread_obj);
8000 thread = THREAD_TO_INTERNAL (thread_obj);
8003 len = decode_int (p, &p, end);
8004 for (i = 0; i < len; ++i) {
8005 f = decode_fieldid (p, &p, end, NULL, &err);
8009 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8010 return ERR_INVALID_FIELDID;
8011 special_static_type = mono_class_field_get_special_static_type (f);
8012 if (special_static_type != SPECIAL_STATIC_NONE) {
8013 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
8014 return ERR_INVALID_FIELDID;
8017 /* Check that the field belongs to the object */
8019 for (k = klass; k; k = k->parent) {
8020 if (k == f->parent) {
8026 return ERR_INVALID_FIELDID;
8028 vtable = mono_class_vtable (domain, f->parent);
8029 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8030 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
8031 buffer_add_value (buf, f->type, val, domain);
8036 case CMD_TYPE_SET_VALUES: {
8044 len = decode_int (p, &p, end);
8045 for (i = 0; i < len; ++i) {
8046 f = decode_fieldid (p, &p, end, NULL, &err);
8050 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8051 return ERR_INVALID_FIELDID;
8052 if (mono_class_field_is_special_static (f))
8053 return ERR_INVALID_FIELDID;
8055 /* Check that the field belongs to the object */
8057 for (k = klass; k; k = k->parent) {
8058 if (k == f->parent) {
8064 return ERR_INVALID_FIELDID;
8066 // FIXME: Check for literal/const
8068 vtable = mono_class_vtable (domain, f->parent);
8069 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8070 err = decode_value (f->type, domain, val, p, &p, end);
8075 if (MONO_TYPE_IS_REFERENCE (f->type))
8076 mono_field_static_set_value (vtable, f, *(gpointer*)val);
8078 mono_field_static_set_value (vtable, f, val);
8083 case CMD_TYPE_GET_OBJECT: {
8084 MonoObject *o = (MonoObject*)mono_type_get_object (domain, &klass->byval_arg);
8085 buffer_add_objid (buf, o);
8088 case CMD_TYPE_GET_SOURCE_FILES:
8089 case CMD_TYPE_GET_SOURCE_FILES_2: {
8090 char *source_file, *base;
8094 files = get_source_files_for_type (klass);
8096 buffer_add_int (buf, files->len);
8097 for (i = 0; i < files->len; ++i) {
8098 source_file = g_ptr_array_index (files, i);
8099 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8100 buffer_add_string (buf, source_file);
8102 base = g_path_get_basename (source_file);
8103 buffer_add_string (buf, base);
8106 g_free (source_file);
8108 g_ptr_array_free (files, TRUE);
8111 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8112 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8116 if (mono_class_is_assignable_from (klass, oklass))
8117 buffer_add_byte (buf, 1);
8119 buffer_add_byte (buf, 0);
8122 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8123 char *name = decode_string (p, &p, end);
8124 int i, flags = decode_int (p, &p, end);
8125 MonoException *ex = NULL;
8126 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
8129 return ERR_LOADER_ERROR;
8130 buffer_add_int (buf, array->len);
8131 for (i = 0; i < array->len; ++i) {
8132 MonoMethod *method = g_ptr_array_index (array, i);
8133 buffer_add_methodid (buf, domain, method);
8136 g_ptr_array_free (array, TRUE);
8140 case CMD_TYPE_GET_INTERFACES: {
8142 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8144 MonoClass *tclass, *iface;
8145 GHashTableIter iter;
8149 for (parent = tclass; parent; parent = parent->parent) {
8150 mono_class_setup_interfaces (parent, &error);
8151 if (!mono_error_ok (&error))
8152 return ERR_LOADER_ERROR;
8153 collect_interfaces (parent, iface_hash, &error);
8154 if (!mono_error_ok (&error))
8155 return ERR_LOADER_ERROR;
8158 buffer_add_int (buf, g_hash_table_size (iface_hash));
8160 g_hash_table_iter_init (&iter, iface_hash);
8161 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8162 buffer_add_typeid (buf, domain, iface);
8163 g_hash_table_destroy (iface_hash);
8166 case CMD_TYPE_GET_INTERFACE_MAP: {
8167 int tindex, ioffset;
8168 gboolean variance_used;
8170 int len, nmethods, i;
8174 len = decode_int (p, &p, end);
8175 mono_class_setup_vtable (klass);
8177 for (tindex = 0; tindex < len; ++tindex) {
8178 iclass = decode_typeid (p, &p, end, NULL, &err);
8182 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8184 return ERR_INVALID_ARGUMENT;
8186 nmethods = mono_class_num_methods (iclass);
8187 buffer_add_int (buf, nmethods);
8190 while ((method = mono_class_get_methods (iclass, &iter))) {
8191 buffer_add_methodid (buf, domain, method);
8193 for (i = 0; i < nmethods; ++i)
8194 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
8198 case CMD_TYPE_IS_INITIALIZED: {
8199 MonoVTable *vtable = mono_class_vtable (domain, klass);
8202 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8204 buffer_add_int (buf, 0);
8207 case CMD_TYPE_CREATE_INSTANCE: {
8210 obj = mono_object_new (domain, klass);
8211 buffer_add_objid (buf, obj);
8215 return ERR_NOT_IMPLEMENTED;
8222 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8225 MonoDomain *old_domain;
8229 klass = decode_typeid (p, &p, end, &domain, &err);
8233 old_domain = mono_domain_get ();
8235 mono_domain_set (domain, TRUE);
8237 err = type_commands_internal (command, klass, domain, p, end, buf);
8239 mono_domain_set (old_domain, TRUE);
8245 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8247 MonoMethodHeader *header;
8251 case CMD_METHOD_GET_NAME: {
8252 buffer_add_string (buf, method->name);
8255 case CMD_METHOD_GET_DECLARING_TYPE: {
8256 buffer_add_typeid (buf, domain, method->klass);
8259 case CMD_METHOD_GET_DEBUG_INFO: {
8260 MonoDebugMethodInfo *minfo;
8262 int i, j, n_il_offsets;
8265 int *column_numbers;
8266 int *end_line_numbers;
8267 int *end_column_numbers;
8269 GPtrArray *source_file_list;
8271 header = mono_method_get_header (method);
8273 buffer_add_int (buf, 0);
8274 buffer_add_string (buf, "");
8275 buffer_add_int (buf, 0);
8279 minfo = mono_debug_lookup_method (method);
8281 buffer_add_int (buf, header->code_size);
8282 buffer_add_string (buf, "");
8283 buffer_add_int (buf, 0);
8284 mono_metadata_free_mh (header);
8288 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, &n_il_offsets, &il_offsets, &line_numbers, &column_numbers, &source_files, &end_line_numbers, &end_column_numbers);
8289 buffer_add_int (buf, header->code_size);
8290 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8291 buffer_add_int (buf, source_file_list->len);
8292 for (i = 0; i < source_file_list->len; ++i) {
8293 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
8294 buffer_add_string (buf, sinfo->source_file);
8295 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8296 for (j = 0; j < 16; ++j)
8297 buffer_add_byte (buf, sinfo->hash [j]);
8301 buffer_add_string (buf, source_file);
8303 buffer_add_int (buf, n_il_offsets);
8304 DEBUG (10, fprintf (log_file, "Line number table for method %s:\n", mono_method_full_name (method, TRUE)));
8305 for (i = 0; i < n_il_offsets; ++i) {
8306 const char *srcfile = "";
8308 if (source_files [i] != -1) {
8309 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
8310 srcfile = sinfo->source_file;
8312 DEBUG (10, fprintf (log_file, "IL%x -> %s:%d %d\n", il_offsets [i], srcfile, line_numbers [i], column_numbers ? column_numbers [i] : -1));
8313 buffer_add_int (buf, il_offsets [i]);
8314 buffer_add_int (buf, line_numbers [i]);
8315 if (CHECK_PROTOCOL_VERSION (2, 13))
8316 buffer_add_int (buf, source_files [i]);
8317 if (CHECK_PROTOCOL_VERSION (2, 19))
8318 buffer_add_int (buf, column_numbers ? column_numbers [i] : -1);
8319 if (CHECK_PROTOCOL_VERSION (2, 32)) {
8320 buffer_add_int (buf, end_line_numbers ? end_line_numbers [i] : -1);
8321 buffer_add_int (buf, end_column_numbers ? end_column_numbers [i] : -1);
8324 g_free (source_file);
8325 g_free (il_offsets);
8326 g_free (line_numbers);
8327 g_free (column_numbers);
8328 g_free (end_line_numbers);
8329 g_free (end_column_numbers);
8330 g_free (source_files);
8331 g_ptr_array_free (source_file_list, TRUE);
8332 mono_metadata_free_mh (header);
8335 case CMD_METHOD_GET_PARAM_INFO: {
8336 MonoMethodSignature *sig = mono_method_signature (method);
8340 /* FIXME: mono_class_from_mono_type () and byrefs */
8342 /* FIXME: Use a smaller encoding */
8343 buffer_add_int (buf, sig->call_convention);
8344 buffer_add_int (buf, sig->param_count);
8345 buffer_add_int (buf, sig->generic_param_count);
8346 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
8347 for (i = 0; i < sig->param_count; ++i) {
8349 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
8352 /* Emit parameter names */
8353 names = g_new (char *, sig->param_count);
8354 mono_method_get_param_names (method, (const char **) names);
8355 for (i = 0; i < sig->param_count; ++i)
8356 buffer_add_string (buf, names [i]);
8361 case CMD_METHOD_GET_LOCALS_INFO: {
8362 int i, j, num_locals;
8363 MonoDebugLocalsInfo *locals;
8365 header = mono_method_get_header (method);
8367 return ERR_INVALID_ARGUMENT;
8369 buffer_add_int (buf, header->num_locals);
8372 for (i = 0; i < header->num_locals; ++i)
8373 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
8376 locals = mono_debug_lookup_locals (method);
8378 num_locals = locals->num_locals;
8381 for (i = 0; i < header->num_locals; ++i) {
8382 for (j = 0; j < num_locals; ++j)
8383 if (locals->locals [j].index == i)
8386 buffer_add_string (buf, locals->locals [j].name);
8388 buffer_add_string (buf, "");
8392 for (i = 0; i < header->num_locals; ++i) {
8393 for (j = 0; j < num_locals; ++j)
8394 if (locals->locals [j].index == i)
8396 if (j < num_locals && locals->locals [j].block) {
8397 buffer_add_int (buf, locals->locals [j].block->start_offset);
8398 buffer_add_int (buf, locals->locals [j].block->end_offset);
8400 buffer_add_int (buf, 0);
8401 buffer_add_int (buf, header->code_size);
8404 mono_metadata_free_mh (header);
8407 mono_debug_symfile_free_locals (locals);
8411 case CMD_METHOD_GET_INFO:
8412 buffer_add_int (buf, method->flags);
8413 buffer_add_int (buf, method->iflags);
8414 buffer_add_int (buf, method->token);
8415 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8417 if (method->is_generic)
8419 if (mono_method_signature (method)->generic_param_count)
8421 buffer_add_byte (buf, attrs);
8422 if (method->is_generic || method->is_inflated) {
8425 if (method->is_generic) {
8428 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8430 result = imethod->declaring;
8431 if (imethod->context.class_inst) {
8432 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8433 /*Generic methods gets the context of the GTD.*/
8434 if (mono_class_get_context (klass))
8435 result = mono_class_inflate_generic_method_full (result, klass, mono_class_get_context (klass));
8439 buffer_add_methodid (buf, domain, result);
8441 buffer_add_id (buf, 0);
8443 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8444 if (mono_method_signature (method)->generic_param_count) {
8447 if (method->is_inflated) {
8448 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
8450 count = inst->type_argc;
8451 buffer_add_int (buf, count);
8453 for (i = 0; i < count; i++)
8454 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8456 buffer_add_int (buf, 0);
8458 } else if (method->is_generic) {
8459 MonoGenericContainer *container = mono_method_get_generic_container (method);
8461 count = mono_method_signature (method)->generic_param_count;
8462 buffer_add_int (buf, count);
8463 for (i = 0; i < count; i++) {
8464 MonoGenericParam *param = mono_generic_container_get_param (container, i);
8465 MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
8466 buffer_add_typeid (buf, domain, pklass);
8469 buffer_add_int (buf, 0);
8472 buffer_add_int (buf, 0);
8477 case CMD_METHOD_GET_BODY: {
8480 header = mono_method_get_header (method);
8482 buffer_add_int (buf, 0);
8484 if (CHECK_PROTOCOL_VERSION (2, 18))
8485 buffer_add_int (buf, 0);
8487 buffer_add_int (buf, header->code_size);
8488 for (i = 0; i < header->code_size; ++i)
8489 buffer_add_byte (buf, header->code [i]);
8491 if (CHECK_PROTOCOL_VERSION (2, 18)) {
8492 buffer_add_int (buf, header->num_clauses);
8493 for (i = 0; i < header->num_clauses; ++i) {
8494 MonoExceptionClause *clause = &header->clauses [i];
8496 buffer_add_int (buf, clause->flags);
8497 buffer_add_int (buf, clause->try_offset);
8498 buffer_add_int (buf, clause->try_len);
8499 buffer_add_int (buf, clause->handler_offset);
8500 buffer_add_int (buf, clause->handler_len);
8501 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
8502 buffer_add_typeid (buf, domain, clause->data.catch_class);
8503 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8504 buffer_add_int (buf, clause->data.filter_offset);
8508 mono_metadata_free_mh (header);
8513 case CMD_METHOD_RESOLVE_TOKEN: {
8514 guint32 token = decode_int (p, &p, end);
8517 switch (mono_metadata_token_code (token)) {
8518 case MONO_TOKEN_STRING: {
8522 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
8525 s2 = mono_string_to_utf8 (s);
8527 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8528 buffer_add_string (buf, s2);
8534 MonoClass *handle_class;
8536 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8537 val = mono_method_get_wrapper_data (method, token);
8538 handle_class = mono_method_get_wrapper_data (method, token + 1);
8540 if (handle_class == NULL) {
8541 // Can't figure out the token type
8542 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8546 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
8550 if (handle_class == mono_defaults.typehandle_class) {
8551 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8552 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8553 buffer_add_typeid (buf, domain, (MonoClass *) val);
8555 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
8556 } else if (handle_class == mono_defaults.fieldhandle_class) {
8557 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8558 buffer_add_fieldid (buf, domain, val);
8559 } else if (handle_class == mono_defaults.methodhandle_class) {
8560 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8561 buffer_add_methodid (buf, domain, val);
8562 } else if (handle_class == mono_defaults.string_class) {
8565 s = mono_string_to_utf8 (val);
8566 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8567 buffer_add_string (buf, s);
8570 g_assert_not_reached ();
8577 case CMD_METHOD_GET_CATTRS: {
8578 MonoClass *attr_klass;
8579 MonoCustomAttrInfo *cinfo;
8581 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8582 /* attr_klass can be NULL */
8586 cinfo = mono_custom_attrs_from_method (method);
8588 buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
8591 case CMD_METHOD_MAKE_GENERIC_METHOD: {
8592 MonoType **type_argv;
8596 MonoGenericInst *ginst;
8597 MonoGenericContext tmp_context;
8598 MonoMethod *inflated;
8600 type_argc = decode_int (p, &p, end);
8601 type_argv = g_new0 (MonoType*, type_argc);
8602 for (i = 0; i < type_argc; ++i) {
8603 klass = decode_typeid (p, &p, end, &d, &err);
8610 return ERR_INVALID_ARGUMENT;
8612 type_argv [i] = &klass->byval_arg;
8614 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
8616 tmp_context.class_inst = method->klass->generic_class ? method->klass->generic_class->context.class_inst : NULL;
8617 tmp_context.method_inst = ginst;
8619 inflated = mono_class_inflate_generic_method (method, &tmp_context);
8620 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
8621 return ERR_INVALID_ARGUMENT;
8622 buffer_add_methodid (buf, domain, inflated);
8626 return ERR_NOT_IMPLEMENTED;
8633 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8636 MonoDomain *old_domain;
8640 method = decode_methodid (p, &p, end, &domain, &err);
8644 old_domain = mono_domain_get ();
8646 mono_domain_set (domain, TRUE);
8648 err = method_commands_internal (command, method, domain, p, end, buf);
8650 mono_domain_set (old_domain, TRUE);
8656 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8658 int objid = decode_objid (p, &p, end);
8660 MonoThread *thread_obj;
8661 MonoInternalThread *thread;
8663 err = get_object (objid, (MonoObject**)&thread_obj);
8667 thread = THREAD_TO_INTERNAL (thread_obj);
8670 case CMD_THREAD_GET_NAME: {
8672 gunichar2 *s = mono_thread_get_name (thread, &name_len);
8675 buffer_add_int (buf, 0);
8680 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
8682 buffer_add_int (buf, len);
8683 buffer_add_data (buf, (guint8*)name, len);
8688 case CMD_THREAD_GET_FRAME_INFO: {
8689 DebuggerTlsData *tls;
8690 int i, start_frame, length;
8692 // Wait for suspending if it already started
8693 // FIXME: Races with suspend_count
8694 while (!is_suspended ()) {
8696 wait_for_suspend ();
8700 wait_for_suspend ();
8701 if (!is_suspended ())
8702 return ERR_NOT_SUSPENDED;
8705 start_frame = decode_int (p, &p, end);
8706 length = decode_int (p, &p, end);
8708 if (start_frame != 0 || length != -1)
8709 return ERR_NOT_IMPLEMENTED;
8711 mono_loader_lock ();
8712 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8713 mono_loader_unlock ();
8716 compute_frame_info (thread, tls);
8718 buffer_add_int (buf, tls->frame_count);
8719 for (i = 0; i < tls->frame_count; ++i) {
8720 buffer_add_int (buf, tls->frames [i]->id);
8721 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
8722 buffer_add_int (buf, tls->frames [i]->il_offset);
8724 * Instead of passing the frame type directly to the client, we associate
8725 * it with the previous frame using a set of flags. This avoids lots of
8726 * conditional code in the client, since a frame whose type isn't
8727 * FRAME_TYPE_MANAGED has no method, location, etc.
8729 buffer_add_byte (buf, tls->frames [i]->flags);
8734 case CMD_THREAD_GET_STATE:
8735 buffer_add_int (buf, thread->state);
8737 case CMD_THREAD_GET_INFO:
8738 buffer_add_byte (buf, thread->threadpool_thread);
8740 case CMD_THREAD_GET_ID:
8741 buffer_add_long (buf, (guint64)(gsize)thread);
8743 case CMD_THREAD_GET_TID:
8744 buffer_add_long (buf, (guint64)thread->tid);
8746 case CMD_THREAD_SET_IP: {
8747 DebuggerTlsData *tls;
8750 MonoSeqPointInfo *seq_points;
8751 SeqPoint *sp = NULL;
8755 method = decode_methodid (p, &p, end, &domain, &err);
8758 il_offset = decode_long (p, &p, end);
8760 while (!is_suspended ()) {
8762 wait_for_suspend ();
8765 mono_loader_lock ();
8766 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8767 mono_loader_unlock ();
8770 compute_frame_info (thread, tls);
8771 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
8772 return ERR_INVALID_ARGUMENT;
8774 seq_points = get_seq_points (domain, method);
8775 g_assert (seq_points);
8777 for (i = 0; i < seq_points->len; ++i) {
8778 sp = &seq_points->seq_points [i];
8780 if (sp->il_offset == il_offset)
8783 if (i == seq_points->len)
8784 return ERR_INVALID_ARGUMENT;
8786 // FIXME: Check that the ip change is safe
8788 DEBUG (1, fprintf (log_file, "[dbg] Setting IP to %s:0x%0x(0x%0x)\n", tls->frames [0]->actual_method->name, (int)sp->il_offset, (int)sp->native_offset));
8789 MONO_CONTEXT_SET_IP (&tls->restore_ctx, (guint8*)tls->frames [0]->ji->code_start + sp->native_offset);
8793 return ERR_NOT_IMPLEMENTED;
8800 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8804 MonoThread *thread_obj;
8805 MonoInternalThread *thread;
8806 int pos, i, len, frame_idx;
8807 DebuggerTlsData *tls;
8809 MonoDebugMethodJitInfo *jit;
8810 MonoDebugVarInfo *var;
8811 MonoMethodSignature *sig;
8813 MonoMethodHeader *header;
8815 objid = decode_objid (p, &p, end);
8816 err = get_object (objid, (MonoObject**)&thread_obj);
8820 thread = THREAD_TO_INTERNAL (thread_obj);
8822 id = decode_id (p, &p, end);
8824 mono_loader_lock ();
8825 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8826 mono_loader_unlock ();
8829 for (i = 0; i < tls->frame_count; ++i) {
8830 if (tls->frames [i]->id == id)
8833 if (i == tls->frame_count)
8834 return ERR_INVALID_FRAMEID;
8837 frame = tls->frames [frame_idx];
8839 if (!frame->has_ctx)
8840 return ERR_ABSENT_INFORMATION;
8843 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
8844 if (!frame->jit && frame->api_method->is_inflated)
8845 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
8849 /* This could happen for aot images with no jit debug info */
8850 s = mono_method_full_name (frame->api_method, TRUE);
8851 DEBUG (1, fprintf (log_file, "[dbg] No debug information found for '%s'.\n", s));
8853 return ERR_ABSENT_INFORMATION;
8858 sig = mono_method_signature (frame->actual_method);
8860 if (!get_seq_points (frame->domain, frame->actual_method))
8862 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
8864 return ERR_ABSENT_INFORMATION;
8867 case CMD_STACK_FRAME_GET_VALUES: {
8868 len = decode_int (p, &p, end);
8869 header = mono_method_get_header (frame->actual_method);
8871 for (i = 0; i < len; ++i) {
8872 pos = decode_int (p, &p, end);
8877 g_assert (pos >= 0 && pos < jit->num_params);
8879 var = &jit->params [pos];
8881 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
8883 g_assert (pos >= 0 && pos < jit->num_locals);
8885 var = &jit->locals [pos];
8887 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
8890 mono_metadata_free_mh (header);
8893 case CMD_STACK_FRAME_GET_THIS: {
8894 if (frame->api_method->klass->valuetype) {
8895 if (!sig->hasthis) {
8896 MonoObject *p = NULL;
8897 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
8899 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8902 if (!sig->hasthis) {
8903 MonoObject *p = NULL;
8904 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
8906 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8911 case CMD_STACK_FRAME_SET_VALUES: {
8914 MonoDebugVarInfo *var;
8916 len = decode_int (p, &p, end);
8917 header = mono_method_get_header (frame->actual_method);
8919 for (i = 0; i < len; ++i) {
8920 pos = decode_int (p, &p, end);
8925 g_assert (pos >= 0 && pos < jit->num_params);
8927 t = sig->params [pos];
8928 var = &jit->params [pos];
8930 g_assert (pos >= 0 && pos < jit->num_locals);
8932 t = header->locals [pos];
8933 var = &jit->locals [pos];
8936 if (MONO_TYPE_IS_REFERENCE (t))
8937 val_buf = g_alloca (sizeof (MonoObject*));
8939 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
8940 err = decode_value (t, frame->domain, val_buf, p, &p, end);
8944 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_ctx);
8946 mono_metadata_free_mh (header);
8950 return ERR_NOT_IMPLEMENTED;
8957 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8960 int objid, err, index, len, i, esize;
8963 objid = decode_objid (p, &p, end);
8964 err = get_object (objid, (MonoObject**)&arr);
8969 case CMD_ARRAY_REF_GET_LENGTH:
8970 buffer_add_int (buf, arr->obj.vtable->klass->rank);
8972 buffer_add_int (buf, arr->max_length);
8973 buffer_add_int (buf, 0);
8975 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
8976 buffer_add_int (buf, arr->bounds [i].length);
8977 buffer_add_int (buf, arr->bounds [i].lower_bound);
8981 case CMD_ARRAY_REF_GET_VALUES:
8982 index = decode_int (p, &p, end);
8983 len = decode_int (p, &p, end);
8985 g_assert (index >= 0 && len >= 0);
8986 // Reordered to avoid integer overflow
8987 g_assert (!(index > arr->max_length - len));
8989 esize = mono_array_element_size (arr->obj.vtable->klass);
8990 for (i = index; i < index + len; ++i) {
8991 elem = (gpointer*)((char*)arr->vector + (i * esize));
8992 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
8995 case CMD_ARRAY_REF_SET_VALUES:
8996 index = decode_int (p, &p, end);
8997 len = decode_int (p, &p, end);
8999 g_assert (index >= 0 && len >= 0);
9000 // Reordered to avoid integer overflow
9001 g_assert (!(index > arr->max_length - len));
9003 esize = mono_array_element_size (arr->obj.vtable->klass);
9004 for (i = index; i < index + len; ++i) {
9005 elem = (gpointer*)((char*)arr->vector + (i * esize));
9007 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
9011 return ERR_NOT_IMPLEMENTED;
9018 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9023 int i, index, length;
9026 objid = decode_objid (p, &p, end);
9027 err = get_object (objid, (MonoObject**)&str);
9032 case CMD_STRING_REF_GET_VALUE:
9033 s = mono_string_to_utf8 (str);
9034 buffer_add_string (buf, s);
9037 case CMD_STRING_REF_GET_LENGTH:
9038 buffer_add_long (buf, mono_string_length (str));
9040 case CMD_STRING_REF_GET_CHARS:
9041 index = decode_long (p, &p, end);
9042 length = decode_long (p, &p, end);
9043 if (index > mono_string_length (str) - length)
9044 return ERR_INVALID_ARGUMENT;
9045 c = mono_string_chars (str) + index;
9046 for (i = 0; i < length; ++i)
9047 buffer_add_short (buf, c [i]);
9050 return ERR_NOT_IMPLEMENTED;
9057 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9066 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9067 objid = decode_objid (p, &p, end);
9068 err = get_object (objid, &obj);
9070 buffer_add_int (buf, 1);
9072 buffer_add_int (buf, 0);
9076 objid = decode_objid (p, &p, end);
9077 err = get_object (objid, &obj);
9082 case CMD_OBJECT_REF_GET_TYPE:
9083 /* This handles transparent proxies too */
9084 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9086 case CMD_OBJECT_REF_GET_VALUES:
9087 len = decode_int (p, &p, end);
9089 for (i = 0; i < len; ++i) {
9090 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9094 /* Check that the field belongs to the object */
9096 for (k = obj->vtable->klass; k; k = k->parent) {
9097 if (k == f->parent) {
9103 return ERR_INVALID_FIELDID;
9105 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9109 if (mono_class_field_is_special_static (f))
9110 return ERR_INVALID_FIELDID;
9112 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9113 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9114 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9115 mono_field_static_get_value (vtable, f, val);
9116 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9119 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
9123 case CMD_OBJECT_REF_SET_VALUES:
9124 len = decode_int (p, &p, end);
9126 for (i = 0; i < len; ++i) {
9127 f = decode_fieldid (p, &p, end, NULL, &err);
9131 /* Check that the field belongs to the object */
9133 for (k = obj->vtable->klass; k; k = k->parent) {
9134 if (k == f->parent) {
9140 return ERR_INVALID_FIELDID;
9142 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9146 if (mono_class_field_is_special_static (f))
9147 return ERR_INVALID_FIELDID;
9149 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9150 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9152 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9153 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
9158 mono_field_static_set_value (vtable, f, val);
9161 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
9167 case CMD_OBJECT_REF_GET_ADDRESS:
9168 buffer_add_long (buf, (gssize)obj);
9170 case CMD_OBJECT_REF_GET_DOMAIN:
9171 buffer_add_domainid (buf, obj->vtable->domain);
9173 case CMD_OBJECT_REF_GET_INFO:
9174 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9175 buffer_add_domainid (buf, obj->vtable->domain);
9178 return ERR_NOT_IMPLEMENTED;
9185 command_set_to_string (CommandSet command_set)
9187 switch (command_set) {
9190 case CMD_SET_OBJECT_REF:
9191 return "OBJECT_REF";
9192 case CMD_SET_STRING_REF:
9193 return "STRING_REF";
9194 case CMD_SET_THREAD:
9196 case CMD_SET_ARRAY_REF:
9198 case CMD_SET_EVENT_REQUEST:
9199 return "EVENT_REQUEST";
9200 case CMD_SET_STACK_FRAME:
9201 return "STACK_FRAME";
9202 case CMD_SET_APPDOMAIN:
9204 case CMD_SET_ASSEMBLY:
9206 case CMD_SET_METHOD:
9210 case CMD_SET_MODULE:
9221 static const char* vm_cmds_str [] = {
9229 "SET_PROTOCOL_VERSION",
9232 "GET_TYPES_FOR_SOURCE_FILE",
9237 static const char* thread_cmds_str[] = {
9247 static const char* event_cmds_str[] = {
9250 "REQUEST_CLEAR_ALL_BREAKPOINTS"
9253 static const char* appdomain_cmds_str[] = {
9255 "GET_FRIENDLY_NAME",
9257 "GET_ENTRY_ASSEMBLY",
9260 "CREATE_BOXED_VALUE"
9263 static const char* assembly_cmds_str[] = {
9266 "GET_MANIFEST_MODULE",
9272 static const char* module_cmds_str[] = {
9276 static const char* field_cmds_str[] = {
9280 static const char* method_cmds_str[] = {
9282 "GET_DECLARING_TYPE",
9290 "MAKE_GENERIC_METHOD"
9293 static const char* type_cmds_str[] = {
9301 "IS_ASSIGNABLE_FROM",
9305 "GET_PROPERTY_CATTRS",
9306 "GET_SOURCE_FILES_2",
9308 "GET_METHODS_BY_NAME_FLAGS",
9310 "GET_INTERFACE_MAP",
9314 static const char* stack_frame_cmds_str[] = {
9320 static const char* array_cmds_str[] = {
9326 static const char* string_cmds_str[] = {
9332 static const char* object_cmds_str[] = {
9343 cmd_to_string (CommandSet set, int command)
9351 cmds_len = G_N_ELEMENTS (vm_cmds_str);
9353 case CMD_SET_OBJECT_REF:
9354 cmds = object_cmds_str;
9355 cmds_len = G_N_ELEMENTS (object_cmds_str);
9357 case CMD_SET_STRING_REF:
9358 cmds = string_cmds_str;
9359 cmds_len = G_N_ELEMENTS (string_cmds_str);
9361 case CMD_SET_THREAD:
9362 cmds = thread_cmds_str;
9363 cmds_len = G_N_ELEMENTS (thread_cmds_str);
9365 case CMD_SET_ARRAY_REF:
9366 cmds = array_cmds_str;
9367 cmds_len = G_N_ELEMENTS (array_cmds_str);
9369 case CMD_SET_EVENT_REQUEST:
9370 cmds = event_cmds_str;
9371 cmds_len = G_N_ELEMENTS (event_cmds_str);
9373 case CMD_SET_STACK_FRAME:
9374 cmds = stack_frame_cmds_str;
9375 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
9377 case CMD_SET_APPDOMAIN:
9378 cmds = appdomain_cmds_str;
9379 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
9381 case CMD_SET_ASSEMBLY:
9382 cmds = assembly_cmds_str;
9383 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
9385 case CMD_SET_METHOD:
9386 cmds = method_cmds_str;
9387 cmds_len = G_N_ELEMENTS (method_cmds_str);
9390 cmds = type_cmds_str;
9391 cmds_len = G_N_ELEMENTS (type_cmds_str);
9393 case CMD_SET_MODULE:
9394 cmds = module_cmds_str;
9395 cmds_len = G_N_ELEMENTS (module_cmds_str);
9398 cmds = field_cmds_str;
9399 cmds_len = G_N_ELEMENTS (field_cmds_str);
9402 cmds = event_cmds_str;
9403 cmds_len = G_N_ELEMENTS (event_cmds_str);
9408 if (command > 0 && command <= cmds_len)
9409 return cmds [command - 1];
9415 wait_for_attach (void)
9417 #ifndef DISABLE_SOCKET_TRANSPORT
9418 if (listen_fd == -1) {
9419 DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
9423 /* Block and wait for client connection */
9424 conn_fd = socket_transport_accept (listen_fd);
9425 DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
9426 if (conn_fd == -1) {
9427 DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
9431 g_assert_not_reached ();
9435 disconnected = !transport_handshake ();
9437 DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
9447 * This thread handles communication with the debugger client using a JDWP
9450 static guint32 WINAPI
9451 debugger_thread (void *arg)
9453 int res, len, id, flags, command_set = 0, command = 0;
9454 guint8 header [HEADER_LENGTH];
9455 guint8 *data, *p, *end;
9459 gboolean attach_failed = FALSE;
9461 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
9463 debugger_thread_id = GetCurrentThreadId ();
9465 mono_jit_thread_attach (mono_get_root_domain ());
9467 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
9469 mono_set_is_debugger_attached (TRUE);
9471 if (agent_config.defer) {
9472 if (!wait_for_attach ()) {
9473 DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
9474 attach_failed = TRUE; // Don't abort process when we can't listen
9476 /* Send start event to client */
9477 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
9481 while (!attach_failed) {
9482 res = transport_recv (header, HEADER_LENGTH);
9484 /* This will break if the socket is closed during shutdown too */
9485 if (res != HEADER_LENGTH) {
9486 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH));
9491 end = header + HEADER_LENGTH;
9493 len = decode_int (p, &p, end);
9494 id = decode_int (p, &p, end);
9495 flags = decode_byte (p, &p, end);
9496 command_set = decode_byte (p, &p, end);
9497 command = decode_byte (p, &p, end);
9499 g_assert (flags == 0);
9502 const char *cmd_str;
9505 cmd_str = cmd_to_string (command_set, command);
9507 sprintf (cmd_num, "%d", command);
9511 DEBUG (1, fprintf (log_file, "[dbg] Command %s(%s) [%d][at=%lx].\n", command_set_to_string (command_set), cmd_str, id, (long)mono_100ns_ticks () / 10000));
9514 data = g_malloc (len - HEADER_LENGTH);
9515 if (len - HEADER_LENGTH > 0)
9517 res = transport_recv (data, len - HEADER_LENGTH);
9518 if (res != len - HEADER_LENGTH) {
9519 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH));
9525 end = data + (len - HEADER_LENGTH);
9527 buffer_init (&buf, 128);
9532 /* Process the request */
9533 switch (command_set) {
9535 err = vm_commands (command, id, p, end, &buf);
9536 if (!err && command == CMD_VM_INVOKE_METHOD)
9537 /* Sent after the invoke is complete */
9540 case CMD_SET_EVENT_REQUEST:
9541 err = event_commands (command, p, end, &buf);
9543 case CMD_SET_APPDOMAIN:
9544 err = domain_commands (command, p, end, &buf);
9546 case CMD_SET_ASSEMBLY:
9547 err = assembly_commands (command, p, end, &buf);
9549 case CMD_SET_MODULE:
9550 err = module_commands (command, p, end, &buf);
9553 err = field_commands (command, p, end, &buf);
9556 err = type_commands (command, p, end, &buf);
9558 case CMD_SET_METHOD:
9559 err = method_commands (command, p, end, &buf);
9561 case CMD_SET_THREAD:
9562 err = thread_commands (command, p, end, &buf);
9564 case CMD_SET_STACK_FRAME:
9565 err = frame_commands (command, p, end, &buf);
9567 case CMD_SET_ARRAY_REF:
9568 err = array_commands (command, p, end, &buf);
9570 case CMD_SET_STRING_REF:
9571 err = string_commands (command, p, end, &buf);
9573 case CMD_SET_OBJECT_REF:
9574 err = object_commands (command, p, end, &buf);
9577 err = ERR_NOT_IMPLEMENTED;
9580 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
9581 buffer_replies = TRUE;
9585 if (buffer_replies) {
9586 buffer_reply_packet (id, err, &buf);
9588 send_reply_packet (id, err, &buf);
9589 //DEBUG (1, fprintf (log_file, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000));
9593 if (!err && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
9594 send_buffered_reply_packets ();
9595 buffer_replies = FALSE;
9601 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
9605 mono_set_is_debugger_attached (FALSE);
9607 mono_mutex_lock (&debugger_thread_exited_mutex);
9608 debugger_thread_exited = TRUE;
9609 mono_cond_signal (&debugger_thread_exited_cond);
9610 mono_mutex_unlock (&debugger_thread_exited_mutex);
9612 DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
9614 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
9615 DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
9616 start_debugger_thread ();
9622 #else /* DISABLE_DEBUGGER_AGENT */
9625 mono_debugger_agent_parse_options (char *options)
9627 g_error ("This runtime is configured with the debugger agent disabled.");
9631 mono_debugger_agent_init (void)
9636 mono_debugger_agent_breakpoint_hit (void *sigctx)
9641 mono_debugger_agent_single_step_event (void *sigctx)
9646 mono_debugger_agent_free_domain_info (MonoDomain *domain)
9651 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
9657 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
9658 MonoContext *catch_ctx)
9663 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9668 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9673 mono_debugger_agent_user_break (void)
9679 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
9684 mono_debugger_agent_debug_log_is_enabled (void)