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 36
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
410 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
411 } BindingFlagsExtensions;
415 CMD_VM_ALL_THREADS = 2,
420 CMD_VM_INVOKE_METHOD = 7,
421 CMD_VM_SET_PROTOCOL_VERSION = 8,
422 CMD_VM_ABORT_INVOKE = 9,
423 CMD_VM_SET_KEEPALIVE = 10,
424 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
425 CMD_VM_GET_TYPES = 12,
426 CMD_VM_INVOKE_METHODS = 13,
427 CMD_VM_START_BUFFERING = 14,
428 CMD_VM_STOP_BUFFERING = 15
432 CMD_THREAD_GET_FRAME_INFO = 1,
433 CMD_THREAD_GET_NAME = 2,
434 CMD_THREAD_GET_STATE = 3,
435 CMD_THREAD_GET_INFO = 4,
436 CMD_THREAD_GET_ID = 5,
437 CMD_THREAD_GET_TID = 6,
438 CMD_THREAD_SET_IP = 7
442 CMD_EVENT_REQUEST_SET = 1,
443 CMD_EVENT_REQUEST_CLEAR = 2,
444 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
452 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
453 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
454 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
455 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
456 CMD_APPDOMAIN_CREATE_STRING = 5,
457 CMD_APPDOMAIN_GET_CORLIB = 6,
458 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
462 CMD_ASSEMBLY_GET_LOCATION = 1,
463 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
464 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
465 CMD_ASSEMBLY_GET_OBJECT = 4,
466 CMD_ASSEMBLY_GET_TYPE = 5,
467 CMD_ASSEMBLY_GET_NAME = 6
471 CMD_MODULE_GET_INFO = 1,
475 CMD_FIELD_GET_INFO = 1,
479 CMD_METHOD_GET_NAME = 1,
480 CMD_METHOD_GET_DECLARING_TYPE = 2,
481 CMD_METHOD_GET_DEBUG_INFO = 3,
482 CMD_METHOD_GET_PARAM_INFO = 4,
483 CMD_METHOD_GET_LOCALS_INFO = 5,
484 CMD_METHOD_GET_INFO = 6,
485 CMD_METHOD_GET_BODY = 7,
486 CMD_METHOD_RESOLVE_TOKEN = 8,
487 CMD_METHOD_GET_CATTRS = 9,
488 CMD_METHOD_MAKE_GENERIC_METHOD = 10
492 CMD_TYPE_GET_INFO = 1,
493 CMD_TYPE_GET_METHODS = 2,
494 CMD_TYPE_GET_FIELDS = 3,
495 CMD_TYPE_GET_VALUES = 4,
496 CMD_TYPE_GET_OBJECT = 5,
497 CMD_TYPE_GET_SOURCE_FILES = 6,
498 CMD_TYPE_SET_VALUES = 7,
499 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
500 CMD_TYPE_GET_PROPERTIES = 9,
501 CMD_TYPE_GET_CATTRS = 10,
502 CMD_TYPE_GET_FIELD_CATTRS = 11,
503 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
504 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
505 CMD_TYPE_GET_VALUES_2 = 14,
506 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
507 CMD_TYPE_GET_INTERFACES = 16,
508 CMD_TYPE_GET_INTERFACE_MAP = 17,
509 CMD_TYPE_IS_INITIALIZED = 18,
510 CMD_TYPE_CREATE_INSTANCE = 19
514 CMD_STACK_FRAME_GET_VALUES = 1,
515 CMD_STACK_FRAME_GET_THIS = 2,
516 CMD_STACK_FRAME_SET_VALUES = 3
520 CMD_ARRAY_REF_GET_LENGTH = 1,
521 CMD_ARRAY_REF_GET_VALUES = 2,
522 CMD_ARRAY_REF_SET_VALUES = 3,
526 CMD_STRING_REF_GET_VALUE = 1,
527 CMD_STRING_REF_GET_LENGTH = 2,
528 CMD_STRING_REF_GET_CHARS = 3
532 CMD_OBJECT_REF_GET_TYPE = 1,
533 CMD_OBJECT_REF_GET_VALUES = 2,
534 CMD_OBJECT_REF_IS_COLLECTED = 3,
535 CMD_OBJECT_REF_GET_ADDRESS = 4,
536 CMD_OBJECT_REF_GET_DOMAIN = 5,
537 CMD_OBJECT_REF_SET_VALUES = 6,
538 CMD_OBJECT_REF_GET_INFO = 7,
544 int count; /* For kind == MOD_KIND_COUNT */
545 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
546 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
547 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
548 GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
549 GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
550 StepFilter filter; /* For kind == MOD_KIND_STEP */
552 gboolean caught, uncaught, subclasses; /* For kind == MOD_KIND_EXCEPTION_ONLY */
561 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
565 * Describes a single step request.
569 MonoInternalThread *thread;
575 MonoMethod *last_method;
577 /* Whenever single stepping is performed using start/stop_single_stepping () */
579 /* The list of breakpoints used to implement step-over */
581 /* The number of frames at the start of a step-over */
586 * Contains additional information for an event
589 /* For EVENT_KIND_EXCEPTION */
591 MonoContext catch_ctx;
593 /* For EVENT_KIND_USER_LOG */
595 char *category, *message;
596 /* For EVENT_KIND_TYPE_LOAD */
600 /* Dummy structure used for the profiler callbacks */
606 guint8 *buf, *p, *end;
609 typedef struct ReplyPacket {
615 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
618 #define get_last_sock_error() WSAGetLastError()
619 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
620 #define MONO_EINTR WSAEINTR
622 #define get_last_sock_error() errno
623 #define MONO_EWOULDBLOCK EWOULDBLOCK
624 #define MONO_EINTR EINTR
627 #define CHECK_PROTOCOL_VERSION(major,minor) \
628 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
634 static AgentConfig agent_config;
637 * Whenever the agent is fully initialized.
638 * When using the onuncaught or onthrow options, only some parts of the agent are
639 * initialized on startup, and the full initialization which includes connection
640 * establishment and the startup of the agent thread is only done in response to
643 static gint32 inited;
645 #ifndef DISABLE_SOCKET_TRANSPORT
647 static int listen_fd;
650 static int packet_id = 0;
652 static int objref_id = 0;
654 static int event_request_id = 0;
656 static int frame_id = 0;
658 static GPtrArray *event_requests;
660 static MonoNativeTlsKey debugger_tls_id;
662 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
664 /* Maps MonoInternalThread -> DebuggerTlsData */
665 static MonoGHashTable *thread_to_tls;
667 /* Maps tid -> MonoInternalThread */
668 static MonoGHashTable *tid_to_thread;
670 /* Maps tid -> MonoThread (not MonoInternalThread) */
671 static MonoGHashTable *tid_to_thread_obj;
673 static gsize debugger_thread_id;
675 static HANDLE debugger_thread_handle;
677 static int log_level;
679 static gboolean embedding;
681 static FILE *log_file;
683 /* Assemblies whose assembly load event has no been sent yet */
684 /* Protected by the dbg lock */
685 static GPtrArray *pending_assembly_loads;
687 /* Whenever the debugger thread has exited */
688 static gboolean debugger_thread_exited;
690 /* Cond variable used to wait for debugger_thread_exited becoming true */
691 static mono_cond_t debugger_thread_exited_cond;
693 /* Mutex for the cond var above */
694 static mono_mutex_t debugger_thread_exited_mutex;
696 static DebuggerProfiler debugger_profiler;
698 /* The single step request instance */
699 static SingleStepReq *ss_req;
700 static gpointer ss_invoke_addr;
702 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
703 /* Number of single stepping operations in progress */
707 /* The protocol version of the client */
708 static int major_version, minor_version;
710 /* Whenever the variables above are set by the client */
711 static gboolean protocol_version_set;
713 /* A hash table containing all active domains */
714 static GHashTable *domains;
716 /* The number of times the runtime is suspended */
717 static gint32 suspend_count;
719 /* Whenever to buffer reply messages and send them together */
720 static gboolean buffer_replies;
722 /* Buffered reply packets */
723 static ReplyPacket reply_packets [128];
726 #define dbg_lock() mono_mutex_lock (&debug_mutex)
727 #define dbg_unlock() mono_mutex_unlock (&debug_mutex)
728 static mono_mutex_t debug_mutex;
730 static void transport_init (void);
731 static void transport_connect (const char *address);
732 static gboolean transport_handshake (void);
733 static void register_transport (DebuggerTransport *trans);
735 static guint32 WINAPI debugger_thread (void *arg);
737 static void runtime_initialized (MonoProfiler *prof);
739 static void runtime_shutdown (MonoProfiler *prof);
741 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
743 static void thread_end (MonoProfiler *prof, uintptr_t tid);
745 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
747 static void appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain);
749 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
751 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
753 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
755 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
757 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
759 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
761 static void emit_assembly_load (gpointer assembly, gpointer user_data);
763 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
765 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
767 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
769 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
771 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
773 static void start_single_stepping (void);
775 static void stop_single_stepping (void);
777 static void suspend_current (void);
779 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
781 static void clear_types_for_assembly (MonoAssembly *assembly);
783 static void clear_breakpoints_for_domain (MonoDomain *domain);
785 static void process_profiler_event (EventKind event, gpointer arg);
787 /* Submodule init/cleanup */
788 static void breakpoints_init (void);
789 static void breakpoints_cleanup (void);
791 static void objrefs_init (void);
792 static void objrefs_cleanup (void);
794 static void ids_init (void);
795 static void ids_cleanup (void);
797 static void suspend_init (void);
799 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch);
800 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
801 static void ss_destroy (SingleStepReq *req);
803 static void start_debugger_thread (void);
804 static void stop_debugger_thread (void);
806 static void finish_agent_init (gboolean on_startup);
808 static void process_profiler_event (EventKind event, gpointer arg);
810 static void invalidate_frames (DebuggerTlsData *tls);
812 #ifndef DISABLE_SOCKET_TRANSPORT
814 register_socket_transport (void);
818 parse_address (char *address, char **host, int *port)
820 char *pos = strchr (address, ':');
822 if (pos == NULL || pos == address)
825 *host = g_malloc (pos - address + 1);
826 strncpy (*host, address, pos - address);
827 (*host) [pos - address] = '\0';
829 *port = atoi (pos + 1);
837 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
838 fprintf (stderr, "Available options:\n");
839 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
840 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
841 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
842 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
843 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
844 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
845 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
846 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
847 fprintf (stderr, " setpgid=y/n\t\t\tWhether to call setpid(0, 0) after startup.\n");
848 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
852 parse_flag (const char *option, char *flag)
854 if (!strcmp (flag, "y"))
856 else if (!strcmp (flag, "n"))
859 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
866 mono_debugger_agent_parse_options (char *options)
873 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
874 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
878 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
880 options = g_strdup_printf ("%s,%s", options, extra);
882 agent_config.enabled = TRUE;
883 agent_config.suspend = TRUE;
884 agent_config.server = FALSE;
885 agent_config.defer = FALSE;
886 agent_config.address = NULL;
888 //agent_config.log_level = 10;
890 args = g_strsplit (options, ",", -1);
891 for (ptr = args; ptr && *ptr; ptr ++) {
894 if (strncmp (arg, "transport=", 10) == 0) {
895 agent_config.transport = g_strdup (arg + 10);
896 } else if (strncmp (arg, "address=", 8) == 0) {
897 agent_config.address = g_strdup (arg + 8);
898 } else if (strncmp (arg, "loglevel=", 9) == 0) {
899 agent_config.log_level = atoi (arg + 9);
900 } else if (strncmp (arg, "logfile=", 8) == 0) {
901 agent_config.log_file = g_strdup (arg + 8);
902 } else if (strncmp (arg, "suspend=", 8) == 0) {
903 agent_config.suspend = parse_flag ("suspend", arg + 8);
904 } else if (strncmp (arg, "server=", 7) == 0) {
905 agent_config.server = parse_flag ("server", arg + 7);
906 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
907 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
908 } else if (strncmp (arg, "onthrow=", 8) == 0) {
909 /* We support multiple onthrow= options */
910 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
911 } else if (strncmp (arg, "onthrow", 7) == 0) {
912 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
913 } else if (strncmp (arg, "help", 4) == 0) {
916 } else if (strncmp (arg, "timeout=", 8) == 0) {
917 agent_config.timeout = atoi (arg + 8);
918 } else if (strncmp (arg, "launch=", 7) == 0) {
919 agent_config.launch = g_strdup (arg + 7);
920 } else if (strncmp (arg, "embedding=", 10) == 0) {
921 agent_config.embedding = atoi (arg + 10) == 1;
922 } else if (strncmp (arg, "keepalive=", 10) == 0) {
923 agent_config.keepalive = atoi (arg + 10);
924 } else if (strncmp (arg, "setpgid=", 8) == 0) {
925 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
932 if (agent_config.server && !agent_config.suspend) {
933 /* Waiting for deferred attachment */
934 agent_config.defer = TRUE;
935 if (agent_config.address == NULL) {
936 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (getpid () % 1000));
940 //agent_config.log_level = 0;
942 if (agent_config.transport == NULL) {
943 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
947 if (agent_config.address == NULL && !agent_config.server) {
948 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
953 if (!strcmp (agent_config.transport, "dt_socket")) {
954 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
955 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
962 mono_debugger_agent_init (void)
964 mono_mutex_init_recursive (&debug_mutex);
966 if (!agent_config.enabled)
971 /* Need to know whenever a thread has acquired the loader mutex */
972 mono_loader_lock_track_ownership (TRUE);
974 event_requests = g_ptr_array_new ();
976 mono_mutex_init (&debugger_thread_exited_mutex);
977 mono_cond_init (&debugger_thread_exited_cond, NULL);
979 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
980 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
981 mono_profiler_install_runtime_initialized (runtime_initialized);
982 mono_profiler_install_appdomain (NULL, appdomain_load, appdomain_start_unload, appdomain_unload);
983 mono_profiler_install_thread (thread_startup, thread_end);
984 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
985 mono_profiler_install_jit_end (jit_end);
986 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
988 mono_native_tls_alloc (&debugger_tls_id, NULL);
990 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
991 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls);
993 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
994 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread);
996 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
997 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj);
999 pending_assembly_loads = g_ptr_array_new ();
1000 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
1002 log_level = agent_config.log_level;
1004 embedding = agent_config.embedding;
1005 disconnected = TRUE;
1007 if (agent_config.log_file) {
1008 log_file = fopen (agent_config.log_file, "w+");
1010 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
1019 breakpoints_init ();
1022 mini_get_debug_options ()->gen_seq_points = TRUE;
1024 * This is needed because currently we don't handle liveness info.
1026 mini_get_debug_options ()->mdb_optimizations = TRUE;
1028 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
1029 /* This is needed because we can't set local variables in registers yet */
1030 mono_disable_optimizations (MONO_OPT_LINEARS);
1034 * The stack walk done from thread_interrupt () needs to be signal safe, but it
1035 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
1036 * safe (#3411). So load AOT info eagerly when the debugger is running as a
1039 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
1042 if (agent_config.setpgid)
1046 if (!agent_config.onuncaught && !agent_config.onthrow)
1047 finish_agent_init (TRUE);
1051 * finish_agent_init:
1053 * Finish the initialization of the agent. This involves connecting the transport
1054 * and starting the agent thread. This is either done at startup, or
1055 * in response to some event like an unhandled exception.
1058 finish_agent_init (gboolean on_startup)
1062 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
1065 if (agent_config.launch) {
1068 // FIXME: Generated address
1069 // FIXME: Races with transport_connect ()
1071 argv [0] = agent_config.launch;
1072 argv [1] = agent_config.transport;
1073 argv [2] = agent_config.address;
1076 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1078 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1083 transport_connect (agent_config.address);
1086 /* Do some which is usually done after sending the VMStart () event */
1087 vm_start_event_sent = TRUE;
1088 start_debugger_thread ();
1093 mono_debugger_agent_cleanup (void)
1098 stop_debugger_thread ();
1100 breakpoints_cleanup ();
1104 mono_mutex_destroy (&debugger_thread_exited_mutex);
1105 mono_cond_destroy (&debugger_thread_exited_cond);
1112 #ifndef DISABLE_SOCKET_TRANSPORT
1117 * recv() + handle incomplete reads and EINTR
1120 socket_transport_recv (void *buf, int len)
1126 static gint32 last_keepalive;
1131 res = recv (fd, (char *) buf + total, len - total, flags);
1134 if (agent_config.keepalive) {
1135 gboolean need_keepalive = FALSE;
1136 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1137 need_keepalive = TRUE;
1138 } else if (res == -1) {
1139 /* This could happen if recv () is interrupted repeatedly */
1140 msecs = mono_msec_ticks ();
1141 if (msecs - last_keepalive >= agent_config.keepalive) {
1142 need_keepalive = TRUE;
1143 last_keepalive = msecs;
1146 if (need_keepalive) {
1147 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1151 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1156 #define HAVE_GETADDRINFO 1
1160 set_keepalive (void)
1165 if (!agent_config.keepalive || !conn_fd)
1168 tv.tv_sec = agent_config.keepalive / 1000;
1169 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1171 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1172 g_assert (result >= 0);
1176 socket_transport_accept (int socket_fd)
1178 conn_fd = accept (socket_fd, NULL, NULL);
1179 if (conn_fd == -1) {
1180 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1182 DEBUG (1, fprintf (log_file, "Accepted connection from client, connection fd=%d.\n", conn_fd));
1189 socket_transport_send (void *data, int len)
1194 res = send (conn_fd, data, len, 0);
1195 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1203 * socket_transport_connect:
1205 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1208 socket_transport_connect (const char *address)
1210 #ifdef HAVE_GETADDRINFO
1211 struct addrinfo hints;
1212 struct addrinfo *result, *rp;
1214 struct hostent *result;
1216 int sfd = -1, s, res;
1217 char port_string [128];
1221 if (agent_config.address) {
1222 res = parse_address (agent_config.address, &host, &port);
1223 g_assert (res == 0);
1233 sprintf (port_string, "%d", port);
1235 mono_network_init ();
1237 /* Obtain address(es) matching host/port */
1238 #ifdef HAVE_GETADDRINFO
1239 memset (&hints, 0, sizeof (struct addrinfo));
1240 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
1241 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
1243 hints.ai_protocol = 0; /* Any protocol */
1245 s = getaddrinfo (host, port_string, &hints, &result);
1247 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %s\n", host, port, gai_strerror (s));
1251 /* The PS3 doesn't even have _r or hstrerror () */
1252 result = gethostbyname (host);
1254 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, h_errno);
1259 if (agent_config.server) {
1260 #ifdef HAVE_GETADDRINFO
1261 /* Wait for a connection */
1263 struct sockaddr_in addr;
1266 /* No address, generate one */
1267 sfd = socket (AF_INET, SOCK_STREAM, 0);
1270 /* This will bind the socket to a random port */
1271 res = listen (sfd, 16);
1273 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1278 addrlen = sizeof (addr);
1279 memset (&addr, 0, sizeof (addr));
1280 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1281 g_assert (res == 0);
1283 host = (char*)"127.0.0.1";
1284 port = ntohs (addr.sin_port);
1286 /* Emit the address to stdout */
1287 /* FIXME: Should print another interface, not localhost */
1288 printf ("%s:%d\n", host, port);
1290 /* Listen on the provided address */
1291 for (rp = result; rp != NULL; rp = rp->ai_next) {
1294 sfd = socket (rp->ai_family, rp->ai_socktype,
1299 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1302 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
1306 res = listen (sfd, 16);
1315 * this function is not present on win2000 which we still support, and the
1316 * workaround described here:
1317 * http://msdn.microsoft.com/en-us/library/ms737931(VS.85).aspx
1318 * only works with MSVC.
1320 #ifdef HAVE_GETADDRINFO
1321 freeaddrinfo (result);
1326 if (agent_config.defer)
1329 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
1331 if (agent_config.timeout) {
1336 tv.tv_usec = agent_config.timeout * 1000;
1338 FD_SET (sfd, &readfds);
1339 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1341 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1346 conn_fd = socket_transport_accept (sfd);
1350 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
1353 #endif /* HAVE_GETADDRINFO */
1355 /* Connect to the specified address */
1356 #ifdef HAVE_GETADDRINFO
1357 /* FIXME: Respect the timeout */
1358 for (rp = result; rp != NULL; rp = rp->ai_next) {
1359 sfd = socket (rp->ai_family, rp->ai_socktype,
1364 if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
1365 break; /* Success */
1371 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1375 sfd = socket (result->h_addrtype, SOCK_STREAM, 0);
1377 g_assert_not_reached ();
1378 res = connect (sfd, (void*)result->h_addr_list [0], result->h_length);
1380 g_assert_not_reached ();
1386 /* See the comment above */
1387 #ifdef HAVE_GETADDRINFO
1388 freeaddrinfo (result);
1393 if (!transport_handshake ())
1398 socket_transport_close1 (void)
1400 /* This will interrupt the agent thread */
1401 /* Close the read part only so it can still send back replies */
1402 /* Also shut down the connection listener so that we can exit normally */
1404 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1405 shutdown (conn_fd, SD_BOTH);
1406 shutdown (listen_fd, SD_BOTH);
1407 closesocket (listen_fd);
1409 shutdown (conn_fd, SHUT_RD);
1410 shutdown (listen_fd, SHUT_RDWR);
1416 socket_transport_close2 (void)
1419 shutdown (conn_fd, SD_BOTH);
1421 shutdown (conn_fd, SHUT_RDWR);
1426 register_socket_transport (void)
1428 DebuggerTransport trans;
1430 trans.name = "dt_socket";
1431 trans.connect = socket_transport_connect;
1432 trans.close1 = socket_transport_close1;
1433 trans.close2 = socket_transport_close2;
1434 trans.send = socket_transport_send;
1435 trans.recv = socket_transport_recv;
1437 register_transport (&trans);
1441 * socket_fd_transport_connect:
1445 socket_fd_transport_connect (const char *address)
1449 res = sscanf (address, "%d", &conn_fd);
1451 fprintf (stderr, "debugger-agent: socket-fd transport address is invalid: '%s'\n", address);
1455 if (!transport_handshake ())
1460 register_socket_fd_transport (void)
1462 DebuggerTransport trans;
1464 /* This is the same as the 'dt_socket' transport, but receives an already connected socket fd */
1465 trans.name = "socket-fd";
1466 trans.connect = socket_fd_transport_connect;
1467 trans.close1 = socket_transport_close1;
1468 trans.close2 = socket_transport_close2;
1469 trans.send = socket_transport_send;
1470 trans.recv = socket_transport_recv;
1472 register_transport (&trans);
1475 #endif /* DISABLE_SOCKET_TRANSPORT */
1481 #define MAX_TRANSPORTS 16
1483 static DebuggerTransport *transport;
1485 static DebuggerTransport transports [MAX_TRANSPORTS];
1486 static int ntransports;
1489 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1492 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1494 register_transport (trans);
1498 register_transport (DebuggerTransport *trans)
1500 g_assert (ntransports < MAX_TRANSPORTS);
1502 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1507 transport_init (void)
1511 #ifndef DISABLE_SOCKET_TRANSPORT
1512 register_socket_transport ();
1513 register_socket_fd_transport ();
1516 for (i = 0; i < ntransports; ++i) {
1517 if (!strcmp (agent_config.transport, transports [i].name))
1520 if (i == ntransports) {
1521 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1522 for (i = 0; i < ntransports; ++i)
1523 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1524 fprintf (stderr, "\n");
1527 transport = &transports [i];
1531 transport_connect (const char *address)
1533 transport->connect (address);
1537 transport_close1 (void)
1539 transport->close1 ();
1543 transport_close2 (void)
1545 transport->close2 ();
1549 transport_send (void *buf, int len)
1551 return transport->send (buf, len);
1555 transport_recv (void *buf, int len)
1557 return transport->recv (buf, len);
1561 mono_debugger_agent_transport_handshake (void)
1563 return transport_handshake ();
1567 transport_handshake (void)
1569 char handshake_msg [128];
1573 disconnected = TRUE;
1575 /* Write handshake message */
1576 sprintf (handshake_msg, "DWP-Handshake");
1578 res = transport_send (handshake_msg, strlen (handshake_msg));
1579 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1580 g_assert (res != -1);
1583 res = transport_recv (buf, strlen (handshake_msg));
1584 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg) != 0))) {
1585 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1590 * To support older clients, the client sends its protocol version after connecting
1591 * using a command. Until that is received, default to our protocol version.
1593 major_version = MAJOR_VERSION;
1594 minor_version = MINOR_VERSION;
1595 protocol_version_set = FALSE;
1597 #ifndef DISABLE_SOCKET_TRANSPORT
1598 // FIXME: Move this somewhere else
1600 * Set TCP_NODELAY on the socket so the client receives events/command
1601 * results immediately.
1605 int result = setsockopt (conn_fd,
1610 g_assert (result >= 0);
1616 disconnected = FALSE;
1621 stop_debugger_thread (void)
1626 transport_close1 ();
1629 * Wait for the thread to exit.
1631 * If we continue with the shutdown without waiting for it, then the client might
1632 * not receive an answer to its last command like a resume.
1633 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
1636 //WaitForSingleObject (debugger_thread_handle, INFINITE);
1637 if (GetCurrentThreadId () != debugger_thread_id) {
1639 mono_mutex_lock (&debugger_thread_exited_mutex);
1640 if (!debugger_thread_exited) {
1642 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
1643 mono_mutex_unlock (&debugger_thread_exited_mutex);
1645 mono_mutex_lock (&debugger_thread_exited_mutex);
1648 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1651 mono_mutex_unlock (&debugger_thread_exited_mutex);
1652 } while (!debugger_thread_exited);
1655 transport_close2 ();
1659 start_debugger_thread (void)
1661 debugger_thread_handle = mono_threads_create_thread (debugger_thread, NULL, 0, 0, NULL);
1662 g_assert (debugger_thread_handle);
1666 * Functions to decode protocol data
1670 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1673 g_assert (*endbuf <= limit);
1678 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1681 g_assert (*endbuf <= limit);
1683 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1686 static inline gint64
1687 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1689 guint32 high = decode_int (buf, &buf, limit);
1690 guint32 low = decode_int (buf, &buf, limit);
1694 return ((((guint64)high) << 32) | ((guint64)low));
1698 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1700 return decode_int (buf, endbuf, limit);
1704 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1706 int len = decode_int (buf, &buf, limit);
1714 s = g_malloc (len + 1);
1717 memcpy (s, buf, len);
1726 * Functions to encode protocol data
1730 buffer_init (Buffer *buf, int size)
1732 buf->buf = g_malloc (size);
1734 buf->end = buf->buf + size;
1738 buffer_len (Buffer *buf)
1740 return buf->p - buf->buf;
1744 buffer_make_room (Buffer *buf, int size)
1746 if (buf->end - buf->p < size) {
1747 int new_size = buf->end - buf->buf + size + 32;
1748 guint8 *p = g_realloc (buf->buf, new_size);
1749 size = buf->p - buf->buf;
1752 buf->end = buf->buf + new_size;
1757 buffer_add_byte (Buffer *buf, guint8 val)
1759 buffer_make_room (buf, 1);
1765 buffer_add_short (Buffer *buf, guint32 val)
1767 buffer_make_room (buf, 2);
1768 buf->p [0] = (val >> 8) & 0xff;
1769 buf->p [1] = (val >> 0) & 0xff;
1774 buffer_add_int (Buffer *buf, guint32 val)
1776 buffer_make_room (buf, 4);
1777 buf->p [0] = (val >> 24) & 0xff;
1778 buf->p [1] = (val >> 16) & 0xff;
1779 buf->p [2] = (val >> 8) & 0xff;
1780 buf->p [3] = (val >> 0) & 0xff;
1785 buffer_add_long (Buffer *buf, guint64 l)
1787 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1788 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1792 buffer_add_id (Buffer *buf, int id)
1794 buffer_add_int (buf, (guint64)id);
1798 buffer_add_data (Buffer *buf, guint8 *data, int len)
1800 buffer_make_room (buf, len);
1801 memcpy (buf->p, data, len);
1806 buffer_add_string (Buffer *buf, const char *str)
1811 buffer_add_int (buf, 0);
1814 buffer_add_int (buf, len);
1815 buffer_add_data (buf, (guint8*)str, len);
1820 buffer_add_buffer (Buffer *buf, Buffer *data)
1822 buffer_add_data (buf, data->buf, buffer_len (data));
1826 buffer_free (Buffer *buf)
1832 send_packet (int command_set, int command, Buffer *data)
1838 id = InterlockedIncrement (&packet_id);
1840 len = data->p - data->buf + 11;
1841 buffer_init (&buf, len);
1842 buffer_add_int (&buf, len);
1843 buffer_add_int (&buf, id);
1844 buffer_add_byte (&buf, 0); /* flags */
1845 buffer_add_byte (&buf, command_set);
1846 buffer_add_byte (&buf, command);
1847 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1849 res = transport_send (buf.buf, len);
1857 send_reply_packets (int npackets, ReplyPacket *packets)
1864 for (i = 0; i < npackets; ++i)
1865 len += buffer_len (packets [i].data) + 11;
1866 buffer_init (&buf, len);
1867 for (i = 0; i < npackets; ++i) {
1868 buffer_add_int (&buf, buffer_len (packets [i].data) + 11);
1869 buffer_add_int (&buf, packets [i].id);
1870 buffer_add_byte (&buf, 0x80); /* flags */
1871 buffer_add_byte (&buf, (packets [i].error >> 8) & 0xff);
1872 buffer_add_byte (&buf, packets [i].error);
1873 buffer_add_buffer (&buf, packets [i].data);
1875 res = transport_send (buf.buf, len);
1883 send_reply_packet (int id, int error, Buffer *data)
1887 memset (&packet, 0, sizeof (ReplyPacket));
1889 packet.error = error;
1892 return send_reply_packets (1, &packet);
1896 send_buffered_reply_packets (void)
1900 send_reply_packets (nreply_packets, reply_packets);
1901 for (i = 0; i < nreply_packets; ++i)
1902 buffer_free (reply_packets [i].data);
1903 DEBUG (1, fprintf (log_file, "[dbg] Sent %d buffered reply packets [at=%lx].\n", nreply_packets, (long)mono_100ns_ticks () / 10000));
1908 buffer_reply_packet (int id, int error, Buffer *data)
1912 if (nreply_packets == 128)
1913 send_buffered_reply_packets ();
1915 p = &reply_packets [nreply_packets];
1918 p->data = g_new0 (Buffer, 1);
1919 buffer_init (p->data, buffer_len (data));
1920 buffer_add_buffer (p->data, data);
1929 * Represents an object accessible by the debugger client.
1932 /* Unique id used in the wire protocol to refer to objects */
1935 * A weakref gc handle pointing to the object. The gc handle is used to
1936 * detect if the object was garbage collected.
1941 /* Maps objid -> ObjRef */
1942 static GHashTable *objrefs;
1943 static GHashTable *obj_to_objref;
1944 /* Protected by the dbg lock */
1945 static MonoGHashTable *suspended_objs;
1948 free_objref (gpointer value)
1952 mono_gchandle_free (o->handle);
1960 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1961 obj_to_objref = g_hash_table_new (NULL, NULL);
1962 suspended_objs = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
1963 MONO_GC_REGISTER_ROOT_FIXED (suspended_objs);
1967 objrefs_cleanup (void)
1969 g_hash_table_destroy (objrefs);
1974 * Return an ObjRef for OBJ.
1977 get_objref (MonoObject *obj)
1980 GSList *reflist = NULL, *l;
1986 if (suspend_count) {
1988 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1991 mono_g_hash_table_insert (suspended_objs, obj, NULL);
1995 mono_loader_lock ();
1997 /* FIXME: The tables can grow indefinitely */
1999 if (mono_gc_is_moving ()) {
2001 * Objects can move, so use a hash table mapping hash codes to lists of
2002 * ObjRef structures.
2004 hash = mono_object_hash (obj);
2006 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
2007 for (l = reflist; l; l = l->next) {
2009 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
2010 mono_loader_unlock ();
2015 /* Use a hash table with masked pointers to internalize object references */
2016 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
2017 /* ref might refer to a different object with the same addr which was GCd */
2018 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
2019 mono_loader_unlock ();
2024 ref = g_new0 (ObjRef, 1);
2025 ref->id = InterlockedIncrement (&objref_id);
2026 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
2028 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
2030 if (mono_gc_is_moving ()) {
2031 reflist = g_slist_append (reflist, ref);
2032 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
2034 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
2037 mono_loader_unlock ();
2043 true_pred (gpointer key, gpointer value, gpointer user_data)
2049 clear_suspended_objs (void)
2052 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
2057 get_objid (MonoObject *obj)
2059 return get_objref (obj)->id;
2063 * Set OBJ to the object identified by OBJID.
2064 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
2068 get_object_allow_null (int objid, MonoObject **obj)
2078 return ERR_INVALID_OBJECT;
2080 mono_loader_lock ();
2082 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
2085 *obj = mono_gchandle_get_target (ref->handle);
2086 mono_loader_unlock ();
2088 return ERR_INVALID_OBJECT;
2091 mono_loader_unlock ();
2092 return ERR_INVALID_OBJECT;
2097 get_object (int objid, MonoObject **obj)
2099 int err = get_object_allow_null (objid, obj);
2104 return ERR_INVALID_OBJECT;
2109 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
2111 return decode_id (buf, endbuf, limit);
2115 buffer_add_objid (Buffer *buf, MonoObject *o)
2117 buffer_add_id (buf, get_objid (o));
2136 * Represents a runtime structure accessible to the debugger client
2139 /* Unique id used in the wire protocol */
2141 /* Domain of the runtime structure, NULL if the domain was unloaded */
2148 MonoAssembly *assembly;
2149 MonoClassField *field;
2151 MonoProperty *property;
2156 /* Maps runtime structure -> Id */
2157 GHashTable *val_to_id [ID_NUM];
2158 /* Classes whose class load event has been sent */
2159 GHashTable *loaded_classes;
2160 /* Maps MonoClass->GPtrArray of file names */
2161 GHashTable *source_files;
2162 /* Maps source file basename -> GSList of classes */
2163 GHashTable *source_file_to_class;
2164 /* Same with ignore-case */
2165 GHashTable *source_file_to_class_ignorecase;
2169 /* Protected by the dbg lock */
2170 static GPtrArray *ids [ID_NUM];
2177 for (i = 0; i < ID_NUM; ++i)
2178 ids [i] = g_ptr_array_new ();
2186 for (i = 0; i < ID_NUM; ++i) {
2188 for (j = 0; j < ids [i]->len; ++j)
2189 g_free (g_ptr_array_index (ids [i], j));
2190 g_ptr_array_free (ids [i], TRUE);
2197 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2199 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
2201 GHashTableIter iter;
2202 GPtrArray *file_names;
2207 for (i = 0; i < ID_NUM; ++i)
2208 if (info->val_to_id [i])
2209 g_hash_table_destroy (info->val_to_id [i]);
2210 g_hash_table_destroy (info->loaded_classes);
2212 g_hash_table_iter_init (&iter, info->source_files);
2213 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2214 for (i = 0; i < file_names->len; ++i)
2215 g_free (g_ptr_array_index (file_names, i));
2216 g_ptr_array_free (file_names, TRUE);
2219 g_hash_table_iter_init (&iter, info->source_file_to_class);
2220 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2225 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2226 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2234 domain_jit_info (domain)->agent_info = NULL;
2236 /* Clear ids referencing structures in the domain */
2238 for (i = 0; i < ID_NUM; ++i) {
2240 for (j = 0; j < ids [i]->len; ++j) {
2241 Id *id = g_ptr_array_index (ids [i], j);
2242 if (id->domain == domain)
2249 mono_loader_lock ();
2250 g_hash_table_remove (domains, domain);
2251 mono_loader_unlock ();
2254 static AgentDomainInfo*
2255 get_agent_domain_info (MonoDomain *domain)
2257 AgentDomainInfo *info = NULL;
2259 mono_domain_lock (domain);
2261 info = domain_jit_info (domain)->agent_info;
2263 info = domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
2264 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2265 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2266 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2267 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2270 mono_domain_unlock (domain);
2276 get_id (MonoDomain *domain, IdType type, gpointer val)
2279 AgentDomainInfo *info;
2284 mono_loader_lock ();
2286 mono_domain_lock (domain);
2288 info = get_agent_domain_info (domain);
2290 if (info->val_to_id [type] == NULL)
2291 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2293 id = g_hash_table_lookup (info->val_to_id [type], val);
2295 mono_domain_unlock (domain);
2296 mono_loader_unlock ();
2302 id = g_new0 (Id, 1);
2304 id->id = ids [type]->len + 1;
2305 id->domain = domain;
2308 g_hash_table_insert (info->val_to_id [type], val, id);
2309 g_ptr_array_add (ids [type], id);
2313 mono_domain_unlock (domain);
2315 mono_loader_unlock ();
2320 static inline gpointer
2321 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
2325 int id = decode_id (buf, endbuf, limit);
2334 // FIXME: error handling
2336 g_assert (id > 0 && id <= ids [type]->len);
2338 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2341 if (res->domain == NULL) {
2342 DEBUG (0, fprintf (log_file, "ERR_UNLOADED, id=%d, type=%d.\n", id, type));
2343 *err = ERR_UNLOADED;
2348 *domain = res->domain;
2350 return res->data.val;
2354 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2356 int id = get_id (domain, type, val);
2358 buffer_add_id (buf, id);
2362 static inline MonoClass*
2363 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2367 klass = decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2368 if (G_UNLIKELY (log_level >= 2) && klass) {
2371 s = mono_type_full_name (&klass->byval_arg);
2372 DEBUG(2, fprintf (log_file, "[dbg] recv class [%s]\n", s));
2378 static inline MonoAssembly*
2379 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2381 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2384 static inline MonoImage*
2385 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2387 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2390 static inline MonoMethod*
2391 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2395 m = decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2396 if (G_UNLIKELY (log_level >= 2) && m) {
2399 s = mono_method_full_name (m, TRUE);
2400 DEBUG(2, fprintf (log_file, "[dbg] recv method [%s]\n", s));
2406 static inline MonoClassField*
2407 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2409 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2412 static inline MonoDomain*
2413 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2415 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2418 static inline MonoProperty*
2419 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2421 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2425 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2427 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2428 if (G_UNLIKELY (log_level >= 2) && klass) {
2431 s = mono_type_full_name (&klass->byval_arg);
2432 if (GetCurrentThreadId () == debugger_thread_id)
2433 DEBUG(2, fprintf (log_file, "[dbg] send class [%s]\n", s));
2435 DEBUG(2, fprintf (log_file, "[%p] send class [%s]\n", (gpointer)GetCurrentThreadId (), s));
2441 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2443 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2444 if (G_UNLIKELY (log_level >= 2) && method) {
2447 s = mono_method_full_name (method, 1);
2448 DEBUG(2, fprintf (log_file, "[dbg] send method [%s]\n", s));
2454 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2458 id = buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2459 if (G_UNLIKELY (log_level >= 2) && assembly)
2460 DEBUG(2, fprintf (log_file, "[dbg] send assembly [%s][%s][%d]\n", assembly->aname.name, domain->friendly_name, id));
2464 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2466 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2470 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2472 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2476 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2478 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2482 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2484 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2487 static void invoke_method (void);
2494 * save_thread_context:
2496 * Set CTX as the current threads context which is used for computing stack traces.
2497 * This function is signal-safe.
2500 save_thread_context (MonoContext *ctx)
2502 DebuggerTlsData *tls;
2504 tls = mono_native_tls_get_value (debugger_tls_id);
2508 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2510 mono_thread_state_init_from_current (&tls->context);
2513 /* Number of threads suspended */
2515 * If this is equal to the size of thread_to_tls, the runtime is considered
2518 static gint32 threads_suspend_count;
2520 static mono_mutex_t suspend_mutex;
2522 /* Cond variable used to wait for suspend_count becoming 0 */
2523 static mono_cond_t suspend_cond;
2525 /* Semaphore used to wait for a thread becoming suspended */
2526 static MonoSemType suspend_sem;
2531 mono_mutex_init (&suspend_mutex);
2532 mono_cond_init (&suspend_cond, NULL);
2533 MONO_SEM_INIT (&suspend_sem, 0);
2538 StackFrameInfo last_frame;
2539 gboolean last_frame_set;
2542 } GetLastFrameUserData;
2545 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2547 GetLastFrameUserData *data = user_data;
2549 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
2552 if (!data->last_frame_set) {
2553 /* Store the last frame */
2554 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2555 data->last_frame_set = TRUE;
2558 /* Store the context/lmf for the frame above the last frame */
2559 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2560 data->lmf = info->lmf;
2568 * Process interruption of a thread. If SIGCTX is set, process the current thread. If
2569 * INFO is set, process the thread described by INFO.
2570 * This should be signal safe.
2573 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, void *sigctx, MonoJitInfo *ji)
2577 MonoNativeThreadId tid;
2580 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2581 * guarantee the signal handler will be called that many times. Instead of tracking
2582 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2583 * has been requested that hasn't been handled yet, otherwise we can have threads
2584 * refuse to die when VM_EXIT is called
2586 #if defined(__APPLE__)
2587 if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
2591 * We use interrupt_count to determine whenever this interrupt should be processed
2592 * by us or the normal interrupt processing code in the signal handler.
2593 * There is no race here with notify_thread (), since the signal is sent after
2594 * incrementing interrupt_count.
2596 if (tls->interrupt_count == 0)
2599 InterlockedDecrement (&tls->interrupt_count);
2603 ip = mono_arch_ip_from_context (sigctx);
2605 ip = MONO_CONTEXT_GET_IP (&info->suspend_state.ctx);
2610 tid = mono_thread_info_get_tid (info);
2612 tid = (MonoNativeThreadId)GetCurrentThreadId ();
2614 // FIXME: Races when the thread leaves managed code before hitting a single step
2618 /* Running managed code, will be suspended by the single step code */
2619 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip));
2623 * Running native code, will be suspended when it returns to/enters
2624 * managed code. Treat it as already suspended.
2625 * This might interrupt the code in process_single_step_inner (), we use the
2626 * tls->suspending flag to avoid races when that happens.
2628 if (!tls->suspended && !tls->suspending) {
2630 GetLastFrameUserData data;
2632 // FIXME: printf is not signal safe, but this is only used during
2633 // debugger debugging
2635 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip));
2636 //save_thread_context (&ctx);
2639 /* Already terminated */
2643 * We are in a difficult position: we want to be able to provide stack
2644 * traces for this thread, but we can't use the current ctx+lmf, since
2645 * the thread is still running, so it might return to managed code,
2646 * making these invalid.
2647 * So we start a stack walk and save the first frame, along with the
2648 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2649 * suspended when it returns to managed code, so the parent's ctx should
2652 data.last_frame_set = FALSE;
2654 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
2656 * Don't pass MONO_UNWIND_ACTUAL_METHOD, its not signal safe, and
2657 * get_last_frame () doesn't need it, the last frame cannot be a ginst
2658 * since we are not in a JITted method.
2660 mono_walk_stack_with_ctx (get_last_frame, &ctx, MONO_UNWIND_NONE, &data);
2662 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, &info->suspend_state, MONO_UNWIND_SIGNAL_SAFE, &data);
2664 if (data.last_frame_set) {
2665 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2666 res = mono_thread_state_init_from_monoctx (&tls->async_state, &ctx);
2668 mono_thread_state_init_from_monoctx (&tls->context, &ctx);
2671 memcpy (&tls->async_state.ctx, &data.ctx, sizeof (MonoContext));
2672 tls->async_state.unwind_data [MONO_UNWIND_DATA_LMF] = data.lmf;
2673 tls->async_state.unwind_data [MONO_UNWIND_DATA_JIT_TLS] = tls->thread->jit_data;
2675 tls->async_state.valid = FALSE;
2678 mono_memory_barrier ();
2680 tls->suspended = TRUE;
2681 MONO_SEM_POST (&suspend_sem);
2688 * mono_debugger_agent_thread_interrupt:
2690 * Called by the abort signal handler.
2691 * Should be signal safe.
2694 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
2696 DebuggerTlsData *tls;
2701 tls = mono_native_tls_get_value (debugger_tls_id);
2703 DEBUG (1, fprintf (log_file, "[%p] Received interrupt with no TLS, continuing.\n", (gpointer)GetCurrentThreadId ()));
2707 return thread_interrupt (tls, NULL, sigctx, ji);
2711 static void CALLBACK notify_thread_apc (ULONG_PTR param)
2714 mono_debugger_agent_thread_interrupt (NULL, NULL);
2716 #endif /* HOST_WIN32 */
2719 * reset_native_thread_suspend_state:
2721 * Reset the suspended flag and state on native threads
2724 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2726 DebuggerTlsData *tls = value;
2728 if (!tls->really_suspended && tls->suspended) {
2729 tls->suspended = FALSE;
2731 * The thread might still be running if it was executing native code, so the state won't be invalided by
2732 * suspend_current ().
2734 tls->context.valid = FALSE;
2735 tls->async_state.valid = FALSE;
2736 invalidate_frames (tls);
2743 * Notify a thread that it needs to suspend.
2746 notify_thread (gpointer key, gpointer value, gpointer user_data)
2748 MonoInternalThread *thread = key;
2749 DebuggerTlsData *tls = value;
2750 gsize tid = thread->tid;
2755 if (GetCurrentThreadId () == tid || tls->terminated)
2758 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2761 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2762 * guarantee the signal handler will be called that many times. Instead of tracking
2763 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2764 * has been requested that hasn't been handled yet, otherwise we can have threads
2765 * refuse to die when VM_EXIT is called
2767 #if defined(__APPLE__)
2768 if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
2772 * Maybe we could use the normal interrupt infrastructure, but that does a lot
2773 * of things like breaking waits etc. which we don't want.
2775 InterlockedIncrement (&tls->interrupt_count);
2778 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2780 QueueUserAPC (notify_thread_apc, thread->handle, (ULONG_PTR)NULL);
2782 if (mono_thread_info_new_interrupt_enabled ()) {
2783 MonoThreadInfo *info;
2786 info = mono_thread_info_safe_suspend_sync ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE);
2788 DEBUG(1, fprintf (log_file, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2790 * Attached thread which died without detaching.
2792 tls->terminated = TRUE;
2794 ji = mono_jit_info_table_find (info->suspend_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], MONO_CONTEXT_GET_IP (&info->suspend_state.ctx));
2796 thread_interrupt (tls, info, NULL, ji);
2798 mono_thread_info_finish_suspend_and_resume (info);
2801 res = mono_thread_kill (thread, mono_thread_get_abort_signal ());
2803 DEBUG(1, fprintf (log_file, "[%p] mono_thread_kill () failed for %p: %d...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid, res));
2805 * Attached thread which died without detaching.
2807 tls->terminated = TRUE;
2814 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2816 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2820 if (mono_loader_lock_is_owned_by_self ()) {
2822 * Shortcut for the check in suspend_current (). This speeds up processing
2823 * when executing long running code inside the loader lock, i.e. assembly load
2829 if (debugger_thread_id == GetCurrentThreadId ())
2832 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2833 if (suspend_count - tls->resume_count > 0)
2834 tls->suspending = TRUE;
2836 DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2838 if (suspend_count - tls->resume_count == 0) {
2840 * We are executing a single threaded invoke but the single step for
2841 * suspending is still active.
2842 * FIXME: This slows down single threaded invokes.
2844 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
2848 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2850 /* Can't suspend in these methods */
2851 method = jinfo_get_method (ji);
2852 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2855 save_thread_context (ctx);
2863 * Increase the suspend count of the VM. While the suspend count is greater
2864 * than 0, runtime threads are suspended at certain points during execution.
2869 mono_loader_lock ();
2871 mono_mutex_lock (&suspend_mutex);
2875 DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
2877 if (suspend_count == 1) {
2878 // FIXME: Is it safe to call this inside the lock ?
2879 start_single_stepping ();
2880 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2883 mono_mutex_unlock (&suspend_mutex);
2885 if (suspend_count == 1)
2887 * Suspend creation of new threadpool threads, since they cannot run
2889 mono_thread_pool_suspend ();
2891 mono_loader_unlock ();
2897 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2905 g_assert (debugger_thread_id == GetCurrentThreadId ());
2907 mono_loader_lock ();
2909 mono_mutex_lock (&suspend_mutex);
2911 g_assert (suspend_count > 0);
2914 DEBUG(1, fprintf (log_file, "[%p] Resuming vm, suspend count=%d...\n", (gpointer)GetCurrentThreadId (), suspend_count));
2916 if (suspend_count == 0) {
2917 // FIXME: Is it safe to call this inside the lock ?
2918 stop_single_stepping ();
2919 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2922 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2923 err = mono_cond_broadcast (&suspend_cond);
2924 g_assert (err == 0);
2926 mono_mutex_unlock (&suspend_mutex);
2927 //g_assert (err == 0);
2929 if (suspend_count == 0)
2930 mono_thread_pool_resume ();
2932 mono_loader_unlock ();
2938 * Resume just one thread.
2941 resume_thread (MonoInternalThread *thread)
2944 DebuggerTlsData *tls;
2946 g_assert (debugger_thread_id == GetCurrentThreadId ());
2948 mono_loader_lock ();
2950 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2953 mono_mutex_lock (&suspend_mutex);
2955 g_assert (suspend_count > 0);
2957 DEBUG(1, fprintf (log_file, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid));
2959 tls->resume_count += suspend_count;
2962 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2963 * but only the one whose resume_count field is > 0 will be resumed.
2965 err = mono_cond_broadcast (&suspend_cond);
2966 g_assert (err == 0);
2968 mono_mutex_unlock (&suspend_mutex);
2969 //g_assert (err == 0);
2971 mono_loader_unlock ();
2975 invalidate_frames (DebuggerTlsData *tls)
2980 tls = mono_native_tls_get_value (debugger_tls_id);
2983 for (i = 0; i < tls->frame_count; ++i) {
2984 if (tls->frames [i]->jit)
2985 mono_debug_free_method_jit_info (tls->frames [i]->jit);
2986 g_free (tls->frames [i]);
2988 g_free (tls->frames);
2989 tls->frame_count = 0;
2996 * Suspend the current thread until the runtime is resumed. If the thread has a
2997 * pending invoke, then the invoke is executed before this function returns.
3000 suspend_current (void)
3005 DebuggerTlsData *tls;
3007 g_assert (debugger_thread_id != GetCurrentThreadId ());
3009 if (mono_loader_lock_is_owned_by_self ()) {
3011 * If we own the loader mutex, can't suspend until we release it, since the
3012 * whole runtime can deadlock otherwise.
3017 tls = mono_native_tls_get_value (debugger_tls_id);
3020 mono_mutex_lock (&suspend_mutex);
3022 tls->suspending = FALSE;
3023 tls->really_suspended = TRUE;
3025 if (!tls->suspended) {
3026 tls->suspended = TRUE;
3027 MONO_SEM_POST (&suspend_sem);
3030 DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
3032 while (suspend_count - tls->resume_count > 0) {
3034 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
3036 mono_mutex_unlock (&suspend_mutex);
3038 mono_mutex_lock (&suspend_mutex);
3044 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
3045 g_assert (err == 0);
3049 tls->suspended = FALSE;
3050 tls->really_suspended = FALSE;
3052 threads_suspend_count --;
3054 mono_mutex_unlock (&suspend_mutex);
3056 DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
3058 if (tls->pending_invoke) {
3059 /* Save the original context */
3060 tls->pending_invoke->has_ctx = TRUE;
3061 tls->pending_invoke->ctx = tls->context.ctx;
3066 /* The frame info becomes invalid after a resume */
3067 tls->context.valid = FALSE;
3068 tls->async_state.valid = FALSE;
3069 invalidate_frames (tls);
3073 count_thread (gpointer key, gpointer value, gpointer user_data)
3075 DebuggerTlsData *tls = value;
3077 if (!tls->suspended && !tls->terminated)
3078 *(int*)user_data = *(int*)user_data + 1;
3082 count_threads_to_wait_for (void)
3086 mono_loader_lock ();
3087 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
3088 mono_loader_unlock ();
3096 * Wait until the runtime is completely suspended.
3099 wait_for_suspend (void)
3101 int nthreads, nwait, err;
3102 gboolean waited = FALSE;
3104 // FIXME: Threads starting/stopping ?
3105 mono_loader_lock ();
3106 nthreads = mono_g_hash_table_size (thread_to_tls);
3107 mono_loader_unlock ();
3110 nwait = count_threads_to_wait_for ();
3112 DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
3113 err = MONO_SEM_WAIT (&suspend_sem);
3114 g_assert (err == 0);
3122 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
3128 * Return whenever the runtime is suspended.
3133 return count_threads_to_wait_for () == 0;
3136 static MonoSeqPointInfo*
3137 get_seq_points (MonoDomain *domain, MonoMethod *method)
3139 MonoSeqPointInfo *seq_points;
3141 mono_domain_lock (domain);
3142 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
3143 if (!seq_points && method->is_inflated) {
3144 /* generic sharing + aot */
3145 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (method));
3147 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mini_get_shared_method (method));
3149 mono_domain_unlock (domain);
3155 no_seq_points_found (MonoMethod *method)
3158 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3160 printf ("Unable to find seq points for method '%s'.\n", mono_method_full_name (method, TRUE));
3164 * find_next_seq_point_for_native_offset:
3166 * Find the first sequence point after NATIVE_OFFSET.
3169 find_next_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
3171 MonoSeqPointInfo *seq_points;
3174 seq_points = get_seq_points (domain, method);
3180 g_assert (seq_points);
3184 for (i = 0; i < seq_points->len; ++i) {
3185 if (seq_points->seq_points [i].native_offset >= native_offset)
3186 return &seq_points->seq_points [i];
3193 * find_prev_seq_point_for_native_offset:
3195 * Find the first sequence point before NATIVE_OFFSET.
3198 find_prev_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
3200 MonoSeqPointInfo *seq_points;
3203 seq_points = get_seq_points (domain, method);
3209 for (i = seq_points->len - 1; i >= 0; --i) {
3210 if (seq_points->seq_points [i].native_offset <= native_offset)
3211 return &seq_points->seq_points [i];
3220 * Find the sequence point corresponding to the IL offset IL_OFFSET, which
3221 * should be the location of a sequence point.
3223 static G_GNUC_UNUSED SeqPoint*
3224 find_seq_point (MonoDomain *domain, MonoMethod *method, gint32 il_offset, MonoSeqPointInfo **info)
3226 MonoSeqPointInfo *seq_points;
3231 seq_points = get_seq_points (domain, method);
3236 for (i = 0; i < seq_points->len; ++i) {
3237 if (seq_points->seq_points [i].il_offset == il_offset)
3238 return &seq_points->seq_points [i];
3245 DebuggerTlsData *tls;
3247 } ComputeFramesUserData;
3250 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3252 ComputeFramesUserData *ud = user_data;
3254 MonoMethod *method, *actual_method, *api_method;
3258 if (info->type != FRAME_TYPE_MANAGED) {
3259 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3260 /* Mark the last frame as an invoke frame */
3262 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3268 method = jinfo_get_method (info->ji);
3270 method = info->method;
3271 actual_method = info->actual_method;
3272 api_method = method;
3277 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3280 if (info->il_offset == -1) {
3281 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3282 if (ud->frames == NULL) {
3283 sp = find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL);
3285 info->il_offset = sp->il_offset;
3287 if (info->il_offset == -1)
3288 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3291 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));
3293 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3294 if (!CHECK_PROTOCOL_VERSION (2, 17))
3295 /* Older clients can't handle this flag */
3297 api_method = mono_marshal_method_from_wrapper (method);
3300 actual_method = api_method;
3301 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3304 frame = g_new0 (StackFrame, 1);
3305 frame->method = method;
3306 frame->actual_method = actual_method;
3307 frame->api_method = api_method;
3308 frame->il_offset = info->il_offset;
3309 frame->native_offset = info->native_offset;
3310 frame->flags = flags;
3311 frame->ji = info->ji;
3312 if (info->reg_locations)
3313 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3316 frame->has_ctx = TRUE;
3318 frame->domain = info->domain;
3320 ud->frames = g_slist_append (ud->frames, frame);
3326 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3328 ComputeFramesUserData *ud = user_data;
3331 * 'tls->filter_ctx' is the location of the throw site.
3333 * mono_walk_stack() will never actually hit the throw site, but unwind
3334 * directly from the filter to the call site; we abort stack unwinding here
3335 * once this happens and resume from the throw site.
3338 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3341 return process_frame (info, ctx, user_data);
3345 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3347 ComputeFramesUserData user_data;
3349 int i, findex, new_frame_count;
3350 StackFrame **new_frames, *f;
3351 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3353 // FIXME: Locking on tls
3354 if (tls->frames && tls->frames_up_to_date)
3357 DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
3359 user_data.tls = tls;
3360 user_data.frames = NULL;
3361 if (tls->terminated) {
3362 tls->frame_count = 0;
3364 } if (!tls->really_suspended && tls->async_state.valid) {
3365 /* Have to use the state saved by the signal handler */
3366 process_frame (&tls->async_last_frame, NULL, &user_data);
3367 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3368 } else if (tls->filter_state.valid) {
3370 * We are inside an exception filter.
3372 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3374 if (tls->context.valid)
3375 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3377 * After that, we resume unwinding from the location where the exception has been thrown.
3379 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3380 } else if (tls->context.valid) {
3381 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3384 tls->frame_count = 0;
3388 new_frame_count = g_slist_length (user_data.frames);
3389 new_frames = g_new0 (StackFrame*, new_frame_count);
3391 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3395 * Reuse the id for already existing stack frames, so invokes don't invalidate
3396 * the still valid stack frames.
3398 for (i = 0; i < tls->frame_count; ++i) {
3399 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3400 f->id = tls->frames [i]->id;
3405 if (i >= tls->frame_count)
3406 f->id = InterlockedIncrement (&frame_id);
3408 new_frames [findex ++] = f;
3411 g_slist_free (user_data.frames);
3413 invalidate_frames (tls);
3415 tls->frames = new_frames;
3416 tls->frame_count = new_frame_count;
3417 tls->frames_up_to_date = TRUE;
3421 * GHFunc to emit an appdomain creation event
3422 * @param key Don't care
3423 * @param value A loaded appdomain
3424 * @param user_data Don't care
3427 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3429 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3430 g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
3434 * GHFunc to emit a thread start event
3435 * @param key A thread id
3436 * @param value A thread object
3437 * @param user_data Don't care
3440 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3442 if (GPOINTER_TO_INT (key) != debugger_thread_id)
3443 process_profiler_event (EVENT_KIND_THREAD_START, value);
3447 * GFunc to emit an assembly load event
3448 * @param value A loaded assembly
3449 * @param user_data Don't care
3452 emit_assembly_load (gpointer value, gpointer user_data)
3454 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3458 * GFunc to emit a type load event
3459 * @param value A loaded type
3460 * @param user_data Don't care
3463 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3465 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3469 strdup_tolower (char *s)
3474 for (p = s2; *p; ++p)
3484 * create_event_list:
3486 * Return a list of event request ids matching EVENT, starting from REQS, which
3487 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3489 * We return request ids, instead of requests, to simplify threading, since
3490 * requests could be deleted anytime when the loader lock is not held.
3491 * LOCKING: Assumes the loader lock is held.
3494 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3497 GSList *events = NULL;
3499 *suspend_policy = SUSPEND_POLICY_NONE;
3502 reqs = event_requests;
3507 for (i = 0; i < reqs->len; ++i) {
3508 EventRequest *req = g_ptr_array_index (reqs, i);
3509 if (req->event_kind == event) {
3510 gboolean filtered = FALSE;
3513 for (j = 0; j < req->nmodifiers; ++j) {
3514 Modifier *mod = &req->modifiers [j];
3516 if (mod->kind == MOD_KIND_COUNT) {
3518 if (mod->data.count > 0) {
3519 if (mod->data.count > 0) {
3521 if (mod->data.count == 0)
3525 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3526 if (mod->data.thread != mono_thread_internal_current ())
3528 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3529 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3531 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3533 if (ei->caught && !mod->caught)
3535 if (!ei->caught && !mod->uncaught)
3537 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3539 gboolean found = FALSE;
3540 MonoAssembly **assemblies = mod->data.assemblies;
3543 for (k = 0; assemblies [k]; ++k)
3544 if (assemblies [k] == jinfo_get_method (ji)->klass->image->assembly)
3549 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3550 gpointer iter = NULL;
3552 MonoDebugSourceInfo *sinfo;
3553 char *source_file, *s;
3554 gboolean found = FALSE;
3556 GPtrArray *source_file_list;
3558 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3559 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3562 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
3563 for (i = 0; i < source_file_list->len; ++i) {
3564 sinfo = g_ptr_array_index (source_file_list, i);
3566 * Do a case-insesitive match by converting the file name to
3569 s = strdup_tolower (sinfo->source_file);
3570 if (g_hash_table_lookup (mod->data.source_files, s))
3573 char *s2 = g_path_get_basename (sinfo->source_file);
3574 char *s3 = strdup_tolower (s2);
3576 if (g_hash_table_lookup (mod->data.source_files, s3))
3583 g_ptr_array_free (source_file_list, TRUE);
3588 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3591 s = mono_type_full_name (&ei->klass->byval_arg);
3592 if (!g_hash_table_lookup (mod->data.type_names, s))
3595 } else if (mod->kind == MOD_KIND_STEP) {
3596 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3597 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3598 !strcmp (jinfo_get_method (ji)->name, ".cctor"))
3600 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3601 MonoCustomAttrInfo *ainfo;
3602 static MonoClass *klass;
3605 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3608 if (!ji->dbg_hidden_inited) {
3609 ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji));
3611 if (mono_custom_attrs_has_attr (ainfo, klass))
3612 ji->dbg_hidden = TRUE;
3613 mono_custom_attrs_free (ainfo);
3615 ji->dbg_hidden_inited = TRUE;
3620 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3621 MonoCustomAttrInfo *ainfo;
3622 static MonoClass *klass;
3625 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3628 if (!ji->dbg_step_through_inited) {
3629 ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji));
3631 if (mono_custom_attrs_has_attr (ainfo, klass))
3632 ji->dbg_step_through = TRUE;
3633 mono_custom_attrs_free (ainfo);
3635 ainfo = mono_custom_attrs_from_class (jinfo_get_method (ji)->klass);
3637 if (mono_custom_attrs_has_attr (ainfo, klass))
3638 ji->dbg_step_through = TRUE;
3639 mono_custom_attrs_free (ainfo);
3641 ji->dbg_step_through_inited = TRUE;
3643 if (ji->dbg_step_through)
3646 if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3647 MonoCustomAttrInfo *ainfo;
3648 static MonoClass *klass;
3651 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute");
3654 if (!ji->dbg_non_user_code_inited) {
3655 ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji));
3657 if (mono_custom_attrs_has_attr (ainfo, klass))
3658 ji->dbg_non_user_code = TRUE;
3659 mono_custom_attrs_free (ainfo);
3661 ainfo = mono_custom_attrs_from_class (jinfo_get_method (ji)->klass);
3663 if (mono_custom_attrs_has_attr (ainfo, klass))
3664 ji->dbg_non_user_code = TRUE;
3665 mono_custom_attrs_free (ainfo);
3667 ji->dbg_non_user_code_inited = TRUE;
3669 if (ji->dbg_non_user_code)
3676 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3677 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3682 /* Send a VM START/DEATH event by default */
3683 if (event == EVENT_KIND_VM_START)
3684 events = g_slist_append (events, GINT_TO_POINTER (0));
3685 if (event == EVENT_KIND_VM_DEATH)
3686 events = g_slist_append (events, GINT_TO_POINTER (0));
3691 static G_GNUC_UNUSED const char*
3692 event_to_string (EventKind event)
3695 case EVENT_KIND_VM_START: return "VM_START";
3696 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3697 case EVENT_KIND_THREAD_START: return "THREAD_START";
3698 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3699 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3700 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3701 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3702 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3703 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3704 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3705 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3706 case EVENT_KIND_STEP: return "STEP";
3707 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3708 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3709 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3710 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3711 case EVENT_KIND_USER_LOG: return "USER_LOG";
3713 g_assert_not_reached ();
3721 * Send an event to the client, suspending the vm if needed.
3722 * LOCKING: Since this can suspend the calling thread, no locks should be held
3724 * The EVENTS list is freed by this function.
3727 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3731 MonoDomain *domain = mono_domain_get ();
3732 MonoThread *thread = NULL;
3733 MonoObject *keepalive_obj = NULL;
3734 gboolean send_success = FALSE;
3739 DEBUG (2, fprintf (log_file, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event)));
3743 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3744 // FIXME: We miss those events
3745 DEBUG (2, fprintf (log_file, "VM start event not sent yet: dropping %s\n", event_to_string (event)));
3749 if (vm_death_event_sent) {
3750 DEBUG (2, fprintf (log_file, "VM death event has been sent: dropping %s\n", event_to_string (event)));
3754 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3755 DEBUG (2, fprintf (log_file, "Mono runtime is shutting down: dropping %s\n", event_to_string (event)));
3760 DEBUG (2, fprintf (log_file, "Debugger client is not connected: dropping %s\n", event_to_string (event)));
3764 if (event == EVENT_KIND_KEEPALIVE)
3765 suspend_policy = SUSPEND_POLICY_NONE;
3770 if (agent_config.defer) {
3771 /* Make sure the thread id is always set when doing deferred debugging */
3772 if (debugger_thread_id == GetCurrentThreadId ()) {
3773 /* Don't suspend on events from the debugger thread */
3774 suspend_policy = SUSPEND_POLICY_NONE;
3775 thread = mono_thread_get_main ();
3777 else thread = mono_thread_current ();
3779 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3780 // FIXME: Send these with a NULL thread, don't suspend the current thread
3785 nevents = g_slist_length (events);
3786 buffer_init (&buf, 128);
3787 buffer_add_byte (&buf, suspend_policy);
3788 buffer_add_int (&buf, nevents);
3790 for (l = events; l; l = l->next) {
3791 buffer_add_byte (&buf, event); // event kind
3792 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3797 thread = mono_thread_current ();
3799 if (event == EVENT_KIND_VM_START && arg != NULL)
3802 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3805 case EVENT_KIND_THREAD_START:
3806 case EVENT_KIND_THREAD_DEATH:
3808 case EVENT_KIND_APPDOMAIN_CREATE:
3809 case EVENT_KIND_APPDOMAIN_UNLOAD:
3810 buffer_add_domainid (&buf, arg);
3812 case EVENT_KIND_METHOD_ENTRY:
3813 case EVENT_KIND_METHOD_EXIT:
3814 buffer_add_methodid (&buf, domain, arg);
3816 case EVENT_KIND_ASSEMBLY_LOAD:
3817 buffer_add_assemblyid (&buf, domain, arg);
3819 case EVENT_KIND_ASSEMBLY_UNLOAD: {
3820 DebuggerTlsData *tls;
3822 /* The domain the assembly belonged to is not equal to the current domain */
3823 tls = mono_native_tls_get_value (debugger_tls_id);
3825 g_assert (tls->domain_unloading);
3827 buffer_add_assemblyid (&buf, tls->domain_unloading, arg);
3830 case EVENT_KIND_TYPE_LOAD:
3831 buffer_add_typeid (&buf, domain, arg);
3833 case EVENT_KIND_BREAKPOINT:
3834 case EVENT_KIND_STEP:
3835 buffer_add_methodid (&buf, domain, arg);
3836 buffer_add_long (&buf, il_offset);
3838 case EVENT_KIND_VM_START:
3839 buffer_add_domainid (&buf, mono_get_root_domain ());
3841 case EVENT_KIND_VM_DEATH:
3842 if (CHECK_PROTOCOL_VERSION (2, 27))
3843 buffer_add_int (&buf, mono_environment_exitcode_get ());
3845 case EVENT_KIND_EXCEPTION: {
3846 EventInfo *ei = arg;
3847 buffer_add_objid (&buf, ei->exc);
3849 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3850 * later after the suspension. (#12494).
3852 keepalive_obj = ei->exc;
3855 case EVENT_KIND_USER_BREAK:
3857 case EVENT_KIND_USER_LOG: {
3858 EventInfo *ei = arg;
3859 buffer_add_int (&buf, ei->level);
3860 buffer_add_string (&buf, ei->category ? ei->category : "");
3861 buffer_add_string (&buf, ei->message ? ei->message : "");
3864 case EVENT_KIND_KEEPALIVE:
3865 suspend_policy = SUSPEND_POLICY_NONE;
3868 g_assert_not_reached ();
3872 if (event == EVENT_KIND_VM_START) {
3873 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3874 if (!agent_config.defer)
3875 start_debugger_thread ();
3878 if (event == EVENT_KIND_VM_DEATH) {
3879 vm_death_event_sent = TRUE;
3880 suspend_policy = SUSPEND_POLICY_NONE;
3883 if (mono_runtime_is_shutting_down ())
3884 suspend_policy = SUSPEND_POLICY_NONE;
3886 if (suspend_policy != SUSPEND_POLICY_NONE) {
3888 * Save the thread context and start suspending before sending the packet,
3889 * since we could be receiving the resume request before send_packet ()
3892 save_thread_context (ctx);
3896 /* This will keep this object alive */
3897 get_objref (keepalive_obj);
3900 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3904 g_slist_free (events);
3907 if (!send_success) {
3908 DEBUG (2, fprintf (log_file, "Sending command %s failed.\n", event_to_string (event)));
3912 if (event == EVENT_KIND_VM_START) {
3913 vm_start_event_sent = TRUE;
3916 DEBUG (1, fprintf (log_file, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer)GetCurrentThreadId (), nevents, event_to_string (event), ecount, suspend_policy));
3918 switch (suspend_policy) {
3919 case SUSPEND_POLICY_NONE:
3921 case SUSPEND_POLICY_ALL:
3924 case SUSPEND_POLICY_EVENT_THREAD:
3928 g_assert_not_reached ();
3933 process_profiler_event (EventKind event, gpointer arg)
3937 EventInfo ei, *ei_arg = NULL;
3939 if (event == EVENT_KIND_TYPE_LOAD) {
3944 mono_loader_lock ();
3945 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3946 mono_loader_unlock ();
3948 process_event (event, arg, 0, NULL, events, suspend_policy);
3952 runtime_initialized (MonoProfiler *prof)
3954 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3955 if (agent_config.defer)
3956 start_debugger_thread ();
3960 runtime_shutdown (MonoProfiler *prof)
3962 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3964 mono_debugger_agent_cleanup ();
3968 thread_startup (MonoProfiler *prof, uintptr_t tid)
3970 MonoInternalThread *thread = mono_thread_internal_current ();
3971 MonoInternalThread *old_thread;
3972 DebuggerTlsData *tls;
3974 if (tid == debugger_thread_id)
3977 g_assert (thread->tid == tid);
3979 mono_loader_lock ();
3980 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3981 mono_loader_unlock ();
3983 if (thread == old_thread) {
3985 * For some reason, thread_startup () might be called for the same thread
3986 * multiple times (attach ?).
3988 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
3992 * thread_end () might not be called for some threads, and the tid could
3995 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
3996 mono_loader_lock ();
3997 mono_g_hash_table_remove (thread_to_tls, old_thread);
3998 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3999 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
4000 mono_loader_unlock ();
4004 tls = mono_native_tls_get_value (debugger_tls_id);
4006 // FIXME: Free this somewhere
4007 tls = g_new0 (DebuggerTlsData, 1);
4008 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
4009 tls->thread = thread;
4010 mono_native_tls_set_value (debugger_tls_id, tls);
4012 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
4014 mono_loader_lock ();
4015 mono_g_hash_table_insert (thread_to_tls, thread, tls);
4016 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
4017 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
4018 mono_loader_unlock ();
4020 process_profiler_event (EVENT_KIND_THREAD_START, thread);
4023 * suspend_vm () could have missed this thread, so wait for a resume.
4029 thread_end (MonoProfiler *prof, uintptr_t tid)
4031 MonoInternalThread *thread;
4032 DebuggerTlsData *tls = NULL;
4034 mono_loader_lock ();
4035 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
4037 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
4038 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4040 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
4041 tls->terminated = TRUE;
4042 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
4043 MONO_GC_UNREGISTER_ROOT (tls->thread);
4047 mono_loader_unlock ();
4049 /* We might be called for threads started before we registered the start callback */
4051 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
4052 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
4057 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
4059 mono_loader_lock ();
4060 g_hash_table_insert (domains, domain, domain);
4061 mono_loader_unlock ();
4063 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
4067 appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain)
4069 DebuggerTlsData *tls;
4072 * Remember the currently unloading appdomain as it is needed to generate
4073 * proper ids for unloading assemblies.
4075 tls = mono_native_tls_get_value (debugger_tls_id);
4077 tls->domain_unloading = domain;
4081 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
4083 DebuggerTlsData *tls;
4085 tls = mono_native_tls_get_value (debugger_tls_id);
4087 tls->domain_unloading = NULL;
4089 clear_breakpoints_for_domain (domain);
4091 mono_loader_lock ();
4092 /* Invalidate each thread's frame stack */
4093 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
4094 mono_loader_unlock ();
4096 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
4100 * invalidate_each_thread:
4102 * A GHFunc to invalidate frames.
4103 * value must be a DebuggerTlsData*
4106 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
4108 invalidate_frames (value);
4112 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
4114 /* Sent later in jit_end () */
4116 g_ptr_array_add (pending_assembly_loads, assembly);
4121 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
4123 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
4125 clear_event_requests_for_assembly (assembly);
4126 clear_types_for_assembly (assembly);
4130 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
4132 #if defined(HOST_WIN32) && !defined(__GNUC__)
4133 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
4135 gpointer stackptr = __builtin_frame_address (1);
4137 MonoInternalThread *thread = mono_thread_internal_current ();
4138 DebuggerTlsData *tls;
4140 mono_loader_lock ();
4142 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4143 /* Could be the debugger thread with assembly/type load hooks */
4145 tls->invoke_addr = stackptr;
4147 mono_loader_unlock ();
4151 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
4154 #if defined(HOST_WIN32) && !defined(__GNUC__)
4155 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
4157 gpointer stackptr = __builtin_frame_address (1);
4160 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
4164 * We need to stop single stepping when exiting a runtime invoke, since if it is
4165 * a step out, it may return to native code, and thus never end.
4167 mono_loader_lock ();
4168 ss_invoke_addr = NULL;
4170 for (i = 0; i < event_requests->len; ++i) {
4171 EventRequest *req = g_ptr_array_index (event_requests, i);
4173 if (req->event_kind == EVENT_KIND_STEP) {
4174 ss_destroy (req->info);
4175 g_ptr_array_remove_index_fast (event_requests, i);
4180 mono_loader_unlock ();
4184 send_type_load (MonoClass *klass)
4186 gboolean type_load = FALSE;
4187 MonoDomain *domain = mono_domain_get ();
4188 AgentDomainInfo *info = NULL;
4190 mono_loader_lock ();
4191 mono_domain_lock (domain);
4193 info = get_agent_domain_info (domain);
4195 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
4197 g_hash_table_insert (info->loaded_classes, klass, klass);
4200 mono_domain_unlock (domain);
4201 mono_loader_unlock ();
4203 emit_type_load (klass, klass, NULL);
4207 * Emit load events for all types currently loaded in the domain.
4208 * Takes the loader and domain locks.
4209 * user_data is unused.
4212 send_types_for_domain (MonoDomain *domain, void *user_data)
4214 AgentDomainInfo *info = NULL;
4216 mono_loader_lock ();
4217 mono_domain_lock (domain);
4218 info = get_agent_domain_info (domain);
4220 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4221 mono_domain_unlock (domain);
4222 mono_loader_unlock ();
4226 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
4229 * We emit type load events when the first method of the type is JITted,
4230 * since the class load profiler callbacks might be called with the
4231 * loader lock held. They could also occur in the debugger thread.
4232 * Same for assembly load events.
4235 MonoAssembly *assembly = NULL;
4237 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4239 if (pending_assembly_loads->len > 0) {
4240 assembly = g_ptr_array_index (pending_assembly_loads, 0);
4241 g_ptr_array_remove_index (pending_assembly_loads, 0);
4246 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4252 send_type_load (method->klass);
4255 add_pending_breakpoints (method, jinfo);
4259 * BREAKPOINTS/SINGLE STEPPING
4263 * Contains information about an inserted breakpoint.
4266 long il_offset, native_offset;
4271 } BreakpointInstance;
4274 * Contains generic information about a breakpoint.
4278 * The method where the breakpoint is placed. Can be NULL in which case it
4279 * is inserted into every method. This is used to implement method entry/
4280 * exit events. Can be a generic method definition, in which case the
4281 * breakpoint is inserted into every instance.
4287 * A list of BreakpointInstance structures describing where the breakpoint
4288 * was inserted. There could be more than one because of
4289 * generics/appdomains/method entry/exit.
4291 GPtrArray *children;
4294 /* List of breakpoints */
4295 static GPtrArray *breakpoints;
4296 /* Maps breakpoint locations to the number of breakpoints at that location */
4297 static GHashTable *bp_locs;
4300 breakpoints_init (void)
4302 breakpoints = g_ptr_array_new ();
4303 bp_locs = g_hash_table_new (NULL, NULL);
4307 * insert_breakpoint:
4309 * Insert the breakpoint described by BP into the method described by
4313 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4316 BreakpointInstance *inst;
4317 SeqPoint *sp = NULL;
4320 mono_error_init (error);
4322 for (i = 0; i < seq_points->len; ++i) {
4323 sp = &seq_points->seq_points [i];
4325 if (sp->il_offset == bp->il_offset)
4329 if (i == seq_points->len) {
4331 * The set of IL offsets with seq points doesn't completely match the
4332 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4334 for (i = 0; i < seq_points->len; ++i) {
4335 sp = &seq_points->seq_points [i];
4337 if (sp->il_offset != METHOD_ENTRY_IL_OFFSET && sp->il_offset != METHOD_EXIT_IL_OFFSET && sp->il_offset + 1 == bp->il_offset)
4342 if (i == seq_points->len) {
4343 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);
4345 for (i = 0; i < seq_points->len; ++i)
4346 DEBUG (1, fprintf (log_file, "%d\n", seq_points->seq_points [i].il_offset));
4349 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4350 g_warning ("%s", s);
4354 g_warning ("%s", s);
4360 inst = g_new0 (BreakpointInstance, 1);
4362 inst->native_offset = sp->native_offset;
4363 inst->ip = (guint8*)ji->code_start + sp->native_offset;
4365 inst->domain = domain;
4367 mono_loader_lock ();
4369 g_ptr_array_add (bp->children, inst);
4371 mono_loader_unlock ();
4374 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4375 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4378 if (sp->native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4379 DEBUG (1, fprintf (log_file, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset));
4380 } else if (count == 0) {
4381 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4382 mono_arch_set_breakpoint (ji, inst->ip);
4388 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));
4392 remove_breakpoint (BreakpointInstance *inst)
4394 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4396 MonoJitInfo *ji = inst->ji;
4397 guint8 *ip = inst->ip;
4400 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4401 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4404 g_assert (count > 0);
4406 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4407 mono_arch_clear_breakpoint (ji, ip);
4408 DEBUG(1, fprintf (log_file, "[dbg] Clear breakpoint at %s [%p].\n", mono_method_full_name (jinfo_get_method (ji), TRUE), ip));
4415 static inline gboolean
4416 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4422 if (method == bp->method)
4424 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4427 if (bp->method->is_inflated && method->is_inflated) {
4428 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4429 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4431 /* Open generic methods should match closed generic methods of the same class */
4432 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4433 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4434 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4436 /* FIXME: Handle !mvar */
4437 if (t1->type != MONO_TYPE_MVAR)
4448 * add_pending_breakpoints:
4450 * Insert pending breakpoints into the newly JITted method METHOD.
4453 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4456 MonoSeqPointInfo *seq_points;
4458 MonoMethod *jmethod;
4463 domain = mono_domain_get ();
4465 mono_loader_lock ();
4467 for (i = 0; i < breakpoints->len; ++i) {
4468 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4469 gboolean found = FALSE;
4471 if (!bp_matches_method (bp, method))
4474 for (j = 0; j < bp->children->len; ++j) {
4475 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4482 jmethod = jinfo_get_method (ji);
4483 mono_domain_lock (domain);
4484 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, jmethod);
4485 if (!seq_points && jmethod->is_inflated)
4486 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (jmethod));
4487 mono_domain_unlock (domain);
4489 /* Could be AOT code */
4491 g_assert (seq_points);
4493 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4497 mono_loader_unlock ();
4501 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4507 mono_error_init (error);
4509 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4511 /* Might be AOTed code */
4512 code = mono_aot_get_method (domain, method);
4514 ji = mono_jit_info_table_find (domain, code);
4519 insert_breakpoint (seq_points, domain, ji, bp, error);
4523 clear_breakpoint (MonoBreakpoint *bp);
4528 * Set a breakpoint at IL_OFFSET in METHOD.
4529 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4530 * METHOD can also be a generic method definition, in which case a breakpoint
4531 * is placed in all instances of the method.
4532 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4535 static MonoBreakpoint*
4536 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4539 GHashTableIter iter, iter2;
4542 MonoSeqPointInfo *seq_points;
4545 mono_error_init (error);
4548 // - suspend/resume the vm to prevent code patching problems
4549 // - multiple breakpoints on the same location
4550 // - dynamic methods
4553 bp = g_new0 (MonoBreakpoint, 1);
4554 bp->method = method;
4555 bp->il_offset = il_offset;
4557 bp->children = g_ptr_array_new ();
4559 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));
4561 mono_loader_lock ();
4563 g_hash_table_iter_init (&iter, domains);
4564 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4565 mono_domain_lock (domain);
4567 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4568 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4569 if (bp_matches_method (bp, m))
4570 set_bp_in_method (domain, m, seq_points, bp, error);
4573 mono_domain_unlock (domain);
4576 mono_loader_unlock ();
4578 mono_loader_lock ();
4579 g_ptr_array_add (breakpoints, bp);
4580 mono_loader_unlock ();
4582 if (error && !mono_error_ok (error)) {
4583 clear_breakpoint (bp);
4591 clear_breakpoint (MonoBreakpoint *bp)
4595 // FIXME: locking, races
4596 for (i = 0; i < bp->children->len; ++i) {
4597 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4599 remove_breakpoint (inst);
4604 mono_loader_lock ();
4605 g_ptr_array_remove (breakpoints, bp);
4606 mono_loader_unlock ();
4608 g_ptr_array_free (bp->children, TRUE);
4613 breakpoints_cleanup (void)
4617 mono_loader_lock ();
4619 while (i < event_requests->len) {
4620 EventRequest *req = g_ptr_array_index (event_requests, i);
4622 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4623 clear_breakpoint (req->info);
4624 g_ptr_array_remove_index_fast (event_requests, i);
4631 for (i = 0; i < breakpoints->len; ++i)
4632 g_free (g_ptr_array_index (breakpoints, i));
4634 g_ptr_array_free (breakpoints, TRUE);
4635 g_hash_table_destroy (bp_locs);
4640 mono_loader_unlock ();
4644 * clear_breakpoints_for_domain:
4646 * Clear breakpoint instances which reference DOMAIN.
4649 clear_breakpoints_for_domain (MonoDomain *domain)
4653 /* This could be called after shutdown */
4657 mono_loader_lock ();
4658 for (i = 0; i < breakpoints->len; ++i) {
4659 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4662 while (j < bp->children->len) {
4663 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4665 if (inst->domain == domain) {
4666 remove_breakpoint (inst);
4670 g_ptr_array_remove_index_fast (bp->children, j);
4676 mono_loader_unlock ();
4682 * Return FALSE if single stepping needs to continue.
4685 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp, DebuggerTlsData *tls, MonoContext *ctx)
4687 MonoDebugMethodInfo *minfo;
4688 MonoDebugSourceLocation *loc = NULL;
4689 gboolean hit = TRUE;
4692 if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK)) {
4694 * These seq points are inserted by the JIT after calls, step over needs to skip them.
4696 DEBUG (1, fprintf (log_file, "[%p] Seq point at nonempty stack %x while stepping over, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset));
4700 if (req->depth == STEP_DEPTH_OVER && hit) {
4701 if (!tls->context.valid)
4702 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4703 compute_frame_info (tls->thread, tls);
4704 if (req->nframes && tls->frame_count && tls->frame_count > req->nframes) {
4705 /* Hit the breakpoint in a recursive call */
4706 DEBUG (1, fprintf (log_file, "[%p] Breakpoint at lower frame while stepping over, continuing single stepping.\n", (gpointer)GetCurrentThreadId ()));
4711 if (req->size != STEP_SIZE_LINE)
4714 /* Have to check whenever a different source line was reached */
4715 method = jinfo_get_method (ji);
4716 minfo = mono_debug_lookup_method (method);
4719 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4721 if (!loc || (loc && method == ss_req->last_method && loc->row == ss_req->last_line)) {
4722 /* Have to continue single stepping */
4724 DEBUG(1, fprintf (log_file, "[%p] No line number info for il offset %x, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset));
4726 DEBUG(1, fprintf (log_file, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer)GetCurrentThreadId (), loc->row));
4731 ss_req->last_method = method;
4732 ss_req->last_line = loc->row;
4733 mono_debug_free_source_location (loc);
4740 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4742 return bp->method && bp->method->klass->image->assembly == assembly;
4746 process_breakpoint_inner (DebuggerTlsData *tls)
4750 int i, j, suspend_policy;
4751 guint32 native_offset;
4753 BreakpointInstance *inst;
4754 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4755 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4756 EventKind kind = EVENT_KIND_BREAKPOINT;
4757 MonoContext *ctx = &tls->restore_ctx;
4759 MonoSeqPointInfo *info;
4762 // FIXME: Speed this up
4764 ip = MONO_CONTEXT_GET_IP (ctx);
4765 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4767 method = jinfo_get_method (ji);
4769 /* Compute the native offset of the breakpoint from the ip */
4770 native_offset = ip - (guint8*)ji->code_start;
4773 * Skip the instruction causing the breakpoint signal.
4775 mono_arch_skip_breakpoint (ctx, ji);
4777 if (method->wrapper_type || tls->disable_breakpoints)
4780 bp_reqs = g_ptr_array_new ();
4781 ss_reqs = g_ptr_array_new ();
4782 ss_reqs_orig = g_ptr_array_new ();
4784 mono_loader_lock ();
4787 * The ip points to the instruction causing the breakpoint event, which is after
4788 * the offset recorded in the seq point map, so find the prev seq point before ip.
4790 sp = find_prev_seq_point_for_native_offset (mono_domain_get (), method, native_offset, &info);
4792 no_seq_points_found (method);
4795 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));
4798 for (i = 0; i < breakpoints->len; ++i) {
4799 bp = g_ptr_array_index (breakpoints, i);
4804 for (j = 0; j < bp->children->len; ++j) {
4805 inst = g_ptr_array_index (bp->children, j);
4806 if (inst->ji == ji && inst->sp == sp) {
4807 if (bp->req->event_kind == EVENT_KIND_STEP) {
4808 g_ptr_array_add (ss_reqs_orig, bp->req);
4810 g_ptr_array_add (bp_reqs, bp->req);
4815 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4816 /* Maybe a method entry/exit event */
4817 if (sp->il_offset == METHOD_ENTRY_IL_OFFSET)
4818 kind = EVENT_KIND_METHOD_ENTRY;
4819 else if (sp->il_offset == METHOD_EXIT_IL_OFFSET)
4820 kind = EVENT_KIND_METHOD_EXIT;
4823 /* Process single step requests */
4824 for (i = 0; i < ss_reqs_orig->len; ++i) {
4825 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4826 SingleStepReq *ss_req = req->info;
4829 if (mono_thread_internal_current () != ss_req->thread)
4832 hit = ss_update (ss_req, ji, sp, tls, ctx);
4834 g_ptr_array_add (ss_reqs, req);
4836 /* Start single stepping again from the current sequence point */
4837 ss_start (ss_req, method, sp, info, ctx, tls, FALSE);
4840 if (ss_reqs->len > 0)
4841 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4842 if (bp_reqs->len > 0)
4843 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4844 if (kind != EVENT_KIND_BREAKPOINT)
4845 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4847 mono_loader_unlock ();
4849 g_ptr_array_free (bp_reqs, TRUE);
4850 g_ptr_array_free (ss_reqs, TRUE);
4853 * FIXME: The first event will suspend, so the second will only be sent after the
4857 process_event (EVENT_KIND_STEP, method, 0, ctx, ss_events, suspend_policy);
4859 process_event (kind, method, 0, ctx, bp_events, suspend_policy);
4860 if (enter_leave_events)
4861 process_event (kind, method, 0, ctx, enter_leave_events, suspend_policy);
4864 /* Process a breakpoint/single step event after resuming from a signal handler */
4866 process_signal_event (void (*func) (DebuggerTlsData*))
4868 DebuggerTlsData *tls;
4869 MonoContext orig_restore_ctx, ctx;
4871 tls = mono_native_tls_get_value (debugger_tls_id);
4872 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4873 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4874 memcpy (&tls->restore_ctx, &tls->handler_ctx, sizeof (MonoContext));
4878 /* This is called when resuming from a signal handler, so it shouldn't return */
4879 memcpy (&ctx, &tls->restore_ctx, sizeof (MonoContext));
4880 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4881 mono_restore_context (&ctx);
4882 g_assert_not_reached ();
4886 process_breakpoint (void)
4888 process_signal_event (process_breakpoint_inner);
4892 resume_from_signal_handler (void *sigctx, void *func)
4894 DebuggerTlsData *tls;
4897 /* Save the original context in TLS */
4898 // FIXME: This might not work on an altstack ?
4899 tls = mono_native_tls_get_value (debugger_tls_id);
4901 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer)GetCurrentThreadId ());
4904 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4905 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4906 // clob:c could be added to op_seq_point.
4908 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4909 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4910 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4911 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4913 MONO_CONTEXT_SET_IP (&ctx, func);
4915 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4917 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4918 mono_ppc_set_func_into_sigctx (sigctx, func);
4923 mono_debugger_agent_breakpoint_hit (void *sigctx)
4926 * We are called from a signal handler, and running code there causes all kinds of
4927 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4928 * So set up the signal context to return to the real breakpoint handler function.
4930 resume_from_signal_handler (sigctx, process_breakpoint);
4934 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4936 if (frame->managed) {
4937 *(MonoContext*)data = *ctx;
4946 * Called by System.Diagnostics.Debugger:Break ().
4949 mono_debugger_agent_user_break (void)
4951 if (agent_config.enabled) {
4956 /* Obtain a context */
4957 MONO_CONTEXT_SET_IP (&ctx, NULL);
4958 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4959 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4961 mono_loader_lock ();
4962 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4963 mono_loader_unlock ();
4965 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4972 ss_depth_to_string (StepDepth depth)
4975 case STEP_DEPTH_OVER:
4977 case STEP_DEPTH_OUT:
4979 case STEP_DEPTH_INTO:
4982 g_assert_not_reached ();
4988 process_single_step_inner (DebuggerTlsData *tls)
4993 int il_offset, suspend_policy;
4996 MonoContext *ctx = &tls->restore_ctx;
4999 MonoSeqPointInfo *info;
5001 ip = MONO_CONTEXT_GET_IP (ctx);
5003 /* Skip the instruction causing the single step */
5004 mono_arch_skip_single_step (ctx);
5006 if (suspend_count > 0) {
5007 process_suspend (tls, ctx);
5012 // FIXME: A suspend race
5015 if (mono_thread_internal_current () != ss_req->thread)
5018 if (log_level > 0) {
5019 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
5021 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));
5024 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
5026 method = jinfo_get_method (ji);
5029 if (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
5034 * Stopping in memset makes half-initialized vtypes visible.
5035 * Stopping in memcpy makes half-copied vtypes visible.
5037 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
5041 * The ip points to the instruction causing the single step event, which is before
5042 * the offset recorded in the seq point map, so find the next seq point after ip.
5044 sp = find_next_seq_point_for_native_offset (domain, method, (guint8*)ip - (guint8*)ji->code_start, &info);
5047 il_offset = sp->il_offset;
5049 if (!ss_update (ss_req, ji, sp, tls, ctx))
5052 /* Start single stepping again from the current sequence point */
5053 ss_start (ss_req, method, sp, info, ctx, tls, FALSE);
5055 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
5056 (method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
5057 !strcmp (method->name, ".cctor"))
5060 // FIXME: Has to lock earlier
5062 reqs = g_ptr_array_new ();
5064 mono_loader_lock ();
5066 g_ptr_array_add (reqs, ss_req->req);
5068 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
5070 g_ptr_array_free (reqs, TRUE);
5072 mono_loader_unlock ();
5074 process_event (EVENT_KIND_STEP, jinfo_get_method (ji), il_offset, ctx, events, suspend_policy);
5078 process_single_step (void)
5080 process_signal_event (process_single_step_inner);
5084 * mono_debugger_agent_single_step_event:
5086 * Called from a signal handler to handle a single step event.
5089 mono_debugger_agent_single_step_event (void *sigctx)
5091 /* Resume to process_single_step through the signal context */
5093 // FIXME: Since step out/over is implemented using step in, the step in case should
5094 // be as fast as possible. Move the relevant code from process_single_step_inner ()
5097 if (GetCurrentThreadId () == debugger_thread_id) {
5099 * This could happen despite our best effors when the runtime calls
5100 * assembly/type resolve hooks.
5101 * FIXME: Breakpoints too.
5105 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
5106 mono_arch_skip_single_step (&ctx);
5107 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
5111 resume_from_signal_handler (sigctx, process_single_step);
5115 debugger_agent_single_step_from_context (MonoContext *ctx)
5117 DebuggerTlsData *tls;
5118 MonoContext orig_restore_ctx;
5120 tls = mono_native_tls_get_value (debugger_tls_id);
5123 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
5124 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
5125 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
5127 process_single_step_inner (tls);
5129 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
5130 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
5134 debugger_agent_breakpoint_from_context (MonoContext *ctx)
5136 DebuggerTlsData *tls;
5137 MonoContext orig_restore_ctx;
5139 tls = mono_native_tls_get_value (debugger_tls_id);
5141 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
5142 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
5144 process_breakpoint_inner (tls);
5146 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
5147 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
5151 * start_single_stepping:
5153 * Turn on single stepping. Can be called multiple times, for example,
5154 * by a single step event request + a suspend.
5157 start_single_stepping (void)
5159 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5160 int val = InterlockedIncrement (&ss_count);
5163 mono_arch_start_single_stepping ();
5165 if (ss_req != NULL && ss_invoke_addr == NULL) {
5166 DebuggerTlsData *tls;
5168 mono_loader_lock ();
5170 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
5171 ss_invoke_addr = tls->invoke_addr;
5173 mono_loader_unlock ();
5176 g_assert_not_reached ();
5181 stop_single_stepping (void)
5183 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5184 int val = InterlockedDecrement (&ss_count);
5187 mono_arch_stop_single_stepping ();
5189 ss_invoke_addr = NULL;
5191 g_assert_not_reached ();
5198 * Stop the single stepping operation given by SS_REQ.
5201 ss_stop (SingleStepReq *ss_req)
5206 for (l = ss_req->bps; l; l = l->next) {
5207 clear_breakpoint (l->data);
5209 g_slist_free (ss_req->bps);
5213 if (ss_req->global) {
5214 stop_single_stepping ();
5215 ss_req->global = FALSE;
5222 * Start the single stepping operation given by SS_REQ from the sequence point SP.
5223 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
5224 * belong to the same thread as CTX.
5227 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
5229 int i, j, frame_index;
5232 gboolean enable_global = FALSE;
5234 /* Stop the previous operation */
5238 * Implement single stepping using breakpoints if possible.
5240 if (step_to_catch) {
5241 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
5242 ss_req->bps = g_slist_append (ss_req->bps, bp);
5246 if ((!sp || sp->next_len == 0 || ss_req->depth == STEP_DEPTH_OUT || ss_req->depth == STEP_DEPTH_OVER) && ctx) {
5247 /* Need parent frames */
5248 if (!tls->context.valid)
5249 mono_thread_state_init_from_monoctx (&tls->context, ctx);
5250 compute_frame_info (tls->thread, tls);
5254 * Find the first sequence point in the current or in a previous frame which
5255 * is not the last in its method.
5257 if (ss_req->depth == STEP_DEPTH_OUT) {
5258 /* Ignore seq points in current method */
5259 while (frame_index < tls->frame_count) {
5260 StackFrame *frame = tls->frames [frame_index];
5262 method = frame->method;
5263 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5265 if (sp && sp->next_len != 0)
5268 // There could be method calls before the next seq point in the caller when using nested calls
5269 //enable_global = TRUE;
5271 if (sp && sp->next_len == 0) {
5273 while (frame_index < tls->frame_count) {
5274 StackFrame *frame = tls->frames [frame_index];
5276 method = frame->method;
5277 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5278 if (sp && sp->next_len != 0)
5286 if (sp && sp->next_len > 0) {
5287 for (i = 0; i < sp->next_len; ++i) {
5288 next_sp = &info->seq_points [sp->next [i]];
5290 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
5291 ss_req->bps = g_slist_append (ss_req->bps, bp);
5295 if (ss_req->depth == STEP_DEPTH_OVER) {
5296 if (ss_req->nframes == 0)
5297 ss_req->nframes = tls->frame_count;
5298 /* Need to stop in catch clauses as well */
5299 for (i = 0; i < tls->frame_count; ++i) {
5300 StackFrame *frame = tls->frames [i];
5303 MonoJitInfo *jinfo = frame->ji;
5304 for (j = 0; j < jinfo->num_clauses; ++j) {
5305 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5307 sp = find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL);
5309 bp = set_breakpoint (frame->method, sp->il_offset, ss_req->req, NULL);
5310 ss_req->bps = g_slist_append (ss_req->bps, bp);
5318 if (ss_req->depth == STEP_DEPTH_INTO) {
5319 /* Enable global stepping so we stop at method entry too */
5320 enable_global = TRUE;
5324 * The ctx/frame info computed above will become invalid when we continue.
5326 tls->context.valid = FALSE;
5327 tls->async_state.valid = FALSE;
5328 invalidate_frames (tls);
5331 if (enable_global) {
5332 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
5333 ss_req->global = TRUE;
5334 start_single_stepping ();
5335 } else if (!ss_req->bps) {
5336 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
5337 ss_req->global = TRUE;
5338 start_single_stepping ();
5340 ss_req->global = FALSE;
5345 * Start single stepping of thread THREAD
5348 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
5350 DebuggerTlsData *tls;
5351 MonoSeqPointInfo *info = NULL;
5352 SeqPoint *sp = NULL;
5353 MonoMethod *method = NULL;
5354 MonoDebugMethodInfo *minfo;
5355 gboolean step_to_catch = FALSE;
5357 if (suspend_count == 0)
5358 return ERR_NOT_SUSPENDED;
5360 wait_for_suspend ();
5362 // FIXME: Multiple requests
5364 DEBUG (0, fprintf (log_file, "Received a single step request while the previous one was still active.\n"));
5365 return ERR_NOT_IMPLEMENTED;
5368 DEBUG (1, fprintf (log_file, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
5370 ss_req = g_new0 (SingleStepReq, 1);
5372 ss_req->thread = thread;
5373 ss_req->size = size;
5374 ss_req->depth = depth;
5377 mono_loader_lock ();
5378 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5379 mono_loader_unlock ();
5381 g_assert (tls->context.valid);
5382 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5384 if (tls->catch_state.valid) {
5386 StackFrameInfo frame;
5387 MonoContext new_ctx;
5388 MonoLMF *lmf = NULL;
5391 * We are stopped at a throw site. Stepping should go to the catch site.
5394 /* Find the the jit info for the catch context */
5395 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);
5397 g_assert (frame.type == FRAME_TYPE_MANAGED);
5400 * Find the seq point corresponding to the landing site ip, which is the first seq
5403 sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
5405 no_seq_points_found (frame.method);
5408 method = frame.method;
5410 step_to_catch = TRUE;
5411 /* This make sure the seq point is not skipped by process_single_step () */
5412 ss_req->last_sp = NULL;
5415 if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
5418 /* Compute the initial line info */
5419 compute_frame_info (thread, tls);
5421 if (tls->frame_count) {
5422 frame = tls->frames [0];
5424 ss_req->last_method = frame->method;
5425 ss_req->last_line = -1;
5427 minfo = mono_debug_lookup_method (frame->method);
5428 if (minfo && frame->il_offset != -1) {
5429 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
5432 ss_req->last_line = loc->row;
5439 if (!step_to_catch) {
5442 compute_frame_info (thread, tls);
5444 if (tls->frame_count) {
5445 frame = tls->frames [0];
5447 if (!method && frame->il_offset != -1) {
5448 /* FIXME: Sort the table and use a binary search */
5449 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5451 no_seq_points_found (frame->method);
5453 method = frame->method;
5458 ss_start (ss_req, method, sp, info, &tls->context.ctx, tls, step_to_catch);
5464 ss_destroy (SingleStepReq *req)
5467 g_assert (ss_req == req);
5476 ss_clear_for_assembly (SingleStepReq *req, MonoAssembly *assembly)
5479 gboolean found = TRUE;
5483 for (l = ss_req->bps; l; l = l->next) {
5484 if (breakpoint_matches_assembly (l->data, assembly)) {
5485 clear_breakpoint (l->data);
5486 ss_req->bps = g_slist_delete_link (ss_req->bps, l);
5495 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5498 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5504 if (!agent_config.enabled)
5507 mono_loader_lock ();
5508 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5509 mono_loader_unlock ();
5512 ei.category = category ? mono_string_to_utf8 (category) : NULL;
5513 ei.message = message ? mono_string_to_utf8 (message) : NULL;
5515 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5517 g_free (ei.category);
5518 g_free (ei.message);
5522 mono_debugger_agent_debug_log_is_enabled (void)
5524 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5525 return agent_config.enabled;
5528 #if defined(PLATFORM_ANDROID) || defined(TARGET_ANDROID)
5530 mono_debugger_agent_unhandled_exception (MonoException *exc)
5539 memset (&ei, 0, sizeof (EventInfo));
5540 ei.exc = (MonoObject*)exc;
5542 mono_loader_lock ();
5543 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5544 mono_loader_unlock ();
5546 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5551 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5552 MonoContext *catch_ctx)
5554 int i, j, suspend_policy;
5556 MonoJitInfo *ji, *catch_ji;
5558 DebuggerTlsData *tls = NULL;
5560 if (thread_to_tls != NULL) {
5561 MonoInternalThread *thread = mono_thread_internal_current ();
5563 mono_loader_lock ();
5564 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5565 mono_loader_unlock ();
5567 if (tls && tls->abort_requested)
5569 if (tls && tls->disable_breakpoints)
5573 memset (&ei, 0, sizeof (EventInfo));
5575 /* Just-In-Time debugging */
5577 if (agent_config.onuncaught && !inited) {
5578 finish_agent_init (FALSE);
5581 * Send an unsolicited EXCEPTION event with a dummy request id.
5583 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5584 ei.exc = (MonoObject*)exc;
5585 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5588 } else if (agent_config.onthrow && !inited) {
5590 gboolean found = FALSE;
5592 for (l = agent_config.onthrow; l; l = l->next) {
5593 char *ex_type = l->data;
5594 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5596 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5603 finish_agent_init (FALSE);
5606 * Send an unsolicited EXCEPTION event with a dummy request id.
5608 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5609 ei.exc = (MonoObject*)exc;
5610 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5618 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5620 catch_ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5624 ei.exc = (MonoObject*)exc;
5625 ei.caught = catch_ctx != NULL;
5627 mono_loader_lock ();
5629 /* Treat exceptions which are caught in non-user code as unhandled */
5630 for (i = 0; i < event_requests->len; ++i) {
5631 EventRequest *req = g_ptr_array_index (event_requests, i);
5632 if (req->event_kind != EVENT_KIND_EXCEPTION)
5635 for (j = 0; j < req->nmodifiers; ++j) {
5636 Modifier *mod = &req->modifiers [j];
5638 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5640 gboolean found = FALSE;
5641 MonoAssembly **assemblies = mod->data.assemblies;
5644 for (k = 0; assemblies [k]; ++k)
5645 if (assemblies [k] == jinfo_get_method (catch_ji)->klass->image->assembly)
5654 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5655 mono_loader_unlock ();
5657 if (tls && ei.caught && catch_ctx) {
5658 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5659 tls->catch_state.ctx = *catch_ctx;
5660 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5661 tls->catch_state.valid = TRUE;
5664 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5667 tls->catch_state.valid = FALSE;
5671 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5673 DebuggerTlsData *tls;
5678 tls = mono_native_tls_get_value (debugger_tls_id);
5683 * We're about to invoke an exception filter during the first pass of exception handling.
5685 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5686 * 'orig_ctx' is the context where the exception has been thrown.
5689 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5691 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5692 * the call site (line 37) and then continue to Main(), but it would never
5693 * include the throw site (line 32).
5695 * Since exception filters are invoked during the first pass of exception handling,
5696 * the stack frames of the throw site are still intact, so we should include them
5699 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5701 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5702 * but report the location of the 'throw' to the user.
5706 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5710 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5712 DebuggerTlsData *tls;
5717 tls = mono_native_tls_get_value (debugger_tls_id);
5721 tls->filter_state.valid = FALSE;
5725 * buffer_add_value_full:
5727 * Add the encoding of the value at ADDR described by T to the buffer.
5728 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5732 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5733 gboolean as_vtype, GHashTable *parent_vtypes)
5736 gboolean boxed_vtype = FALSE;
5739 if (!(*(void**)addr)) {
5740 /* This can happen with compiler generated locals */
5741 //printf ("%s\n", mono_type_full_name (t));
5742 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5745 g_assert (*(void**)addr);
5746 addr = *(void**)addr;
5751 case MONO_TYPE_BOOLEAN:
5754 case MONO_TYPE_CHAR:
5774 case MONO_TYPE_VOID:
5775 buffer_add_byte (buf, t->type);
5777 case MONO_TYPE_BOOLEAN:
5780 buffer_add_byte (buf, t->type);
5781 buffer_add_int (buf, *(gint8*)addr);
5783 case MONO_TYPE_CHAR:
5786 buffer_add_byte (buf, t->type);
5787 buffer_add_int (buf, *(gint16*)addr);
5792 buffer_add_byte (buf, t->type);
5793 buffer_add_int (buf, *(gint32*)addr);
5798 buffer_add_byte (buf, t->type);
5799 buffer_add_long (buf, *(gint64*)addr);
5803 /* Treat it as a vtype */
5805 case MONO_TYPE_PTR: {
5806 gssize val = *(gssize*)addr;
5808 buffer_add_byte (buf, t->type);
5809 buffer_add_long (buf, val);
5813 case MONO_TYPE_STRING:
5814 case MONO_TYPE_SZARRAY:
5815 case MONO_TYPE_OBJECT:
5816 case MONO_TYPE_CLASS:
5817 case MONO_TYPE_ARRAY:
5818 obj = *(MonoObject**)addr;
5821 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5823 if (obj->vtable->klass->valuetype) {
5824 t = &obj->vtable->klass->byval_arg;
5825 addr = mono_object_unbox (obj);
5828 } else if (obj->vtable->klass->rank) {
5829 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5830 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5831 buffer_add_byte (buf, MONO_TYPE_CLASS);
5833 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5835 buffer_add_objid (buf, obj);
5839 case MONO_TYPE_VALUETYPE: {
5843 MonoClass *klass = mono_class_from_mono_type (t);
5848 * Handle boxed vtypes recursively referencing themselves using fields.
5851 parent_vtypes = g_hash_table_new (NULL, NULL);
5852 vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
5854 if (CHECK_PROTOCOL_VERSION (2, 33)) {
5855 buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
5856 buffer_add_int (buf, vtype_index - 1);
5858 /* The client can't handle PARENT_VTYPE */
5859 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5863 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
5867 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5868 buffer_add_byte (buf, klass->enumtype);
5869 buffer_add_typeid (buf, domain, klass);
5873 while ((f = mono_class_get_fields (klass, &iter))) {
5874 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5876 if (mono_field_is_deleted (f))
5880 buffer_add_int (buf, nfields);
5883 while ((f = mono_class_get_fields (klass, &iter))) {
5884 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5886 if (mono_field_is_deleted (f))
5888 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE, parent_vtypes);
5892 g_hash_table_remove (parent_vtypes, addr);
5893 if (g_hash_table_size (parent_vtypes) == 0) {
5894 g_hash_table_destroy (parent_vtypes);
5895 parent_vtypes = NULL;
5900 case MONO_TYPE_GENERICINST:
5901 if (mono_type_generic_inst_is_valuetype (t)) {
5913 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5915 buffer_add_value_full (buf, t, addr, domain, FALSE, NULL);
5919 obj_is_of_type (MonoObject *obj, MonoType *t)
5921 MonoClass *klass = obj->vtable->klass;
5922 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5923 if (mono_class_is_transparent_proxy (klass)) {
5924 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5925 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5935 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5938 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5944 gpointer iter = NULL;
5948 is_enum = decode_byte (buf, &buf, limit);
5949 /* Enums are sent as a normal vtype */
5951 return ERR_NOT_IMPLEMENTED;
5952 klass = decode_typeid (buf, &buf, limit, &d, &err);
5956 if (t && klass != mono_class_from_mono_type (t)) {
5957 char *name = mono_type_full_name (t);
5958 char *name2 = mono_type_full_name (&klass->byval_arg);
5959 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got %s.\n", (gpointer)GetCurrentThreadId (), name, name2));
5962 return ERR_INVALID_ARGUMENT;
5965 nfields = decode_int (buf, &buf, limit);
5966 while ((f = mono_class_get_fields (klass, &iter))) {
5967 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5969 if (mono_field_is_deleted (f))
5971 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5976 g_assert (nfields == 0);
5984 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5988 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5989 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5990 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5991 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5992 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
5993 char *name = mono_type_full_name (t);
5994 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5996 return ERR_INVALID_ARGUMENT;
6000 case MONO_TYPE_BOOLEAN:
6001 *(guint8*)addr = decode_int (buf, &buf, limit);
6003 case MONO_TYPE_CHAR:
6004 *(gunichar2*)addr = decode_int (buf, &buf, limit);
6007 *(gint8*)addr = decode_int (buf, &buf, limit);
6010 *(guint8*)addr = decode_int (buf, &buf, limit);
6013 *(gint16*)addr = decode_int (buf, &buf, limit);
6016 *(guint16*)addr = decode_int (buf, &buf, limit);
6019 *(gint32*)addr = decode_int (buf, &buf, limit);
6022 *(guint32*)addr = decode_int (buf, &buf, limit);
6025 *(gint64*)addr = decode_long (buf, &buf, limit);
6028 *(guint64*)addr = decode_long (buf, &buf, limit);
6031 *(guint32*)addr = decode_int (buf, &buf, limit);
6034 *(guint64*)addr = decode_long (buf, &buf, limit);
6037 /* We send these as I8, so we get them back as such */
6038 g_assert (type == MONO_TYPE_I8);
6039 *(gssize*)addr = decode_long (buf, &buf, limit);
6041 case MONO_TYPE_GENERICINST:
6042 if (MONO_TYPE_ISSTRUCT (t)) {
6043 /* The client sends these as a valuetype */
6051 /* We send these as vtypes, so we get them back as such */
6052 g_assert (type == MONO_TYPE_VALUETYPE);
6055 case MONO_TYPE_VALUETYPE:
6056 err = decode_vtype (t, domain, addr,buf, &buf, limit);
6062 if (MONO_TYPE_IS_REFERENCE (t)) {
6063 if (type == MONO_TYPE_OBJECT) {
6064 int objid = decode_objid (buf, &buf, limit);
6068 err = get_object (objid, (MonoObject**)&obj);
6073 if (!obj_is_of_type (obj, t)) {
6074 DEBUG (1, fprintf (log_file, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name));
6075 return ERR_INVALID_ARGUMENT;
6078 if (obj && obj->vtable->domain != domain)
6079 return ERR_INVALID_ARGUMENT;
6081 mono_gc_wbarrier_generic_store (addr, obj);
6082 } else if (type == VALUE_TYPE_ID_NULL) {
6083 *(MonoObject**)addr = NULL;
6084 } else if (type == MONO_TYPE_VALUETYPE) {
6092 /* This can happen when round-tripping boxed vtypes */
6094 * Obtain vtype class.
6095 * Same as the beginning of the handle_vtype case above.
6098 is_enum = decode_byte (buf, &buf, limit);
6100 return ERR_NOT_IMPLEMENTED;
6101 klass = decode_typeid (buf, &buf, limit, &d, &err);
6105 /* Decode the vtype into a temporary buffer, then box it. */
6106 vtype_buf_size = mono_class_value_size (klass, NULL);
6107 vtype_buf = g_malloc0 (vtype_buf_size);
6108 g_assert (vtype_buf);
6111 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
6116 *(MonoObject**)addr = mono_value_box (d, klass, vtype_buf);
6119 char *name = mono_type_full_name (t);
6120 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
6122 return ERR_INVALID_ARGUMENT;
6136 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6139 int type = decode_byte (buf, &buf, limit);
6141 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
6142 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
6143 guint8 *nullable_buf;
6146 * First try decoding it as a Nullable`1
6148 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6153 * Then try decoding as a primitive value or null.
6155 if (targ->type == type) {
6156 nullable_buf = g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
6157 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
6159 g_free (nullable_buf);
6162 mono_nullable_init (addr, mono_value_box (domain, mono_class_from_mono_type (targ), nullable_buf), mono_class_from_mono_type (t));
6163 g_free (nullable_buf);
6166 } else if (type == VALUE_TYPE_ID_NULL) {
6167 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
6173 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6177 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
6181 guint8 *addr, *gaddr;
6184 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6185 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6188 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
6189 reg_val = mono_arch_context_get_int_reg (ctx, reg);
6191 buffer_add_value_full (buf, t, ®_val, domain, as_vtype, NULL);
6193 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6194 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6195 addr += (gint32)var->offset;
6197 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6199 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6201 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6204 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6205 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
6206 /* Same as regoffset, but with an indirection */
6207 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6208 addr += (gint32)var->offset;
6210 gaddr = *(gpointer*)addr;
6212 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL);
6214 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
6215 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
6216 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
6217 MonoGSharedVtMethodRuntimeInfo *info;
6223 g_assert (info_var);
6224 g_assert (locals_var);
6226 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6227 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6228 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6229 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6230 addr += (gint32)info_var->offset;
6231 info = *(gpointer*)addr;
6232 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6233 info = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6235 g_assert_not_reached ();
6239 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6240 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6241 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6242 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6243 addr += (gint32)locals_var->offset;
6244 locals = *(gpointer*)addr;
6245 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6246 locals = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6248 g_assert_not_reached ();
6252 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6254 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6259 g_assert_not_reached ();
6264 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
6268 guint8 *addr, *gaddr;
6270 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6271 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6273 if (MONO_TYPE_IS_REFERENCE (t))
6274 size = sizeof (gpointer);
6276 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6279 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6280 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6282 gboolean is_signed = FALSE;
6285 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6288 // FIXME: Write barriers
6289 mono_gc_memmove_atomic (addr, val, size);
6294 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6299 v = is_signed ? *(gint8*)val : *(guint8*)val;
6302 v = is_signed ? *(gint16*)val : *(guint16*)val;
6305 v = is_signed ? *(gint32*)val : *(guint32*)val;
6308 v = is_signed ? *(gint64*)val : *(guint64*)val;
6311 g_assert_not_reached ();
6314 /* Set value on the stack or in the return ctx */
6315 if (reg_locations [reg]) {
6316 /* Saved on the stack */
6317 DEBUG (1, fprintf (log_file, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v));
6318 *(reg_locations [reg]) = v;
6321 DEBUG (1, fprintf (log_file, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v));
6322 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6325 // FIXME: Move these to mono-context.h/c.
6326 mono_arch_context_set_int_reg (ctx, reg, v);
6328 // FIXME: Can't set registers, so we disable linears
6333 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6334 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6335 addr += (gint32)var->offset;
6337 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6340 addr = *(guint8**)addr;
6346 // FIXME: Write barriers
6347 mono_gc_memmove_atomic (addr, val, size);
6349 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6350 /* Same as regoffset, but with an indirection */
6351 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6352 addr += (gint32)var->offset;
6354 gaddr = *(gpointer*)addr;
6356 // FIXME: Write barriers
6357 mono_gc_memmove_atomic (gaddr, val, size);
6359 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6363 g_assert_not_reached ();
6368 clear_event_request (int req_id, int etype)
6372 mono_loader_lock ();
6373 for (i = 0; i < event_requests->len; ++i) {
6374 EventRequest *req = g_ptr_array_index (event_requests, i);
6376 if (req->id == req_id && req->event_kind == etype) {
6377 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6378 clear_breakpoint (req->info);
6379 if (req->event_kind == EVENT_KIND_STEP)
6380 ss_destroy (req->info);
6381 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6382 clear_breakpoint (req->info);
6383 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6384 clear_breakpoint (req->info);
6385 g_ptr_array_remove_index_fast (event_requests, i);
6390 mono_loader_unlock ();
6394 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
6398 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6399 m->kind = MOD_KIND_NONE;
6400 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6401 int count = 0, match_count = 0, pos;
6402 MonoAssembly **newassemblies;
6404 for (i = 0; m->data.assemblies [i]; ++i) {
6406 if (m->data.assemblies [i] == assembly)
6411 newassemblies = g_new0 (MonoAssembly*, count - match_count);
6414 for (i = 0; i < count; ++i)
6415 if (m->data.assemblies [i] != assembly)
6416 newassemblies [pos ++] = m->data.assemblies [i];
6417 g_assert (pos == count - match_count);
6418 g_free (m->data.assemblies);
6419 m->data.assemblies = newassemblies;
6425 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
6429 for (i = 0; i < req->nmodifiers; ++i) {
6430 Modifier *m = &req->modifiers [i];
6432 clear_assembly_from_modifier (req, m, assembly);
6437 * clear_event_requests_for_assembly:
6439 * Clear all events requests which reference ASSEMBLY.
6442 clear_event_requests_for_assembly (MonoAssembly *assembly)
6447 mono_loader_lock ();
6451 for (i = 0; i < event_requests->len; ++i) {
6452 EventRequest *req = g_ptr_array_index (event_requests, i);
6454 clear_assembly_from_modifiers (req, assembly);
6456 if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly (req->info, assembly)) {
6457 clear_event_request (req->id, req->event_kind);
6462 if (req->event_kind == EVENT_KIND_STEP)
6463 ss_clear_for_assembly (req->info, assembly);
6466 mono_loader_unlock ();
6470 * type_comes_from_assembly:
6472 * GHRFunc that returns TRUE if klass comes from assembly
6475 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6477 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6481 * clear_types_for_assembly:
6483 * Clears types from loaded_classes for a given assembly
6486 clear_types_for_assembly (MonoAssembly *assembly)
6488 MonoDomain *domain = mono_domain_get ();
6489 AgentDomainInfo *info = NULL;
6491 mono_loader_lock ();
6492 info = get_agent_domain_info (domain);
6493 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6494 mono_loader_unlock ();
6498 add_thread (gpointer key, gpointer value, gpointer user_data)
6500 MonoInternalThread *thread = value;
6501 Buffer *buf = user_data;
6503 buffer_add_objid (buf, (MonoObject*)thread);
6507 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6509 guint8 *end = invoke->endp;
6512 MonoMethodSignature *sig;
6515 MonoObject *this, *res, *exc;
6518 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6521 MonoStopwatch watch;
6523 if (invoke->method) {
6525 * Invoke this method directly, currently only Environment.Exit () is supported.
6528 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>"));
6529 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
6530 g_assert_not_reached ();
6533 m = decode_methodid (p, &p, end, &domain, &err);
6536 sig = mono_method_signature (m);
6538 if (m->klass->valuetype)
6539 this_buf = g_alloca (mono_class_instance_size (m->klass));
6541 this_buf = g_alloca (sizeof (MonoObject*));
6542 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6543 /* Should be null */
6544 int type = decode_byte (p, &p, end);
6545 if (type != VALUE_TYPE_ID_NULL) {
6546 DEBUG (1, fprintf (log_file, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer)GetCurrentThreadId ()));
6547 return ERR_INVALID_ARGUMENT;
6549 memset (this_buf, 0, mono_class_instance_size (m->klass));
6551 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6556 if (!m->klass->valuetype)
6557 this = *(MonoObject**)this_buf;
6561 if (MONO_CLASS_IS_INTERFACE (m->klass)) {
6563 DEBUG (1, fprintf (log_file, "[%p] Error: Interface method invoked without this argument.\n", (gpointer)GetCurrentThreadId ()));
6564 return ERR_INVALID_ARGUMENT;
6566 m = mono_object_get_virtual_method (this, m);
6569 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>"));
6571 if (this && this->vtable->domain != domain)
6574 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
6575 if (!strcmp (m->name, ".ctor")) {
6576 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
6577 return ERR_INVALID_ARGUMENT;
6579 this = mono_object_new (domain, m->klass);
6581 return ERR_INVALID_ARGUMENT;
6585 if (this && !obj_is_of_type (this, &m->klass->byval_arg))
6586 return ERR_INVALID_ARGUMENT;
6588 nargs = decode_int (p, &p, end);
6589 if (nargs != sig->param_count)
6590 return ERR_INVALID_ARGUMENT;
6591 /* Use alloca to get gc tracking */
6592 arg_buf = g_alloca (nargs * sizeof (gpointer));
6593 memset (arg_buf, 0, nargs * sizeof (gpointer));
6594 args = g_alloca (nargs * sizeof (gpointer));
6595 for (i = 0; i < nargs; ++i) {
6596 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6597 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6600 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6603 if (sig->params [i]->byref) {
6604 arg_buf [i] = g_alloca (sizeof (mgreg_t));
6605 *(gpointer*)arg_buf [i] = args [i];
6606 args [i] = arg_buf [i];
6609 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6610 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6613 args [i] = arg_buf [i];
6620 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6621 tls->disable_breakpoints = TRUE;
6623 tls->disable_breakpoints = FALSE;
6626 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6628 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6629 if (invoke->has_ctx) {
6632 lmf_addr = mono_get_lmf_addr ();
6635 memset (&ext, 0, sizeof (ext));
6636 mono_arch_init_lmf_ext (&ext, *lmf_addr);
6638 ext.debugger_invoke = TRUE;
6639 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6641 mono_set_lmf ((MonoLMF*)&ext);
6645 mono_stopwatch_start (&watch);
6646 if (m->klass->valuetype)
6647 res = mono_runtime_invoke (m, this_buf, args, &exc);
6649 res = mono_runtime_invoke (m, this, args, &exc);
6650 mono_stopwatch_stop (&watch);
6651 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)));
6653 buffer_add_byte (buf, 0);
6654 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6656 gboolean out_this = FALSE;
6657 gboolean out_args = FALSE;
6659 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_THIS) && CHECK_PROTOCOL_VERSION (2, 35))
6661 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_ARGS) && CHECK_PROTOCOL_VERSION (2, 35))
6663 buffer_add_byte (buf, 1 + (out_this ? 2 : 0) + (out_args ? 4 : 0));
6664 if (sig->ret->type == MONO_TYPE_VOID) {
6665 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
6666 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
6669 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6670 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6671 buffer_add_value (buf, sig->ret, &res, domain);
6672 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6673 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6674 MonoClass *k = mono_class_from_mono_type (sig->ret);
6675 guint8 *nullable_buf = g_alloca (mono_class_value_size (k, NULL));
6677 g_assert (nullable_buf);
6678 mono_nullable_init (nullable_buf, res, k);
6679 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6682 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6688 /* Return the new value of the receiver after the call */
6689 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
6691 buffer_add_int (buf, nargs);
6692 for (i = 0; i < nargs; ++i) {
6693 if (MONO_TYPE_IS_REFERENCE (sig->params [i]))
6694 buffer_add_value (buf, sig->params [i], &args [i], domain);
6695 else if (sig->params [i]->byref)
6696 /* add_value () does an indirection */
6697 buffer_add_value (buf, sig->params [i], &arg_buf [i], domain);
6699 buffer_add_value (buf, sig->params [i], arg_buf [i], domain);
6704 tls->disable_breakpoints = FALSE;
6706 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6707 if (invoke->has_ctx)
6708 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
6712 // FIXME: byref arguments
6720 * Invoke the method given by tls->pending_invoke in the current thread.
6723 invoke_method (void)
6725 DebuggerTlsData *tls;
6730 MonoContext restore_ctx;
6733 tls = mono_native_tls_get_value (debugger_tls_id);
6737 * Store the `InvokeData *' in `tls->invoke' until we're done with
6738 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6741 mono_loader_lock ();
6743 invoke = tls->pending_invoke;
6745 tls->pending_invoke = NULL;
6747 invoke->last_invoke = tls->invoke;
6748 tls->invoke = invoke;
6750 mono_loader_unlock ();
6752 tls->frames_up_to_date = FALSE;
6758 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6759 buffer_init (&buf, 128);
6762 /* Fail the other invokes as well */
6764 err = do_invoke_method (tls, &buf, invoke, p, &p);
6767 /* Start suspending before sending the reply */
6768 if (mindex == invoke->nmethods - 1) {
6769 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6770 for (i = 0; i < invoke->suspend_count; ++i)
6775 send_reply_packet (id, err, &buf);
6780 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6782 if (invoke->has_ctx)
6783 save_thread_context (&restore_ctx);
6785 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6786 g_assert (tls->resume_count);
6787 tls->resume_count -= invoke->suspend_count;
6790 DEBUG (1, fprintf (log_file, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer)GetCurrentThreadId (), err, tls->resume_count));
6793 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6795 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
6796 * after the mono_runtime_invoke() already returned, but it doesn't matter
6797 * because we reset the abort here.
6800 mono_loader_lock ();
6802 if (tls->abort_requested)
6803 mono_thread_internal_reset_abort (tls->thread);
6805 tls->invoke = tls->invoke->last_invoke;
6806 tls->abort_requested = FALSE;
6808 mono_loader_unlock ();
6817 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6819 MonoThread *thread = value;
6820 DebuggerTlsData *tls;
6823 mono_loader_lock ();
6824 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6826 res = tls->really_suspended;
6827 mono_loader_unlock ();
6833 get_source_files_for_type (MonoClass *klass)
6835 gpointer iter = NULL;
6837 MonoDebugSourceInfo *sinfo;
6841 files = g_ptr_array_new ();
6843 while ((method = mono_class_get_methods (klass, &iter))) {
6844 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6845 GPtrArray *source_file_list;
6848 mono_debug_symfile_get_line_numbers_full (minfo, NULL, &source_file_list, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
6849 for (j = 0; j < source_file_list->len; ++j) {
6850 sinfo = g_ptr_array_index (source_file_list, j);
6851 for (i = 0; i < files->len; ++i)
6852 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6854 if (i == files->len)
6855 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6857 g_ptr_array_free (source_file_list, TRUE);
6865 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6868 case CMD_VM_VERSION: {
6869 char *build_info, *version;
6871 build_info = mono_get_runtime_build_info ();
6872 version = g_strdup_printf ("mono %s", build_info);
6874 buffer_add_string (buf, version); /* vm version */
6875 buffer_add_int (buf, MAJOR_VERSION);
6876 buffer_add_int (buf, MINOR_VERSION);
6877 g_free (build_info);
6881 case CMD_VM_SET_PROTOCOL_VERSION: {
6882 major_version = decode_int (p, &p, end);
6883 minor_version = decode_int (p, &p, end);
6884 protocol_version_set = TRUE;
6885 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
6888 case CMD_VM_ALL_THREADS: {
6890 mono_loader_lock ();
6891 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6892 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6893 mono_loader_unlock ();
6896 case CMD_VM_SUSPEND:
6898 wait_for_suspend ();
6901 if (suspend_count == 0)
6902 return ERR_NOT_SUSPENDED;
6904 clear_suspended_objs ();
6906 case CMD_VM_DISPOSE:
6907 /* Clear all event requests */
6908 mono_loader_lock ();
6909 while (event_requests->len > 0) {
6910 EventRequest *req = g_ptr_array_index (event_requests, 0);
6912 clear_event_request (req->id, req->event_kind);
6914 mono_loader_unlock ();
6916 while (suspend_count > 0)
6918 disconnected = TRUE;
6919 vm_start_event_sent = FALSE;
6922 MonoInternalThread *thread;
6923 DebuggerTlsData *tls;
6924 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6925 MonoClass *env_class;
6927 MonoMethod *exit_method = NULL;
6931 exit_code = decode_int (p, &p, end);
6933 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6935 /* Have to send a reply before exiting */
6936 send_reply_packet (id, 0, buf);
6938 /* Clear all event requests */
6939 mono_loader_lock ();
6940 while (event_requests->len > 0) {
6941 EventRequest *req = g_ptr_array_index (event_requests, 0);
6943 clear_event_request (req->id, req->event_kind);
6945 mono_loader_unlock ();
6948 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6949 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6950 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6951 * better than doing the shutdown ourselves, since it avoids various races.
6955 wait_for_suspend ();
6957 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6958 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
6960 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6963 mono_loader_lock ();
6964 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6965 mono_loader_unlock ();
6967 if (thread && exit_method) {
6968 mono_loader_lock ();
6969 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6970 mono_loader_unlock ();
6972 args = g_new0 (gpointer, 1);
6973 args [0] = g_malloc (sizeof (int));
6974 *(int*)(args [0]) = exit_code;
6976 tls->pending_invoke = g_new0 (InvokeData, 1);
6977 tls->pending_invoke->method = exit_method;
6978 tls->pending_invoke->args = args;
6979 tls->pending_invoke->nmethods = 1;
6981 while (suspend_count > 0)
6985 * No thread found, do it ourselves.
6986 * FIXME: This can race with normal shutdown etc.
6988 while (suspend_count > 0)
6991 if (!mono_runtime_try_shutdown ())
6994 mono_environment_exitcode_set (exit_code);
6996 /* Suspend all managed threads since the runtime is going away */
6997 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
6998 mono_thread_suspend_all_other_threads ();
6999 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
7000 mono_runtime_quit ();
7001 transport_close2 ();
7002 DEBUG(1, fprintf (log_file, "Exiting...\n"));
7008 case CMD_VM_INVOKE_METHOD:
7009 case CMD_VM_INVOKE_METHODS: {
7010 int objid = decode_objid (p, &p, end);
7012 DebuggerTlsData *tls;
7013 int i, count, err, flags, nmethods;
7015 err = get_object (objid, (MonoObject**)&thread);
7019 flags = decode_int (p, &p, end);
7021 if (command == CMD_VM_INVOKE_METHODS)
7022 nmethods = decode_int (p, &p, end);
7026 // Wait for suspending if it already started
7028 wait_for_suspend ();
7029 if (!is_suspended ())
7030 return ERR_NOT_SUSPENDED;
7032 mono_loader_lock ();
7033 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7034 mono_loader_unlock ();
7037 if (!tls->really_suspended)
7038 /* The thread is still running native code, can't do invokes */
7039 return ERR_NOT_SUSPENDED;
7042 * Store the invoke data into tls, the thread will execute it after it is
7045 if (tls->pending_invoke)
7046 return ERR_NOT_SUSPENDED;
7047 tls->pending_invoke = g_new0 (InvokeData, 1);
7048 tls->pending_invoke->id = id;
7049 tls->pending_invoke->flags = flags;
7050 tls->pending_invoke->p = g_malloc (end - p);
7051 memcpy (tls->pending_invoke->p, p, end - p);
7052 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
7053 tls->pending_invoke->suspend_count = suspend_count;
7054 tls->pending_invoke->nmethods = nmethods;
7056 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
7057 resume_thread (THREAD_TO_INTERNAL (thread));
7060 count = suspend_count;
7061 for (i = 0; i < count; ++i)
7066 case CMD_VM_ABORT_INVOKE: {
7067 int objid = decode_objid (p, &p, end);
7069 DebuggerTlsData *tls;
7072 err = get_object (objid, (MonoObject**)&thread);
7076 invoke_id = decode_int (p, &p, end);
7078 mono_loader_lock ();
7079 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7082 if (tls->abort_requested) {
7083 mono_loader_unlock ();
7088 * Check whether we're still inside the mono_runtime_invoke() and that it's
7089 * actually the correct invocation.
7091 * Careful, we do not stop the thread that's doing the invocation, so we can't
7092 * inspect its stack. However, invoke_method() also acquires the loader lock
7093 * when it's done, so we're safe here.
7097 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
7098 mono_loader_unlock ();
7099 return ERR_NO_INVOCATION;
7102 tls->abort_requested = TRUE;
7104 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
7105 mono_loader_unlock ();
7109 case CMD_VM_SET_KEEPALIVE: {
7110 int timeout = decode_int (p, &p, end);
7111 agent_config.keepalive = timeout;
7113 #ifndef DISABLE_SOCKET_TRANSPORT
7120 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
7121 GHashTableIter iter, kiter;
7126 char *fname, *basename;
7127 gboolean ignore_case;
7128 GSList *class_list, *l;
7129 GPtrArray *res_classes, *res_domains;
7131 fname = decode_string (p, &p, end);
7132 ignore_case = decode_byte (p, &p, end);
7134 basename = g_path_get_basename (fname);
7136 res_classes = g_ptr_array_new ();
7137 res_domains = g_ptr_array_new ();
7139 mono_loader_lock ();
7140 g_hash_table_iter_init (&iter, domains);
7141 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7142 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
7144 /* Update 'source_file_to_class' cache */
7145 g_hash_table_iter_init (&kiter, info->loaded_classes);
7146 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
7147 if (!g_hash_table_lookup (info->source_files, klass)) {
7148 files = get_source_files_for_type (klass);
7149 g_hash_table_insert (info->source_files, klass, files);
7151 for (i = 0; i < files->len; ++i) {
7152 char *s = g_ptr_array_index (files, i);
7153 char *s2 = g_path_get_basename (s);
7156 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
7158 class_list = g_slist_prepend (class_list, klass);
7159 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
7161 class_list = g_slist_prepend (class_list, klass);
7162 g_hash_table_insert (info->source_file_to_class, s2, class_list);
7165 /* The _ignorecase hash contains the lowercase path */
7166 s3 = strdup_tolower (s2);
7167 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
7169 class_list = g_slist_prepend (class_list, klass);
7170 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
7172 class_list = g_slist_prepend (class_list, klass);
7173 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
7185 s = strdup_tolower (basename);
7186 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
7189 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
7192 for (l = class_list; l; l = l->next) {
7195 g_ptr_array_add (res_classes, klass);
7196 g_ptr_array_add (res_domains, domain);
7199 mono_loader_unlock ();
7204 buffer_add_int (buf, res_classes->len);
7205 for (i = 0; i < res_classes->len; ++i)
7206 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
7207 g_ptr_array_free (res_classes, TRUE);
7208 g_ptr_array_free (res_domains, TRUE);
7211 case CMD_VM_GET_TYPES: {
7212 GHashTableIter iter;
7216 gboolean ignore_case;
7217 GPtrArray *res_classes, *res_domains;
7218 MonoTypeNameParse info;
7220 name = decode_string (p, &p, end);
7221 ignore_case = decode_byte (p, &p, end);
7223 if (!mono_reflection_parse_type (name, &info)) {
7225 mono_reflection_free_type_info (&info);
7226 return ERR_INVALID_ARGUMENT;
7229 res_classes = g_ptr_array_new ();
7230 res_domains = g_ptr_array_new ();
7232 mono_loader_lock ();
7233 g_hash_table_iter_init (&iter, domains);
7234 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7236 gboolean type_resolve;
7240 mono_domain_assemblies_lock (domain);
7241 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7245 type_resolve = TRUE;
7246 t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
7248 g_ptr_array_add (res_classes, mono_type_get_class (t));
7249 g_ptr_array_add (res_domains, domain);
7253 mono_domain_assemblies_unlock (domain);
7255 mono_loader_unlock ();
7258 mono_reflection_free_type_info (&info);
7260 buffer_add_int (buf, res_classes->len);
7261 for (i = 0; i < res_classes->len; ++i)
7262 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
7263 g_ptr_array_free (res_classes, TRUE);
7264 g_ptr_array_free (res_domains, TRUE);
7267 case CMD_VM_START_BUFFERING:
7268 case CMD_VM_STOP_BUFFERING:
7269 /* Handled in the main loop */
7272 return ERR_NOT_IMPLEMENTED;
7279 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7285 case CMD_EVENT_REQUEST_SET: {
7287 int i, event_kind, suspend_policy, nmodifiers, mod;
7290 MonoThread *step_thread;
7291 int size = 0, depth = 0, filter = 0, step_thread_id = 0;
7295 event_kind = decode_byte (p, &p, end);
7296 suspend_policy = decode_byte (p, &p, end);
7297 nmodifiers = decode_byte (p, &p, end);
7299 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7300 req->id = InterlockedIncrement (&event_request_id);
7301 req->event_kind = event_kind;
7302 req->suspend_policy = suspend_policy;
7303 req->nmodifiers = nmodifiers;
7306 for (i = 0; i < nmodifiers; ++i) {
7307 mod = decode_byte (p, &p, end);
7309 req->modifiers [i].kind = mod;
7310 if (mod == MOD_KIND_COUNT) {
7311 req->modifiers [i].data.count = decode_int (p, &p, end);
7312 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7313 method = decode_methodid (p, &p, end, &domain, &err);
7316 location = decode_long (p, &p, end);
7317 } else if (mod == MOD_KIND_STEP) {
7318 step_thread_id = decode_id (p, &p, end);
7319 size = decode_int (p, &p, end);
7320 depth = decode_int (p, &p, end);
7321 if (CHECK_PROTOCOL_VERSION (2, 16))
7322 filter = decode_int (p, &p, end);
7323 req->modifiers [i].data.filter = filter;
7324 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7325 /* Treat STEP_THOUGH the same as HIDDEN */
7326 req->modifiers [i].data.filter |= STEP_FILTER_DEBUGGER_STEP_THROUGH;
7327 } else if (mod == MOD_KIND_THREAD_ONLY) {
7328 int id = decode_id (p, &p, end);
7330 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7335 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7336 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7340 req->modifiers [i].caught = decode_byte (p, &p, end);
7341 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7342 if (CHECK_PROTOCOL_VERSION (2, 25))
7343 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7345 req->modifiers [i].subclasses = TRUE;
7346 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" : ""));
7348 req->modifiers [i].data.exc_class = exc_class;
7350 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
7352 return ERR_INVALID_ARGUMENT;
7355 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7356 int n = decode_int (p, &p, end);
7359 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
7360 for (j = 0; j < n; ++j) {
7361 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7363 g_free (req->modifiers [i].data.assemblies);
7367 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7368 int n = decode_int (p, &p, end);
7371 modifier = &req->modifiers [i];
7372 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7373 for (j = 0; j < n; ++j) {
7374 char *s = decode_string (p, &p, end);
7378 s2 = strdup_tolower (s);
7379 g_hash_table_insert (modifier->data.source_files, s2, s2);
7383 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7384 int n = decode_int (p, &p, end);
7387 modifier = &req->modifiers [i];
7388 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7389 for (j = 0; j < n; ++j) {
7390 char *s = decode_string (p, &p, end);
7393 g_hash_table_insert (modifier->data.type_names, s, s);
7397 return ERR_NOT_IMPLEMENTED;
7401 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7404 req->info = set_breakpoint (method, location, req, &error);
7405 if (!mono_error_ok (&error)) {
7407 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
7408 mono_error_cleanup (&error);
7409 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7411 } else if (req->event_kind == EVENT_KIND_STEP) {
7412 g_assert (step_thread_id);
7414 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7420 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
7425 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7426 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7427 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7428 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7429 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7430 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7432 if (req->nmodifiers) {
7434 return ERR_NOT_IMPLEMENTED;
7438 mono_loader_lock ();
7439 g_ptr_array_add (event_requests, req);
7441 if (agent_config.defer) {
7442 /* Transmit cached data to the client on receipt of the event request */
7443 switch (req->event_kind) {
7444 case EVENT_KIND_APPDOMAIN_CREATE:
7445 /* Emit load events for currently loaded domains */
7446 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7448 case EVENT_KIND_ASSEMBLY_LOAD:
7449 /* Emit load events for currently loaded assemblies */
7450 mono_assembly_foreach (emit_assembly_load, NULL);
7452 case EVENT_KIND_THREAD_START:
7453 /* Emit start events for currently started threads */
7454 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7456 case EVENT_KIND_TYPE_LOAD:
7457 /* Emit type load events for currently loaded types */
7458 mono_domain_foreach (send_types_for_domain, NULL);
7464 mono_loader_unlock ();
7466 buffer_add_int (buf, req->id);
7469 case CMD_EVENT_REQUEST_CLEAR: {
7470 int etype = decode_byte (p, &p, end);
7471 int req_id = decode_int (p, &p, end);
7473 // FIXME: Make a faster mapping from req_id to request
7474 mono_loader_lock ();
7475 clear_event_request (req_id, etype);
7476 mono_loader_unlock ();
7479 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7482 mono_loader_lock ();
7484 while (i < event_requests->len) {
7485 EventRequest *req = g_ptr_array_index (event_requests, i);
7487 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7488 clear_breakpoint (req->info);
7490 g_ptr_array_remove_index_fast (event_requests, i);
7496 mono_loader_unlock ();
7500 return ERR_NOT_IMPLEMENTED;
7507 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7513 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7514 buffer_add_domainid (buf, mono_get_root_domain ());
7517 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7518 domain = decode_domainid (p, &p, end, NULL, &err);
7521 buffer_add_string (buf, domain->friendly_name);
7524 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7529 domain = decode_domainid (p, &p, end, NULL, &err);
7532 mono_loader_lock ();
7534 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7537 buffer_add_int (buf, count);
7538 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7540 buffer_add_assemblyid (buf, domain, ass);
7542 mono_loader_unlock ();
7545 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7546 domain = decode_domainid (p, &p, end, NULL, &err);
7550 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7553 case CMD_APPDOMAIN_GET_CORLIB: {
7554 domain = decode_domainid (p, &p, end, NULL, &err);
7558 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7561 case CMD_APPDOMAIN_CREATE_STRING: {
7565 domain = decode_domainid (p, &p, end, NULL, &err);
7568 s = decode_string (p, &p, end);
7570 o = mono_string_new (domain, s);
7571 buffer_add_objid (buf, (MonoObject*)o);
7574 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7576 MonoDomain *domain2;
7579 domain = decode_domainid (p, &p, end, NULL, &err);
7582 klass = decode_typeid (p, &p, end, &domain2, &err);
7587 g_assert (domain == domain2);
7589 o = mono_object_new (domain, klass);
7591 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
7595 buffer_add_objid (buf, o);
7599 return ERR_NOT_IMPLEMENTED;
7606 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7612 ass = decode_assemblyid (p, &p, end, &domain, &err);
7617 case CMD_ASSEMBLY_GET_LOCATION: {
7618 buffer_add_string (buf, mono_image_get_filename (ass->image));
7621 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7625 if (ass->image->dynamic) {
7626 buffer_add_id (buf, 0);
7628 token = mono_image_get_entry_point (ass->image);
7630 buffer_add_id (buf, 0);
7632 m = mono_get_method (ass->image, token, NULL);
7633 buffer_add_methodid (buf, domain, m);
7638 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7639 buffer_add_moduleid (buf, domain, ass->image);
7642 case CMD_ASSEMBLY_GET_OBJECT: {
7643 MonoObject *o = (MonoObject*)mono_assembly_get_object (domain, ass);
7644 buffer_add_objid (buf, o);
7647 case CMD_ASSEMBLY_GET_TYPE: {
7648 char *s = decode_string (p, &p, end);
7649 gboolean ignorecase = decode_byte (p, &p, end);
7650 MonoTypeNameParse info;
7652 gboolean type_resolve, res;
7653 MonoDomain *d = mono_domain_get ();
7655 /* This is needed to be able to find referenced assemblies */
7656 res = mono_domain_set (domain, FALSE);
7659 if (!mono_reflection_parse_type (s, &info)) {
7662 if (info.assembly.name)
7664 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
7666 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
7667 mono_reflection_free_type_info (&info);
7670 mono_domain_set (d, TRUE);
7674 case CMD_ASSEMBLY_GET_NAME: {
7676 MonoAssembly *mass = ass;
7678 name = g_strdup_printf (
7679 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7681 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7682 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7683 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7684 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7686 buffer_add_string (buf, name);
7691 return ERR_NOT_IMPLEMENTED;
7698 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7704 case CMD_MODULE_GET_INFO: {
7705 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7708 basename = g_path_get_basename (image->name);
7709 buffer_add_string (buf, basename); // name
7710 buffer_add_string (buf, image->module_name); // scopename
7711 buffer_add_string (buf, image->name); // fqname
7712 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7713 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7718 return ERR_NOT_IMPLEMENTED;
7725 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7731 case CMD_FIELD_GET_INFO: {
7732 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
7734 buffer_add_string (buf, f->name);
7735 buffer_add_typeid (buf, domain, f->parent);
7736 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7737 buffer_add_int (buf, f->type->attrs);
7741 return ERR_NOT_IMPLEMENTED;
7748 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7750 if (val && val->vtable->klass == mono_defaults.monotype_class) {
7751 /* Special case these so the client doesn't have to handle Type objects */
7753 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7754 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7755 } else if (MONO_TYPE_IS_REFERENCE (t))
7756 buffer_add_value (buf, t, &val, domain);
7758 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7762 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7768 buffer_add_int (buf, 0);
7772 for (i = 0; i < cinfo->num_attrs; ++i) {
7773 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7776 buffer_add_int (buf, nattrs);
7778 for (i = 0; i < cinfo->num_attrs; ++i) {
7779 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7780 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7781 MonoArray *typed_args, *named_args;
7783 CattrNamedArg *arginfo = NULL;
7786 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
7787 if (!mono_error_ok (&error)) {
7788 DEBUG(2, fprintf (log_file, "[dbg] mono_reflection_create_custom_attr_data_args () failed with: '%s'\n", mono_error_get_message (&error)));
7789 mono_error_cleanup (&error);
7790 return ERR_LOADER_ERROR;
7793 buffer_add_methodid (buf, domain, attr->ctor);
7797 buffer_add_int (buf, mono_array_length (typed_args));
7798 for (j = 0; j < mono_array_length (typed_args); ++j) {
7799 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7801 t = mono_method_signature (attr->ctor)->params [j];
7803 buffer_add_cattr_arg (buf, t, domain, val);
7806 buffer_add_int (buf, 0);
7811 buffer_add_int (buf, mono_array_length (named_args));
7813 for (j = 0; j < mono_array_length (named_args); ++j) {
7814 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7816 if (arginfo [j].prop) {
7817 buffer_add_byte (buf, 0x54);
7818 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7819 } else if (arginfo [j].field) {
7820 buffer_add_byte (buf, 0x53);
7821 buffer_add_fieldid (buf, domain, arginfo [j].field);
7823 g_assert_not_reached ();
7826 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7829 buffer_add_int (buf, 0);
7838 /* FIXME: Code duplication with icall.c */
7840 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7845 mono_class_setup_interfaces (klass, error);
7846 if (!mono_error_ok (error))
7849 for (i = 0; i < klass->interface_count; i++) {
7850 ic = klass->interfaces [i];
7851 g_hash_table_insert (ifaces, ic, ic);
7853 collect_interfaces (ic, ifaces, error);
7854 if (!mono_error_ok (error))
7860 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7870 case CMD_TYPE_GET_INFO: {
7871 buffer_add_string (buf, klass->name_space);
7872 buffer_add_string (buf, klass->name);
7874 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7875 buffer_add_string (buf, name);
7877 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7878 buffer_add_moduleid (buf, domain, klass->image);
7879 buffer_add_typeid (buf, domain, klass->parent);
7880 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7881 buffer_add_typeid (buf, domain, klass->element_class);
7883 buffer_add_id (buf, 0);
7884 buffer_add_int (buf, klass->type_token);
7885 buffer_add_byte (buf, klass->rank);
7886 buffer_add_int (buf, klass->flags);
7888 type = &klass->byval_arg;
7889 // FIXME: Can't decide whenever a class represents a byref type
7892 if (type->type == MONO_TYPE_PTR)
7894 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7896 if (type->type == MONO_TYPE_VALUETYPE)
7898 if (klass->enumtype)
7900 if (klass->generic_container)
7902 if (klass->generic_container || klass->generic_class)
7904 buffer_add_byte (buf, b);
7907 while ((nested = mono_class_get_nested_types (klass, &iter)))
7909 buffer_add_int (buf, nnested);
7911 while ((nested = mono_class_get_nested_types (klass, &iter)))
7912 buffer_add_typeid (buf, domain, nested);
7913 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7914 if (klass->generic_container)
7915 buffer_add_typeid (buf, domain, klass);
7916 else if (klass->generic_class)
7917 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7919 buffer_add_id (buf, 0);
7921 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7924 if (klass->generic_class) {
7925 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7927 count = inst->type_argc;
7928 buffer_add_int (buf, count);
7929 for (i = 0; i < count; i++)
7930 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7931 } else if (klass->generic_container) {
7932 MonoGenericContainer *container = klass->generic_container;
7935 count = container->type_argc;
7936 buffer_add_int (buf, count);
7937 for (i = 0; i < count; i++) {
7938 pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
7939 buffer_add_typeid (buf, domain, pklass);
7942 buffer_add_int (buf, 0);
7947 case CMD_TYPE_GET_METHODS: {
7950 gpointer iter = NULL;
7953 mono_class_setup_methods (klass);
7955 nmethods = mono_class_num_methods (klass);
7957 buffer_add_int (buf, nmethods);
7959 while ((m = mono_class_get_methods (klass, &iter))) {
7960 buffer_add_methodid (buf, domain, m);
7963 g_assert (i == nmethods);
7966 case CMD_TYPE_GET_FIELDS: {
7969 gpointer iter = NULL;
7972 nfields = mono_class_num_fields (klass);
7974 buffer_add_int (buf, nfields);
7976 while ((f = mono_class_get_fields (klass, &iter))) {
7977 buffer_add_fieldid (buf, domain, f);
7978 buffer_add_string (buf, f->name);
7979 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7980 buffer_add_int (buf, f->type->attrs);
7983 g_assert (i == nfields);
7986 case CMD_TYPE_GET_PROPERTIES: {
7989 gpointer iter = NULL;
7992 nprops = mono_class_num_properties (klass);
7994 buffer_add_int (buf, nprops);
7996 while ((p = mono_class_get_properties (klass, &iter))) {
7997 buffer_add_propertyid (buf, domain, p);
7998 buffer_add_string (buf, p->name);
7999 buffer_add_methodid (buf, domain, p->get);
8000 buffer_add_methodid (buf, domain, p->set);
8001 buffer_add_int (buf, p->attrs);
8004 g_assert (i == nprops);
8007 case CMD_TYPE_GET_CATTRS: {
8008 MonoClass *attr_klass;
8009 MonoCustomAttrInfo *cinfo;
8011 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8012 /* attr_klass can be NULL */
8016 cinfo = mono_custom_attrs_from_class (klass);
8018 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8023 case CMD_TYPE_GET_FIELD_CATTRS: {
8024 MonoClass *attr_klass;
8025 MonoCustomAttrInfo *cinfo;
8026 MonoClassField *field;
8028 field = decode_fieldid (p, &p, end, NULL, &err);
8031 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8035 cinfo = mono_custom_attrs_from_field (klass, field);
8037 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8042 case CMD_TYPE_GET_PROPERTY_CATTRS: {
8043 MonoClass *attr_klass;
8044 MonoCustomAttrInfo *cinfo;
8047 prop = decode_propertyid (p, &p, end, NULL, &err);
8050 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8054 cinfo = mono_custom_attrs_from_property (klass, prop);
8056 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8061 case CMD_TYPE_GET_VALUES:
8062 case CMD_TYPE_GET_VALUES_2: {
8069 MonoThread *thread_obj;
8070 MonoInternalThread *thread = NULL;
8071 guint32 special_static_type;
8073 if (command == CMD_TYPE_GET_VALUES_2) {
8074 int objid = decode_objid (p, &p, end);
8077 err = get_object (objid, (MonoObject**)&thread_obj);
8081 thread = THREAD_TO_INTERNAL (thread_obj);
8084 len = decode_int (p, &p, end);
8085 for (i = 0; i < len; ++i) {
8086 f = decode_fieldid (p, &p, end, NULL, &err);
8090 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8091 return ERR_INVALID_FIELDID;
8092 special_static_type = mono_class_field_get_special_static_type (f);
8093 if (special_static_type != SPECIAL_STATIC_NONE) {
8094 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
8095 return ERR_INVALID_FIELDID;
8098 /* Check that the field belongs to the object */
8100 for (k = klass; k; k = k->parent) {
8101 if (k == f->parent) {
8107 return ERR_INVALID_FIELDID;
8109 vtable = mono_class_vtable (domain, f->parent);
8110 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8111 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
8112 buffer_add_value (buf, f->type, val, domain);
8117 case CMD_TYPE_SET_VALUES: {
8125 len = decode_int (p, &p, end);
8126 for (i = 0; i < len; ++i) {
8127 f = decode_fieldid (p, &p, end, NULL, &err);
8131 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8132 return ERR_INVALID_FIELDID;
8133 if (mono_class_field_is_special_static (f))
8134 return ERR_INVALID_FIELDID;
8136 /* Check that the field belongs to the object */
8138 for (k = klass; k; k = k->parent) {
8139 if (k == f->parent) {
8145 return ERR_INVALID_FIELDID;
8147 // FIXME: Check for literal/const
8149 vtable = mono_class_vtable (domain, f->parent);
8150 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8151 err = decode_value (f->type, domain, val, p, &p, end);
8156 if (MONO_TYPE_IS_REFERENCE (f->type))
8157 mono_field_static_set_value (vtable, f, *(gpointer*)val);
8159 mono_field_static_set_value (vtable, f, val);
8164 case CMD_TYPE_GET_OBJECT: {
8165 MonoObject *o = (MonoObject*)mono_type_get_object (domain, &klass->byval_arg);
8166 buffer_add_objid (buf, o);
8169 case CMD_TYPE_GET_SOURCE_FILES:
8170 case CMD_TYPE_GET_SOURCE_FILES_2: {
8171 char *source_file, *base;
8175 files = get_source_files_for_type (klass);
8177 buffer_add_int (buf, files->len);
8178 for (i = 0; i < files->len; ++i) {
8179 source_file = g_ptr_array_index (files, i);
8180 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8181 buffer_add_string (buf, source_file);
8183 base = g_path_get_basename (source_file);
8184 buffer_add_string (buf, base);
8187 g_free (source_file);
8189 g_ptr_array_free (files, TRUE);
8192 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8193 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8197 if (mono_class_is_assignable_from (klass, oklass))
8198 buffer_add_byte (buf, 1);
8200 buffer_add_byte (buf, 0);
8203 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8204 char *name = decode_string (p, &p, end);
8205 int i, flags = decode_int (p, &p, end);
8206 MonoException *ex = NULL;
8207 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
8210 return ERR_LOADER_ERROR;
8211 buffer_add_int (buf, array->len);
8212 for (i = 0; i < array->len; ++i) {
8213 MonoMethod *method = g_ptr_array_index (array, i);
8214 buffer_add_methodid (buf, domain, method);
8217 g_ptr_array_free (array, TRUE);
8221 case CMD_TYPE_GET_INTERFACES: {
8223 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8225 MonoClass *tclass, *iface;
8226 GHashTableIter iter;
8230 for (parent = tclass; parent; parent = parent->parent) {
8231 mono_class_setup_interfaces (parent, &error);
8232 if (!mono_error_ok (&error))
8233 return ERR_LOADER_ERROR;
8234 collect_interfaces (parent, iface_hash, &error);
8235 if (!mono_error_ok (&error))
8236 return ERR_LOADER_ERROR;
8239 buffer_add_int (buf, g_hash_table_size (iface_hash));
8241 g_hash_table_iter_init (&iter, iface_hash);
8242 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8243 buffer_add_typeid (buf, domain, iface);
8244 g_hash_table_destroy (iface_hash);
8247 case CMD_TYPE_GET_INTERFACE_MAP: {
8248 int tindex, ioffset;
8249 gboolean variance_used;
8251 int len, nmethods, i;
8255 len = decode_int (p, &p, end);
8256 mono_class_setup_vtable (klass);
8258 for (tindex = 0; tindex < len; ++tindex) {
8259 iclass = decode_typeid (p, &p, end, NULL, &err);
8263 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8265 return ERR_INVALID_ARGUMENT;
8267 nmethods = mono_class_num_methods (iclass);
8268 buffer_add_int (buf, nmethods);
8271 while ((method = mono_class_get_methods (iclass, &iter))) {
8272 buffer_add_methodid (buf, domain, method);
8274 for (i = 0; i < nmethods; ++i)
8275 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
8279 case CMD_TYPE_IS_INITIALIZED: {
8280 MonoVTable *vtable = mono_class_vtable (domain, klass);
8283 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8285 buffer_add_int (buf, 0);
8288 case CMD_TYPE_CREATE_INSTANCE: {
8291 obj = mono_object_new (domain, klass);
8292 buffer_add_objid (buf, obj);
8296 return ERR_NOT_IMPLEMENTED;
8303 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8306 MonoDomain *old_domain;
8310 klass = decode_typeid (p, &p, end, &domain, &err);
8314 old_domain = mono_domain_get ();
8316 mono_domain_set (domain, TRUE);
8318 err = type_commands_internal (command, klass, domain, p, end, buf);
8320 mono_domain_set (old_domain, TRUE);
8326 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8328 MonoMethodHeader *header;
8332 case CMD_METHOD_GET_NAME: {
8333 buffer_add_string (buf, method->name);
8336 case CMD_METHOD_GET_DECLARING_TYPE: {
8337 buffer_add_typeid (buf, domain, method->klass);
8340 case CMD_METHOD_GET_DEBUG_INFO: {
8341 MonoDebugMethodInfo *minfo;
8343 int i, j, n_il_offsets;
8346 int *column_numbers;
8347 int *end_line_numbers;
8348 int *end_column_numbers;
8350 GPtrArray *source_file_list;
8352 header = mono_method_get_header (method);
8354 buffer_add_int (buf, 0);
8355 buffer_add_string (buf, "");
8356 buffer_add_int (buf, 0);
8360 minfo = mono_debug_lookup_method (method);
8362 buffer_add_int (buf, header->code_size);
8363 buffer_add_string (buf, "");
8364 buffer_add_int (buf, 0);
8365 mono_metadata_free_mh (header);
8369 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);
8370 buffer_add_int (buf, header->code_size);
8371 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8372 buffer_add_int (buf, source_file_list->len);
8373 for (i = 0; i < source_file_list->len; ++i) {
8374 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
8375 buffer_add_string (buf, sinfo->source_file);
8376 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8377 for (j = 0; j < 16; ++j)
8378 buffer_add_byte (buf, sinfo->hash [j]);
8382 buffer_add_string (buf, source_file);
8384 buffer_add_int (buf, n_il_offsets);
8385 DEBUG (10, fprintf (log_file, "Line number table for method %s:\n", mono_method_full_name (method, TRUE)));
8386 for (i = 0; i < n_il_offsets; ++i) {
8387 const char *srcfile = "";
8389 if (source_files [i] != -1) {
8390 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
8391 srcfile = sinfo->source_file;
8393 DEBUG (10, fprintf (log_file, "IL%x -> %s:%d %d\n", il_offsets [i], srcfile, line_numbers [i], column_numbers ? column_numbers [i] : -1));
8394 buffer_add_int (buf, il_offsets [i]);
8395 buffer_add_int (buf, line_numbers [i]);
8396 if (CHECK_PROTOCOL_VERSION (2, 13))
8397 buffer_add_int (buf, source_files [i]);
8398 if (CHECK_PROTOCOL_VERSION (2, 19))
8399 buffer_add_int (buf, column_numbers ? column_numbers [i] : -1);
8400 if (CHECK_PROTOCOL_VERSION (2, 32)) {
8401 buffer_add_int (buf, end_line_numbers ? end_line_numbers [i] : -1);
8402 buffer_add_int (buf, end_column_numbers ? end_column_numbers [i] : -1);
8405 g_free (source_file);
8406 g_free (il_offsets);
8407 g_free (line_numbers);
8408 g_free (column_numbers);
8409 g_free (end_line_numbers);
8410 g_free (end_column_numbers);
8411 g_free (source_files);
8412 g_ptr_array_free (source_file_list, TRUE);
8413 mono_metadata_free_mh (header);
8416 case CMD_METHOD_GET_PARAM_INFO: {
8417 MonoMethodSignature *sig = mono_method_signature (method);
8421 /* FIXME: mono_class_from_mono_type () and byrefs */
8423 /* FIXME: Use a smaller encoding */
8424 buffer_add_int (buf, sig->call_convention);
8425 buffer_add_int (buf, sig->param_count);
8426 buffer_add_int (buf, sig->generic_param_count);
8427 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
8428 for (i = 0; i < sig->param_count; ++i) {
8430 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
8433 /* Emit parameter names */
8434 names = g_new (char *, sig->param_count);
8435 mono_method_get_param_names (method, (const char **) names);
8436 for (i = 0; i < sig->param_count; ++i)
8437 buffer_add_string (buf, names [i]);
8442 case CMD_METHOD_GET_LOCALS_INFO: {
8443 int i, j, num_locals;
8444 MonoDebugLocalsInfo *locals;
8446 header = mono_method_get_header (method);
8448 return ERR_INVALID_ARGUMENT;
8450 buffer_add_int (buf, header->num_locals);
8453 for (i = 0; i < header->num_locals; ++i)
8454 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
8457 locals = mono_debug_lookup_locals (method);
8459 num_locals = locals->num_locals;
8462 for (i = 0; i < header->num_locals; ++i) {
8463 for (j = 0; j < num_locals; ++j)
8464 if (locals->locals [j].index == i)
8467 buffer_add_string (buf, locals->locals [j].name);
8469 buffer_add_string (buf, "");
8473 for (i = 0; i < header->num_locals; ++i) {
8474 for (j = 0; j < num_locals; ++j)
8475 if (locals->locals [j].index == i)
8477 if (j < num_locals && locals->locals [j].block) {
8478 buffer_add_int (buf, locals->locals [j].block->start_offset);
8479 buffer_add_int (buf, locals->locals [j].block->end_offset);
8481 buffer_add_int (buf, 0);
8482 buffer_add_int (buf, header->code_size);
8485 mono_metadata_free_mh (header);
8488 mono_debug_symfile_free_locals (locals);
8492 case CMD_METHOD_GET_INFO:
8493 buffer_add_int (buf, method->flags);
8494 buffer_add_int (buf, method->iflags);
8495 buffer_add_int (buf, method->token);
8496 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8498 if (method->is_generic)
8500 if (mono_method_signature (method)->generic_param_count)
8502 buffer_add_byte (buf, attrs);
8503 if (method->is_generic || method->is_inflated) {
8506 if (method->is_generic) {
8509 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8511 result = imethod->declaring;
8512 if (imethod->context.class_inst) {
8513 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8514 /*Generic methods gets the context of the GTD.*/
8515 if (mono_class_get_context (klass))
8516 result = mono_class_inflate_generic_method_full (result, klass, mono_class_get_context (klass));
8520 buffer_add_methodid (buf, domain, result);
8522 buffer_add_id (buf, 0);
8524 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8525 if (mono_method_signature (method)->generic_param_count) {
8528 if (method->is_inflated) {
8529 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
8531 count = inst->type_argc;
8532 buffer_add_int (buf, count);
8534 for (i = 0; i < count; i++)
8535 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8537 buffer_add_int (buf, 0);
8539 } else if (method->is_generic) {
8540 MonoGenericContainer *container = mono_method_get_generic_container (method);
8542 count = mono_method_signature (method)->generic_param_count;
8543 buffer_add_int (buf, count);
8544 for (i = 0; i < count; i++) {
8545 MonoGenericParam *param = mono_generic_container_get_param (container, i);
8546 MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
8547 buffer_add_typeid (buf, domain, pklass);
8550 buffer_add_int (buf, 0);
8553 buffer_add_int (buf, 0);
8558 case CMD_METHOD_GET_BODY: {
8561 header = mono_method_get_header (method);
8563 buffer_add_int (buf, 0);
8565 if (CHECK_PROTOCOL_VERSION (2, 18))
8566 buffer_add_int (buf, 0);
8568 buffer_add_int (buf, header->code_size);
8569 for (i = 0; i < header->code_size; ++i)
8570 buffer_add_byte (buf, header->code [i]);
8572 if (CHECK_PROTOCOL_VERSION (2, 18)) {
8573 buffer_add_int (buf, header->num_clauses);
8574 for (i = 0; i < header->num_clauses; ++i) {
8575 MonoExceptionClause *clause = &header->clauses [i];
8577 buffer_add_int (buf, clause->flags);
8578 buffer_add_int (buf, clause->try_offset);
8579 buffer_add_int (buf, clause->try_len);
8580 buffer_add_int (buf, clause->handler_offset);
8581 buffer_add_int (buf, clause->handler_len);
8582 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
8583 buffer_add_typeid (buf, domain, clause->data.catch_class);
8584 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8585 buffer_add_int (buf, clause->data.filter_offset);
8589 mono_metadata_free_mh (header);
8594 case CMD_METHOD_RESOLVE_TOKEN: {
8595 guint32 token = decode_int (p, &p, end);
8598 switch (mono_metadata_token_code (token)) {
8599 case MONO_TOKEN_STRING: {
8603 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
8606 s2 = mono_string_to_utf8 (s);
8608 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8609 buffer_add_string (buf, s2);
8615 MonoClass *handle_class;
8617 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8618 val = mono_method_get_wrapper_data (method, token);
8619 handle_class = mono_method_get_wrapper_data (method, token + 1);
8621 if (handle_class == NULL) {
8622 // Can't figure out the token type
8623 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8627 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
8631 if (handle_class == mono_defaults.typehandle_class) {
8632 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8633 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8634 buffer_add_typeid (buf, domain, (MonoClass *) val);
8636 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
8637 } else if (handle_class == mono_defaults.fieldhandle_class) {
8638 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8639 buffer_add_fieldid (buf, domain, val);
8640 } else if (handle_class == mono_defaults.methodhandle_class) {
8641 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8642 buffer_add_methodid (buf, domain, val);
8643 } else if (handle_class == mono_defaults.string_class) {
8646 s = mono_string_to_utf8 (val);
8647 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8648 buffer_add_string (buf, s);
8651 g_assert_not_reached ();
8658 case CMD_METHOD_GET_CATTRS: {
8659 MonoClass *attr_klass;
8660 MonoCustomAttrInfo *cinfo;
8662 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8663 /* attr_klass can be NULL */
8667 cinfo = mono_custom_attrs_from_method (method);
8669 err = buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
8674 case CMD_METHOD_MAKE_GENERIC_METHOD: {
8675 MonoType **type_argv;
8679 MonoGenericInst *ginst;
8680 MonoGenericContext tmp_context;
8681 MonoMethod *inflated;
8683 type_argc = decode_int (p, &p, end);
8684 type_argv = g_new0 (MonoType*, type_argc);
8685 for (i = 0; i < type_argc; ++i) {
8686 klass = decode_typeid (p, &p, end, &d, &err);
8693 return ERR_INVALID_ARGUMENT;
8695 type_argv [i] = &klass->byval_arg;
8697 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
8699 tmp_context.class_inst = method->klass->generic_class ? method->klass->generic_class->context.class_inst : NULL;
8700 tmp_context.method_inst = ginst;
8702 inflated = mono_class_inflate_generic_method (method, &tmp_context);
8703 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
8704 return ERR_INVALID_ARGUMENT;
8705 buffer_add_methodid (buf, domain, inflated);
8709 return ERR_NOT_IMPLEMENTED;
8716 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8719 MonoDomain *old_domain;
8723 method = decode_methodid (p, &p, end, &domain, &err);
8727 old_domain = mono_domain_get ();
8729 mono_domain_set (domain, TRUE);
8731 err = method_commands_internal (command, method, domain, p, end, buf);
8733 mono_domain_set (old_domain, TRUE);
8739 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8741 int objid = decode_objid (p, &p, end);
8743 MonoThread *thread_obj;
8744 MonoInternalThread *thread;
8746 err = get_object (objid, (MonoObject**)&thread_obj);
8750 thread = THREAD_TO_INTERNAL (thread_obj);
8753 case CMD_THREAD_GET_NAME: {
8755 gunichar2 *s = mono_thread_get_name (thread, &name_len);
8758 buffer_add_int (buf, 0);
8763 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
8765 buffer_add_int (buf, len);
8766 buffer_add_data (buf, (guint8*)name, len);
8771 case CMD_THREAD_GET_FRAME_INFO: {
8772 DebuggerTlsData *tls;
8773 int i, start_frame, length;
8775 // Wait for suspending if it already started
8776 // FIXME: Races with suspend_count
8777 while (!is_suspended ()) {
8779 wait_for_suspend ();
8783 wait_for_suspend ();
8784 if (!is_suspended ())
8785 return ERR_NOT_SUSPENDED;
8788 start_frame = decode_int (p, &p, end);
8789 length = decode_int (p, &p, end);
8791 if (start_frame != 0 || length != -1)
8792 return ERR_NOT_IMPLEMENTED;
8794 mono_loader_lock ();
8795 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8796 mono_loader_unlock ();
8799 compute_frame_info (thread, tls);
8801 buffer_add_int (buf, tls->frame_count);
8802 for (i = 0; i < tls->frame_count; ++i) {
8803 buffer_add_int (buf, tls->frames [i]->id);
8804 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
8805 buffer_add_int (buf, tls->frames [i]->il_offset);
8807 * Instead of passing the frame type directly to the client, we associate
8808 * it with the previous frame using a set of flags. This avoids lots of
8809 * conditional code in the client, since a frame whose type isn't
8810 * FRAME_TYPE_MANAGED has no method, location, etc.
8812 buffer_add_byte (buf, tls->frames [i]->flags);
8817 case CMD_THREAD_GET_STATE:
8818 buffer_add_int (buf, thread->state);
8820 case CMD_THREAD_GET_INFO:
8821 buffer_add_byte (buf, thread->threadpool_thread);
8823 case CMD_THREAD_GET_ID:
8824 buffer_add_long (buf, (guint64)(gsize)thread);
8826 case CMD_THREAD_GET_TID:
8827 buffer_add_long (buf, (guint64)thread->tid);
8829 case CMD_THREAD_SET_IP: {
8830 DebuggerTlsData *tls;
8833 MonoSeqPointInfo *seq_points;
8834 SeqPoint *sp = NULL;
8838 method = decode_methodid (p, &p, end, &domain, &err);
8841 il_offset = decode_long (p, &p, end);
8843 while (!is_suspended ()) {
8845 wait_for_suspend ();
8848 mono_loader_lock ();
8849 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8850 mono_loader_unlock ();
8853 compute_frame_info (thread, tls);
8854 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
8855 return ERR_INVALID_ARGUMENT;
8857 seq_points = get_seq_points (domain, method);
8858 g_assert (seq_points);
8860 for (i = 0; i < seq_points->len; ++i) {
8861 sp = &seq_points->seq_points [i];
8863 if (sp->il_offset == il_offset)
8866 if (i == seq_points->len)
8867 return ERR_INVALID_ARGUMENT;
8869 // FIXME: Check that the ip change is safe
8871 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));
8872 MONO_CONTEXT_SET_IP (&tls->restore_ctx, (guint8*)tls->frames [0]->ji->code_start + sp->native_offset);
8876 return ERR_NOT_IMPLEMENTED;
8883 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8887 MonoThread *thread_obj;
8888 MonoInternalThread *thread;
8889 int pos, i, len, frame_idx;
8890 DebuggerTlsData *tls;
8892 MonoDebugMethodJitInfo *jit;
8893 MonoDebugVarInfo *var;
8894 MonoMethodSignature *sig;
8896 MonoMethodHeader *header;
8898 objid = decode_objid (p, &p, end);
8899 err = get_object (objid, (MonoObject**)&thread_obj);
8903 thread = THREAD_TO_INTERNAL (thread_obj);
8905 id = decode_id (p, &p, end);
8907 mono_loader_lock ();
8908 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8909 mono_loader_unlock ();
8912 for (i = 0; i < tls->frame_count; ++i) {
8913 if (tls->frames [i]->id == id)
8916 if (i == tls->frame_count)
8917 return ERR_INVALID_FRAMEID;
8920 frame = tls->frames [frame_idx];
8922 if (!frame->has_ctx)
8923 return ERR_ABSENT_INFORMATION;
8926 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
8927 if (!frame->jit && frame->api_method->is_inflated)
8928 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
8932 /* This could happen for aot images with no jit debug info */
8933 s = mono_method_full_name (frame->api_method, TRUE);
8934 DEBUG (1, fprintf (log_file, "[dbg] No debug information found for '%s'.\n", s));
8936 return ERR_ABSENT_INFORMATION;
8941 sig = mono_method_signature (frame->actual_method);
8943 if (!get_seq_points (frame->domain, frame->actual_method))
8945 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
8947 return ERR_ABSENT_INFORMATION;
8950 case CMD_STACK_FRAME_GET_VALUES: {
8951 len = decode_int (p, &p, end);
8952 header = mono_method_get_header (frame->actual_method);
8954 for (i = 0; i < len; ++i) {
8955 pos = decode_int (p, &p, end);
8960 g_assert (pos >= 0 && pos < jit->num_params);
8962 var = &jit->params [pos];
8964 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
8966 g_assert (pos >= 0 && pos < jit->num_locals);
8968 var = &jit->locals [pos];
8970 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
8973 mono_metadata_free_mh (header);
8976 case CMD_STACK_FRAME_GET_THIS: {
8977 if (frame->api_method->klass->valuetype) {
8978 if (!sig->hasthis) {
8979 MonoObject *p = NULL;
8980 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
8982 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8985 if (!sig->hasthis) {
8986 MonoObject *p = NULL;
8987 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
8989 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8994 case CMD_STACK_FRAME_SET_VALUES: {
8997 MonoDebugVarInfo *var;
8999 len = decode_int (p, &p, end);
9000 header = mono_method_get_header (frame->actual_method);
9002 for (i = 0; i < len; ++i) {
9003 pos = decode_int (p, &p, end);
9008 g_assert (pos >= 0 && pos < jit->num_params);
9010 t = sig->params [pos];
9011 var = &jit->params [pos];
9013 g_assert (pos >= 0 && pos < jit->num_locals);
9015 t = header->locals [pos];
9016 var = &jit->locals [pos];
9019 if (MONO_TYPE_IS_REFERENCE (t))
9020 val_buf = g_alloca (sizeof (MonoObject*));
9022 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9023 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9027 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_ctx);
9029 mono_metadata_free_mh (header);
9033 return ERR_NOT_IMPLEMENTED;
9040 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9043 int objid, err, index, len, i, esize;
9046 objid = decode_objid (p, &p, end);
9047 err = get_object (objid, (MonoObject**)&arr);
9052 case CMD_ARRAY_REF_GET_LENGTH:
9053 buffer_add_int (buf, arr->obj.vtable->klass->rank);
9055 buffer_add_int (buf, arr->max_length);
9056 buffer_add_int (buf, 0);
9058 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
9059 buffer_add_int (buf, arr->bounds [i].length);
9060 buffer_add_int (buf, arr->bounds [i].lower_bound);
9064 case CMD_ARRAY_REF_GET_VALUES:
9065 index = decode_int (p, &p, end);
9066 len = decode_int (p, &p, end);
9068 g_assert (index >= 0 && len >= 0);
9069 // Reordered to avoid integer overflow
9070 g_assert (!(index > arr->max_length - len));
9072 esize = mono_array_element_size (arr->obj.vtable->klass);
9073 for (i = index; i < index + len; ++i) {
9074 elem = (gpointer*)((char*)arr->vector + (i * esize));
9075 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
9078 case CMD_ARRAY_REF_SET_VALUES:
9079 index = decode_int (p, &p, end);
9080 len = decode_int (p, &p, end);
9082 g_assert (index >= 0 && len >= 0);
9083 // Reordered to avoid integer overflow
9084 g_assert (!(index > arr->max_length - len));
9086 esize = mono_array_element_size (arr->obj.vtable->klass);
9087 for (i = index; i < index + len; ++i) {
9088 elem = (gpointer*)((char*)arr->vector + (i * esize));
9090 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
9094 return ERR_NOT_IMPLEMENTED;
9101 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9106 int i, index, length;
9109 objid = decode_objid (p, &p, end);
9110 err = get_object (objid, (MonoObject**)&str);
9115 case CMD_STRING_REF_GET_VALUE:
9116 s = mono_string_to_utf8 (str);
9117 buffer_add_string (buf, s);
9120 case CMD_STRING_REF_GET_LENGTH:
9121 buffer_add_long (buf, mono_string_length (str));
9123 case CMD_STRING_REF_GET_CHARS:
9124 index = decode_long (p, &p, end);
9125 length = decode_long (p, &p, end);
9126 if (index > mono_string_length (str) - length)
9127 return ERR_INVALID_ARGUMENT;
9128 c = mono_string_chars (str) + index;
9129 for (i = 0; i < length; ++i)
9130 buffer_add_short (buf, c [i]);
9133 return ERR_NOT_IMPLEMENTED;
9140 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9149 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9150 objid = decode_objid (p, &p, end);
9151 err = get_object (objid, &obj);
9153 buffer_add_int (buf, 1);
9155 buffer_add_int (buf, 0);
9159 objid = decode_objid (p, &p, end);
9160 err = get_object (objid, &obj);
9165 case CMD_OBJECT_REF_GET_TYPE:
9166 /* This handles transparent proxies too */
9167 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9169 case CMD_OBJECT_REF_GET_VALUES:
9170 len = decode_int (p, &p, end);
9172 for (i = 0; i < len; ++i) {
9173 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9177 /* Check that the field belongs to the object */
9179 for (k = obj->vtable->klass; k; k = k->parent) {
9180 if (k == f->parent) {
9186 return ERR_INVALID_FIELDID;
9188 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9192 if (mono_class_field_is_special_static (f))
9193 return ERR_INVALID_FIELDID;
9195 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9196 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9197 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9198 mono_field_static_get_value (vtable, f, val);
9199 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9202 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
9206 case CMD_OBJECT_REF_SET_VALUES:
9207 len = decode_int (p, &p, end);
9209 for (i = 0; i < len; ++i) {
9210 f = decode_fieldid (p, &p, end, NULL, &err);
9214 /* Check that the field belongs to the object */
9216 for (k = obj->vtable->klass; k; k = k->parent) {
9217 if (k == f->parent) {
9223 return ERR_INVALID_FIELDID;
9225 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9229 if (mono_class_field_is_special_static (f))
9230 return ERR_INVALID_FIELDID;
9232 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9233 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9235 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9236 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
9241 mono_field_static_set_value (vtable, f, val);
9244 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
9250 case CMD_OBJECT_REF_GET_ADDRESS:
9251 buffer_add_long (buf, (gssize)obj);
9253 case CMD_OBJECT_REF_GET_DOMAIN:
9254 buffer_add_domainid (buf, obj->vtable->domain);
9256 case CMD_OBJECT_REF_GET_INFO:
9257 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9258 buffer_add_domainid (buf, obj->vtable->domain);
9261 return ERR_NOT_IMPLEMENTED;
9268 command_set_to_string (CommandSet command_set)
9270 switch (command_set) {
9273 case CMD_SET_OBJECT_REF:
9274 return "OBJECT_REF";
9275 case CMD_SET_STRING_REF:
9276 return "STRING_REF";
9277 case CMD_SET_THREAD:
9279 case CMD_SET_ARRAY_REF:
9281 case CMD_SET_EVENT_REQUEST:
9282 return "EVENT_REQUEST";
9283 case CMD_SET_STACK_FRAME:
9284 return "STACK_FRAME";
9285 case CMD_SET_APPDOMAIN:
9287 case CMD_SET_ASSEMBLY:
9289 case CMD_SET_METHOD:
9293 case CMD_SET_MODULE:
9304 static const char* vm_cmds_str [] = {
9312 "SET_PROTOCOL_VERSION",
9315 "GET_TYPES_FOR_SOURCE_FILE",
9320 static const char* thread_cmds_str[] = {
9330 static const char* event_cmds_str[] = {
9333 "REQUEST_CLEAR_ALL_BREAKPOINTS"
9336 static const char* appdomain_cmds_str[] = {
9338 "GET_FRIENDLY_NAME",
9340 "GET_ENTRY_ASSEMBLY",
9343 "CREATE_BOXED_VALUE"
9346 static const char* assembly_cmds_str[] = {
9349 "GET_MANIFEST_MODULE",
9355 static const char* module_cmds_str[] = {
9359 static const char* field_cmds_str[] = {
9363 static const char* method_cmds_str[] = {
9365 "GET_DECLARING_TYPE",
9373 "MAKE_GENERIC_METHOD"
9376 static const char* type_cmds_str[] = {
9384 "IS_ASSIGNABLE_FROM",
9388 "GET_PROPERTY_CATTRS",
9389 "GET_SOURCE_FILES_2",
9391 "GET_METHODS_BY_NAME_FLAGS",
9393 "GET_INTERFACE_MAP",
9397 static const char* stack_frame_cmds_str[] = {
9403 static const char* array_cmds_str[] = {
9409 static const char* string_cmds_str[] = {
9415 static const char* object_cmds_str[] = {
9426 cmd_to_string (CommandSet set, int command)
9434 cmds_len = G_N_ELEMENTS (vm_cmds_str);
9436 case CMD_SET_OBJECT_REF:
9437 cmds = object_cmds_str;
9438 cmds_len = G_N_ELEMENTS (object_cmds_str);
9440 case CMD_SET_STRING_REF:
9441 cmds = string_cmds_str;
9442 cmds_len = G_N_ELEMENTS (string_cmds_str);
9444 case CMD_SET_THREAD:
9445 cmds = thread_cmds_str;
9446 cmds_len = G_N_ELEMENTS (thread_cmds_str);
9448 case CMD_SET_ARRAY_REF:
9449 cmds = array_cmds_str;
9450 cmds_len = G_N_ELEMENTS (array_cmds_str);
9452 case CMD_SET_EVENT_REQUEST:
9453 cmds = event_cmds_str;
9454 cmds_len = G_N_ELEMENTS (event_cmds_str);
9456 case CMD_SET_STACK_FRAME:
9457 cmds = stack_frame_cmds_str;
9458 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
9460 case CMD_SET_APPDOMAIN:
9461 cmds = appdomain_cmds_str;
9462 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
9464 case CMD_SET_ASSEMBLY:
9465 cmds = assembly_cmds_str;
9466 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
9468 case CMD_SET_METHOD:
9469 cmds = method_cmds_str;
9470 cmds_len = G_N_ELEMENTS (method_cmds_str);
9473 cmds = type_cmds_str;
9474 cmds_len = G_N_ELEMENTS (type_cmds_str);
9476 case CMD_SET_MODULE:
9477 cmds = module_cmds_str;
9478 cmds_len = G_N_ELEMENTS (module_cmds_str);
9481 cmds = field_cmds_str;
9482 cmds_len = G_N_ELEMENTS (field_cmds_str);
9485 cmds = event_cmds_str;
9486 cmds_len = G_N_ELEMENTS (event_cmds_str);
9491 if (command > 0 && command <= cmds_len)
9492 return cmds [command - 1];
9498 wait_for_attach (void)
9500 #ifndef DISABLE_SOCKET_TRANSPORT
9501 if (listen_fd == -1) {
9502 DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
9506 /* Block and wait for client connection */
9507 conn_fd = socket_transport_accept (listen_fd);
9508 DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
9509 if (conn_fd == -1) {
9510 DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
9514 g_assert_not_reached ();
9518 disconnected = !transport_handshake ();
9520 DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
9530 * This thread handles communication with the debugger client using a JDWP
9533 static guint32 WINAPI
9534 debugger_thread (void *arg)
9536 int res, len, id, flags, command_set = 0, command = 0;
9537 guint8 header [HEADER_LENGTH];
9538 guint8 *data, *p, *end;
9542 gboolean attach_failed = FALSE;
9544 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
9546 debugger_thread_id = GetCurrentThreadId ();
9548 mono_jit_thread_attach (mono_get_root_domain ());
9550 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
9552 mono_set_is_debugger_attached (TRUE);
9554 if (agent_config.defer) {
9555 if (!wait_for_attach ()) {
9556 DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
9557 attach_failed = TRUE; // Don't abort process when we can't listen
9559 /* Send start event to client */
9560 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
9564 while (!attach_failed) {
9565 res = transport_recv (header, HEADER_LENGTH);
9567 /* This will break if the socket is closed during shutdown too */
9568 if (res != HEADER_LENGTH) {
9569 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH));
9574 end = header + HEADER_LENGTH;
9576 len = decode_int (p, &p, end);
9577 id = decode_int (p, &p, end);
9578 flags = decode_byte (p, &p, end);
9579 command_set = decode_byte (p, &p, end);
9580 command = decode_byte (p, &p, end);
9582 g_assert (flags == 0);
9585 const char *cmd_str;
9588 cmd_str = cmd_to_string (command_set, command);
9590 sprintf (cmd_num, "%d", command);
9594 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));
9597 data = g_malloc (len - HEADER_LENGTH);
9598 if (len - HEADER_LENGTH > 0)
9600 res = transport_recv (data, len - HEADER_LENGTH);
9601 if (res != len - HEADER_LENGTH) {
9602 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH));
9608 end = data + (len - HEADER_LENGTH);
9610 buffer_init (&buf, 128);
9615 /* Process the request */
9616 switch (command_set) {
9618 err = vm_commands (command, id, p, end, &buf);
9619 if (!err && command == CMD_VM_INVOKE_METHOD)
9620 /* Sent after the invoke is complete */
9623 case CMD_SET_EVENT_REQUEST:
9624 err = event_commands (command, p, end, &buf);
9626 case CMD_SET_APPDOMAIN:
9627 err = domain_commands (command, p, end, &buf);
9629 case CMD_SET_ASSEMBLY:
9630 err = assembly_commands (command, p, end, &buf);
9632 case CMD_SET_MODULE:
9633 err = module_commands (command, p, end, &buf);
9636 err = field_commands (command, p, end, &buf);
9639 err = type_commands (command, p, end, &buf);
9641 case CMD_SET_METHOD:
9642 err = method_commands (command, p, end, &buf);
9644 case CMD_SET_THREAD:
9645 err = thread_commands (command, p, end, &buf);
9647 case CMD_SET_STACK_FRAME:
9648 err = frame_commands (command, p, end, &buf);
9650 case CMD_SET_ARRAY_REF:
9651 err = array_commands (command, p, end, &buf);
9653 case CMD_SET_STRING_REF:
9654 err = string_commands (command, p, end, &buf);
9656 case CMD_SET_OBJECT_REF:
9657 err = object_commands (command, p, end, &buf);
9660 err = ERR_NOT_IMPLEMENTED;
9663 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
9664 buffer_replies = TRUE;
9668 if (buffer_replies) {
9669 buffer_reply_packet (id, err, &buf);
9671 send_reply_packet (id, err, &buf);
9672 //DEBUG (1, fprintf (log_file, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000));
9676 if (!err && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
9677 send_buffered_reply_packets ();
9678 buffer_replies = FALSE;
9684 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
9688 mono_set_is_debugger_attached (FALSE);
9690 mono_mutex_lock (&debugger_thread_exited_mutex);
9691 debugger_thread_exited = TRUE;
9692 mono_cond_signal (&debugger_thread_exited_cond);
9693 mono_mutex_unlock (&debugger_thread_exited_mutex);
9695 DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
9697 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
9698 DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
9699 start_debugger_thread ();
9705 #else /* DISABLE_DEBUGGER_AGENT */
9708 mono_debugger_agent_parse_options (char *options)
9710 g_error ("This runtime is configured with the debugger agent disabled.");
9714 mono_debugger_agent_init (void)
9719 mono_debugger_agent_breakpoint_hit (void *sigctx)
9724 mono_debugger_agent_single_step_event (void *sigctx)
9729 mono_debugger_agent_free_domain_info (MonoDomain *domain)
9734 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
9740 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
9741 MonoContext *catch_ctx)
9746 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9751 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9756 mono_debugger_agent_user_break (void)
9762 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
9767 mono_debugger_agent_debug_log_is_enabled (void)
9773 mono_debugger_agent_unhandled_exception (MonoException *exc)
9775 g_assert_not_reached ();