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"
89 On iOS we can't use System.Environment.Exit () as it will do the wrong
92 #if !defined (TARGET_IOS)
93 #define TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
97 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
98 #define DISABLE_DEBUGGER_AGENT 1
101 #ifdef DISABLE_SOFT_DEBUG
102 #define DISABLE_DEBUGGER_AGENT 1
105 #ifndef DISABLE_DEBUGGER_AGENT
107 #include <mono/utils/mono-mutex.h>
109 /* Definitions to make backporting to 2.6 easier */
110 //#define MonoInternalThread MonoThread
111 //#define mono_thread_internal_current mono_thread_current
112 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
135 guint32 il_offset, native_offset;
139 * If method is gshared, this is the actual instance, otherwise this is equal to
142 MonoMethod *actual_method;
144 * This is the method which is visible to debugger clients. Same as method,
145 * except for native-to-managed wrappers.
147 MonoMethod *api_method;
149 MonoDebugMethodJitInfo *jit;
152 mgreg_t *reg_locations [MONO_MAX_IREGS];
154 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
155 * the frame can become invalid.
160 typedef struct _InvokeData InvokeData;
168 /* This is the context which needs to be restored after the invoke */
172 * If this is set, invoke this method with the arguments given by ARGS.
176 guint32 suspend_count;
179 InvokeData *last_invoke;
183 MonoThreadUnwindState context;
185 /* This is computed on demand when it is requested using the wire protocol */
186 /* It is freed up when the thread is resumed */
190 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
193 gboolean frames_up_to_date;
195 * Points to data about a pending invoke which needs to be executed after the thread
198 InvokeData *pending_invoke;
200 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
205 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
206 * within a finite amount of time.
210 * Set to TRUE if this thread is suspended in suspend_current ().
212 gboolean really_suspended;
213 /* Used to pass the context to the breakpoint/single step handler */
214 MonoContext handler_ctx;
215 /* Whenever thread_stop () was called for this thread */
218 /* Number of thread interruptions not yet processed */
219 gint32 interrupt_count;
221 /* Whenever to disable breakpoints (used during invokes) */
222 gboolean disable_breakpoints;
225 * Number of times this thread has been resumed using resume_thread ().
227 guint32 resume_count;
229 MonoInternalThread *thread;
232 * Information about the frame which transitioned to native code for running
235 StackFrameInfo async_last_frame;
238 * The context where the stack walk can be started for running threads.
240 MonoThreadUnwindState async_state;
243 * The context used for filter clauses
245 MonoThreadUnwindState filter_state;
248 * The callee address of the last mono_runtime_invoke call
250 gpointer invoke_addr;
252 gboolean abort_requested;
255 * The current mono_runtime_invoke invocation.
260 * The context where single stepping should resume while the thread is suspended because
261 * of an EXCEPTION event.
263 MonoThreadUnwindState catch_state;
266 * The context which needs to be restored after handling a single step/breakpoint
267 * event. This is the same as the ctx at step/breakpoint site, but includes changes
268 * to caller saved registers done by set_var ().
270 MonoContext restore_ctx;
272 /* The currently unloading appdomain */
273 MonoDomain *domain_unloading;
278 void (*connect) (const char *address);
279 void (*close1) (void);
280 void (*close2) (void);
281 gboolean (*send) (void *buf, int len);
282 int (*recv) (void *buf, int len);
286 * Wire Protocol definitions
289 #define HEADER_LENGTH 11
291 #define MAJOR_VERSION 2
292 #define MINOR_VERSION 38
296 CMD_SET_OBJECT_REF = 9,
297 CMD_SET_STRING_REF = 10,
299 CMD_SET_ARRAY_REF = 13,
300 CMD_SET_EVENT_REQUEST = 15,
301 CMD_SET_STACK_FRAME = 16,
302 CMD_SET_APPDOMAIN = 20,
303 CMD_SET_ASSEMBLY = 21,
312 EVENT_KIND_VM_START = 0,
313 EVENT_KIND_VM_DEATH = 1,
314 EVENT_KIND_THREAD_START = 2,
315 EVENT_KIND_THREAD_DEATH = 3,
316 EVENT_KIND_APPDOMAIN_CREATE = 4,
317 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
318 EVENT_KIND_METHOD_ENTRY = 6,
319 EVENT_KIND_METHOD_EXIT = 7,
320 EVENT_KIND_ASSEMBLY_LOAD = 8,
321 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
322 EVENT_KIND_BREAKPOINT = 10,
323 EVENT_KIND_STEP = 11,
324 EVENT_KIND_TYPE_LOAD = 12,
325 EVENT_KIND_EXCEPTION = 13,
326 EVENT_KIND_KEEPALIVE = 14,
327 EVENT_KIND_USER_BREAK = 15,
328 EVENT_KIND_USER_LOG = 16
332 SUSPEND_POLICY_NONE = 0,
333 SUSPEND_POLICY_EVENT_THREAD = 1,
334 SUSPEND_POLICY_ALL = 2
339 ERR_INVALID_OBJECT = 20,
340 ERR_INVALID_FIELDID = 25,
341 ERR_INVALID_FRAMEID = 30,
342 ERR_NOT_IMPLEMENTED = 100,
343 ERR_NOT_SUSPENDED = 101,
344 ERR_INVALID_ARGUMENT = 102,
346 ERR_NO_INVOCATION = 104,
347 ERR_ABSENT_INFORMATION = 105,
348 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
349 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
354 MOD_KIND_THREAD_ONLY = 3,
355 MOD_KIND_LOCATION_ONLY = 7,
356 MOD_KIND_EXCEPTION_ONLY = 8,
358 MOD_KIND_ASSEMBLY_ONLY = 11,
359 MOD_KIND_SOURCE_FILE_ONLY = 12,
360 MOD_KIND_TYPE_NAME_ONLY = 13,
376 STEP_FILTER_NONE = 0,
377 STEP_FILTER_STATIC_CTOR = 1,
378 STEP_FILTER_DEBUGGER_HIDDEN = 2,
379 STEP_FILTER_DEBUGGER_STEP_THROUGH = 4,
380 STEP_FILTER_DEBUGGER_NON_USER_CODE = 8
384 TOKEN_TYPE_STRING = 0,
386 TOKEN_TYPE_FIELD = 2,
387 TOKEN_TYPE_METHOD = 3,
388 TOKEN_TYPE_UNKNOWN = 4
392 VALUE_TYPE_ID_NULL = 0xf0,
393 VALUE_TYPE_ID_TYPE = 0xf1,
394 VALUE_TYPE_ID_PARENT_VTYPE = 0xf2
398 FRAME_FLAG_DEBUGGER_INVOKE = 1,
399 FRAME_FLAG_NATIVE_TRANSITION = 2
403 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
404 INVOKE_FLAG_SINGLE_THREADED = 2,
405 INVOKE_FLAG_RETURN_OUT_THIS = 4,
406 INVOKE_FLAG_RETURN_OUT_ARGS = 8,
407 INVOKE_FLAG_VIRTUAL = 16
411 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
412 } BindingFlagsExtensions;
416 CMD_VM_ALL_THREADS = 2,
421 CMD_VM_INVOKE_METHOD = 7,
422 CMD_VM_SET_PROTOCOL_VERSION = 8,
423 CMD_VM_ABORT_INVOKE = 9,
424 CMD_VM_SET_KEEPALIVE = 10,
425 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
426 CMD_VM_GET_TYPES = 12,
427 CMD_VM_INVOKE_METHODS = 13,
428 CMD_VM_START_BUFFERING = 14,
429 CMD_VM_STOP_BUFFERING = 15
433 CMD_THREAD_GET_FRAME_INFO = 1,
434 CMD_THREAD_GET_NAME = 2,
435 CMD_THREAD_GET_STATE = 3,
436 CMD_THREAD_GET_INFO = 4,
437 CMD_THREAD_GET_ID = 5,
438 CMD_THREAD_GET_TID = 6,
439 CMD_THREAD_SET_IP = 7
443 CMD_EVENT_REQUEST_SET = 1,
444 CMD_EVENT_REQUEST_CLEAR = 2,
445 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
453 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
454 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
455 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
456 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
457 CMD_APPDOMAIN_CREATE_STRING = 5,
458 CMD_APPDOMAIN_GET_CORLIB = 6,
459 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
463 CMD_ASSEMBLY_GET_LOCATION = 1,
464 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
465 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
466 CMD_ASSEMBLY_GET_OBJECT = 4,
467 CMD_ASSEMBLY_GET_TYPE = 5,
468 CMD_ASSEMBLY_GET_NAME = 6
472 CMD_MODULE_GET_INFO = 1,
476 CMD_FIELD_GET_INFO = 1,
480 CMD_METHOD_GET_NAME = 1,
481 CMD_METHOD_GET_DECLARING_TYPE = 2,
482 CMD_METHOD_GET_DEBUG_INFO = 3,
483 CMD_METHOD_GET_PARAM_INFO = 4,
484 CMD_METHOD_GET_LOCALS_INFO = 5,
485 CMD_METHOD_GET_INFO = 6,
486 CMD_METHOD_GET_BODY = 7,
487 CMD_METHOD_RESOLVE_TOKEN = 8,
488 CMD_METHOD_GET_CATTRS = 9,
489 CMD_METHOD_MAKE_GENERIC_METHOD = 10
493 CMD_TYPE_GET_INFO = 1,
494 CMD_TYPE_GET_METHODS = 2,
495 CMD_TYPE_GET_FIELDS = 3,
496 CMD_TYPE_GET_VALUES = 4,
497 CMD_TYPE_GET_OBJECT = 5,
498 CMD_TYPE_GET_SOURCE_FILES = 6,
499 CMD_TYPE_SET_VALUES = 7,
500 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
501 CMD_TYPE_GET_PROPERTIES = 9,
502 CMD_TYPE_GET_CATTRS = 10,
503 CMD_TYPE_GET_FIELD_CATTRS = 11,
504 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
505 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
506 CMD_TYPE_GET_VALUES_2 = 14,
507 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
508 CMD_TYPE_GET_INTERFACES = 16,
509 CMD_TYPE_GET_INTERFACE_MAP = 17,
510 CMD_TYPE_IS_INITIALIZED = 18,
511 CMD_TYPE_CREATE_INSTANCE = 19
515 CMD_STACK_FRAME_GET_VALUES = 1,
516 CMD_STACK_FRAME_GET_THIS = 2,
517 CMD_STACK_FRAME_SET_VALUES = 3,
518 CMD_STACK_FRAME_GET_DOMAIN = 4,
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);
819 static inline gboolean
820 is_debugger_thread (void)
822 return GetCurrentThreadId () == debugger_thread_id;
826 parse_address (char *address, char **host, int *port)
828 char *pos = strchr (address, ':');
830 if (pos == NULL || pos == address)
833 *host = g_malloc (pos - address + 1);
834 strncpy (*host, address, pos - address);
835 (*host) [pos - address] = '\0';
837 *port = atoi (pos + 1);
845 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
846 fprintf (stderr, "Available options:\n");
847 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
848 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
849 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
850 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
851 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
852 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
853 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
854 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
855 fprintf (stderr, " setpgid=y/n\t\t\tWhether to call setpid(0, 0) after startup.\n");
856 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
860 parse_flag (const char *option, char *flag)
862 if (!strcmp (flag, "y"))
864 else if (!strcmp (flag, "n"))
867 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
874 mono_debugger_agent_parse_options (char *options)
881 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
882 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
886 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
888 options = g_strdup_printf ("%s,%s", options, extra);
890 agent_config.enabled = TRUE;
891 agent_config.suspend = TRUE;
892 agent_config.server = FALSE;
893 agent_config.defer = FALSE;
894 agent_config.address = NULL;
896 //agent_config.log_level = 10;
898 args = g_strsplit (options, ",", -1);
899 for (ptr = args; ptr && *ptr; ptr ++) {
902 if (strncmp (arg, "transport=", 10) == 0) {
903 agent_config.transport = g_strdup (arg + 10);
904 } else if (strncmp (arg, "address=", 8) == 0) {
905 agent_config.address = g_strdup (arg + 8);
906 } else if (strncmp (arg, "loglevel=", 9) == 0) {
907 agent_config.log_level = atoi (arg + 9);
908 } else if (strncmp (arg, "logfile=", 8) == 0) {
909 agent_config.log_file = g_strdup (arg + 8);
910 } else if (strncmp (arg, "suspend=", 8) == 0) {
911 agent_config.suspend = parse_flag ("suspend", arg + 8);
912 } else if (strncmp (arg, "server=", 7) == 0) {
913 agent_config.server = parse_flag ("server", arg + 7);
914 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
915 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
916 } else if (strncmp (arg, "onthrow=", 8) == 0) {
917 /* We support multiple onthrow= options */
918 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
919 } else if (strncmp (arg, "onthrow", 7) == 0) {
920 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
921 } else if (strncmp (arg, "help", 4) == 0) {
924 } else if (strncmp (arg, "timeout=", 8) == 0) {
925 agent_config.timeout = atoi (arg + 8);
926 } else if (strncmp (arg, "launch=", 7) == 0) {
927 agent_config.launch = g_strdup (arg + 7);
928 } else if (strncmp (arg, "embedding=", 10) == 0) {
929 agent_config.embedding = atoi (arg + 10) == 1;
930 } else if (strncmp (arg, "keepalive=", 10) == 0) {
931 agent_config.keepalive = atoi (arg + 10);
932 } else if (strncmp (arg, "setpgid=", 8) == 0) {
933 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
940 if (agent_config.server && !agent_config.suspend) {
941 /* Waiting for deferred attachment */
942 agent_config.defer = TRUE;
943 if (agent_config.address == NULL) {
944 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (getpid () % 1000));
948 //agent_config.log_level = 0;
950 if (agent_config.transport == NULL) {
951 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
955 if (agent_config.address == NULL && !agent_config.server) {
956 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
961 if (!strcmp (agent_config.transport, "dt_socket")) {
962 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
963 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
970 mono_debugger_agent_init (void)
972 mono_mutex_init_recursive (&debug_mutex);
974 if (!agent_config.enabled)
979 /* Need to know whenever a thread has acquired the loader mutex */
980 mono_loader_lock_track_ownership (TRUE);
982 event_requests = g_ptr_array_new ();
984 mono_mutex_init (&debugger_thread_exited_mutex);
985 mono_cond_init (&debugger_thread_exited_cond, NULL);
987 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
988 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
989 mono_profiler_install_runtime_initialized (runtime_initialized);
990 mono_profiler_install_appdomain (NULL, appdomain_load, appdomain_start_unload, appdomain_unload);
991 mono_profiler_install_thread (thread_startup, thread_end);
992 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
993 mono_profiler_install_jit_end (jit_end);
994 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
996 mono_native_tls_alloc (&debugger_tls_id, NULL);
998 /* Needed by the hash_table_new_type () call below */
999 mono_gc_base_init ();
1001 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
1002 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls);
1004 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
1005 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread);
1007 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
1008 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj);
1010 pending_assembly_loads = g_ptr_array_new ();
1011 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
1013 log_level = agent_config.log_level;
1015 embedding = agent_config.embedding;
1016 disconnected = TRUE;
1018 if (agent_config.log_file) {
1019 log_file = fopen (agent_config.log_file, "w+");
1021 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
1030 breakpoints_init ();
1033 mini_get_debug_options ()->gen_seq_points = TRUE;
1035 * This is needed because currently we don't handle liveness info.
1037 mini_get_debug_options ()->mdb_optimizations = TRUE;
1039 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
1040 /* This is needed because we can't set local variables in registers yet */
1041 mono_disable_optimizations (MONO_OPT_LINEARS);
1045 * The stack walk done from thread_interrupt () needs to be signal safe, but it
1046 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
1047 * safe (#3411). So load AOT info eagerly when the debugger is running as a
1050 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
1053 if (agent_config.setpgid)
1057 if (!agent_config.onuncaught && !agent_config.onthrow)
1058 finish_agent_init (TRUE);
1062 * finish_agent_init:
1064 * Finish the initialization of the agent. This involves connecting the transport
1065 * and starting the agent thread. This is either done at startup, or
1066 * in response to some event like an unhandled exception.
1069 finish_agent_init (gboolean on_startup)
1073 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
1076 if (agent_config.launch) {
1079 // FIXME: Generated address
1080 // FIXME: Races with transport_connect ()
1082 argv [0] = agent_config.launch;
1083 argv [1] = agent_config.transport;
1084 argv [2] = agent_config.address;
1087 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1089 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1094 transport_connect (agent_config.address);
1097 /* Do some which is usually done after sending the VMStart () event */
1098 vm_start_event_sent = TRUE;
1099 start_debugger_thread ();
1104 mono_debugger_agent_cleanup (void)
1109 stop_debugger_thread ();
1111 breakpoints_cleanup ();
1115 mono_mutex_destroy (&debugger_thread_exited_mutex);
1116 mono_cond_destroy (&debugger_thread_exited_cond);
1123 #ifndef DISABLE_SOCKET_TRANSPORT
1128 * recv() + handle incomplete reads and EINTR
1131 socket_transport_recv (void *buf, int len)
1137 static gint32 last_keepalive;
1142 res = recv (fd, (char *) buf + total, len - total, flags);
1145 if (agent_config.keepalive) {
1146 gboolean need_keepalive = FALSE;
1147 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1148 need_keepalive = TRUE;
1149 } else if (res == -1) {
1150 /* This could happen if recv () is interrupted repeatedly */
1151 msecs = mono_msec_ticks ();
1152 if (msecs - last_keepalive >= agent_config.keepalive) {
1153 need_keepalive = TRUE;
1154 last_keepalive = msecs;
1157 if (need_keepalive) {
1158 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1162 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1167 #define HAVE_GETADDRINFO 1
1171 set_keepalive (void)
1176 if (!agent_config.keepalive || !conn_fd)
1179 tv.tv_sec = agent_config.keepalive / 1000;
1180 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1182 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1183 g_assert (result >= 0);
1187 socket_transport_accept (int socket_fd)
1189 conn_fd = accept (socket_fd, NULL, NULL);
1190 if (conn_fd == -1) {
1191 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1193 DEBUG (1, fprintf (log_file, "Accepted connection from client, connection fd=%d.\n", conn_fd));
1200 socket_transport_send (void *data, int len)
1205 res = send (conn_fd, data, len, 0);
1206 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1214 * socket_transport_connect:
1216 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1219 socket_transport_connect (const char *address)
1221 #ifdef HAVE_GETADDRINFO
1222 struct addrinfo hints;
1223 struct addrinfo *result, *rp;
1225 struct hostent *result;
1227 int sfd = -1, s, res;
1228 char port_string [128];
1232 if (agent_config.address) {
1233 res = parse_address (agent_config.address, &host, &port);
1234 g_assert (res == 0);
1244 sprintf (port_string, "%d", port);
1246 mono_network_init ();
1248 /* Obtain address(es) matching host/port */
1249 #ifdef HAVE_GETADDRINFO
1250 memset (&hints, 0, sizeof (struct addrinfo));
1251 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
1252 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
1254 hints.ai_protocol = 0; /* Any protocol */
1256 s = getaddrinfo (host, port_string, &hints, &result);
1258 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %s\n", host, port, gai_strerror (s));
1262 /* The PS3 doesn't even have _r or hstrerror () */
1263 result = gethostbyname (host);
1265 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, h_errno);
1270 if (agent_config.server) {
1271 #ifdef HAVE_GETADDRINFO
1272 /* Wait for a connection */
1274 struct sockaddr_in addr;
1277 /* No address, generate one */
1278 sfd = socket (AF_INET, SOCK_STREAM, 0);
1281 /* This will bind the socket to a random port */
1282 res = listen (sfd, 16);
1284 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1289 addrlen = sizeof (addr);
1290 memset (&addr, 0, sizeof (addr));
1291 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1292 g_assert (res == 0);
1294 host = (char*)"127.0.0.1";
1295 port = ntohs (addr.sin_port);
1297 /* Emit the address to stdout */
1298 /* FIXME: Should print another interface, not localhost */
1299 printf ("%s:%d\n", host, port);
1301 /* Listen on the provided address */
1302 for (rp = result; rp != NULL; rp = rp->ai_next) {
1305 sfd = socket (rp->ai_family, rp->ai_socktype,
1310 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1313 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
1317 res = listen (sfd, 16);
1326 * this function is not present on win2000 which we still support, and the
1327 * workaround described here:
1328 * http://msdn.microsoft.com/en-us/library/ms737931(VS.85).aspx
1329 * only works with MSVC.
1331 #ifdef HAVE_GETADDRINFO
1332 freeaddrinfo (result);
1337 if (agent_config.defer)
1340 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
1342 if (agent_config.timeout) {
1347 tv.tv_usec = agent_config.timeout * 1000;
1349 FD_SET (sfd, &readfds);
1350 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1352 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1357 conn_fd = socket_transport_accept (sfd);
1361 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
1364 #endif /* HAVE_GETADDRINFO */
1366 /* Connect to the specified address */
1367 #ifdef HAVE_GETADDRINFO
1368 /* FIXME: Respect the timeout */
1369 for (rp = result; rp != NULL; rp = rp->ai_next) {
1370 sfd = socket (rp->ai_family, rp->ai_socktype,
1375 if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
1376 break; /* Success */
1382 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1386 sfd = socket (result->h_addrtype, SOCK_STREAM, 0);
1388 g_assert_not_reached ();
1389 res = connect (sfd, (void*)result->h_addr_list [0], result->h_length);
1391 g_assert_not_reached ();
1397 /* See the comment above */
1398 #ifdef HAVE_GETADDRINFO
1399 freeaddrinfo (result);
1404 if (!transport_handshake ())
1409 socket_transport_close1 (void)
1411 /* This will interrupt the agent thread */
1412 /* Close the read part only so it can still send back replies */
1413 /* Also shut down the connection listener so that we can exit normally */
1415 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1416 shutdown (conn_fd, SD_BOTH);
1417 shutdown (listen_fd, SD_BOTH);
1418 closesocket (listen_fd);
1420 shutdown (conn_fd, SHUT_RD);
1421 shutdown (listen_fd, SHUT_RDWR);
1427 socket_transport_close2 (void)
1430 shutdown (conn_fd, SD_BOTH);
1432 shutdown (conn_fd, SHUT_RDWR);
1437 register_socket_transport (void)
1439 DebuggerTransport trans;
1441 trans.name = "dt_socket";
1442 trans.connect = socket_transport_connect;
1443 trans.close1 = socket_transport_close1;
1444 trans.close2 = socket_transport_close2;
1445 trans.send = socket_transport_send;
1446 trans.recv = socket_transport_recv;
1448 register_transport (&trans);
1452 * socket_fd_transport_connect:
1456 socket_fd_transport_connect (const char *address)
1460 res = sscanf (address, "%d", &conn_fd);
1462 fprintf (stderr, "debugger-agent: socket-fd transport address is invalid: '%s'\n", address);
1466 if (!transport_handshake ())
1471 register_socket_fd_transport (void)
1473 DebuggerTransport trans;
1475 /* This is the same as the 'dt_socket' transport, but receives an already connected socket fd */
1476 trans.name = "socket-fd";
1477 trans.connect = socket_fd_transport_connect;
1478 trans.close1 = socket_transport_close1;
1479 trans.close2 = socket_transport_close2;
1480 trans.send = socket_transport_send;
1481 trans.recv = socket_transport_recv;
1483 register_transport (&trans);
1486 #endif /* DISABLE_SOCKET_TRANSPORT */
1492 #define MAX_TRANSPORTS 16
1494 static DebuggerTransport *transport;
1496 static DebuggerTransport transports [MAX_TRANSPORTS];
1497 static int ntransports;
1500 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1503 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1505 register_transport (trans);
1509 register_transport (DebuggerTransport *trans)
1511 g_assert (ntransports < MAX_TRANSPORTS);
1513 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1518 transport_init (void)
1522 #ifndef DISABLE_SOCKET_TRANSPORT
1523 register_socket_transport ();
1524 register_socket_fd_transport ();
1527 for (i = 0; i < ntransports; ++i) {
1528 if (!strcmp (agent_config.transport, transports [i].name))
1531 if (i == ntransports) {
1532 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1533 for (i = 0; i < ntransports; ++i)
1534 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1535 fprintf (stderr, "\n");
1538 transport = &transports [i];
1542 transport_connect (const char *address)
1544 transport->connect (address);
1548 transport_close1 (void)
1550 transport->close1 ();
1554 transport_close2 (void)
1556 transport->close2 ();
1560 transport_send (void *buf, int len)
1562 return transport->send (buf, len);
1566 transport_recv (void *buf, int len)
1568 return transport->recv (buf, len);
1572 mono_debugger_agent_transport_handshake (void)
1574 return transport_handshake ();
1578 transport_handshake (void)
1580 char handshake_msg [128];
1584 disconnected = TRUE;
1586 /* Write handshake message */
1587 sprintf (handshake_msg, "DWP-Handshake");
1589 res = transport_send (handshake_msg, strlen (handshake_msg));
1590 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1591 g_assert (res != -1);
1594 res = transport_recv (buf, strlen (handshake_msg));
1595 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg)) != 0)) {
1596 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1601 * To support older clients, the client sends its protocol version after connecting
1602 * using a command. Until that is received, default to our protocol version.
1604 major_version = MAJOR_VERSION;
1605 minor_version = MINOR_VERSION;
1606 protocol_version_set = FALSE;
1608 #ifndef DISABLE_SOCKET_TRANSPORT
1609 // FIXME: Move this somewhere else
1611 * Set TCP_NODELAY on the socket so the client receives events/command
1612 * results immediately.
1616 int result = setsockopt (conn_fd,
1621 g_assert (result >= 0);
1627 disconnected = FALSE;
1632 stop_debugger_thread (void)
1637 transport_close1 ();
1640 * Wait for the thread to exit.
1642 * If we continue with the shutdown without waiting for it, then the client might
1643 * not receive an answer to its last command like a resume.
1644 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
1647 //WaitForSingleObject (debugger_thread_handle, INFINITE);
1648 if (GetCurrentThreadId () != debugger_thread_id) {
1650 mono_mutex_lock (&debugger_thread_exited_mutex);
1651 if (!debugger_thread_exited) {
1653 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
1654 mono_mutex_unlock (&debugger_thread_exited_mutex);
1656 mono_mutex_lock (&debugger_thread_exited_mutex);
1659 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1662 mono_mutex_unlock (&debugger_thread_exited_mutex);
1663 } while (!debugger_thread_exited);
1666 transport_close2 ();
1670 start_debugger_thread (void)
1672 debugger_thread_handle = mono_threads_create_thread (debugger_thread, NULL, 0, 0, NULL);
1673 g_assert (debugger_thread_handle);
1677 * Functions to decode protocol data
1681 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1684 g_assert (*endbuf <= limit);
1689 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1692 g_assert (*endbuf <= limit);
1694 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1697 static inline gint64
1698 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1700 guint32 high = decode_int (buf, &buf, limit);
1701 guint32 low = decode_int (buf, &buf, limit);
1705 return ((((guint64)high) << 32) | ((guint64)low));
1709 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1711 return decode_int (buf, endbuf, limit);
1715 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1717 int len = decode_int (buf, &buf, limit);
1725 s = g_malloc (len + 1);
1728 memcpy (s, buf, len);
1737 * Functions to encode protocol data
1741 buffer_init (Buffer *buf, int size)
1743 buf->buf = g_malloc (size);
1745 buf->end = buf->buf + size;
1749 buffer_len (Buffer *buf)
1751 return buf->p - buf->buf;
1755 buffer_make_room (Buffer *buf, int size)
1757 if (buf->end - buf->p < size) {
1758 int new_size = buf->end - buf->buf + size + 32;
1759 guint8 *p = g_realloc (buf->buf, new_size);
1760 size = buf->p - buf->buf;
1763 buf->end = buf->buf + new_size;
1768 buffer_add_byte (Buffer *buf, guint8 val)
1770 buffer_make_room (buf, 1);
1776 buffer_add_short (Buffer *buf, guint32 val)
1778 buffer_make_room (buf, 2);
1779 buf->p [0] = (val >> 8) & 0xff;
1780 buf->p [1] = (val >> 0) & 0xff;
1785 buffer_add_int (Buffer *buf, guint32 val)
1787 buffer_make_room (buf, 4);
1788 buf->p [0] = (val >> 24) & 0xff;
1789 buf->p [1] = (val >> 16) & 0xff;
1790 buf->p [2] = (val >> 8) & 0xff;
1791 buf->p [3] = (val >> 0) & 0xff;
1796 buffer_add_long (Buffer *buf, guint64 l)
1798 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1799 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1803 buffer_add_id (Buffer *buf, int id)
1805 buffer_add_int (buf, (guint64)id);
1809 buffer_add_data (Buffer *buf, guint8 *data, int len)
1811 buffer_make_room (buf, len);
1812 memcpy (buf->p, data, len);
1817 buffer_add_string (Buffer *buf, const char *str)
1822 buffer_add_int (buf, 0);
1825 buffer_add_int (buf, len);
1826 buffer_add_data (buf, (guint8*)str, len);
1831 buffer_add_buffer (Buffer *buf, Buffer *data)
1833 buffer_add_data (buf, data->buf, buffer_len (data));
1837 buffer_free (Buffer *buf)
1843 send_packet (int command_set, int command, Buffer *data)
1849 id = InterlockedIncrement (&packet_id);
1851 len = data->p - data->buf + 11;
1852 buffer_init (&buf, len);
1853 buffer_add_int (&buf, len);
1854 buffer_add_int (&buf, id);
1855 buffer_add_byte (&buf, 0); /* flags */
1856 buffer_add_byte (&buf, command_set);
1857 buffer_add_byte (&buf, command);
1858 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1860 res = transport_send (buf.buf, len);
1868 send_reply_packets (int npackets, ReplyPacket *packets)
1875 for (i = 0; i < npackets; ++i)
1876 len += buffer_len (packets [i].data) + 11;
1877 buffer_init (&buf, len);
1878 for (i = 0; i < npackets; ++i) {
1879 buffer_add_int (&buf, buffer_len (packets [i].data) + 11);
1880 buffer_add_int (&buf, packets [i].id);
1881 buffer_add_byte (&buf, 0x80); /* flags */
1882 buffer_add_byte (&buf, (packets [i].error >> 8) & 0xff);
1883 buffer_add_byte (&buf, packets [i].error);
1884 buffer_add_buffer (&buf, packets [i].data);
1886 res = transport_send (buf.buf, len);
1894 send_reply_packet (int id, int error, Buffer *data)
1898 memset (&packet, 0, sizeof (ReplyPacket));
1900 packet.error = error;
1903 return send_reply_packets (1, &packet);
1907 send_buffered_reply_packets (void)
1911 send_reply_packets (nreply_packets, reply_packets);
1912 for (i = 0; i < nreply_packets; ++i)
1913 buffer_free (reply_packets [i].data);
1914 DEBUG (1, fprintf (log_file, "[dbg] Sent %d buffered reply packets [at=%lx].\n", nreply_packets, (long)mono_100ns_ticks () / 10000));
1919 buffer_reply_packet (int id, int error, Buffer *data)
1923 if (nreply_packets == 128)
1924 send_buffered_reply_packets ();
1926 p = &reply_packets [nreply_packets];
1929 p->data = g_new0 (Buffer, 1);
1930 buffer_init (p->data, buffer_len (data));
1931 buffer_add_buffer (p->data, data);
1940 * Represents an object accessible by the debugger client.
1943 /* Unique id used in the wire protocol to refer to objects */
1946 * A weakref gc handle pointing to the object. The gc handle is used to
1947 * detect if the object was garbage collected.
1952 /* Maps objid -> ObjRef */
1953 static GHashTable *objrefs;
1954 static GHashTable *obj_to_objref;
1955 /* Protected by the dbg lock */
1956 static MonoGHashTable *suspended_objs;
1959 free_objref (gpointer value)
1963 mono_gchandle_free (o->handle);
1971 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1972 obj_to_objref = g_hash_table_new (NULL, NULL);
1973 suspended_objs = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
1974 MONO_GC_REGISTER_ROOT_FIXED (suspended_objs);
1978 objrefs_cleanup (void)
1980 g_hash_table_destroy (objrefs);
1985 * Return an ObjRef for OBJ.
1988 get_objref (MonoObject *obj)
1991 GSList *reflist = NULL, *l;
1997 if (suspend_count) {
1999 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
2002 mono_g_hash_table_insert (suspended_objs, obj, NULL);
2006 mono_loader_lock ();
2008 /* FIXME: The tables can grow indefinitely */
2010 if (mono_gc_is_moving ()) {
2012 * Objects can move, so use a hash table mapping hash codes to lists of
2013 * ObjRef structures.
2015 hash = mono_object_hash (obj);
2017 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
2018 for (l = reflist; l; l = l->next) {
2020 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
2021 mono_loader_unlock ();
2026 /* Use a hash table with masked pointers to internalize object references */
2027 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
2028 /* ref might refer to a different object with the same addr which was GCd */
2029 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
2030 mono_loader_unlock ();
2035 ref = g_new0 (ObjRef, 1);
2036 ref->id = InterlockedIncrement (&objref_id);
2037 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
2039 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
2041 if (mono_gc_is_moving ()) {
2042 reflist = g_slist_append (reflist, ref);
2043 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
2045 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
2048 mono_loader_unlock ();
2054 true_pred (gpointer key, gpointer value, gpointer user_data)
2060 clear_suspended_objs (void)
2063 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
2068 get_objid (MonoObject *obj)
2070 return get_objref (obj)->id;
2074 * Set OBJ to the object identified by OBJID.
2075 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
2079 get_object_allow_null (int objid, MonoObject **obj)
2089 return ERR_INVALID_OBJECT;
2091 mono_loader_lock ();
2093 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
2096 *obj = mono_gchandle_get_target (ref->handle);
2097 mono_loader_unlock ();
2099 return ERR_INVALID_OBJECT;
2102 mono_loader_unlock ();
2103 return ERR_INVALID_OBJECT;
2108 get_object (int objid, MonoObject **obj)
2110 int err = get_object_allow_null (objid, obj);
2115 return ERR_INVALID_OBJECT;
2120 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
2122 return decode_id (buf, endbuf, limit);
2126 buffer_add_objid (Buffer *buf, MonoObject *o)
2128 buffer_add_id (buf, get_objid (o));
2147 * Represents a runtime structure accessible to the debugger client
2150 /* Unique id used in the wire protocol */
2152 /* Domain of the runtime structure, NULL if the domain was unloaded */
2159 MonoAssembly *assembly;
2160 MonoClassField *field;
2162 MonoProperty *property;
2167 /* Maps runtime structure -> Id */
2168 GHashTable *val_to_id [ID_NUM];
2169 /* Classes whose class load event has been sent */
2170 GHashTable *loaded_classes;
2171 /* Maps MonoClass->GPtrArray of file names */
2172 GHashTable *source_files;
2173 /* Maps source file basename -> GSList of classes */
2174 GHashTable *source_file_to_class;
2175 /* Same with ignore-case */
2176 GHashTable *source_file_to_class_ignorecase;
2180 /* Protected by the dbg lock */
2181 static GPtrArray *ids [ID_NUM];
2188 for (i = 0; i < ID_NUM; ++i)
2189 ids [i] = g_ptr_array_new ();
2197 for (i = 0; i < ID_NUM; ++i) {
2199 for (j = 0; j < ids [i]->len; ++j)
2200 g_free (g_ptr_array_index (ids [i], j));
2201 g_ptr_array_free (ids [i], TRUE);
2208 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2210 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
2212 GHashTableIter iter;
2213 GPtrArray *file_names;
2218 for (i = 0; i < ID_NUM; ++i)
2219 if (info->val_to_id [i])
2220 g_hash_table_destroy (info->val_to_id [i]);
2221 g_hash_table_destroy (info->loaded_classes);
2223 g_hash_table_iter_init (&iter, info->source_files);
2224 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2225 for (i = 0; i < file_names->len; ++i)
2226 g_free (g_ptr_array_index (file_names, i));
2227 g_ptr_array_free (file_names, TRUE);
2230 g_hash_table_iter_init (&iter, info->source_file_to_class);
2231 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2236 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2237 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2245 domain_jit_info (domain)->agent_info = NULL;
2247 /* Clear ids referencing structures in the domain */
2249 for (i = 0; i < ID_NUM; ++i) {
2251 for (j = 0; j < ids [i]->len; ++j) {
2252 Id *id = g_ptr_array_index (ids [i], j);
2253 if (id->domain == domain)
2260 mono_loader_lock ();
2261 g_hash_table_remove (domains, domain);
2262 mono_loader_unlock ();
2265 static AgentDomainInfo*
2266 get_agent_domain_info (MonoDomain *domain)
2268 AgentDomainInfo *info = NULL;
2270 mono_domain_lock (domain);
2272 info = domain_jit_info (domain)->agent_info;
2274 info = domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
2275 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2276 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2277 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2278 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2281 mono_domain_unlock (domain);
2287 get_id (MonoDomain *domain, IdType type, gpointer val)
2290 AgentDomainInfo *info;
2295 mono_loader_lock ();
2297 mono_domain_lock (domain);
2299 info = get_agent_domain_info (domain);
2301 if (info->val_to_id [type] == NULL)
2302 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2304 id = g_hash_table_lookup (info->val_to_id [type], val);
2306 mono_domain_unlock (domain);
2307 mono_loader_unlock ();
2313 id = g_new0 (Id, 1);
2315 id->id = ids [type]->len + 1;
2316 id->domain = domain;
2319 g_hash_table_insert (info->val_to_id [type], val, id);
2320 g_ptr_array_add (ids [type], id);
2324 mono_domain_unlock (domain);
2326 mono_loader_unlock ();
2331 static inline gpointer
2332 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
2336 int id = decode_id (buf, endbuf, limit);
2345 // FIXME: error handling
2347 g_assert (id > 0 && id <= ids [type]->len);
2349 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2352 if (res->domain == NULL) {
2353 DEBUG (0, fprintf (log_file, "ERR_UNLOADED, id=%d, type=%d.\n", id, type));
2354 *err = ERR_UNLOADED;
2359 *domain = res->domain;
2361 return res->data.val;
2365 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2367 int id = get_id (domain, type, val);
2369 buffer_add_id (buf, id);
2373 static inline MonoClass*
2374 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2378 klass = decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2379 if (G_UNLIKELY (log_level >= 2) && klass) {
2382 s = mono_type_full_name (&klass->byval_arg);
2383 DEBUG(2, fprintf (log_file, "[dbg] recv class [%s]\n", s));
2389 static inline MonoAssembly*
2390 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2392 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2395 static inline MonoImage*
2396 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2398 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2401 static inline MonoMethod*
2402 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2406 m = decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2407 if (G_UNLIKELY (log_level >= 2) && m) {
2410 s = mono_method_full_name (m, TRUE);
2411 DEBUG(2, fprintf (log_file, "[dbg] recv method [%s]\n", s));
2417 static inline MonoClassField*
2418 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2420 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2423 static inline MonoDomain*
2424 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2426 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2429 static inline MonoProperty*
2430 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2432 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2436 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2438 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2439 if (G_UNLIKELY (log_level >= 2) && klass) {
2442 s = mono_type_full_name (&klass->byval_arg);
2443 if (GetCurrentThreadId () == debugger_thread_id)
2444 DEBUG(2, fprintf (log_file, "[dbg] send class [%s]\n", s));
2446 DEBUG(2, fprintf (log_file, "[%p] send class [%s]\n", (gpointer)GetCurrentThreadId (), s));
2452 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2454 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2455 if (G_UNLIKELY (log_level >= 2) && method) {
2458 s = mono_method_full_name (method, 1);
2459 DEBUG(2, fprintf (log_file, "[dbg] send method [%s]\n", s));
2465 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2469 id = buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2470 if (G_UNLIKELY (log_level >= 2) && assembly)
2471 DEBUG(2, fprintf (log_file, "[dbg] send assembly [%s][%s][%d]\n", assembly->aname.name, domain->friendly_name, id));
2475 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2477 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2481 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2483 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2487 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2489 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2493 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2495 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2498 static void invoke_method (void);
2505 * save_thread_context:
2507 * Set CTX as the current threads context which is used for computing stack traces.
2508 * This function is signal-safe.
2511 save_thread_context (MonoContext *ctx)
2513 DebuggerTlsData *tls;
2515 tls = mono_native_tls_get_value (debugger_tls_id);
2519 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2521 mono_thread_state_init_from_current (&tls->context);
2524 /* Number of threads suspended */
2526 * If this is equal to the size of thread_to_tls, the runtime is considered
2529 static gint32 threads_suspend_count;
2531 static mono_mutex_t suspend_mutex;
2533 /* Cond variable used to wait for suspend_count becoming 0 */
2534 static mono_cond_t suspend_cond;
2536 /* Semaphore used to wait for a thread becoming suspended */
2537 static MonoSemType suspend_sem;
2542 mono_mutex_init (&suspend_mutex);
2543 mono_cond_init (&suspend_cond, NULL);
2544 MONO_SEM_INIT (&suspend_sem, 0);
2549 StackFrameInfo last_frame;
2550 gboolean last_frame_set;
2553 } GetLastFrameUserData;
2556 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2558 GetLastFrameUserData *data = user_data;
2560 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
2563 if (!data->last_frame_set) {
2564 /* Store the last frame */
2565 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2566 data->last_frame_set = TRUE;
2569 /* Store the context/lmf for the frame above the last frame */
2570 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2571 data->lmf = info->lmf;
2579 * Process interruption of a thread. If SIGCTX is set, process the current thread. If
2580 * INFO is set, process the thread described by INFO.
2581 * This should be signal safe.
2584 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, void *sigctx, MonoJitInfo *ji)
2588 MonoNativeThreadId tid;
2591 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2592 * guarantee the signal handler will be called that many times. Instead of tracking
2593 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2594 * has been requested that hasn't been handled yet, otherwise we can have threads
2595 * refuse to die when VM_EXIT is called
2597 #if defined(__APPLE__)
2598 if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
2602 * We use interrupt_count to determine whenever this interrupt should be processed
2603 * by us or the normal interrupt processing code in the signal handler.
2604 * There is no race here with notify_thread (), since the signal is sent after
2605 * incrementing interrupt_count.
2607 if (tls->interrupt_count == 0)
2610 InterlockedDecrement (&tls->interrupt_count);
2614 ip = mono_arch_ip_from_context (sigctx);
2616 ip = MONO_CONTEXT_GET_IP (&info->suspend_state.ctx);
2621 tid = mono_thread_info_get_tid (info);
2623 tid = (MonoNativeThreadId)GetCurrentThreadId ();
2625 // FIXME: Races when the thread leaves managed code before hitting a single step
2629 /* Running managed code, will be suspended by the single step code */
2630 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip));
2634 * Running native code, will be suspended when it returns to/enters
2635 * managed code. Treat it as already suspended.
2636 * This might interrupt the code in process_single_step_inner (), we use the
2637 * tls->suspending flag to avoid races when that happens.
2639 if (!tls->suspended && !tls->suspending) {
2641 GetLastFrameUserData data;
2643 // FIXME: printf is not signal safe, but this is only used during
2644 // debugger debugging
2646 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip));
2647 //save_thread_context (&ctx);
2650 /* Already terminated */
2654 * We are in a difficult position: we want to be able to provide stack
2655 * traces for this thread, but we can't use the current ctx+lmf, since
2656 * the thread is still running, so it might return to managed code,
2657 * making these invalid.
2658 * So we start a stack walk and save the first frame, along with the
2659 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2660 * suspended when it returns to managed code, so the parent's ctx should
2663 data.last_frame_set = FALSE;
2665 mono_sigctx_to_monoctx (sigctx, &ctx);
2667 * Don't pass MONO_UNWIND_ACTUAL_METHOD, its not signal safe, and
2668 * get_last_frame () doesn't need it, the last frame cannot be a ginst
2669 * since we are not in a JITted method.
2671 mono_walk_stack_with_ctx (get_last_frame, &ctx, MONO_UNWIND_NONE, &data);
2673 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, &info->suspend_state, MONO_UNWIND_SIGNAL_SAFE, &data);
2675 if (data.last_frame_set) {
2676 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2677 res = mono_thread_state_init_from_monoctx (&tls->async_state, &ctx);
2679 mono_thread_state_init_from_monoctx (&tls->context, &ctx);
2682 memcpy (&tls->async_state.ctx, &data.ctx, sizeof (MonoContext));
2683 tls->async_state.unwind_data [MONO_UNWIND_DATA_LMF] = data.lmf;
2684 tls->async_state.unwind_data [MONO_UNWIND_DATA_JIT_TLS] = tls->thread->jit_data;
2686 tls->async_state.valid = FALSE;
2689 mono_memory_barrier ();
2691 tls->suspended = TRUE;
2692 MONO_SEM_POST (&suspend_sem);
2699 * mono_debugger_agent_thread_interrupt:
2701 * Called by the abort signal handler.
2702 * Should be signal safe.
2705 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
2707 DebuggerTlsData *tls;
2712 tls = mono_native_tls_get_value (debugger_tls_id);
2714 DEBUG (1, fprintf (log_file, "[%p] Received interrupt with no TLS, continuing.\n", (gpointer)GetCurrentThreadId ()));
2718 return thread_interrupt (tls, NULL, sigctx, ji);
2722 static void CALLBACK notify_thread_apc (ULONG_PTR param)
2725 mono_debugger_agent_thread_interrupt (NULL, NULL);
2727 #endif /* HOST_WIN32 */
2730 * reset_native_thread_suspend_state:
2732 * Reset the suspended flag and state on native threads
2735 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2737 DebuggerTlsData *tls = value;
2739 if (!tls->really_suspended && tls->suspended) {
2740 tls->suspended = FALSE;
2742 * The thread might still be running if it was executing native code, so the state won't be invalided by
2743 * suspend_current ().
2745 tls->context.valid = FALSE;
2746 tls->async_state.valid = FALSE;
2747 invalidate_frames (tls);
2754 * Notify a thread that it needs to suspend.
2757 notify_thread (gpointer key, gpointer value, gpointer user_data)
2759 MonoInternalThread *thread = key;
2760 DebuggerTlsData *tls = value;
2761 gsize tid = thread->tid;
2766 if (GetCurrentThreadId () == tid || tls->terminated)
2769 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2772 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2773 * guarantee the signal handler will be called that many times. Instead of tracking
2774 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2775 * has been requested that hasn't been handled yet, otherwise we can have threads
2776 * refuse to die when VM_EXIT is called
2778 #if defined(__APPLE__)
2779 if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
2783 * Maybe we could use the normal interrupt infrastructure, but that does a lot
2784 * of things like breaking waits etc. which we don't want.
2786 InterlockedIncrement (&tls->interrupt_count);
2789 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2790 if (mono_thread_info_new_interrupt_enabled ()) {
2791 MonoThreadInfo *info;
2794 info = mono_thread_info_safe_suspend_sync ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE);
2796 DEBUG(1, fprintf (log_file, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2798 * Attached thread which died without detaching.
2800 tls->terminated = TRUE;
2802 ji = mono_jit_info_table_find (info->suspend_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], MONO_CONTEXT_GET_IP (&info->suspend_state.ctx));
2804 thread_interrupt (tls, info, NULL, ji);
2806 mono_thread_info_finish_suspend_and_resume (info);
2810 // FIXME: Remove this since new interrupt is used on win32 now
2811 QueueUserAPC (notify_thread_apc, thread->handle, (ULONG_PTR)NULL);
2813 res = mono_thread_kill (thread, mono_thread_get_abort_signal ());
2815 DEBUG(1, fprintf (log_file, "[%p] mono_thread_kill () failed for %p: %d...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid, res));
2817 * Attached thread which died without detaching.
2819 tls->terminated = TRUE;
2826 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2828 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2832 if (mono_loader_lock_is_owned_by_self ()) {
2834 * Shortcut for the check in suspend_current (). This speeds up processing
2835 * when executing long running code inside the loader lock, i.e. assembly load
2841 if (debugger_thread_id == GetCurrentThreadId ())
2844 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2845 if (suspend_count - tls->resume_count > 0)
2846 tls->suspending = TRUE;
2848 DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2850 if (suspend_count - tls->resume_count == 0) {
2852 * We are executing a single threaded invoke but the single step for
2853 * suspending is still active.
2854 * FIXME: This slows down single threaded invokes.
2856 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
2860 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2862 /* Can't suspend in these methods */
2863 method = jinfo_get_method (ji);
2864 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2867 save_thread_context (ctx);
2875 * Increase the suspend count of the VM. While the suspend count is greater
2876 * than 0, runtime threads are suspended at certain points during execution.
2881 mono_loader_lock ();
2883 mono_mutex_lock (&suspend_mutex);
2887 DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
2889 if (suspend_count == 1) {
2890 // FIXME: Is it safe to call this inside the lock ?
2891 start_single_stepping ();
2892 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2895 mono_mutex_unlock (&suspend_mutex);
2897 if (suspend_count == 1)
2899 * Suspend creation of new threadpool threads, since they cannot run
2901 mono_thread_pool_suspend ();
2903 mono_loader_unlock ();
2909 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2917 g_assert (debugger_thread_id == GetCurrentThreadId ());
2919 mono_loader_lock ();
2921 mono_mutex_lock (&suspend_mutex);
2923 g_assert (suspend_count > 0);
2926 DEBUG(1, fprintf (log_file, "[%p] Resuming vm, suspend count=%d...\n", (gpointer)GetCurrentThreadId (), suspend_count));
2928 if (suspend_count == 0) {
2929 // FIXME: Is it safe to call this inside the lock ?
2930 stop_single_stepping ();
2931 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2934 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2935 err = mono_cond_broadcast (&suspend_cond);
2936 g_assert (err == 0);
2938 mono_mutex_unlock (&suspend_mutex);
2939 //g_assert (err == 0);
2941 if (suspend_count == 0)
2942 mono_thread_pool_resume ();
2944 mono_loader_unlock ();
2950 * Resume just one thread.
2953 resume_thread (MonoInternalThread *thread)
2956 DebuggerTlsData *tls;
2958 g_assert (debugger_thread_id == GetCurrentThreadId ());
2960 mono_loader_lock ();
2962 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2965 mono_mutex_lock (&suspend_mutex);
2967 g_assert (suspend_count > 0);
2969 DEBUG(1, fprintf (log_file, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid));
2971 tls->resume_count += suspend_count;
2974 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2975 * but only the one whose resume_count field is > 0 will be resumed.
2977 err = mono_cond_broadcast (&suspend_cond);
2978 g_assert (err == 0);
2980 mono_mutex_unlock (&suspend_mutex);
2981 //g_assert (err == 0);
2983 mono_loader_unlock ();
2987 invalidate_frames (DebuggerTlsData *tls)
2992 tls = mono_native_tls_get_value (debugger_tls_id);
2995 for (i = 0; i < tls->frame_count; ++i) {
2996 if (tls->frames [i]->jit)
2997 mono_debug_free_method_jit_info (tls->frames [i]->jit);
2998 g_free (tls->frames [i]);
3000 g_free (tls->frames);
3001 tls->frame_count = 0;
3008 * Suspend the current thread until the runtime is resumed. If the thread has a
3009 * pending invoke, then the invoke is executed before this function returns.
3012 suspend_current (void)
3017 DebuggerTlsData *tls;
3019 g_assert (debugger_thread_id != GetCurrentThreadId ());
3021 if (mono_loader_lock_is_owned_by_self ()) {
3023 * If we own the loader mutex, can't suspend until we release it, since the
3024 * whole runtime can deadlock otherwise.
3029 tls = mono_native_tls_get_value (debugger_tls_id);
3032 mono_mutex_lock (&suspend_mutex);
3034 tls->suspending = FALSE;
3035 tls->really_suspended = TRUE;
3037 if (!tls->suspended) {
3038 tls->suspended = TRUE;
3039 MONO_SEM_POST (&suspend_sem);
3042 DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
3044 while (suspend_count - tls->resume_count > 0) {
3046 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
3048 mono_mutex_unlock (&suspend_mutex);
3050 mono_mutex_lock (&suspend_mutex);
3056 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
3057 g_assert (err == 0);
3061 tls->suspended = FALSE;
3062 tls->really_suspended = FALSE;
3064 threads_suspend_count --;
3066 mono_mutex_unlock (&suspend_mutex);
3068 DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
3070 if (tls->pending_invoke) {
3071 /* Save the original context */
3072 tls->pending_invoke->has_ctx = TRUE;
3073 tls->pending_invoke->ctx = tls->context.ctx;
3078 /* The frame info becomes invalid after a resume */
3079 tls->context.valid = FALSE;
3080 tls->async_state.valid = FALSE;
3081 invalidate_frames (tls);
3085 count_thread (gpointer key, gpointer value, gpointer user_data)
3087 DebuggerTlsData *tls = value;
3089 if (!tls->suspended && !tls->terminated)
3090 *(int*)user_data = *(int*)user_data + 1;
3094 count_threads_to_wait_for (void)
3098 mono_loader_lock ();
3099 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
3100 mono_loader_unlock ();
3108 * Wait until the runtime is completely suspended.
3111 wait_for_suspend (void)
3113 int nthreads, nwait, err;
3114 gboolean waited = FALSE;
3116 // FIXME: Threads starting/stopping ?
3117 mono_loader_lock ();
3118 nthreads = mono_g_hash_table_size (thread_to_tls);
3119 mono_loader_unlock ();
3122 nwait = count_threads_to_wait_for ();
3124 DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
3125 err = MONO_SEM_WAIT (&suspend_sem);
3126 g_assert (err == 0);
3134 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
3140 * Return whenever the runtime is suspended.
3145 return count_threads_to_wait_for () == 0;
3148 static MonoSeqPointInfo*
3149 get_seq_points (MonoDomain *domain, MonoMethod *method)
3151 MonoSeqPointInfo *seq_points;
3153 mono_domain_lock (domain);
3154 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
3155 if (!seq_points && method->is_inflated) {
3156 /* generic sharing + aot */
3157 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (method));
3159 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mini_get_shared_method (method));
3161 mono_domain_unlock (domain);
3167 no_seq_points_found (MonoMethod *method)
3170 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3172 printf ("Unable to find seq points for method '%s'.\n", mono_method_full_name (method, TRUE));
3176 * find_next_seq_point_for_native_offset:
3178 * Find the first sequence point after NATIVE_OFFSET.
3181 find_next_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
3183 MonoSeqPointInfo *seq_points;
3186 seq_points = get_seq_points (domain, method);
3192 g_assert (seq_points);
3196 for (i = 0; i < seq_points->len; ++i) {
3197 if (seq_points->seq_points [i].native_offset >= native_offset)
3198 return &seq_points->seq_points [i];
3205 * find_prev_seq_point_for_native_offset:
3207 * Find the first sequence point before NATIVE_OFFSET.
3210 find_prev_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
3212 MonoSeqPointInfo *seq_points;
3215 seq_points = get_seq_points (domain, method);
3221 for (i = seq_points->len - 1; i >= 0; --i) {
3222 if (seq_points->seq_points [i].native_offset <= native_offset)
3223 return &seq_points->seq_points [i];
3232 * Find the sequence point corresponding to the IL offset IL_OFFSET, which
3233 * should be the location of a sequence point.
3235 static G_GNUC_UNUSED SeqPoint*
3236 find_seq_point (MonoDomain *domain, MonoMethod *method, gint32 il_offset, MonoSeqPointInfo **info)
3238 MonoSeqPointInfo *seq_points;
3243 seq_points = get_seq_points (domain, method);
3248 for (i = 0; i < seq_points->len; ++i) {
3249 if (seq_points->seq_points [i].il_offset == il_offset)
3250 return &seq_points->seq_points [i];
3257 DebuggerTlsData *tls;
3259 } ComputeFramesUserData;
3262 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3264 ComputeFramesUserData *ud = user_data;
3266 MonoMethod *method, *actual_method, *api_method;
3270 if (info->type != FRAME_TYPE_MANAGED) {
3271 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3272 /* Mark the last frame as an invoke frame */
3274 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3280 method = jinfo_get_method (info->ji);
3282 method = info->method;
3283 actual_method = info->actual_method;
3284 api_method = method;
3289 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3292 if (info->il_offset == -1) {
3293 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3294 if (ud->frames == NULL) {
3295 sp = find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL);
3297 info->il_offset = sp->il_offset;
3299 if (info->il_offset == -1)
3300 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3303 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));
3305 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3306 if (!CHECK_PROTOCOL_VERSION (2, 17))
3307 /* Older clients can't handle this flag */
3309 api_method = mono_marshal_method_from_wrapper (method);
3312 actual_method = api_method;
3313 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3316 frame = g_new0 (StackFrame, 1);
3317 frame->method = method;
3318 frame->actual_method = actual_method;
3319 frame->api_method = api_method;
3320 frame->il_offset = info->il_offset;
3321 frame->native_offset = info->native_offset;
3322 frame->flags = flags;
3323 frame->ji = info->ji;
3324 if (info->reg_locations)
3325 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3328 frame->has_ctx = TRUE;
3330 frame->domain = info->domain;
3332 ud->frames = g_slist_append (ud->frames, frame);
3338 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3340 ComputeFramesUserData *ud = user_data;
3343 * 'tls->filter_ctx' is the location of the throw site.
3345 * mono_walk_stack() will never actually hit the throw site, but unwind
3346 * directly from the filter to the call site; we abort stack unwinding here
3347 * once this happens and resume from the throw site.
3350 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3353 return process_frame (info, ctx, user_data);
3357 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3359 ComputeFramesUserData user_data;
3361 int i, findex, new_frame_count;
3362 StackFrame **new_frames, *f;
3363 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3365 // FIXME: Locking on tls
3366 if (tls->frames && tls->frames_up_to_date)
3369 DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
3371 user_data.tls = tls;
3372 user_data.frames = NULL;
3373 if (tls->terminated) {
3374 tls->frame_count = 0;
3376 } if (!tls->really_suspended && tls->async_state.valid) {
3377 /* Have to use the state saved by the signal handler */
3378 process_frame (&tls->async_last_frame, NULL, &user_data);
3379 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3380 } else if (tls->filter_state.valid) {
3382 * We are inside an exception filter.
3384 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3386 if (tls->context.valid)
3387 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3389 * After that, we resume unwinding from the location where the exception has been thrown.
3391 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3392 } else if (tls->context.valid) {
3393 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3396 tls->frame_count = 0;
3400 new_frame_count = g_slist_length (user_data.frames);
3401 new_frames = g_new0 (StackFrame*, new_frame_count);
3403 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3407 * Reuse the id for already existing stack frames, so invokes don't invalidate
3408 * the still valid stack frames.
3410 for (i = 0; i < tls->frame_count; ++i) {
3411 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3412 f->id = tls->frames [i]->id;
3417 if (i >= tls->frame_count)
3418 f->id = InterlockedIncrement (&frame_id);
3420 new_frames [findex ++] = f;
3423 g_slist_free (user_data.frames);
3425 invalidate_frames (tls);
3427 tls->frames = new_frames;
3428 tls->frame_count = new_frame_count;
3429 tls->frames_up_to_date = TRUE;
3433 * GHFunc to emit an appdomain creation event
3434 * @param key Don't care
3435 * @param value A loaded appdomain
3436 * @param user_data Don't care
3439 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3441 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3442 g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
3446 * GHFunc to emit a thread start event
3447 * @param key A thread id
3448 * @param value A thread object
3449 * @param user_data Don't care
3452 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3454 if (GPOINTER_TO_INT (key) != debugger_thread_id)
3455 process_profiler_event (EVENT_KIND_THREAD_START, value);
3459 * GFunc to emit an assembly load event
3460 * @param value A loaded assembly
3461 * @param user_data Don't care
3464 emit_assembly_load (gpointer value, gpointer user_data)
3466 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3470 * GFunc to emit a type load event
3471 * @param value A loaded type
3472 * @param user_data Don't care
3475 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3477 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3481 strdup_tolower (char *s)
3486 for (p = s2; *p; ++p)
3496 * create_event_list:
3498 * Return a list of event request ids matching EVENT, starting from REQS, which
3499 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3501 * We return request ids, instead of requests, to simplify threading, since
3502 * requests could be deleted anytime when the loader lock is not held.
3503 * LOCKING: Assumes the loader lock is held.
3506 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3509 GSList *events = NULL;
3511 *suspend_policy = SUSPEND_POLICY_NONE;
3514 reqs = event_requests;
3519 for (i = 0; i < reqs->len; ++i) {
3520 EventRequest *req = g_ptr_array_index (reqs, i);
3521 if (req->event_kind == event) {
3522 gboolean filtered = FALSE;
3525 for (j = 0; j < req->nmodifiers; ++j) {
3526 Modifier *mod = &req->modifiers [j];
3528 if (mod->kind == MOD_KIND_COUNT) {
3530 if (mod->data.count > 0) {
3531 if (mod->data.count > 0) {
3533 if (mod->data.count == 0)
3537 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3538 if (mod->data.thread != mono_thread_internal_current ())
3540 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3541 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3543 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3545 if (ei->caught && !mod->caught)
3547 if (!ei->caught && !mod->uncaught)
3549 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3551 gboolean found = FALSE;
3552 MonoAssembly **assemblies = mod->data.assemblies;
3555 for (k = 0; assemblies [k]; ++k)
3556 if (assemblies [k] == jinfo_get_method (ji)->klass->image->assembly)
3561 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3562 gpointer iter = NULL;
3564 MonoDebugSourceInfo *sinfo;
3565 char *source_file, *s;
3566 gboolean found = FALSE;
3568 GPtrArray *source_file_list;
3570 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3571 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3574 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
3575 for (i = 0; i < source_file_list->len; ++i) {
3576 sinfo = g_ptr_array_index (source_file_list, i);
3578 * Do a case-insesitive match by converting the file name to
3581 s = strdup_tolower (sinfo->source_file);
3582 if (g_hash_table_lookup (mod->data.source_files, s))
3585 char *s2 = g_path_get_basename (sinfo->source_file);
3586 char *s3 = strdup_tolower (s2);
3588 if (g_hash_table_lookup (mod->data.source_files, s3))
3595 g_ptr_array_free (source_file_list, TRUE);
3600 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3603 s = mono_type_full_name (&ei->klass->byval_arg);
3604 if (!g_hash_table_lookup (mod->data.type_names, s))
3607 } else if (mod->kind == MOD_KIND_STEP) {
3608 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3609 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3610 !strcmp (jinfo_get_method (ji)->name, ".cctor"))
3612 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3613 MonoCustomAttrInfo *ainfo;
3614 static MonoClass *klass;
3617 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3620 if (!ji->dbg_hidden_inited) {
3621 ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji));
3623 if (mono_custom_attrs_has_attr (ainfo, klass))
3624 ji->dbg_hidden = TRUE;
3625 mono_custom_attrs_free (ainfo);
3627 ji->dbg_hidden_inited = TRUE;
3632 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3633 MonoCustomAttrInfo *ainfo;
3634 static MonoClass *klass;
3637 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3640 if (!ji->dbg_step_through_inited) {
3641 ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji));
3643 if (mono_custom_attrs_has_attr (ainfo, klass))
3644 ji->dbg_step_through = TRUE;
3645 mono_custom_attrs_free (ainfo);
3647 ainfo = mono_custom_attrs_from_class (jinfo_get_method (ji)->klass);
3649 if (mono_custom_attrs_has_attr (ainfo, klass))
3650 ji->dbg_step_through = TRUE;
3651 mono_custom_attrs_free (ainfo);
3653 ji->dbg_step_through_inited = TRUE;
3655 if (ji->dbg_step_through)
3658 if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3659 MonoCustomAttrInfo *ainfo;
3660 static MonoClass *klass;
3663 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute");
3666 if (!ji->dbg_non_user_code_inited) {
3667 ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji));
3669 if (mono_custom_attrs_has_attr (ainfo, klass))
3670 ji->dbg_non_user_code = TRUE;
3671 mono_custom_attrs_free (ainfo);
3673 ainfo = mono_custom_attrs_from_class (jinfo_get_method (ji)->klass);
3675 if (mono_custom_attrs_has_attr (ainfo, klass))
3676 ji->dbg_non_user_code = TRUE;
3677 mono_custom_attrs_free (ainfo);
3679 ji->dbg_non_user_code_inited = TRUE;
3681 if (ji->dbg_non_user_code)
3688 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3689 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3694 /* Send a VM START/DEATH event by default */
3695 if (event == EVENT_KIND_VM_START)
3696 events = g_slist_append (events, GINT_TO_POINTER (0));
3697 if (event == EVENT_KIND_VM_DEATH)
3698 events = g_slist_append (events, GINT_TO_POINTER (0));
3703 static G_GNUC_UNUSED const char*
3704 event_to_string (EventKind event)
3707 case EVENT_KIND_VM_START: return "VM_START";
3708 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3709 case EVENT_KIND_THREAD_START: return "THREAD_START";
3710 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3711 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3712 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3713 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3714 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3715 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3716 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3717 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3718 case EVENT_KIND_STEP: return "STEP";
3719 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3720 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3721 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3722 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3723 case EVENT_KIND_USER_LOG: return "USER_LOG";
3725 g_assert_not_reached ();
3733 * Send an event to the client, suspending the vm if needed.
3734 * LOCKING: Since this can suspend the calling thread, no locks should be held
3736 * The EVENTS list is freed by this function.
3739 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3743 MonoDomain *domain = mono_domain_get ();
3744 MonoThread *thread = NULL;
3745 MonoObject *keepalive_obj = NULL;
3746 gboolean send_success = FALSE;
3751 DEBUG (2, fprintf (log_file, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event)));
3755 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3756 // FIXME: We miss those events
3757 DEBUG (2, fprintf (log_file, "VM start event not sent yet: dropping %s\n", event_to_string (event)));
3761 if (vm_death_event_sent) {
3762 DEBUG (2, fprintf (log_file, "VM death event has been sent: dropping %s\n", event_to_string (event)));
3766 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3767 DEBUG (2, fprintf (log_file, "Mono runtime is shutting down: dropping %s\n", event_to_string (event)));
3772 DEBUG (2, fprintf (log_file, "Debugger client is not connected: dropping %s\n", event_to_string (event)));
3776 if (event == EVENT_KIND_KEEPALIVE)
3777 suspend_policy = SUSPEND_POLICY_NONE;
3782 if (agent_config.defer) {
3783 /* Make sure the thread id is always set when doing deferred debugging */
3784 if (debugger_thread_id == GetCurrentThreadId ()) {
3785 /* Don't suspend on events from the debugger thread */
3786 suspend_policy = SUSPEND_POLICY_NONE;
3787 thread = mono_thread_get_main ();
3789 else thread = mono_thread_current ();
3791 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3792 // FIXME: Send these with a NULL thread, don't suspend the current thread
3797 nevents = g_slist_length (events);
3798 buffer_init (&buf, 128);
3799 buffer_add_byte (&buf, suspend_policy);
3800 buffer_add_int (&buf, nevents);
3802 for (l = events; l; l = l->next) {
3803 buffer_add_byte (&buf, event); // event kind
3804 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3809 thread = mono_thread_current ();
3811 if (event == EVENT_KIND_VM_START && arg != NULL)
3814 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3817 case EVENT_KIND_THREAD_START:
3818 case EVENT_KIND_THREAD_DEATH:
3820 case EVENT_KIND_APPDOMAIN_CREATE:
3821 case EVENT_KIND_APPDOMAIN_UNLOAD:
3822 buffer_add_domainid (&buf, arg);
3824 case EVENT_KIND_METHOD_ENTRY:
3825 case EVENT_KIND_METHOD_EXIT:
3826 buffer_add_methodid (&buf, domain, arg);
3828 case EVENT_KIND_ASSEMBLY_LOAD:
3829 buffer_add_assemblyid (&buf, domain, arg);
3831 case EVENT_KIND_ASSEMBLY_UNLOAD: {
3832 DebuggerTlsData *tls;
3834 /* The domain the assembly belonged to is not equal to the current domain */
3835 tls = mono_native_tls_get_value (debugger_tls_id);
3837 g_assert (tls->domain_unloading);
3839 buffer_add_assemblyid (&buf, tls->domain_unloading, arg);
3842 case EVENT_KIND_TYPE_LOAD:
3843 buffer_add_typeid (&buf, domain, arg);
3845 case EVENT_KIND_BREAKPOINT:
3846 case EVENT_KIND_STEP:
3847 buffer_add_methodid (&buf, domain, arg);
3848 buffer_add_long (&buf, il_offset);
3850 case EVENT_KIND_VM_START:
3851 buffer_add_domainid (&buf, mono_get_root_domain ());
3853 case EVENT_KIND_VM_DEATH:
3854 if (CHECK_PROTOCOL_VERSION (2, 27))
3855 buffer_add_int (&buf, mono_environment_exitcode_get ());
3857 case EVENT_KIND_EXCEPTION: {
3858 EventInfo *ei = arg;
3859 buffer_add_objid (&buf, ei->exc);
3861 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3862 * later after the suspension. (#12494).
3864 keepalive_obj = ei->exc;
3867 case EVENT_KIND_USER_BREAK:
3869 case EVENT_KIND_USER_LOG: {
3870 EventInfo *ei = arg;
3871 buffer_add_int (&buf, ei->level);
3872 buffer_add_string (&buf, ei->category ? ei->category : "");
3873 buffer_add_string (&buf, ei->message ? ei->message : "");
3876 case EVENT_KIND_KEEPALIVE:
3877 suspend_policy = SUSPEND_POLICY_NONE;
3880 g_assert_not_reached ();
3884 if (event == EVENT_KIND_VM_START) {
3885 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3886 if (!agent_config.defer)
3887 start_debugger_thread ();
3890 if (event == EVENT_KIND_VM_DEATH) {
3891 vm_death_event_sent = TRUE;
3892 suspend_policy = SUSPEND_POLICY_NONE;
3895 if (mono_runtime_is_shutting_down ())
3896 suspend_policy = SUSPEND_POLICY_NONE;
3898 if (suspend_policy != SUSPEND_POLICY_NONE) {
3900 * Save the thread context and start suspending before sending the packet,
3901 * since we could be receiving the resume request before send_packet ()
3904 save_thread_context (ctx);
3908 /* This will keep this object alive */
3909 get_objref (keepalive_obj);
3912 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3916 g_slist_free (events);
3919 if (!send_success) {
3920 DEBUG (2, fprintf (log_file, "Sending command %s failed.\n", event_to_string (event)));
3924 if (event == EVENT_KIND_VM_START) {
3925 vm_start_event_sent = TRUE;
3928 DEBUG (1, fprintf (log_file, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer)GetCurrentThreadId (), nevents, event_to_string (event), ecount, suspend_policy));
3930 switch (suspend_policy) {
3931 case SUSPEND_POLICY_NONE:
3933 case SUSPEND_POLICY_ALL:
3936 case SUSPEND_POLICY_EVENT_THREAD:
3940 g_assert_not_reached ();
3945 process_profiler_event (EventKind event, gpointer arg)
3949 EventInfo ei, *ei_arg = NULL;
3951 if (event == EVENT_KIND_TYPE_LOAD) {
3956 mono_loader_lock ();
3957 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3958 mono_loader_unlock ();
3960 process_event (event, arg, 0, NULL, events, suspend_policy);
3964 runtime_initialized (MonoProfiler *prof)
3966 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3967 if (agent_config.defer)
3968 start_debugger_thread ();
3972 runtime_shutdown (MonoProfiler *prof)
3974 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3976 mono_debugger_agent_cleanup ();
3980 thread_startup (MonoProfiler *prof, uintptr_t tid)
3982 MonoInternalThread *thread = mono_thread_internal_current ();
3983 MonoInternalThread *old_thread;
3984 DebuggerTlsData *tls;
3986 if (tid == debugger_thread_id)
3989 g_assert (thread->tid == tid);
3991 mono_loader_lock ();
3992 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3993 mono_loader_unlock ();
3995 if (thread == old_thread) {
3997 * For some reason, thread_startup () might be called for the same thread
3998 * multiple times (attach ?).
4000 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
4004 * thread_end () might not be called for some threads, and the tid could
4007 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
4008 mono_loader_lock ();
4009 mono_g_hash_table_remove (thread_to_tls, old_thread);
4010 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
4011 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
4012 mono_loader_unlock ();
4016 tls = mono_native_tls_get_value (debugger_tls_id);
4018 // FIXME: Free this somewhere
4019 tls = g_new0 (DebuggerTlsData, 1);
4020 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
4021 tls->thread = thread;
4022 mono_native_tls_set_value (debugger_tls_id, tls);
4024 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
4026 mono_loader_lock ();
4027 mono_g_hash_table_insert (thread_to_tls, thread, tls);
4028 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
4029 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
4030 mono_loader_unlock ();
4032 process_profiler_event (EVENT_KIND_THREAD_START, thread);
4035 * suspend_vm () could have missed this thread, so wait for a resume.
4041 thread_end (MonoProfiler *prof, uintptr_t tid)
4043 MonoInternalThread *thread;
4044 DebuggerTlsData *tls = NULL;
4046 mono_loader_lock ();
4047 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
4049 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
4050 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4052 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
4053 tls->terminated = TRUE;
4054 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
4055 MONO_GC_UNREGISTER_ROOT (tls->thread);
4059 mono_loader_unlock ();
4061 /* We might be called for threads started before we registered the start callback */
4063 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
4064 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
4069 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
4071 mono_loader_lock ();
4072 g_hash_table_insert (domains, domain, domain);
4073 mono_loader_unlock ();
4075 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
4079 appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain)
4081 DebuggerTlsData *tls;
4083 /* This might be called during shutdown on the debugger thread from the CMD_VM_EXIT code */
4084 if (is_debugger_thread ())
4088 * Remember the currently unloading appdomain as it is needed to generate
4089 * proper ids for unloading assemblies.
4091 tls = mono_native_tls_get_value (debugger_tls_id);
4093 tls->domain_unloading = domain;
4097 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
4099 DebuggerTlsData *tls;
4101 if (is_debugger_thread ())
4104 tls = mono_native_tls_get_value (debugger_tls_id);
4106 tls->domain_unloading = NULL;
4108 clear_breakpoints_for_domain (domain);
4110 mono_loader_lock ();
4111 /* Invalidate each thread's frame stack */
4112 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
4113 mono_loader_unlock ();
4115 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
4119 * invalidate_each_thread:
4121 * A GHFunc to invalidate frames.
4122 * value must be a DebuggerTlsData*
4125 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
4127 invalidate_frames (value);
4131 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
4133 /* Sent later in jit_end () */
4135 g_ptr_array_add (pending_assembly_loads, assembly);
4140 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
4142 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
4144 clear_event_requests_for_assembly (assembly);
4145 clear_types_for_assembly (assembly);
4149 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
4151 #if defined(HOST_WIN32) && !defined(__GNUC__)
4152 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
4154 gpointer stackptr = __builtin_frame_address (1);
4156 MonoInternalThread *thread = mono_thread_internal_current ();
4157 DebuggerTlsData *tls;
4159 mono_loader_lock ();
4161 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4162 /* Could be the debugger thread with assembly/type load hooks */
4164 tls->invoke_addr = stackptr;
4166 mono_loader_unlock ();
4170 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
4173 #if defined(HOST_WIN32) && !defined(__GNUC__)
4174 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
4176 gpointer stackptr = __builtin_frame_address (1);
4179 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
4183 * We need to stop single stepping when exiting a runtime invoke, since if it is
4184 * a step out, it may return to native code, and thus never end.
4186 mono_loader_lock ();
4187 ss_invoke_addr = NULL;
4189 for (i = 0; i < event_requests->len; ++i) {
4190 EventRequest *req = g_ptr_array_index (event_requests, i);
4192 if (req->event_kind == EVENT_KIND_STEP) {
4193 ss_destroy (req->info);
4194 g_ptr_array_remove_index_fast (event_requests, i);
4199 mono_loader_unlock ();
4203 send_type_load (MonoClass *klass)
4205 gboolean type_load = FALSE;
4206 MonoDomain *domain = mono_domain_get ();
4207 AgentDomainInfo *info = NULL;
4209 mono_loader_lock ();
4210 mono_domain_lock (domain);
4212 info = get_agent_domain_info (domain);
4214 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
4216 g_hash_table_insert (info->loaded_classes, klass, klass);
4219 mono_domain_unlock (domain);
4220 mono_loader_unlock ();
4222 emit_type_load (klass, klass, NULL);
4226 * Emit load events for all types currently loaded in the domain.
4227 * Takes the loader and domain locks.
4228 * user_data is unused.
4231 send_types_for_domain (MonoDomain *domain, void *user_data)
4233 AgentDomainInfo *info = NULL;
4235 mono_loader_lock ();
4236 mono_domain_lock (domain);
4237 info = get_agent_domain_info (domain);
4239 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4240 mono_domain_unlock (domain);
4241 mono_loader_unlock ();
4245 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
4248 * We emit type load events when the first method of the type is JITted,
4249 * since the class load profiler callbacks might be called with the
4250 * loader lock held. They could also occur in the debugger thread.
4251 * Same for assembly load events.
4254 MonoAssembly *assembly = NULL;
4256 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4258 if (pending_assembly_loads->len > 0) {
4259 assembly = g_ptr_array_index (pending_assembly_loads, 0);
4260 g_ptr_array_remove_index (pending_assembly_loads, 0);
4265 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4271 send_type_load (method->klass);
4274 add_pending_breakpoints (method, jinfo);
4278 * BREAKPOINTS/SINGLE STEPPING
4282 * Contains information about an inserted breakpoint.
4285 long il_offset, native_offset;
4290 } BreakpointInstance;
4293 * Contains generic information about a breakpoint.
4297 * The method where the breakpoint is placed. Can be NULL in which case it
4298 * is inserted into every method. This is used to implement method entry/
4299 * exit events. Can be a generic method definition, in which case the
4300 * breakpoint is inserted into every instance.
4306 * A list of BreakpointInstance structures describing where the breakpoint
4307 * was inserted. There could be more than one because of
4308 * generics/appdomains/method entry/exit.
4310 GPtrArray *children;
4313 /* List of breakpoints */
4314 static GPtrArray *breakpoints;
4315 /* Maps breakpoint locations to the number of breakpoints at that location */
4316 static GHashTable *bp_locs;
4319 breakpoints_init (void)
4321 breakpoints = g_ptr_array_new ();
4322 bp_locs = g_hash_table_new (NULL, NULL);
4326 * insert_breakpoint:
4328 * Insert the breakpoint described by BP into the method described by
4332 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4335 BreakpointInstance *inst;
4336 SeqPoint *sp = NULL;
4339 mono_error_init (error);
4341 for (i = 0; i < seq_points->len; ++i) {
4342 sp = &seq_points->seq_points [i];
4344 if (sp->il_offset == bp->il_offset)
4348 if (i == seq_points->len) {
4350 * The set of IL offsets with seq points doesn't completely match the
4351 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4353 for (i = 0; i < seq_points->len; ++i) {
4354 sp = &seq_points->seq_points [i];
4356 if (sp->il_offset != METHOD_ENTRY_IL_OFFSET && sp->il_offset != METHOD_EXIT_IL_OFFSET && sp->il_offset + 1 == bp->il_offset)
4361 if (i == seq_points->len) {
4362 char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d, seq_points=%d\n", mono_method_full_name (jinfo_get_method (ji), TRUE), bp->il_offset, seq_points->len);
4364 for (i = 0; i < seq_points->len; ++i)
4365 DEBUG (1, fprintf (log_file, "%d\n", seq_points->seq_points [i].il_offset));
4368 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4369 g_warning ("%s", s);
4373 g_warning ("%s", s);
4379 inst = g_new0 (BreakpointInstance, 1);
4381 inst->native_offset = sp->native_offset;
4382 inst->ip = (guint8*)ji->code_start + sp->native_offset;
4384 inst->domain = domain;
4386 mono_loader_lock ();
4388 g_ptr_array_add (bp->children, inst);
4390 mono_loader_unlock ();
4393 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4394 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4397 if (sp->native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4398 DEBUG (1, fprintf (log_file, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset));
4399 } else if (count == 0) {
4400 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4401 mono_arch_set_breakpoint (ji, inst->ip);
4407 DEBUG(1, fprintf (log_file, "[dbg] Inserted breakpoint at %s:0x%x [%p](%d).\n", mono_method_full_name (jinfo_get_method (ji), TRUE), (int)sp->il_offset, inst->ip, count));
4411 remove_breakpoint (BreakpointInstance *inst)
4413 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4415 MonoJitInfo *ji = inst->ji;
4416 guint8 *ip = inst->ip;
4419 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4420 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4423 g_assert (count > 0);
4425 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4426 mono_arch_clear_breakpoint (ji, ip);
4427 DEBUG(1, fprintf (log_file, "[dbg] Clear breakpoint at %s [%p].\n", mono_method_full_name (jinfo_get_method (ji), TRUE), ip));
4434 static inline gboolean
4435 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4441 if (method == bp->method)
4443 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4446 if (bp->method->is_inflated && method->is_inflated) {
4447 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4448 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4450 /* Open generic methods should match closed generic methods of the same class */
4451 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4452 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4453 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4455 /* FIXME: Handle !mvar */
4456 if (t1->type != MONO_TYPE_MVAR)
4467 * add_pending_breakpoints:
4469 * Insert pending breakpoints into the newly JITted method METHOD.
4472 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4475 MonoSeqPointInfo *seq_points;
4477 MonoMethod *jmethod;
4482 domain = mono_domain_get ();
4484 mono_loader_lock ();
4486 for (i = 0; i < breakpoints->len; ++i) {
4487 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4488 gboolean found = FALSE;
4490 if (!bp_matches_method (bp, method))
4493 for (j = 0; j < bp->children->len; ++j) {
4494 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4501 jmethod = jinfo_get_method (ji);
4502 mono_domain_lock (domain);
4503 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, jmethod);
4504 if (!seq_points && jmethod->is_inflated)
4505 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (jmethod));
4506 mono_domain_unlock (domain);
4508 /* Could be AOT code */
4510 g_assert (seq_points);
4512 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4516 mono_loader_unlock ();
4520 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4526 mono_error_init (error);
4528 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4530 /* Might be AOTed code */
4531 code = mono_aot_get_method (domain, method);
4533 ji = mono_jit_info_table_find (domain, code);
4538 insert_breakpoint (seq_points, domain, ji, bp, error);
4542 clear_breakpoint (MonoBreakpoint *bp);
4547 * Set a breakpoint at IL_OFFSET in METHOD.
4548 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4549 * METHOD can also be a generic method definition, in which case a breakpoint
4550 * is placed in all instances of the method.
4551 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4554 static MonoBreakpoint*
4555 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4558 GHashTableIter iter, iter2;
4561 MonoSeqPointInfo *seq_points;
4564 mono_error_init (error);
4567 // - suspend/resume the vm to prevent code patching problems
4568 // - multiple breakpoints on the same location
4569 // - dynamic methods
4572 bp = g_new0 (MonoBreakpoint, 1);
4573 bp->method = method;
4574 bp->il_offset = il_offset;
4576 bp->children = g_ptr_array_new ();
4578 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));
4580 mono_loader_lock ();
4582 g_hash_table_iter_init (&iter, domains);
4583 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4584 mono_domain_lock (domain);
4586 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4587 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4588 if (bp_matches_method (bp, m))
4589 set_bp_in_method (domain, m, seq_points, bp, error);
4592 mono_domain_unlock (domain);
4595 mono_loader_unlock ();
4597 mono_loader_lock ();
4598 g_ptr_array_add (breakpoints, bp);
4599 mono_loader_unlock ();
4601 if (error && !mono_error_ok (error)) {
4602 clear_breakpoint (bp);
4610 clear_breakpoint (MonoBreakpoint *bp)
4614 // FIXME: locking, races
4615 for (i = 0; i < bp->children->len; ++i) {
4616 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4618 remove_breakpoint (inst);
4623 mono_loader_lock ();
4624 g_ptr_array_remove (breakpoints, bp);
4625 mono_loader_unlock ();
4627 g_ptr_array_free (bp->children, TRUE);
4632 breakpoints_cleanup (void)
4636 mono_loader_lock ();
4638 while (i < event_requests->len) {
4639 EventRequest *req = g_ptr_array_index (event_requests, i);
4641 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4642 clear_breakpoint (req->info);
4643 g_ptr_array_remove_index_fast (event_requests, i);
4650 for (i = 0; i < breakpoints->len; ++i)
4651 g_free (g_ptr_array_index (breakpoints, i));
4653 g_ptr_array_free (breakpoints, TRUE);
4654 g_hash_table_destroy (bp_locs);
4659 mono_loader_unlock ();
4663 * clear_breakpoints_for_domain:
4665 * Clear breakpoint instances which reference DOMAIN.
4668 clear_breakpoints_for_domain (MonoDomain *domain)
4672 /* This could be called after shutdown */
4676 mono_loader_lock ();
4677 for (i = 0; i < breakpoints->len; ++i) {
4678 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4681 while (j < bp->children->len) {
4682 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4684 if (inst->domain == domain) {
4685 remove_breakpoint (inst);
4689 g_ptr_array_remove_index_fast (bp->children, j);
4695 mono_loader_unlock ();
4701 * Return FALSE if single stepping needs to continue.
4704 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp, DebuggerTlsData *tls, MonoContext *ctx)
4706 MonoDebugMethodInfo *minfo;
4707 MonoDebugSourceLocation *loc = NULL;
4708 gboolean hit = TRUE;
4711 if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK)) {
4713 * These seq points are inserted by the JIT after calls, step over needs to skip them.
4715 DEBUG (1, fprintf (log_file, "[%p] Seq point at nonempty stack %x while stepping over, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset));
4719 if (req->depth == STEP_DEPTH_OVER && hit) {
4720 if (!tls->context.valid)
4721 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4722 compute_frame_info (tls->thread, tls);
4723 if (req->nframes && tls->frame_count && tls->frame_count > req->nframes) {
4724 /* Hit the breakpoint in a recursive call */
4725 DEBUG (1, fprintf (log_file, "[%p] Breakpoint at lower frame while stepping over, continuing single stepping.\n", (gpointer)GetCurrentThreadId ()));
4730 if (req->size != STEP_SIZE_LINE)
4733 /* Have to check whenever a different source line was reached */
4734 method = jinfo_get_method (ji);
4735 minfo = mono_debug_lookup_method (method);
4738 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4740 if (!loc || (loc && method == ss_req->last_method && loc->row == ss_req->last_line)) {
4741 /* Have to continue single stepping */
4743 DEBUG(1, fprintf (log_file, "[%p] No line number info for il offset %x, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset));
4745 DEBUG(1, fprintf (log_file, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer)GetCurrentThreadId (), loc->row));
4750 ss_req->last_method = method;
4751 ss_req->last_line = loc->row;
4752 mono_debug_free_source_location (loc);
4759 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4761 return bp->method && bp->method->klass->image->assembly == assembly;
4765 process_breakpoint_inner (DebuggerTlsData *tls)
4769 int i, j, suspend_policy;
4770 guint32 native_offset;
4772 BreakpointInstance *inst;
4773 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4774 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4775 EventKind kind = EVENT_KIND_BREAKPOINT;
4776 MonoContext *ctx = &tls->restore_ctx;
4778 MonoSeqPointInfo *info;
4781 // FIXME: Speed this up
4783 ip = MONO_CONTEXT_GET_IP (ctx);
4784 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4786 method = jinfo_get_method (ji);
4788 /* Compute the native offset of the breakpoint from the ip */
4789 native_offset = ip - (guint8*)ji->code_start;
4792 * Skip the instruction causing the breakpoint signal.
4794 mono_arch_skip_breakpoint (ctx, ji);
4796 if (method->wrapper_type || tls->disable_breakpoints)
4799 bp_reqs = g_ptr_array_new ();
4800 ss_reqs = g_ptr_array_new ();
4801 ss_reqs_orig = g_ptr_array_new ();
4803 mono_loader_lock ();
4806 * The ip points to the instruction causing the breakpoint event, which is after
4807 * the offset recorded in the seq point map, so find the prev seq point before ip.
4809 sp = find_prev_seq_point_for_native_offset (mono_domain_get (), method, native_offset, &info);
4811 no_seq_points_found (method);
4814 DEBUG(1, fprintf (log_file, "[%p] Breakpoint hit, method=%s, ip=%p, offset=0x%x, sp il offset=0x%x.\n", (gpointer)GetCurrentThreadId (), method->name, ip, native_offset, sp ? sp->il_offset : -1));
4817 for (i = 0; i < breakpoints->len; ++i) {
4818 bp = g_ptr_array_index (breakpoints, i);
4823 for (j = 0; j < bp->children->len; ++j) {
4824 inst = g_ptr_array_index (bp->children, j);
4825 if (inst->ji == ji && inst->sp == sp) {
4826 if (bp->req->event_kind == EVENT_KIND_STEP) {
4827 g_ptr_array_add (ss_reqs_orig, bp->req);
4829 g_ptr_array_add (bp_reqs, bp->req);
4834 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4835 /* Maybe a method entry/exit event */
4836 if (sp->il_offset == METHOD_ENTRY_IL_OFFSET)
4837 kind = EVENT_KIND_METHOD_ENTRY;
4838 else if (sp->il_offset == METHOD_EXIT_IL_OFFSET)
4839 kind = EVENT_KIND_METHOD_EXIT;
4842 /* Process single step requests */
4843 for (i = 0; i < ss_reqs_orig->len; ++i) {
4844 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4845 SingleStepReq *ss_req = req->info;
4848 if (mono_thread_internal_current () != ss_req->thread)
4851 hit = ss_update (ss_req, ji, sp, tls, ctx);
4853 g_ptr_array_add (ss_reqs, req);
4855 /* Start single stepping again from the current sequence point */
4856 ss_start (ss_req, method, sp, info, ctx, tls, FALSE);
4859 if (ss_reqs->len > 0)
4860 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4861 if (bp_reqs->len > 0)
4862 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4863 if (kind != EVENT_KIND_BREAKPOINT)
4864 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4866 mono_loader_unlock ();
4868 g_ptr_array_free (bp_reqs, TRUE);
4869 g_ptr_array_free (ss_reqs, TRUE);
4872 * FIXME: The first event will suspend, so the second will only be sent after the
4876 process_event (EVENT_KIND_STEP, method, 0, ctx, ss_events, suspend_policy);
4878 process_event (kind, method, 0, ctx, bp_events, suspend_policy);
4879 if (enter_leave_events)
4880 process_event (kind, method, 0, ctx, enter_leave_events, suspend_policy);
4883 /* Process a breakpoint/single step event after resuming from a signal handler */
4885 process_signal_event (void (*func) (DebuggerTlsData*))
4887 DebuggerTlsData *tls;
4888 MonoContext orig_restore_ctx, ctx;
4890 tls = mono_native_tls_get_value (debugger_tls_id);
4891 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4892 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4893 memcpy (&tls->restore_ctx, &tls->handler_ctx, sizeof (MonoContext));
4897 /* This is called when resuming from a signal handler, so it shouldn't return */
4898 memcpy (&ctx, &tls->restore_ctx, sizeof (MonoContext));
4899 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4900 mono_restore_context (&ctx);
4901 g_assert_not_reached ();
4905 process_breakpoint (void)
4907 process_signal_event (process_breakpoint_inner);
4911 resume_from_signal_handler (void *sigctx, void *func)
4913 DebuggerTlsData *tls;
4916 /* Save the original context in TLS */
4917 // FIXME: This might not work on an altstack ?
4918 tls = mono_native_tls_get_value (debugger_tls_id);
4920 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer)GetCurrentThreadId ());
4923 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4924 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4925 // clob:c could be added to op_seq_point.
4927 mono_sigctx_to_monoctx (sigctx, &ctx);
4928 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4929 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4930 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4932 MONO_CONTEXT_SET_IP (&ctx, func);
4934 mono_monoctx_to_sigctx (&ctx, sigctx);
4936 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4937 mono_ppc_set_func_into_sigctx (sigctx, func);
4942 mono_debugger_agent_breakpoint_hit (void *sigctx)
4945 * We are called from a signal handler, and running code there causes all kinds of
4946 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4947 * So set up the signal context to return to the real breakpoint handler function.
4949 resume_from_signal_handler (sigctx, process_breakpoint);
4953 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4955 if (frame->managed) {
4956 *(MonoContext*)data = *ctx;
4965 * Called by System.Diagnostics.Debugger:Break ().
4968 mono_debugger_agent_user_break (void)
4970 if (agent_config.enabled) {
4975 /* Obtain a context */
4976 MONO_CONTEXT_SET_IP (&ctx, NULL);
4977 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4978 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4980 mono_loader_lock ();
4981 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4982 mono_loader_unlock ();
4984 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4991 ss_depth_to_string (StepDepth depth)
4994 case STEP_DEPTH_OVER:
4996 case STEP_DEPTH_OUT:
4998 case STEP_DEPTH_INTO:
5001 g_assert_not_reached ();
5007 process_single_step_inner (DebuggerTlsData *tls)
5012 int il_offset, suspend_policy;
5015 MonoContext *ctx = &tls->restore_ctx;
5018 MonoSeqPointInfo *info;
5020 ip = MONO_CONTEXT_GET_IP (ctx);
5022 /* Skip the instruction causing the single step */
5023 mono_arch_skip_single_step (ctx);
5025 if (suspend_count > 0) {
5026 process_suspend (tls, ctx);
5031 // FIXME: A suspend race
5034 if (mono_thread_internal_current () != ss_req->thread)
5037 if (log_level > 0) {
5038 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
5040 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));
5043 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
5045 method = jinfo_get_method (ji);
5048 if (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
5053 * Stopping in memset makes half-initialized vtypes visible.
5054 * Stopping in memcpy makes half-copied vtypes visible.
5056 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
5060 * The ip points to the instruction causing the single step event, which is before
5061 * the offset recorded in the seq point map, so find the next seq point after ip.
5063 sp = find_next_seq_point_for_native_offset (domain, method, (guint8*)ip - (guint8*)ji->code_start, &info);
5066 il_offset = sp->il_offset;
5068 if (!ss_update (ss_req, ji, sp, tls, ctx))
5071 /* Start single stepping again from the current sequence point */
5072 ss_start (ss_req, method, sp, info, ctx, tls, FALSE);
5074 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
5075 (method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
5076 !strcmp (method->name, ".cctor"))
5079 // FIXME: Has to lock earlier
5081 reqs = g_ptr_array_new ();
5083 mono_loader_lock ();
5085 g_ptr_array_add (reqs, ss_req->req);
5087 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
5089 g_ptr_array_free (reqs, TRUE);
5091 mono_loader_unlock ();
5093 process_event (EVENT_KIND_STEP, jinfo_get_method (ji), il_offset, ctx, events, suspend_policy);
5097 process_single_step (void)
5099 process_signal_event (process_single_step_inner);
5103 * mono_debugger_agent_single_step_event:
5105 * Called from a signal handler to handle a single step event.
5108 mono_debugger_agent_single_step_event (void *sigctx)
5110 /* Resume to process_single_step through the signal context */
5112 // FIXME: Since step out/over is implemented using step in, the step in case should
5113 // be as fast as possible. Move the relevant code from process_single_step_inner ()
5116 if (GetCurrentThreadId () == debugger_thread_id) {
5118 * This could happen despite our best effors when the runtime calls
5119 * assembly/type resolve hooks.
5120 * FIXME: Breakpoints too.
5124 mono_sigctx_to_monoctx (sigctx, &ctx);
5125 mono_arch_skip_single_step (&ctx);
5126 mono_monoctx_to_sigctx (&ctx, sigctx);
5130 resume_from_signal_handler (sigctx, process_single_step);
5134 debugger_agent_single_step_from_context (MonoContext *ctx)
5136 DebuggerTlsData *tls;
5137 MonoContext orig_restore_ctx;
5139 tls = mono_native_tls_get_value (debugger_tls_id);
5142 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
5143 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
5144 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
5146 process_single_step_inner (tls);
5148 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
5149 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
5153 debugger_agent_breakpoint_from_context (MonoContext *ctx)
5155 DebuggerTlsData *tls;
5156 MonoContext orig_restore_ctx;
5158 tls = mono_native_tls_get_value (debugger_tls_id);
5160 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
5161 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
5163 process_breakpoint_inner (tls);
5165 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
5166 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
5170 * start_single_stepping:
5172 * Turn on single stepping. Can be called multiple times, for example,
5173 * by a single step event request + a suspend.
5176 start_single_stepping (void)
5178 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5179 int val = InterlockedIncrement (&ss_count);
5182 mono_arch_start_single_stepping ();
5184 if (ss_req != NULL && ss_invoke_addr == NULL) {
5185 DebuggerTlsData *tls;
5187 mono_loader_lock ();
5189 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
5190 ss_invoke_addr = tls->invoke_addr;
5192 mono_loader_unlock ();
5195 g_assert_not_reached ();
5200 stop_single_stepping (void)
5202 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5203 int val = InterlockedDecrement (&ss_count);
5206 mono_arch_stop_single_stepping ();
5208 ss_invoke_addr = NULL;
5210 g_assert_not_reached ();
5217 * Stop the single stepping operation given by SS_REQ.
5220 ss_stop (SingleStepReq *ss_req)
5225 for (l = ss_req->bps; l; l = l->next) {
5226 clear_breakpoint (l->data);
5228 g_slist_free (ss_req->bps);
5232 if (ss_req->global) {
5233 stop_single_stepping ();
5234 ss_req->global = FALSE;
5241 * Start the single stepping operation given by SS_REQ from the sequence point SP.
5242 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
5243 * belong to the same thread as CTX.
5246 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
5248 int i, j, frame_index;
5251 gboolean enable_global = FALSE;
5253 /* Stop the previous operation */
5257 * Implement single stepping using breakpoints if possible.
5259 if (step_to_catch) {
5260 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
5261 ss_req->bps = g_slist_append (ss_req->bps, bp);
5265 if ((!sp || sp->next_len == 0 || ss_req->depth == STEP_DEPTH_OUT || ss_req->depth == STEP_DEPTH_OVER) && ctx) {
5266 /* Need parent frames */
5267 if (!tls->context.valid)
5268 mono_thread_state_init_from_monoctx (&tls->context, ctx);
5269 compute_frame_info (tls->thread, tls);
5273 * Find the first sequence point in the current or in a previous frame which
5274 * is not the last in its method.
5276 if (ss_req->depth == STEP_DEPTH_OUT) {
5277 /* Ignore seq points in current method */
5278 while (frame_index < tls->frame_count) {
5279 StackFrame *frame = tls->frames [frame_index];
5281 method = frame->method;
5282 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5284 if (sp && sp->next_len != 0)
5287 // There could be method calls before the next seq point in the caller when using nested calls
5288 //enable_global = TRUE;
5290 if (sp && sp->next_len == 0) {
5292 while (frame_index < tls->frame_count) {
5293 StackFrame *frame = tls->frames [frame_index];
5295 method = frame->method;
5296 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5297 if (sp && sp->next_len != 0)
5305 if (sp && sp->next_len > 0) {
5306 for (i = 0; i < sp->next_len; ++i) {
5307 next_sp = &info->seq_points [sp->next [i]];
5309 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
5310 ss_req->bps = g_slist_append (ss_req->bps, bp);
5314 if (ss_req->depth == STEP_DEPTH_OVER) {
5315 if (ss_req->nframes == 0)
5316 ss_req->nframes = tls->frame_count;
5317 /* Need to stop in catch clauses as well */
5318 for (i = 0; i < tls->frame_count; ++i) {
5319 StackFrame *frame = tls->frames [i];
5322 MonoJitInfo *jinfo = frame->ji;
5323 for (j = 0; j < jinfo->num_clauses; ++j) {
5324 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5326 sp = find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL);
5328 bp = set_breakpoint (frame->method, sp->il_offset, ss_req->req, NULL);
5329 ss_req->bps = g_slist_append (ss_req->bps, bp);
5337 if (ss_req->depth == STEP_DEPTH_INTO) {
5338 /* Enable global stepping so we stop at method entry too */
5339 enable_global = TRUE;
5343 * The ctx/frame info computed above will become invalid when we continue.
5345 tls->context.valid = FALSE;
5346 tls->async_state.valid = FALSE;
5347 invalidate_frames (tls);
5350 if (enable_global) {
5351 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
5352 ss_req->global = TRUE;
5353 start_single_stepping ();
5354 } else if (!ss_req->bps) {
5355 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
5356 ss_req->global = TRUE;
5357 start_single_stepping ();
5359 ss_req->global = FALSE;
5364 * Start single stepping of thread THREAD
5367 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
5369 DebuggerTlsData *tls;
5370 MonoSeqPointInfo *info = NULL;
5371 SeqPoint *sp = NULL;
5372 MonoMethod *method = NULL;
5373 MonoDebugMethodInfo *minfo;
5374 gboolean step_to_catch = FALSE;
5376 if (suspend_count == 0)
5377 return ERR_NOT_SUSPENDED;
5379 wait_for_suspend ();
5381 // FIXME: Multiple requests
5383 DEBUG (0, fprintf (log_file, "Received a single step request while the previous one was still active.\n"));
5384 return ERR_NOT_IMPLEMENTED;
5387 DEBUG (1, fprintf (log_file, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
5389 ss_req = g_new0 (SingleStepReq, 1);
5391 ss_req->thread = thread;
5392 ss_req->size = size;
5393 ss_req->depth = depth;
5396 mono_loader_lock ();
5397 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5398 mono_loader_unlock ();
5400 g_assert (tls->context.valid);
5401 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5403 if (tls->catch_state.valid) {
5405 StackFrameInfo frame;
5406 MonoContext new_ctx;
5407 MonoLMF *lmf = NULL;
5410 * We are stopped at a throw site. Stepping should go to the catch site.
5413 /* Find the the jit info for the catch context */
5414 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);
5416 g_assert (frame.type == FRAME_TYPE_MANAGED);
5419 * Find the seq point corresponding to the landing site ip, which is the first seq
5422 sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
5424 no_seq_points_found (frame.method);
5427 method = frame.method;
5429 step_to_catch = TRUE;
5430 /* This make sure the seq point is not skipped by process_single_step () */
5431 ss_req->last_sp = NULL;
5434 if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
5437 /* Compute the initial line info */
5438 compute_frame_info (thread, tls);
5440 if (tls->frame_count) {
5441 frame = tls->frames [0];
5443 ss_req->last_method = frame->method;
5444 ss_req->last_line = -1;
5446 minfo = mono_debug_lookup_method (frame->method);
5447 if (minfo && frame->il_offset != -1) {
5448 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
5451 ss_req->last_line = loc->row;
5458 if (!step_to_catch) {
5461 compute_frame_info (thread, tls);
5463 if (tls->frame_count) {
5464 frame = tls->frames [0];
5466 if (!method && frame->il_offset != -1) {
5467 /* FIXME: Sort the table and use a binary search */
5468 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5470 no_seq_points_found (frame->method);
5472 method = frame->method;
5477 ss_start (ss_req, method, sp, info, &tls->context.ctx, tls, step_to_catch);
5483 ss_destroy (SingleStepReq *req)
5486 g_assert (ss_req == req);
5495 ss_clear_for_assembly (SingleStepReq *req, MonoAssembly *assembly)
5498 gboolean found = TRUE;
5502 for (l = ss_req->bps; l; l = l->next) {
5503 if (breakpoint_matches_assembly (l->data, assembly)) {
5504 clear_breakpoint (l->data);
5505 ss_req->bps = g_slist_delete_link (ss_req->bps, l);
5514 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5517 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5523 if (!agent_config.enabled)
5526 mono_loader_lock ();
5527 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5528 mono_loader_unlock ();
5531 ei.category = category ? mono_string_to_utf8 (category) : NULL;
5532 ei.message = message ? mono_string_to_utf8 (message) : NULL;
5534 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5536 g_free (ei.category);
5537 g_free (ei.message);
5541 mono_debugger_agent_debug_log_is_enabled (void)
5543 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5544 return agent_config.enabled;
5547 #if defined(PLATFORM_ANDROID) || defined(TARGET_ANDROID)
5549 mono_debugger_agent_unhandled_exception (MonoException *exc)
5558 memset (&ei, 0, sizeof (EventInfo));
5559 ei.exc = (MonoObject*)exc;
5561 mono_loader_lock ();
5562 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5563 mono_loader_unlock ();
5565 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5570 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5571 MonoContext *catch_ctx)
5573 int i, j, suspend_policy;
5575 MonoJitInfo *ji, *catch_ji;
5577 DebuggerTlsData *tls = NULL;
5579 if (thread_to_tls != NULL) {
5580 MonoInternalThread *thread = mono_thread_internal_current ();
5582 mono_loader_lock ();
5583 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5584 mono_loader_unlock ();
5586 if (tls && tls->abort_requested)
5588 if (tls && tls->disable_breakpoints)
5592 memset (&ei, 0, sizeof (EventInfo));
5594 /* Just-In-Time debugging */
5596 if (agent_config.onuncaught && !inited) {
5597 finish_agent_init (FALSE);
5600 * Send an unsolicited EXCEPTION event with a dummy request id.
5602 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5603 ei.exc = (MonoObject*)exc;
5604 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5607 } else if (agent_config.onthrow && !inited) {
5609 gboolean found = FALSE;
5611 for (l = agent_config.onthrow; l; l = l->next) {
5612 char *ex_type = l->data;
5613 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5615 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5622 finish_agent_init (FALSE);
5625 * Send an unsolicited EXCEPTION event with a dummy request id.
5627 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5628 ei.exc = (MonoObject*)exc;
5629 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5637 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5639 catch_ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5643 ei.exc = (MonoObject*)exc;
5644 ei.caught = catch_ctx != NULL;
5646 mono_loader_lock ();
5648 /* Treat exceptions which are caught in non-user code as unhandled */
5649 for (i = 0; i < event_requests->len; ++i) {
5650 EventRequest *req = g_ptr_array_index (event_requests, i);
5651 if (req->event_kind != EVENT_KIND_EXCEPTION)
5654 for (j = 0; j < req->nmodifiers; ++j) {
5655 Modifier *mod = &req->modifiers [j];
5657 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5659 gboolean found = FALSE;
5660 MonoAssembly **assemblies = mod->data.assemblies;
5663 for (k = 0; assemblies [k]; ++k)
5664 if (assemblies [k] == jinfo_get_method (catch_ji)->klass->image->assembly)
5673 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5674 mono_loader_unlock ();
5676 if (tls && ei.caught && catch_ctx) {
5677 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5678 tls->catch_state.ctx = *catch_ctx;
5679 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5680 tls->catch_state.valid = TRUE;
5683 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5686 tls->catch_state.valid = FALSE;
5690 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5692 DebuggerTlsData *tls;
5697 tls = mono_native_tls_get_value (debugger_tls_id);
5702 * We're about to invoke an exception filter during the first pass of exception handling.
5704 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5705 * 'orig_ctx' is the context where the exception has been thrown.
5708 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5710 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5711 * the call site (line 37) and then continue to Main(), but it would never
5712 * include the throw site (line 32).
5714 * Since exception filters are invoked during the first pass of exception handling,
5715 * the stack frames of the throw site are still intact, so we should include them
5718 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5720 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5721 * but report the location of the 'throw' to the user.
5725 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5729 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5731 DebuggerTlsData *tls;
5736 tls = mono_native_tls_get_value (debugger_tls_id);
5740 tls->filter_state.valid = FALSE;
5744 * buffer_add_value_full:
5746 * Add the encoding of the value at ADDR described by T to the buffer.
5747 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5751 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5752 gboolean as_vtype, GHashTable *parent_vtypes)
5755 gboolean boxed_vtype = FALSE;
5758 if (!(*(void**)addr)) {
5759 /* This can happen with compiler generated locals */
5760 //printf ("%s\n", mono_type_full_name (t));
5761 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5764 g_assert (*(void**)addr);
5765 addr = *(void**)addr;
5770 case MONO_TYPE_BOOLEAN:
5773 case MONO_TYPE_CHAR:
5793 case MONO_TYPE_VOID:
5794 buffer_add_byte (buf, t->type);
5796 case MONO_TYPE_BOOLEAN:
5799 buffer_add_byte (buf, t->type);
5800 buffer_add_int (buf, *(gint8*)addr);
5802 case MONO_TYPE_CHAR:
5805 buffer_add_byte (buf, t->type);
5806 buffer_add_int (buf, *(gint16*)addr);
5811 buffer_add_byte (buf, t->type);
5812 buffer_add_int (buf, *(gint32*)addr);
5817 buffer_add_byte (buf, t->type);
5818 buffer_add_long (buf, *(gint64*)addr);
5822 /* Treat it as a vtype */
5824 case MONO_TYPE_PTR: {
5825 gssize val = *(gssize*)addr;
5827 buffer_add_byte (buf, t->type);
5828 buffer_add_long (buf, val);
5832 case MONO_TYPE_STRING:
5833 case MONO_TYPE_SZARRAY:
5834 case MONO_TYPE_OBJECT:
5835 case MONO_TYPE_CLASS:
5836 case MONO_TYPE_ARRAY:
5837 obj = *(MonoObject**)addr;
5840 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5842 if (obj->vtable->klass->valuetype) {
5843 t = &obj->vtable->klass->byval_arg;
5844 addr = mono_object_unbox (obj);
5847 } else if (obj->vtable->klass->rank) {
5848 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5849 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5850 buffer_add_byte (buf, MONO_TYPE_CLASS);
5852 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5854 buffer_add_objid (buf, obj);
5858 case MONO_TYPE_VALUETYPE: {
5862 MonoClass *klass = mono_class_from_mono_type (t);
5867 * Handle boxed vtypes recursively referencing themselves using fields.
5870 parent_vtypes = g_hash_table_new (NULL, NULL);
5871 vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
5873 if (CHECK_PROTOCOL_VERSION (2, 33)) {
5874 buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
5875 buffer_add_int (buf, vtype_index - 1);
5877 /* The client can't handle PARENT_VTYPE */
5878 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5882 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
5886 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5887 buffer_add_byte (buf, klass->enumtype);
5888 buffer_add_typeid (buf, domain, klass);
5892 while ((f = mono_class_get_fields (klass, &iter))) {
5893 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5895 if (mono_field_is_deleted (f))
5899 buffer_add_int (buf, nfields);
5902 while ((f = mono_class_get_fields (klass, &iter))) {
5903 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5905 if (mono_field_is_deleted (f))
5907 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE, parent_vtypes);
5911 g_hash_table_remove (parent_vtypes, addr);
5912 if (g_hash_table_size (parent_vtypes) == 0) {
5913 g_hash_table_destroy (parent_vtypes);
5914 parent_vtypes = NULL;
5919 case MONO_TYPE_GENERICINST:
5920 if (mono_type_generic_inst_is_valuetype (t)) {
5932 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5934 buffer_add_value_full (buf, t, addr, domain, FALSE, NULL);
5938 obj_is_of_type (MonoObject *obj, MonoType *t)
5940 MonoClass *klass = obj->vtable->klass;
5941 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5942 if (mono_class_is_transparent_proxy (klass)) {
5943 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5944 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5954 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5957 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5963 gpointer iter = NULL;
5967 is_enum = decode_byte (buf, &buf, limit);
5968 /* Enums are sent as a normal vtype */
5970 return ERR_NOT_IMPLEMENTED;
5971 klass = decode_typeid (buf, &buf, limit, &d, &err);
5975 if (t && klass != mono_class_from_mono_type (t)) {
5976 char *name = mono_type_full_name (t);
5977 char *name2 = mono_type_full_name (&klass->byval_arg);
5978 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got %s.\n", (gpointer)GetCurrentThreadId (), name, name2));
5981 return ERR_INVALID_ARGUMENT;
5984 nfields = decode_int (buf, &buf, limit);
5985 while ((f = mono_class_get_fields (klass, &iter))) {
5986 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5988 if (mono_field_is_deleted (f))
5990 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5995 g_assert (nfields == 0);
6003 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6007 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
6008 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
6009 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
6010 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
6011 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
6012 char *name = mono_type_full_name (t);
6013 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
6015 return ERR_INVALID_ARGUMENT;
6019 case MONO_TYPE_BOOLEAN:
6020 *(guint8*)addr = decode_int (buf, &buf, limit);
6022 case MONO_TYPE_CHAR:
6023 *(gunichar2*)addr = decode_int (buf, &buf, limit);
6026 *(gint8*)addr = decode_int (buf, &buf, limit);
6029 *(guint8*)addr = decode_int (buf, &buf, limit);
6032 *(gint16*)addr = decode_int (buf, &buf, limit);
6035 *(guint16*)addr = decode_int (buf, &buf, limit);
6038 *(gint32*)addr = decode_int (buf, &buf, limit);
6041 *(guint32*)addr = decode_int (buf, &buf, limit);
6044 *(gint64*)addr = decode_long (buf, &buf, limit);
6047 *(guint64*)addr = decode_long (buf, &buf, limit);
6050 *(guint32*)addr = decode_int (buf, &buf, limit);
6053 *(guint64*)addr = decode_long (buf, &buf, limit);
6056 /* We send these as I8, so we get them back as such */
6057 g_assert (type == MONO_TYPE_I8);
6058 *(gssize*)addr = decode_long (buf, &buf, limit);
6060 case MONO_TYPE_GENERICINST:
6061 if (MONO_TYPE_ISSTRUCT (t)) {
6062 /* The client sends these as a valuetype */
6070 /* We send these as vtypes, so we get them back as such */
6071 g_assert (type == MONO_TYPE_VALUETYPE);
6074 case MONO_TYPE_VALUETYPE:
6075 err = decode_vtype (t, domain, addr,buf, &buf, limit);
6081 if (MONO_TYPE_IS_REFERENCE (t)) {
6082 if (type == MONO_TYPE_OBJECT) {
6083 int objid = decode_objid (buf, &buf, limit);
6087 err = get_object (objid, (MonoObject**)&obj);
6092 if (!obj_is_of_type (obj, t)) {
6093 DEBUG (1, fprintf (log_file, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name));
6094 return ERR_INVALID_ARGUMENT;
6097 if (obj && obj->vtable->domain != domain)
6098 return ERR_INVALID_ARGUMENT;
6100 mono_gc_wbarrier_generic_store (addr, obj);
6101 } else if (type == VALUE_TYPE_ID_NULL) {
6102 *(MonoObject**)addr = NULL;
6103 } else if (type == MONO_TYPE_VALUETYPE) {
6111 /* This can happen when round-tripping boxed vtypes */
6113 * Obtain vtype class.
6114 * Same as the beginning of the handle_vtype case above.
6117 is_enum = decode_byte (buf, &buf, limit);
6119 return ERR_NOT_IMPLEMENTED;
6120 klass = decode_typeid (buf, &buf, limit, &d, &err);
6124 /* Decode the vtype into a temporary buffer, then box it. */
6125 vtype_buf_size = mono_class_value_size (klass, NULL);
6126 vtype_buf = g_malloc0 (vtype_buf_size);
6127 g_assert (vtype_buf);
6130 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
6135 *(MonoObject**)addr = mono_value_box (d, klass, vtype_buf);
6138 char *name = mono_type_full_name (t);
6139 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
6141 return ERR_INVALID_ARGUMENT;
6155 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6158 int type = decode_byte (buf, &buf, limit);
6160 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
6161 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
6162 guint8 *nullable_buf;
6165 * First try decoding it as a Nullable`1
6167 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6172 * Then try decoding as a primitive value or null.
6174 if (targ->type == type) {
6175 nullable_buf = g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
6176 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
6178 g_free (nullable_buf);
6181 mono_nullable_init (addr, mono_value_box (domain, mono_class_from_mono_type (targ), nullable_buf), mono_class_from_mono_type (t));
6182 g_free (nullable_buf);
6185 } else if (type == VALUE_TYPE_ID_NULL) {
6186 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
6192 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6196 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
6200 guint8 *addr, *gaddr;
6203 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6204 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6207 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
6208 reg_val = mono_arch_context_get_int_reg (ctx, reg);
6210 buffer_add_value_full (buf, t, ®_val, domain, as_vtype, NULL);
6212 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6213 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6214 addr += (gint32)var->offset;
6216 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6218 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6220 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6223 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6224 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
6225 /* Same as regoffset, but with an indirection */
6226 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6227 addr += (gint32)var->offset;
6229 gaddr = *(gpointer*)addr;
6231 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL);
6233 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
6234 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
6235 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
6236 MonoGSharedVtMethodRuntimeInfo *info;
6242 g_assert (info_var);
6243 g_assert (locals_var);
6245 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6246 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6247 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6248 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6249 addr += (gint32)info_var->offset;
6250 info = *(gpointer*)addr;
6251 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6252 info = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6254 g_assert_not_reached ();
6258 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6259 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6260 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6261 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6262 addr += (gint32)locals_var->offset;
6263 locals = *(gpointer*)addr;
6264 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6265 locals = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6267 g_assert_not_reached ();
6271 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6273 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6278 g_assert_not_reached ();
6283 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
6287 guint8 *addr, *gaddr;
6289 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6290 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6292 if (MONO_TYPE_IS_REFERENCE (t))
6293 size = sizeof (gpointer);
6295 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6298 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6299 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6301 gboolean is_signed = FALSE;
6304 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6307 // FIXME: Write barriers
6308 mono_gc_memmove_atomic (addr, val, size);
6313 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6318 v = is_signed ? *(gint8*)val : *(guint8*)val;
6321 v = is_signed ? *(gint16*)val : *(guint16*)val;
6324 v = is_signed ? *(gint32*)val : *(guint32*)val;
6327 v = is_signed ? *(gint64*)val : *(guint64*)val;
6330 g_assert_not_reached ();
6333 /* Set value on the stack or in the return ctx */
6334 if (reg_locations [reg]) {
6335 /* Saved on the stack */
6336 DEBUG (1, fprintf (log_file, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v));
6337 *(reg_locations [reg]) = v;
6340 DEBUG (1, fprintf (log_file, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v));
6341 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6344 // FIXME: Move these to mono-context.h/c.
6345 mono_arch_context_set_int_reg (ctx, reg, v);
6347 // FIXME: Can't set registers, so we disable linears
6352 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6353 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6354 addr += (gint32)var->offset;
6356 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6359 addr = *(guint8**)addr;
6365 // FIXME: Write barriers
6366 mono_gc_memmove_atomic (addr, val, size);
6368 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6369 /* Same as regoffset, but with an indirection */
6370 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6371 addr += (gint32)var->offset;
6373 gaddr = *(gpointer*)addr;
6375 // FIXME: Write barriers
6376 mono_gc_memmove_atomic (gaddr, val, size);
6378 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6382 g_assert_not_reached ();
6387 clear_event_request (int req_id, int etype)
6391 mono_loader_lock ();
6392 for (i = 0; i < event_requests->len; ++i) {
6393 EventRequest *req = g_ptr_array_index (event_requests, i);
6395 if (req->id == req_id && req->event_kind == etype) {
6396 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6397 clear_breakpoint (req->info);
6398 if (req->event_kind == EVENT_KIND_STEP)
6399 ss_destroy (req->info);
6400 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6401 clear_breakpoint (req->info);
6402 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6403 clear_breakpoint (req->info);
6404 g_ptr_array_remove_index_fast (event_requests, i);
6409 mono_loader_unlock ();
6413 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
6417 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6418 m->kind = MOD_KIND_NONE;
6419 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6420 int count = 0, match_count = 0, pos;
6421 MonoAssembly **newassemblies;
6423 for (i = 0; m->data.assemblies [i]; ++i) {
6425 if (m->data.assemblies [i] == assembly)
6430 newassemblies = g_new0 (MonoAssembly*, count - match_count);
6433 for (i = 0; i < count; ++i)
6434 if (m->data.assemblies [i] != assembly)
6435 newassemblies [pos ++] = m->data.assemblies [i];
6436 g_assert (pos == count - match_count);
6437 g_free (m->data.assemblies);
6438 m->data.assemblies = newassemblies;
6444 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
6448 for (i = 0; i < req->nmodifiers; ++i) {
6449 Modifier *m = &req->modifiers [i];
6451 clear_assembly_from_modifier (req, m, assembly);
6456 * clear_event_requests_for_assembly:
6458 * Clear all events requests which reference ASSEMBLY.
6461 clear_event_requests_for_assembly (MonoAssembly *assembly)
6466 mono_loader_lock ();
6470 for (i = 0; i < event_requests->len; ++i) {
6471 EventRequest *req = g_ptr_array_index (event_requests, i);
6473 clear_assembly_from_modifiers (req, assembly);
6475 if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly (req->info, assembly)) {
6476 clear_event_request (req->id, req->event_kind);
6481 if (req->event_kind == EVENT_KIND_STEP)
6482 ss_clear_for_assembly (req->info, assembly);
6485 mono_loader_unlock ();
6489 * type_comes_from_assembly:
6491 * GHRFunc that returns TRUE if klass comes from assembly
6494 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6496 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6500 * clear_types_for_assembly:
6502 * Clears types from loaded_classes for a given assembly
6505 clear_types_for_assembly (MonoAssembly *assembly)
6507 MonoDomain *domain = mono_domain_get ();
6508 AgentDomainInfo *info = NULL;
6510 mono_loader_lock ();
6511 info = get_agent_domain_info (domain);
6512 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6513 mono_loader_unlock ();
6517 add_thread (gpointer key, gpointer value, gpointer user_data)
6519 MonoInternalThread *thread = value;
6520 Buffer *buf = user_data;
6522 buffer_add_objid (buf, (MonoObject*)thread);
6526 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6528 guint8 *end = invoke->endp;
6531 MonoMethodSignature *sig;
6534 MonoObject *this, *res, *exc;
6537 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6540 MonoStopwatch watch;
6542 if (invoke->method) {
6544 * Invoke this method directly, currently only Environment.Exit () is supported.
6547 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>"));
6548 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
6549 g_assert_not_reached ();
6552 m = decode_methodid (p, &p, end, &domain, &err);
6555 sig = mono_method_signature (m);
6557 if (m->klass->valuetype)
6558 this_buf = g_alloca (mono_class_instance_size (m->klass));
6560 this_buf = g_alloca (sizeof (MonoObject*));
6561 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6562 /* Should be null */
6563 int type = decode_byte (p, &p, end);
6564 if (type != VALUE_TYPE_ID_NULL) {
6565 DEBUG (1, fprintf (log_file, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer)GetCurrentThreadId ()));
6566 return ERR_INVALID_ARGUMENT;
6568 memset (this_buf, 0, mono_class_instance_size (m->klass));
6570 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6575 if (!m->klass->valuetype)
6576 this = *(MonoObject**)this_buf;
6580 if (MONO_CLASS_IS_INTERFACE (m->klass)) {
6582 DEBUG (1, fprintf (log_file, "[%p] Error: Interface method invoked without this argument.\n", (gpointer)GetCurrentThreadId ()));
6583 return ERR_INVALID_ARGUMENT;
6585 m = mono_object_get_virtual_method (this, m);
6586 } else if (invoke->flags & INVOKE_FLAG_VIRTUAL) {
6588 DEBUG (1, fprintf (log_file, "[%p] Error: invoke with INVOKE_FLAG_VIRTUAL flag set without this argument.\n", (gpointer)GetCurrentThreadId ()));
6589 return ERR_INVALID_ARGUMENT;
6591 m = mono_object_get_virtual_method (this, m);
6594 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>"));
6596 if (this && this->vtable->domain != domain)
6599 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
6600 if (!strcmp (m->name, ".ctor")) {
6601 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
6602 return ERR_INVALID_ARGUMENT;
6604 this = mono_object_new (domain, m->klass);
6606 return ERR_INVALID_ARGUMENT;
6610 if (this && !obj_is_of_type (this, &m->klass->byval_arg))
6611 return ERR_INVALID_ARGUMENT;
6613 nargs = decode_int (p, &p, end);
6614 if (nargs != sig->param_count)
6615 return ERR_INVALID_ARGUMENT;
6616 /* Use alloca to get gc tracking */
6617 arg_buf = g_alloca (nargs * sizeof (gpointer));
6618 memset (arg_buf, 0, nargs * sizeof (gpointer));
6619 args = g_alloca (nargs * sizeof (gpointer));
6620 for (i = 0; i < nargs; ++i) {
6621 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6622 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6625 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6628 if (sig->params [i]->byref) {
6629 arg_buf [i] = g_alloca (sizeof (mgreg_t));
6630 *(gpointer*)arg_buf [i] = args [i];
6631 args [i] = arg_buf [i];
6634 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6635 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6638 args [i] = arg_buf [i];
6645 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6646 tls->disable_breakpoints = TRUE;
6648 tls->disable_breakpoints = FALSE;
6651 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6653 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6654 if (invoke->has_ctx) {
6657 lmf_addr = mono_get_lmf_addr ();
6660 memset (&ext, 0, sizeof (ext));
6661 mono_arch_init_lmf_ext (&ext, *lmf_addr);
6663 ext.debugger_invoke = TRUE;
6664 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6666 mono_set_lmf ((MonoLMF*)&ext);
6670 mono_stopwatch_start (&watch);
6671 if (m->klass->valuetype)
6672 res = mono_runtime_invoke (m, this_buf, args, &exc);
6674 res = mono_runtime_invoke (m, this, args, &exc);
6675 mono_stopwatch_stop (&watch);
6676 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)));
6678 buffer_add_byte (buf, 0);
6679 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6681 gboolean out_this = FALSE;
6682 gboolean out_args = FALSE;
6684 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_THIS) && CHECK_PROTOCOL_VERSION (2, 35))
6686 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_ARGS) && CHECK_PROTOCOL_VERSION (2, 35))
6688 buffer_add_byte (buf, 1 + (out_this ? 2 : 0) + (out_args ? 4 : 0));
6689 if (sig->ret->type == MONO_TYPE_VOID) {
6690 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
6691 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
6694 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6695 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6696 buffer_add_value (buf, sig->ret, &res, domain);
6697 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6698 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6699 MonoClass *k = mono_class_from_mono_type (sig->ret);
6700 guint8 *nullable_buf = g_alloca (mono_class_value_size (k, NULL));
6702 g_assert (nullable_buf);
6703 mono_nullable_init (nullable_buf, res, k);
6704 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6707 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6713 /* Return the new value of the receiver after the call */
6714 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
6716 buffer_add_int (buf, nargs);
6717 for (i = 0; i < nargs; ++i) {
6718 if (MONO_TYPE_IS_REFERENCE (sig->params [i]))
6719 buffer_add_value (buf, sig->params [i], &args [i], domain);
6720 else if (sig->params [i]->byref)
6721 /* add_value () does an indirection */
6722 buffer_add_value (buf, sig->params [i], &arg_buf [i], domain);
6724 buffer_add_value (buf, sig->params [i], arg_buf [i], domain);
6729 tls->disable_breakpoints = FALSE;
6731 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6732 if (invoke->has_ctx)
6733 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
6737 // FIXME: byref arguments
6745 * Invoke the method given by tls->pending_invoke in the current thread.
6748 invoke_method (void)
6750 DebuggerTlsData *tls;
6755 MonoContext restore_ctx;
6758 tls = mono_native_tls_get_value (debugger_tls_id);
6762 * Store the `InvokeData *' in `tls->invoke' until we're done with
6763 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6766 mono_loader_lock ();
6768 invoke = tls->pending_invoke;
6770 tls->pending_invoke = NULL;
6772 invoke->last_invoke = tls->invoke;
6773 tls->invoke = invoke;
6775 mono_loader_unlock ();
6777 tls->frames_up_to_date = FALSE;
6783 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6784 buffer_init (&buf, 128);
6787 /* Fail the other invokes as well */
6789 err = do_invoke_method (tls, &buf, invoke, p, &p);
6792 /* Start suspending before sending the reply */
6793 if (mindex == invoke->nmethods - 1) {
6794 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6795 for (i = 0; i < invoke->suspend_count; ++i)
6800 send_reply_packet (id, err, &buf);
6805 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6807 if (invoke->has_ctx)
6808 save_thread_context (&restore_ctx);
6810 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6811 g_assert (tls->resume_count);
6812 tls->resume_count -= invoke->suspend_count;
6815 DEBUG (1, fprintf (log_file, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer)GetCurrentThreadId (), err, tls->resume_count));
6818 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6820 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
6821 * after the mono_runtime_invoke() already returned, but it doesn't matter
6822 * because we reset the abort here.
6825 mono_loader_lock ();
6827 if (tls->abort_requested)
6828 mono_thread_internal_reset_abort (tls->thread);
6830 tls->invoke = tls->invoke->last_invoke;
6831 tls->abort_requested = FALSE;
6833 mono_loader_unlock ();
6842 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6844 MonoThread *thread = value;
6845 DebuggerTlsData *tls;
6848 mono_loader_lock ();
6849 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6851 res = tls->really_suspended;
6852 mono_loader_unlock ();
6858 get_source_files_for_type (MonoClass *klass)
6860 gpointer iter = NULL;
6862 MonoDebugSourceInfo *sinfo;
6866 files = g_ptr_array_new ();
6868 while ((method = mono_class_get_methods (klass, &iter))) {
6869 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6870 GPtrArray *source_file_list;
6873 mono_debug_symfile_get_line_numbers_full (minfo, NULL, &source_file_list, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
6874 for (j = 0; j < source_file_list->len; ++j) {
6875 sinfo = g_ptr_array_index (source_file_list, j);
6876 for (i = 0; i < files->len; ++i)
6877 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6879 if (i == files->len)
6880 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6882 g_ptr_array_free (source_file_list, TRUE);
6890 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6893 case CMD_VM_VERSION: {
6894 char *build_info, *version;
6896 build_info = mono_get_runtime_build_info ();
6897 version = g_strdup_printf ("mono %s", build_info);
6899 buffer_add_string (buf, version); /* vm version */
6900 buffer_add_int (buf, MAJOR_VERSION);
6901 buffer_add_int (buf, MINOR_VERSION);
6902 g_free (build_info);
6906 case CMD_VM_SET_PROTOCOL_VERSION: {
6907 major_version = decode_int (p, &p, end);
6908 minor_version = decode_int (p, &p, end);
6909 protocol_version_set = TRUE;
6910 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
6913 case CMD_VM_ALL_THREADS: {
6915 mono_loader_lock ();
6916 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6917 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6918 mono_loader_unlock ();
6921 case CMD_VM_SUSPEND:
6923 wait_for_suspend ();
6926 if (suspend_count == 0)
6927 return ERR_NOT_SUSPENDED;
6929 clear_suspended_objs ();
6931 case CMD_VM_DISPOSE:
6932 /* Clear all event requests */
6933 mono_loader_lock ();
6934 while (event_requests->len > 0) {
6935 EventRequest *req = g_ptr_array_index (event_requests, 0);
6937 clear_event_request (req->id, req->event_kind);
6939 mono_loader_unlock ();
6941 while (suspend_count > 0)
6943 disconnected = TRUE;
6944 vm_start_event_sent = FALSE;
6947 MonoInternalThread *thread;
6948 DebuggerTlsData *tls;
6949 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6950 MonoClass *env_class;
6952 MonoMethod *exit_method = NULL;
6956 exit_code = decode_int (p, &p, end);
6958 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6960 /* Have to send a reply before exiting */
6961 send_reply_packet (id, 0, buf);
6963 /* Clear all event requests */
6964 mono_loader_lock ();
6965 while (event_requests->len > 0) {
6966 EventRequest *req = g_ptr_array_index (event_requests, 0);
6968 clear_event_request (req->id, req->event_kind);
6970 mono_loader_unlock ();
6973 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6974 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6975 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6976 * better than doing the shutdown ourselves, since it avoids various races.
6980 wait_for_suspend ();
6982 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6983 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
6985 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6988 mono_loader_lock ();
6989 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6990 mono_loader_unlock ();
6992 if (thread && exit_method) {
6993 mono_loader_lock ();
6994 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6995 mono_loader_unlock ();
6997 args = g_new0 (gpointer, 1);
6998 args [0] = g_malloc (sizeof (int));
6999 *(int*)(args [0]) = exit_code;
7001 tls->pending_invoke = g_new0 (InvokeData, 1);
7002 tls->pending_invoke->method = exit_method;
7003 tls->pending_invoke->args = args;
7004 tls->pending_invoke->nmethods = 1;
7006 while (suspend_count > 0)
7010 * No thread found, do it ourselves.
7011 * FIXME: This can race with normal shutdown etc.
7013 while (suspend_count > 0)
7016 if (!mono_runtime_try_shutdown ())
7019 mono_environment_exitcode_set (exit_code);
7021 /* Suspend all managed threads since the runtime is going away */
7022 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
7023 mono_thread_suspend_all_other_threads ();
7024 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
7025 mono_runtime_quit ();
7026 transport_close2 ();
7027 DEBUG(1, fprintf (log_file, "Exiting...\n"));
7033 case CMD_VM_INVOKE_METHOD:
7034 case CMD_VM_INVOKE_METHODS: {
7035 int objid = decode_objid (p, &p, end);
7037 DebuggerTlsData *tls;
7038 int i, count, err, flags, nmethods;
7040 err = get_object (objid, (MonoObject**)&thread);
7044 flags = decode_int (p, &p, end);
7046 if (command == CMD_VM_INVOKE_METHODS)
7047 nmethods = decode_int (p, &p, end);
7051 // Wait for suspending if it already started
7053 wait_for_suspend ();
7054 if (!is_suspended ())
7055 return ERR_NOT_SUSPENDED;
7057 mono_loader_lock ();
7058 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7059 mono_loader_unlock ();
7062 if (!tls->really_suspended)
7063 /* The thread is still running native code, can't do invokes */
7064 return ERR_NOT_SUSPENDED;
7067 * Store the invoke data into tls, the thread will execute it after it is
7070 if (tls->pending_invoke)
7071 return ERR_NOT_SUSPENDED;
7072 tls->pending_invoke = g_new0 (InvokeData, 1);
7073 tls->pending_invoke->id = id;
7074 tls->pending_invoke->flags = flags;
7075 tls->pending_invoke->p = g_malloc (end - p);
7076 memcpy (tls->pending_invoke->p, p, end - p);
7077 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
7078 tls->pending_invoke->suspend_count = suspend_count;
7079 tls->pending_invoke->nmethods = nmethods;
7081 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
7082 resume_thread (THREAD_TO_INTERNAL (thread));
7085 count = suspend_count;
7086 for (i = 0; i < count; ++i)
7091 case CMD_VM_ABORT_INVOKE: {
7092 int objid = decode_objid (p, &p, end);
7094 DebuggerTlsData *tls;
7097 err = get_object (objid, (MonoObject**)&thread);
7101 invoke_id = decode_int (p, &p, end);
7103 mono_loader_lock ();
7104 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7107 if (tls->abort_requested) {
7108 mono_loader_unlock ();
7113 * Check whether we're still inside the mono_runtime_invoke() and that it's
7114 * actually the correct invocation.
7116 * Careful, we do not stop the thread that's doing the invocation, so we can't
7117 * inspect its stack. However, invoke_method() also acquires the loader lock
7118 * when it's done, so we're safe here.
7122 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
7123 mono_loader_unlock ();
7124 return ERR_NO_INVOCATION;
7127 tls->abort_requested = TRUE;
7129 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
7130 mono_loader_unlock ();
7134 case CMD_VM_SET_KEEPALIVE: {
7135 int timeout = decode_int (p, &p, end);
7136 agent_config.keepalive = timeout;
7138 #ifndef DISABLE_SOCKET_TRANSPORT
7145 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
7146 GHashTableIter iter, kiter;
7151 char *fname, *basename;
7152 gboolean ignore_case;
7153 GSList *class_list, *l;
7154 GPtrArray *res_classes, *res_domains;
7156 fname = decode_string (p, &p, end);
7157 ignore_case = decode_byte (p, &p, end);
7159 basename = g_path_get_basename (fname);
7161 res_classes = g_ptr_array_new ();
7162 res_domains = g_ptr_array_new ();
7164 mono_loader_lock ();
7165 g_hash_table_iter_init (&iter, domains);
7166 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7167 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
7169 /* Update 'source_file_to_class' cache */
7170 g_hash_table_iter_init (&kiter, info->loaded_classes);
7171 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
7172 if (!g_hash_table_lookup (info->source_files, klass)) {
7173 files = get_source_files_for_type (klass);
7174 g_hash_table_insert (info->source_files, klass, files);
7176 for (i = 0; i < files->len; ++i) {
7177 char *s = g_ptr_array_index (files, i);
7178 char *s2 = g_path_get_basename (s);
7181 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
7183 class_list = g_slist_prepend (class_list, klass);
7184 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
7186 class_list = g_slist_prepend (class_list, klass);
7187 g_hash_table_insert (info->source_file_to_class, s2, class_list);
7190 /* The _ignorecase hash contains the lowercase path */
7191 s3 = strdup_tolower (s2);
7192 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
7194 class_list = g_slist_prepend (class_list, klass);
7195 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
7197 class_list = g_slist_prepend (class_list, klass);
7198 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
7210 s = strdup_tolower (basename);
7211 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
7214 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
7217 for (l = class_list; l; l = l->next) {
7220 g_ptr_array_add (res_classes, klass);
7221 g_ptr_array_add (res_domains, domain);
7224 mono_loader_unlock ();
7229 buffer_add_int (buf, res_classes->len);
7230 for (i = 0; i < res_classes->len; ++i)
7231 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
7232 g_ptr_array_free (res_classes, TRUE);
7233 g_ptr_array_free (res_domains, TRUE);
7236 case CMD_VM_GET_TYPES: {
7237 GHashTableIter iter;
7241 gboolean ignore_case;
7242 GPtrArray *res_classes, *res_domains;
7243 MonoTypeNameParse info;
7245 name = decode_string (p, &p, end);
7246 ignore_case = decode_byte (p, &p, end);
7248 if (!mono_reflection_parse_type (name, &info)) {
7250 mono_reflection_free_type_info (&info);
7251 return ERR_INVALID_ARGUMENT;
7254 res_classes = g_ptr_array_new ();
7255 res_domains = g_ptr_array_new ();
7257 mono_loader_lock ();
7258 g_hash_table_iter_init (&iter, domains);
7259 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7261 gboolean type_resolve;
7265 mono_domain_assemblies_lock (domain);
7266 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7270 type_resolve = TRUE;
7271 t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
7273 g_ptr_array_add (res_classes, mono_type_get_class (t));
7274 g_ptr_array_add (res_domains, domain);
7278 mono_domain_assemblies_unlock (domain);
7280 mono_loader_unlock ();
7283 mono_reflection_free_type_info (&info);
7285 buffer_add_int (buf, res_classes->len);
7286 for (i = 0; i < res_classes->len; ++i)
7287 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
7288 g_ptr_array_free (res_classes, TRUE);
7289 g_ptr_array_free (res_domains, TRUE);
7292 case CMD_VM_START_BUFFERING:
7293 case CMD_VM_STOP_BUFFERING:
7294 /* Handled in the main loop */
7297 return ERR_NOT_IMPLEMENTED;
7304 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7310 case CMD_EVENT_REQUEST_SET: {
7312 int i, event_kind, suspend_policy, nmodifiers, mod;
7315 MonoThread *step_thread;
7316 int size = 0, depth = 0, filter = 0, step_thread_id = 0;
7320 event_kind = decode_byte (p, &p, end);
7321 suspend_policy = decode_byte (p, &p, end);
7322 nmodifiers = decode_byte (p, &p, end);
7324 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7325 req->id = InterlockedIncrement (&event_request_id);
7326 req->event_kind = event_kind;
7327 req->suspend_policy = suspend_policy;
7328 req->nmodifiers = nmodifiers;
7331 for (i = 0; i < nmodifiers; ++i) {
7332 mod = decode_byte (p, &p, end);
7334 req->modifiers [i].kind = mod;
7335 if (mod == MOD_KIND_COUNT) {
7336 req->modifiers [i].data.count = decode_int (p, &p, end);
7337 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7338 method = decode_methodid (p, &p, end, &domain, &err);
7341 location = decode_long (p, &p, end);
7342 } else if (mod == MOD_KIND_STEP) {
7343 step_thread_id = decode_id (p, &p, end);
7344 size = decode_int (p, &p, end);
7345 depth = decode_int (p, &p, end);
7346 if (CHECK_PROTOCOL_VERSION (2, 16))
7347 filter = decode_int (p, &p, end);
7348 req->modifiers [i].data.filter = filter;
7349 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7350 /* Treat STEP_THOUGH the same as HIDDEN */
7351 req->modifiers [i].data.filter |= STEP_FILTER_DEBUGGER_STEP_THROUGH;
7352 } else if (mod == MOD_KIND_THREAD_ONLY) {
7353 int id = decode_id (p, &p, end);
7355 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7360 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7361 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7365 req->modifiers [i].caught = decode_byte (p, &p, end);
7366 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7367 if (CHECK_PROTOCOL_VERSION (2, 25))
7368 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7370 req->modifiers [i].subclasses = TRUE;
7371 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" : ""));
7373 req->modifiers [i].data.exc_class = exc_class;
7375 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
7377 return ERR_INVALID_ARGUMENT;
7380 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7381 int n = decode_int (p, &p, end);
7384 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
7385 for (j = 0; j < n; ++j) {
7386 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7388 g_free (req->modifiers [i].data.assemblies);
7392 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7393 int n = decode_int (p, &p, end);
7396 modifier = &req->modifiers [i];
7397 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7398 for (j = 0; j < n; ++j) {
7399 char *s = decode_string (p, &p, end);
7403 s2 = strdup_tolower (s);
7404 g_hash_table_insert (modifier->data.source_files, s2, s2);
7408 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7409 int n = decode_int (p, &p, end);
7412 modifier = &req->modifiers [i];
7413 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7414 for (j = 0; j < n; ++j) {
7415 char *s = decode_string (p, &p, end);
7418 g_hash_table_insert (modifier->data.type_names, s, s);
7422 return ERR_NOT_IMPLEMENTED;
7426 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7429 req->info = set_breakpoint (method, location, req, &error);
7430 if (!mono_error_ok (&error)) {
7432 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
7433 mono_error_cleanup (&error);
7434 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7436 } else if (req->event_kind == EVENT_KIND_STEP) {
7437 g_assert (step_thread_id);
7439 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7445 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
7450 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7451 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7452 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7453 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7454 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7455 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7457 if (req->nmodifiers) {
7459 return ERR_NOT_IMPLEMENTED;
7463 mono_loader_lock ();
7464 g_ptr_array_add (event_requests, req);
7466 if (agent_config.defer) {
7467 /* Transmit cached data to the client on receipt of the event request */
7468 switch (req->event_kind) {
7469 case EVENT_KIND_APPDOMAIN_CREATE:
7470 /* Emit load events for currently loaded domains */
7471 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7473 case EVENT_KIND_ASSEMBLY_LOAD:
7474 /* Emit load events for currently loaded assemblies */
7475 mono_assembly_foreach (emit_assembly_load, NULL);
7477 case EVENT_KIND_THREAD_START:
7478 /* Emit start events for currently started threads */
7479 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7481 case EVENT_KIND_TYPE_LOAD:
7482 /* Emit type load events for currently loaded types */
7483 mono_domain_foreach (send_types_for_domain, NULL);
7489 mono_loader_unlock ();
7491 buffer_add_int (buf, req->id);
7494 case CMD_EVENT_REQUEST_CLEAR: {
7495 int etype = decode_byte (p, &p, end);
7496 int req_id = decode_int (p, &p, end);
7498 // FIXME: Make a faster mapping from req_id to request
7499 mono_loader_lock ();
7500 clear_event_request (req_id, etype);
7501 mono_loader_unlock ();
7504 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7507 mono_loader_lock ();
7509 while (i < event_requests->len) {
7510 EventRequest *req = g_ptr_array_index (event_requests, i);
7512 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7513 clear_breakpoint (req->info);
7515 g_ptr_array_remove_index_fast (event_requests, i);
7521 mono_loader_unlock ();
7525 return ERR_NOT_IMPLEMENTED;
7532 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7538 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7539 buffer_add_domainid (buf, mono_get_root_domain ());
7542 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7543 domain = decode_domainid (p, &p, end, NULL, &err);
7546 buffer_add_string (buf, domain->friendly_name);
7549 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7554 domain = decode_domainid (p, &p, end, NULL, &err);
7557 mono_loader_lock ();
7559 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7562 buffer_add_int (buf, count);
7563 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7565 buffer_add_assemblyid (buf, domain, ass);
7567 mono_loader_unlock ();
7570 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7571 domain = decode_domainid (p, &p, end, NULL, &err);
7575 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7578 case CMD_APPDOMAIN_GET_CORLIB: {
7579 domain = decode_domainid (p, &p, end, NULL, &err);
7583 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7586 case CMD_APPDOMAIN_CREATE_STRING: {
7590 domain = decode_domainid (p, &p, end, NULL, &err);
7593 s = decode_string (p, &p, end);
7595 o = mono_string_new (domain, s);
7596 buffer_add_objid (buf, (MonoObject*)o);
7599 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7601 MonoDomain *domain2;
7604 domain = decode_domainid (p, &p, end, NULL, &err);
7607 klass = decode_typeid (p, &p, end, &domain2, &err);
7612 g_assert (domain == domain2);
7614 o = mono_object_new (domain, klass);
7616 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
7620 buffer_add_objid (buf, o);
7624 return ERR_NOT_IMPLEMENTED;
7631 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7637 ass = decode_assemblyid (p, &p, end, &domain, &err);
7642 case CMD_ASSEMBLY_GET_LOCATION: {
7643 buffer_add_string (buf, mono_image_get_filename (ass->image));
7646 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7650 if (ass->image->dynamic) {
7651 buffer_add_id (buf, 0);
7653 token = mono_image_get_entry_point (ass->image);
7655 buffer_add_id (buf, 0);
7657 m = mono_get_method (ass->image, token, NULL);
7658 buffer_add_methodid (buf, domain, m);
7663 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7664 buffer_add_moduleid (buf, domain, ass->image);
7667 case CMD_ASSEMBLY_GET_OBJECT: {
7668 MonoObject *o = (MonoObject*)mono_assembly_get_object (domain, ass);
7669 buffer_add_objid (buf, o);
7672 case CMD_ASSEMBLY_GET_TYPE: {
7673 char *s = decode_string (p, &p, end);
7674 gboolean ignorecase = decode_byte (p, &p, end);
7675 MonoTypeNameParse info;
7677 gboolean type_resolve, res;
7678 MonoDomain *d = mono_domain_get ();
7680 /* This is needed to be able to find referenced assemblies */
7681 res = mono_domain_set (domain, FALSE);
7684 if (!mono_reflection_parse_type (s, &info)) {
7687 if (info.assembly.name)
7689 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
7691 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
7692 mono_reflection_free_type_info (&info);
7695 mono_domain_set (d, TRUE);
7699 case CMD_ASSEMBLY_GET_NAME: {
7701 MonoAssembly *mass = ass;
7703 name = g_strdup_printf (
7704 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7706 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7707 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7708 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7709 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7711 buffer_add_string (buf, name);
7716 return ERR_NOT_IMPLEMENTED;
7723 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7729 case CMD_MODULE_GET_INFO: {
7730 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7733 basename = g_path_get_basename (image->name);
7734 buffer_add_string (buf, basename); // name
7735 buffer_add_string (buf, image->module_name); // scopename
7736 buffer_add_string (buf, image->name); // fqname
7737 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7738 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7743 return ERR_NOT_IMPLEMENTED;
7750 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7756 case CMD_FIELD_GET_INFO: {
7757 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
7759 buffer_add_string (buf, f->name);
7760 buffer_add_typeid (buf, domain, f->parent);
7761 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7762 buffer_add_int (buf, f->type->attrs);
7766 return ERR_NOT_IMPLEMENTED;
7773 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7775 if (val && val->vtable->klass == mono_defaults.monotype_class) {
7776 /* Special case these so the client doesn't have to handle Type objects */
7778 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7779 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7780 } else if (MONO_TYPE_IS_REFERENCE (t))
7781 buffer_add_value (buf, t, &val, domain);
7783 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7787 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7793 buffer_add_int (buf, 0);
7797 for (i = 0; i < cinfo->num_attrs; ++i) {
7798 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7801 buffer_add_int (buf, nattrs);
7803 for (i = 0; i < cinfo->num_attrs; ++i) {
7804 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7805 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7806 MonoArray *typed_args, *named_args;
7808 CattrNamedArg *arginfo = NULL;
7811 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
7812 if (!mono_error_ok (&error)) {
7813 DEBUG(2, fprintf (log_file, "[dbg] mono_reflection_create_custom_attr_data_args () failed with: '%s'\n", mono_error_get_message (&error)));
7814 mono_error_cleanup (&error);
7815 return ERR_LOADER_ERROR;
7818 buffer_add_methodid (buf, domain, attr->ctor);
7822 buffer_add_int (buf, mono_array_length (typed_args));
7823 for (j = 0; j < mono_array_length (typed_args); ++j) {
7824 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7826 t = mono_method_signature (attr->ctor)->params [j];
7828 buffer_add_cattr_arg (buf, t, domain, val);
7831 buffer_add_int (buf, 0);
7836 buffer_add_int (buf, mono_array_length (named_args));
7838 for (j = 0; j < mono_array_length (named_args); ++j) {
7839 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7841 if (arginfo [j].prop) {
7842 buffer_add_byte (buf, 0x54);
7843 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7844 } else if (arginfo [j].field) {
7845 buffer_add_byte (buf, 0x53);
7846 buffer_add_fieldid (buf, domain, arginfo [j].field);
7848 g_assert_not_reached ();
7851 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7854 buffer_add_int (buf, 0);
7863 /* FIXME: Code duplication with icall.c */
7865 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7870 mono_class_setup_interfaces (klass, error);
7871 if (!mono_error_ok (error))
7874 for (i = 0; i < klass->interface_count; i++) {
7875 ic = klass->interfaces [i];
7876 g_hash_table_insert (ifaces, ic, ic);
7878 collect_interfaces (ic, ifaces, error);
7879 if (!mono_error_ok (error))
7885 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7895 case CMD_TYPE_GET_INFO: {
7896 buffer_add_string (buf, klass->name_space);
7897 buffer_add_string (buf, klass->name);
7899 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7900 buffer_add_string (buf, name);
7902 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7903 buffer_add_moduleid (buf, domain, klass->image);
7904 buffer_add_typeid (buf, domain, klass->parent);
7905 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7906 buffer_add_typeid (buf, domain, klass->element_class);
7908 buffer_add_id (buf, 0);
7909 buffer_add_int (buf, klass->type_token);
7910 buffer_add_byte (buf, klass->rank);
7911 buffer_add_int (buf, klass->flags);
7913 type = &klass->byval_arg;
7914 // FIXME: Can't decide whenever a class represents a byref type
7917 if (type->type == MONO_TYPE_PTR)
7919 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7921 if (type->type == MONO_TYPE_VALUETYPE)
7923 if (klass->enumtype)
7925 if (klass->generic_container)
7927 if (klass->generic_container || klass->generic_class)
7929 buffer_add_byte (buf, b);
7932 while ((nested = mono_class_get_nested_types (klass, &iter)))
7934 buffer_add_int (buf, nnested);
7936 while ((nested = mono_class_get_nested_types (klass, &iter)))
7937 buffer_add_typeid (buf, domain, nested);
7938 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7939 if (klass->generic_container)
7940 buffer_add_typeid (buf, domain, klass);
7941 else if (klass->generic_class)
7942 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7944 buffer_add_id (buf, 0);
7946 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7949 if (klass->generic_class) {
7950 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7952 count = inst->type_argc;
7953 buffer_add_int (buf, count);
7954 for (i = 0; i < count; i++)
7955 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7956 } else if (klass->generic_container) {
7957 MonoGenericContainer *container = klass->generic_container;
7960 count = container->type_argc;
7961 buffer_add_int (buf, count);
7962 for (i = 0; i < count; i++) {
7963 pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
7964 buffer_add_typeid (buf, domain, pklass);
7967 buffer_add_int (buf, 0);
7972 case CMD_TYPE_GET_METHODS: {
7975 gpointer iter = NULL;
7978 mono_class_setup_methods (klass);
7980 nmethods = mono_class_num_methods (klass);
7982 buffer_add_int (buf, nmethods);
7984 while ((m = mono_class_get_methods (klass, &iter))) {
7985 buffer_add_methodid (buf, domain, m);
7988 g_assert (i == nmethods);
7991 case CMD_TYPE_GET_FIELDS: {
7994 gpointer iter = NULL;
7997 nfields = mono_class_num_fields (klass);
7999 buffer_add_int (buf, nfields);
8001 while ((f = mono_class_get_fields (klass, &iter))) {
8002 buffer_add_fieldid (buf, domain, f);
8003 buffer_add_string (buf, f->name);
8004 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
8005 buffer_add_int (buf, f->type->attrs);
8008 g_assert (i == nfields);
8011 case CMD_TYPE_GET_PROPERTIES: {
8014 gpointer iter = NULL;
8017 nprops = mono_class_num_properties (klass);
8019 buffer_add_int (buf, nprops);
8021 while ((p = mono_class_get_properties (klass, &iter))) {
8022 buffer_add_propertyid (buf, domain, p);
8023 buffer_add_string (buf, p->name);
8024 buffer_add_methodid (buf, domain, p->get);
8025 buffer_add_methodid (buf, domain, p->set);
8026 buffer_add_int (buf, p->attrs);
8029 g_assert (i == nprops);
8032 case CMD_TYPE_GET_CATTRS: {
8033 MonoClass *attr_klass;
8034 MonoCustomAttrInfo *cinfo;
8036 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8037 /* attr_klass can be NULL */
8041 cinfo = mono_custom_attrs_from_class (klass);
8043 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8048 case CMD_TYPE_GET_FIELD_CATTRS: {
8049 MonoClass *attr_klass;
8050 MonoCustomAttrInfo *cinfo;
8051 MonoClassField *field;
8053 field = decode_fieldid (p, &p, end, NULL, &err);
8056 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8060 cinfo = mono_custom_attrs_from_field (klass, field);
8062 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8067 case CMD_TYPE_GET_PROPERTY_CATTRS: {
8068 MonoClass *attr_klass;
8069 MonoCustomAttrInfo *cinfo;
8072 prop = decode_propertyid (p, &p, end, NULL, &err);
8075 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8079 cinfo = mono_custom_attrs_from_property (klass, prop);
8081 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8086 case CMD_TYPE_GET_VALUES:
8087 case CMD_TYPE_GET_VALUES_2: {
8094 MonoThread *thread_obj;
8095 MonoInternalThread *thread = NULL;
8096 guint32 special_static_type;
8098 if (command == CMD_TYPE_GET_VALUES_2) {
8099 int objid = decode_objid (p, &p, end);
8102 err = get_object (objid, (MonoObject**)&thread_obj);
8106 thread = THREAD_TO_INTERNAL (thread_obj);
8109 len = decode_int (p, &p, end);
8110 for (i = 0; i < len; ++i) {
8111 f = decode_fieldid (p, &p, end, NULL, &err);
8115 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8116 return ERR_INVALID_FIELDID;
8117 special_static_type = mono_class_field_get_special_static_type (f);
8118 if (special_static_type != SPECIAL_STATIC_NONE) {
8119 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
8120 return ERR_INVALID_FIELDID;
8123 /* Check that the field belongs to the object */
8125 for (k = klass; k; k = k->parent) {
8126 if (k == f->parent) {
8132 return ERR_INVALID_FIELDID;
8134 vtable = mono_class_vtable (domain, f->parent);
8135 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8136 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
8137 buffer_add_value (buf, f->type, val, domain);
8142 case CMD_TYPE_SET_VALUES: {
8150 len = decode_int (p, &p, end);
8151 for (i = 0; i < len; ++i) {
8152 f = decode_fieldid (p, &p, end, NULL, &err);
8156 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8157 return ERR_INVALID_FIELDID;
8158 if (mono_class_field_is_special_static (f))
8159 return ERR_INVALID_FIELDID;
8161 /* Check that the field belongs to the object */
8163 for (k = klass; k; k = k->parent) {
8164 if (k == f->parent) {
8170 return ERR_INVALID_FIELDID;
8172 // FIXME: Check for literal/const
8174 vtable = mono_class_vtable (domain, f->parent);
8175 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8176 err = decode_value (f->type, domain, val, p, &p, end);
8181 if (MONO_TYPE_IS_REFERENCE (f->type))
8182 mono_field_static_set_value (vtable, f, *(gpointer*)val);
8184 mono_field_static_set_value (vtable, f, val);
8189 case CMD_TYPE_GET_OBJECT: {
8190 MonoObject *o = (MonoObject*)mono_type_get_object (domain, &klass->byval_arg);
8191 buffer_add_objid (buf, o);
8194 case CMD_TYPE_GET_SOURCE_FILES:
8195 case CMD_TYPE_GET_SOURCE_FILES_2: {
8196 char *source_file, *base;
8200 files = get_source_files_for_type (klass);
8202 buffer_add_int (buf, files->len);
8203 for (i = 0; i < files->len; ++i) {
8204 source_file = g_ptr_array_index (files, i);
8205 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8206 buffer_add_string (buf, source_file);
8208 base = g_path_get_basename (source_file);
8209 buffer_add_string (buf, base);
8212 g_free (source_file);
8214 g_ptr_array_free (files, TRUE);
8217 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8218 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8222 if (mono_class_is_assignable_from (klass, oklass))
8223 buffer_add_byte (buf, 1);
8225 buffer_add_byte (buf, 0);
8228 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8229 char *name = decode_string (p, &p, end);
8230 int i, flags = decode_int (p, &p, end);
8231 MonoException *ex = NULL;
8232 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
8235 return ERR_LOADER_ERROR;
8236 buffer_add_int (buf, array->len);
8237 for (i = 0; i < array->len; ++i) {
8238 MonoMethod *method = g_ptr_array_index (array, i);
8239 buffer_add_methodid (buf, domain, method);
8242 g_ptr_array_free (array, TRUE);
8246 case CMD_TYPE_GET_INTERFACES: {
8248 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8250 MonoClass *tclass, *iface;
8251 GHashTableIter iter;
8255 for (parent = tclass; parent; parent = parent->parent) {
8256 mono_class_setup_interfaces (parent, &error);
8257 if (!mono_error_ok (&error))
8258 return ERR_LOADER_ERROR;
8259 collect_interfaces (parent, iface_hash, &error);
8260 if (!mono_error_ok (&error))
8261 return ERR_LOADER_ERROR;
8264 buffer_add_int (buf, g_hash_table_size (iface_hash));
8266 g_hash_table_iter_init (&iter, iface_hash);
8267 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8268 buffer_add_typeid (buf, domain, iface);
8269 g_hash_table_destroy (iface_hash);
8272 case CMD_TYPE_GET_INTERFACE_MAP: {
8273 int tindex, ioffset;
8274 gboolean variance_used;
8276 int len, nmethods, i;
8280 len = decode_int (p, &p, end);
8281 mono_class_setup_vtable (klass);
8283 for (tindex = 0; tindex < len; ++tindex) {
8284 iclass = decode_typeid (p, &p, end, NULL, &err);
8288 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8290 return ERR_INVALID_ARGUMENT;
8292 nmethods = mono_class_num_methods (iclass);
8293 buffer_add_int (buf, nmethods);
8296 while ((method = mono_class_get_methods (iclass, &iter))) {
8297 buffer_add_methodid (buf, domain, method);
8299 for (i = 0; i < nmethods; ++i)
8300 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
8304 case CMD_TYPE_IS_INITIALIZED: {
8305 MonoVTable *vtable = mono_class_vtable (domain, klass);
8308 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8310 buffer_add_int (buf, 0);
8313 case CMD_TYPE_CREATE_INSTANCE: {
8316 obj = mono_object_new (domain, klass);
8317 buffer_add_objid (buf, obj);
8321 return ERR_NOT_IMPLEMENTED;
8328 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8331 MonoDomain *old_domain;
8335 klass = decode_typeid (p, &p, end, &domain, &err);
8339 old_domain = mono_domain_get ();
8341 mono_domain_set (domain, TRUE);
8343 err = type_commands_internal (command, klass, domain, p, end, buf);
8345 mono_domain_set (old_domain, TRUE);
8351 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8353 MonoMethodHeader *header;
8357 case CMD_METHOD_GET_NAME: {
8358 buffer_add_string (buf, method->name);
8361 case CMD_METHOD_GET_DECLARING_TYPE: {
8362 buffer_add_typeid (buf, domain, method->klass);
8365 case CMD_METHOD_GET_DEBUG_INFO: {
8366 MonoDebugMethodInfo *minfo;
8368 int i, j, n_il_offsets;
8371 int *column_numbers;
8372 int *end_line_numbers;
8373 int *end_column_numbers;
8375 GPtrArray *source_file_list;
8377 header = mono_method_get_header (method);
8379 buffer_add_int (buf, 0);
8380 buffer_add_string (buf, "");
8381 buffer_add_int (buf, 0);
8385 minfo = mono_debug_lookup_method (method);
8387 buffer_add_int (buf, header->code_size);
8388 buffer_add_string (buf, "");
8389 buffer_add_int (buf, 0);
8390 mono_metadata_free_mh (header);
8394 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);
8395 buffer_add_int (buf, header->code_size);
8396 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8397 buffer_add_int (buf, source_file_list->len);
8398 for (i = 0; i < source_file_list->len; ++i) {
8399 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
8400 buffer_add_string (buf, sinfo->source_file);
8401 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8402 for (j = 0; j < 16; ++j)
8403 buffer_add_byte (buf, sinfo->hash [j]);
8407 buffer_add_string (buf, source_file);
8409 buffer_add_int (buf, n_il_offsets);
8410 DEBUG (10, fprintf (log_file, "Line number table for method %s:\n", mono_method_full_name (method, TRUE)));
8411 for (i = 0; i < n_il_offsets; ++i) {
8412 const char *srcfile = "";
8414 if (source_files [i] != -1) {
8415 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
8416 srcfile = sinfo->source_file;
8418 DEBUG (10, fprintf (log_file, "IL%x -> %s:%d %d\n", il_offsets [i], srcfile, line_numbers [i], column_numbers ? column_numbers [i] : -1));
8419 buffer_add_int (buf, il_offsets [i]);
8420 buffer_add_int (buf, line_numbers [i]);
8421 if (CHECK_PROTOCOL_VERSION (2, 13))
8422 buffer_add_int (buf, source_files [i]);
8423 if (CHECK_PROTOCOL_VERSION (2, 19))
8424 buffer_add_int (buf, column_numbers ? column_numbers [i] : -1);
8425 if (CHECK_PROTOCOL_VERSION (2, 32)) {
8426 buffer_add_int (buf, end_line_numbers ? end_line_numbers [i] : -1);
8427 buffer_add_int (buf, end_column_numbers ? end_column_numbers [i] : -1);
8430 g_free (source_file);
8431 g_free (il_offsets);
8432 g_free (line_numbers);
8433 g_free (column_numbers);
8434 g_free (end_line_numbers);
8435 g_free (end_column_numbers);
8436 g_free (source_files);
8437 g_ptr_array_free (source_file_list, TRUE);
8438 mono_metadata_free_mh (header);
8441 case CMD_METHOD_GET_PARAM_INFO: {
8442 MonoMethodSignature *sig = mono_method_signature (method);
8446 /* FIXME: mono_class_from_mono_type () and byrefs */
8448 /* FIXME: Use a smaller encoding */
8449 buffer_add_int (buf, sig->call_convention);
8450 buffer_add_int (buf, sig->param_count);
8451 buffer_add_int (buf, sig->generic_param_count);
8452 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
8453 for (i = 0; i < sig->param_count; ++i) {
8455 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
8458 /* Emit parameter names */
8459 names = g_new (char *, sig->param_count);
8460 mono_method_get_param_names (method, (const char **) names);
8461 for (i = 0; i < sig->param_count; ++i)
8462 buffer_add_string (buf, names [i]);
8467 case CMD_METHOD_GET_LOCALS_INFO: {
8468 int i, j, num_locals;
8469 MonoDebugLocalsInfo *locals;
8471 header = mono_method_get_header (method);
8473 return ERR_INVALID_ARGUMENT;
8475 buffer_add_int (buf, header->num_locals);
8478 for (i = 0; i < header->num_locals; ++i)
8479 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
8482 locals = mono_debug_lookup_locals (method);
8484 num_locals = locals->num_locals;
8487 for (i = 0; i < header->num_locals; ++i) {
8488 for (j = 0; j < num_locals; ++j)
8489 if (locals->locals [j].index == i)
8492 buffer_add_string (buf, locals->locals [j].name);
8494 buffer_add_string (buf, "");
8498 for (i = 0; i < header->num_locals; ++i) {
8499 for (j = 0; j < num_locals; ++j)
8500 if (locals->locals [j].index == i)
8502 if (j < num_locals && locals->locals [j].block) {
8503 buffer_add_int (buf, locals->locals [j].block->start_offset);
8504 buffer_add_int (buf, locals->locals [j].block->end_offset);
8506 buffer_add_int (buf, 0);
8507 buffer_add_int (buf, header->code_size);
8510 mono_metadata_free_mh (header);
8513 mono_debug_symfile_free_locals (locals);
8517 case CMD_METHOD_GET_INFO:
8518 buffer_add_int (buf, method->flags);
8519 buffer_add_int (buf, method->iflags);
8520 buffer_add_int (buf, method->token);
8521 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8523 if (method->is_generic)
8525 if (mono_method_signature (method)->generic_param_count)
8527 buffer_add_byte (buf, attrs);
8528 if (method->is_generic || method->is_inflated) {
8531 if (method->is_generic) {
8534 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8536 result = imethod->declaring;
8537 if (imethod->context.class_inst) {
8538 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8539 /*Generic methods gets the context of the GTD.*/
8540 if (mono_class_get_context (klass))
8541 result = mono_class_inflate_generic_method_full (result, klass, mono_class_get_context (klass));
8545 buffer_add_methodid (buf, domain, result);
8547 buffer_add_id (buf, 0);
8549 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8550 if (mono_method_signature (method)->generic_param_count) {
8553 if (method->is_inflated) {
8554 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
8556 count = inst->type_argc;
8557 buffer_add_int (buf, count);
8559 for (i = 0; i < count; i++)
8560 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8562 buffer_add_int (buf, 0);
8564 } else if (method->is_generic) {
8565 MonoGenericContainer *container = mono_method_get_generic_container (method);
8567 count = mono_method_signature (method)->generic_param_count;
8568 buffer_add_int (buf, count);
8569 for (i = 0; i < count; i++) {
8570 MonoGenericParam *param = mono_generic_container_get_param (container, i);
8571 MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
8572 buffer_add_typeid (buf, domain, pklass);
8575 buffer_add_int (buf, 0);
8578 buffer_add_int (buf, 0);
8583 case CMD_METHOD_GET_BODY: {
8586 header = mono_method_get_header (method);
8588 buffer_add_int (buf, 0);
8590 if (CHECK_PROTOCOL_VERSION (2, 18))
8591 buffer_add_int (buf, 0);
8593 buffer_add_int (buf, header->code_size);
8594 for (i = 0; i < header->code_size; ++i)
8595 buffer_add_byte (buf, header->code [i]);
8597 if (CHECK_PROTOCOL_VERSION (2, 18)) {
8598 buffer_add_int (buf, header->num_clauses);
8599 for (i = 0; i < header->num_clauses; ++i) {
8600 MonoExceptionClause *clause = &header->clauses [i];
8602 buffer_add_int (buf, clause->flags);
8603 buffer_add_int (buf, clause->try_offset);
8604 buffer_add_int (buf, clause->try_len);
8605 buffer_add_int (buf, clause->handler_offset);
8606 buffer_add_int (buf, clause->handler_len);
8607 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
8608 buffer_add_typeid (buf, domain, clause->data.catch_class);
8609 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8610 buffer_add_int (buf, clause->data.filter_offset);
8614 mono_metadata_free_mh (header);
8619 case CMD_METHOD_RESOLVE_TOKEN: {
8620 guint32 token = decode_int (p, &p, end);
8623 switch (mono_metadata_token_code (token)) {
8624 case MONO_TOKEN_STRING: {
8628 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
8631 s2 = mono_string_to_utf8 (s);
8633 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8634 buffer_add_string (buf, s2);
8640 MonoClass *handle_class;
8642 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8643 val = mono_method_get_wrapper_data (method, token);
8644 handle_class = mono_method_get_wrapper_data (method, token + 1);
8646 if (handle_class == NULL) {
8647 // Can't figure out the token type
8648 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8652 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
8656 if (handle_class == mono_defaults.typehandle_class) {
8657 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8658 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8659 buffer_add_typeid (buf, domain, (MonoClass *) val);
8661 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
8662 } else if (handle_class == mono_defaults.fieldhandle_class) {
8663 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8664 buffer_add_fieldid (buf, domain, val);
8665 } else if (handle_class == mono_defaults.methodhandle_class) {
8666 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8667 buffer_add_methodid (buf, domain, val);
8668 } else if (handle_class == mono_defaults.string_class) {
8671 s = mono_string_to_utf8 (val);
8672 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8673 buffer_add_string (buf, s);
8676 g_assert_not_reached ();
8683 case CMD_METHOD_GET_CATTRS: {
8684 MonoClass *attr_klass;
8685 MonoCustomAttrInfo *cinfo;
8687 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8688 /* attr_klass can be NULL */
8692 cinfo = mono_custom_attrs_from_method (method);
8694 err = buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
8699 case CMD_METHOD_MAKE_GENERIC_METHOD: {
8700 MonoType **type_argv;
8704 MonoGenericInst *ginst;
8705 MonoGenericContext tmp_context;
8706 MonoMethod *inflated;
8708 type_argc = decode_int (p, &p, end);
8709 type_argv = g_new0 (MonoType*, type_argc);
8710 for (i = 0; i < type_argc; ++i) {
8711 klass = decode_typeid (p, &p, end, &d, &err);
8718 return ERR_INVALID_ARGUMENT;
8720 type_argv [i] = &klass->byval_arg;
8722 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
8724 tmp_context.class_inst = method->klass->generic_class ? method->klass->generic_class->context.class_inst : NULL;
8725 tmp_context.method_inst = ginst;
8727 inflated = mono_class_inflate_generic_method (method, &tmp_context);
8728 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
8729 return ERR_INVALID_ARGUMENT;
8730 buffer_add_methodid (buf, domain, inflated);
8734 return ERR_NOT_IMPLEMENTED;
8741 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8744 MonoDomain *old_domain;
8748 method = decode_methodid (p, &p, end, &domain, &err);
8752 old_domain = mono_domain_get ();
8754 mono_domain_set (domain, TRUE);
8756 err = method_commands_internal (command, method, domain, p, end, buf);
8758 mono_domain_set (old_domain, TRUE);
8764 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8766 int objid = decode_objid (p, &p, end);
8768 MonoThread *thread_obj;
8769 MonoInternalThread *thread;
8771 err = get_object (objid, (MonoObject**)&thread_obj);
8775 thread = THREAD_TO_INTERNAL (thread_obj);
8778 case CMD_THREAD_GET_NAME: {
8780 gunichar2 *s = mono_thread_get_name (thread, &name_len);
8783 buffer_add_int (buf, 0);
8788 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
8790 buffer_add_int (buf, len);
8791 buffer_add_data (buf, (guint8*)name, len);
8796 case CMD_THREAD_GET_FRAME_INFO: {
8797 DebuggerTlsData *tls;
8798 int i, start_frame, length;
8800 // Wait for suspending if it already started
8801 // FIXME: Races with suspend_count
8802 while (!is_suspended ()) {
8804 wait_for_suspend ();
8808 wait_for_suspend ();
8809 if (!is_suspended ())
8810 return ERR_NOT_SUSPENDED;
8813 start_frame = decode_int (p, &p, end);
8814 length = decode_int (p, &p, end);
8816 if (start_frame != 0 || length != -1)
8817 return ERR_NOT_IMPLEMENTED;
8819 mono_loader_lock ();
8820 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8821 mono_loader_unlock ();
8824 compute_frame_info (thread, tls);
8826 buffer_add_int (buf, tls->frame_count);
8827 for (i = 0; i < tls->frame_count; ++i) {
8828 buffer_add_int (buf, tls->frames [i]->id);
8829 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
8830 buffer_add_int (buf, tls->frames [i]->il_offset);
8832 * Instead of passing the frame type directly to the client, we associate
8833 * it with the previous frame using a set of flags. This avoids lots of
8834 * conditional code in the client, since a frame whose type isn't
8835 * FRAME_TYPE_MANAGED has no method, location, etc.
8837 buffer_add_byte (buf, tls->frames [i]->flags);
8842 case CMD_THREAD_GET_STATE:
8843 buffer_add_int (buf, thread->state);
8845 case CMD_THREAD_GET_INFO:
8846 buffer_add_byte (buf, thread->threadpool_thread);
8848 case CMD_THREAD_GET_ID:
8849 buffer_add_long (buf, (guint64)(gsize)thread);
8851 case CMD_THREAD_GET_TID:
8852 buffer_add_long (buf, (guint64)thread->tid);
8854 case CMD_THREAD_SET_IP: {
8855 DebuggerTlsData *tls;
8858 MonoSeqPointInfo *seq_points;
8859 SeqPoint *sp = NULL;
8863 method = decode_methodid (p, &p, end, &domain, &err);
8866 il_offset = decode_long (p, &p, end);
8868 while (!is_suspended ()) {
8870 wait_for_suspend ();
8873 mono_loader_lock ();
8874 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8875 mono_loader_unlock ();
8878 compute_frame_info (thread, tls);
8879 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
8880 return ERR_INVALID_ARGUMENT;
8882 seq_points = get_seq_points (domain, method);
8883 g_assert (seq_points);
8885 for (i = 0; i < seq_points->len; ++i) {
8886 sp = &seq_points->seq_points [i];
8888 if (sp->il_offset == il_offset)
8891 if (i == seq_points->len)
8892 return ERR_INVALID_ARGUMENT;
8894 // FIXME: Check that the ip change is safe
8896 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));
8897 MONO_CONTEXT_SET_IP (&tls->restore_ctx, (guint8*)tls->frames [0]->ji->code_start + sp->native_offset);
8901 return ERR_NOT_IMPLEMENTED;
8908 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8912 MonoThread *thread_obj;
8913 MonoInternalThread *thread;
8914 int pos, i, len, frame_idx;
8915 DebuggerTlsData *tls;
8917 MonoDebugMethodJitInfo *jit;
8918 MonoDebugVarInfo *var;
8919 MonoMethodSignature *sig;
8921 MonoMethodHeader *header;
8923 objid = decode_objid (p, &p, end);
8924 err = get_object (objid, (MonoObject**)&thread_obj);
8928 thread = THREAD_TO_INTERNAL (thread_obj);
8930 id = decode_id (p, &p, end);
8932 mono_loader_lock ();
8933 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8934 mono_loader_unlock ();
8937 for (i = 0; i < tls->frame_count; ++i) {
8938 if (tls->frames [i]->id == id)
8941 if (i == tls->frame_count)
8942 return ERR_INVALID_FRAMEID;
8945 frame = tls->frames [frame_idx];
8947 if (!frame->has_ctx)
8948 return ERR_ABSENT_INFORMATION;
8951 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
8952 if (!frame->jit && frame->api_method->is_inflated)
8953 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
8957 /* This could happen for aot images with no jit debug info */
8958 s = mono_method_full_name (frame->api_method, TRUE);
8959 DEBUG (1, fprintf (log_file, "[dbg] No debug information found for '%s'.\n", s));
8961 return ERR_ABSENT_INFORMATION;
8966 sig = mono_method_signature (frame->actual_method);
8968 if (!get_seq_points (frame->domain, frame->actual_method))
8970 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
8972 return ERR_ABSENT_INFORMATION;
8975 case CMD_STACK_FRAME_GET_VALUES: {
8976 len = decode_int (p, &p, end);
8977 header = mono_method_get_header (frame->actual_method);
8979 for (i = 0; i < len; ++i) {
8980 pos = decode_int (p, &p, end);
8985 g_assert (pos >= 0 && pos < jit->num_params);
8987 var = &jit->params [pos];
8989 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
8991 g_assert (pos >= 0 && pos < jit->num_locals);
8993 var = &jit->locals [pos];
8995 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
8998 mono_metadata_free_mh (header);
9001 case CMD_STACK_FRAME_GET_THIS: {
9002 if (frame->api_method->klass->valuetype) {
9003 if (!sig->hasthis) {
9004 MonoObject *p = NULL;
9005 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
9007 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9010 if (!sig->hasthis) {
9011 MonoObject *p = NULL;
9012 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
9014 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9019 case CMD_STACK_FRAME_SET_VALUES: {
9022 MonoDebugVarInfo *var;
9024 len = decode_int (p, &p, end);
9025 header = mono_method_get_header (frame->actual_method);
9027 for (i = 0; i < len; ++i) {
9028 pos = decode_int (p, &p, end);
9033 g_assert (pos >= 0 && pos < jit->num_params);
9035 t = sig->params [pos];
9036 var = &jit->params [pos];
9038 g_assert (pos >= 0 && pos < jit->num_locals);
9040 t = header->locals [pos];
9041 var = &jit->locals [pos];
9044 if (MONO_TYPE_IS_REFERENCE (t))
9045 val_buf = g_alloca (sizeof (MonoObject*));
9047 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9048 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9052 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_ctx);
9054 mono_metadata_free_mh (header);
9057 case CMD_STACK_FRAME_GET_DOMAIN: {
9058 if (CHECK_PROTOCOL_VERSION (2, 38))
9059 buffer_add_domainid (buf, frame->domain);
9063 return ERR_NOT_IMPLEMENTED;
9070 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9073 int objid, err, index, len, i, esize;
9076 objid = decode_objid (p, &p, end);
9077 err = get_object (objid, (MonoObject**)&arr);
9082 case CMD_ARRAY_REF_GET_LENGTH:
9083 buffer_add_int (buf, arr->obj.vtable->klass->rank);
9085 buffer_add_int (buf, arr->max_length);
9086 buffer_add_int (buf, 0);
9088 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
9089 buffer_add_int (buf, arr->bounds [i].length);
9090 buffer_add_int (buf, arr->bounds [i].lower_bound);
9094 case CMD_ARRAY_REF_GET_VALUES:
9095 index = decode_int (p, &p, end);
9096 len = decode_int (p, &p, end);
9098 g_assert (index >= 0 && len >= 0);
9099 // Reordered to avoid integer overflow
9100 g_assert (!(index > arr->max_length - len));
9102 esize = mono_array_element_size (arr->obj.vtable->klass);
9103 for (i = index; i < index + len; ++i) {
9104 elem = (gpointer*)((char*)arr->vector + (i * esize));
9105 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
9108 case CMD_ARRAY_REF_SET_VALUES:
9109 index = decode_int (p, &p, end);
9110 len = decode_int (p, &p, end);
9112 g_assert (index >= 0 && len >= 0);
9113 // Reordered to avoid integer overflow
9114 g_assert (!(index > arr->max_length - len));
9116 esize = mono_array_element_size (arr->obj.vtable->klass);
9117 for (i = index; i < index + len; ++i) {
9118 elem = (gpointer*)((char*)arr->vector + (i * esize));
9120 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
9124 return ERR_NOT_IMPLEMENTED;
9131 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9136 int i, index, length;
9139 objid = decode_objid (p, &p, end);
9140 err = get_object (objid, (MonoObject**)&str);
9145 case CMD_STRING_REF_GET_VALUE:
9146 s = mono_string_to_utf8 (str);
9147 buffer_add_string (buf, s);
9150 case CMD_STRING_REF_GET_LENGTH:
9151 buffer_add_long (buf, mono_string_length (str));
9153 case CMD_STRING_REF_GET_CHARS:
9154 index = decode_long (p, &p, end);
9155 length = decode_long (p, &p, end);
9156 if (index > mono_string_length (str) - length)
9157 return ERR_INVALID_ARGUMENT;
9158 c = mono_string_chars (str) + index;
9159 for (i = 0; i < length; ++i)
9160 buffer_add_short (buf, c [i]);
9163 return ERR_NOT_IMPLEMENTED;
9170 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9179 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9180 objid = decode_objid (p, &p, end);
9181 err = get_object (objid, &obj);
9183 buffer_add_int (buf, 1);
9185 buffer_add_int (buf, 0);
9189 objid = decode_objid (p, &p, end);
9190 err = get_object (objid, &obj);
9195 case CMD_OBJECT_REF_GET_TYPE:
9196 /* This handles transparent proxies too */
9197 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9199 case CMD_OBJECT_REF_GET_VALUES:
9200 len = decode_int (p, &p, end);
9202 for (i = 0; i < len; ++i) {
9203 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9207 /* Check that the field belongs to the object */
9209 for (k = obj->vtable->klass; k; k = k->parent) {
9210 if (k == f->parent) {
9216 return ERR_INVALID_FIELDID;
9218 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9222 if (mono_class_field_is_special_static (f))
9223 return ERR_INVALID_FIELDID;
9225 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9226 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9227 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9228 mono_field_static_get_value (vtable, f, val);
9229 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9232 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
9236 case CMD_OBJECT_REF_SET_VALUES:
9237 len = decode_int (p, &p, end);
9239 for (i = 0; i < len; ++i) {
9240 f = decode_fieldid (p, &p, end, NULL, &err);
9244 /* Check that the field belongs to the object */
9246 for (k = obj->vtable->klass; k; k = k->parent) {
9247 if (k == f->parent) {
9253 return ERR_INVALID_FIELDID;
9255 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9259 if (mono_class_field_is_special_static (f))
9260 return ERR_INVALID_FIELDID;
9262 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9263 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9265 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9266 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
9271 mono_field_static_set_value (vtable, f, val);
9274 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
9280 case CMD_OBJECT_REF_GET_ADDRESS:
9281 buffer_add_long (buf, (gssize)obj);
9283 case CMD_OBJECT_REF_GET_DOMAIN:
9284 buffer_add_domainid (buf, obj->vtable->domain);
9286 case CMD_OBJECT_REF_GET_INFO:
9287 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9288 buffer_add_domainid (buf, obj->vtable->domain);
9291 return ERR_NOT_IMPLEMENTED;
9298 command_set_to_string (CommandSet command_set)
9300 switch (command_set) {
9303 case CMD_SET_OBJECT_REF:
9304 return "OBJECT_REF";
9305 case CMD_SET_STRING_REF:
9306 return "STRING_REF";
9307 case CMD_SET_THREAD:
9309 case CMD_SET_ARRAY_REF:
9311 case CMD_SET_EVENT_REQUEST:
9312 return "EVENT_REQUEST";
9313 case CMD_SET_STACK_FRAME:
9314 return "STACK_FRAME";
9315 case CMD_SET_APPDOMAIN:
9317 case CMD_SET_ASSEMBLY:
9319 case CMD_SET_METHOD:
9323 case CMD_SET_MODULE:
9334 static const char* vm_cmds_str [] = {
9342 "SET_PROTOCOL_VERSION",
9345 "GET_TYPES_FOR_SOURCE_FILE",
9350 static const char* thread_cmds_str[] = {
9360 static const char* event_cmds_str[] = {
9363 "REQUEST_CLEAR_ALL_BREAKPOINTS"
9366 static const char* appdomain_cmds_str[] = {
9368 "GET_FRIENDLY_NAME",
9370 "GET_ENTRY_ASSEMBLY",
9373 "CREATE_BOXED_VALUE"
9376 static const char* assembly_cmds_str[] = {
9379 "GET_MANIFEST_MODULE",
9385 static const char* module_cmds_str[] = {
9389 static const char* field_cmds_str[] = {
9393 static const char* method_cmds_str[] = {
9395 "GET_DECLARING_TYPE",
9403 "MAKE_GENERIC_METHOD"
9406 static const char* type_cmds_str[] = {
9414 "IS_ASSIGNABLE_FROM",
9418 "GET_PROPERTY_CATTRS",
9419 "GET_SOURCE_FILES_2",
9421 "GET_METHODS_BY_NAME_FLAGS",
9423 "GET_INTERFACE_MAP",
9427 static const char* stack_frame_cmds_str[] = {
9434 static const char* array_cmds_str[] = {
9440 static const char* string_cmds_str[] = {
9446 static const char* object_cmds_str[] = {
9457 cmd_to_string (CommandSet set, int command)
9465 cmds_len = G_N_ELEMENTS (vm_cmds_str);
9467 case CMD_SET_OBJECT_REF:
9468 cmds = object_cmds_str;
9469 cmds_len = G_N_ELEMENTS (object_cmds_str);
9471 case CMD_SET_STRING_REF:
9472 cmds = string_cmds_str;
9473 cmds_len = G_N_ELEMENTS (string_cmds_str);
9475 case CMD_SET_THREAD:
9476 cmds = thread_cmds_str;
9477 cmds_len = G_N_ELEMENTS (thread_cmds_str);
9479 case CMD_SET_ARRAY_REF:
9480 cmds = array_cmds_str;
9481 cmds_len = G_N_ELEMENTS (array_cmds_str);
9483 case CMD_SET_EVENT_REQUEST:
9484 cmds = event_cmds_str;
9485 cmds_len = G_N_ELEMENTS (event_cmds_str);
9487 case CMD_SET_STACK_FRAME:
9488 cmds = stack_frame_cmds_str;
9489 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
9491 case CMD_SET_APPDOMAIN:
9492 cmds = appdomain_cmds_str;
9493 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
9495 case CMD_SET_ASSEMBLY:
9496 cmds = assembly_cmds_str;
9497 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
9499 case CMD_SET_METHOD:
9500 cmds = method_cmds_str;
9501 cmds_len = G_N_ELEMENTS (method_cmds_str);
9504 cmds = type_cmds_str;
9505 cmds_len = G_N_ELEMENTS (type_cmds_str);
9507 case CMD_SET_MODULE:
9508 cmds = module_cmds_str;
9509 cmds_len = G_N_ELEMENTS (module_cmds_str);
9512 cmds = field_cmds_str;
9513 cmds_len = G_N_ELEMENTS (field_cmds_str);
9516 cmds = event_cmds_str;
9517 cmds_len = G_N_ELEMENTS (event_cmds_str);
9522 if (command > 0 && command <= cmds_len)
9523 return cmds [command - 1];
9529 wait_for_attach (void)
9531 #ifndef DISABLE_SOCKET_TRANSPORT
9532 if (listen_fd == -1) {
9533 DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
9537 /* Block and wait for client connection */
9538 conn_fd = socket_transport_accept (listen_fd);
9539 DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
9540 if (conn_fd == -1) {
9541 DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
9545 g_assert_not_reached ();
9549 disconnected = !transport_handshake ();
9551 DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
9561 * This thread handles communication with the debugger client using a JDWP
9564 static guint32 WINAPI
9565 debugger_thread (void *arg)
9567 int res, len, id, flags, command_set = 0, command = 0;
9568 guint8 header [HEADER_LENGTH];
9569 guint8 *data, *p, *end;
9573 gboolean attach_failed = FALSE;
9575 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
9577 debugger_thread_id = GetCurrentThreadId ();
9579 mono_jit_thread_attach (mono_get_root_domain ());
9581 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
9583 mono_set_is_debugger_attached (TRUE);
9585 if (agent_config.defer) {
9586 if (!wait_for_attach ()) {
9587 DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
9588 attach_failed = TRUE; // Don't abort process when we can't listen
9590 /* Send start event to client */
9591 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
9595 while (!attach_failed) {
9596 res = transport_recv (header, HEADER_LENGTH);
9598 /* This will break if the socket is closed during shutdown too */
9599 if (res != HEADER_LENGTH) {
9600 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH));
9605 end = header + HEADER_LENGTH;
9607 len = decode_int (p, &p, end);
9608 id = decode_int (p, &p, end);
9609 flags = decode_byte (p, &p, end);
9610 command_set = decode_byte (p, &p, end);
9611 command = decode_byte (p, &p, end);
9613 g_assert (flags == 0);
9616 const char *cmd_str;
9619 cmd_str = cmd_to_string (command_set, command);
9621 sprintf (cmd_num, "%d", command);
9625 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));
9628 data = g_malloc (len - HEADER_LENGTH);
9629 if (len - HEADER_LENGTH > 0)
9631 res = transport_recv (data, len - HEADER_LENGTH);
9632 if (res != len - HEADER_LENGTH) {
9633 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH));
9639 end = data + (len - HEADER_LENGTH);
9641 buffer_init (&buf, 128);
9646 /* Process the request */
9647 switch (command_set) {
9649 err = vm_commands (command, id, p, end, &buf);
9650 if (!err && command == CMD_VM_INVOKE_METHOD)
9651 /* Sent after the invoke is complete */
9654 case CMD_SET_EVENT_REQUEST:
9655 err = event_commands (command, p, end, &buf);
9657 case CMD_SET_APPDOMAIN:
9658 err = domain_commands (command, p, end, &buf);
9660 case CMD_SET_ASSEMBLY:
9661 err = assembly_commands (command, p, end, &buf);
9663 case CMD_SET_MODULE:
9664 err = module_commands (command, p, end, &buf);
9667 err = field_commands (command, p, end, &buf);
9670 err = type_commands (command, p, end, &buf);
9672 case CMD_SET_METHOD:
9673 err = method_commands (command, p, end, &buf);
9675 case CMD_SET_THREAD:
9676 err = thread_commands (command, p, end, &buf);
9678 case CMD_SET_STACK_FRAME:
9679 err = frame_commands (command, p, end, &buf);
9681 case CMD_SET_ARRAY_REF:
9682 err = array_commands (command, p, end, &buf);
9684 case CMD_SET_STRING_REF:
9685 err = string_commands (command, p, end, &buf);
9687 case CMD_SET_OBJECT_REF:
9688 err = object_commands (command, p, end, &buf);
9691 err = ERR_NOT_IMPLEMENTED;
9694 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
9695 buffer_replies = TRUE;
9699 if (buffer_replies) {
9700 buffer_reply_packet (id, err, &buf);
9702 send_reply_packet (id, err, &buf);
9703 //DEBUG (1, fprintf (log_file, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000));
9707 if (!err && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
9708 send_buffered_reply_packets ();
9709 buffer_replies = FALSE;
9715 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
9719 mono_set_is_debugger_attached (FALSE);
9721 mono_mutex_lock (&debugger_thread_exited_mutex);
9722 debugger_thread_exited = TRUE;
9723 mono_cond_signal (&debugger_thread_exited_cond);
9724 mono_mutex_unlock (&debugger_thread_exited_mutex);
9726 DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
9728 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
9729 DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
9730 start_debugger_thread ();
9736 #else /* DISABLE_DEBUGGER_AGENT */
9739 mono_debugger_agent_parse_options (char *options)
9741 g_error ("This runtime is configured with the debugger agent disabled.");
9745 mono_debugger_agent_init (void)
9750 mono_debugger_agent_breakpoint_hit (void *sigctx)
9755 mono_debugger_agent_single_step_event (void *sigctx)
9760 mono_debugger_agent_free_domain_info (MonoDomain *domain)
9765 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
9771 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
9772 MonoContext *catch_ctx)
9777 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9782 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9787 mono_debugger_agent_user_break (void)
9793 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
9798 mono_debugger_agent_debug_log_is_enabled (void)
9804 mono_debugger_agent_unhandled_exception (MonoException *exc)
9806 g_assert_not_reached ();