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
54 /* cygwin's headers do not seem to define these */
55 void WSAAPI freeaddrinfo (struct addrinfo*);
56 int WSAAPI getaddrinfo (const char*,const char*,const struct addrinfo*,
58 int WSAAPI getnameinfo(const struct sockaddr*,socklen_t,char*,DWORD,
63 #ifdef PLATFORM_ANDROID
65 #include <linux/tcp.h>
66 #include <sys/endian.h>
69 #include <mono/metadata/mono-debug.h>
70 #include <mono/metadata/mono-debug-debugger.h>
71 #include <mono/metadata/debug-mono-symfile.h>
72 #include <mono/metadata/gc-internal.h>
73 #include <mono/metadata/environment.h>
74 #include <mono/metadata/threads-types.h>
75 #include <mono/metadata/socket-io.h>
76 #include <mono/metadata/assembly.h>
77 #include <mono/metadata/runtime.h>
78 #include <mono/metadata/threadpool.h>
79 #include <mono/metadata/verify-internals.h>
80 #include <mono/utils/mono-semaphore.h>
81 #include <mono/utils/mono-error-internals.h>
82 #include <mono/utils/mono-stack-unwinding.h>
83 #include <mono/utils/mono-time.h>
84 #include <mono/utils/mono-threads.h>
85 #include "debugger-agent.h"
87 #include "seq-points.h"
90 On iOS we can't use System.Environment.Exit () as it will do the wrong
93 #if !defined (TARGET_IOS)
94 #define TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
98 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
99 #define DISABLE_DEBUGGER_AGENT 1
102 #ifdef DISABLE_SOFT_DEBUG
103 #define DISABLE_DEBUGGER_AGENT 1
106 #ifndef DISABLE_DEBUGGER_AGENT
108 #include <mono/utils/mono-mutex.h>
110 /* Definitions to make backporting to 2.6 easier */
111 //#define MonoInternalThread MonoThread
112 //#define mono_thread_internal_current mono_thread_current
113 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
136 guint32 il_offset, native_offset;
140 * If method is gshared, this is the actual instance, otherwise this is equal to
143 MonoMethod *actual_method;
145 * This is the method which is visible to debugger clients. Same as method,
146 * except for native-to-managed wrappers.
148 MonoMethod *api_method;
150 MonoDebugMethodJitInfo *jit;
153 mgreg_t *reg_locations [MONO_MAX_IREGS];
155 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
156 * the frame can become invalid.
161 typedef struct _InvokeData InvokeData;
169 /* This is the context which needs to be restored after the invoke */
173 * If this is set, invoke this method with the arguments given by ARGS.
177 guint32 suspend_count;
180 InvokeData *last_invoke;
184 MonoThreadUnwindState context;
186 /* This is computed on demand when it is requested using the wire protocol */
187 /* It is freed up when the thread is resumed */
191 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
194 gboolean frames_up_to_date;
196 * Points to data about a pending invoke which needs to be executed after the thread
199 InvokeData *pending_invoke;
201 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
206 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
207 * within a finite amount of time.
211 * Set to TRUE if this thread is suspended in suspend_current ().
213 gboolean really_suspended;
214 /* Used to pass the context to the breakpoint/single step handler */
215 MonoContext handler_ctx;
216 /* Whenever thread_stop () was called for this thread */
219 /* Number of thread interruptions not yet processed */
220 gint32 interrupt_count;
222 /* Whenever to disable breakpoints (used during invokes) */
223 gboolean disable_breakpoints;
226 * Number of times this thread has been resumed using resume_thread ().
228 guint32 resume_count;
230 MonoInternalThread *thread;
233 * Information about the frame which transitioned to native code for running
236 StackFrameInfo async_last_frame;
239 * The context where the stack walk can be started for running threads.
241 MonoThreadUnwindState async_state;
244 * The context used for filter clauses
246 MonoThreadUnwindState filter_state;
249 * The callee address of the last mono_runtime_invoke call
251 gpointer invoke_addr;
253 gboolean abort_requested;
256 * The current mono_runtime_invoke invocation.
261 * The context where single stepping should resume while the thread is suspended because
262 * of an EXCEPTION event.
264 MonoThreadUnwindState catch_state;
267 * The context which needs to be restored after handling a single step/breakpoint
268 * event. This is the same as the ctx at step/breakpoint site, but includes changes
269 * to caller saved registers done by set_var ().
271 MonoContext restore_ctx;
273 /* The currently unloading appdomain */
274 MonoDomain *domain_unloading;
279 void (*connect) (const char *address);
280 void (*close1) (void);
281 void (*close2) (void);
282 gboolean (*send) (void *buf, int len);
283 int (*recv) (void *buf, int len);
287 * Wire Protocol definitions
290 #define HEADER_LENGTH 11
292 #define MAJOR_VERSION 2
293 #define MINOR_VERSION 37
297 CMD_SET_OBJECT_REF = 9,
298 CMD_SET_STRING_REF = 10,
300 CMD_SET_ARRAY_REF = 13,
301 CMD_SET_EVENT_REQUEST = 15,
302 CMD_SET_STACK_FRAME = 16,
303 CMD_SET_APPDOMAIN = 20,
304 CMD_SET_ASSEMBLY = 21,
313 EVENT_KIND_VM_START = 0,
314 EVENT_KIND_VM_DEATH = 1,
315 EVENT_KIND_THREAD_START = 2,
316 EVENT_KIND_THREAD_DEATH = 3,
317 EVENT_KIND_APPDOMAIN_CREATE = 4,
318 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
319 EVENT_KIND_METHOD_ENTRY = 6,
320 EVENT_KIND_METHOD_EXIT = 7,
321 EVENT_KIND_ASSEMBLY_LOAD = 8,
322 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
323 EVENT_KIND_BREAKPOINT = 10,
324 EVENT_KIND_STEP = 11,
325 EVENT_KIND_TYPE_LOAD = 12,
326 EVENT_KIND_EXCEPTION = 13,
327 EVENT_KIND_KEEPALIVE = 14,
328 EVENT_KIND_USER_BREAK = 15,
329 EVENT_KIND_USER_LOG = 16
333 SUSPEND_POLICY_NONE = 0,
334 SUSPEND_POLICY_EVENT_THREAD = 1,
335 SUSPEND_POLICY_ALL = 2
340 ERR_INVALID_OBJECT = 20,
341 ERR_INVALID_FIELDID = 25,
342 ERR_INVALID_FRAMEID = 30,
343 ERR_NOT_IMPLEMENTED = 100,
344 ERR_NOT_SUSPENDED = 101,
345 ERR_INVALID_ARGUMENT = 102,
347 ERR_NO_INVOCATION = 104,
348 ERR_ABSENT_INFORMATION = 105,
349 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
350 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
355 MOD_KIND_THREAD_ONLY = 3,
356 MOD_KIND_LOCATION_ONLY = 7,
357 MOD_KIND_EXCEPTION_ONLY = 8,
359 MOD_KIND_ASSEMBLY_ONLY = 11,
360 MOD_KIND_SOURCE_FILE_ONLY = 12,
361 MOD_KIND_TYPE_NAME_ONLY = 13,
377 STEP_FILTER_NONE = 0,
378 STEP_FILTER_STATIC_CTOR = 1,
379 STEP_FILTER_DEBUGGER_HIDDEN = 2,
380 STEP_FILTER_DEBUGGER_STEP_THROUGH = 4,
381 STEP_FILTER_DEBUGGER_NON_USER_CODE = 8
385 TOKEN_TYPE_STRING = 0,
387 TOKEN_TYPE_FIELD = 2,
388 TOKEN_TYPE_METHOD = 3,
389 TOKEN_TYPE_UNKNOWN = 4
393 VALUE_TYPE_ID_NULL = 0xf0,
394 VALUE_TYPE_ID_TYPE = 0xf1,
395 VALUE_TYPE_ID_PARENT_VTYPE = 0xf2
399 FRAME_FLAG_DEBUGGER_INVOKE = 1,
400 FRAME_FLAG_NATIVE_TRANSITION = 2
404 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
405 INVOKE_FLAG_SINGLE_THREADED = 2,
406 INVOKE_FLAG_RETURN_OUT_THIS = 4,
407 INVOKE_FLAG_RETURN_OUT_ARGS = 8,
408 INVOKE_FLAG_VIRTUAL = 16
412 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
413 } BindingFlagsExtensions;
417 CMD_VM_ALL_THREADS = 2,
422 CMD_VM_INVOKE_METHOD = 7,
423 CMD_VM_SET_PROTOCOL_VERSION = 8,
424 CMD_VM_ABORT_INVOKE = 9,
425 CMD_VM_SET_KEEPALIVE = 10,
426 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
427 CMD_VM_GET_TYPES = 12,
428 CMD_VM_INVOKE_METHODS = 13,
429 CMD_VM_START_BUFFERING = 14,
430 CMD_VM_STOP_BUFFERING = 15
434 CMD_THREAD_GET_FRAME_INFO = 1,
435 CMD_THREAD_GET_NAME = 2,
436 CMD_THREAD_GET_STATE = 3,
437 CMD_THREAD_GET_INFO = 4,
438 CMD_THREAD_GET_ID = 5,
439 CMD_THREAD_GET_TID = 6,
440 CMD_THREAD_SET_IP = 7
444 CMD_EVENT_REQUEST_SET = 1,
445 CMD_EVENT_REQUEST_CLEAR = 2,
446 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
454 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
455 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
456 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
457 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
458 CMD_APPDOMAIN_CREATE_STRING = 5,
459 CMD_APPDOMAIN_GET_CORLIB = 6,
460 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
464 CMD_ASSEMBLY_GET_LOCATION = 1,
465 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
466 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
467 CMD_ASSEMBLY_GET_OBJECT = 4,
468 CMD_ASSEMBLY_GET_TYPE = 5,
469 CMD_ASSEMBLY_GET_NAME = 6
473 CMD_MODULE_GET_INFO = 1,
477 CMD_FIELD_GET_INFO = 1,
481 CMD_METHOD_GET_NAME = 1,
482 CMD_METHOD_GET_DECLARING_TYPE = 2,
483 CMD_METHOD_GET_DEBUG_INFO = 3,
484 CMD_METHOD_GET_PARAM_INFO = 4,
485 CMD_METHOD_GET_LOCALS_INFO = 5,
486 CMD_METHOD_GET_INFO = 6,
487 CMD_METHOD_GET_BODY = 7,
488 CMD_METHOD_RESOLVE_TOKEN = 8,
489 CMD_METHOD_GET_CATTRS = 9,
490 CMD_METHOD_MAKE_GENERIC_METHOD = 10
494 CMD_TYPE_GET_INFO = 1,
495 CMD_TYPE_GET_METHODS = 2,
496 CMD_TYPE_GET_FIELDS = 3,
497 CMD_TYPE_GET_VALUES = 4,
498 CMD_TYPE_GET_OBJECT = 5,
499 CMD_TYPE_GET_SOURCE_FILES = 6,
500 CMD_TYPE_SET_VALUES = 7,
501 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
502 CMD_TYPE_GET_PROPERTIES = 9,
503 CMD_TYPE_GET_CATTRS = 10,
504 CMD_TYPE_GET_FIELD_CATTRS = 11,
505 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
506 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
507 CMD_TYPE_GET_VALUES_2 = 14,
508 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
509 CMD_TYPE_GET_INTERFACES = 16,
510 CMD_TYPE_GET_INTERFACE_MAP = 17,
511 CMD_TYPE_IS_INITIALIZED = 18,
512 CMD_TYPE_CREATE_INSTANCE = 19
516 CMD_STACK_FRAME_GET_VALUES = 1,
517 CMD_STACK_FRAME_GET_THIS = 2,
518 CMD_STACK_FRAME_SET_VALUES = 3
522 CMD_ARRAY_REF_GET_LENGTH = 1,
523 CMD_ARRAY_REF_GET_VALUES = 2,
524 CMD_ARRAY_REF_SET_VALUES = 3,
528 CMD_STRING_REF_GET_VALUE = 1,
529 CMD_STRING_REF_GET_LENGTH = 2,
530 CMD_STRING_REF_GET_CHARS = 3
534 CMD_OBJECT_REF_GET_TYPE = 1,
535 CMD_OBJECT_REF_GET_VALUES = 2,
536 CMD_OBJECT_REF_IS_COLLECTED = 3,
537 CMD_OBJECT_REF_GET_ADDRESS = 4,
538 CMD_OBJECT_REF_GET_DOMAIN = 5,
539 CMD_OBJECT_REF_SET_VALUES = 6,
540 CMD_OBJECT_REF_GET_INFO = 7,
546 int count; /* For kind == MOD_KIND_COUNT */
547 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
548 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
549 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
550 GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
551 GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
552 StepFilter filter; /* For kind == MOD_KIND_STEP */
554 gboolean caught, uncaught, subclasses; /* For kind == MOD_KIND_EXCEPTION_ONLY */
563 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
567 * Describes a single step request.
571 MonoInternalThread *thread;
577 MonoMethod *last_method;
579 /* Whenever single stepping is performed using start/stop_single_stepping () */
581 /* The list of breakpoints used to implement step-over */
583 /* The number of frames at the start of a step-over */
588 * Contains additional information for an event
591 /* For EVENT_KIND_EXCEPTION */
593 MonoContext catch_ctx;
595 /* For EVENT_KIND_USER_LOG */
597 char *category, *message;
598 /* For EVENT_KIND_TYPE_LOAD */
602 /* Dummy structure used for the profiler callbacks */
608 guint8 *buf, *p, *end;
611 typedef struct ReplyPacket {
617 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
620 #define get_last_sock_error() WSAGetLastError()
621 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
622 #define MONO_EINTR WSAEINTR
624 #define get_last_sock_error() errno
625 #define MONO_EWOULDBLOCK EWOULDBLOCK
626 #define MONO_EINTR EINTR
629 #define CHECK_PROTOCOL_VERSION(major,minor) \
630 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
636 static AgentConfig agent_config;
639 * Whenever the agent is fully initialized.
640 * When using the onuncaught or onthrow options, only some parts of the agent are
641 * initialized on startup, and the full initialization which includes connection
642 * establishment and the startup of the agent thread is only done in response to
645 static gint32 inited;
647 #ifndef DISABLE_SOCKET_TRANSPORT
649 static int listen_fd;
652 static int packet_id = 0;
654 static int objref_id = 0;
656 static int event_request_id = 0;
658 static int frame_id = 0;
660 static GPtrArray *event_requests;
662 static MonoNativeTlsKey debugger_tls_id;
664 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
666 /* Maps MonoInternalThread -> DebuggerTlsData */
667 static MonoGHashTable *thread_to_tls;
669 /* Maps tid -> MonoInternalThread */
670 static MonoGHashTable *tid_to_thread;
672 /* Maps tid -> MonoThread (not MonoInternalThread) */
673 static MonoGHashTable *tid_to_thread_obj;
675 static gsize debugger_thread_id;
677 static HANDLE debugger_thread_handle;
679 static int log_level;
681 static gboolean embedding;
683 static FILE *log_file;
685 /* Assemblies whose assembly load event has no been sent yet */
686 /* Protected by the dbg lock */
687 static GPtrArray *pending_assembly_loads;
689 /* Whenever the debugger thread has exited */
690 static gboolean debugger_thread_exited;
692 /* Cond variable used to wait for debugger_thread_exited becoming true */
693 static mono_cond_t debugger_thread_exited_cond;
695 /* Mutex for the cond var above */
696 static mono_mutex_t debugger_thread_exited_mutex;
698 static DebuggerProfiler debugger_profiler;
700 /* The single step request instance */
701 static SingleStepReq *ss_req;
702 static gpointer ss_invoke_addr;
704 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
705 /* Number of single stepping operations in progress */
709 /* The protocol version of the client */
710 static int major_version, minor_version;
712 /* Whenever the variables above are set by the client */
713 static gboolean protocol_version_set;
715 /* A hash table containing all active domains */
716 static GHashTable *domains;
718 /* The number of times the runtime is suspended */
719 static gint32 suspend_count;
721 /* Whenever to buffer reply messages and send them together */
722 static gboolean buffer_replies;
724 /* Buffered reply packets */
725 static ReplyPacket reply_packets [128];
728 #define dbg_lock() mono_mutex_lock (&debug_mutex)
729 #define dbg_unlock() mono_mutex_unlock (&debug_mutex)
730 static mono_mutex_t debug_mutex;
732 static void transport_init (void);
733 static void transport_connect (const char *address);
734 static gboolean transport_handshake (void);
735 static void register_transport (DebuggerTransport *trans);
737 static guint32 WINAPI debugger_thread (void *arg);
739 static void runtime_initialized (MonoProfiler *prof);
741 static void runtime_shutdown (MonoProfiler *prof);
743 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
745 static void thread_end (MonoProfiler *prof, uintptr_t tid);
747 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
749 static void appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain);
751 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
753 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
755 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
757 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
759 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
761 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
763 static void emit_assembly_load (gpointer assembly, gpointer user_data);
765 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
767 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
769 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
771 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
773 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
775 static void start_single_stepping (void);
777 static void stop_single_stepping (void);
779 static void suspend_current (void);
781 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
783 static void clear_types_for_assembly (MonoAssembly *assembly);
785 static void clear_breakpoints_for_domain (MonoDomain *domain);
787 static void process_profiler_event (EventKind event, gpointer arg);
789 /* Submodule init/cleanup */
790 static void breakpoints_init (void);
791 static void breakpoints_cleanup (void);
793 static void objrefs_init (void);
794 static void objrefs_cleanup (void);
796 static void ids_init (void);
797 static void ids_cleanup (void);
799 static void suspend_init (void);
801 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch);
802 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
803 static void ss_destroy (SingleStepReq *req);
805 static void start_debugger_thread (void);
806 static void stop_debugger_thread (void);
808 static void finish_agent_init (gboolean on_startup);
810 static void process_profiler_event (EventKind event, gpointer arg);
812 static void invalidate_frames (DebuggerTlsData *tls);
814 #ifndef DISABLE_SOCKET_TRANSPORT
816 register_socket_transport (void);
820 parse_address (char *address, char **host, int *port)
822 char *pos = strchr (address, ':');
824 if (pos == NULL || pos == address)
827 *host = g_malloc (pos - address + 1);
828 strncpy (*host, address, pos - address);
829 (*host) [pos - address] = '\0';
831 *port = atoi (pos + 1);
839 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
840 fprintf (stderr, "Available options:\n");
841 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
842 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
843 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
844 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
845 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
846 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
847 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
848 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
849 fprintf (stderr, " setpgid=y/n\t\t\tWhether to call setpid(0, 0) after startup.\n");
850 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
854 parse_flag (const char *option, char *flag)
856 if (!strcmp (flag, "y"))
858 else if (!strcmp (flag, "n"))
861 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
868 mono_debugger_agent_parse_options (char *options)
875 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
876 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
880 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
882 options = g_strdup_printf ("%s,%s", options, extra);
884 agent_config.enabled = TRUE;
885 agent_config.suspend = TRUE;
886 agent_config.server = FALSE;
887 agent_config.defer = FALSE;
888 agent_config.address = NULL;
890 //agent_config.log_level = 10;
892 args = g_strsplit (options, ",", -1);
893 for (ptr = args; ptr && *ptr; ptr ++) {
896 if (strncmp (arg, "transport=", 10) == 0) {
897 agent_config.transport = g_strdup (arg + 10);
898 } else if (strncmp (arg, "address=", 8) == 0) {
899 agent_config.address = g_strdup (arg + 8);
900 } else if (strncmp (arg, "loglevel=", 9) == 0) {
901 agent_config.log_level = atoi (arg + 9);
902 } else if (strncmp (arg, "logfile=", 8) == 0) {
903 agent_config.log_file = g_strdup (arg + 8);
904 } else if (strncmp (arg, "suspend=", 8) == 0) {
905 agent_config.suspend = parse_flag ("suspend", arg + 8);
906 } else if (strncmp (arg, "server=", 7) == 0) {
907 agent_config.server = parse_flag ("server", arg + 7);
908 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
909 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
910 } else if (strncmp (arg, "onthrow=", 8) == 0) {
911 /* We support multiple onthrow= options */
912 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
913 } else if (strncmp (arg, "onthrow", 7) == 0) {
914 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
915 } else if (strncmp (arg, "help", 4) == 0) {
918 } else if (strncmp (arg, "timeout=", 8) == 0) {
919 agent_config.timeout = atoi (arg + 8);
920 } else if (strncmp (arg, "launch=", 7) == 0) {
921 agent_config.launch = g_strdup (arg + 7);
922 } else if (strncmp (arg, "embedding=", 10) == 0) {
923 agent_config.embedding = atoi (arg + 10) == 1;
924 } else if (strncmp (arg, "keepalive=", 10) == 0) {
925 agent_config.keepalive = atoi (arg + 10);
926 } else if (strncmp (arg, "setpgid=", 8) == 0) {
927 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
934 if (agent_config.server && !agent_config.suspend) {
935 /* Waiting for deferred attachment */
936 agent_config.defer = TRUE;
937 if (agent_config.address == NULL) {
938 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (getpid () % 1000));
942 //agent_config.log_level = 0;
944 if (agent_config.transport == NULL) {
945 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
949 if (agent_config.address == NULL && !agent_config.server) {
950 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
955 if (!strcmp (agent_config.transport, "dt_socket")) {
956 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
957 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
964 mono_debugger_agent_init (void)
966 mono_mutex_init_recursive (&debug_mutex);
968 if (!agent_config.enabled)
973 /* Need to know whenever a thread has acquired the loader mutex */
974 mono_loader_lock_track_ownership (TRUE);
976 event_requests = g_ptr_array_new ();
978 mono_mutex_init (&debugger_thread_exited_mutex);
979 mono_cond_init (&debugger_thread_exited_cond, NULL);
981 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
982 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
983 mono_profiler_install_runtime_initialized (runtime_initialized);
984 mono_profiler_install_appdomain (NULL, appdomain_load, appdomain_start_unload, appdomain_unload);
985 mono_profiler_install_thread (thread_startup, thread_end);
986 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
987 mono_profiler_install_jit_end (jit_end);
988 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
990 mono_native_tls_alloc (&debugger_tls_id, NULL);
992 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
993 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls);
995 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
996 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread);
998 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
999 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj);
1001 pending_assembly_loads = g_ptr_array_new ();
1002 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
1004 log_level = agent_config.log_level;
1006 embedding = agent_config.embedding;
1007 disconnected = TRUE;
1009 if (agent_config.log_file) {
1010 log_file = fopen (agent_config.log_file, "w+");
1012 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
1021 breakpoints_init ();
1024 mini_get_debug_options ()->gen_seq_points = TRUE;
1026 * This is needed because currently we don't handle liveness info.
1028 mini_get_debug_options ()->mdb_optimizations = TRUE;
1030 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
1031 /* This is needed because we can't set local variables in registers yet */
1032 mono_disable_optimizations (MONO_OPT_LINEARS);
1036 * The stack walk done from thread_interrupt () needs to be signal safe, but it
1037 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
1038 * safe (#3411). So load AOT info eagerly when the debugger is running as a
1041 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
1044 if (agent_config.setpgid)
1048 if (!agent_config.onuncaught && !agent_config.onthrow)
1049 finish_agent_init (TRUE);
1053 * finish_agent_init:
1055 * Finish the initialization of the agent. This involves connecting the transport
1056 * and starting the agent thread. This is either done at startup, or
1057 * in response to some event like an unhandled exception.
1060 finish_agent_init (gboolean on_startup)
1064 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
1067 if (agent_config.launch) {
1070 // FIXME: Generated address
1071 // FIXME: Races with transport_connect ()
1073 argv [0] = agent_config.launch;
1074 argv [1] = agent_config.transport;
1075 argv [2] = agent_config.address;
1078 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1080 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1085 transport_connect (agent_config.address);
1088 /* Do some which is usually done after sending the VMStart () event */
1089 vm_start_event_sent = TRUE;
1090 start_debugger_thread ();
1095 mono_debugger_agent_cleanup (void)
1100 stop_debugger_thread ();
1102 breakpoints_cleanup ();
1106 mono_mutex_destroy (&debugger_thread_exited_mutex);
1107 mono_cond_destroy (&debugger_thread_exited_cond);
1114 #ifndef DISABLE_SOCKET_TRANSPORT
1119 * recv() + handle incomplete reads and EINTR
1122 socket_transport_recv (void *buf, int len)
1128 static gint32 last_keepalive;
1133 res = recv (fd, (char *) buf + total, len - total, flags);
1136 if (agent_config.keepalive) {
1137 gboolean need_keepalive = FALSE;
1138 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1139 need_keepalive = TRUE;
1140 } else if (res == -1) {
1141 /* This could happen if recv () is interrupted repeatedly */
1142 msecs = mono_msec_ticks ();
1143 if (msecs - last_keepalive >= agent_config.keepalive) {
1144 need_keepalive = TRUE;
1145 last_keepalive = msecs;
1148 if (need_keepalive) {
1149 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1153 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1158 #define HAVE_GETADDRINFO 1
1162 set_keepalive (void)
1167 if (!agent_config.keepalive || !conn_fd)
1170 tv.tv_sec = agent_config.keepalive / 1000;
1171 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1173 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1174 g_assert (result >= 0);
1178 socket_transport_accept (int socket_fd)
1180 conn_fd = accept (socket_fd, NULL, NULL);
1181 if (conn_fd == -1) {
1182 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1184 DEBUG (1, fprintf (log_file, "Accepted connection from client, connection fd=%d.\n", conn_fd));
1191 socket_transport_send (void *data, int len)
1196 res = send (conn_fd, data, len, 0);
1197 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1205 * socket_transport_connect:
1207 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1210 socket_transport_connect (const char *address)
1212 #ifdef HAVE_GETADDRINFO
1213 struct addrinfo hints;
1214 struct addrinfo *result, *rp;
1216 struct hostent *result;
1218 int sfd = -1, s, res;
1219 char port_string [128];
1223 if (agent_config.address) {
1224 res = parse_address (agent_config.address, &host, &port);
1225 g_assert (res == 0);
1235 sprintf (port_string, "%d", port);
1237 mono_network_init ();
1239 /* Obtain address(es) matching host/port */
1240 #ifdef HAVE_GETADDRINFO
1241 memset (&hints, 0, sizeof (struct addrinfo));
1242 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
1243 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
1245 hints.ai_protocol = 0; /* Any protocol */
1247 s = getaddrinfo (host, port_string, &hints, &result);
1249 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %s\n", host, port, gai_strerror (s));
1253 /* The PS3 doesn't even have _r or hstrerror () */
1254 result = gethostbyname (host);
1256 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, h_errno);
1261 if (agent_config.server) {
1262 #ifdef HAVE_GETADDRINFO
1263 /* Wait for a connection */
1265 struct sockaddr_in addr;
1268 /* No address, generate one */
1269 sfd = socket (AF_INET, SOCK_STREAM, 0);
1272 /* This will bind the socket to a random port */
1273 res = listen (sfd, 16);
1275 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1280 addrlen = sizeof (addr);
1281 memset (&addr, 0, sizeof (addr));
1282 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1283 g_assert (res == 0);
1285 host = (char*)"127.0.0.1";
1286 port = ntohs (addr.sin_port);
1288 /* Emit the address to stdout */
1289 /* FIXME: Should print another interface, not localhost */
1290 printf ("%s:%d\n", host, port);
1292 /* Listen on the provided address */
1293 for (rp = result; rp != NULL; rp = rp->ai_next) {
1296 sfd = socket (rp->ai_family, rp->ai_socktype,
1301 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1304 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
1308 res = listen (sfd, 16);
1317 * this function is not present on win2000 which we still support, and the
1318 * workaround described here:
1319 * http://msdn.microsoft.com/en-us/library/ms737931(VS.85).aspx
1320 * only works with MSVC.
1322 #ifdef HAVE_GETADDRINFO
1323 freeaddrinfo (result);
1328 if (agent_config.defer)
1331 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
1333 if (agent_config.timeout) {
1338 tv.tv_usec = agent_config.timeout * 1000;
1340 FD_SET (sfd, &readfds);
1341 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1343 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1348 conn_fd = socket_transport_accept (sfd);
1352 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
1355 #endif /* HAVE_GETADDRINFO */
1357 /* Connect to the specified address */
1358 #ifdef HAVE_GETADDRINFO
1359 /* FIXME: Respect the timeout */
1360 for (rp = result; rp != NULL; rp = rp->ai_next) {
1361 sfd = socket (rp->ai_family, rp->ai_socktype,
1366 if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
1367 break; /* Success */
1373 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1377 sfd = socket (result->h_addrtype, SOCK_STREAM, 0);
1379 g_assert_not_reached ();
1380 res = connect (sfd, (void*)result->h_addr_list [0], result->h_length);
1382 g_assert_not_reached ();
1388 /* See the comment above */
1389 #ifdef HAVE_GETADDRINFO
1390 freeaddrinfo (result);
1395 if (!transport_handshake ())
1400 socket_transport_close1 (void)
1402 /* This will interrupt the agent thread */
1403 /* Close the read part only so it can still send back replies */
1404 /* Also shut down the connection listener so that we can exit normally */
1406 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1407 shutdown (conn_fd, SD_BOTH);
1408 shutdown (listen_fd, SD_BOTH);
1409 closesocket (listen_fd);
1411 shutdown (conn_fd, SHUT_RD);
1412 shutdown (listen_fd, SHUT_RDWR);
1418 socket_transport_close2 (void)
1421 shutdown (conn_fd, SD_BOTH);
1423 shutdown (conn_fd, SHUT_RDWR);
1428 register_socket_transport (void)
1430 DebuggerTransport trans;
1432 trans.name = "dt_socket";
1433 trans.connect = socket_transport_connect;
1434 trans.close1 = socket_transport_close1;
1435 trans.close2 = socket_transport_close2;
1436 trans.send = socket_transport_send;
1437 trans.recv = socket_transport_recv;
1439 register_transport (&trans);
1443 * socket_fd_transport_connect:
1447 socket_fd_transport_connect (const char *address)
1451 res = sscanf (address, "%d", &conn_fd);
1453 fprintf (stderr, "debugger-agent: socket-fd transport address is invalid: '%s'\n", address);
1457 if (!transport_handshake ())
1462 register_socket_fd_transport (void)
1464 DebuggerTransport trans;
1466 /* This is the same as the 'dt_socket' transport, but receives an already connected socket fd */
1467 trans.name = "socket-fd";
1468 trans.connect = socket_fd_transport_connect;
1469 trans.close1 = socket_transport_close1;
1470 trans.close2 = socket_transport_close2;
1471 trans.send = socket_transport_send;
1472 trans.recv = socket_transport_recv;
1474 register_transport (&trans);
1477 #endif /* DISABLE_SOCKET_TRANSPORT */
1483 #define MAX_TRANSPORTS 16
1485 static DebuggerTransport *transport;
1487 static DebuggerTransport transports [MAX_TRANSPORTS];
1488 static int ntransports;
1491 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1494 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1496 register_transport (trans);
1500 register_transport (DebuggerTransport *trans)
1502 g_assert (ntransports < MAX_TRANSPORTS);
1504 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1509 transport_init (void)
1513 #ifndef DISABLE_SOCKET_TRANSPORT
1514 register_socket_transport ();
1515 register_socket_fd_transport ();
1518 for (i = 0; i < ntransports; ++i) {
1519 if (!strcmp (agent_config.transport, transports [i].name))
1522 if (i == ntransports) {
1523 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1524 for (i = 0; i < ntransports; ++i)
1525 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1526 fprintf (stderr, "\n");
1529 transport = &transports [i];
1533 transport_connect (const char *address)
1535 transport->connect (address);
1539 transport_close1 (void)
1541 transport->close1 ();
1545 transport_close2 (void)
1547 transport->close2 ();
1551 transport_send (void *buf, int len)
1553 return transport->send (buf, len);
1557 transport_recv (void *buf, int len)
1559 return transport->recv (buf, len);
1563 mono_debugger_agent_transport_handshake (void)
1565 return transport_handshake ();
1569 transport_handshake (void)
1571 char handshake_msg [128];
1575 disconnected = TRUE;
1577 /* Write handshake message */
1578 sprintf (handshake_msg, "DWP-Handshake");
1580 res = transport_send (handshake_msg, strlen (handshake_msg));
1581 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1582 g_assert (res != -1);
1585 res = transport_recv (buf, strlen (handshake_msg));
1586 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg)) != 0)) {
1587 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1592 * To support older clients, the client sends its protocol version after connecting
1593 * using a command. Until that is received, default to our protocol version.
1595 major_version = MAJOR_VERSION;
1596 minor_version = MINOR_VERSION;
1597 protocol_version_set = FALSE;
1599 #ifndef DISABLE_SOCKET_TRANSPORT
1600 // FIXME: Move this somewhere else
1602 * Set TCP_NODELAY on the socket so the client receives events/command
1603 * results immediately.
1607 int result = setsockopt (conn_fd,
1612 g_assert (result >= 0);
1618 disconnected = FALSE;
1623 stop_debugger_thread (void)
1628 transport_close1 ();
1631 * Wait for the thread to exit.
1633 * If we continue with the shutdown without waiting for it, then the client might
1634 * not receive an answer to its last command like a resume.
1635 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
1638 //WaitForSingleObject (debugger_thread_handle, INFINITE);
1639 if (GetCurrentThreadId () != debugger_thread_id) {
1641 mono_mutex_lock (&debugger_thread_exited_mutex);
1642 if (!debugger_thread_exited) {
1644 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
1645 mono_mutex_unlock (&debugger_thread_exited_mutex);
1647 mono_mutex_lock (&debugger_thread_exited_mutex);
1650 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1653 mono_mutex_unlock (&debugger_thread_exited_mutex);
1654 } while (!debugger_thread_exited);
1657 transport_close2 ();
1661 start_debugger_thread (void)
1663 debugger_thread_handle = mono_threads_create_thread (debugger_thread, NULL, 0, 0, NULL);
1664 g_assert (debugger_thread_handle);
1668 * Functions to decode protocol data
1672 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1675 g_assert (*endbuf <= limit);
1680 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1683 g_assert (*endbuf <= limit);
1685 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1688 static inline gint64
1689 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1691 guint32 high = decode_int (buf, &buf, limit);
1692 guint32 low = decode_int (buf, &buf, limit);
1696 return ((((guint64)high) << 32) | ((guint64)low));
1700 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1702 return decode_int (buf, endbuf, limit);
1706 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1708 int len = decode_int (buf, &buf, limit);
1716 s = g_malloc (len + 1);
1719 memcpy (s, buf, len);
1728 * Functions to encode protocol data
1732 buffer_init (Buffer *buf, int size)
1734 buf->buf = g_malloc (size);
1736 buf->end = buf->buf + size;
1740 buffer_len (Buffer *buf)
1742 return buf->p - buf->buf;
1746 buffer_make_room (Buffer *buf, int size)
1748 if (buf->end - buf->p < size) {
1749 int new_size = buf->end - buf->buf + size + 32;
1750 guint8 *p = g_realloc (buf->buf, new_size);
1751 size = buf->p - buf->buf;
1754 buf->end = buf->buf + new_size;
1759 buffer_add_byte (Buffer *buf, guint8 val)
1761 buffer_make_room (buf, 1);
1767 buffer_add_short (Buffer *buf, guint32 val)
1769 buffer_make_room (buf, 2);
1770 buf->p [0] = (val >> 8) & 0xff;
1771 buf->p [1] = (val >> 0) & 0xff;
1776 buffer_add_int (Buffer *buf, guint32 val)
1778 buffer_make_room (buf, 4);
1779 buf->p [0] = (val >> 24) & 0xff;
1780 buf->p [1] = (val >> 16) & 0xff;
1781 buf->p [2] = (val >> 8) & 0xff;
1782 buf->p [3] = (val >> 0) & 0xff;
1787 buffer_add_long (Buffer *buf, guint64 l)
1789 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1790 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1794 buffer_add_id (Buffer *buf, int id)
1796 buffer_add_int (buf, (guint64)id);
1800 buffer_add_data (Buffer *buf, guint8 *data, int len)
1802 buffer_make_room (buf, len);
1803 memcpy (buf->p, data, len);
1808 buffer_add_string (Buffer *buf, const char *str)
1813 buffer_add_int (buf, 0);
1816 buffer_add_int (buf, len);
1817 buffer_add_data (buf, (guint8*)str, len);
1822 buffer_add_buffer (Buffer *buf, Buffer *data)
1824 buffer_add_data (buf, data->buf, buffer_len (data));
1828 buffer_free (Buffer *buf)
1834 send_packet (int command_set, int command, Buffer *data)
1840 id = InterlockedIncrement (&packet_id);
1842 len = data->p - data->buf + 11;
1843 buffer_init (&buf, len);
1844 buffer_add_int (&buf, len);
1845 buffer_add_int (&buf, id);
1846 buffer_add_byte (&buf, 0); /* flags */
1847 buffer_add_byte (&buf, command_set);
1848 buffer_add_byte (&buf, command);
1849 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1851 res = transport_send (buf.buf, len);
1859 send_reply_packets (int npackets, ReplyPacket *packets)
1866 for (i = 0; i < npackets; ++i)
1867 len += buffer_len (packets [i].data) + 11;
1868 buffer_init (&buf, len);
1869 for (i = 0; i < npackets; ++i) {
1870 buffer_add_int (&buf, buffer_len (packets [i].data) + 11);
1871 buffer_add_int (&buf, packets [i].id);
1872 buffer_add_byte (&buf, 0x80); /* flags */
1873 buffer_add_byte (&buf, (packets [i].error >> 8) & 0xff);
1874 buffer_add_byte (&buf, packets [i].error);
1875 buffer_add_buffer (&buf, packets [i].data);
1877 res = transport_send (buf.buf, len);
1885 send_reply_packet (int id, int error, Buffer *data)
1889 memset (&packet, 0, sizeof (ReplyPacket));
1891 packet.error = error;
1894 return send_reply_packets (1, &packet);
1898 send_buffered_reply_packets (void)
1902 send_reply_packets (nreply_packets, reply_packets);
1903 for (i = 0; i < nreply_packets; ++i)
1904 buffer_free (reply_packets [i].data);
1905 DEBUG (1, fprintf (log_file, "[dbg] Sent %d buffered reply packets [at=%lx].\n", nreply_packets, (long)mono_100ns_ticks () / 10000));
1910 buffer_reply_packet (int id, int error, Buffer *data)
1914 if (nreply_packets == 128)
1915 send_buffered_reply_packets ();
1917 p = &reply_packets [nreply_packets];
1920 p->data = g_new0 (Buffer, 1);
1921 buffer_init (p->data, buffer_len (data));
1922 buffer_add_buffer (p->data, data);
1931 * Represents an object accessible by the debugger client.
1934 /* Unique id used in the wire protocol to refer to objects */
1937 * A weakref gc handle pointing to the object. The gc handle is used to
1938 * detect if the object was garbage collected.
1943 /* Maps objid -> ObjRef */
1944 static GHashTable *objrefs;
1945 static GHashTable *obj_to_objref;
1946 /* Protected by the dbg lock */
1947 static MonoGHashTable *suspended_objs;
1950 free_objref (gpointer value)
1954 mono_gchandle_free (o->handle);
1962 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1963 obj_to_objref = g_hash_table_new (NULL, NULL);
1964 suspended_objs = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
1965 MONO_GC_REGISTER_ROOT_FIXED (suspended_objs);
1969 objrefs_cleanup (void)
1971 g_hash_table_destroy (objrefs);
1976 * Return an ObjRef for OBJ.
1979 get_objref (MonoObject *obj)
1982 GSList *reflist = NULL, *l;
1988 if (suspend_count) {
1990 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1993 mono_g_hash_table_insert (suspended_objs, obj, NULL);
1997 mono_loader_lock ();
1999 /* FIXME: The tables can grow indefinitely */
2001 if (mono_gc_is_moving ()) {
2003 * Objects can move, so use a hash table mapping hash codes to lists of
2004 * ObjRef structures.
2006 hash = mono_object_hash (obj);
2008 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
2009 for (l = reflist; l; l = l->next) {
2011 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
2012 mono_loader_unlock ();
2017 /* Use a hash table with masked pointers to internalize object references */
2018 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
2019 /* ref might refer to a different object with the same addr which was GCd */
2020 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
2021 mono_loader_unlock ();
2026 ref = g_new0 (ObjRef, 1);
2027 ref->id = InterlockedIncrement (&objref_id);
2028 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
2030 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
2032 if (mono_gc_is_moving ()) {
2033 reflist = g_slist_append (reflist, ref);
2034 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
2036 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
2039 mono_loader_unlock ();
2045 true_pred (gpointer key, gpointer value, gpointer user_data)
2051 clear_suspended_objs (void)
2054 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
2059 get_objid (MonoObject *obj)
2061 return get_objref (obj)->id;
2065 * Set OBJ to the object identified by OBJID.
2066 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
2070 get_object_allow_null (int objid, MonoObject **obj)
2080 return ERR_INVALID_OBJECT;
2082 mono_loader_lock ();
2084 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
2087 *obj = mono_gchandle_get_target (ref->handle);
2088 mono_loader_unlock ();
2090 return ERR_INVALID_OBJECT;
2093 mono_loader_unlock ();
2094 return ERR_INVALID_OBJECT;
2099 get_object (int objid, MonoObject **obj)
2101 int err = get_object_allow_null (objid, obj);
2106 return ERR_INVALID_OBJECT;
2111 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
2113 return decode_id (buf, endbuf, limit);
2117 buffer_add_objid (Buffer *buf, MonoObject *o)
2119 buffer_add_id (buf, get_objid (o));
2138 * Represents a runtime structure accessible to the debugger client
2141 /* Unique id used in the wire protocol */
2143 /* Domain of the runtime structure, NULL if the domain was unloaded */
2150 MonoAssembly *assembly;
2151 MonoClassField *field;
2153 MonoProperty *property;
2158 /* Maps runtime structure -> Id */
2159 GHashTable *val_to_id [ID_NUM];
2160 /* Classes whose class load event has been sent */
2161 GHashTable *loaded_classes;
2162 /* Maps MonoClass->GPtrArray of file names */
2163 GHashTable *source_files;
2164 /* Maps source file basename -> GSList of classes */
2165 GHashTable *source_file_to_class;
2166 /* Same with ignore-case */
2167 GHashTable *source_file_to_class_ignorecase;
2171 /* Protected by the dbg lock */
2172 static GPtrArray *ids [ID_NUM];
2179 for (i = 0; i < ID_NUM; ++i)
2180 ids [i] = g_ptr_array_new ();
2188 for (i = 0; i < ID_NUM; ++i) {
2190 for (j = 0; j < ids [i]->len; ++j)
2191 g_free (g_ptr_array_index (ids [i], j));
2192 g_ptr_array_free (ids [i], TRUE);
2199 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2201 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
2203 GHashTableIter iter;
2204 GPtrArray *file_names;
2209 for (i = 0; i < ID_NUM; ++i)
2210 if (info->val_to_id [i])
2211 g_hash_table_destroy (info->val_to_id [i]);
2212 g_hash_table_destroy (info->loaded_classes);
2214 g_hash_table_iter_init (&iter, info->source_files);
2215 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2216 for (i = 0; i < file_names->len; ++i)
2217 g_free (g_ptr_array_index (file_names, i));
2218 g_ptr_array_free (file_names, TRUE);
2221 g_hash_table_iter_init (&iter, info->source_file_to_class);
2222 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2227 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2228 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2236 domain_jit_info (domain)->agent_info = NULL;
2238 /* Clear ids referencing structures in the domain */
2240 for (i = 0; i < ID_NUM; ++i) {
2242 for (j = 0; j < ids [i]->len; ++j) {
2243 Id *id = g_ptr_array_index (ids [i], j);
2244 if (id->domain == domain)
2251 mono_loader_lock ();
2252 g_hash_table_remove (domains, domain);
2253 mono_loader_unlock ();
2256 static AgentDomainInfo*
2257 get_agent_domain_info (MonoDomain *domain)
2259 AgentDomainInfo *info = NULL;
2261 mono_domain_lock (domain);
2263 info = domain_jit_info (domain)->agent_info;
2265 info = domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
2266 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2267 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2268 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2269 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2272 mono_domain_unlock (domain);
2278 get_id (MonoDomain *domain, IdType type, gpointer val)
2281 AgentDomainInfo *info;
2286 mono_loader_lock ();
2288 mono_domain_lock (domain);
2290 info = get_agent_domain_info (domain);
2292 if (info->val_to_id [type] == NULL)
2293 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2295 id = g_hash_table_lookup (info->val_to_id [type], val);
2297 mono_domain_unlock (domain);
2298 mono_loader_unlock ();
2304 id = g_new0 (Id, 1);
2306 id->id = ids [type]->len + 1;
2307 id->domain = domain;
2310 g_hash_table_insert (info->val_to_id [type], val, id);
2311 g_ptr_array_add (ids [type], id);
2315 mono_domain_unlock (domain);
2317 mono_loader_unlock ();
2322 static inline gpointer
2323 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
2327 int id = decode_id (buf, endbuf, limit);
2336 // FIXME: error handling
2338 g_assert (id > 0 && id <= ids [type]->len);
2340 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2343 if (res->domain == NULL) {
2344 DEBUG (0, fprintf (log_file, "ERR_UNLOADED, id=%d, type=%d.\n", id, type));
2345 *err = ERR_UNLOADED;
2350 *domain = res->domain;
2352 return res->data.val;
2356 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2358 int id = get_id (domain, type, val);
2360 buffer_add_id (buf, id);
2364 static inline MonoClass*
2365 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2369 klass = decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2370 if (G_UNLIKELY (log_level >= 2) && klass) {
2373 s = mono_type_full_name (&klass->byval_arg);
2374 DEBUG(2, fprintf (log_file, "[dbg] recv class [%s]\n", s));
2380 static inline MonoAssembly*
2381 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2383 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2386 static inline MonoImage*
2387 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2389 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2392 static inline MonoMethod*
2393 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2397 m = decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2398 if (G_UNLIKELY (log_level >= 2) && m) {
2401 s = mono_method_full_name (m, TRUE);
2402 DEBUG(2, fprintf (log_file, "[dbg] recv method [%s]\n", s));
2408 static inline MonoClassField*
2409 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2411 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2414 static inline MonoDomain*
2415 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2417 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2420 static inline MonoProperty*
2421 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2423 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2427 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2429 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2430 if (G_UNLIKELY (log_level >= 2) && klass) {
2433 s = mono_type_full_name (&klass->byval_arg);
2434 if (GetCurrentThreadId () == debugger_thread_id)
2435 DEBUG(2, fprintf (log_file, "[dbg] send class [%s]\n", s));
2437 DEBUG(2, fprintf (log_file, "[%p] send class [%s]\n", (gpointer)GetCurrentThreadId (), s));
2443 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2445 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2446 if (G_UNLIKELY (log_level >= 2) && method) {
2449 s = mono_method_full_name (method, 1);
2450 DEBUG(2, fprintf (log_file, "[dbg] send method [%s]\n", s));
2456 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2460 id = buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2461 if (G_UNLIKELY (log_level >= 2) && assembly)
2462 DEBUG(2, fprintf (log_file, "[dbg] send assembly [%s][%s][%d]\n", assembly->aname.name, domain->friendly_name, id));
2466 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2468 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2472 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2474 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2478 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2480 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2484 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2486 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2489 static void invoke_method (void);
2496 * save_thread_context:
2498 * Set CTX as the current threads context which is used for computing stack traces.
2499 * This function is signal-safe.
2502 save_thread_context (MonoContext *ctx)
2504 DebuggerTlsData *tls;
2506 tls = mono_native_tls_get_value (debugger_tls_id);
2510 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2512 mono_thread_state_init_from_current (&tls->context);
2515 /* Number of threads suspended */
2517 * If this is equal to the size of thread_to_tls, the runtime is considered
2520 static gint32 threads_suspend_count;
2522 static mono_mutex_t suspend_mutex;
2524 /* Cond variable used to wait for suspend_count becoming 0 */
2525 static mono_cond_t suspend_cond;
2527 /* Semaphore used to wait for a thread becoming suspended */
2528 static MonoSemType suspend_sem;
2533 mono_mutex_init (&suspend_mutex);
2534 mono_cond_init (&suspend_cond, NULL);
2535 MONO_SEM_INIT (&suspend_sem, 0);
2540 StackFrameInfo last_frame;
2541 gboolean last_frame_set;
2544 } GetLastFrameUserData;
2547 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2549 GetLastFrameUserData *data = user_data;
2551 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
2554 if (!data->last_frame_set) {
2555 /* Store the last frame */
2556 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2557 data->last_frame_set = TRUE;
2560 /* Store the context/lmf for the frame above the last frame */
2561 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2562 data->lmf = info->lmf;
2570 * Process interruption of a thread. If SIGCTX is set, process the current thread. If
2571 * INFO is set, process the thread described by INFO.
2572 * This should be signal safe.
2575 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, void *sigctx, MonoJitInfo *ji)
2579 MonoNativeThreadId tid;
2582 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2583 * guarantee the signal handler will be called that many times. Instead of tracking
2584 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2585 * has been requested that hasn't been handled yet, otherwise we can have threads
2586 * refuse to die when VM_EXIT is called
2588 #if defined(__APPLE__)
2589 if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
2593 * We use interrupt_count to determine whenever this interrupt should be processed
2594 * by us or the normal interrupt processing code in the signal handler.
2595 * There is no race here with notify_thread (), since the signal is sent after
2596 * incrementing interrupt_count.
2598 if (tls->interrupt_count == 0)
2601 InterlockedDecrement (&tls->interrupt_count);
2605 ip = mono_arch_ip_from_context (sigctx);
2607 ip = MONO_CONTEXT_GET_IP (&info->suspend_state.ctx);
2612 tid = mono_thread_info_get_tid (info);
2614 tid = (MonoNativeThreadId)GetCurrentThreadId ();
2616 // FIXME: Races when the thread leaves managed code before hitting a single step
2620 /* Running managed code, will be suspended by the single step code */
2621 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip));
2625 * Running native code, will be suspended when it returns to/enters
2626 * managed code. Treat it as already suspended.
2627 * This might interrupt the code in process_single_step_inner (), we use the
2628 * tls->suspending flag to avoid races when that happens.
2630 if (!tls->suspended && !tls->suspending) {
2632 GetLastFrameUserData data;
2634 // FIXME: printf is not signal safe, but this is only used during
2635 // debugger debugging
2637 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip));
2638 //save_thread_context (&ctx);
2641 /* Already terminated */
2645 * We are in a difficult position: we want to be able to provide stack
2646 * traces for this thread, but we can't use the current ctx+lmf, since
2647 * the thread is still running, so it might return to managed code,
2648 * making these invalid.
2649 * So we start a stack walk and save the first frame, along with the
2650 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2651 * suspended when it returns to managed code, so the parent's ctx should
2654 data.last_frame_set = FALSE;
2656 mono_sigctx_to_monoctx (sigctx, &ctx);
2658 * Don't pass MONO_UNWIND_ACTUAL_METHOD, its not signal safe, and
2659 * get_last_frame () doesn't need it, the last frame cannot be a ginst
2660 * since we are not in a JITted method.
2662 mono_walk_stack_with_ctx (get_last_frame, &ctx, MONO_UNWIND_NONE, &data);
2664 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, &info->suspend_state, MONO_UNWIND_SIGNAL_SAFE, &data);
2666 if (data.last_frame_set) {
2667 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2668 res = mono_thread_state_init_from_monoctx (&tls->async_state, &ctx);
2670 mono_thread_state_init_from_monoctx (&tls->context, &ctx);
2673 memcpy (&tls->async_state.ctx, &data.ctx, sizeof (MonoContext));
2674 tls->async_state.unwind_data [MONO_UNWIND_DATA_LMF] = data.lmf;
2675 tls->async_state.unwind_data [MONO_UNWIND_DATA_JIT_TLS] = tls->thread->jit_data;
2677 tls->async_state.valid = FALSE;
2680 mono_memory_barrier ();
2682 tls->suspended = TRUE;
2683 MONO_SEM_POST (&suspend_sem);
2690 * mono_debugger_agent_thread_interrupt:
2692 * Called by the abort signal handler.
2693 * Should be signal safe.
2696 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
2698 DebuggerTlsData *tls;
2703 tls = mono_native_tls_get_value (debugger_tls_id);
2705 DEBUG (1, fprintf (log_file, "[%p] Received interrupt with no TLS, continuing.\n", (gpointer)GetCurrentThreadId ()));
2709 return thread_interrupt (tls, NULL, sigctx, ji);
2713 static void CALLBACK notify_thread_apc (ULONG_PTR param)
2716 mono_debugger_agent_thread_interrupt (NULL, NULL);
2718 #endif /* HOST_WIN32 */
2721 * reset_native_thread_suspend_state:
2723 * Reset the suspended flag and state on native threads
2726 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2728 DebuggerTlsData *tls = value;
2730 if (!tls->really_suspended && tls->suspended) {
2731 tls->suspended = FALSE;
2733 * The thread might still be running if it was executing native code, so the state won't be invalided by
2734 * suspend_current ().
2736 tls->context.valid = FALSE;
2737 tls->async_state.valid = FALSE;
2738 invalidate_frames (tls);
2745 * Notify a thread that it needs to suspend.
2748 notify_thread (gpointer key, gpointer value, gpointer user_data)
2750 MonoInternalThread *thread = key;
2751 DebuggerTlsData *tls = value;
2752 gsize tid = thread->tid;
2757 if (GetCurrentThreadId () == tid || tls->terminated)
2760 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2763 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2764 * guarantee the signal handler will be called that many times. Instead of tracking
2765 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2766 * has been requested that hasn't been handled yet, otherwise we can have threads
2767 * refuse to die when VM_EXIT is called
2769 #if defined(__APPLE__)
2770 if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
2774 * Maybe we could use the normal interrupt infrastructure, but that does a lot
2775 * of things like breaking waits etc. which we don't want.
2777 InterlockedIncrement (&tls->interrupt_count);
2780 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2781 if (mono_thread_info_new_interrupt_enabled ()) {
2782 MonoThreadInfo *info;
2785 info = mono_thread_info_safe_suspend_sync ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE);
2787 DEBUG(1, fprintf (log_file, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2789 * Attached thread which died without detaching.
2791 tls->terminated = TRUE;
2793 ji = mono_jit_info_table_find (info->suspend_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], MONO_CONTEXT_GET_IP (&info->suspend_state.ctx));
2795 thread_interrupt (tls, info, NULL, ji);
2797 mono_thread_info_finish_suspend_and_resume (info);
2801 // FIXME: Remove this since new interrupt is used on win32 now
2802 QueueUserAPC (notify_thread_apc, thread->handle, (ULONG_PTR)NULL);
2804 res = mono_thread_kill (thread, mono_thread_get_abort_signal ());
2806 DEBUG(1, fprintf (log_file, "[%p] mono_thread_kill () failed for %p: %d...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid, res));
2808 * Attached thread which died without detaching.
2810 tls->terminated = TRUE;
2817 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2819 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2823 if (mono_loader_lock_is_owned_by_self ()) {
2825 * Shortcut for the check in suspend_current (). This speeds up processing
2826 * when executing long running code inside the loader lock, i.e. assembly load
2832 if (debugger_thread_id == GetCurrentThreadId ())
2835 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2836 if (suspend_count - tls->resume_count > 0)
2837 tls->suspending = TRUE;
2839 DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2841 if (suspend_count - tls->resume_count == 0) {
2843 * We are executing a single threaded invoke but the single step for
2844 * suspending is still active.
2845 * FIXME: This slows down single threaded invokes.
2847 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
2851 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2853 /* Can't suspend in these methods */
2854 method = jinfo_get_method (ji);
2855 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2858 save_thread_context (ctx);
2866 * Increase the suspend count of the VM. While the suspend count is greater
2867 * than 0, runtime threads are suspended at certain points during execution.
2872 mono_loader_lock ();
2874 mono_mutex_lock (&suspend_mutex);
2878 DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
2880 if (suspend_count == 1) {
2881 // FIXME: Is it safe to call this inside the lock ?
2882 start_single_stepping ();
2883 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2886 mono_mutex_unlock (&suspend_mutex);
2888 if (suspend_count == 1)
2890 * Suspend creation of new threadpool threads, since they cannot run
2892 mono_thread_pool_suspend ();
2894 mono_loader_unlock ();
2900 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2908 g_assert (debugger_thread_id == GetCurrentThreadId ());
2910 mono_loader_lock ();
2912 mono_mutex_lock (&suspend_mutex);
2914 g_assert (suspend_count > 0);
2917 DEBUG(1, fprintf (log_file, "[%p] Resuming vm, suspend count=%d...\n", (gpointer)GetCurrentThreadId (), suspend_count));
2919 if (suspend_count == 0) {
2920 // FIXME: Is it safe to call this inside the lock ?
2921 stop_single_stepping ();
2922 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2925 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2926 err = mono_cond_broadcast (&suspend_cond);
2927 g_assert (err == 0);
2929 mono_mutex_unlock (&suspend_mutex);
2930 //g_assert (err == 0);
2932 if (suspend_count == 0)
2933 mono_thread_pool_resume ();
2935 mono_loader_unlock ();
2941 * Resume just one thread.
2944 resume_thread (MonoInternalThread *thread)
2947 DebuggerTlsData *tls;
2949 g_assert (debugger_thread_id == GetCurrentThreadId ());
2951 mono_loader_lock ();
2953 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2956 mono_mutex_lock (&suspend_mutex);
2958 g_assert (suspend_count > 0);
2960 DEBUG(1, fprintf (log_file, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid));
2962 tls->resume_count += suspend_count;
2965 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2966 * but only the one whose resume_count field is > 0 will be resumed.
2968 err = mono_cond_broadcast (&suspend_cond);
2969 g_assert (err == 0);
2971 mono_mutex_unlock (&suspend_mutex);
2972 //g_assert (err == 0);
2974 mono_loader_unlock ();
2978 invalidate_frames (DebuggerTlsData *tls)
2983 tls = mono_native_tls_get_value (debugger_tls_id);
2986 for (i = 0; i < tls->frame_count; ++i) {
2987 if (tls->frames [i]->jit)
2988 mono_debug_free_method_jit_info (tls->frames [i]->jit);
2989 g_free (tls->frames [i]);
2991 g_free (tls->frames);
2992 tls->frame_count = 0;
2999 * Suspend the current thread until the runtime is resumed. If the thread has a
3000 * pending invoke, then the invoke is executed before this function returns.
3003 suspend_current (void)
3008 DebuggerTlsData *tls;
3010 g_assert (debugger_thread_id != GetCurrentThreadId ());
3012 if (mono_loader_lock_is_owned_by_self ()) {
3014 * If we own the loader mutex, can't suspend until we release it, since the
3015 * whole runtime can deadlock otherwise.
3020 tls = mono_native_tls_get_value (debugger_tls_id);
3023 mono_mutex_lock (&suspend_mutex);
3025 tls->suspending = FALSE;
3026 tls->really_suspended = TRUE;
3028 if (!tls->suspended) {
3029 tls->suspended = TRUE;
3030 MONO_SEM_POST (&suspend_sem);
3033 DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
3035 while (suspend_count - tls->resume_count > 0) {
3037 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
3039 mono_mutex_unlock (&suspend_mutex);
3041 mono_mutex_lock (&suspend_mutex);
3047 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
3048 g_assert (err == 0);
3052 tls->suspended = FALSE;
3053 tls->really_suspended = FALSE;
3055 threads_suspend_count --;
3057 mono_mutex_unlock (&suspend_mutex);
3059 DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
3061 if (tls->pending_invoke) {
3062 /* Save the original context */
3063 tls->pending_invoke->has_ctx = TRUE;
3064 tls->pending_invoke->ctx = tls->context.ctx;
3069 /* The frame info becomes invalid after a resume */
3070 tls->context.valid = FALSE;
3071 tls->async_state.valid = FALSE;
3072 invalidate_frames (tls);
3076 count_thread (gpointer key, gpointer value, gpointer user_data)
3078 DebuggerTlsData *tls = value;
3080 if (!tls->suspended && !tls->terminated)
3081 *(int*)user_data = *(int*)user_data + 1;
3085 count_threads_to_wait_for (void)
3089 mono_loader_lock ();
3090 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
3091 mono_loader_unlock ();
3099 * Wait until the runtime is completely suspended.
3102 wait_for_suspend (void)
3104 int nthreads, nwait, err;
3105 gboolean waited = FALSE;
3107 // FIXME: Threads starting/stopping ?
3108 mono_loader_lock ();
3109 nthreads = mono_g_hash_table_size (thread_to_tls);
3110 mono_loader_unlock ();
3113 nwait = count_threads_to_wait_for ();
3115 DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
3116 err = MONO_SEM_WAIT (&suspend_sem);
3117 g_assert (err == 0);
3125 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
3131 * Return whenever the runtime is suspended.
3136 return count_threads_to_wait_for () == 0;
3140 no_seq_points_found (MonoMethod *method)
3143 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3145 printf ("Unable to find seq points for method '%s'.\n", mono_method_full_name (method, TRUE));
3149 DebuggerTlsData *tls;
3151 } ComputeFramesUserData;
3154 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3156 ComputeFramesUserData *ud = user_data;
3158 MonoMethod *method, *actual_method, *api_method;
3162 if (info->type != FRAME_TYPE_MANAGED) {
3163 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3164 /* Mark the last frame as an invoke frame */
3166 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3172 method = jinfo_get_method (info->ji);
3174 method = info->method;
3175 actual_method = info->actual_method;
3176 api_method = method;
3181 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3184 if (info->il_offset == -1) {
3185 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3186 if (ud->frames == NULL) {
3187 if (find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL, &sp))
3188 info->il_offset = sp.il_offset;
3190 if (info->il_offset == -1)
3191 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3194 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));
3196 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3197 if (!CHECK_PROTOCOL_VERSION (2, 17))
3198 /* Older clients can't handle this flag */
3200 api_method = mono_marshal_method_from_wrapper (method);
3203 actual_method = api_method;
3204 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3207 frame = g_new0 (StackFrame, 1);
3208 frame->method = method;
3209 frame->actual_method = actual_method;
3210 frame->api_method = api_method;
3211 frame->il_offset = info->il_offset;
3212 frame->native_offset = info->native_offset;
3213 frame->flags = flags;
3214 frame->ji = info->ji;
3215 if (info->reg_locations)
3216 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3219 frame->has_ctx = TRUE;
3221 frame->domain = info->domain;
3223 ud->frames = g_slist_append (ud->frames, frame);
3229 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3231 ComputeFramesUserData *ud = user_data;
3234 * 'tls->filter_ctx' is the location of the throw site.
3236 * mono_walk_stack() will never actually hit the throw site, but unwind
3237 * directly from the filter to the call site; we abort stack unwinding here
3238 * once this happens and resume from the throw site.
3241 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3244 return process_frame (info, ctx, user_data);
3248 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3250 ComputeFramesUserData user_data;
3252 int i, findex, new_frame_count;
3253 StackFrame **new_frames, *f;
3254 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3256 // FIXME: Locking on tls
3257 if (tls->frames && tls->frames_up_to_date)
3260 DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
3262 user_data.tls = tls;
3263 user_data.frames = NULL;
3264 if (tls->terminated) {
3265 tls->frame_count = 0;
3267 } if (!tls->really_suspended && tls->async_state.valid) {
3268 /* Have to use the state saved by the signal handler */
3269 process_frame (&tls->async_last_frame, NULL, &user_data);
3270 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3271 } else if (tls->filter_state.valid) {
3273 * We are inside an exception filter.
3275 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3277 if (tls->context.valid)
3278 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3280 * After that, we resume unwinding from the location where the exception has been thrown.
3282 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3283 } else if (tls->context.valid) {
3284 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3287 tls->frame_count = 0;
3291 new_frame_count = g_slist_length (user_data.frames);
3292 new_frames = g_new0 (StackFrame*, new_frame_count);
3294 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3298 * Reuse the id for already existing stack frames, so invokes don't invalidate
3299 * the still valid stack frames.
3301 for (i = 0; i < tls->frame_count; ++i) {
3302 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3303 f->id = tls->frames [i]->id;
3308 if (i >= tls->frame_count)
3309 f->id = InterlockedIncrement (&frame_id);
3311 new_frames [findex ++] = f;
3314 g_slist_free (user_data.frames);
3316 invalidate_frames (tls);
3318 tls->frames = new_frames;
3319 tls->frame_count = new_frame_count;
3320 tls->frames_up_to_date = TRUE;
3324 * GHFunc to emit an appdomain creation event
3325 * @param key Don't care
3326 * @param value A loaded appdomain
3327 * @param user_data Don't care
3330 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3332 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3333 g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
3337 * GHFunc to emit a thread start event
3338 * @param key A thread id
3339 * @param value A thread object
3340 * @param user_data Don't care
3343 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3345 if (GPOINTER_TO_INT (key) != debugger_thread_id)
3346 process_profiler_event (EVENT_KIND_THREAD_START, value);
3350 * GFunc to emit an assembly load event
3351 * @param value A loaded assembly
3352 * @param user_data Don't care
3355 emit_assembly_load (gpointer value, gpointer user_data)
3357 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3361 * GFunc to emit a type load event
3362 * @param value A loaded type
3363 * @param user_data Don't care
3366 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3368 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3372 strdup_tolower (char *s)
3377 for (p = s2; *p; ++p)
3387 * create_event_list:
3389 * Return a list of event request ids matching EVENT, starting from REQS, which
3390 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3392 * We return request ids, instead of requests, to simplify threading, since
3393 * requests could be deleted anytime when the loader lock is not held.
3394 * LOCKING: Assumes the loader lock is held.
3397 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3400 GSList *events = NULL;
3402 *suspend_policy = SUSPEND_POLICY_NONE;
3405 reqs = event_requests;
3410 for (i = 0; i < reqs->len; ++i) {
3411 EventRequest *req = g_ptr_array_index (reqs, i);
3412 if (req->event_kind == event) {
3413 gboolean filtered = FALSE;
3416 for (j = 0; j < req->nmodifiers; ++j) {
3417 Modifier *mod = &req->modifiers [j];
3419 if (mod->kind == MOD_KIND_COUNT) {
3421 if (mod->data.count > 0) {
3422 if (mod->data.count > 0) {
3424 if (mod->data.count == 0)
3428 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3429 if (mod->data.thread != mono_thread_internal_current ())
3431 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3432 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3434 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3436 if (ei->caught && !mod->caught)
3438 if (!ei->caught && !mod->uncaught)
3440 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3442 gboolean found = FALSE;
3443 MonoAssembly **assemblies = mod->data.assemblies;
3446 for (k = 0; assemblies [k]; ++k)
3447 if (assemblies [k] == jinfo_get_method (ji)->klass->image->assembly)
3452 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3453 gpointer iter = NULL;
3455 MonoDebugSourceInfo *sinfo;
3456 char *source_file, *s;
3457 gboolean found = FALSE;
3459 GPtrArray *source_file_list;
3461 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3462 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3465 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
3466 for (i = 0; i < source_file_list->len; ++i) {
3467 sinfo = g_ptr_array_index (source_file_list, i);
3469 * Do a case-insesitive match by converting the file name to
3472 s = strdup_tolower (sinfo->source_file);
3473 if (g_hash_table_lookup (mod->data.source_files, s))
3476 char *s2 = g_path_get_basename (sinfo->source_file);
3477 char *s3 = strdup_tolower (s2);
3479 if (g_hash_table_lookup (mod->data.source_files, s3))
3486 g_ptr_array_free (source_file_list, TRUE);
3491 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3494 s = mono_type_full_name (&ei->klass->byval_arg);
3495 if (!g_hash_table_lookup (mod->data.type_names, s))
3498 } else if (mod->kind == MOD_KIND_STEP) {
3499 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3500 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3501 !strcmp (jinfo_get_method (ji)->name, ".cctor"))
3503 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3504 MonoCustomAttrInfo *ainfo;
3505 static MonoClass *klass;
3508 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3511 if (!ji->dbg_hidden_inited) {
3512 ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji));
3514 if (mono_custom_attrs_has_attr (ainfo, klass))
3515 ji->dbg_hidden = TRUE;
3516 mono_custom_attrs_free (ainfo);
3518 ji->dbg_hidden_inited = TRUE;
3523 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3524 MonoCustomAttrInfo *ainfo;
3525 static MonoClass *klass;
3528 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3531 if (!ji->dbg_step_through_inited) {
3532 ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji));
3534 if (mono_custom_attrs_has_attr (ainfo, klass))
3535 ji->dbg_step_through = TRUE;
3536 mono_custom_attrs_free (ainfo);
3538 ainfo = mono_custom_attrs_from_class (jinfo_get_method (ji)->klass);
3540 if (mono_custom_attrs_has_attr (ainfo, klass))
3541 ji->dbg_step_through = TRUE;
3542 mono_custom_attrs_free (ainfo);
3544 ji->dbg_step_through_inited = TRUE;
3546 if (ji->dbg_step_through)
3549 if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3550 MonoCustomAttrInfo *ainfo;
3551 static MonoClass *klass;
3554 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute");
3557 if (!ji->dbg_non_user_code_inited) {
3558 ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji));
3560 if (mono_custom_attrs_has_attr (ainfo, klass))
3561 ji->dbg_non_user_code = TRUE;
3562 mono_custom_attrs_free (ainfo);
3564 ainfo = mono_custom_attrs_from_class (jinfo_get_method (ji)->klass);
3566 if (mono_custom_attrs_has_attr (ainfo, klass))
3567 ji->dbg_non_user_code = TRUE;
3568 mono_custom_attrs_free (ainfo);
3570 ji->dbg_non_user_code_inited = TRUE;
3572 if (ji->dbg_non_user_code)
3579 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3580 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3585 /* Send a VM START/DEATH event by default */
3586 if (event == EVENT_KIND_VM_START)
3587 events = g_slist_append (events, GINT_TO_POINTER (0));
3588 if (event == EVENT_KIND_VM_DEATH)
3589 events = g_slist_append (events, GINT_TO_POINTER (0));
3594 static G_GNUC_UNUSED const char*
3595 event_to_string (EventKind event)
3598 case EVENT_KIND_VM_START: return "VM_START";
3599 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3600 case EVENT_KIND_THREAD_START: return "THREAD_START";
3601 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3602 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3603 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3604 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3605 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3606 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3607 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3608 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3609 case EVENT_KIND_STEP: return "STEP";
3610 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3611 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3612 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3613 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3614 case EVENT_KIND_USER_LOG: return "USER_LOG";
3616 g_assert_not_reached ();
3624 * Send an event to the client, suspending the vm if needed.
3625 * LOCKING: Since this can suspend the calling thread, no locks should be held
3627 * The EVENTS list is freed by this function.
3630 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3634 MonoDomain *domain = mono_domain_get ();
3635 MonoThread *thread = NULL;
3636 MonoObject *keepalive_obj = NULL;
3637 gboolean send_success = FALSE;
3642 DEBUG (2, fprintf (log_file, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event)));
3646 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3647 // FIXME: We miss those events
3648 DEBUG (2, fprintf (log_file, "VM start event not sent yet: dropping %s\n", event_to_string (event)));
3652 if (vm_death_event_sent) {
3653 DEBUG (2, fprintf (log_file, "VM death event has been sent: dropping %s\n", event_to_string (event)));
3657 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3658 DEBUG (2, fprintf (log_file, "Mono runtime is shutting down: dropping %s\n", event_to_string (event)));
3663 DEBUG (2, fprintf (log_file, "Debugger client is not connected: dropping %s\n", event_to_string (event)));
3667 if (event == EVENT_KIND_KEEPALIVE)
3668 suspend_policy = SUSPEND_POLICY_NONE;
3673 if (agent_config.defer) {
3674 /* Make sure the thread id is always set when doing deferred debugging */
3675 if (debugger_thread_id == GetCurrentThreadId ()) {
3676 /* Don't suspend on events from the debugger thread */
3677 suspend_policy = SUSPEND_POLICY_NONE;
3678 thread = mono_thread_get_main ();
3680 else thread = mono_thread_current ();
3682 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3683 // FIXME: Send these with a NULL thread, don't suspend the current thread
3688 nevents = g_slist_length (events);
3689 buffer_init (&buf, 128);
3690 buffer_add_byte (&buf, suspend_policy);
3691 buffer_add_int (&buf, nevents);
3693 for (l = events; l; l = l->next) {
3694 buffer_add_byte (&buf, event); // event kind
3695 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3700 thread = mono_thread_current ();
3702 if (event == EVENT_KIND_VM_START && arg != NULL)
3705 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3708 case EVENT_KIND_THREAD_START:
3709 case EVENT_KIND_THREAD_DEATH:
3711 case EVENT_KIND_APPDOMAIN_CREATE:
3712 case EVENT_KIND_APPDOMAIN_UNLOAD:
3713 buffer_add_domainid (&buf, arg);
3715 case EVENT_KIND_METHOD_ENTRY:
3716 case EVENT_KIND_METHOD_EXIT:
3717 buffer_add_methodid (&buf, domain, arg);
3719 case EVENT_KIND_ASSEMBLY_LOAD:
3720 buffer_add_assemblyid (&buf, domain, arg);
3722 case EVENT_KIND_ASSEMBLY_UNLOAD: {
3723 DebuggerTlsData *tls;
3725 /* The domain the assembly belonged to is not equal to the current domain */
3726 tls = mono_native_tls_get_value (debugger_tls_id);
3728 g_assert (tls->domain_unloading);
3730 buffer_add_assemblyid (&buf, tls->domain_unloading, arg);
3733 case EVENT_KIND_TYPE_LOAD:
3734 buffer_add_typeid (&buf, domain, arg);
3736 case EVENT_KIND_BREAKPOINT:
3737 case EVENT_KIND_STEP:
3738 buffer_add_methodid (&buf, domain, arg);
3739 buffer_add_long (&buf, il_offset);
3741 case EVENT_KIND_VM_START:
3742 buffer_add_domainid (&buf, mono_get_root_domain ());
3744 case EVENT_KIND_VM_DEATH:
3745 if (CHECK_PROTOCOL_VERSION (2, 27))
3746 buffer_add_int (&buf, mono_environment_exitcode_get ());
3748 case EVENT_KIND_EXCEPTION: {
3749 EventInfo *ei = arg;
3750 buffer_add_objid (&buf, ei->exc);
3752 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3753 * later after the suspension. (#12494).
3755 keepalive_obj = ei->exc;
3758 case EVENT_KIND_USER_BREAK:
3760 case EVENT_KIND_USER_LOG: {
3761 EventInfo *ei = arg;
3762 buffer_add_int (&buf, ei->level);
3763 buffer_add_string (&buf, ei->category ? ei->category : "");
3764 buffer_add_string (&buf, ei->message ? ei->message : "");
3767 case EVENT_KIND_KEEPALIVE:
3768 suspend_policy = SUSPEND_POLICY_NONE;
3771 g_assert_not_reached ();
3775 if (event == EVENT_KIND_VM_START) {
3776 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3777 if (!agent_config.defer)
3778 start_debugger_thread ();
3781 if (event == EVENT_KIND_VM_DEATH) {
3782 vm_death_event_sent = TRUE;
3783 suspend_policy = SUSPEND_POLICY_NONE;
3786 if (mono_runtime_is_shutting_down ())
3787 suspend_policy = SUSPEND_POLICY_NONE;
3789 if (suspend_policy != SUSPEND_POLICY_NONE) {
3791 * Save the thread context and start suspending before sending the packet,
3792 * since we could be receiving the resume request before send_packet ()
3795 save_thread_context (ctx);
3799 /* This will keep this object alive */
3800 get_objref (keepalive_obj);
3803 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3807 g_slist_free (events);
3810 if (!send_success) {
3811 DEBUG (2, fprintf (log_file, "Sending command %s failed.\n", event_to_string (event)));
3815 if (event == EVENT_KIND_VM_START) {
3816 vm_start_event_sent = TRUE;
3819 DEBUG (1, fprintf (log_file, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer)GetCurrentThreadId (), nevents, event_to_string (event), ecount, suspend_policy));
3821 switch (suspend_policy) {
3822 case SUSPEND_POLICY_NONE:
3824 case SUSPEND_POLICY_ALL:
3827 case SUSPEND_POLICY_EVENT_THREAD:
3831 g_assert_not_reached ();
3836 process_profiler_event (EventKind event, gpointer arg)
3840 EventInfo ei, *ei_arg = NULL;
3842 if (event == EVENT_KIND_TYPE_LOAD) {
3847 mono_loader_lock ();
3848 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3849 mono_loader_unlock ();
3851 process_event (event, arg, 0, NULL, events, suspend_policy);
3855 runtime_initialized (MonoProfiler *prof)
3857 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3858 if (agent_config.defer)
3859 start_debugger_thread ();
3863 runtime_shutdown (MonoProfiler *prof)
3865 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3867 mono_debugger_agent_cleanup ();
3871 thread_startup (MonoProfiler *prof, uintptr_t tid)
3873 MonoInternalThread *thread = mono_thread_internal_current ();
3874 MonoInternalThread *old_thread;
3875 DebuggerTlsData *tls;
3877 if (tid == debugger_thread_id)
3880 g_assert (thread->tid == tid);
3882 mono_loader_lock ();
3883 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3884 mono_loader_unlock ();
3886 if (thread == old_thread) {
3888 * For some reason, thread_startup () might be called for the same thread
3889 * multiple times (attach ?).
3891 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
3895 * thread_end () might not be called for some threads, and the tid could
3898 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
3899 mono_loader_lock ();
3900 mono_g_hash_table_remove (thread_to_tls, old_thread);
3901 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3902 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3903 mono_loader_unlock ();
3907 tls = mono_native_tls_get_value (debugger_tls_id);
3909 // FIXME: Free this somewhere
3910 tls = g_new0 (DebuggerTlsData, 1);
3911 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3912 tls->thread = thread;
3913 mono_native_tls_set_value (debugger_tls_id, tls);
3915 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3917 mono_loader_lock ();
3918 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3919 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3920 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3921 mono_loader_unlock ();
3923 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3926 * suspend_vm () could have missed this thread, so wait for a resume.
3932 thread_end (MonoProfiler *prof, uintptr_t tid)
3934 MonoInternalThread *thread;
3935 DebuggerTlsData *tls = NULL;
3937 mono_loader_lock ();
3938 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3940 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3941 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3943 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3944 tls->terminated = TRUE;
3945 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3946 MONO_GC_UNREGISTER_ROOT (tls->thread);
3950 mono_loader_unlock ();
3952 /* We might be called for threads started before we registered the start callback */
3954 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3955 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3960 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3962 mono_loader_lock ();
3963 g_hash_table_insert (domains, domain, domain);
3964 mono_loader_unlock ();
3966 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3970 appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain)
3972 DebuggerTlsData *tls;
3975 * Remember the currently unloading appdomain as it is needed to generate
3976 * proper ids for unloading assemblies.
3978 tls = mono_native_tls_get_value (debugger_tls_id);
3980 tls->domain_unloading = domain;
3984 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3986 DebuggerTlsData *tls;
3988 tls = mono_native_tls_get_value (debugger_tls_id);
3990 tls->domain_unloading = NULL;
3992 clear_breakpoints_for_domain (domain);
3994 mono_loader_lock ();
3995 /* Invalidate each thread's frame stack */
3996 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3997 mono_loader_unlock ();
3999 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
4003 * invalidate_each_thread:
4005 * A GHFunc to invalidate frames.
4006 * value must be a DebuggerTlsData*
4009 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
4011 invalidate_frames (value);
4015 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
4017 /* Sent later in jit_end () */
4019 g_ptr_array_add (pending_assembly_loads, assembly);
4024 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
4026 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
4028 clear_event_requests_for_assembly (assembly);
4029 clear_types_for_assembly (assembly);
4033 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
4035 #if defined(HOST_WIN32) && !defined(__GNUC__)
4036 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
4038 gpointer stackptr = __builtin_frame_address (1);
4040 MonoInternalThread *thread = mono_thread_internal_current ();
4041 DebuggerTlsData *tls;
4043 mono_loader_lock ();
4045 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4046 /* Could be the debugger thread with assembly/type load hooks */
4048 tls->invoke_addr = stackptr;
4050 mono_loader_unlock ();
4054 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
4057 #if defined(HOST_WIN32) && !defined(__GNUC__)
4058 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
4060 gpointer stackptr = __builtin_frame_address (1);
4063 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
4067 * We need to stop single stepping when exiting a runtime invoke, since if it is
4068 * a step out, it may return to native code, and thus never end.
4070 mono_loader_lock ();
4071 ss_invoke_addr = NULL;
4073 for (i = 0; i < event_requests->len; ++i) {
4074 EventRequest *req = g_ptr_array_index (event_requests, i);
4076 if (req->event_kind == EVENT_KIND_STEP) {
4077 ss_destroy (req->info);
4078 g_ptr_array_remove_index_fast (event_requests, i);
4083 mono_loader_unlock ();
4087 send_type_load (MonoClass *klass)
4089 gboolean type_load = FALSE;
4090 MonoDomain *domain = mono_domain_get ();
4091 AgentDomainInfo *info = NULL;
4093 mono_loader_lock ();
4094 mono_domain_lock (domain);
4096 info = get_agent_domain_info (domain);
4098 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
4100 g_hash_table_insert (info->loaded_classes, klass, klass);
4103 mono_domain_unlock (domain);
4104 mono_loader_unlock ();
4106 emit_type_load (klass, klass, NULL);
4110 * Emit load events for all types currently loaded in the domain.
4111 * Takes the loader and domain locks.
4112 * user_data is unused.
4115 send_types_for_domain (MonoDomain *domain, void *user_data)
4117 AgentDomainInfo *info = NULL;
4119 mono_loader_lock ();
4120 mono_domain_lock (domain);
4121 info = get_agent_domain_info (domain);
4123 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4124 mono_domain_unlock (domain);
4125 mono_loader_unlock ();
4129 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
4132 * We emit type load events when the first method of the type is JITted,
4133 * since the class load profiler callbacks might be called with the
4134 * loader lock held. They could also occur in the debugger thread.
4135 * Same for assembly load events.
4138 MonoAssembly *assembly = NULL;
4140 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4142 if (pending_assembly_loads->len > 0) {
4143 assembly = g_ptr_array_index (pending_assembly_loads, 0);
4144 g_ptr_array_remove_index (pending_assembly_loads, 0);
4149 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4155 send_type_load (method->klass);
4158 add_pending_breakpoints (method, jinfo);
4162 * BREAKPOINTS/SINGLE STEPPING
4166 * Contains information about an inserted breakpoint.
4169 long il_offset, native_offset;
4173 } BreakpointInstance;
4176 * Contains generic information about a breakpoint.
4180 * The method where the breakpoint is placed. Can be NULL in which case it
4181 * is inserted into every method. This is used to implement method entry/
4182 * exit events. Can be a generic method definition, in which case the
4183 * breakpoint is inserted into every instance.
4189 * A list of BreakpointInstance structures describing where the breakpoint
4190 * was inserted. There could be more than one because of
4191 * generics/appdomains/method entry/exit.
4193 GPtrArray *children;
4196 /* List of breakpoints */
4197 static GPtrArray *breakpoints;
4198 /* Maps breakpoint locations to the number of breakpoints at that location */
4199 static GHashTable *bp_locs;
4202 breakpoints_init (void)
4204 breakpoints = g_ptr_array_new ();
4205 bp_locs = g_hash_table_new (NULL, NULL);
4209 * insert_breakpoint:
4211 * Insert the breakpoint described by BP into the method described by
4215 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4218 BreakpointInstance *inst;
4219 SeqPointIterator it;
4220 gboolean it_has_sp = FALSE;
4223 mono_error_init (error);
4225 seq_point_iterator_init (&it, seq_points);
4226 while (seq_point_iterator_next (&it)) {
4227 if (it.seq_point.il_offset == bp->il_offset) {
4235 * The set of IL offsets with seq points doesn't completely match the
4236 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4238 seq_point_iterator_init (&it, seq_points);
4239 while (seq_point_iterator_next (&it)) {
4240 if (it.seq_point.il_offset != METHOD_ENTRY_IL_OFFSET &&
4241 it.seq_point.il_offset != METHOD_EXIT_IL_OFFSET &&
4242 it.seq_point.il_offset + 1 == bp->il_offset) {
4250 char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d", mono_method_full_name (jinfo_get_method (ji), TRUE), bp->il_offset);
4252 seq_point_iterator_init (&it, seq_points);
4253 while (seq_point_iterator_next (&it))
4254 DEBUG (1, fprintf (log_file, "%d\n", it.seq_point.il_offset));
4257 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4258 g_warning ("%s", s);
4262 g_warning ("%s", s);
4268 inst = g_new0 (BreakpointInstance, 1);
4269 inst->il_offset = it.seq_point.il_offset;
4270 inst->native_offset = it.seq_point.native_offset;
4271 inst->ip = (guint8*)ji->code_start + it.seq_point.native_offset;
4273 inst->domain = domain;
4275 mono_loader_lock ();
4277 g_ptr_array_add (bp->children, inst);
4279 mono_loader_unlock ();
4282 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4283 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4286 if (it.seq_point.native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4287 DEBUG (1, fprintf (log_file, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset));
4288 } else if (count == 0) {
4289 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4290 mono_arch_set_breakpoint (ji, inst->ip);
4296 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)it.seq_point.il_offset, inst->ip, count));
4300 remove_breakpoint (BreakpointInstance *inst)
4302 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4304 MonoJitInfo *ji = inst->ji;
4305 guint8 *ip = inst->ip;
4308 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4309 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4312 g_assert (count > 0);
4314 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4315 mono_arch_clear_breakpoint (ji, ip);
4316 DEBUG(1, fprintf (log_file, "[dbg] Clear breakpoint at %s [%p].\n", mono_method_full_name (jinfo_get_method (ji), TRUE), ip));
4323 static inline gboolean
4324 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4330 if (method == bp->method)
4332 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4335 if (bp->method->is_inflated && method->is_inflated) {
4336 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4337 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4339 /* Open generic methods should match closed generic methods of the same class */
4340 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4341 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4342 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4344 /* FIXME: Handle !mvar */
4345 if (t1->type != MONO_TYPE_MVAR)
4356 * add_pending_breakpoints:
4358 * Insert pending breakpoints into the newly JITted method METHOD.
4361 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4364 MonoSeqPointInfo *seq_points;
4366 MonoMethod *jmethod;
4371 domain = mono_domain_get ();
4373 mono_loader_lock ();
4375 for (i = 0; i < breakpoints->len; ++i) {
4376 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4377 gboolean found = FALSE;
4379 if (!bp_matches_method (bp, method))
4382 for (j = 0; j < bp->children->len; ++j) {
4383 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4390 jmethod = jinfo_get_method (ji);
4391 mono_domain_lock (domain);
4392 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, jmethod);
4393 if (!seq_points && jmethod->is_inflated)
4394 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (jmethod));
4395 mono_domain_unlock (domain);
4397 /* Could be AOT code */
4399 g_assert (seq_points);
4401 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4405 mono_loader_unlock ();
4409 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4415 mono_error_init (error);
4417 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4419 /* Might be AOTed code */
4420 code = mono_aot_get_method (domain, method);
4422 ji = mono_jit_info_table_find (domain, code);
4427 insert_breakpoint (seq_points, domain, ji, bp, error);
4431 clear_breakpoint (MonoBreakpoint *bp);
4436 * Set a breakpoint at IL_OFFSET in METHOD.
4437 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4438 * METHOD can also be a generic method definition, in which case a breakpoint
4439 * is placed in all instances of the method.
4440 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4443 static MonoBreakpoint*
4444 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4447 GHashTableIter iter, iter2;
4450 MonoSeqPointInfo *seq_points;
4453 mono_error_init (error);
4456 // - suspend/resume the vm to prevent code patching problems
4457 // - multiple breakpoints on the same location
4458 // - dynamic methods
4461 bp = g_new0 (MonoBreakpoint, 1);
4462 bp->method = method;
4463 bp->il_offset = il_offset;
4465 bp->children = g_ptr_array_new ();
4467 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));
4469 mono_loader_lock ();
4471 g_hash_table_iter_init (&iter, domains);
4472 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4473 mono_domain_lock (domain);
4475 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4476 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4477 if (bp_matches_method (bp, m))
4478 set_bp_in_method (domain, m, seq_points, bp, error);
4481 mono_domain_unlock (domain);
4484 mono_loader_unlock ();
4486 mono_loader_lock ();
4487 g_ptr_array_add (breakpoints, bp);
4488 mono_loader_unlock ();
4490 if (error && !mono_error_ok (error)) {
4491 clear_breakpoint (bp);
4499 clear_breakpoint (MonoBreakpoint *bp)
4503 // FIXME: locking, races
4504 for (i = 0; i < bp->children->len; ++i) {
4505 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4507 remove_breakpoint (inst);
4512 mono_loader_lock ();
4513 g_ptr_array_remove (breakpoints, bp);
4514 mono_loader_unlock ();
4516 g_ptr_array_free (bp->children, TRUE);
4521 breakpoints_cleanup (void)
4525 mono_loader_lock ();
4527 while (i < event_requests->len) {
4528 EventRequest *req = g_ptr_array_index (event_requests, i);
4530 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4531 clear_breakpoint (req->info);
4532 g_ptr_array_remove_index_fast (event_requests, i);
4539 for (i = 0; i < breakpoints->len; ++i)
4540 g_free (g_ptr_array_index (breakpoints, i));
4542 g_ptr_array_free (breakpoints, TRUE);
4543 g_hash_table_destroy (bp_locs);
4548 mono_loader_unlock ();
4552 * clear_breakpoints_for_domain:
4554 * Clear breakpoint instances which reference DOMAIN.
4557 clear_breakpoints_for_domain (MonoDomain *domain)
4561 /* This could be called after shutdown */
4565 mono_loader_lock ();
4566 for (i = 0; i < breakpoints->len; ++i) {
4567 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4570 while (j < bp->children->len) {
4571 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4573 if (inst->domain == domain) {
4574 remove_breakpoint (inst);
4578 g_ptr_array_remove_index_fast (bp->children, j);
4584 mono_loader_unlock ();
4590 * Return FALSE if single stepping needs to continue.
4593 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp, DebuggerTlsData *tls, MonoContext *ctx)
4595 MonoDebugMethodInfo *minfo;
4596 MonoDebugSourceLocation *loc = NULL;
4597 gboolean hit = TRUE;
4600 if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK)) {
4602 * These seq points are inserted by the JIT after calls, step over needs to skip them.
4604 DEBUG (1, fprintf (log_file, "[%p] Seq point at nonempty stack %x while stepping over, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset));
4608 if (req->depth == STEP_DEPTH_OVER && hit) {
4609 if (!tls->context.valid)
4610 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4611 compute_frame_info (tls->thread, tls);
4612 if (req->nframes && tls->frame_count && tls->frame_count > req->nframes) {
4613 /* Hit the breakpoint in a recursive call */
4614 DEBUG (1, fprintf (log_file, "[%p] Breakpoint at lower frame while stepping over, continuing single stepping.\n", (gpointer)GetCurrentThreadId ()));
4619 if (req->size != STEP_SIZE_LINE)
4622 /* Have to check whenever a different source line was reached */
4623 method = jinfo_get_method (ji);
4624 minfo = mono_debug_lookup_method (method);
4627 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4629 if (!loc || (loc && method == ss_req->last_method && loc->row == ss_req->last_line)) {
4630 /* Have to continue single stepping */
4632 DEBUG(1, fprintf (log_file, "[%p] No line number info for il offset %x, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset));
4634 DEBUG(1, fprintf (log_file, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer)GetCurrentThreadId (), loc->row));
4639 ss_req->last_method = method;
4640 ss_req->last_line = loc->row;
4641 mono_debug_free_source_location (loc);
4648 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4650 return bp->method && bp->method->klass->image->assembly == assembly;
4654 process_breakpoint_inner (DebuggerTlsData *tls)
4658 int i, j, suspend_policy;
4659 guint32 native_offset;
4661 BreakpointInstance *inst;
4662 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4663 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4664 EventKind kind = EVENT_KIND_BREAKPOINT;
4665 MonoContext *ctx = &tls->restore_ctx;
4667 MonoSeqPointInfo *info;
4671 // FIXME: Speed this up
4673 ip = MONO_CONTEXT_GET_IP (ctx);
4674 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4676 method = jinfo_get_method (ji);
4678 /* Compute the native offset of the breakpoint from the ip */
4679 native_offset = ip - (guint8*)ji->code_start;
4682 * Skip the instruction causing the breakpoint signal.
4684 mono_arch_skip_breakpoint (ctx, ji);
4686 if (method->wrapper_type || tls->disable_breakpoints)
4689 bp_reqs = g_ptr_array_new ();
4690 ss_reqs = g_ptr_array_new ();
4691 ss_reqs_orig = g_ptr_array_new ();
4693 mono_loader_lock ();
4696 * The ip points to the instruction causing the breakpoint event, which is after
4697 * the offset recorded in the seq point map, so find the prev seq point before ip.
4699 found_sp = find_prev_seq_point_for_native_offset (mono_domain_get (), method, native_offset, &info, &sp);
4702 no_seq_points_found (method);
4704 g_assert (found_sp);
4706 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.il_offset));
4709 for (i = 0; i < breakpoints->len; ++i) {
4710 bp = g_ptr_array_index (breakpoints, i);
4715 for (j = 0; j < bp->children->len; ++j) {
4716 inst = g_ptr_array_index (bp->children, j);
4717 if (inst->ji == ji && inst->il_offset == sp.il_offset && inst->native_offset == sp.native_offset) {
4718 if (bp->req->event_kind == EVENT_KIND_STEP) {
4719 g_ptr_array_add (ss_reqs_orig, bp->req);
4721 g_ptr_array_add (bp_reqs, bp->req);
4726 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4727 /* Maybe a method entry/exit event */
4728 if (sp.il_offset == METHOD_ENTRY_IL_OFFSET)
4729 kind = EVENT_KIND_METHOD_ENTRY;
4730 else if (sp.il_offset == METHOD_EXIT_IL_OFFSET)
4731 kind = EVENT_KIND_METHOD_EXIT;
4734 /* Process single step requests */
4735 for (i = 0; i < ss_reqs_orig->len; ++i) {
4736 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4737 SingleStepReq *ss_req = req->info;
4740 if (mono_thread_internal_current () != ss_req->thread)
4743 hit = ss_update (ss_req, ji, &sp, tls, ctx);
4745 g_ptr_array_add (ss_reqs, req);
4747 /* Start single stepping again from the current sequence point */
4748 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE);
4751 if (ss_reqs->len > 0)
4752 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4753 if (bp_reqs->len > 0)
4754 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4755 if (kind != EVENT_KIND_BREAKPOINT)
4756 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4758 mono_loader_unlock ();
4760 g_ptr_array_free (bp_reqs, TRUE);
4761 g_ptr_array_free (ss_reqs, TRUE);
4764 * FIXME: The first event will suspend, so the second will only be sent after the
4768 process_event (EVENT_KIND_STEP, method, 0, ctx, ss_events, suspend_policy);
4770 process_event (kind, method, 0, ctx, bp_events, suspend_policy);
4771 if (enter_leave_events)
4772 process_event (kind, method, 0, ctx, enter_leave_events, suspend_policy);
4775 /* Process a breakpoint/single step event after resuming from a signal handler */
4777 process_signal_event (void (*func) (DebuggerTlsData*))
4779 DebuggerTlsData *tls;
4780 MonoContext orig_restore_ctx, ctx;
4782 tls = mono_native_tls_get_value (debugger_tls_id);
4783 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4784 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4785 memcpy (&tls->restore_ctx, &tls->handler_ctx, sizeof (MonoContext));
4789 /* This is called when resuming from a signal handler, so it shouldn't return */
4790 memcpy (&ctx, &tls->restore_ctx, sizeof (MonoContext));
4791 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4792 mono_restore_context (&ctx);
4793 g_assert_not_reached ();
4797 process_breakpoint (void)
4799 process_signal_event (process_breakpoint_inner);
4803 resume_from_signal_handler (void *sigctx, void *func)
4805 DebuggerTlsData *tls;
4808 /* Save the original context in TLS */
4809 // FIXME: This might not work on an altstack ?
4810 tls = mono_native_tls_get_value (debugger_tls_id);
4812 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer)GetCurrentThreadId ());
4815 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4816 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4817 // clob:c could be added to op_seq_point.
4819 mono_sigctx_to_monoctx (sigctx, &ctx);
4820 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4821 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4822 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4824 MONO_CONTEXT_SET_IP (&ctx, func);
4826 mono_monoctx_to_sigctx (&ctx, sigctx);
4828 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4829 mono_ppc_set_func_into_sigctx (sigctx, func);
4834 mono_debugger_agent_breakpoint_hit (void *sigctx)
4837 * We are called from a signal handler, and running code there causes all kinds of
4838 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4839 * So set up the signal context to return to the real breakpoint handler function.
4841 resume_from_signal_handler (sigctx, process_breakpoint);
4845 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4847 if (frame->managed) {
4848 *(MonoContext*)data = *ctx;
4857 * Called by System.Diagnostics.Debugger:Break ().
4860 mono_debugger_agent_user_break (void)
4862 if (agent_config.enabled) {
4867 /* Obtain a context */
4868 MONO_CONTEXT_SET_IP (&ctx, NULL);
4869 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4870 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4872 mono_loader_lock ();
4873 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4874 mono_loader_unlock ();
4876 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4883 ss_depth_to_string (StepDepth depth)
4886 case STEP_DEPTH_OVER:
4888 case STEP_DEPTH_OUT:
4890 case STEP_DEPTH_INTO:
4893 g_assert_not_reached ();
4899 process_single_step_inner (DebuggerTlsData *tls)
4904 int il_offset, suspend_policy;
4907 MonoContext *ctx = &tls->restore_ctx;
4910 MonoSeqPointInfo *info;
4912 ip = MONO_CONTEXT_GET_IP (ctx);
4914 /* Skip the instruction causing the single step */
4915 mono_arch_skip_single_step (ctx);
4917 if (suspend_count > 0) {
4918 process_suspend (tls, ctx);
4923 // FIXME: A suspend race
4926 if (mono_thread_internal_current () != ss_req->thread)
4929 if (log_level > 0) {
4930 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4932 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));
4935 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4937 method = jinfo_get_method (ji);
4940 if (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4945 * Stopping in memset makes half-initialized vtypes visible.
4946 * Stopping in memcpy makes half-copied vtypes visible.
4948 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
4952 * The ip points to the instruction causing the single step event, which is before
4953 * the offset recorded in the seq point map, so find the next seq point after ip.
4955 if (!find_next_seq_point_for_native_offset (domain, method, (guint8*)ip - (guint8*)ji->code_start, &info, &sp))
4958 il_offset = sp.il_offset;
4960 if (!ss_update (ss_req, ji, &sp, tls, ctx))
4963 /* Start single stepping again from the current sequence point */
4964 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE);
4966 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
4967 (method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4968 !strcmp (method->name, ".cctor"))
4971 // FIXME: Has to lock earlier
4973 reqs = g_ptr_array_new ();
4975 mono_loader_lock ();
4977 g_ptr_array_add (reqs, ss_req->req);
4979 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4981 g_ptr_array_free (reqs, TRUE);
4983 mono_loader_unlock ();
4985 process_event (EVENT_KIND_STEP, jinfo_get_method (ji), il_offset, ctx, events, suspend_policy);
4989 process_single_step (void)
4991 process_signal_event (process_single_step_inner);
4995 * mono_debugger_agent_single_step_event:
4997 * Called from a signal handler to handle a single step event.
5000 mono_debugger_agent_single_step_event (void *sigctx)
5002 /* Resume to process_single_step through the signal context */
5004 // FIXME: Since step out/over is implemented using step in, the step in case should
5005 // be as fast as possible. Move the relevant code from process_single_step_inner ()
5008 if (GetCurrentThreadId () == debugger_thread_id) {
5010 * This could happen despite our best effors when the runtime calls
5011 * assembly/type resolve hooks.
5012 * FIXME: Breakpoints too.
5016 mono_sigctx_to_monoctx (sigctx, &ctx);
5017 mono_arch_skip_single_step (&ctx);
5018 mono_monoctx_to_sigctx (&ctx, sigctx);
5022 resume_from_signal_handler (sigctx, process_single_step);
5026 debugger_agent_single_step_from_context (MonoContext *ctx)
5028 DebuggerTlsData *tls;
5029 MonoContext orig_restore_ctx;
5031 tls = mono_native_tls_get_value (debugger_tls_id);
5034 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
5035 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
5036 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
5038 process_single_step_inner (tls);
5040 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
5041 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
5045 debugger_agent_breakpoint_from_context (MonoContext *ctx)
5047 DebuggerTlsData *tls;
5048 MonoContext orig_restore_ctx;
5050 tls = mono_native_tls_get_value (debugger_tls_id);
5052 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
5053 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
5055 process_breakpoint_inner (tls);
5057 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
5058 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
5062 * start_single_stepping:
5064 * Turn on single stepping. Can be called multiple times, for example,
5065 * by a single step event request + a suspend.
5068 start_single_stepping (void)
5070 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5071 int val = InterlockedIncrement (&ss_count);
5074 mono_arch_start_single_stepping ();
5076 if (ss_req != NULL && ss_invoke_addr == NULL) {
5077 DebuggerTlsData *tls;
5079 mono_loader_lock ();
5081 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
5082 ss_invoke_addr = tls->invoke_addr;
5084 mono_loader_unlock ();
5087 g_assert_not_reached ();
5092 stop_single_stepping (void)
5094 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5095 int val = InterlockedDecrement (&ss_count);
5098 mono_arch_stop_single_stepping ();
5100 ss_invoke_addr = NULL;
5102 g_assert_not_reached ();
5109 * Stop the single stepping operation given by SS_REQ.
5112 ss_stop (SingleStepReq *ss_req)
5117 for (l = ss_req->bps; l; l = l->next) {
5118 clear_breakpoint (l->data);
5120 g_slist_free (ss_req->bps);
5124 if (ss_req->global) {
5125 stop_single_stepping ();
5126 ss_req->global = FALSE;
5133 * Start the single stepping operation given by SS_REQ from the sequence point SP.
5134 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
5135 * belong to the same thread as CTX.
5138 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint* sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
5140 int i, j, frame_index;
5145 gboolean enable_global = FALSE;
5147 /* Stop the previous operation */
5151 * Implement single stepping using breakpoints if possible.
5153 if (step_to_catch) {
5154 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
5155 ss_req->bps = g_slist_append (ss_req->bps, bp);
5159 if ((!sp || sp->next_len == 0 || ss_req->depth == STEP_DEPTH_OUT || ss_req->depth == STEP_DEPTH_OVER) && ctx) {
5160 /* Need parent frames */
5161 if (!tls->context.valid)
5162 mono_thread_state_init_from_monoctx (&tls->context, ctx);
5163 compute_frame_info (tls->thread, tls);
5167 * Find the first sequence point in the current or in a previous frame which
5168 * is not the last in its method.
5170 if (ss_req->depth == STEP_DEPTH_OUT) {
5171 /* Ignore seq points in current method */
5172 while (frame_index < tls->frame_count) {
5173 StackFrame *frame = tls->frames [frame_index];
5175 method = frame->method;
5176 found_sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5177 sp = (found_sp)? &local_sp : NULL;
5179 if (sp && sp->next_len != 0)
5182 // There could be method calls before the next seq point in the caller when using nested calls
5183 //enable_global = TRUE;
5185 if (sp && sp->next_len == 0) {
5187 while (frame_index < tls->frame_count) {
5188 StackFrame *frame = tls->frames [frame_index];
5190 method = frame->method;
5191 found_sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5192 sp = (found_sp)? &local_sp : NULL;
5193 if (sp && sp->next_len != 0)
5201 if (sp && sp->next_len > 0) {
5202 SeqPoint* next = g_new(SeqPoint, sp->next_len);
5204 seq_point_init_next (info, *sp, next);
5205 for (i = 0; i < sp->next_len; i++) {
5208 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
5209 ss_req->bps = g_slist_append (ss_req->bps, bp);
5214 if (ss_req->depth == STEP_DEPTH_OVER) {
5215 if (ss_req->nframes == 0)
5216 ss_req->nframes = tls->frame_count;
5217 /* Need to stop in catch clauses as well */
5218 for (i = 0; i < tls->frame_count; ++i) {
5219 StackFrame *frame = tls->frames [i];
5222 MonoJitInfo *jinfo = frame->ji;
5223 for (j = 0; j < jinfo->num_clauses; ++j) {
5224 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5226 found_sp = find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL, &local_sp);
5227 sp = (found_sp)? &local_sp : NULL;
5229 bp = set_breakpoint (frame->method, sp->il_offset, ss_req->req, NULL);
5230 ss_req->bps = g_slist_append (ss_req->bps, bp);
5238 if (ss_req->depth == STEP_DEPTH_INTO) {
5239 /* Enable global stepping so we stop at method entry too */
5240 enable_global = TRUE;
5244 * The ctx/frame info computed above will become invalid when we continue.
5246 tls->context.valid = FALSE;
5247 tls->async_state.valid = FALSE;
5248 invalidate_frames (tls);
5251 if (enable_global) {
5252 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
5253 ss_req->global = TRUE;
5254 start_single_stepping ();
5255 } else if (!ss_req->bps) {
5256 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
5257 ss_req->global = TRUE;
5258 start_single_stepping ();
5260 ss_req->global = FALSE;
5265 * Start single stepping of thread THREAD
5268 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
5270 DebuggerTlsData *tls;
5271 MonoSeqPointInfo *info = NULL;
5272 SeqPoint *sp = NULL;
5275 MonoMethod *method = NULL;
5276 MonoDebugMethodInfo *minfo;
5277 gboolean step_to_catch = FALSE;
5279 if (suspend_count == 0)
5280 return ERR_NOT_SUSPENDED;
5282 wait_for_suspend ();
5284 // FIXME: Multiple requests
5286 DEBUG (0, fprintf (log_file, "Received a single step request while the previous one was still active.\n"));
5287 return ERR_NOT_IMPLEMENTED;
5290 DEBUG (1, fprintf (log_file, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
5292 ss_req = g_new0 (SingleStepReq, 1);
5294 ss_req->thread = thread;
5295 ss_req->size = size;
5296 ss_req->depth = depth;
5299 mono_loader_lock ();
5300 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5301 mono_loader_unlock ();
5303 g_assert (tls->context.valid);
5304 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5306 if (tls->catch_state.valid) {
5308 StackFrameInfo frame;
5309 MonoContext new_ctx;
5310 MonoLMF *lmf = NULL;
5313 * We are stopped at a throw site. Stepping should go to the catch site.
5316 /* Find the the jit info for the catch context */
5317 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);
5319 g_assert (frame.type == FRAME_TYPE_MANAGED);
5322 * Find the seq point corresponding to the landing site ip, which is the first seq
5325 found_sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info, &local_sp);
5326 sp = (found_sp)? &local_sp : NULL;
5328 no_seq_points_found (frame.method);
5331 method = frame.method;
5333 step_to_catch = TRUE;
5334 /* This make sure the seq point is not skipped by process_single_step () */
5335 ss_req->last_sp = NULL;
5338 if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
5341 /* Compute the initial line info */
5342 compute_frame_info (thread, tls);
5344 if (tls->frame_count) {
5345 frame = tls->frames [0];
5347 ss_req->last_method = frame->method;
5348 ss_req->last_line = -1;
5350 minfo = mono_debug_lookup_method (frame->method);
5351 if (minfo && frame->il_offset != -1) {
5352 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
5355 ss_req->last_line = loc->row;
5362 if (!step_to_catch) {
5365 compute_frame_info (thread, tls);
5367 if (tls->frame_count) {
5368 frame = tls->frames [0];
5370 if (!method && frame->il_offset != -1) {
5371 /* FIXME: Sort the table and use a binary search */
5372 found_sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5373 sp = (found_sp)? &local_sp : NULL;
5375 no_seq_points_found (frame->method);
5377 method = frame->method;
5382 ss_start (ss_req, method, sp, info, &tls->context.ctx, tls, step_to_catch);
5388 ss_destroy (SingleStepReq *req)
5391 g_assert (ss_req == req);
5400 ss_clear_for_assembly (SingleStepReq *req, MonoAssembly *assembly)
5403 gboolean found = TRUE;
5407 for (l = ss_req->bps; l; l = l->next) {
5408 if (breakpoint_matches_assembly (l->data, assembly)) {
5409 clear_breakpoint (l->data);
5410 ss_req->bps = g_slist_delete_link (ss_req->bps, l);
5419 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5422 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5428 if (!agent_config.enabled)
5431 mono_loader_lock ();
5432 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5433 mono_loader_unlock ();
5436 ei.category = category ? mono_string_to_utf8 (category) : NULL;
5437 ei.message = message ? mono_string_to_utf8 (message) : NULL;
5439 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5441 g_free (ei.category);
5442 g_free (ei.message);
5446 mono_debugger_agent_debug_log_is_enabled (void)
5448 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5449 return agent_config.enabled;
5452 #if defined(PLATFORM_ANDROID) || defined(TARGET_ANDROID)
5454 mono_debugger_agent_unhandled_exception (MonoException *exc)
5463 memset (&ei, 0, sizeof (EventInfo));
5464 ei.exc = (MonoObject*)exc;
5466 mono_loader_lock ();
5467 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5468 mono_loader_unlock ();
5470 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5475 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5476 MonoContext *catch_ctx)
5478 int i, j, suspend_policy;
5480 MonoJitInfo *ji, *catch_ji;
5482 DebuggerTlsData *tls = NULL;
5484 if (thread_to_tls != NULL) {
5485 MonoInternalThread *thread = mono_thread_internal_current ();
5487 mono_loader_lock ();
5488 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5489 mono_loader_unlock ();
5491 if (tls && tls->abort_requested)
5493 if (tls && tls->disable_breakpoints)
5497 memset (&ei, 0, sizeof (EventInfo));
5499 /* Just-In-Time debugging */
5501 if (agent_config.onuncaught && !inited) {
5502 finish_agent_init (FALSE);
5505 * Send an unsolicited EXCEPTION event with a dummy request id.
5507 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5508 ei.exc = (MonoObject*)exc;
5509 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5512 } else if (agent_config.onthrow && !inited) {
5514 gboolean found = FALSE;
5516 for (l = agent_config.onthrow; l; l = l->next) {
5517 char *ex_type = l->data;
5518 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5520 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5527 finish_agent_init (FALSE);
5530 * Send an unsolicited EXCEPTION event with a dummy request id.
5532 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5533 ei.exc = (MonoObject*)exc;
5534 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5542 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5544 catch_ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5548 ei.exc = (MonoObject*)exc;
5549 ei.caught = catch_ctx != NULL;
5551 mono_loader_lock ();
5553 /* Treat exceptions which are caught in non-user code as unhandled */
5554 for (i = 0; i < event_requests->len; ++i) {
5555 EventRequest *req = g_ptr_array_index (event_requests, i);
5556 if (req->event_kind != EVENT_KIND_EXCEPTION)
5559 for (j = 0; j < req->nmodifiers; ++j) {
5560 Modifier *mod = &req->modifiers [j];
5562 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5564 gboolean found = FALSE;
5565 MonoAssembly **assemblies = mod->data.assemblies;
5568 for (k = 0; assemblies [k]; ++k)
5569 if (assemblies [k] == jinfo_get_method (catch_ji)->klass->image->assembly)
5578 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5579 mono_loader_unlock ();
5581 if (tls && ei.caught && catch_ctx) {
5582 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5583 tls->catch_state.ctx = *catch_ctx;
5584 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5585 tls->catch_state.valid = TRUE;
5588 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5591 tls->catch_state.valid = FALSE;
5595 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5597 DebuggerTlsData *tls;
5602 tls = mono_native_tls_get_value (debugger_tls_id);
5607 * We're about to invoke an exception filter during the first pass of exception handling.
5609 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5610 * 'orig_ctx' is the context where the exception has been thrown.
5613 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5615 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5616 * the call site (line 37) and then continue to Main(), but it would never
5617 * include the throw site (line 32).
5619 * Since exception filters are invoked during the first pass of exception handling,
5620 * the stack frames of the throw site are still intact, so we should include them
5623 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5625 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5626 * but report the location of the 'throw' to the user.
5630 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5634 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5636 DebuggerTlsData *tls;
5641 tls = mono_native_tls_get_value (debugger_tls_id);
5645 tls->filter_state.valid = FALSE;
5649 * buffer_add_value_full:
5651 * Add the encoding of the value at ADDR described by T to the buffer.
5652 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5656 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5657 gboolean as_vtype, GHashTable *parent_vtypes)
5660 gboolean boxed_vtype = FALSE;
5663 if (!(*(void**)addr)) {
5664 /* This can happen with compiler generated locals */
5665 //printf ("%s\n", mono_type_full_name (t));
5666 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5669 g_assert (*(void**)addr);
5670 addr = *(void**)addr;
5675 case MONO_TYPE_BOOLEAN:
5678 case MONO_TYPE_CHAR:
5698 case MONO_TYPE_VOID:
5699 buffer_add_byte (buf, t->type);
5701 case MONO_TYPE_BOOLEAN:
5704 buffer_add_byte (buf, t->type);
5705 buffer_add_int (buf, *(gint8*)addr);
5707 case MONO_TYPE_CHAR:
5710 buffer_add_byte (buf, t->type);
5711 buffer_add_int (buf, *(gint16*)addr);
5716 buffer_add_byte (buf, t->type);
5717 buffer_add_int (buf, *(gint32*)addr);
5722 buffer_add_byte (buf, t->type);
5723 buffer_add_long (buf, *(gint64*)addr);
5727 /* Treat it as a vtype */
5729 case MONO_TYPE_PTR: {
5730 gssize val = *(gssize*)addr;
5732 buffer_add_byte (buf, t->type);
5733 buffer_add_long (buf, val);
5737 case MONO_TYPE_STRING:
5738 case MONO_TYPE_SZARRAY:
5739 case MONO_TYPE_OBJECT:
5740 case MONO_TYPE_CLASS:
5741 case MONO_TYPE_ARRAY:
5742 obj = *(MonoObject**)addr;
5745 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5747 if (obj->vtable->klass->valuetype) {
5748 t = &obj->vtable->klass->byval_arg;
5749 addr = mono_object_unbox (obj);
5752 } else if (obj->vtable->klass->rank) {
5753 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5754 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5755 buffer_add_byte (buf, MONO_TYPE_CLASS);
5757 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5759 buffer_add_objid (buf, obj);
5763 case MONO_TYPE_VALUETYPE: {
5767 MonoClass *klass = mono_class_from_mono_type (t);
5772 * Handle boxed vtypes recursively referencing themselves using fields.
5775 parent_vtypes = g_hash_table_new (NULL, NULL);
5776 vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
5778 if (CHECK_PROTOCOL_VERSION (2, 33)) {
5779 buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
5780 buffer_add_int (buf, vtype_index - 1);
5782 /* The client can't handle PARENT_VTYPE */
5783 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5787 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
5791 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5792 buffer_add_byte (buf, klass->enumtype);
5793 buffer_add_typeid (buf, domain, klass);
5797 while ((f = mono_class_get_fields (klass, &iter))) {
5798 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5800 if (mono_field_is_deleted (f))
5804 buffer_add_int (buf, nfields);
5807 while ((f = mono_class_get_fields (klass, &iter))) {
5808 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5810 if (mono_field_is_deleted (f))
5812 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE, parent_vtypes);
5816 g_hash_table_remove (parent_vtypes, addr);
5817 if (g_hash_table_size (parent_vtypes) == 0) {
5818 g_hash_table_destroy (parent_vtypes);
5819 parent_vtypes = NULL;
5824 case MONO_TYPE_GENERICINST:
5825 if (mono_type_generic_inst_is_valuetype (t)) {
5837 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5839 buffer_add_value_full (buf, t, addr, domain, FALSE, NULL);
5843 obj_is_of_type (MonoObject *obj, MonoType *t)
5845 MonoClass *klass = obj->vtable->klass;
5846 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5847 if (mono_class_is_transparent_proxy (klass)) {
5848 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5849 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5859 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5862 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5868 gpointer iter = NULL;
5872 is_enum = decode_byte (buf, &buf, limit);
5873 /* Enums are sent as a normal vtype */
5875 return ERR_NOT_IMPLEMENTED;
5876 klass = decode_typeid (buf, &buf, limit, &d, &err);
5880 if (t && klass != mono_class_from_mono_type (t)) {
5881 char *name = mono_type_full_name (t);
5882 char *name2 = mono_type_full_name (&klass->byval_arg);
5883 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got %s.\n", (gpointer)GetCurrentThreadId (), name, name2));
5886 return ERR_INVALID_ARGUMENT;
5889 nfields = decode_int (buf, &buf, limit);
5890 while ((f = mono_class_get_fields (klass, &iter))) {
5891 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5893 if (mono_field_is_deleted (f))
5895 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5900 g_assert (nfields == 0);
5908 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5912 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5913 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5914 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5915 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5916 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
5917 char *name = mono_type_full_name (t);
5918 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5920 return ERR_INVALID_ARGUMENT;
5924 case MONO_TYPE_BOOLEAN:
5925 *(guint8*)addr = decode_int (buf, &buf, limit);
5927 case MONO_TYPE_CHAR:
5928 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5931 *(gint8*)addr = decode_int (buf, &buf, limit);
5934 *(guint8*)addr = decode_int (buf, &buf, limit);
5937 *(gint16*)addr = decode_int (buf, &buf, limit);
5940 *(guint16*)addr = decode_int (buf, &buf, limit);
5943 *(gint32*)addr = decode_int (buf, &buf, limit);
5946 *(guint32*)addr = decode_int (buf, &buf, limit);
5949 *(gint64*)addr = decode_long (buf, &buf, limit);
5952 *(guint64*)addr = decode_long (buf, &buf, limit);
5955 *(guint32*)addr = decode_int (buf, &buf, limit);
5958 *(guint64*)addr = decode_long (buf, &buf, limit);
5961 /* We send these as I8, so we get them back as such */
5962 g_assert (type == MONO_TYPE_I8);
5963 *(gssize*)addr = decode_long (buf, &buf, limit);
5965 case MONO_TYPE_GENERICINST:
5966 if (MONO_TYPE_ISSTRUCT (t)) {
5967 /* The client sends these as a valuetype */
5975 /* We send these as vtypes, so we get them back as such */
5976 g_assert (type == MONO_TYPE_VALUETYPE);
5979 case MONO_TYPE_VALUETYPE:
5980 err = decode_vtype (t, domain, addr,buf, &buf, limit);
5986 if (MONO_TYPE_IS_REFERENCE (t)) {
5987 if (type == MONO_TYPE_OBJECT) {
5988 int objid = decode_objid (buf, &buf, limit);
5992 err = get_object (objid, (MonoObject**)&obj);
5997 if (!obj_is_of_type (obj, t)) {
5998 DEBUG (1, fprintf (log_file, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name));
5999 return ERR_INVALID_ARGUMENT;
6002 if (obj && obj->vtable->domain != domain)
6003 return ERR_INVALID_ARGUMENT;
6005 mono_gc_wbarrier_generic_store (addr, obj);
6006 } else if (type == VALUE_TYPE_ID_NULL) {
6007 *(MonoObject**)addr = NULL;
6008 } else if (type == MONO_TYPE_VALUETYPE) {
6016 /* This can happen when round-tripping boxed vtypes */
6018 * Obtain vtype class.
6019 * Same as the beginning of the handle_vtype case above.
6022 is_enum = decode_byte (buf, &buf, limit);
6024 return ERR_NOT_IMPLEMENTED;
6025 klass = decode_typeid (buf, &buf, limit, &d, &err);
6029 /* Decode the vtype into a temporary buffer, then box it. */
6030 vtype_buf_size = mono_class_value_size (klass, NULL);
6031 vtype_buf = g_malloc0 (vtype_buf_size);
6032 g_assert (vtype_buf);
6035 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
6040 *(MonoObject**)addr = mono_value_box (d, klass, vtype_buf);
6043 char *name = mono_type_full_name (t);
6044 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
6046 return ERR_INVALID_ARGUMENT;
6060 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6063 int type = decode_byte (buf, &buf, limit);
6065 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
6066 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
6067 guint8 *nullable_buf;
6070 * First try decoding it as a Nullable`1
6072 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6077 * Then try decoding as a primitive value or null.
6079 if (targ->type == type) {
6080 nullable_buf = g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
6081 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
6083 g_free (nullable_buf);
6086 mono_nullable_init (addr, mono_value_box (domain, mono_class_from_mono_type (targ), nullable_buf), mono_class_from_mono_type (t));
6087 g_free (nullable_buf);
6090 } else if (type == VALUE_TYPE_ID_NULL) {
6091 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
6097 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6101 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
6105 guint8 *addr, *gaddr;
6108 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6109 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6112 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
6113 reg_val = mono_arch_context_get_int_reg (ctx, reg);
6115 buffer_add_value_full (buf, t, ®_val, domain, as_vtype, NULL);
6117 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6118 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6119 addr += (gint32)var->offset;
6121 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6123 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6125 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6128 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6129 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
6130 /* Same as regoffset, but with an indirection */
6131 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6132 addr += (gint32)var->offset;
6134 gaddr = *(gpointer*)addr;
6136 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL);
6138 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
6139 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
6140 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
6141 MonoGSharedVtMethodRuntimeInfo *info;
6147 g_assert (info_var);
6148 g_assert (locals_var);
6150 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6151 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6152 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6153 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6154 addr += (gint32)info_var->offset;
6155 info = *(gpointer*)addr;
6156 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6157 info = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6159 g_assert_not_reached ();
6163 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6164 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6165 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6166 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6167 addr += (gint32)locals_var->offset;
6168 locals = *(gpointer*)addr;
6169 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6170 locals = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6172 g_assert_not_reached ();
6176 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6178 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6183 g_assert_not_reached ();
6188 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
6192 guint8 *addr, *gaddr;
6194 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6195 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6197 if (MONO_TYPE_IS_REFERENCE (t))
6198 size = sizeof (gpointer);
6200 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6203 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6204 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6206 gboolean is_signed = FALSE;
6209 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6212 // FIXME: Write barriers
6213 mono_gc_memmove_atomic (addr, val, size);
6218 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6223 v = is_signed ? *(gint8*)val : *(guint8*)val;
6226 v = is_signed ? *(gint16*)val : *(guint16*)val;
6229 v = is_signed ? *(gint32*)val : *(guint32*)val;
6232 v = is_signed ? *(gint64*)val : *(guint64*)val;
6235 g_assert_not_reached ();
6238 /* Set value on the stack or in the return ctx */
6239 if (reg_locations [reg]) {
6240 /* Saved on the stack */
6241 DEBUG (1, fprintf (log_file, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v));
6242 *(reg_locations [reg]) = v;
6245 DEBUG (1, fprintf (log_file, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v));
6246 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6249 // FIXME: Move these to mono-context.h/c.
6250 mono_arch_context_set_int_reg (ctx, reg, v);
6252 // FIXME: Can't set registers, so we disable linears
6257 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6258 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6259 addr += (gint32)var->offset;
6261 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6264 addr = *(guint8**)addr;
6270 // FIXME: Write barriers
6271 mono_gc_memmove_atomic (addr, val, size);
6273 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6274 /* Same as regoffset, but with an indirection */
6275 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6276 addr += (gint32)var->offset;
6278 gaddr = *(gpointer*)addr;
6280 // FIXME: Write barriers
6281 mono_gc_memmove_atomic (gaddr, val, size);
6283 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6287 g_assert_not_reached ();
6292 clear_event_request (int req_id, int etype)
6296 mono_loader_lock ();
6297 for (i = 0; i < event_requests->len; ++i) {
6298 EventRequest *req = g_ptr_array_index (event_requests, i);
6300 if (req->id == req_id && req->event_kind == etype) {
6301 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6302 clear_breakpoint (req->info);
6303 if (req->event_kind == EVENT_KIND_STEP)
6304 ss_destroy (req->info);
6305 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6306 clear_breakpoint (req->info);
6307 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6308 clear_breakpoint (req->info);
6309 g_ptr_array_remove_index_fast (event_requests, i);
6314 mono_loader_unlock ();
6318 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
6322 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6323 m->kind = MOD_KIND_NONE;
6324 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6325 int count = 0, match_count = 0, pos;
6326 MonoAssembly **newassemblies;
6328 for (i = 0; m->data.assemblies [i]; ++i) {
6330 if (m->data.assemblies [i] == assembly)
6335 newassemblies = g_new0 (MonoAssembly*, count - match_count);
6338 for (i = 0; i < count; ++i)
6339 if (m->data.assemblies [i] != assembly)
6340 newassemblies [pos ++] = m->data.assemblies [i];
6341 g_assert (pos == count - match_count);
6342 g_free (m->data.assemblies);
6343 m->data.assemblies = newassemblies;
6349 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
6353 for (i = 0; i < req->nmodifiers; ++i) {
6354 Modifier *m = &req->modifiers [i];
6356 clear_assembly_from_modifier (req, m, assembly);
6361 * clear_event_requests_for_assembly:
6363 * Clear all events requests which reference ASSEMBLY.
6366 clear_event_requests_for_assembly (MonoAssembly *assembly)
6371 mono_loader_lock ();
6375 for (i = 0; i < event_requests->len; ++i) {
6376 EventRequest *req = g_ptr_array_index (event_requests, i);
6378 clear_assembly_from_modifiers (req, assembly);
6380 if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly (req->info, assembly)) {
6381 clear_event_request (req->id, req->event_kind);
6386 if (req->event_kind == EVENT_KIND_STEP)
6387 ss_clear_for_assembly (req->info, assembly);
6390 mono_loader_unlock ();
6394 * type_comes_from_assembly:
6396 * GHRFunc that returns TRUE if klass comes from assembly
6399 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6401 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6405 * clear_types_for_assembly:
6407 * Clears types from loaded_classes for a given assembly
6410 clear_types_for_assembly (MonoAssembly *assembly)
6412 MonoDomain *domain = mono_domain_get ();
6413 AgentDomainInfo *info = NULL;
6415 mono_loader_lock ();
6416 info = get_agent_domain_info (domain);
6417 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6418 mono_loader_unlock ();
6422 add_thread (gpointer key, gpointer value, gpointer user_data)
6424 MonoInternalThread *thread = value;
6425 Buffer *buf = user_data;
6427 buffer_add_objid (buf, (MonoObject*)thread);
6431 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6433 guint8 *end = invoke->endp;
6436 MonoMethodSignature *sig;
6439 MonoObject *this, *res, *exc;
6442 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6445 MonoStopwatch watch;
6447 if (invoke->method) {
6449 * Invoke this method directly, currently only Environment.Exit () is supported.
6452 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>"));
6453 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
6454 g_assert_not_reached ();
6457 m = decode_methodid (p, &p, end, &domain, &err);
6460 sig = mono_method_signature (m);
6462 if (m->klass->valuetype)
6463 this_buf = g_alloca (mono_class_instance_size (m->klass));
6465 this_buf = g_alloca (sizeof (MonoObject*));
6466 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6467 /* Should be null */
6468 int type = decode_byte (p, &p, end);
6469 if (type != VALUE_TYPE_ID_NULL) {
6470 DEBUG (1, fprintf (log_file, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer)GetCurrentThreadId ()));
6471 return ERR_INVALID_ARGUMENT;
6473 memset (this_buf, 0, mono_class_instance_size (m->klass));
6475 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6480 if (!m->klass->valuetype)
6481 this = *(MonoObject**)this_buf;
6485 if (MONO_CLASS_IS_INTERFACE (m->klass)) {
6487 DEBUG (1, fprintf (log_file, "[%p] Error: Interface method invoked without this argument.\n", (gpointer)GetCurrentThreadId ()));
6488 return ERR_INVALID_ARGUMENT;
6490 m = mono_object_get_virtual_method (this, m);
6491 } else if (invoke->flags & INVOKE_FLAG_VIRTUAL) {
6493 DEBUG (1, fprintf (log_file, "[%p] Error: invoke with INVOKE_FLAG_VIRTUAL flag set without this argument.\n", (gpointer)GetCurrentThreadId ()));
6494 return ERR_INVALID_ARGUMENT;
6496 m = mono_object_get_virtual_method (this, m);
6499 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>"));
6501 if (this && this->vtable->domain != domain)
6504 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
6505 if (!strcmp (m->name, ".ctor")) {
6506 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
6507 return ERR_INVALID_ARGUMENT;
6509 this = mono_object_new (domain, m->klass);
6511 return ERR_INVALID_ARGUMENT;
6515 if (this && !obj_is_of_type (this, &m->klass->byval_arg))
6516 return ERR_INVALID_ARGUMENT;
6518 nargs = decode_int (p, &p, end);
6519 if (nargs != sig->param_count)
6520 return ERR_INVALID_ARGUMENT;
6521 /* Use alloca to get gc tracking */
6522 arg_buf = g_alloca (nargs * sizeof (gpointer));
6523 memset (arg_buf, 0, nargs * sizeof (gpointer));
6524 args = g_alloca (nargs * sizeof (gpointer));
6525 for (i = 0; i < nargs; ++i) {
6526 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6527 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6530 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6533 if (sig->params [i]->byref) {
6534 arg_buf [i] = g_alloca (sizeof (mgreg_t));
6535 *(gpointer*)arg_buf [i] = args [i];
6536 args [i] = arg_buf [i];
6539 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6540 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6543 args [i] = arg_buf [i];
6550 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6551 tls->disable_breakpoints = TRUE;
6553 tls->disable_breakpoints = FALSE;
6556 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6558 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6559 if (invoke->has_ctx) {
6562 lmf_addr = mono_get_lmf_addr ();
6565 memset (&ext, 0, sizeof (ext));
6566 mono_arch_init_lmf_ext (&ext, *lmf_addr);
6568 ext.debugger_invoke = TRUE;
6569 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6571 mono_set_lmf ((MonoLMF*)&ext);
6575 mono_stopwatch_start (&watch);
6576 if (m->klass->valuetype)
6577 res = mono_runtime_invoke (m, this_buf, args, &exc);
6579 res = mono_runtime_invoke (m, this, args, &exc);
6580 mono_stopwatch_stop (&watch);
6581 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)));
6583 buffer_add_byte (buf, 0);
6584 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6586 gboolean out_this = FALSE;
6587 gboolean out_args = FALSE;
6589 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_THIS) && CHECK_PROTOCOL_VERSION (2, 35))
6591 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_ARGS) && CHECK_PROTOCOL_VERSION (2, 35))
6593 buffer_add_byte (buf, 1 + (out_this ? 2 : 0) + (out_args ? 4 : 0));
6594 if (sig->ret->type == MONO_TYPE_VOID) {
6595 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
6596 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
6599 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6600 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6601 buffer_add_value (buf, sig->ret, &res, domain);
6602 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6603 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6604 MonoClass *k = mono_class_from_mono_type (sig->ret);
6605 guint8 *nullable_buf = g_alloca (mono_class_value_size (k, NULL));
6607 g_assert (nullable_buf);
6608 mono_nullable_init (nullable_buf, res, k);
6609 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6612 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6618 /* Return the new value of the receiver after the call */
6619 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
6621 buffer_add_int (buf, nargs);
6622 for (i = 0; i < nargs; ++i) {
6623 if (MONO_TYPE_IS_REFERENCE (sig->params [i]))
6624 buffer_add_value (buf, sig->params [i], &args [i], domain);
6625 else if (sig->params [i]->byref)
6626 /* add_value () does an indirection */
6627 buffer_add_value (buf, sig->params [i], &arg_buf [i], domain);
6629 buffer_add_value (buf, sig->params [i], arg_buf [i], domain);
6634 tls->disable_breakpoints = FALSE;
6636 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6637 if (invoke->has_ctx)
6638 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
6642 // FIXME: byref arguments
6650 * Invoke the method given by tls->pending_invoke in the current thread.
6653 invoke_method (void)
6655 DebuggerTlsData *tls;
6660 MonoContext restore_ctx;
6663 tls = mono_native_tls_get_value (debugger_tls_id);
6667 * Store the `InvokeData *' in `tls->invoke' until we're done with
6668 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6671 mono_loader_lock ();
6673 invoke = tls->pending_invoke;
6675 tls->pending_invoke = NULL;
6677 invoke->last_invoke = tls->invoke;
6678 tls->invoke = invoke;
6680 mono_loader_unlock ();
6682 tls->frames_up_to_date = FALSE;
6688 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6689 buffer_init (&buf, 128);
6692 /* Fail the other invokes as well */
6694 err = do_invoke_method (tls, &buf, invoke, p, &p);
6697 /* Start suspending before sending the reply */
6698 if (mindex == invoke->nmethods - 1) {
6699 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6700 for (i = 0; i < invoke->suspend_count; ++i)
6705 send_reply_packet (id, err, &buf);
6710 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6712 if (invoke->has_ctx)
6713 save_thread_context (&restore_ctx);
6715 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6716 g_assert (tls->resume_count);
6717 tls->resume_count -= invoke->suspend_count;
6720 DEBUG (1, fprintf (log_file, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer)GetCurrentThreadId (), err, tls->resume_count));
6723 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6725 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
6726 * after the mono_runtime_invoke() already returned, but it doesn't matter
6727 * because we reset the abort here.
6730 mono_loader_lock ();
6732 if (tls->abort_requested)
6733 mono_thread_internal_reset_abort (tls->thread);
6735 tls->invoke = tls->invoke->last_invoke;
6736 tls->abort_requested = FALSE;
6738 mono_loader_unlock ();
6747 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6749 MonoThread *thread = value;
6750 DebuggerTlsData *tls;
6753 mono_loader_lock ();
6754 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6756 res = tls->really_suspended;
6757 mono_loader_unlock ();
6763 get_source_files_for_type (MonoClass *klass)
6765 gpointer iter = NULL;
6767 MonoDebugSourceInfo *sinfo;
6771 files = g_ptr_array_new ();
6773 while ((method = mono_class_get_methods (klass, &iter))) {
6774 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6775 GPtrArray *source_file_list;
6778 mono_debug_symfile_get_line_numbers_full (minfo, NULL, &source_file_list, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
6779 for (j = 0; j < source_file_list->len; ++j) {
6780 sinfo = g_ptr_array_index (source_file_list, j);
6781 for (i = 0; i < files->len; ++i)
6782 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6784 if (i == files->len)
6785 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6787 g_ptr_array_free (source_file_list, TRUE);
6795 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6798 case CMD_VM_VERSION: {
6799 char *build_info, *version;
6801 build_info = mono_get_runtime_build_info ();
6802 version = g_strdup_printf ("mono %s", build_info);
6804 buffer_add_string (buf, version); /* vm version */
6805 buffer_add_int (buf, MAJOR_VERSION);
6806 buffer_add_int (buf, MINOR_VERSION);
6807 g_free (build_info);
6811 case CMD_VM_SET_PROTOCOL_VERSION: {
6812 major_version = decode_int (p, &p, end);
6813 minor_version = decode_int (p, &p, end);
6814 protocol_version_set = TRUE;
6815 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
6818 case CMD_VM_ALL_THREADS: {
6820 mono_loader_lock ();
6821 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6822 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6823 mono_loader_unlock ();
6826 case CMD_VM_SUSPEND:
6828 wait_for_suspend ();
6831 if (suspend_count == 0)
6832 return ERR_NOT_SUSPENDED;
6834 clear_suspended_objs ();
6836 case CMD_VM_DISPOSE:
6837 /* Clear all event requests */
6838 mono_loader_lock ();
6839 while (event_requests->len > 0) {
6840 EventRequest *req = g_ptr_array_index (event_requests, 0);
6842 clear_event_request (req->id, req->event_kind);
6844 mono_loader_unlock ();
6846 while (suspend_count > 0)
6848 disconnected = TRUE;
6849 vm_start_event_sent = FALSE;
6852 MonoInternalThread *thread;
6853 DebuggerTlsData *tls;
6854 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6855 MonoClass *env_class;
6857 MonoMethod *exit_method = NULL;
6861 exit_code = decode_int (p, &p, end);
6863 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6865 /* Have to send a reply before exiting */
6866 send_reply_packet (id, 0, buf);
6868 /* Clear all event requests */
6869 mono_loader_lock ();
6870 while (event_requests->len > 0) {
6871 EventRequest *req = g_ptr_array_index (event_requests, 0);
6873 clear_event_request (req->id, req->event_kind);
6875 mono_loader_unlock ();
6878 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6879 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6880 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6881 * better than doing the shutdown ourselves, since it avoids various races.
6885 wait_for_suspend ();
6887 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6888 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
6890 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6893 mono_loader_lock ();
6894 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6895 mono_loader_unlock ();
6897 if (thread && exit_method) {
6898 mono_loader_lock ();
6899 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6900 mono_loader_unlock ();
6902 args = g_new0 (gpointer, 1);
6903 args [0] = g_malloc (sizeof (int));
6904 *(int*)(args [0]) = exit_code;
6906 tls->pending_invoke = g_new0 (InvokeData, 1);
6907 tls->pending_invoke->method = exit_method;
6908 tls->pending_invoke->args = args;
6909 tls->pending_invoke->nmethods = 1;
6911 while (suspend_count > 0)
6915 * No thread found, do it ourselves.
6916 * FIXME: This can race with normal shutdown etc.
6918 while (suspend_count > 0)
6921 if (!mono_runtime_try_shutdown ())
6924 mono_environment_exitcode_set (exit_code);
6926 /* Suspend all managed threads since the runtime is going away */
6927 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
6928 mono_thread_suspend_all_other_threads ();
6929 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
6930 mono_runtime_quit ();
6931 transport_close2 ();
6932 DEBUG(1, fprintf (log_file, "Exiting...\n"));
6938 case CMD_VM_INVOKE_METHOD:
6939 case CMD_VM_INVOKE_METHODS: {
6940 int objid = decode_objid (p, &p, end);
6942 DebuggerTlsData *tls;
6943 int i, count, err, flags, nmethods;
6945 err = get_object (objid, (MonoObject**)&thread);
6949 flags = decode_int (p, &p, end);
6951 if (command == CMD_VM_INVOKE_METHODS)
6952 nmethods = decode_int (p, &p, end);
6956 // Wait for suspending if it already started
6958 wait_for_suspend ();
6959 if (!is_suspended ())
6960 return ERR_NOT_SUSPENDED;
6962 mono_loader_lock ();
6963 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6964 mono_loader_unlock ();
6967 if (!tls->really_suspended)
6968 /* The thread is still running native code, can't do invokes */
6969 return ERR_NOT_SUSPENDED;
6972 * Store the invoke data into tls, the thread will execute it after it is
6975 if (tls->pending_invoke)
6976 return ERR_NOT_SUSPENDED;
6977 tls->pending_invoke = g_new0 (InvokeData, 1);
6978 tls->pending_invoke->id = id;
6979 tls->pending_invoke->flags = flags;
6980 tls->pending_invoke->p = g_malloc (end - p);
6981 memcpy (tls->pending_invoke->p, p, end - p);
6982 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
6983 tls->pending_invoke->suspend_count = suspend_count;
6984 tls->pending_invoke->nmethods = nmethods;
6986 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
6987 resume_thread (THREAD_TO_INTERNAL (thread));
6990 count = suspend_count;
6991 for (i = 0; i < count; ++i)
6996 case CMD_VM_ABORT_INVOKE: {
6997 int objid = decode_objid (p, &p, end);
6999 DebuggerTlsData *tls;
7002 err = get_object (objid, (MonoObject**)&thread);
7006 invoke_id = decode_int (p, &p, end);
7008 mono_loader_lock ();
7009 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7012 if (tls->abort_requested) {
7013 mono_loader_unlock ();
7018 * Check whether we're still inside the mono_runtime_invoke() and that it's
7019 * actually the correct invocation.
7021 * Careful, we do not stop the thread that's doing the invocation, so we can't
7022 * inspect its stack. However, invoke_method() also acquires the loader lock
7023 * when it's done, so we're safe here.
7027 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
7028 mono_loader_unlock ();
7029 return ERR_NO_INVOCATION;
7032 tls->abort_requested = TRUE;
7034 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
7035 mono_loader_unlock ();
7039 case CMD_VM_SET_KEEPALIVE: {
7040 int timeout = decode_int (p, &p, end);
7041 agent_config.keepalive = timeout;
7043 #ifndef DISABLE_SOCKET_TRANSPORT
7050 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
7051 GHashTableIter iter, kiter;
7056 char *fname, *basename;
7057 gboolean ignore_case;
7058 GSList *class_list, *l;
7059 GPtrArray *res_classes, *res_domains;
7061 fname = decode_string (p, &p, end);
7062 ignore_case = decode_byte (p, &p, end);
7064 basename = g_path_get_basename (fname);
7066 res_classes = g_ptr_array_new ();
7067 res_domains = g_ptr_array_new ();
7069 mono_loader_lock ();
7070 g_hash_table_iter_init (&iter, domains);
7071 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7072 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
7074 /* Update 'source_file_to_class' cache */
7075 g_hash_table_iter_init (&kiter, info->loaded_classes);
7076 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
7077 if (!g_hash_table_lookup (info->source_files, klass)) {
7078 files = get_source_files_for_type (klass);
7079 g_hash_table_insert (info->source_files, klass, files);
7081 for (i = 0; i < files->len; ++i) {
7082 char *s = g_ptr_array_index (files, i);
7083 char *s2 = g_path_get_basename (s);
7086 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
7088 class_list = g_slist_prepend (class_list, klass);
7089 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
7091 class_list = g_slist_prepend (class_list, klass);
7092 g_hash_table_insert (info->source_file_to_class, s2, class_list);
7095 /* The _ignorecase hash contains the lowercase path */
7096 s3 = strdup_tolower (s2);
7097 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
7099 class_list = g_slist_prepend (class_list, klass);
7100 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
7102 class_list = g_slist_prepend (class_list, klass);
7103 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
7115 s = strdup_tolower (basename);
7116 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
7119 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
7122 for (l = class_list; l; l = l->next) {
7125 g_ptr_array_add (res_classes, klass);
7126 g_ptr_array_add (res_domains, domain);
7129 mono_loader_unlock ();
7134 buffer_add_int (buf, res_classes->len);
7135 for (i = 0; i < res_classes->len; ++i)
7136 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
7137 g_ptr_array_free (res_classes, TRUE);
7138 g_ptr_array_free (res_domains, TRUE);
7141 case CMD_VM_GET_TYPES: {
7142 GHashTableIter iter;
7146 gboolean ignore_case;
7147 GPtrArray *res_classes, *res_domains;
7148 MonoTypeNameParse info;
7150 name = decode_string (p, &p, end);
7151 ignore_case = decode_byte (p, &p, end);
7153 if (!mono_reflection_parse_type (name, &info)) {
7155 mono_reflection_free_type_info (&info);
7156 return ERR_INVALID_ARGUMENT;
7159 res_classes = g_ptr_array_new ();
7160 res_domains = g_ptr_array_new ();
7162 mono_loader_lock ();
7163 g_hash_table_iter_init (&iter, domains);
7164 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7166 gboolean type_resolve;
7170 mono_domain_assemblies_lock (domain);
7171 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7175 type_resolve = TRUE;
7176 t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
7178 g_ptr_array_add (res_classes, mono_type_get_class (t));
7179 g_ptr_array_add (res_domains, domain);
7183 mono_domain_assemblies_unlock (domain);
7185 mono_loader_unlock ();
7188 mono_reflection_free_type_info (&info);
7190 buffer_add_int (buf, res_classes->len);
7191 for (i = 0; i < res_classes->len; ++i)
7192 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
7193 g_ptr_array_free (res_classes, TRUE);
7194 g_ptr_array_free (res_domains, TRUE);
7197 case CMD_VM_START_BUFFERING:
7198 case CMD_VM_STOP_BUFFERING:
7199 /* Handled in the main loop */
7202 return ERR_NOT_IMPLEMENTED;
7209 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7215 case CMD_EVENT_REQUEST_SET: {
7217 int i, event_kind, suspend_policy, nmodifiers, mod;
7220 MonoThread *step_thread;
7221 int size = 0, depth = 0, filter = 0, step_thread_id = 0;
7225 event_kind = decode_byte (p, &p, end);
7226 suspend_policy = decode_byte (p, &p, end);
7227 nmodifiers = decode_byte (p, &p, end);
7229 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7230 req->id = InterlockedIncrement (&event_request_id);
7231 req->event_kind = event_kind;
7232 req->suspend_policy = suspend_policy;
7233 req->nmodifiers = nmodifiers;
7236 for (i = 0; i < nmodifiers; ++i) {
7237 mod = decode_byte (p, &p, end);
7239 req->modifiers [i].kind = mod;
7240 if (mod == MOD_KIND_COUNT) {
7241 req->modifiers [i].data.count = decode_int (p, &p, end);
7242 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7243 method = decode_methodid (p, &p, end, &domain, &err);
7246 location = decode_long (p, &p, end);
7247 } else if (mod == MOD_KIND_STEP) {
7248 step_thread_id = decode_id (p, &p, end);
7249 size = decode_int (p, &p, end);
7250 depth = decode_int (p, &p, end);
7251 if (CHECK_PROTOCOL_VERSION (2, 16))
7252 filter = decode_int (p, &p, end);
7253 req->modifiers [i].data.filter = filter;
7254 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7255 /* Treat STEP_THOUGH the same as HIDDEN */
7256 req->modifiers [i].data.filter |= STEP_FILTER_DEBUGGER_STEP_THROUGH;
7257 } else if (mod == MOD_KIND_THREAD_ONLY) {
7258 int id = decode_id (p, &p, end);
7260 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7265 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7266 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7270 req->modifiers [i].caught = decode_byte (p, &p, end);
7271 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7272 if (CHECK_PROTOCOL_VERSION (2, 25))
7273 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7275 req->modifiers [i].subclasses = TRUE;
7276 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" : ""));
7278 req->modifiers [i].data.exc_class = exc_class;
7280 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
7282 return ERR_INVALID_ARGUMENT;
7285 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7286 int n = decode_int (p, &p, end);
7289 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
7290 for (j = 0; j < n; ++j) {
7291 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7293 g_free (req->modifiers [i].data.assemblies);
7297 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7298 int n = decode_int (p, &p, end);
7301 modifier = &req->modifiers [i];
7302 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7303 for (j = 0; j < n; ++j) {
7304 char *s = decode_string (p, &p, end);
7308 s2 = strdup_tolower (s);
7309 g_hash_table_insert (modifier->data.source_files, s2, s2);
7313 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7314 int n = decode_int (p, &p, end);
7317 modifier = &req->modifiers [i];
7318 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7319 for (j = 0; j < n; ++j) {
7320 char *s = decode_string (p, &p, end);
7323 g_hash_table_insert (modifier->data.type_names, s, s);
7327 return ERR_NOT_IMPLEMENTED;
7331 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7334 req->info = set_breakpoint (method, location, req, &error);
7335 if (!mono_error_ok (&error)) {
7337 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
7338 mono_error_cleanup (&error);
7339 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7341 } else if (req->event_kind == EVENT_KIND_STEP) {
7342 g_assert (step_thread_id);
7344 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7350 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
7355 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7356 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7357 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7358 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7359 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7360 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7362 if (req->nmodifiers) {
7364 return ERR_NOT_IMPLEMENTED;
7368 mono_loader_lock ();
7369 g_ptr_array_add (event_requests, req);
7371 if (agent_config.defer) {
7372 /* Transmit cached data to the client on receipt of the event request */
7373 switch (req->event_kind) {
7374 case EVENT_KIND_APPDOMAIN_CREATE:
7375 /* Emit load events for currently loaded domains */
7376 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7378 case EVENT_KIND_ASSEMBLY_LOAD:
7379 /* Emit load events for currently loaded assemblies */
7380 mono_assembly_foreach (emit_assembly_load, NULL);
7382 case EVENT_KIND_THREAD_START:
7383 /* Emit start events for currently started threads */
7384 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7386 case EVENT_KIND_TYPE_LOAD:
7387 /* Emit type load events for currently loaded types */
7388 mono_domain_foreach (send_types_for_domain, NULL);
7394 mono_loader_unlock ();
7396 buffer_add_int (buf, req->id);
7399 case CMD_EVENT_REQUEST_CLEAR: {
7400 int etype = decode_byte (p, &p, end);
7401 int req_id = decode_int (p, &p, end);
7403 // FIXME: Make a faster mapping from req_id to request
7404 mono_loader_lock ();
7405 clear_event_request (req_id, etype);
7406 mono_loader_unlock ();
7409 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7412 mono_loader_lock ();
7414 while (i < event_requests->len) {
7415 EventRequest *req = g_ptr_array_index (event_requests, i);
7417 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7418 clear_breakpoint (req->info);
7420 g_ptr_array_remove_index_fast (event_requests, i);
7426 mono_loader_unlock ();
7430 return ERR_NOT_IMPLEMENTED;
7437 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7443 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7444 buffer_add_domainid (buf, mono_get_root_domain ());
7447 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7448 domain = decode_domainid (p, &p, end, NULL, &err);
7451 buffer_add_string (buf, domain->friendly_name);
7454 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7459 domain = decode_domainid (p, &p, end, NULL, &err);
7462 mono_loader_lock ();
7464 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7467 buffer_add_int (buf, count);
7468 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7470 buffer_add_assemblyid (buf, domain, ass);
7472 mono_loader_unlock ();
7475 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7476 domain = decode_domainid (p, &p, end, NULL, &err);
7480 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7483 case CMD_APPDOMAIN_GET_CORLIB: {
7484 domain = decode_domainid (p, &p, end, NULL, &err);
7488 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7491 case CMD_APPDOMAIN_CREATE_STRING: {
7495 domain = decode_domainid (p, &p, end, NULL, &err);
7498 s = decode_string (p, &p, end);
7500 o = mono_string_new (domain, s);
7501 buffer_add_objid (buf, (MonoObject*)o);
7504 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7506 MonoDomain *domain2;
7509 domain = decode_domainid (p, &p, end, NULL, &err);
7512 klass = decode_typeid (p, &p, end, &domain2, &err);
7517 g_assert (domain == domain2);
7519 o = mono_object_new (domain, klass);
7521 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
7525 buffer_add_objid (buf, o);
7529 return ERR_NOT_IMPLEMENTED;
7536 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7542 ass = decode_assemblyid (p, &p, end, &domain, &err);
7547 case CMD_ASSEMBLY_GET_LOCATION: {
7548 buffer_add_string (buf, mono_image_get_filename (ass->image));
7551 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7555 if (ass->image->dynamic) {
7556 buffer_add_id (buf, 0);
7558 token = mono_image_get_entry_point (ass->image);
7560 buffer_add_id (buf, 0);
7562 m = mono_get_method (ass->image, token, NULL);
7563 buffer_add_methodid (buf, domain, m);
7568 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7569 buffer_add_moduleid (buf, domain, ass->image);
7572 case CMD_ASSEMBLY_GET_OBJECT: {
7573 MonoObject *o = (MonoObject*)mono_assembly_get_object (domain, ass);
7574 buffer_add_objid (buf, o);
7577 case CMD_ASSEMBLY_GET_TYPE: {
7578 char *s = decode_string (p, &p, end);
7579 gboolean ignorecase = decode_byte (p, &p, end);
7580 MonoTypeNameParse info;
7582 gboolean type_resolve, res;
7583 MonoDomain *d = mono_domain_get ();
7585 /* This is needed to be able to find referenced assemblies */
7586 res = mono_domain_set (domain, FALSE);
7589 if (!mono_reflection_parse_type (s, &info)) {
7592 if (info.assembly.name)
7594 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
7596 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
7597 mono_reflection_free_type_info (&info);
7600 mono_domain_set (d, TRUE);
7604 case CMD_ASSEMBLY_GET_NAME: {
7606 MonoAssembly *mass = ass;
7608 name = g_strdup_printf (
7609 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7611 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7612 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7613 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7614 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7616 buffer_add_string (buf, name);
7621 return ERR_NOT_IMPLEMENTED;
7628 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7634 case CMD_MODULE_GET_INFO: {
7635 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7638 basename = g_path_get_basename (image->name);
7639 buffer_add_string (buf, basename); // name
7640 buffer_add_string (buf, image->module_name); // scopename
7641 buffer_add_string (buf, image->name); // fqname
7642 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7643 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7648 return ERR_NOT_IMPLEMENTED;
7655 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7661 case CMD_FIELD_GET_INFO: {
7662 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
7664 buffer_add_string (buf, f->name);
7665 buffer_add_typeid (buf, domain, f->parent);
7666 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7667 buffer_add_int (buf, f->type->attrs);
7671 return ERR_NOT_IMPLEMENTED;
7678 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7680 if (val && val->vtable->klass == mono_defaults.monotype_class) {
7681 /* Special case these so the client doesn't have to handle Type objects */
7683 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7684 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7685 } else if (MONO_TYPE_IS_REFERENCE (t))
7686 buffer_add_value (buf, t, &val, domain);
7688 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7692 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7698 buffer_add_int (buf, 0);
7702 for (i = 0; i < cinfo->num_attrs; ++i) {
7703 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7706 buffer_add_int (buf, nattrs);
7708 for (i = 0; i < cinfo->num_attrs; ++i) {
7709 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7710 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7711 MonoArray *typed_args, *named_args;
7713 CattrNamedArg *arginfo = NULL;
7716 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
7717 if (!mono_error_ok (&error)) {
7718 DEBUG(2, fprintf (log_file, "[dbg] mono_reflection_create_custom_attr_data_args () failed with: '%s'\n", mono_error_get_message (&error)));
7719 mono_error_cleanup (&error);
7720 return ERR_LOADER_ERROR;
7723 buffer_add_methodid (buf, domain, attr->ctor);
7727 buffer_add_int (buf, mono_array_length (typed_args));
7728 for (j = 0; j < mono_array_length (typed_args); ++j) {
7729 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7731 t = mono_method_signature (attr->ctor)->params [j];
7733 buffer_add_cattr_arg (buf, t, domain, val);
7736 buffer_add_int (buf, 0);
7741 buffer_add_int (buf, mono_array_length (named_args));
7743 for (j = 0; j < mono_array_length (named_args); ++j) {
7744 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7746 if (arginfo [j].prop) {
7747 buffer_add_byte (buf, 0x54);
7748 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7749 } else if (arginfo [j].field) {
7750 buffer_add_byte (buf, 0x53);
7751 buffer_add_fieldid (buf, domain, arginfo [j].field);
7753 g_assert_not_reached ();
7756 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7759 buffer_add_int (buf, 0);
7768 /* FIXME: Code duplication with icall.c */
7770 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7775 mono_class_setup_interfaces (klass, error);
7776 if (!mono_error_ok (error))
7779 for (i = 0; i < klass->interface_count; i++) {
7780 ic = klass->interfaces [i];
7781 g_hash_table_insert (ifaces, ic, ic);
7783 collect_interfaces (ic, ifaces, error);
7784 if (!mono_error_ok (error))
7790 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7800 case CMD_TYPE_GET_INFO: {
7801 buffer_add_string (buf, klass->name_space);
7802 buffer_add_string (buf, klass->name);
7804 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7805 buffer_add_string (buf, name);
7807 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7808 buffer_add_moduleid (buf, domain, klass->image);
7809 buffer_add_typeid (buf, domain, klass->parent);
7810 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7811 buffer_add_typeid (buf, domain, klass->element_class);
7813 buffer_add_id (buf, 0);
7814 buffer_add_int (buf, klass->type_token);
7815 buffer_add_byte (buf, klass->rank);
7816 buffer_add_int (buf, klass->flags);
7818 type = &klass->byval_arg;
7819 // FIXME: Can't decide whenever a class represents a byref type
7822 if (type->type == MONO_TYPE_PTR)
7824 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7826 if (type->type == MONO_TYPE_VALUETYPE)
7828 if (klass->enumtype)
7830 if (klass->generic_container)
7832 if (klass->generic_container || klass->generic_class)
7834 buffer_add_byte (buf, b);
7837 while ((nested = mono_class_get_nested_types (klass, &iter)))
7839 buffer_add_int (buf, nnested);
7841 while ((nested = mono_class_get_nested_types (klass, &iter)))
7842 buffer_add_typeid (buf, domain, nested);
7843 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7844 if (klass->generic_container)
7845 buffer_add_typeid (buf, domain, klass);
7846 else if (klass->generic_class)
7847 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7849 buffer_add_id (buf, 0);
7851 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7854 if (klass->generic_class) {
7855 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7857 count = inst->type_argc;
7858 buffer_add_int (buf, count);
7859 for (i = 0; i < count; i++)
7860 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7861 } else if (klass->generic_container) {
7862 MonoGenericContainer *container = klass->generic_container;
7865 count = container->type_argc;
7866 buffer_add_int (buf, count);
7867 for (i = 0; i < count; i++) {
7868 pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
7869 buffer_add_typeid (buf, domain, pklass);
7872 buffer_add_int (buf, 0);
7877 case CMD_TYPE_GET_METHODS: {
7880 gpointer iter = NULL;
7883 mono_class_setup_methods (klass);
7885 nmethods = mono_class_num_methods (klass);
7887 buffer_add_int (buf, nmethods);
7889 while ((m = mono_class_get_methods (klass, &iter))) {
7890 buffer_add_methodid (buf, domain, m);
7893 g_assert (i == nmethods);
7896 case CMD_TYPE_GET_FIELDS: {
7899 gpointer iter = NULL;
7902 nfields = mono_class_num_fields (klass);
7904 buffer_add_int (buf, nfields);
7906 while ((f = mono_class_get_fields (klass, &iter))) {
7907 buffer_add_fieldid (buf, domain, f);
7908 buffer_add_string (buf, f->name);
7909 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7910 buffer_add_int (buf, f->type->attrs);
7913 g_assert (i == nfields);
7916 case CMD_TYPE_GET_PROPERTIES: {
7919 gpointer iter = NULL;
7922 nprops = mono_class_num_properties (klass);
7924 buffer_add_int (buf, nprops);
7926 while ((p = mono_class_get_properties (klass, &iter))) {
7927 buffer_add_propertyid (buf, domain, p);
7928 buffer_add_string (buf, p->name);
7929 buffer_add_methodid (buf, domain, p->get);
7930 buffer_add_methodid (buf, domain, p->set);
7931 buffer_add_int (buf, p->attrs);
7934 g_assert (i == nprops);
7937 case CMD_TYPE_GET_CATTRS: {
7938 MonoClass *attr_klass;
7939 MonoCustomAttrInfo *cinfo;
7941 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7942 /* attr_klass can be NULL */
7946 cinfo = mono_custom_attrs_from_class (klass);
7948 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7953 case CMD_TYPE_GET_FIELD_CATTRS: {
7954 MonoClass *attr_klass;
7955 MonoCustomAttrInfo *cinfo;
7956 MonoClassField *field;
7958 field = decode_fieldid (p, &p, end, NULL, &err);
7961 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7965 cinfo = mono_custom_attrs_from_field (klass, field);
7967 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7972 case CMD_TYPE_GET_PROPERTY_CATTRS: {
7973 MonoClass *attr_klass;
7974 MonoCustomAttrInfo *cinfo;
7977 prop = decode_propertyid (p, &p, end, NULL, &err);
7980 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7984 cinfo = mono_custom_attrs_from_property (klass, prop);
7986 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7991 case CMD_TYPE_GET_VALUES:
7992 case CMD_TYPE_GET_VALUES_2: {
7999 MonoThread *thread_obj;
8000 MonoInternalThread *thread = NULL;
8001 guint32 special_static_type;
8003 if (command == CMD_TYPE_GET_VALUES_2) {
8004 int objid = decode_objid (p, &p, end);
8007 err = get_object (objid, (MonoObject**)&thread_obj);
8011 thread = THREAD_TO_INTERNAL (thread_obj);
8014 len = decode_int (p, &p, end);
8015 for (i = 0; i < len; ++i) {
8016 f = decode_fieldid (p, &p, end, NULL, &err);
8020 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8021 return ERR_INVALID_FIELDID;
8022 special_static_type = mono_class_field_get_special_static_type (f);
8023 if (special_static_type != SPECIAL_STATIC_NONE) {
8024 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
8025 return ERR_INVALID_FIELDID;
8028 /* Check that the field belongs to the object */
8030 for (k = klass; k; k = k->parent) {
8031 if (k == f->parent) {
8037 return ERR_INVALID_FIELDID;
8039 vtable = mono_class_vtable (domain, f->parent);
8040 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8041 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
8042 buffer_add_value (buf, f->type, val, domain);
8047 case CMD_TYPE_SET_VALUES: {
8055 len = decode_int (p, &p, end);
8056 for (i = 0; i < len; ++i) {
8057 f = decode_fieldid (p, &p, end, NULL, &err);
8061 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8062 return ERR_INVALID_FIELDID;
8063 if (mono_class_field_is_special_static (f))
8064 return ERR_INVALID_FIELDID;
8066 /* Check that the field belongs to the object */
8068 for (k = klass; k; k = k->parent) {
8069 if (k == f->parent) {
8075 return ERR_INVALID_FIELDID;
8077 // FIXME: Check for literal/const
8079 vtable = mono_class_vtable (domain, f->parent);
8080 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8081 err = decode_value (f->type, domain, val, p, &p, end);
8086 if (MONO_TYPE_IS_REFERENCE (f->type))
8087 mono_field_static_set_value (vtable, f, *(gpointer*)val);
8089 mono_field_static_set_value (vtable, f, val);
8094 case CMD_TYPE_GET_OBJECT: {
8095 MonoObject *o = (MonoObject*)mono_type_get_object (domain, &klass->byval_arg);
8096 buffer_add_objid (buf, o);
8099 case CMD_TYPE_GET_SOURCE_FILES:
8100 case CMD_TYPE_GET_SOURCE_FILES_2: {
8101 char *source_file, *base;
8105 files = get_source_files_for_type (klass);
8107 buffer_add_int (buf, files->len);
8108 for (i = 0; i < files->len; ++i) {
8109 source_file = g_ptr_array_index (files, i);
8110 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8111 buffer_add_string (buf, source_file);
8113 base = g_path_get_basename (source_file);
8114 buffer_add_string (buf, base);
8117 g_free (source_file);
8119 g_ptr_array_free (files, TRUE);
8122 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8123 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8127 if (mono_class_is_assignable_from (klass, oklass))
8128 buffer_add_byte (buf, 1);
8130 buffer_add_byte (buf, 0);
8133 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8134 char *name = decode_string (p, &p, end);
8135 int i, flags = decode_int (p, &p, end);
8136 MonoException *ex = NULL;
8137 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
8140 return ERR_LOADER_ERROR;
8141 buffer_add_int (buf, array->len);
8142 for (i = 0; i < array->len; ++i) {
8143 MonoMethod *method = g_ptr_array_index (array, i);
8144 buffer_add_methodid (buf, domain, method);
8147 g_ptr_array_free (array, TRUE);
8151 case CMD_TYPE_GET_INTERFACES: {
8153 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8155 MonoClass *tclass, *iface;
8156 GHashTableIter iter;
8160 for (parent = tclass; parent; parent = parent->parent) {
8161 mono_class_setup_interfaces (parent, &error);
8162 if (!mono_error_ok (&error))
8163 return ERR_LOADER_ERROR;
8164 collect_interfaces (parent, iface_hash, &error);
8165 if (!mono_error_ok (&error))
8166 return ERR_LOADER_ERROR;
8169 buffer_add_int (buf, g_hash_table_size (iface_hash));
8171 g_hash_table_iter_init (&iter, iface_hash);
8172 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8173 buffer_add_typeid (buf, domain, iface);
8174 g_hash_table_destroy (iface_hash);
8177 case CMD_TYPE_GET_INTERFACE_MAP: {
8178 int tindex, ioffset;
8179 gboolean variance_used;
8181 int len, nmethods, i;
8185 len = decode_int (p, &p, end);
8186 mono_class_setup_vtable (klass);
8188 for (tindex = 0; tindex < len; ++tindex) {
8189 iclass = decode_typeid (p, &p, end, NULL, &err);
8193 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8195 return ERR_INVALID_ARGUMENT;
8197 nmethods = mono_class_num_methods (iclass);
8198 buffer_add_int (buf, nmethods);
8201 while ((method = mono_class_get_methods (iclass, &iter))) {
8202 buffer_add_methodid (buf, domain, method);
8204 for (i = 0; i < nmethods; ++i)
8205 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
8209 case CMD_TYPE_IS_INITIALIZED: {
8210 MonoVTable *vtable = mono_class_vtable (domain, klass);
8213 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8215 buffer_add_int (buf, 0);
8218 case CMD_TYPE_CREATE_INSTANCE: {
8221 obj = mono_object_new (domain, klass);
8222 buffer_add_objid (buf, obj);
8226 return ERR_NOT_IMPLEMENTED;
8233 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8236 MonoDomain *old_domain;
8240 klass = decode_typeid (p, &p, end, &domain, &err);
8244 old_domain = mono_domain_get ();
8246 mono_domain_set (domain, TRUE);
8248 err = type_commands_internal (command, klass, domain, p, end, buf);
8250 mono_domain_set (old_domain, TRUE);
8256 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8258 MonoMethodHeader *header;
8262 case CMD_METHOD_GET_NAME: {
8263 buffer_add_string (buf, method->name);
8266 case CMD_METHOD_GET_DECLARING_TYPE: {
8267 buffer_add_typeid (buf, domain, method->klass);
8270 case CMD_METHOD_GET_DEBUG_INFO: {
8271 MonoDebugMethodInfo *minfo;
8273 int i, j, n_il_offsets;
8276 int *column_numbers;
8277 int *end_line_numbers;
8278 int *end_column_numbers;
8280 GPtrArray *source_file_list;
8282 header = mono_method_get_header (method);
8284 buffer_add_int (buf, 0);
8285 buffer_add_string (buf, "");
8286 buffer_add_int (buf, 0);
8290 minfo = mono_debug_lookup_method (method);
8292 buffer_add_int (buf, header->code_size);
8293 buffer_add_string (buf, "");
8294 buffer_add_int (buf, 0);
8295 mono_metadata_free_mh (header);
8299 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);
8300 buffer_add_int (buf, header->code_size);
8301 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8302 buffer_add_int (buf, source_file_list->len);
8303 for (i = 0; i < source_file_list->len; ++i) {
8304 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
8305 buffer_add_string (buf, sinfo->source_file);
8306 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8307 for (j = 0; j < 16; ++j)
8308 buffer_add_byte (buf, sinfo->hash [j]);
8312 buffer_add_string (buf, source_file);
8314 buffer_add_int (buf, n_il_offsets);
8315 DEBUG (10, fprintf (log_file, "Line number table for method %s:\n", mono_method_full_name (method, TRUE)));
8316 for (i = 0; i < n_il_offsets; ++i) {
8317 const char *srcfile = "";
8319 if (source_files [i] != -1) {
8320 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
8321 srcfile = sinfo->source_file;
8323 DEBUG (10, fprintf (log_file, "IL%x -> %s:%d %d\n", il_offsets [i], srcfile, line_numbers [i], column_numbers ? column_numbers [i] : -1));
8324 buffer_add_int (buf, il_offsets [i]);
8325 buffer_add_int (buf, line_numbers [i]);
8326 if (CHECK_PROTOCOL_VERSION (2, 13))
8327 buffer_add_int (buf, source_files [i]);
8328 if (CHECK_PROTOCOL_VERSION (2, 19))
8329 buffer_add_int (buf, column_numbers ? column_numbers [i] : -1);
8330 if (CHECK_PROTOCOL_VERSION (2, 32)) {
8331 buffer_add_int (buf, end_line_numbers ? end_line_numbers [i] : -1);
8332 buffer_add_int (buf, end_column_numbers ? end_column_numbers [i] : -1);
8335 g_free (source_file);
8336 g_free (il_offsets);
8337 g_free (line_numbers);
8338 g_free (column_numbers);
8339 g_free (end_line_numbers);
8340 g_free (end_column_numbers);
8341 g_free (source_files);
8342 g_ptr_array_free (source_file_list, TRUE);
8343 mono_metadata_free_mh (header);
8346 case CMD_METHOD_GET_PARAM_INFO: {
8347 MonoMethodSignature *sig = mono_method_signature (method);
8351 /* FIXME: mono_class_from_mono_type () and byrefs */
8353 /* FIXME: Use a smaller encoding */
8354 buffer_add_int (buf, sig->call_convention);
8355 buffer_add_int (buf, sig->param_count);
8356 buffer_add_int (buf, sig->generic_param_count);
8357 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
8358 for (i = 0; i < sig->param_count; ++i) {
8360 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
8363 /* Emit parameter names */
8364 names = g_new (char *, sig->param_count);
8365 mono_method_get_param_names (method, (const char **) names);
8366 for (i = 0; i < sig->param_count; ++i)
8367 buffer_add_string (buf, names [i]);
8372 case CMD_METHOD_GET_LOCALS_INFO: {
8373 int i, j, num_locals;
8374 MonoDebugLocalsInfo *locals;
8376 header = mono_method_get_header (method);
8378 return ERR_INVALID_ARGUMENT;
8380 buffer_add_int (buf, header->num_locals);
8383 for (i = 0; i < header->num_locals; ++i)
8384 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
8387 locals = mono_debug_lookup_locals (method);
8389 num_locals = locals->num_locals;
8392 for (i = 0; i < header->num_locals; ++i) {
8393 for (j = 0; j < num_locals; ++j)
8394 if (locals->locals [j].index == i)
8397 buffer_add_string (buf, locals->locals [j].name);
8399 buffer_add_string (buf, "");
8403 for (i = 0; i < header->num_locals; ++i) {
8404 for (j = 0; j < num_locals; ++j)
8405 if (locals->locals [j].index == i)
8407 if (j < num_locals && locals->locals [j].block) {
8408 buffer_add_int (buf, locals->locals [j].block->start_offset);
8409 buffer_add_int (buf, locals->locals [j].block->end_offset);
8411 buffer_add_int (buf, 0);
8412 buffer_add_int (buf, header->code_size);
8415 mono_metadata_free_mh (header);
8418 mono_debug_symfile_free_locals (locals);
8422 case CMD_METHOD_GET_INFO:
8423 buffer_add_int (buf, method->flags);
8424 buffer_add_int (buf, method->iflags);
8425 buffer_add_int (buf, method->token);
8426 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8428 if (method->is_generic)
8430 if (mono_method_signature (method)->generic_param_count)
8432 buffer_add_byte (buf, attrs);
8433 if (method->is_generic || method->is_inflated) {
8436 if (method->is_generic) {
8439 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8441 result = imethod->declaring;
8442 if (imethod->context.class_inst) {
8443 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8444 /*Generic methods gets the context of the GTD.*/
8445 if (mono_class_get_context (klass))
8446 result = mono_class_inflate_generic_method_full (result, klass, mono_class_get_context (klass));
8450 buffer_add_methodid (buf, domain, result);
8452 buffer_add_id (buf, 0);
8454 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8455 if (mono_method_signature (method)->generic_param_count) {
8458 if (method->is_inflated) {
8459 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
8461 count = inst->type_argc;
8462 buffer_add_int (buf, count);
8464 for (i = 0; i < count; i++)
8465 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8467 buffer_add_int (buf, 0);
8469 } else if (method->is_generic) {
8470 MonoGenericContainer *container = mono_method_get_generic_container (method);
8472 count = mono_method_signature (method)->generic_param_count;
8473 buffer_add_int (buf, count);
8474 for (i = 0; i < count; i++) {
8475 MonoGenericParam *param = mono_generic_container_get_param (container, i);
8476 MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
8477 buffer_add_typeid (buf, domain, pklass);
8480 buffer_add_int (buf, 0);
8483 buffer_add_int (buf, 0);
8488 case CMD_METHOD_GET_BODY: {
8491 header = mono_method_get_header (method);
8493 buffer_add_int (buf, 0);
8495 if (CHECK_PROTOCOL_VERSION (2, 18))
8496 buffer_add_int (buf, 0);
8498 buffer_add_int (buf, header->code_size);
8499 for (i = 0; i < header->code_size; ++i)
8500 buffer_add_byte (buf, header->code [i]);
8502 if (CHECK_PROTOCOL_VERSION (2, 18)) {
8503 buffer_add_int (buf, header->num_clauses);
8504 for (i = 0; i < header->num_clauses; ++i) {
8505 MonoExceptionClause *clause = &header->clauses [i];
8507 buffer_add_int (buf, clause->flags);
8508 buffer_add_int (buf, clause->try_offset);
8509 buffer_add_int (buf, clause->try_len);
8510 buffer_add_int (buf, clause->handler_offset);
8511 buffer_add_int (buf, clause->handler_len);
8512 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
8513 buffer_add_typeid (buf, domain, clause->data.catch_class);
8514 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8515 buffer_add_int (buf, clause->data.filter_offset);
8519 mono_metadata_free_mh (header);
8524 case CMD_METHOD_RESOLVE_TOKEN: {
8525 guint32 token = decode_int (p, &p, end);
8528 switch (mono_metadata_token_code (token)) {
8529 case MONO_TOKEN_STRING: {
8533 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
8536 s2 = mono_string_to_utf8 (s);
8538 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8539 buffer_add_string (buf, s2);
8545 MonoClass *handle_class;
8547 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8548 val = mono_method_get_wrapper_data (method, token);
8549 handle_class = mono_method_get_wrapper_data (method, token + 1);
8551 if (handle_class == NULL) {
8552 // Can't figure out the token type
8553 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8557 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
8561 if (handle_class == mono_defaults.typehandle_class) {
8562 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8563 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8564 buffer_add_typeid (buf, domain, (MonoClass *) val);
8566 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
8567 } else if (handle_class == mono_defaults.fieldhandle_class) {
8568 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8569 buffer_add_fieldid (buf, domain, val);
8570 } else if (handle_class == mono_defaults.methodhandle_class) {
8571 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8572 buffer_add_methodid (buf, domain, val);
8573 } else if (handle_class == mono_defaults.string_class) {
8576 s = mono_string_to_utf8 (val);
8577 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8578 buffer_add_string (buf, s);
8581 g_assert_not_reached ();
8588 case CMD_METHOD_GET_CATTRS: {
8589 MonoClass *attr_klass;
8590 MonoCustomAttrInfo *cinfo;
8592 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8593 /* attr_klass can be NULL */
8597 cinfo = mono_custom_attrs_from_method (method);
8599 err = buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
8604 case CMD_METHOD_MAKE_GENERIC_METHOD: {
8605 MonoType **type_argv;
8609 MonoGenericInst *ginst;
8610 MonoGenericContext tmp_context;
8611 MonoMethod *inflated;
8613 type_argc = decode_int (p, &p, end);
8614 type_argv = g_new0 (MonoType*, type_argc);
8615 for (i = 0; i < type_argc; ++i) {
8616 klass = decode_typeid (p, &p, end, &d, &err);
8623 return ERR_INVALID_ARGUMENT;
8625 type_argv [i] = &klass->byval_arg;
8627 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
8629 tmp_context.class_inst = method->klass->generic_class ? method->klass->generic_class->context.class_inst : NULL;
8630 tmp_context.method_inst = ginst;
8632 inflated = mono_class_inflate_generic_method (method, &tmp_context);
8633 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
8634 return ERR_INVALID_ARGUMENT;
8635 buffer_add_methodid (buf, domain, inflated);
8639 return ERR_NOT_IMPLEMENTED;
8646 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8649 MonoDomain *old_domain;
8653 method = decode_methodid (p, &p, end, &domain, &err);
8657 old_domain = mono_domain_get ();
8659 mono_domain_set (domain, TRUE);
8661 err = method_commands_internal (command, method, domain, p, end, buf);
8663 mono_domain_set (old_domain, TRUE);
8669 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8671 int objid = decode_objid (p, &p, end);
8673 MonoThread *thread_obj;
8674 MonoInternalThread *thread;
8676 err = get_object (objid, (MonoObject**)&thread_obj);
8680 thread = THREAD_TO_INTERNAL (thread_obj);
8683 case CMD_THREAD_GET_NAME: {
8685 gunichar2 *s = mono_thread_get_name (thread, &name_len);
8688 buffer_add_int (buf, 0);
8693 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
8695 buffer_add_int (buf, len);
8696 buffer_add_data (buf, (guint8*)name, len);
8701 case CMD_THREAD_GET_FRAME_INFO: {
8702 DebuggerTlsData *tls;
8703 int i, start_frame, length;
8705 // Wait for suspending if it already started
8706 // FIXME: Races with suspend_count
8707 while (!is_suspended ()) {
8709 wait_for_suspend ();
8713 wait_for_suspend ();
8714 if (!is_suspended ())
8715 return ERR_NOT_SUSPENDED;
8718 start_frame = decode_int (p, &p, end);
8719 length = decode_int (p, &p, end);
8721 if (start_frame != 0 || length != -1)
8722 return ERR_NOT_IMPLEMENTED;
8724 mono_loader_lock ();
8725 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8726 mono_loader_unlock ();
8729 compute_frame_info (thread, tls);
8731 buffer_add_int (buf, tls->frame_count);
8732 for (i = 0; i < tls->frame_count; ++i) {
8733 buffer_add_int (buf, tls->frames [i]->id);
8734 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
8735 buffer_add_int (buf, tls->frames [i]->il_offset);
8737 * Instead of passing the frame type directly to the client, we associate
8738 * it with the previous frame using a set of flags. This avoids lots of
8739 * conditional code in the client, since a frame whose type isn't
8740 * FRAME_TYPE_MANAGED has no method, location, etc.
8742 buffer_add_byte (buf, tls->frames [i]->flags);
8747 case CMD_THREAD_GET_STATE:
8748 buffer_add_int (buf, thread->state);
8750 case CMD_THREAD_GET_INFO:
8751 buffer_add_byte (buf, thread->threadpool_thread);
8753 case CMD_THREAD_GET_ID:
8754 buffer_add_long (buf, (guint64)(gsize)thread);
8756 case CMD_THREAD_GET_TID:
8757 buffer_add_long (buf, (guint64)thread->tid);
8759 case CMD_THREAD_SET_IP: {
8760 DebuggerTlsData *tls;
8763 MonoSeqPointInfo *seq_points;
8768 method = decode_methodid (p, &p, end, &domain, &err);
8771 il_offset = decode_long (p, &p, end);
8773 while (!is_suspended ()) {
8775 wait_for_suspend ();
8778 mono_loader_lock ();
8779 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8780 mono_loader_unlock ();
8783 compute_frame_info (thread, tls);
8784 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
8785 return ERR_INVALID_ARGUMENT;
8787 found_sp = find_seq_point (domain, method, il_offset, &seq_points, &sp);
8789 g_assert (seq_points);
8792 return ERR_INVALID_ARGUMENT;
8794 // FIXME: Check that the ip change is safe
8796 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));
8797 MONO_CONTEXT_SET_IP (&tls->restore_ctx, (guint8*)tls->frames [0]->ji->code_start + sp.native_offset);
8801 return ERR_NOT_IMPLEMENTED;
8808 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8812 MonoThread *thread_obj;
8813 MonoInternalThread *thread;
8814 int pos, i, len, frame_idx;
8815 DebuggerTlsData *tls;
8817 MonoDebugMethodJitInfo *jit;
8818 MonoDebugVarInfo *var;
8819 MonoMethodSignature *sig;
8821 MonoMethodHeader *header;
8823 objid = decode_objid (p, &p, end);
8824 err = get_object (objid, (MonoObject**)&thread_obj);
8828 thread = THREAD_TO_INTERNAL (thread_obj);
8830 id = decode_id (p, &p, end);
8832 mono_loader_lock ();
8833 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8834 mono_loader_unlock ();
8837 for (i = 0; i < tls->frame_count; ++i) {
8838 if (tls->frames [i]->id == id)
8841 if (i == tls->frame_count)
8842 return ERR_INVALID_FRAMEID;
8845 frame = tls->frames [frame_idx];
8847 if (!frame->has_ctx)
8848 return ERR_ABSENT_INFORMATION;
8851 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
8852 if (!frame->jit && frame->api_method->is_inflated)
8853 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
8857 /* This could happen for aot images with no jit debug info */
8858 s = mono_method_full_name (frame->api_method, TRUE);
8859 DEBUG (1, fprintf (log_file, "[dbg] No debug information found for '%s'.\n", s));
8861 return ERR_ABSENT_INFORMATION;
8866 sig = mono_method_signature (frame->actual_method);
8868 if (!get_seq_points (frame->domain, frame->actual_method))
8870 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
8872 return ERR_ABSENT_INFORMATION;
8875 case CMD_STACK_FRAME_GET_VALUES: {
8876 len = decode_int (p, &p, end);
8877 header = mono_method_get_header (frame->actual_method);
8879 for (i = 0; i < len; ++i) {
8880 pos = decode_int (p, &p, end);
8885 g_assert (pos >= 0 && pos < jit->num_params);
8887 var = &jit->params [pos];
8889 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
8891 g_assert (pos >= 0 && pos < jit->num_locals);
8893 var = &jit->locals [pos];
8895 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
8898 mono_metadata_free_mh (header);
8901 case CMD_STACK_FRAME_GET_THIS: {
8902 if (frame->api_method->klass->valuetype) {
8903 if (!sig->hasthis) {
8904 MonoObject *p = NULL;
8905 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
8907 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8910 if (!sig->hasthis) {
8911 MonoObject *p = NULL;
8912 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
8914 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8919 case CMD_STACK_FRAME_SET_VALUES: {
8922 MonoDebugVarInfo *var;
8924 len = decode_int (p, &p, end);
8925 header = mono_method_get_header (frame->actual_method);
8927 for (i = 0; i < len; ++i) {
8928 pos = decode_int (p, &p, end);
8933 g_assert (pos >= 0 && pos < jit->num_params);
8935 t = sig->params [pos];
8936 var = &jit->params [pos];
8938 g_assert (pos >= 0 && pos < jit->num_locals);
8940 t = header->locals [pos];
8941 var = &jit->locals [pos];
8944 if (MONO_TYPE_IS_REFERENCE (t))
8945 val_buf = g_alloca (sizeof (MonoObject*));
8947 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
8948 err = decode_value (t, frame->domain, val_buf, p, &p, end);
8952 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_ctx);
8954 mono_metadata_free_mh (header);
8958 return ERR_NOT_IMPLEMENTED;
8965 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8968 int objid, err, index, len, i, esize;
8971 objid = decode_objid (p, &p, end);
8972 err = get_object (objid, (MonoObject**)&arr);
8977 case CMD_ARRAY_REF_GET_LENGTH:
8978 buffer_add_int (buf, arr->obj.vtable->klass->rank);
8980 buffer_add_int (buf, arr->max_length);
8981 buffer_add_int (buf, 0);
8983 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
8984 buffer_add_int (buf, arr->bounds [i].length);
8985 buffer_add_int (buf, arr->bounds [i].lower_bound);
8989 case CMD_ARRAY_REF_GET_VALUES:
8990 index = decode_int (p, &p, end);
8991 len = decode_int (p, &p, end);
8993 g_assert (index >= 0 && len >= 0);
8994 // Reordered to avoid integer overflow
8995 g_assert (!(index > arr->max_length - len));
8997 esize = mono_array_element_size (arr->obj.vtable->klass);
8998 for (i = index; i < index + len; ++i) {
8999 elem = (gpointer*)((char*)arr->vector + (i * esize));
9000 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
9003 case CMD_ARRAY_REF_SET_VALUES:
9004 index = decode_int (p, &p, end);
9005 len = decode_int (p, &p, end);
9007 g_assert (index >= 0 && len >= 0);
9008 // Reordered to avoid integer overflow
9009 g_assert (!(index > arr->max_length - len));
9011 esize = mono_array_element_size (arr->obj.vtable->klass);
9012 for (i = index; i < index + len; ++i) {
9013 elem = (gpointer*)((char*)arr->vector + (i * esize));
9015 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
9019 return ERR_NOT_IMPLEMENTED;
9026 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9031 int i, index, length;
9034 objid = decode_objid (p, &p, end);
9035 err = get_object (objid, (MonoObject**)&str);
9040 case CMD_STRING_REF_GET_VALUE:
9041 s = mono_string_to_utf8 (str);
9042 buffer_add_string (buf, s);
9045 case CMD_STRING_REF_GET_LENGTH:
9046 buffer_add_long (buf, mono_string_length (str));
9048 case CMD_STRING_REF_GET_CHARS:
9049 index = decode_long (p, &p, end);
9050 length = decode_long (p, &p, end);
9051 if (index > mono_string_length (str) - length)
9052 return ERR_INVALID_ARGUMENT;
9053 c = mono_string_chars (str) + index;
9054 for (i = 0; i < length; ++i)
9055 buffer_add_short (buf, c [i]);
9058 return ERR_NOT_IMPLEMENTED;
9065 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9074 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9075 objid = decode_objid (p, &p, end);
9076 err = get_object (objid, &obj);
9078 buffer_add_int (buf, 1);
9080 buffer_add_int (buf, 0);
9084 objid = decode_objid (p, &p, end);
9085 err = get_object (objid, &obj);
9090 case CMD_OBJECT_REF_GET_TYPE:
9091 /* This handles transparent proxies too */
9092 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9094 case CMD_OBJECT_REF_GET_VALUES:
9095 len = decode_int (p, &p, end);
9097 for (i = 0; i < len; ++i) {
9098 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9102 /* Check that the field belongs to the object */
9104 for (k = obj->vtable->klass; k; k = k->parent) {
9105 if (k == f->parent) {
9111 return ERR_INVALID_FIELDID;
9113 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9117 if (mono_class_field_is_special_static (f))
9118 return ERR_INVALID_FIELDID;
9120 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9121 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9122 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9123 mono_field_static_get_value (vtable, f, val);
9124 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9127 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
9131 case CMD_OBJECT_REF_SET_VALUES:
9132 len = decode_int (p, &p, end);
9134 for (i = 0; i < len; ++i) {
9135 f = decode_fieldid (p, &p, end, NULL, &err);
9139 /* Check that the field belongs to the object */
9141 for (k = obj->vtable->klass; k; k = k->parent) {
9142 if (k == f->parent) {
9148 return ERR_INVALID_FIELDID;
9150 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9154 if (mono_class_field_is_special_static (f))
9155 return ERR_INVALID_FIELDID;
9157 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9158 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9160 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9161 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
9166 mono_field_static_set_value (vtable, f, val);
9169 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
9175 case CMD_OBJECT_REF_GET_ADDRESS:
9176 buffer_add_long (buf, (gssize)obj);
9178 case CMD_OBJECT_REF_GET_DOMAIN:
9179 buffer_add_domainid (buf, obj->vtable->domain);
9181 case CMD_OBJECT_REF_GET_INFO:
9182 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9183 buffer_add_domainid (buf, obj->vtable->domain);
9186 return ERR_NOT_IMPLEMENTED;
9193 command_set_to_string (CommandSet command_set)
9195 switch (command_set) {
9198 case CMD_SET_OBJECT_REF:
9199 return "OBJECT_REF";
9200 case CMD_SET_STRING_REF:
9201 return "STRING_REF";
9202 case CMD_SET_THREAD:
9204 case CMD_SET_ARRAY_REF:
9206 case CMD_SET_EVENT_REQUEST:
9207 return "EVENT_REQUEST";
9208 case CMD_SET_STACK_FRAME:
9209 return "STACK_FRAME";
9210 case CMD_SET_APPDOMAIN:
9212 case CMD_SET_ASSEMBLY:
9214 case CMD_SET_METHOD:
9218 case CMD_SET_MODULE:
9229 static const char* vm_cmds_str [] = {
9237 "SET_PROTOCOL_VERSION",
9240 "GET_TYPES_FOR_SOURCE_FILE",
9245 static const char* thread_cmds_str[] = {
9255 static const char* event_cmds_str[] = {
9258 "REQUEST_CLEAR_ALL_BREAKPOINTS"
9261 static const char* appdomain_cmds_str[] = {
9263 "GET_FRIENDLY_NAME",
9265 "GET_ENTRY_ASSEMBLY",
9268 "CREATE_BOXED_VALUE"
9271 static const char* assembly_cmds_str[] = {
9274 "GET_MANIFEST_MODULE",
9280 static const char* module_cmds_str[] = {
9284 static const char* field_cmds_str[] = {
9288 static const char* method_cmds_str[] = {
9290 "GET_DECLARING_TYPE",
9298 "MAKE_GENERIC_METHOD"
9301 static const char* type_cmds_str[] = {
9309 "IS_ASSIGNABLE_FROM",
9313 "GET_PROPERTY_CATTRS",
9314 "GET_SOURCE_FILES_2",
9316 "GET_METHODS_BY_NAME_FLAGS",
9318 "GET_INTERFACE_MAP",
9322 static const char* stack_frame_cmds_str[] = {
9328 static const char* array_cmds_str[] = {
9334 static const char* string_cmds_str[] = {
9340 static const char* object_cmds_str[] = {
9351 cmd_to_string (CommandSet set, int command)
9359 cmds_len = G_N_ELEMENTS (vm_cmds_str);
9361 case CMD_SET_OBJECT_REF:
9362 cmds = object_cmds_str;
9363 cmds_len = G_N_ELEMENTS (object_cmds_str);
9365 case CMD_SET_STRING_REF:
9366 cmds = string_cmds_str;
9367 cmds_len = G_N_ELEMENTS (string_cmds_str);
9369 case CMD_SET_THREAD:
9370 cmds = thread_cmds_str;
9371 cmds_len = G_N_ELEMENTS (thread_cmds_str);
9373 case CMD_SET_ARRAY_REF:
9374 cmds = array_cmds_str;
9375 cmds_len = G_N_ELEMENTS (array_cmds_str);
9377 case CMD_SET_EVENT_REQUEST:
9378 cmds = event_cmds_str;
9379 cmds_len = G_N_ELEMENTS (event_cmds_str);
9381 case CMD_SET_STACK_FRAME:
9382 cmds = stack_frame_cmds_str;
9383 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
9385 case CMD_SET_APPDOMAIN:
9386 cmds = appdomain_cmds_str;
9387 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
9389 case CMD_SET_ASSEMBLY:
9390 cmds = assembly_cmds_str;
9391 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
9393 case CMD_SET_METHOD:
9394 cmds = method_cmds_str;
9395 cmds_len = G_N_ELEMENTS (method_cmds_str);
9398 cmds = type_cmds_str;
9399 cmds_len = G_N_ELEMENTS (type_cmds_str);
9401 case CMD_SET_MODULE:
9402 cmds = module_cmds_str;
9403 cmds_len = G_N_ELEMENTS (module_cmds_str);
9406 cmds = field_cmds_str;
9407 cmds_len = G_N_ELEMENTS (field_cmds_str);
9410 cmds = event_cmds_str;
9411 cmds_len = G_N_ELEMENTS (event_cmds_str);
9416 if (command > 0 && command <= cmds_len)
9417 return cmds [command - 1];
9423 wait_for_attach (void)
9425 #ifndef DISABLE_SOCKET_TRANSPORT
9426 if (listen_fd == -1) {
9427 DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
9431 /* Block and wait for client connection */
9432 conn_fd = socket_transport_accept (listen_fd);
9433 DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
9434 if (conn_fd == -1) {
9435 DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
9439 g_assert_not_reached ();
9443 disconnected = !transport_handshake ();
9445 DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
9455 * This thread handles communication with the debugger client using a JDWP
9458 static guint32 WINAPI
9459 debugger_thread (void *arg)
9461 int res, len, id, flags, command_set = 0, command = 0;
9462 guint8 header [HEADER_LENGTH];
9463 guint8 *data, *p, *end;
9467 gboolean attach_failed = FALSE;
9469 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
9471 debugger_thread_id = GetCurrentThreadId ();
9473 mono_jit_thread_attach (mono_get_root_domain ());
9475 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
9477 mono_set_is_debugger_attached (TRUE);
9479 if (agent_config.defer) {
9480 if (!wait_for_attach ()) {
9481 DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
9482 attach_failed = TRUE; // Don't abort process when we can't listen
9484 /* Send start event to client */
9485 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
9489 while (!attach_failed) {
9490 res = transport_recv (header, HEADER_LENGTH);
9492 /* This will break if the socket is closed during shutdown too */
9493 if (res != HEADER_LENGTH) {
9494 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH));
9499 end = header + HEADER_LENGTH;
9501 len = decode_int (p, &p, end);
9502 id = decode_int (p, &p, end);
9503 flags = decode_byte (p, &p, end);
9504 command_set = decode_byte (p, &p, end);
9505 command = decode_byte (p, &p, end);
9507 g_assert (flags == 0);
9510 const char *cmd_str;
9513 cmd_str = cmd_to_string (command_set, command);
9515 sprintf (cmd_num, "%d", command);
9519 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));
9522 data = g_malloc (len - HEADER_LENGTH);
9523 if (len - HEADER_LENGTH > 0)
9525 res = transport_recv (data, len - HEADER_LENGTH);
9526 if (res != len - HEADER_LENGTH) {
9527 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH));
9533 end = data + (len - HEADER_LENGTH);
9535 buffer_init (&buf, 128);
9540 /* Process the request */
9541 switch (command_set) {
9543 err = vm_commands (command, id, p, end, &buf);
9544 if (!err && command == CMD_VM_INVOKE_METHOD)
9545 /* Sent after the invoke is complete */
9548 case CMD_SET_EVENT_REQUEST:
9549 err = event_commands (command, p, end, &buf);
9551 case CMD_SET_APPDOMAIN:
9552 err = domain_commands (command, p, end, &buf);
9554 case CMD_SET_ASSEMBLY:
9555 err = assembly_commands (command, p, end, &buf);
9557 case CMD_SET_MODULE:
9558 err = module_commands (command, p, end, &buf);
9561 err = field_commands (command, p, end, &buf);
9564 err = type_commands (command, p, end, &buf);
9566 case CMD_SET_METHOD:
9567 err = method_commands (command, p, end, &buf);
9569 case CMD_SET_THREAD:
9570 err = thread_commands (command, p, end, &buf);
9572 case CMD_SET_STACK_FRAME:
9573 err = frame_commands (command, p, end, &buf);
9575 case CMD_SET_ARRAY_REF:
9576 err = array_commands (command, p, end, &buf);
9578 case CMD_SET_STRING_REF:
9579 err = string_commands (command, p, end, &buf);
9581 case CMD_SET_OBJECT_REF:
9582 err = object_commands (command, p, end, &buf);
9585 err = ERR_NOT_IMPLEMENTED;
9588 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
9589 buffer_replies = TRUE;
9593 if (buffer_replies) {
9594 buffer_reply_packet (id, err, &buf);
9596 send_reply_packet (id, err, &buf);
9597 //DEBUG (1, fprintf (log_file, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000));
9601 if (!err && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
9602 send_buffered_reply_packets ();
9603 buffer_replies = FALSE;
9609 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
9613 mono_set_is_debugger_attached (FALSE);
9615 mono_mutex_lock (&debugger_thread_exited_mutex);
9616 debugger_thread_exited = TRUE;
9617 mono_cond_signal (&debugger_thread_exited_cond);
9618 mono_mutex_unlock (&debugger_thread_exited_mutex);
9620 DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
9622 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
9623 DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
9624 start_debugger_thread ();
9630 #else /* DISABLE_DEBUGGER_AGENT */
9633 mono_debugger_agent_parse_options (char *options)
9635 g_error ("This runtime is configured with the debugger agent disabled.");
9639 mono_debugger_agent_init (void)
9644 mono_debugger_agent_breakpoint_hit (void *sigctx)
9649 mono_debugger_agent_single_step_event (void *sigctx)
9654 mono_debugger_agent_free_domain_info (MonoDomain *domain)
9659 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
9665 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
9666 MonoContext *catch_ctx)
9671 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9676 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9681 mono_debugger_agent_user_break (void)
9687 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
9692 mono_debugger_agent_debug_log_is_enabled (void)
9698 mono_debugger_agent_unhandled_exception (MonoException *exc)
9700 g_assert_not_reached ();