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 34
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
408 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
409 } BindingFlagsExtensions;
413 CMD_VM_ALL_THREADS = 2,
418 CMD_VM_INVOKE_METHOD = 7,
419 CMD_VM_SET_PROTOCOL_VERSION = 8,
420 CMD_VM_ABORT_INVOKE = 9,
421 CMD_VM_SET_KEEPALIVE = 10,
422 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
423 CMD_VM_GET_TYPES = 12,
424 CMD_VM_INVOKE_METHODS = 13,
425 CMD_VM_START_BUFFERING = 14,
426 CMD_VM_STOP_BUFFERING = 15
430 CMD_THREAD_GET_FRAME_INFO = 1,
431 CMD_THREAD_GET_NAME = 2,
432 CMD_THREAD_GET_STATE = 3,
433 CMD_THREAD_GET_INFO = 4,
434 CMD_THREAD_GET_ID = 5,
435 CMD_THREAD_GET_TID = 6,
436 CMD_THREAD_SET_IP = 7
440 CMD_EVENT_REQUEST_SET = 1,
441 CMD_EVENT_REQUEST_CLEAR = 2,
442 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
450 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
451 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
452 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
453 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
454 CMD_APPDOMAIN_CREATE_STRING = 5,
455 CMD_APPDOMAIN_GET_CORLIB = 6,
456 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
460 CMD_ASSEMBLY_GET_LOCATION = 1,
461 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
462 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
463 CMD_ASSEMBLY_GET_OBJECT = 4,
464 CMD_ASSEMBLY_GET_TYPE = 5,
465 CMD_ASSEMBLY_GET_NAME = 6
469 CMD_MODULE_GET_INFO = 1,
473 CMD_FIELD_GET_INFO = 1,
477 CMD_METHOD_GET_NAME = 1,
478 CMD_METHOD_GET_DECLARING_TYPE = 2,
479 CMD_METHOD_GET_DEBUG_INFO = 3,
480 CMD_METHOD_GET_PARAM_INFO = 4,
481 CMD_METHOD_GET_LOCALS_INFO = 5,
482 CMD_METHOD_GET_INFO = 6,
483 CMD_METHOD_GET_BODY = 7,
484 CMD_METHOD_RESOLVE_TOKEN = 8,
485 CMD_METHOD_GET_CATTRS = 9,
486 CMD_METHOD_MAKE_GENERIC_METHOD = 10
490 CMD_TYPE_GET_INFO = 1,
491 CMD_TYPE_GET_METHODS = 2,
492 CMD_TYPE_GET_FIELDS = 3,
493 CMD_TYPE_GET_VALUES = 4,
494 CMD_TYPE_GET_OBJECT = 5,
495 CMD_TYPE_GET_SOURCE_FILES = 6,
496 CMD_TYPE_SET_VALUES = 7,
497 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
498 CMD_TYPE_GET_PROPERTIES = 9,
499 CMD_TYPE_GET_CATTRS = 10,
500 CMD_TYPE_GET_FIELD_CATTRS = 11,
501 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
502 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
503 CMD_TYPE_GET_VALUES_2 = 14,
504 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
505 CMD_TYPE_GET_INTERFACES = 16,
506 CMD_TYPE_GET_INTERFACE_MAP = 17,
507 CMD_TYPE_IS_INITIALIZED = 18,
508 CMD_TYPE_CREATE_INSTANCE = 19
512 CMD_STACK_FRAME_GET_VALUES = 1,
513 CMD_STACK_FRAME_GET_THIS = 2,
514 CMD_STACK_FRAME_SET_VALUES = 3
518 CMD_ARRAY_REF_GET_LENGTH = 1,
519 CMD_ARRAY_REF_GET_VALUES = 2,
520 CMD_ARRAY_REF_SET_VALUES = 3,
524 CMD_STRING_REF_GET_VALUE = 1,
525 CMD_STRING_REF_GET_LENGTH = 2,
526 CMD_STRING_REF_GET_CHARS = 3
530 CMD_OBJECT_REF_GET_TYPE = 1,
531 CMD_OBJECT_REF_GET_VALUES = 2,
532 CMD_OBJECT_REF_IS_COLLECTED = 3,
533 CMD_OBJECT_REF_GET_ADDRESS = 4,
534 CMD_OBJECT_REF_GET_DOMAIN = 5,
535 CMD_OBJECT_REF_SET_VALUES = 6,
536 CMD_OBJECT_REF_GET_INFO = 7,
542 int count; /* For kind == MOD_KIND_COUNT */
543 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
544 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
545 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
546 GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
547 GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
548 StepFilter filter; /* For kind == MOD_KIND_STEP */
550 gboolean caught, uncaught, subclasses; /* For kind == MOD_KIND_EXCEPTION_ONLY */
559 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
563 * Describes a single step request.
567 MonoInternalThread *thread;
573 MonoMethod *last_method;
575 /* Whenever single stepping is performed using start/stop_single_stepping () */
577 /* The list of breakpoints used to implement step-over */
579 /* The number of frames at the start of a step-over */
584 * Contains additional information for an event
587 /* For EVENT_KIND_EXCEPTION */
589 MonoContext catch_ctx;
591 /* For EVENT_KIND_USER_LOG */
593 char *category, *message;
594 /* For EVENT_KIND_TYPE_LOAD */
598 /* Dummy structure used for the profiler callbacks */
604 guint8 *buf, *p, *end;
607 typedef struct ReplyPacket {
613 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
616 #define get_last_sock_error() WSAGetLastError()
617 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
618 #define MONO_EINTR WSAEINTR
620 #define get_last_sock_error() errno
621 #define MONO_EWOULDBLOCK EWOULDBLOCK
622 #define MONO_EINTR EINTR
625 #define CHECK_PROTOCOL_VERSION(major,minor) \
626 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
632 static AgentConfig agent_config;
635 * Whenever the agent is fully initialized.
636 * When using the onuncaught or onthrow options, only some parts of the agent are
637 * initialized on startup, and the full initialization which includes connection
638 * establishment and the startup of the agent thread is only done in response to
641 static gint32 inited;
643 #ifndef DISABLE_SOCKET_TRANSPORT
645 static int listen_fd;
648 static int packet_id = 0;
650 static int objref_id = 0;
652 static int event_request_id = 0;
654 static int frame_id = 0;
656 static GPtrArray *event_requests;
658 static MonoNativeTlsKey debugger_tls_id;
660 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
662 /* Maps MonoInternalThread -> DebuggerTlsData */
663 static MonoGHashTable *thread_to_tls;
665 /* Maps tid -> MonoInternalThread */
666 static MonoGHashTable *tid_to_thread;
668 /* Maps tid -> MonoThread (not MonoInternalThread) */
669 static MonoGHashTable *tid_to_thread_obj;
671 static gsize debugger_thread_id;
673 static HANDLE debugger_thread_handle;
675 static int log_level;
677 static gboolean embedding;
679 static FILE *log_file;
681 /* Assemblies whose assembly load event has no been sent yet */
682 /* Protected by the dbg lock */
683 static GPtrArray *pending_assembly_loads;
685 /* Whenever the debugger thread has exited */
686 static gboolean debugger_thread_exited;
688 /* Cond variable used to wait for debugger_thread_exited becoming true */
689 static mono_cond_t debugger_thread_exited_cond;
691 /* Mutex for the cond var above */
692 static mono_mutex_t debugger_thread_exited_mutex;
694 static DebuggerProfiler debugger_profiler;
696 /* The single step request instance */
697 static SingleStepReq *ss_req = NULL;
698 static gpointer ss_invoke_addr = NULL;
700 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
701 /* Number of single stepping operations in progress */
705 /* The protocol version of the client */
706 static int major_version, minor_version;
708 /* Whenever the variables above are set by the client */
709 static gboolean protocol_version_set;
711 /* A hash table containing all active domains */
712 static GHashTable *domains;
714 /* The number of times the runtime is suspended */
715 static gint32 suspend_count;
717 /* Whenever to buffer reply messages and send them together */
718 static gboolean buffer_replies;
720 /* Buffered reply packets */
721 static ReplyPacket reply_packets [128];
724 #define dbg_lock() EnterCriticalSection (&debug_mutex)
725 #define dbg_unlock() LeaveCriticalSection (&debug_mutex)
726 static CRITICAL_SECTION debug_mutex;
728 static void transport_init (void);
729 static void transport_connect (const char *address);
730 static gboolean transport_handshake (void);
731 static void register_transport (DebuggerTransport *trans);
733 static guint32 WINAPI debugger_thread (void *arg);
735 static void runtime_initialized (MonoProfiler *prof);
737 static void runtime_shutdown (MonoProfiler *prof);
739 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
741 static void thread_end (MonoProfiler *prof, uintptr_t tid);
743 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
745 static void appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain);
747 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
749 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
751 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
753 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
755 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
757 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
759 static void emit_assembly_load (gpointer assembly, gpointer user_data);
761 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
763 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
765 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
767 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
769 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
771 static void start_single_stepping (void);
773 static void stop_single_stepping (void);
775 static void suspend_current (void);
777 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
779 static void clear_types_for_assembly (MonoAssembly *assembly);
781 static void clear_breakpoints_for_domain (MonoDomain *domain);
783 static void process_profiler_event (EventKind event, gpointer arg);
785 /* Submodule init/cleanup */
786 static void breakpoints_init (void);
787 static void breakpoints_cleanup (void);
789 static void objrefs_init (void);
790 static void objrefs_cleanup (void);
792 static void ids_init (void);
793 static void ids_cleanup (void);
795 static void suspend_init (void);
797 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch);
798 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
799 static void ss_destroy (SingleStepReq *req);
801 static void start_debugger_thread (void);
802 static void stop_debugger_thread (void);
804 static void finish_agent_init (gboolean on_startup);
806 static void process_profiler_event (EventKind event, gpointer arg);
808 static void invalidate_frames (DebuggerTlsData *tls);
810 #ifndef DISABLE_SOCKET_TRANSPORT
812 register_socket_transport (void);
816 parse_address (char *address, char **host, int *port)
818 char *pos = strchr (address, ':');
820 if (pos == NULL || pos == address)
823 *host = g_malloc (pos - address + 1);
824 strncpy (*host, address, pos - address);
825 (*host) [pos - address] = '\0';
827 *port = atoi (pos + 1);
835 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
836 fprintf (stderr, "Available options:\n");
837 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
838 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
839 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
840 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
841 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
842 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
843 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
844 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
845 fprintf (stderr, " setpgid=y/n\t\t\tWhether to call setpid(0, 0) after startup.\n");
846 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
850 parse_flag (const char *option, char *flag)
852 if (!strcmp (flag, "y"))
854 else if (!strcmp (flag, "n"))
857 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
864 mono_debugger_agent_parse_options (char *options)
871 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
872 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
876 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
878 options = g_strdup_printf ("%s,%s", options, extra);
880 agent_config.enabled = TRUE;
881 agent_config.suspend = TRUE;
882 agent_config.server = FALSE;
883 agent_config.defer = FALSE;
884 agent_config.address = NULL;
886 //agent_config.log_level = 10;
888 args = g_strsplit (options, ",", -1);
889 for (ptr = args; ptr && *ptr; ptr ++) {
892 if (strncmp (arg, "transport=", 10) == 0) {
893 agent_config.transport = g_strdup (arg + 10);
894 } else if (strncmp (arg, "address=", 8) == 0) {
895 agent_config.address = g_strdup (arg + 8);
896 } else if (strncmp (arg, "loglevel=", 9) == 0) {
897 agent_config.log_level = atoi (arg + 9);
898 } else if (strncmp (arg, "logfile=", 8) == 0) {
899 agent_config.log_file = g_strdup (arg + 8);
900 } else if (strncmp (arg, "suspend=", 8) == 0) {
901 agent_config.suspend = parse_flag ("suspend", arg + 8);
902 } else if (strncmp (arg, "server=", 7) == 0) {
903 agent_config.server = parse_flag ("server", arg + 7);
904 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
905 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
906 } else if (strncmp (arg, "onthrow=", 8) == 0) {
907 /* We support multiple onthrow= options */
908 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
909 } else if (strncmp (arg, "onthrow", 7) == 0) {
910 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
911 } else if (strncmp (arg, "help", 4) == 0) {
914 } else if (strncmp (arg, "timeout=", 8) == 0) {
915 agent_config.timeout = atoi (arg + 8);
916 } else if (strncmp (arg, "launch=", 7) == 0) {
917 agent_config.launch = g_strdup (arg + 7);
918 } else if (strncmp (arg, "embedding=", 10) == 0) {
919 agent_config.embedding = atoi (arg + 10) == 1;
920 } else if (strncmp (arg, "keepalive=", 10) == 0) {
921 agent_config.keepalive = atoi (arg + 10);
922 } else if (strncmp (arg, "setpgid=", 8) == 0) {
923 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
930 if (agent_config.server && !agent_config.suspend) {
931 /* Waiting for deferred attachment */
932 agent_config.defer = TRUE;
933 if (agent_config.address == NULL) {
934 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (getpid () % 1000));
938 //agent_config.log_level = 0;
940 if (agent_config.transport == NULL) {
941 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
945 if (agent_config.address == NULL && !agent_config.server) {
946 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
951 if (!strcmp (agent_config.transport, "dt_socket")) {
952 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
953 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
960 mono_debugger_agent_init (void)
962 InitializeCriticalSection (&debug_mutex);
964 if (!agent_config.enabled)
969 /* Need to know whenever a thread has acquired the loader mutex */
970 mono_loader_lock_track_ownership (TRUE);
972 event_requests = g_ptr_array_new ();
974 mono_mutex_init (&debugger_thread_exited_mutex);
975 mono_cond_init (&debugger_thread_exited_cond, NULL);
977 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
978 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
979 mono_profiler_install_runtime_initialized (runtime_initialized);
980 mono_profiler_install_appdomain (NULL, appdomain_load, appdomain_start_unload, appdomain_unload);
981 mono_profiler_install_thread (thread_startup, thread_end);
982 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
983 mono_profiler_install_jit_end (jit_end);
984 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
986 mono_native_tls_alloc (&debugger_tls_id, NULL);
988 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
989 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls);
991 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
992 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread);
994 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
995 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj);
997 pending_assembly_loads = g_ptr_array_new ();
998 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
1000 log_level = agent_config.log_level;
1002 embedding = agent_config.embedding;
1003 disconnected = TRUE;
1005 if (agent_config.log_file) {
1006 log_file = fopen (agent_config.log_file, "w+");
1008 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
1017 breakpoints_init ();
1020 mini_get_debug_options ()->gen_seq_points = TRUE;
1022 * This is needed because currently we don't handle liveness info.
1024 mini_get_debug_options ()->mdb_optimizations = TRUE;
1026 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
1027 /* This is needed because we can't set local variables in registers yet */
1028 mono_disable_optimizations (MONO_OPT_LINEARS);
1032 * The stack walk done from thread_interrupt () needs to be signal safe, but it
1033 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
1034 * safe (#3411). So load AOT info eagerly when the debugger is running as a
1037 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
1040 if (agent_config.setpgid)
1044 if (!agent_config.onuncaught && !agent_config.onthrow)
1045 finish_agent_init (TRUE);
1049 * finish_agent_init:
1051 * Finish the initialization of the agent. This involves connecting the transport
1052 * and starting the agent thread. This is either done at startup, or
1053 * in response to some event like an unhandled exception.
1056 finish_agent_init (gboolean on_startup)
1060 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
1063 if (agent_config.launch) {
1066 // FIXME: Generated address
1067 // FIXME: Races with transport_connect ()
1069 argv [0] = agent_config.launch;
1070 argv [1] = agent_config.transport;
1071 argv [2] = agent_config.address;
1074 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1076 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1081 transport_connect (agent_config.address);
1084 /* Do some which is usually done after sending the VMStart () event */
1085 vm_start_event_sent = TRUE;
1086 start_debugger_thread ();
1091 mono_debugger_agent_cleanup (void)
1096 stop_debugger_thread ();
1098 breakpoints_cleanup ();
1102 mono_mutex_destroy (&debugger_thread_exited_mutex);
1103 mono_cond_destroy (&debugger_thread_exited_cond);
1110 #ifndef DISABLE_SOCKET_TRANSPORT
1115 * recv() + handle incomplete reads and EINTR
1118 socket_transport_recv (void *buf, int len)
1124 static gint32 last_keepalive;
1129 res = recv (fd, (char *) buf + total, len - total, flags);
1132 if (agent_config.keepalive) {
1133 gboolean need_keepalive = FALSE;
1134 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1135 need_keepalive = TRUE;
1136 } else if (res == -1) {
1137 /* This could happen if recv () is interrupted repeatedly */
1138 msecs = mono_msec_ticks ();
1139 if (msecs - last_keepalive >= agent_config.keepalive) {
1140 need_keepalive = TRUE;
1141 last_keepalive = msecs;
1144 if (need_keepalive) {
1145 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1149 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1154 #define HAVE_GETADDRINFO 1
1158 set_keepalive (void)
1163 if (!agent_config.keepalive || !conn_fd)
1166 tv.tv_sec = agent_config.keepalive / 1000;
1167 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1169 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1170 g_assert (result >= 0);
1174 socket_transport_accept (int socket_fd)
1176 conn_fd = accept (socket_fd, NULL, NULL);
1177 if (conn_fd == -1) {
1178 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1180 DEBUG (1, fprintf (log_file, "Accepted connection from client, connection fd=%d.\n", conn_fd));
1187 socket_transport_send (void *data, int len)
1192 res = send (conn_fd, data, len, 0);
1193 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1201 * socket_transport_connect:
1203 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1206 socket_transport_connect (const char *address)
1208 #ifdef HAVE_GETADDRINFO
1209 struct addrinfo hints;
1210 struct addrinfo *result, *rp;
1212 struct hostent *result;
1214 int sfd = -1, s, res;
1215 char port_string [128];
1219 if (agent_config.address) {
1220 res = parse_address (agent_config.address, &host, &port);
1221 g_assert (res == 0);
1231 sprintf (port_string, "%d", port);
1233 mono_network_init ();
1235 /* Obtain address(es) matching host/port */
1236 #ifdef HAVE_GETADDRINFO
1237 memset (&hints, 0, sizeof (struct addrinfo));
1238 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
1239 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
1241 hints.ai_protocol = 0; /* Any protocol */
1243 s = getaddrinfo (host, port_string, &hints, &result);
1245 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %s\n", host, port, gai_strerror (s));
1249 /* The PS3 doesn't even have _r or hstrerror () */
1250 result = gethostbyname (host);
1252 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, h_errno);
1257 if (agent_config.server) {
1258 #ifdef HAVE_GETADDRINFO
1259 /* Wait for a connection */
1261 struct sockaddr_in addr;
1264 /* No address, generate one */
1265 sfd = socket (AF_INET, SOCK_STREAM, 0);
1268 /* This will bind the socket to a random port */
1269 res = listen (sfd, 16);
1271 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1276 addrlen = sizeof (addr);
1277 memset (&addr, 0, sizeof (addr));
1278 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1279 g_assert (res == 0);
1281 host = (char*)"127.0.0.1";
1282 port = ntohs (addr.sin_port);
1284 /* Emit the address to stdout */
1285 /* FIXME: Should print another interface, not localhost */
1286 printf ("%s:%d\n", host, port);
1288 /* Listen on the provided address */
1289 for (rp = result; rp != NULL; rp = rp->ai_next) {
1292 sfd = socket (rp->ai_family, rp->ai_socktype,
1297 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1300 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
1304 res = listen (sfd, 16);
1313 * this function is not present on win2000 which we still support, and the
1314 * workaround described here:
1315 * http://msdn.microsoft.com/en-us/library/ms737931(VS.85).aspx
1316 * only works with MSVC.
1318 #ifdef HAVE_GETADDRINFO
1319 freeaddrinfo (result);
1324 if (agent_config.defer)
1327 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
1329 if (agent_config.timeout) {
1334 tv.tv_usec = agent_config.timeout * 1000;
1336 FD_SET (sfd, &readfds);
1337 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1339 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1344 conn_fd = socket_transport_accept (sfd);
1348 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
1351 #endif /* HAVE_GETADDRINFO */
1353 /* Connect to the specified address */
1354 #ifdef HAVE_GETADDRINFO
1355 /* FIXME: Respect the timeout */
1356 for (rp = result; rp != NULL; rp = rp->ai_next) {
1357 sfd = socket (rp->ai_family, rp->ai_socktype,
1362 if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
1363 break; /* Success */
1369 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1373 sfd = socket (result->h_addrtype, SOCK_STREAM, 0);
1375 g_assert_not_reached ();
1376 res = connect (sfd, (void*)result->h_addr_list [0], result->h_length);
1378 g_assert_not_reached ();
1384 /* See the comment above */
1385 #ifdef HAVE_GETADDRINFO
1386 freeaddrinfo (result);
1391 if (!transport_handshake ())
1396 socket_transport_close1 (void)
1398 /* This will interrupt the agent thread */
1399 /* Close the read part only so it can still send back replies */
1400 /* Also shut down the connection listener so that we can exit normally */
1402 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1403 shutdown (conn_fd, SD_BOTH);
1404 shutdown (listen_fd, SD_BOTH);
1405 closesocket (listen_fd);
1407 shutdown (conn_fd, SHUT_RD);
1408 shutdown (listen_fd, SHUT_RDWR);
1414 socket_transport_close2 (void)
1417 shutdown (conn_fd, SD_BOTH);
1419 shutdown (conn_fd, SHUT_RDWR);
1424 register_socket_transport (void)
1426 DebuggerTransport trans;
1428 trans.name = "dt_socket";
1429 trans.connect = socket_transport_connect;
1430 trans.close1 = socket_transport_close1;
1431 trans.close2 = socket_transport_close2;
1432 trans.send = socket_transport_send;
1433 trans.recv = socket_transport_recv;
1435 register_transport (&trans);
1438 #endif /* DISABLE_SOCKET_TRANSPORT */
1444 #define MAX_TRANSPORTS 16
1446 static DebuggerTransport *transport;
1448 static DebuggerTransport transports [MAX_TRANSPORTS];
1449 static int ntransports;
1452 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1455 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1457 register_transport (trans);
1461 register_transport (DebuggerTransport *trans)
1463 g_assert (ntransports < MAX_TRANSPORTS);
1465 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1470 transport_init (void)
1474 #ifndef DISABLE_SOCKET_TRANSPORT
1475 register_socket_transport ();
1478 for (i = 0; i < ntransports; ++i) {
1479 if (!strcmp (agent_config.transport, transports [i].name))
1482 if (i == ntransports) {
1483 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1484 for (i = 0; i < ntransports; ++i)
1485 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1486 fprintf (stderr, "\n");
1489 transport = &transports [i];
1493 transport_connect (const char *address)
1495 transport->connect (address);
1499 transport_close1 (void)
1501 transport->close1 ();
1505 transport_close2 (void)
1507 transport->close2 ();
1511 transport_send (void *buf, int len)
1513 return transport->send (buf, len);
1517 transport_recv (void *buf, int len)
1519 return transport->recv (buf, len);
1523 mono_debugger_agent_transport_handshake (void)
1525 return transport_handshake ();
1529 transport_handshake (void)
1531 char handshake_msg [128];
1535 disconnected = TRUE;
1537 /* Write handshake message */
1538 sprintf (handshake_msg, "DWP-Handshake");
1540 res = transport_send (handshake_msg, strlen (handshake_msg));
1541 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1542 g_assert (res != -1);
1545 res = transport_recv (buf, strlen (handshake_msg));
1546 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg) != 0))) {
1547 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1552 * To support older clients, the client sends its protocol version after connecting
1553 * using a command. Until that is received, default to our protocol version.
1555 major_version = MAJOR_VERSION;
1556 minor_version = MINOR_VERSION;
1557 protocol_version_set = FALSE;
1559 #ifndef DISABLE_SOCKET_TRANSPORT
1560 // FIXME: Move this somewhere else
1562 * Set TCP_NODELAY on the socket so the client receives events/command
1563 * results immediately.
1567 int result = setsockopt (conn_fd,
1572 g_assert (result >= 0);
1578 disconnected = FALSE;
1583 stop_debugger_thread (void)
1588 transport_close1 ();
1591 * Wait for the thread to exit.
1593 * If we continue with the shutdown without waiting for it, then the client might
1594 * not receive an answer to its last command like a resume.
1595 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
1598 //WaitForSingleObject (debugger_thread_handle, INFINITE);
1599 if (GetCurrentThreadId () != debugger_thread_id) {
1601 mono_mutex_lock (&debugger_thread_exited_mutex);
1602 if (!debugger_thread_exited) {
1604 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
1605 mono_mutex_unlock (&debugger_thread_exited_mutex);
1607 mono_mutex_lock (&debugger_thread_exited_mutex);
1610 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1613 mono_mutex_unlock (&debugger_thread_exited_mutex);
1614 } while (!debugger_thread_exited);
1617 transport_close2 ();
1621 start_debugger_thread (void)
1623 debugger_thread_handle = mono_threads_create_thread (debugger_thread, NULL, 0, 0, NULL);
1624 g_assert (debugger_thread_handle);
1628 * Functions to decode protocol data
1632 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1635 g_assert (*endbuf <= limit);
1640 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1643 g_assert (*endbuf <= limit);
1645 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1648 static inline gint64
1649 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1651 guint32 high = decode_int (buf, &buf, limit);
1652 guint32 low = decode_int (buf, &buf, limit);
1656 return ((((guint64)high) << 32) | ((guint64)low));
1660 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1662 return decode_int (buf, endbuf, limit);
1666 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1668 int len = decode_int (buf, &buf, limit);
1676 s = g_malloc (len + 1);
1679 memcpy (s, buf, len);
1688 * Functions to encode protocol data
1692 buffer_init (Buffer *buf, int size)
1694 buf->buf = g_malloc (size);
1696 buf->end = buf->buf + size;
1700 buffer_len (Buffer *buf)
1702 return buf->p - buf->buf;
1706 buffer_make_room (Buffer *buf, int size)
1708 if (buf->end - buf->p < size) {
1709 int new_size = buf->end - buf->buf + size + 32;
1710 guint8 *p = g_realloc (buf->buf, new_size);
1711 size = buf->p - buf->buf;
1714 buf->end = buf->buf + new_size;
1719 buffer_add_byte (Buffer *buf, guint8 val)
1721 buffer_make_room (buf, 1);
1727 buffer_add_short (Buffer *buf, guint32 val)
1729 buffer_make_room (buf, 2);
1730 buf->p [0] = (val >> 8) & 0xff;
1731 buf->p [1] = (val >> 0) & 0xff;
1736 buffer_add_int (Buffer *buf, guint32 val)
1738 buffer_make_room (buf, 4);
1739 buf->p [0] = (val >> 24) & 0xff;
1740 buf->p [1] = (val >> 16) & 0xff;
1741 buf->p [2] = (val >> 8) & 0xff;
1742 buf->p [3] = (val >> 0) & 0xff;
1747 buffer_add_long (Buffer *buf, guint64 l)
1749 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1750 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1754 buffer_add_id (Buffer *buf, int id)
1756 buffer_add_int (buf, (guint64)id);
1760 buffer_add_data (Buffer *buf, guint8 *data, int len)
1762 buffer_make_room (buf, len);
1763 memcpy (buf->p, data, len);
1768 buffer_add_string (Buffer *buf, const char *str)
1773 buffer_add_int (buf, 0);
1776 buffer_add_int (buf, len);
1777 buffer_add_data (buf, (guint8*)str, len);
1782 buffer_add_buffer (Buffer *buf, Buffer *data)
1784 buffer_add_data (buf, data->buf, buffer_len (data));
1788 buffer_free (Buffer *buf)
1794 send_packet (int command_set, int command, Buffer *data)
1800 id = InterlockedIncrement (&packet_id);
1802 len = data->p - data->buf + 11;
1803 buffer_init (&buf, len);
1804 buffer_add_int (&buf, len);
1805 buffer_add_int (&buf, id);
1806 buffer_add_byte (&buf, 0); /* flags */
1807 buffer_add_byte (&buf, command_set);
1808 buffer_add_byte (&buf, command);
1809 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1811 res = transport_send (buf.buf, len);
1819 send_reply_packets (int npackets, ReplyPacket *packets)
1826 for (i = 0; i < npackets; ++i)
1827 len += buffer_len (packets [i].data) + 11;
1828 buffer_init (&buf, len);
1829 for (i = 0; i < npackets; ++i) {
1830 buffer_add_int (&buf, buffer_len (packets [i].data) + 11);
1831 buffer_add_int (&buf, packets [i].id);
1832 buffer_add_byte (&buf, 0x80); /* flags */
1833 buffer_add_byte (&buf, (packets [i].error >> 8) & 0xff);
1834 buffer_add_byte (&buf, packets [i].error);
1835 buffer_add_buffer (&buf, packets [i].data);
1837 res = transport_send (buf.buf, len);
1845 send_reply_packet (int id, int error, Buffer *data)
1849 memset (&packet, 0, sizeof (ReplyPacket));
1851 packet.error = error;
1854 return send_reply_packets (1, &packet);
1858 send_buffered_reply_packets (void)
1862 send_reply_packets (nreply_packets, reply_packets);
1863 for (i = 0; i < nreply_packets; ++i)
1864 buffer_free (reply_packets [i].data);
1865 DEBUG (1, fprintf (log_file, "[dbg] Sent %d buffered reply packets [at=%lx].\n", nreply_packets, (long)mono_100ns_ticks () / 10000));
1870 buffer_reply_packet (int id, int error, Buffer *data)
1874 if (nreply_packets == 128)
1875 send_buffered_reply_packets ();
1877 p = &reply_packets [nreply_packets];
1880 p->data = g_new0 (Buffer, 1);
1881 buffer_init (p->data, buffer_len (data));
1882 buffer_add_buffer (p->data, data);
1891 * Represents an object accessible by the debugger client.
1894 /* Unique id used in the wire protocol to refer to objects */
1897 * A weakref gc handle pointing to the object. The gc handle is used to
1898 * detect if the object was garbage collected.
1903 /* Maps objid -> ObjRef */
1904 static GHashTable *objrefs;
1905 static GHashTable *obj_to_objref;
1906 /* Protected by the dbg lock */
1907 static MonoGHashTable *suspended_objs;
1910 free_objref (gpointer value)
1914 mono_gchandle_free (o->handle);
1922 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1923 obj_to_objref = g_hash_table_new (NULL, NULL);
1924 suspended_objs = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
1925 MONO_GC_REGISTER_ROOT_FIXED (suspended_objs);
1929 objrefs_cleanup (void)
1931 g_hash_table_destroy (objrefs);
1936 * Return an ObjRef for OBJ.
1939 get_objref (MonoObject *obj)
1942 GSList *reflist = NULL, *l;
1948 if (suspend_count) {
1950 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1953 mono_g_hash_table_insert (suspended_objs, obj, NULL);
1957 mono_loader_lock ();
1959 /* FIXME: The tables can grow indefinitely */
1961 if (mono_gc_is_moving ()) {
1963 * Objects can move, so use a hash table mapping hash codes to lists of
1964 * ObjRef structures.
1966 hash = mono_object_hash (obj);
1968 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1969 for (l = reflist; l; l = l->next) {
1971 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1972 mono_loader_unlock ();
1977 /* Use a hash table with masked pointers to internalize object references */
1978 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1979 /* ref might refer to a different object with the same addr which was GCd */
1980 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1981 mono_loader_unlock ();
1986 ref = g_new0 (ObjRef, 1);
1987 ref->id = InterlockedIncrement (&objref_id);
1988 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1990 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
1992 if (mono_gc_is_moving ()) {
1993 reflist = g_slist_append (reflist, ref);
1994 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
1996 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
1999 mono_loader_unlock ();
2005 true_pred (gpointer key, gpointer value, gpointer user_data)
2011 clear_suspended_objs (void)
2014 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
2019 get_objid (MonoObject *obj)
2021 return get_objref (obj)->id;
2025 * Set OBJ to the object identified by OBJID.
2026 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
2030 get_object_allow_null (int objid, MonoObject **obj)
2040 return ERR_INVALID_OBJECT;
2042 mono_loader_lock ();
2044 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
2047 *obj = mono_gchandle_get_target (ref->handle);
2048 mono_loader_unlock ();
2050 return ERR_INVALID_OBJECT;
2053 mono_loader_unlock ();
2054 return ERR_INVALID_OBJECT;
2059 get_object (int objid, MonoObject **obj)
2061 int err = get_object_allow_null (objid, obj);
2066 return ERR_INVALID_OBJECT;
2071 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
2073 return decode_id (buf, endbuf, limit);
2077 buffer_add_objid (Buffer *buf, MonoObject *o)
2079 buffer_add_id (buf, get_objid (o));
2098 * Represents a runtime structure accessible to the debugger client
2101 /* Unique id used in the wire protocol */
2103 /* Domain of the runtime structure, NULL if the domain was unloaded */
2110 MonoAssembly *assembly;
2111 MonoClassField *field;
2113 MonoProperty *property;
2118 /* Maps runtime structure -> Id */
2119 GHashTable *val_to_id [ID_NUM];
2120 /* Classes whose class load event has been sent */
2121 GHashTable *loaded_classes;
2122 /* Maps MonoClass->GPtrArray of file names */
2123 GHashTable *source_files;
2124 /* Maps source file basename -> GSList of classes */
2125 GHashTable *source_file_to_class;
2126 /* Same with ignore-case */
2127 GHashTable *source_file_to_class_ignorecase;
2131 /* Protected by the dbg lock */
2132 static GPtrArray *ids [ID_NUM];
2139 for (i = 0; i < ID_NUM; ++i)
2140 ids [i] = g_ptr_array_new ();
2148 for (i = 0; i < ID_NUM; ++i) {
2150 for (j = 0; j < ids [i]->len; ++j)
2151 g_free (g_ptr_array_index (ids [i], j));
2152 g_ptr_array_free (ids [i], TRUE);
2159 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2161 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
2163 GHashTableIter iter;
2164 GPtrArray *file_names;
2169 for (i = 0; i < ID_NUM; ++i)
2170 if (info->val_to_id [i])
2171 g_hash_table_destroy (info->val_to_id [i]);
2172 g_hash_table_destroy (info->loaded_classes);
2174 g_hash_table_iter_init (&iter, info->source_files);
2175 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2176 for (i = 0; i < file_names->len; ++i)
2177 g_free (g_ptr_array_index (file_names, i));
2178 g_ptr_array_free (file_names, TRUE);
2181 g_hash_table_iter_init (&iter, info->source_file_to_class);
2182 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2187 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2188 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2196 domain_jit_info (domain)->agent_info = NULL;
2198 /* Clear ids referencing structures in the domain */
2200 for (i = 0; i < ID_NUM; ++i) {
2202 for (j = 0; j < ids [i]->len; ++j) {
2203 Id *id = g_ptr_array_index (ids [i], j);
2204 if (id->domain == domain)
2211 mono_loader_lock ();
2212 g_hash_table_remove (domains, domain);
2213 mono_loader_unlock ();
2216 static AgentDomainInfo*
2217 get_agent_domain_info (MonoDomain *domain)
2219 AgentDomainInfo *info = NULL;
2221 mono_domain_lock (domain);
2223 info = domain_jit_info (domain)->agent_info;
2225 info = domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
2226 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2227 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2228 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2229 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2232 mono_domain_unlock (domain);
2238 get_id (MonoDomain *domain, IdType type, gpointer val)
2241 AgentDomainInfo *info;
2246 mono_loader_lock ();
2248 mono_domain_lock (domain);
2250 info = get_agent_domain_info (domain);
2252 if (info->val_to_id [type] == NULL)
2253 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2255 id = g_hash_table_lookup (info->val_to_id [type], val);
2257 mono_domain_unlock (domain);
2258 mono_loader_unlock ();
2264 id = g_new0 (Id, 1);
2266 id->id = ids [type]->len + 1;
2267 id->domain = domain;
2270 g_hash_table_insert (info->val_to_id [type], val, id);
2271 g_ptr_array_add (ids [type], id);
2275 mono_domain_unlock (domain);
2277 mono_loader_unlock ();
2282 static inline gpointer
2283 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
2287 int id = decode_id (buf, endbuf, limit);
2296 // FIXME: error handling
2298 g_assert (id > 0 && id <= ids [type]->len);
2300 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2303 if (res->domain == NULL) {
2304 DEBUG (0, fprintf (log_file, "ERR_UNLOADED, id=%d, type=%d.\n", id, type));
2305 *err = ERR_UNLOADED;
2310 *domain = res->domain;
2312 return res->data.val;
2316 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2318 int id = get_id (domain, type, val);
2320 buffer_add_id (buf, id);
2324 static inline MonoClass*
2325 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2329 klass = decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2330 if (G_UNLIKELY (log_level >= 2) && klass) {
2333 s = mono_type_full_name (&klass->byval_arg);
2334 DEBUG(2, fprintf (log_file, "[dbg] recv class [%s]\n", s));
2340 static inline MonoAssembly*
2341 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2343 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2346 static inline MonoImage*
2347 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2349 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2352 static inline MonoMethod*
2353 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2357 m = decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2358 if (G_UNLIKELY (log_level >= 2) && m) {
2361 s = mono_method_full_name (m, TRUE);
2362 DEBUG(2, fprintf (log_file, "[dbg] recv method [%s]\n", s));
2368 static inline MonoClassField*
2369 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2371 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2374 static inline MonoDomain*
2375 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2377 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2380 static inline MonoProperty*
2381 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2383 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2387 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2389 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2390 if (G_UNLIKELY (log_level >= 2) && klass) {
2393 s = mono_type_full_name (&klass->byval_arg);
2394 if (GetCurrentThreadId () == debugger_thread_id)
2395 DEBUG(2, fprintf (log_file, "[dbg] send class [%s]\n", s));
2397 DEBUG(2, fprintf (log_file, "[%p] send class [%s]\n", (gpointer)GetCurrentThreadId (), s));
2403 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2405 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2406 if (G_UNLIKELY (log_level >= 2) && method) {
2409 s = mono_method_full_name (method, 1);
2410 DEBUG(2, fprintf (log_file, "[dbg] send method [%s]\n", s));
2416 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2420 id = buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2421 if (G_UNLIKELY (log_level >= 2) && assembly)
2422 DEBUG(2, fprintf (log_file, "[dbg] send assembly [%s][%s][%d]\n", assembly->aname.name, domain->friendly_name, id));
2426 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2428 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2432 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2434 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2438 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2440 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2444 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2446 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2449 static void invoke_method (void);
2456 * save_thread_context:
2458 * Set CTX as the current threads context which is used for computing stack traces.
2459 * This function is signal-safe.
2462 save_thread_context (MonoContext *ctx)
2464 DebuggerTlsData *tls;
2466 tls = mono_native_tls_get_value (debugger_tls_id);
2470 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2472 mono_thread_state_init_from_current (&tls->context);
2475 /* Number of threads suspended */
2477 * If this is equal to the size of thread_to_tls, the runtime is considered
2480 static gint32 threads_suspend_count;
2482 static mono_mutex_t suspend_mutex;
2484 /* Cond variable used to wait for suspend_count becoming 0 */
2485 static mono_cond_t suspend_cond;
2487 /* Semaphore used to wait for a thread becoming suspended */
2488 static MonoSemType suspend_sem;
2493 mono_mutex_init (&suspend_mutex);
2494 mono_cond_init (&suspend_cond, NULL);
2495 MONO_SEM_INIT (&suspend_sem, 0);
2500 StackFrameInfo last_frame;
2501 gboolean last_frame_set;
2504 } GetLastFrameUserData;
2507 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2509 GetLastFrameUserData *data = user_data;
2511 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
2514 if (!data->last_frame_set) {
2515 /* Store the last frame */
2516 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2517 data->last_frame_set = TRUE;
2520 /* Store the context/lmf for the frame above the last frame */
2521 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2522 data->lmf = info->lmf;
2530 * Process interruption of a thread. If SIGCTX is set, process the current thread. If
2531 * INFO is set, process the thread described by INFO.
2532 * This should be signal safe.
2535 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, void *sigctx, MonoJitInfo *ji)
2539 MonoNativeThreadId tid;
2542 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2543 * guarantee the signal handler will be called that many times. Instead of tracking
2544 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2545 * has been requested that hasn't been handled yet, otherwise we can have threads
2546 * refuse to die when VM_EXIT is called
2548 #if defined(__APPLE__)
2549 if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
2553 * We use interrupt_count to determine whenever this interrupt should be processed
2554 * by us or the normal interrupt processing code in the signal handler.
2555 * There is no race here with notify_thread (), since the signal is sent after
2556 * incrementing interrupt_count.
2558 if (tls->interrupt_count == 0)
2561 InterlockedDecrement (&tls->interrupt_count);
2565 ip = mono_arch_ip_from_context (sigctx);
2567 ip = MONO_CONTEXT_GET_IP (&info->suspend_state.ctx);
2572 tid = mono_thread_info_get_tid (info);
2574 tid = (MonoNativeThreadId)GetCurrentThreadId ();
2576 // FIXME: Races when the thread leaves managed code before hitting a single step
2580 /* Running managed code, will be suspended by the single step code */
2581 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip));
2585 * Running native code, will be suspended when it returns to/enters
2586 * managed code. Treat it as already suspended.
2587 * This might interrupt the code in process_single_step_inner (), we use the
2588 * tls->suspending flag to avoid races when that happens.
2590 if (!tls->suspended && !tls->suspending) {
2592 GetLastFrameUserData data;
2594 // FIXME: printf is not signal safe, but this is only used during
2595 // debugger debugging
2597 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip));
2598 //save_thread_context (&ctx);
2601 /* Already terminated */
2605 * We are in a difficult position: we want to be able to provide stack
2606 * traces for this thread, but we can't use the current ctx+lmf, since
2607 * the thread is still running, so it might return to managed code,
2608 * making these invalid.
2609 * So we start a stack walk and save the first frame, along with the
2610 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2611 * suspended when it returns to managed code, so the parent's ctx should
2614 data.last_frame_set = FALSE;
2616 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
2618 * Don't pass MONO_UNWIND_ACTUAL_METHOD, its not signal safe, and
2619 * get_last_frame () doesn't need it, the last frame cannot be a ginst
2620 * since we are not in a JITted method.
2622 mono_walk_stack_with_ctx (get_last_frame, &ctx, MONO_UNWIND_NONE, &data);
2624 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, &info->suspend_state, MONO_UNWIND_SIGNAL_SAFE, &data);
2626 if (data.last_frame_set) {
2627 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2628 res = mono_thread_state_init_from_monoctx (&tls->async_state, &ctx);
2630 mono_thread_state_init_from_monoctx (&tls->context, &ctx);
2633 memcpy (&tls->async_state.ctx, &data.ctx, sizeof (MonoContext));
2634 tls->async_state.unwind_data [MONO_UNWIND_DATA_LMF] = data.lmf;
2635 tls->async_state.unwind_data [MONO_UNWIND_DATA_JIT_TLS] = tls->thread->jit_data;
2637 tls->async_state.valid = FALSE;
2640 mono_memory_barrier ();
2642 tls->suspended = TRUE;
2643 MONO_SEM_POST (&suspend_sem);
2650 * mono_debugger_agent_thread_interrupt:
2652 * Called by the abort signal handler.
2653 * Should be signal safe.
2656 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
2658 DebuggerTlsData *tls;
2663 tls = mono_native_tls_get_value (debugger_tls_id);
2665 DEBUG (1, fprintf (log_file, "[%p] Received interrupt with no TLS, continuing.\n", (gpointer)GetCurrentThreadId ()));
2669 return thread_interrupt (tls, NULL, sigctx, ji);
2673 static void CALLBACK notify_thread_apc (ULONG_PTR param)
2676 mono_debugger_agent_thread_interrupt (NULL, NULL);
2678 #endif /* HOST_WIN32 */
2681 * reset_native_thread_suspend_state:
2683 * Reset the suspended flag and state on native threads
2686 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2688 DebuggerTlsData *tls = value;
2690 if (!tls->really_suspended && tls->suspended) {
2691 tls->suspended = FALSE;
2693 * The thread might still be running if it was executing native code, so the state won't be invalided by
2694 * suspend_current ().
2696 tls->context.valid = FALSE;
2697 tls->async_state.valid = FALSE;
2698 invalidate_frames (tls);
2705 * Notify a thread that it needs to suspend.
2708 notify_thread (gpointer key, gpointer value, gpointer user_data)
2710 MonoInternalThread *thread = key;
2711 DebuggerTlsData *tls = value;
2712 gsize tid = thread->tid;
2715 if (GetCurrentThreadId () == tid || tls->terminated)
2718 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2721 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2722 * guarantee the signal handler will be called that many times. Instead of tracking
2723 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2724 * has been requested that hasn't been handled yet, otherwise we can have threads
2725 * refuse to die when VM_EXIT is called
2727 #if defined(__APPLE__)
2728 if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
2732 * Maybe we could use the normal interrupt infrastructure, but that does a lot
2733 * of things like breaking waits etc. which we don't want.
2735 InterlockedIncrement (&tls->interrupt_count);
2738 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2740 QueueUserAPC (notify_thread_apc, thread->handle, NULL);
2742 if (mono_thread_info_new_interrupt_enabled ()) {
2743 MonoThreadInfo *info;
2746 info = mono_thread_info_safe_suspend_sync ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE);
2748 DEBUG(1, fprintf (log_file, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2750 * Attached thread which died without detaching.
2752 tls->terminated = TRUE;
2754 ji = mono_jit_info_table_find (info->suspend_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], MONO_CONTEXT_GET_IP (&info->suspend_state.ctx));
2756 thread_interrupt (tls, info, NULL, ji);
2758 mono_thread_info_finish_suspend_and_resume (info);
2761 res = mono_thread_kill (thread, mono_thread_get_abort_signal ());
2763 DEBUG(1, fprintf (log_file, "[%p] mono_thread_kill () failed for %p: %d...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid, res));
2765 * Attached thread which died without detaching.
2767 tls->terminated = TRUE;
2774 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2776 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2780 if (mono_loader_lock_is_owned_by_self ()) {
2782 * Shortcut for the check in suspend_current (). This speeds up processing
2783 * when executing long running code inside the loader lock, i.e. assembly load
2789 if (debugger_thread_id == GetCurrentThreadId ())
2792 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2793 if (suspend_count - tls->resume_count > 0)
2794 tls->suspending = TRUE;
2796 DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2798 if (suspend_count - tls->resume_count == 0) {
2800 * We are executing a single threaded invoke but the single step for
2801 * suspending is still active.
2802 * FIXME: This slows down single threaded invokes.
2804 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
2808 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2810 /* Can't suspend in these methods */
2811 method = jinfo_get_method (ji);
2812 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2815 save_thread_context (ctx);
2823 * Increase the suspend count of the VM. While the suspend count is greater
2824 * than 0, runtime threads are suspended at certain points during execution.
2829 mono_loader_lock ();
2831 mono_mutex_lock (&suspend_mutex);
2835 DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
2837 if (suspend_count == 1) {
2838 // FIXME: Is it safe to call this inside the lock ?
2839 start_single_stepping ();
2840 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2843 mono_mutex_unlock (&suspend_mutex);
2845 if (suspend_count == 1)
2847 * Suspend creation of new threadpool threads, since they cannot run
2849 mono_thread_pool_suspend ();
2851 mono_loader_unlock ();
2857 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2865 g_assert (debugger_thread_id == GetCurrentThreadId ());
2867 mono_loader_lock ();
2869 mono_mutex_lock (&suspend_mutex);
2871 g_assert (suspend_count > 0);
2874 DEBUG(1, fprintf (log_file, "[%p] Resuming vm, suspend count=%d...\n", (gpointer)GetCurrentThreadId (), suspend_count));
2876 if (suspend_count == 0) {
2877 // FIXME: Is it safe to call this inside the lock ?
2878 stop_single_stepping ();
2879 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2882 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2883 err = mono_cond_broadcast (&suspend_cond);
2884 g_assert (err == 0);
2886 mono_mutex_unlock (&suspend_mutex);
2887 //g_assert (err == 0);
2889 if (suspend_count == 0)
2890 mono_thread_pool_resume ();
2892 mono_loader_unlock ();
2898 * Resume just one thread.
2901 resume_thread (MonoInternalThread *thread)
2904 DebuggerTlsData *tls;
2906 g_assert (debugger_thread_id == GetCurrentThreadId ());
2908 mono_loader_lock ();
2910 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2913 mono_mutex_lock (&suspend_mutex);
2915 g_assert (suspend_count > 0);
2917 DEBUG(1, fprintf (log_file, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid));
2919 tls->resume_count += suspend_count;
2922 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2923 * but only the one whose resume_count field is > 0 will be resumed.
2925 err = mono_cond_broadcast (&suspend_cond);
2926 g_assert (err == 0);
2928 mono_mutex_unlock (&suspend_mutex);
2929 //g_assert (err == 0);
2931 mono_loader_unlock ();
2935 invalidate_frames (DebuggerTlsData *tls)
2940 tls = mono_native_tls_get_value (debugger_tls_id);
2943 for (i = 0; i < tls->frame_count; ++i) {
2944 if (tls->frames [i]->jit)
2945 mono_debug_free_method_jit_info (tls->frames [i]->jit);
2946 g_free (tls->frames [i]);
2948 g_free (tls->frames);
2949 tls->frame_count = 0;
2956 * Suspend the current thread until the runtime is resumed. If the thread has a
2957 * pending invoke, then the invoke is executed before this function returns.
2960 suspend_current (void)
2963 DebuggerTlsData *tls;
2965 g_assert (debugger_thread_id != GetCurrentThreadId ());
2967 if (mono_loader_lock_is_owned_by_self ()) {
2969 * If we own the loader mutex, can't suspend until we release it, since the
2970 * whole runtime can deadlock otherwise.
2975 tls = mono_native_tls_get_value (debugger_tls_id);
2978 mono_mutex_lock (&suspend_mutex);
2980 tls->suspending = FALSE;
2981 tls->really_suspended = TRUE;
2983 if (!tls->suspended) {
2984 tls->suspended = TRUE;
2985 MONO_SEM_POST (&suspend_sem);
2988 DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
2990 while (suspend_count - tls->resume_count > 0) {
2992 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
2994 mono_mutex_unlock (&suspend_mutex);
2996 mono_mutex_lock (&suspend_mutex);
3002 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
3003 g_assert (err == 0);
3007 tls->suspended = FALSE;
3008 tls->really_suspended = FALSE;
3010 threads_suspend_count --;
3012 mono_mutex_unlock (&suspend_mutex);
3014 DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
3016 if (tls->pending_invoke) {
3017 /* Save the original context */
3018 tls->pending_invoke->has_ctx = TRUE;
3019 tls->pending_invoke->ctx = tls->context.ctx;
3024 /* The frame info becomes invalid after a resume */
3025 tls->context.valid = FALSE;
3026 tls->async_state.valid = FALSE;
3027 invalidate_frames (tls);
3031 count_thread (gpointer key, gpointer value, gpointer user_data)
3033 DebuggerTlsData *tls = value;
3035 if (!tls->suspended && !tls->terminated)
3036 *(int*)user_data = *(int*)user_data + 1;
3040 count_threads_to_wait_for (void)
3044 mono_loader_lock ();
3045 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
3046 mono_loader_unlock ();
3054 * Wait until the runtime is completely suspended.
3057 wait_for_suspend (void)
3059 int nthreads, nwait, err;
3060 gboolean waited = FALSE;
3062 // FIXME: Threads starting/stopping ?
3063 mono_loader_lock ();
3064 nthreads = mono_g_hash_table_size (thread_to_tls);
3065 mono_loader_unlock ();
3068 nwait = count_threads_to_wait_for ();
3070 DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
3071 err = MONO_SEM_WAIT (&suspend_sem);
3072 g_assert (err == 0);
3080 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
3086 * Return whenever the runtime is suspended.
3091 return count_threads_to_wait_for () == 0;
3094 static MonoSeqPointInfo*
3095 get_seq_points (MonoDomain *domain, MonoMethod *method)
3097 MonoSeqPointInfo *seq_points;
3099 mono_domain_lock (domain);
3100 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
3101 if (!seq_points && method->is_inflated) {
3102 /* generic sharing + aot */
3103 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (method));
3105 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mini_get_shared_method (method));
3107 mono_domain_unlock (domain);
3113 no_seq_points_found (MonoMethod *method)
3116 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3118 printf ("Unable to find seq points for method '%s'.\n", mono_method_full_name (method, TRUE));
3122 * find_next_seq_point_for_native_offset:
3124 * Find the first sequence point after NATIVE_OFFSET.
3127 find_next_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
3129 MonoSeqPointInfo *seq_points;
3132 seq_points = get_seq_points (domain, method);
3138 g_assert (seq_points);
3142 for (i = 0; i < seq_points->len; ++i) {
3143 if (seq_points->seq_points [i].native_offset >= native_offset)
3144 return &seq_points->seq_points [i];
3151 * find_prev_seq_point_for_native_offset:
3153 * Find the first sequence point before NATIVE_OFFSET.
3156 find_prev_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
3158 MonoSeqPointInfo *seq_points;
3161 seq_points = get_seq_points (domain, method);
3167 for (i = seq_points->len - 1; i >= 0; --i) {
3168 if (seq_points->seq_points [i].native_offset <= native_offset)
3169 return &seq_points->seq_points [i];
3178 * Find the sequence point corresponding to the IL offset IL_OFFSET, which
3179 * should be the location of a sequence point.
3181 static G_GNUC_UNUSED SeqPoint*
3182 find_seq_point (MonoDomain *domain, MonoMethod *method, gint32 il_offset, MonoSeqPointInfo **info)
3184 MonoSeqPointInfo *seq_points;
3189 seq_points = get_seq_points (domain, method);
3194 for (i = 0; i < seq_points->len; ++i) {
3195 if (seq_points->seq_points [i].il_offset == il_offset)
3196 return &seq_points->seq_points [i];
3203 DebuggerTlsData *tls;
3205 } ComputeFramesUserData;
3208 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3210 ComputeFramesUserData *ud = user_data;
3212 MonoMethod *method, *actual_method, *api_method;
3216 if (info->type != FRAME_TYPE_MANAGED) {
3217 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3218 /* Mark the last frame as an invoke frame */
3220 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3226 method = jinfo_get_method (info->ji);
3228 method = info->method;
3229 actual_method = info->actual_method;
3230 api_method = method;
3235 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3238 if (info->il_offset == -1) {
3239 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3240 if (ud->frames == NULL) {
3241 sp = find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL);
3243 info->il_offset = sp->il_offset;
3245 if (info->il_offset == -1)
3246 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3249 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));
3251 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3252 if (!CHECK_PROTOCOL_VERSION (2, 17))
3253 /* Older clients can't handle this flag */
3255 api_method = mono_marshal_method_from_wrapper (method);
3258 actual_method = api_method;
3259 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3262 frame = g_new0 (StackFrame, 1);
3263 frame->method = method;
3264 frame->actual_method = actual_method;
3265 frame->api_method = api_method;
3266 frame->il_offset = info->il_offset;
3267 frame->native_offset = info->native_offset;
3268 frame->flags = flags;
3269 frame->ji = info->ji;
3270 if (info->reg_locations)
3271 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3274 frame->has_ctx = TRUE;
3276 frame->domain = info->domain;
3278 ud->frames = g_slist_append (ud->frames, frame);
3284 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3286 ComputeFramesUserData *ud = user_data;
3289 * 'tls->filter_ctx' is the location of the throw site.
3291 * mono_walk_stack() will never actually hit the throw site, but unwind
3292 * directly from the filter to the call site; we abort stack unwinding here
3293 * once this happens and resume from the throw site.
3296 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3299 return process_frame (info, ctx, user_data);
3303 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3305 ComputeFramesUserData user_data;
3307 int i, findex, new_frame_count;
3308 StackFrame **new_frames, *f;
3309 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3311 // FIXME: Locking on tls
3312 if (tls->frames && tls->frames_up_to_date)
3315 DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
3317 user_data.tls = tls;
3318 user_data.frames = NULL;
3319 if (tls->terminated) {
3320 tls->frame_count = 0;
3322 } if (!tls->really_suspended && tls->async_state.valid) {
3323 /* Have to use the state saved by the signal handler */
3324 process_frame (&tls->async_last_frame, NULL, &user_data);
3325 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3326 } else if (tls->filter_state.valid) {
3328 * We are inside an exception filter.
3330 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3332 if (tls->context.valid)
3333 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3335 * After that, we resume unwinding from the location where the exception has been thrown.
3337 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3338 } else if (tls->context.valid) {
3339 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3342 tls->frame_count = 0;
3346 new_frame_count = g_slist_length (user_data.frames);
3347 new_frames = g_new0 (StackFrame*, new_frame_count);
3349 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3353 * Reuse the id for already existing stack frames, so invokes don't invalidate
3354 * the still valid stack frames.
3356 for (i = 0; i < tls->frame_count; ++i) {
3357 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3358 f->id = tls->frames [i]->id;
3363 if (i >= tls->frame_count)
3364 f->id = InterlockedIncrement (&frame_id);
3366 new_frames [findex ++] = f;
3369 g_slist_free (user_data.frames);
3371 invalidate_frames (tls);
3373 tls->frames = new_frames;
3374 tls->frame_count = new_frame_count;
3375 tls->frames_up_to_date = TRUE;
3379 * GHFunc to emit an appdomain creation event
3380 * @param key Don't care
3381 * @param value A loaded appdomain
3382 * @param user_data Don't care
3385 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3387 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3388 g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
3392 * GHFunc to emit a thread start event
3393 * @param key A thread id
3394 * @param value A thread object
3395 * @param user_data Don't care
3398 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3400 if (GPOINTER_TO_INT (key) != debugger_thread_id)
3401 process_profiler_event (EVENT_KIND_THREAD_START, value);
3405 * GFunc to emit an assembly load event
3406 * @param value A loaded assembly
3407 * @param user_data Don't care
3410 emit_assembly_load (gpointer value, gpointer user_data)
3412 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3416 * GFunc to emit a type load event
3417 * @param value A loaded type
3418 * @param user_data Don't care
3421 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3423 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3427 strdup_tolower (char *s)
3432 for (p = s2; *p; ++p)
3442 * create_event_list:
3444 * Return a list of event request ids matching EVENT, starting from REQS, which
3445 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3447 * We return request ids, instead of requests, to simplify threading, since
3448 * requests could be deleted anytime when the loader lock is not held.
3449 * LOCKING: Assumes the loader lock is held.
3452 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3455 GSList *events = NULL;
3457 *suspend_policy = SUSPEND_POLICY_NONE;
3460 reqs = event_requests;
3465 for (i = 0; i < reqs->len; ++i) {
3466 EventRequest *req = g_ptr_array_index (reqs, i);
3467 if (req->event_kind == event) {
3468 gboolean filtered = FALSE;
3471 for (j = 0; j < req->nmodifiers; ++j) {
3472 Modifier *mod = &req->modifiers [j];
3474 if (mod->kind == MOD_KIND_COUNT) {
3476 if (mod->data.count > 0) {
3477 if (mod->data.count > 0) {
3479 if (mod->data.count == 0)
3483 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3484 if (mod->data.thread != mono_thread_internal_current ())
3486 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3487 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3489 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3491 if (ei->caught && !mod->caught)
3493 if (!ei->caught && !mod->uncaught)
3495 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3497 gboolean found = FALSE;
3498 MonoAssembly **assemblies = mod->data.assemblies;
3501 for (k = 0; assemblies [k]; ++k)
3502 if (assemblies [k] == jinfo_get_method (ji)->klass->image->assembly)
3507 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3508 gpointer iter = NULL;
3510 MonoDebugSourceInfo *sinfo;
3511 char *source_file, *s;
3512 gboolean found = FALSE;
3514 GPtrArray *source_file_list;
3516 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3517 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3520 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
3521 for (i = 0; i < source_file_list->len; ++i) {
3522 sinfo = g_ptr_array_index (source_file_list, i);
3524 * Do a case-insesitive match by converting the file name to
3527 s = strdup_tolower (sinfo->source_file);
3528 if (g_hash_table_lookup (mod->data.source_files, s))
3531 char *s2 = g_path_get_basename (sinfo->source_file);
3532 char *s3 = strdup_tolower (s2);
3534 if (g_hash_table_lookup (mod->data.source_files, s3))
3541 g_ptr_array_free (source_file_list, TRUE);
3546 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3549 s = mono_type_full_name (&ei->klass->byval_arg);
3550 if (!g_hash_table_lookup (mod->data.type_names, s))
3553 } else if (mod->kind == MOD_KIND_STEP) {
3554 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3555 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3556 !strcmp (jinfo_get_method (ji)->name, ".cctor"))
3558 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3559 MonoCustomAttrInfo *ainfo;
3560 static MonoClass *klass;
3563 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3566 if (!ji->dbg_hidden_inited) {
3567 ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji));
3569 if (mono_custom_attrs_has_attr (ainfo, klass))
3570 ji->dbg_hidden = TRUE;
3571 mono_custom_attrs_free (ainfo);
3573 ji->dbg_hidden_inited = TRUE;
3578 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3579 MonoCustomAttrInfo *ainfo;
3580 static MonoClass *klass;
3583 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3586 if (!ji->dbg_step_through_inited) {
3587 ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji));
3589 if (mono_custom_attrs_has_attr (ainfo, klass))
3590 ji->dbg_step_through = TRUE;
3591 mono_custom_attrs_free (ainfo);
3593 ainfo = mono_custom_attrs_from_class (jinfo_get_method (ji)->klass);
3595 if (mono_custom_attrs_has_attr (ainfo, klass))
3596 ji->dbg_step_through = TRUE;
3597 mono_custom_attrs_free (ainfo);
3599 ji->dbg_step_through_inited = TRUE;
3601 if (ji->dbg_step_through)
3604 if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3605 MonoCustomAttrInfo *ainfo;
3606 static MonoClass *klass;
3609 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute");
3612 if (!ji->dbg_non_user_code_inited) {
3613 ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji));
3615 if (mono_custom_attrs_has_attr (ainfo, klass))
3616 ji->dbg_non_user_code = TRUE;
3617 mono_custom_attrs_free (ainfo);
3619 ainfo = mono_custom_attrs_from_class (jinfo_get_method (ji)->klass);
3621 if (mono_custom_attrs_has_attr (ainfo, klass))
3622 ji->dbg_non_user_code = TRUE;
3623 mono_custom_attrs_free (ainfo);
3625 ji->dbg_non_user_code_inited = TRUE;
3627 if (ji->dbg_non_user_code)
3634 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3635 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3640 /* Send a VM START/DEATH event by default */
3641 if (event == EVENT_KIND_VM_START)
3642 events = g_slist_append (events, GINT_TO_POINTER (0));
3643 if (event == EVENT_KIND_VM_DEATH)
3644 events = g_slist_append (events, GINT_TO_POINTER (0));
3649 static G_GNUC_UNUSED const char*
3650 event_to_string (EventKind event)
3653 case EVENT_KIND_VM_START: return "VM_START";
3654 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3655 case EVENT_KIND_THREAD_START: return "THREAD_START";
3656 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3657 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3658 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3659 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3660 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3661 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3662 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3663 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3664 case EVENT_KIND_STEP: return "STEP";
3665 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3666 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3667 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3668 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3669 case EVENT_KIND_USER_LOG: return "USER_LOG";
3671 g_assert_not_reached ();
3679 * Send an event to the client, suspending the vm if needed.
3680 * LOCKING: Since this can suspend the calling thread, no locks should be held
3682 * The EVENTS list is freed by this function.
3685 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3689 MonoDomain *domain = mono_domain_get ();
3690 MonoThread *thread = NULL;
3691 MonoObject *keepalive_obj = NULL;
3692 gboolean send_success = FALSE;
3697 DEBUG (2, fprintf (log_file, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event)));
3701 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3702 // FIXME: We miss those events
3703 DEBUG (2, fprintf (log_file, "VM start event not sent yet: dropping %s\n", event_to_string (event)));
3707 if (vm_death_event_sent) {
3708 DEBUG (2, fprintf (log_file, "VM death event has been sent: dropping %s\n", event_to_string (event)));
3712 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3713 DEBUG (2, fprintf (log_file, "Mono runtime is shutting down: dropping %s\n", event_to_string (event)));
3718 DEBUG (2, fprintf (log_file, "Debugger client is not connected: dropping %s\n", event_to_string (event)));
3722 if (event == EVENT_KIND_KEEPALIVE)
3723 suspend_policy = SUSPEND_POLICY_NONE;
3728 if (agent_config.defer) {
3729 /* Make sure the thread id is always set when doing deferred debugging */
3730 if (debugger_thread_id == GetCurrentThreadId ()) {
3731 /* Don't suspend on events from the debugger thread */
3732 suspend_policy = SUSPEND_POLICY_NONE;
3733 thread = mono_thread_get_main ();
3735 else thread = mono_thread_current ();
3737 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3738 // FIXME: Send these with a NULL thread, don't suspend the current thread
3743 nevents = g_slist_length (events);
3744 buffer_init (&buf, 128);
3745 buffer_add_byte (&buf, suspend_policy);
3746 buffer_add_int (&buf, nevents);
3748 for (l = events; l; l = l->next) {
3749 buffer_add_byte (&buf, event); // event kind
3750 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3755 thread = mono_thread_current ();
3757 if (event == EVENT_KIND_VM_START && arg != NULL)
3760 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3763 case EVENT_KIND_THREAD_START:
3764 case EVENT_KIND_THREAD_DEATH:
3766 case EVENT_KIND_APPDOMAIN_CREATE:
3767 case EVENT_KIND_APPDOMAIN_UNLOAD:
3768 buffer_add_domainid (&buf, arg);
3770 case EVENT_KIND_METHOD_ENTRY:
3771 case EVENT_KIND_METHOD_EXIT:
3772 buffer_add_methodid (&buf, domain, arg);
3774 case EVENT_KIND_ASSEMBLY_LOAD:
3775 buffer_add_assemblyid (&buf, domain, arg);
3777 case EVENT_KIND_ASSEMBLY_UNLOAD: {
3778 DebuggerTlsData *tls;
3780 /* The domain the assembly belonged to is not equal to the current domain */
3781 tls = mono_native_tls_get_value (debugger_tls_id);
3783 g_assert (tls->domain_unloading);
3785 buffer_add_assemblyid (&buf, tls->domain_unloading, arg);
3788 case EVENT_KIND_TYPE_LOAD:
3789 buffer_add_typeid (&buf, domain, arg);
3791 case EVENT_KIND_BREAKPOINT:
3792 case EVENT_KIND_STEP:
3793 buffer_add_methodid (&buf, domain, arg);
3794 buffer_add_long (&buf, il_offset);
3796 case EVENT_KIND_VM_START:
3797 buffer_add_domainid (&buf, mono_get_root_domain ());
3799 case EVENT_KIND_VM_DEATH:
3800 if (CHECK_PROTOCOL_VERSION (2, 27))
3801 buffer_add_int (&buf, mono_environment_exitcode_get ());
3803 case EVENT_KIND_EXCEPTION: {
3804 EventInfo *ei = arg;
3805 buffer_add_objid (&buf, ei->exc);
3807 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3808 * later after the suspension. (#12494).
3810 keepalive_obj = ei->exc;
3813 case EVENT_KIND_USER_BREAK:
3815 case EVENT_KIND_USER_LOG: {
3816 EventInfo *ei = arg;
3817 buffer_add_int (&buf, ei->level);
3818 buffer_add_string (&buf, ei->category ? ei->category : "");
3819 buffer_add_string (&buf, ei->message ? ei->message : "");
3822 case EVENT_KIND_KEEPALIVE:
3823 suspend_policy = SUSPEND_POLICY_NONE;
3826 g_assert_not_reached ();
3830 if (event == EVENT_KIND_VM_START) {
3831 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3832 if (!agent_config.defer)
3833 start_debugger_thread ();
3836 if (event == EVENT_KIND_VM_DEATH) {
3837 vm_death_event_sent = TRUE;
3838 suspend_policy = SUSPEND_POLICY_NONE;
3841 if (mono_runtime_is_shutting_down ())
3842 suspend_policy = SUSPEND_POLICY_NONE;
3844 if (suspend_policy != SUSPEND_POLICY_NONE) {
3846 * Save the thread context and start suspending before sending the packet,
3847 * since we could be receiving the resume request before send_packet ()
3850 save_thread_context (ctx);
3854 /* This will keep this object alive */
3855 get_objref (keepalive_obj);
3858 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3862 g_slist_free (events);
3865 if (!send_success) {
3866 DEBUG (2, fprintf (log_file, "Sending command %s failed.\n", event_to_string (event)));
3870 if (event == EVENT_KIND_VM_START) {
3871 vm_start_event_sent = TRUE;
3874 DEBUG (1, fprintf (log_file, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer)GetCurrentThreadId (), nevents, event_to_string (event), ecount, suspend_policy));
3876 switch (suspend_policy) {
3877 case SUSPEND_POLICY_NONE:
3879 case SUSPEND_POLICY_ALL:
3882 case SUSPEND_POLICY_EVENT_THREAD:
3886 g_assert_not_reached ();
3891 process_profiler_event (EventKind event, gpointer arg)
3895 EventInfo ei, *ei_arg = NULL;
3897 if (event == EVENT_KIND_TYPE_LOAD) {
3902 mono_loader_lock ();
3903 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3904 mono_loader_unlock ();
3906 process_event (event, arg, 0, NULL, events, suspend_policy);
3910 runtime_initialized (MonoProfiler *prof)
3912 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3913 if (agent_config.defer)
3914 start_debugger_thread ();
3918 runtime_shutdown (MonoProfiler *prof)
3920 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3922 mono_debugger_agent_cleanup ();
3926 thread_startup (MonoProfiler *prof, uintptr_t tid)
3928 MonoInternalThread *thread = mono_thread_internal_current ();
3929 MonoInternalThread *old_thread;
3930 DebuggerTlsData *tls;
3932 if (tid == debugger_thread_id)
3935 g_assert (thread->tid == tid);
3937 mono_loader_lock ();
3938 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3939 mono_loader_unlock ();
3941 if (thread == old_thread) {
3943 * For some reason, thread_startup () might be called for the same thread
3944 * multiple times (attach ?).
3946 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
3950 * thread_end () might not be called for some threads, and the tid could
3953 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
3954 mono_loader_lock ();
3955 mono_g_hash_table_remove (thread_to_tls, old_thread);
3956 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3957 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3958 mono_loader_unlock ();
3962 tls = mono_native_tls_get_value (debugger_tls_id);
3964 // FIXME: Free this somewhere
3965 tls = g_new0 (DebuggerTlsData, 1);
3966 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3967 tls->thread = thread;
3968 mono_native_tls_set_value (debugger_tls_id, tls);
3970 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3972 mono_loader_lock ();
3973 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3974 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3975 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3976 mono_loader_unlock ();
3978 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3981 * suspend_vm () could have missed this thread, so wait for a resume.
3987 thread_end (MonoProfiler *prof, uintptr_t tid)
3989 MonoInternalThread *thread;
3990 DebuggerTlsData *tls = NULL;
3992 mono_loader_lock ();
3993 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3995 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3996 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3998 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3999 tls->terminated = TRUE;
4000 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
4001 MONO_GC_UNREGISTER_ROOT (tls->thread);
4005 mono_loader_unlock ();
4007 /* We might be called for threads started before we registered the start callback */
4009 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
4010 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
4015 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
4017 mono_loader_lock ();
4018 g_hash_table_insert (domains, domain, domain);
4019 mono_loader_unlock ();
4021 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
4025 appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain)
4027 DebuggerTlsData *tls;
4030 * Remember the currently unloading appdomain as it is needed to generate
4031 * proper ids for unloading assemblies.
4033 tls = mono_native_tls_get_value (debugger_tls_id);
4035 tls->domain_unloading = domain;
4039 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
4041 DebuggerTlsData *tls;
4043 tls = mono_native_tls_get_value (debugger_tls_id);
4045 tls->domain_unloading = NULL;
4047 clear_breakpoints_for_domain (domain);
4049 mono_loader_lock ();
4050 /* Invalidate each thread's frame stack */
4051 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
4052 mono_loader_unlock ();
4054 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
4058 * invalidate_each_thread:
4060 * A GHFunc to invalidate frames.
4061 * value must be a DebuggerTlsData*
4064 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
4066 invalidate_frames (value);
4070 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
4072 /* Sent later in jit_end () */
4074 g_ptr_array_add (pending_assembly_loads, assembly);
4079 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
4081 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
4083 clear_event_requests_for_assembly (assembly);
4084 clear_types_for_assembly (assembly);
4088 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
4090 #if defined(HOST_WIN32) && !defined(__GNUC__)
4091 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
4093 gpointer stackptr = __builtin_frame_address (1);
4095 MonoInternalThread *thread = mono_thread_internal_current ();
4096 DebuggerTlsData *tls;
4098 mono_loader_lock ();
4100 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4101 /* Could be the debugger thread with assembly/type load hooks */
4103 tls->invoke_addr = stackptr;
4105 mono_loader_unlock ();
4109 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
4112 #if defined(HOST_WIN32) && !defined(__GNUC__)
4113 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
4115 gpointer stackptr = __builtin_frame_address (1);
4118 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
4122 * We need to stop single stepping when exiting a runtime invoke, since if it is
4123 * a step out, it may return to native code, and thus never end.
4125 mono_loader_lock ();
4126 ss_invoke_addr = NULL;
4128 for (i = 0; i < event_requests->len; ++i) {
4129 EventRequest *req = g_ptr_array_index (event_requests, i);
4131 if (req->event_kind == EVENT_KIND_STEP) {
4132 ss_destroy (req->info);
4133 g_ptr_array_remove_index_fast (event_requests, i);
4138 mono_loader_unlock ();
4142 send_type_load (MonoClass *klass)
4144 gboolean type_load = FALSE;
4145 MonoDomain *domain = mono_domain_get ();
4146 AgentDomainInfo *info = NULL;
4148 mono_loader_lock ();
4149 mono_domain_lock (domain);
4151 info = get_agent_domain_info (domain);
4153 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
4155 g_hash_table_insert (info->loaded_classes, klass, klass);
4158 mono_domain_unlock (domain);
4159 mono_loader_unlock ();
4161 emit_type_load (klass, klass, NULL);
4165 * Emit load events for all types currently loaded in the domain.
4166 * Takes the loader and domain locks.
4167 * user_data is unused.
4170 send_types_for_domain (MonoDomain *domain, void *user_data)
4172 AgentDomainInfo *info = NULL;
4174 mono_loader_lock ();
4175 mono_domain_lock (domain);
4176 info = get_agent_domain_info (domain);
4178 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4179 mono_domain_unlock (domain);
4180 mono_loader_unlock ();
4184 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
4187 * We emit type load events when the first method of the type is JITted,
4188 * since the class load profiler callbacks might be called with the
4189 * loader lock held. They could also occur in the debugger thread.
4190 * Same for assembly load events.
4193 MonoAssembly *assembly = NULL;
4195 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4197 if (pending_assembly_loads->len > 0) {
4198 assembly = g_ptr_array_index (pending_assembly_loads, 0);
4199 g_ptr_array_remove_index (pending_assembly_loads, 0);
4204 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4210 send_type_load (method->klass);
4213 add_pending_breakpoints (method, jinfo);
4217 * BREAKPOINTS/SINGLE STEPPING
4221 * Contains information about an inserted breakpoint.
4224 long il_offset, native_offset;
4229 } BreakpointInstance;
4232 * Contains generic information about a breakpoint.
4236 * The method where the breakpoint is placed. Can be NULL in which case it
4237 * is inserted into every method. This is used to implement method entry/
4238 * exit events. Can be a generic method definition, in which case the
4239 * breakpoint is inserted into every instance.
4245 * A list of BreakpointInstance structures describing where the breakpoint
4246 * was inserted. There could be more than one because of
4247 * generics/appdomains/method entry/exit.
4249 GPtrArray *children;
4252 /* List of breakpoints */
4253 static GPtrArray *breakpoints;
4254 /* Maps breakpoint locations to the number of breakpoints at that location */
4255 static GHashTable *bp_locs;
4258 breakpoints_init (void)
4260 breakpoints = g_ptr_array_new ();
4261 bp_locs = g_hash_table_new (NULL, NULL);
4265 * insert_breakpoint:
4267 * Insert the breakpoint described by BP into the method described by
4271 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4274 BreakpointInstance *inst;
4275 SeqPoint *sp = NULL;
4278 mono_error_init (error);
4280 for (i = 0; i < seq_points->len; ++i) {
4281 sp = &seq_points->seq_points [i];
4283 if (sp->il_offset == bp->il_offset)
4287 if (i == seq_points->len) {
4289 * The set of IL offsets with seq points doesn't completely match the
4290 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4292 for (i = 0; i < seq_points->len; ++i) {
4293 sp = &seq_points->seq_points [i];
4295 if (sp->il_offset != METHOD_ENTRY_IL_OFFSET && sp->il_offset != METHOD_EXIT_IL_OFFSET && sp->il_offset + 1 == bp->il_offset)
4300 if (i == seq_points->len) {
4301 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);
4303 for (i = 0; i < seq_points->len; ++i)
4304 DEBUG (1, fprintf (log_file, "%d\n", seq_points->seq_points [i].il_offset));
4307 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4308 g_warning ("%s", s);
4312 g_warning ("%s", s);
4318 inst = g_new0 (BreakpointInstance, 1);
4320 inst->native_offset = sp->native_offset;
4321 inst->ip = (guint8*)ji->code_start + sp->native_offset;
4323 inst->domain = domain;
4325 mono_loader_lock ();
4327 g_ptr_array_add (bp->children, inst);
4329 mono_loader_unlock ();
4332 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4333 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4336 if (sp->native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4337 DEBUG (1, fprintf (log_file, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset));
4338 } else if (count == 0) {
4339 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4340 mono_arch_set_breakpoint (ji, inst->ip);
4346 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));
4350 remove_breakpoint (BreakpointInstance *inst)
4352 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4354 MonoJitInfo *ji = inst->ji;
4355 guint8 *ip = inst->ip;
4358 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4359 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4362 g_assert (count > 0);
4364 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4365 mono_arch_clear_breakpoint (ji, ip);
4366 DEBUG(1, fprintf (log_file, "[dbg] Clear breakpoint at %s [%p].\n", mono_method_full_name (jinfo_get_method (ji), TRUE), ip));
4373 static inline gboolean
4374 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4380 if (method == bp->method)
4382 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4385 if (bp->method->is_inflated && method->is_inflated) {
4386 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4387 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4389 /* Open generic methods should match closed generic methods of the same class */
4390 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4391 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4392 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4394 /* FIXME: Handle !mvar */
4395 if (t1->type != MONO_TYPE_MVAR)
4406 * add_pending_breakpoints:
4408 * Insert pending breakpoints into the newly JITted method METHOD.
4411 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4414 MonoSeqPointInfo *seq_points;
4416 MonoMethod *jmethod;
4421 domain = mono_domain_get ();
4423 mono_loader_lock ();
4425 for (i = 0; i < breakpoints->len; ++i) {
4426 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4427 gboolean found = FALSE;
4429 if (!bp_matches_method (bp, method))
4432 for (j = 0; j < bp->children->len; ++j) {
4433 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4440 jmethod = jinfo_get_method (ji);
4441 mono_domain_lock (domain);
4442 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, jmethod);
4443 if (!seq_points && jmethod->is_inflated)
4444 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (jmethod));
4445 mono_domain_unlock (domain);
4447 /* Could be AOT code */
4449 g_assert (seq_points);
4451 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4455 mono_loader_unlock ();
4459 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4465 mono_error_init (error);
4467 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4469 /* Might be AOTed code */
4470 code = mono_aot_get_method (domain, method);
4472 ji = mono_jit_info_table_find (domain, code);
4477 insert_breakpoint (seq_points, domain, ji, bp, error);
4481 clear_breakpoint (MonoBreakpoint *bp);
4486 * Set a breakpoint at IL_OFFSET in METHOD.
4487 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4488 * METHOD can also be a generic method definition, in which case a breakpoint
4489 * is placed in all instances of the method.
4490 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4493 static MonoBreakpoint*
4494 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4497 GHashTableIter iter, iter2;
4500 MonoSeqPointInfo *seq_points;
4503 mono_error_init (error);
4506 // - suspend/resume the vm to prevent code patching problems
4507 // - multiple breakpoints on the same location
4508 // - dynamic methods
4511 bp = g_new0 (MonoBreakpoint, 1);
4512 bp->method = method;
4513 bp->il_offset = il_offset;
4515 bp->children = g_ptr_array_new ();
4517 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));
4519 mono_loader_lock ();
4521 g_hash_table_iter_init (&iter, domains);
4522 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4523 mono_domain_lock (domain);
4525 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4526 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4527 if (bp_matches_method (bp, m))
4528 set_bp_in_method (domain, m, seq_points, bp, error);
4531 mono_domain_unlock (domain);
4534 mono_loader_unlock ();
4536 mono_loader_lock ();
4537 g_ptr_array_add (breakpoints, bp);
4538 mono_loader_unlock ();
4540 if (error && !mono_error_ok (error)) {
4541 clear_breakpoint (bp);
4549 clear_breakpoint (MonoBreakpoint *bp)
4553 // FIXME: locking, races
4554 for (i = 0; i < bp->children->len; ++i) {
4555 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4557 remove_breakpoint (inst);
4562 mono_loader_lock ();
4563 g_ptr_array_remove (breakpoints, bp);
4564 mono_loader_unlock ();
4566 g_ptr_array_free (bp->children, TRUE);
4571 breakpoints_cleanup (void)
4575 mono_loader_lock ();
4577 while (i < event_requests->len) {
4578 EventRequest *req = g_ptr_array_index (event_requests, i);
4580 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4581 clear_breakpoint (req->info);
4582 g_ptr_array_remove_index_fast (event_requests, i);
4589 for (i = 0; i < breakpoints->len; ++i)
4590 g_free (g_ptr_array_index (breakpoints, i));
4592 g_ptr_array_free (breakpoints, TRUE);
4593 g_hash_table_destroy (bp_locs);
4598 mono_loader_unlock ();
4602 * clear_breakpoints_for_domain:
4604 * Clear breakpoint instances which reference DOMAIN.
4607 clear_breakpoints_for_domain (MonoDomain *domain)
4611 /* This could be called after shutdown */
4615 mono_loader_lock ();
4616 for (i = 0; i < breakpoints->len; ++i) {
4617 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4620 while (j < bp->children->len) {
4621 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4623 if (inst->domain == domain) {
4624 remove_breakpoint (inst);
4628 g_ptr_array_remove_index_fast (bp->children, j);
4634 mono_loader_unlock ();
4640 * Return FALSE if single stepping needs to continue.
4643 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp, DebuggerTlsData *tls, MonoContext *ctx)
4645 MonoDebugMethodInfo *minfo;
4646 MonoDebugSourceLocation *loc = NULL;
4647 gboolean hit = TRUE;
4650 if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK)) {
4652 * These seq points are inserted by the JIT after calls, step over needs to skip them.
4654 DEBUG (1, fprintf (log_file, "[%p] Seq point at nonempty stack %x while stepping over, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset));
4658 if (req->depth == STEP_DEPTH_OVER && hit) {
4659 if (!tls->context.valid)
4660 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4661 compute_frame_info (tls->thread, tls);
4662 if (req->nframes && tls->frame_count && tls->frame_count > req->nframes) {
4663 /* Hit the breakpoint in a recursive call */
4664 DEBUG (1, fprintf (log_file, "[%p] Breakpoint at lower frame while stepping over, continuing single stepping.\n", (gpointer)GetCurrentThreadId ()));
4669 if (req->size != STEP_SIZE_LINE)
4672 /* Have to check whenever a different source line was reached */
4673 method = jinfo_get_method (ji);
4674 minfo = mono_debug_lookup_method (method);
4677 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4679 if (!loc || (loc && method == ss_req->last_method && loc->row == ss_req->last_line)) {
4680 /* Have to continue single stepping */
4682 DEBUG(1, fprintf (log_file, "[%p] No line number info for il offset %x, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset));
4684 DEBUG(1, fprintf (log_file, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer)GetCurrentThreadId (), loc->row));
4689 ss_req->last_method = method;
4690 ss_req->last_line = loc->row;
4691 mono_debug_free_source_location (loc);
4698 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4700 return bp->method && bp->method->klass->image->assembly == assembly;
4704 process_breakpoint_inner (DebuggerTlsData *tls)
4708 int i, j, suspend_policy;
4709 guint32 native_offset;
4711 BreakpointInstance *inst;
4712 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4713 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4714 EventKind kind = EVENT_KIND_BREAKPOINT;
4715 MonoContext *ctx = &tls->restore_ctx;
4717 MonoSeqPointInfo *info;
4720 // FIXME: Speed this up
4722 ip = MONO_CONTEXT_GET_IP (ctx);
4723 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4725 method = jinfo_get_method (ji);
4727 /* Compute the native offset of the breakpoint from the ip */
4728 native_offset = ip - (guint8*)ji->code_start;
4731 * Skip the instruction causing the breakpoint signal.
4733 mono_arch_skip_breakpoint (ctx, ji);
4735 if (method->wrapper_type || tls->disable_breakpoints)
4738 bp_reqs = g_ptr_array_new ();
4739 ss_reqs = g_ptr_array_new ();
4740 ss_reqs_orig = g_ptr_array_new ();
4742 mono_loader_lock ();
4745 * The ip points to the instruction causing the breakpoint event, which is after
4746 * the offset recorded in the seq point map, so find the prev seq point before ip.
4748 sp = find_prev_seq_point_for_native_offset (mono_domain_get (), method, native_offset, &info);
4750 no_seq_points_found (method);
4753 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));
4756 for (i = 0; i < breakpoints->len; ++i) {
4757 bp = g_ptr_array_index (breakpoints, i);
4762 for (j = 0; j < bp->children->len; ++j) {
4763 inst = g_ptr_array_index (bp->children, j);
4764 if (inst->ji == ji && inst->sp == sp) {
4765 if (bp->req->event_kind == EVENT_KIND_STEP) {
4766 g_ptr_array_add (ss_reqs_orig, bp->req);
4768 g_ptr_array_add (bp_reqs, bp->req);
4773 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4774 /* Maybe a method entry/exit event */
4775 if (sp->il_offset == METHOD_ENTRY_IL_OFFSET)
4776 kind = EVENT_KIND_METHOD_ENTRY;
4777 else if (sp->il_offset == METHOD_EXIT_IL_OFFSET)
4778 kind = EVENT_KIND_METHOD_EXIT;
4781 /* Process single step requests */
4782 for (i = 0; i < ss_reqs_orig->len; ++i) {
4783 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4784 SingleStepReq *ss_req = req->info;
4787 if (mono_thread_internal_current () != ss_req->thread)
4790 hit = ss_update (ss_req, ji, sp, tls, ctx);
4792 g_ptr_array_add (ss_reqs, req);
4794 /* Start single stepping again from the current sequence point */
4795 ss_start (ss_req, method, sp, info, ctx, tls, FALSE);
4798 if (ss_reqs->len > 0)
4799 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4800 if (bp_reqs->len > 0)
4801 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4802 if (kind != EVENT_KIND_BREAKPOINT)
4803 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4805 mono_loader_unlock ();
4807 g_ptr_array_free (bp_reqs, TRUE);
4808 g_ptr_array_free (ss_reqs, TRUE);
4811 * FIXME: The first event will suspend, so the second will only be sent after the
4815 process_event (EVENT_KIND_STEP, method, 0, ctx, ss_events, suspend_policy);
4817 process_event (kind, method, 0, ctx, bp_events, suspend_policy);
4818 if (enter_leave_events)
4819 process_event (kind, method, 0, ctx, enter_leave_events, suspend_policy);
4822 /* Process a breakpoint/single step event after resuming from a signal handler */
4824 process_signal_event (void (*func) (DebuggerTlsData*))
4826 DebuggerTlsData *tls;
4827 MonoContext orig_restore_ctx, ctx;
4829 tls = mono_native_tls_get_value (debugger_tls_id);
4830 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4831 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4832 memcpy (&tls->restore_ctx, &tls->handler_ctx, sizeof (MonoContext));
4836 /* This is called when resuming from a signal handler, so it shouldn't return */
4837 memcpy (&ctx, &tls->restore_ctx, sizeof (MonoContext));
4838 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4839 mono_restore_context (&ctx);
4840 g_assert_not_reached ();
4844 process_breakpoint (void)
4846 process_signal_event (process_breakpoint_inner);
4850 resume_from_signal_handler (void *sigctx, void *func)
4852 DebuggerTlsData *tls;
4855 /* Save the original context in TLS */
4856 // FIXME: This might not work on an altstack ?
4857 tls = mono_native_tls_get_value (debugger_tls_id);
4859 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer)GetCurrentThreadId ());
4862 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4863 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4864 // clob:c could be added to op_seq_point.
4866 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4867 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4868 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4869 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4871 MONO_CONTEXT_SET_IP (&ctx, func);
4873 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4875 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4876 mono_ppc_set_func_into_sigctx (sigctx, func);
4881 mono_debugger_agent_breakpoint_hit (void *sigctx)
4884 * We are called from a signal handler, and running code there causes all kinds of
4885 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4886 * So set up the signal context to return to the real breakpoint handler function.
4888 resume_from_signal_handler (sigctx, process_breakpoint);
4892 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4894 if (frame->managed) {
4895 *(MonoContext*)data = *ctx;
4904 * Called by System.Diagnostics.Debugger:Break ().
4907 mono_debugger_agent_user_break (void)
4909 if (agent_config.enabled) {
4914 /* Obtain a context */
4915 MONO_CONTEXT_SET_IP (&ctx, NULL);
4916 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4917 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4919 mono_loader_lock ();
4920 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4921 mono_loader_unlock ();
4923 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4930 ss_depth_to_string (StepDepth depth)
4933 case STEP_DEPTH_OVER:
4935 case STEP_DEPTH_OUT:
4937 case STEP_DEPTH_INTO:
4940 g_assert_not_reached ();
4946 process_single_step_inner (DebuggerTlsData *tls)
4951 int il_offset, suspend_policy;
4954 MonoContext *ctx = &tls->restore_ctx;
4957 MonoSeqPointInfo *info;
4959 ip = MONO_CONTEXT_GET_IP (ctx);
4961 /* Skip the instruction causing the single step */
4962 mono_arch_skip_single_step (ctx);
4964 if (suspend_count > 0) {
4965 process_suspend (tls, ctx);
4970 // FIXME: A suspend race
4973 if (mono_thread_internal_current () != ss_req->thread)
4976 if (log_level > 0) {
4977 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4979 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));
4982 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4984 method = jinfo_get_method (ji);
4987 if (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4992 * Stopping in memset makes half-initialized vtypes visible.
4993 * Stopping in memcpy makes half-copied vtypes visible.
4995 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
4999 * The ip points to the instruction causing the single step event, which is before
5000 * the offset recorded in the seq point map, so find the next seq point after ip.
5002 sp = find_next_seq_point_for_native_offset (domain, method, (guint8*)ip - (guint8*)ji->code_start, &info);
5005 il_offset = sp->il_offset;
5007 if (!ss_update (ss_req, ji, sp, tls, ctx))
5010 /* Start single stepping again from the current sequence point */
5011 ss_start (ss_req, method, sp, info, ctx, tls, FALSE);
5013 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
5014 (method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
5015 !strcmp (method->name, ".cctor"))
5018 // FIXME: Has to lock earlier
5020 reqs = g_ptr_array_new ();
5022 mono_loader_lock ();
5024 g_ptr_array_add (reqs, ss_req->req);
5026 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
5028 g_ptr_array_free (reqs, TRUE);
5030 mono_loader_unlock ();
5032 process_event (EVENT_KIND_STEP, jinfo_get_method (ji), il_offset, ctx, events, suspend_policy);
5036 process_single_step (void)
5038 process_signal_event (process_single_step_inner);
5042 * mono_debugger_agent_single_step_event:
5044 * Called from a signal handler to handle a single step event.
5047 mono_debugger_agent_single_step_event (void *sigctx)
5049 /* Resume to process_single_step through the signal context */
5051 // FIXME: Since step out/over is implemented using step in, the step in case should
5052 // be as fast as possible. Move the relevant code from process_single_step_inner ()
5055 if (GetCurrentThreadId () == debugger_thread_id) {
5057 * This could happen despite our best effors when the runtime calls
5058 * assembly/type resolve hooks.
5059 * FIXME: Breakpoints too.
5063 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
5064 mono_arch_skip_single_step (&ctx);
5065 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
5069 resume_from_signal_handler (sigctx, process_single_step);
5073 debugger_agent_single_step_from_context (MonoContext *ctx)
5075 DebuggerTlsData *tls;
5076 MonoContext orig_restore_ctx;
5078 tls = mono_native_tls_get_value (debugger_tls_id);
5081 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
5082 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
5083 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
5085 process_single_step_inner (tls);
5087 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
5088 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
5092 debugger_agent_breakpoint_from_context (MonoContext *ctx)
5094 DebuggerTlsData *tls;
5095 MonoContext orig_restore_ctx;
5097 tls = mono_native_tls_get_value (debugger_tls_id);
5099 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
5100 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
5102 process_breakpoint_inner (tls);
5104 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
5105 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
5109 * start_single_stepping:
5111 * Turn on single stepping. Can be called multiple times, for example,
5112 * by a single step event request + a suspend.
5115 start_single_stepping (void)
5117 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5118 int val = InterlockedIncrement (&ss_count);
5121 mono_arch_start_single_stepping ();
5123 if (ss_req != NULL && ss_invoke_addr == NULL) {
5124 DebuggerTlsData *tls;
5126 mono_loader_lock ();
5128 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
5129 ss_invoke_addr = tls->invoke_addr;
5131 mono_loader_unlock ();
5134 g_assert_not_reached ();
5139 stop_single_stepping (void)
5141 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5142 int val = InterlockedDecrement (&ss_count);
5145 mono_arch_stop_single_stepping ();
5147 ss_invoke_addr = NULL;
5149 g_assert_not_reached ();
5156 * Stop the single stepping operation given by SS_REQ.
5159 ss_stop (SingleStepReq *ss_req)
5164 for (l = ss_req->bps; l; l = l->next) {
5165 clear_breakpoint (l->data);
5167 g_slist_free (ss_req->bps);
5171 if (ss_req->global) {
5172 stop_single_stepping ();
5173 ss_req->global = FALSE;
5180 * Start the single stepping operation given by SS_REQ from the sequence point SP.
5181 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
5182 * belong to the same thread as CTX.
5185 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
5187 int i, j, frame_index;
5190 gboolean enable_global = FALSE;
5192 /* Stop the previous operation */
5196 * Implement single stepping using breakpoints if possible.
5198 if (step_to_catch) {
5199 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
5200 ss_req->bps = g_slist_append (ss_req->bps, bp);
5204 if ((!sp || sp->next_len == 0 || ss_req->depth == STEP_DEPTH_OUT || ss_req->depth == STEP_DEPTH_OVER) && ctx) {
5205 /* Need parent frames */
5206 if (!tls->context.valid)
5207 mono_thread_state_init_from_monoctx (&tls->context, ctx);
5208 compute_frame_info (tls->thread, tls);
5212 * Find the first sequence point in the current or in a previous frame which
5213 * is not the last in its method.
5215 if (ss_req->depth == STEP_DEPTH_OUT) {
5216 /* Ignore seq points in current method */
5217 while (frame_index < tls->frame_count) {
5218 StackFrame *frame = tls->frames [frame_index];
5220 method = frame->method;
5221 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5223 if (sp && sp->next_len != 0)
5226 // There could be method calls before the next seq point in the caller when using nested calls
5227 //enable_global = TRUE;
5229 if (sp && sp->next_len == 0) {
5231 while (frame_index < tls->frame_count) {
5232 StackFrame *frame = tls->frames [frame_index];
5234 method = frame->method;
5235 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5236 if (sp && sp->next_len != 0)
5244 if (sp && sp->next_len > 0) {
5245 for (i = 0; i < sp->next_len; ++i) {
5246 next_sp = &info->seq_points [sp->next [i]];
5248 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
5249 ss_req->bps = g_slist_append (ss_req->bps, bp);
5253 if (ss_req->depth == STEP_DEPTH_OVER) {
5254 if (ss_req->nframes == 0)
5255 ss_req->nframes = tls->frame_count;
5256 /* Need to stop in catch clauses as well */
5257 for (i = 0; i < tls->frame_count; ++i) {
5258 StackFrame *frame = tls->frames [i];
5261 MonoJitInfo *jinfo = frame->ji;
5262 for (j = 0; j < jinfo->num_clauses; ++j) {
5263 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5265 sp = find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL);
5267 bp = set_breakpoint (frame->method, sp->il_offset, ss_req->req, NULL);
5268 ss_req->bps = g_slist_append (ss_req->bps, bp);
5276 if (ss_req->depth == STEP_DEPTH_INTO) {
5277 /* Enable global stepping so we stop at method entry too */
5278 enable_global = TRUE;
5282 * The ctx/frame info computed above will become invalid when we continue.
5284 tls->context.valid = FALSE;
5285 tls->async_state.valid = FALSE;
5286 invalidate_frames (tls);
5289 if (enable_global) {
5290 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
5291 ss_req->global = TRUE;
5292 start_single_stepping ();
5293 } else if (!ss_req->bps) {
5294 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
5295 ss_req->global = TRUE;
5296 start_single_stepping ();
5298 ss_req->global = FALSE;
5303 * Start single stepping of thread THREAD
5306 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
5308 DebuggerTlsData *tls;
5309 MonoSeqPointInfo *info = NULL;
5310 SeqPoint *sp = NULL;
5311 MonoMethod *method = NULL;
5312 MonoDebugMethodInfo *minfo;
5313 gboolean step_to_catch = FALSE;
5315 if (suspend_count == 0)
5316 return ERR_NOT_SUSPENDED;
5318 wait_for_suspend ();
5320 // FIXME: Multiple requests
5322 DEBUG (0, fprintf (log_file, "Received a single step request while the previous one was still active.\n"));
5323 return ERR_NOT_IMPLEMENTED;
5326 DEBUG (1, fprintf (log_file, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
5328 ss_req = g_new0 (SingleStepReq, 1);
5330 ss_req->thread = thread;
5331 ss_req->size = size;
5332 ss_req->depth = depth;
5335 mono_loader_lock ();
5336 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5337 mono_loader_unlock ();
5339 g_assert (tls->context.valid);
5340 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5342 if (tls->catch_state.valid) {
5344 StackFrameInfo frame;
5345 MonoContext new_ctx;
5346 MonoLMF *lmf = NULL;
5349 * We are stopped at a throw site. Stepping should go to the catch site.
5352 /* Find the the jit info for the catch context */
5353 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);
5355 g_assert (frame.type == FRAME_TYPE_MANAGED);
5358 * Find the seq point corresponding to the landing site ip, which is the first seq
5361 sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
5363 no_seq_points_found (frame.method);
5366 method = frame.method;
5368 step_to_catch = TRUE;
5369 /* This make sure the seq point is not skipped by process_single_step () */
5370 ss_req->last_sp = NULL;
5373 if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
5376 /* Compute the initial line info */
5377 compute_frame_info (thread, tls);
5379 if (tls->frame_count) {
5380 frame = tls->frames [0];
5382 ss_req->last_method = frame->method;
5383 ss_req->last_line = -1;
5385 minfo = mono_debug_lookup_method (frame->method);
5386 if (minfo && frame->il_offset != -1) {
5387 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
5390 ss_req->last_line = loc->row;
5397 if (!step_to_catch) {
5400 compute_frame_info (thread, tls);
5402 if (tls->frame_count) {
5403 frame = tls->frames [0];
5405 if (!method && frame->il_offset != -1) {
5406 /* FIXME: Sort the table and use a binary search */
5407 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5409 no_seq_points_found (frame->method);
5411 method = frame->method;
5416 ss_start (ss_req, method, sp, info, &tls->context.ctx, tls, step_to_catch);
5422 ss_destroy (SingleStepReq *req)
5425 g_assert (ss_req == req);
5434 ss_clear_for_assembly (SingleStepReq *req, MonoAssembly *assembly)
5437 gboolean found = TRUE;
5441 for (l = ss_req->bps; l; l = l->next) {
5442 if (breakpoint_matches_assembly (l->data, assembly)) {
5443 clear_breakpoint (l->data);
5444 ss_req->bps = g_slist_delete_link (ss_req->bps, l);
5453 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5456 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5462 if (!agent_config.enabled)
5465 mono_loader_lock ();
5466 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5467 mono_loader_unlock ();
5470 ei.category = category ? mono_string_to_utf8 (category) : NULL;
5471 ei.message = message ? mono_string_to_utf8 (message) : NULL;
5473 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5475 g_free (ei.category);
5476 g_free (ei.message);
5480 mono_debugger_agent_debug_log_is_enabled (void)
5482 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5483 return agent_config.enabled;
5486 #if defined(PLATFORM_ANDROID) || defined(TARGET_ANDROID)
5488 mono_debugger_agent_unhandled_exception (MonoException *exc)
5497 memset (&ei, 0, sizeof (EventInfo));
5498 ei.exc = (MonoObject*)exc;
5500 mono_loader_lock ();
5501 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5502 mono_loader_unlock ();
5504 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5509 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5510 MonoContext *catch_ctx)
5512 int i, j, suspend_policy;
5514 MonoJitInfo *ji, *catch_ji;
5516 DebuggerTlsData *tls = NULL;
5518 if (thread_to_tls != NULL) {
5519 MonoInternalThread *thread = mono_thread_internal_current ();
5521 mono_loader_lock ();
5522 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5523 mono_loader_unlock ();
5525 if (tls && tls->abort_requested)
5527 if (tls && tls->disable_breakpoints)
5531 memset (&ei, 0, sizeof (EventInfo));
5533 /* Just-In-Time debugging */
5535 if (agent_config.onuncaught && !inited) {
5536 finish_agent_init (FALSE);
5539 * Send an unsolicited EXCEPTION event with a dummy request id.
5541 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5542 ei.exc = (MonoObject*)exc;
5543 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5546 } else if (agent_config.onthrow && !inited) {
5548 gboolean found = FALSE;
5550 for (l = agent_config.onthrow; l; l = l->next) {
5551 char *ex_type = l->data;
5552 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5554 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5561 finish_agent_init (FALSE);
5564 * Send an unsolicited EXCEPTION event with a dummy request id.
5566 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5567 ei.exc = (MonoObject*)exc;
5568 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5576 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5578 catch_ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5582 ei.exc = (MonoObject*)exc;
5583 ei.caught = catch_ctx != NULL;
5585 mono_loader_lock ();
5587 /* Treat exceptions which are caught in non-user code as unhandled */
5588 for (i = 0; i < event_requests->len; ++i) {
5589 EventRequest *req = g_ptr_array_index (event_requests, i);
5590 if (req->event_kind != EVENT_KIND_EXCEPTION)
5593 for (j = 0; j < req->nmodifiers; ++j) {
5594 Modifier *mod = &req->modifiers [j];
5596 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5598 gboolean found = FALSE;
5599 MonoAssembly **assemblies = mod->data.assemblies;
5602 for (k = 0; assemblies [k]; ++k)
5603 if (assemblies [k] == jinfo_get_method (catch_ji)->klass->image->assembly)
5612 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5613 mono_loader_unlock ();
5615 if (tls && ei.caught && catch_ctx) {
5616 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5617 tls->catch_state.ctx = *catch_ctx;
5618 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5619 tls->catch_state.valid = TRUE;
5622 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5625 tls->catch_state.valid = FALSE;
5629 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5631 DebuggerTlsData *tls;
5636 tls = mono_native_tls_get_value (debugger_tls_id);
5641 * We're about to invoke an exception filter during the first pass of exception handling.
5643 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5644 * 'orig_ctx' is the context where the exception has been thrown.
5647 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5649 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5650 * the call site (line 37) and then continue to Main(), but it would never
5651 * include the throw site (line 32).
5653 * Since exception filters are invoked during the first pass of exception handling,
5654 * the stack frames of the throw site are still intact, so we should include them
5657 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5659 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5660 * but report the location of the 'throw' to the user.
5664 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5668 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5670 DebuggerTlsData *tls;
5675 tls = mono_native_tls_get_value (debugger_tls_id);
5679 tls->filter_state.valid = FALSE;
5683 * buffer_add_value_full:
5685 * Add the encoding of the value at ADDR described by T to the buffer.
5686 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5690 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5691 gboolean as_vtype, GHashTable *parent_vtypes)
5694 gboolean boxed_vtype = FALSE;
5697 if (!(*(void**)addr)) {
5698 /* This can happen with compiler generated locals */
5699 //printf ("%s\n", mono_type_full_name (t));
5700 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5703 g_assert (*(void**)addr);
5704 addr = *(void**)addr;
5709 case MONO_TYPE_BOOLEAN:
5712 case MONO_TYPE_CHAR:
5732 case MONO_TYPE_VOID:
5733 buffer_add_byte (buf, t->type);
5735 case MONO_TYPE_BOOLEAN:
5738 buffer_add_byte (buf, t->type);
5739 buffer_add_int (buf, *(gint8*)addr);
5741 case MONO_TYPE_CHAR:
5744 buffer_add_byte (buf, t->type);
5745 buffer_add_int (buf, *(gint16*)addr);
5750 buffer_add_byte (buf, t->type);
5751 buffer_add_int (buf, *(gint32*)addr);
5756 buffer_add_byte (buf, t->type);
5757 buffer_add_long (buf, *(gint64*)addr);
5761 /* Treat it as a vtype */
5763 case MONO_TYPE_PTR: {
5764 gssize val = *(gssize*)addr;
5766 buffer_add_byte (buf, t->type);
5767 buffer_add_long (buf, val);
5771 case MONO_TYPE_STRING:
5772 case MONO_TYPE_SZARRAY:
5773 case MONO_TYPE_OBJECT:
5774 case MONO_TYPE_CLASS:
5775 case MONO_TYPE_ARRAY:
5776 obj = *(MonoObject**)addr;
5779 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5781 if (obj->vtable->klass->valuetype) {
5782 t = &obj->vtable->klass->byval_arg;
5783 addr = mono_object_unbox (obj);
5786 } else if (obj->vtable->klass->rank) {
5787 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5788 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5789 buffer_add_byte (buf, MONO_TYPE_CLASS);
5791 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5793 buffer_add_objid (buf, obj);
5797 case MONO_TYPE_VALUETYPE: {
5801 MonoClass *klass = mono_class_from_mono_type (t);
5806 * Handle boxed vtypes recursively referencing themselves using fields.
5809 parent_vtypes = g_hash_table_new (NULL, NULL);
5810 vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
5812 if (CHECK_PROTOCOL_VERSION (2, 33)) {
5813 buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
5814 buffer_add_int (buf, vtype_index - 1);
5816 /* The client can't handle PARENT_VTYPE */
5817 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5821 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
5825 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5826 buffer_add_byte (buf, klass->enumtype);
5827 buffer_add_typeid (buf, domain, klass);
5831 while ((f = mono_class_get_fields (klass, &iter))) {
5832 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5834 if (mono_field_is_deleted (f))
5838 buffer_add_int (buf, nfields);
5841 while ((f = mono_class_get_fields (klass, &iter))) {
5842 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5844 if (mono_field_is_deleted (f))
5846 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE, parent_vtypes);
5850 g_hash_table_remove (parent_vtypes, addr);
5851 if (g_hash_table_size (parent_vtypes) == 0) {
5852 g_hash_table_destroy (parent_vtypes);
5853 parent_vtypes = NULL;
5858 case MONO_TYPE_GENERICINST:
5859 if (mono_type_generic_inst_is_valuetype (t)) {
5871 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5873 buffer_add_value_full (buf, t, addr, domain, FALSE, NULL);
5877 obj_is_of_type (MonoObject *obj, MonoType *t)
5879 MonoClass *klass = obj->vtable->klass;
5880 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5881 if (mono_class_is_transparent_proxy (klass)) {
5882 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5883 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5893 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5896 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5902 gpointer iter = NULL;
5906 is_enum = decode_byte (buf, &buf, limit);
5907 /* Enums are sent as a normal vtype */
5909 return ERR_NOT_IMPLEMENTED;
5910 klass = decode_typeid (buf, &buf, limit, &d, &err);
5914 if (t && klass != mono_class_from_mono_type (t)) {
5915 char *name = mono_type_full_name (t);
5916 char *name2 = mono_type_full_name (&klass->byval_arg);
5917 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got %s.\n", (gpointer)GetCurrentThreadId (), name, name2));
5920 return ERR_INVALID_ARGUMENT;
5923 nfields = decode_int (buf, &buf, limit);
5924 while ((f = mono_class_get_fields (klass, &iter))) {
5925 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5927 if (mono_field_is_deleted (f))
5929 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5934 g_assert (nfields == 0);
5942 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5946 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5947 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5948 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5949 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5950 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
5951 char *name = mono_type_full_name (t);
5952 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5954 return ERR_INVALID_ARGUMENT;
5958 case MONO_TYPE_BOOLEAN:
5959 *(guint8*)addr = decode_int (buf, &buf, limit);
5961 case MONO_TYPE_CHAR:
5962 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5965 *(gint8*)addr = decode_int (buf, &buf, limit);
5968 *(guint8*)addr = decode_int (buf, &buf, limit);
5971 *(gint16*)addr = decode_int (buf, &buf, limit);
5974 *(guint16*)addr = decode_int (buf, &buf, limit);
5977 *(gint32*)addr = decode_int (buf, &buf, limit);
5980 *(guint32*)addr = decode_int (buf, &buf, limit);
5983 *(gint64*)addr = decode_long (buf, &buf, limit);
5986 *(guint64*)addr = decode_long (buf, &buf, limit);
5989 *(guint32*)addr = decode_int (buf, &buf, limit);
5992 *(guint64*)addr = decode_long (buf, &buf, limit);
5995 /* We send these as I8, so we get them back as such */
5996 g_assert (type == MONO_TYPE_I8);
5997 *(gssize*)addr = decode_long (buf, &buf, limit);
5999 case MONO_TYPE_GENERICINST:
6000 if (MONO_TYPE_ISSTRUCT (t)) {
6001 /* The client sends these as a valuetype */
6009 /* We send these as vtypes, so we get them back as such */
6010 g_assert (type == MONO_TYPE_VALUETYPE);
6013 case MONO_TYPE_VALUETYPE:
6014 err = decode_vtype (t, domain, addr,buf, &buf, limit);
6020 if (MONO_TYPE_IS_REFERENCE (t)) {
6021 if (type == MONO_TYPE_OBJECT) {
6022 int objid = decode_objid (buf, &buf, limit);
6026 err = get_object (objid, (MonoObject**)&obj);
6031 if (!obj_is_of_type (obj, t)) {
6032 DEBUG (1, fprintf (log_file, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name));
6033 return ERR_INVALID_ARGUMENT;
6036 if (obj && obj->vtable->domain != domain)
6037 return ERR_INVALID_ARGUMENT;
6039 mono_gc_wbarrier_generic_store (addr, obj);
6040 } else if (type == VALUE_TYPE_ID_NULL) {
6041 *(MonoObject**)addr = NULL;
6042 } else if (type == MONO_TYPE_VALUETYPE) {
6050 /* This can happen when round-tripping boxed vtypes */
6052 * Obtain vtype class.
6053 * Same as the beginning of the handle_vtype case above.
6056 is_enum = decode_byte (buf, &buf, limit);
6058 return ERR_NOT_IMPLEMENTED;
6059 klass = decode_typeid (buf, &buf, limit, &d, &err);
6063 /* Decode the vtype into a temporary buffer, then box it. */
6064 vtype_buf_size = mono_class_value_size (klass, NULL);
6065 vtype_buf = g_malloc0 (vtype_buf_size);
6066 g_assert (vtype_buf);
6069 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
6074 *(MonoObject**)addr = mono_value_box (d, klass, vtype_buf);
6077 char *name = mono_type_full_name (t);
6078 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
6080 return ERR_INVALID_ARGUMENT;
6094 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6097 int type = decode_byte (buf, &buf, limit);
6099 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
6100 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
6101 guint8 *nullable_buf;
6104 * First try decoding it as a Nullable`1
6106 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6111 * Then try decoding as a primitive value or null.
6113 if (targ->type == type) {
6114 nullable_buf = g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
6115 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
6117 g_free (nullable_buf);
6120 mono_nullable_init (addr, mono_value_box (domain, mono_class_from_mono_type (targ), nullable_buf), mono_class_from_mono_type (t));
6121 g_free (nullable_buf);
6124 } else if (type == VALUE_TYPE_ID_NULL) {
6125 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
6131 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6135 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
6139 guint8 *addr, *gaddr;
6142 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6143 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6146 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
6147 reg_val = mono_arch_context_get_int_reg (ctx, reg);
6149 buffer_add_value_full (buf, t, ®_val, domain, as_vtype, NULL);
6151 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6152 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6153 addr += (gint32)var->offset;
6155 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6157 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6159 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6162 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6163 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
6164 /* Same as regoffset, but with an indirection */
6165 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6166 addr += (gint32)var->offset;
6168 gaddr = *(gpointer*)addr;
6170 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL);
6172 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
6173 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
6174 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
6175 MonoGSharedVtMethodRuntimeInfo *info;
6181 g_assert (info_var);
6182 g_assert (locals_var);
6184 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6185 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6186 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6187 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6188 addr += (gint32)info_var->offset;
6189 info = *(gpointer*)addr;
6190 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6191 info = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6193 g_assert_not_reached ();
6197 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6198 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6199 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6200 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6201 addr += (gint32)locals_var->offset;
6202 locals = *(gpointer*)addr;
6203 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6204 locals = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6206 g_assert_not_reached ();
6210 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6212 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6217 g_assert_not_reached ();
6222 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
6226 guint8 *addr, *gaddr;
6228 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6229 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6231 if (MONO_TYPE_IS_REFERENCE (t))
6232 size = sizeof (gpointer);
6234 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6237 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6238 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6240 gboolean is_signed = FALSE;
6243 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6246 // FIXME: Write barriers
6247 mono_gc_memmove_atomic (addr, val, size);
6252 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6257 v = is_signed ? *(gint8*)val : *(guint8*)val;
6260 v = is_signed ? *(gint16*)val : *(guint16*)val;
6263 v = is_signed ? *(gint32*)val : *(guint32*)val;
6266 v = is_signed ? *(gint64*)val : *(guint64*)val;
6269 g_assert_not_reached ();
6272 /* Set value on the stack or in the return ctx */
6273 if (reg_locations [reg]) {
6274 /* Saved on the stack */
6275 DEBUG (1, fprintf (log_file, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v));
6276 *(reg_locations [reg]) = v;
6279 DEBUG (1, fprintf (log_file, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v));
6280 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6283 // FIXME: Move these to mono-context.h/c.
6284 mono_arch_context_set_int_reg (ctx, reg, v);
6286 // FIXME: Can't set registers, so we disable linears
6291 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6292 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6293 addr += (gint32)var->offset;
6295 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6298 addr = *(guint8**)addr;
6304 // FIXME: Write barriers
6305 mono_gc_memmove_atomic (addr, val, size);
6307 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6308 /* Same as regoffset, but with an indirection */
6309 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6310 addr += (gint32)var->offset;
6312 gaddr = *(gpointer*)addr;
6314 // FIXME: Write barriers
6315 mono_gc_memmove_atomic (gaddr, val, size);
6317 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6321 g_assert_not_reached ();
6326 clear_event_request (int req_id, int etype)
6330 mono_loader_lock ();
6331 for (i = 0; i < event_requests->len; ++i) {
6332 EventRequest *req = g_ptr_array_index (event_requests, i);
6334 if (req->id == req_id && req->event_kind == etype) {
6335 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6336 clear_breakpoint (req->info);
6337 if (req->event_kind == EVENT_KIND_STEP)
6338 ss_destroy (req->info);
6339 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6340 clear_breakpoint (req->info);
6341 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6342 clear_breakpoint (req->info);
6343 g_ptr_array_remove_index_fast (event_requests, i);
6348 mono_loader_unlock ();
6352 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
6356 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6357 m->kind = MOD_KIND_NONE;
6358 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6359 int count = 0, match_count = 0, pos;
6360 MonoAssembly **newassemblies;
6362 for (i = 0; m->data.assemblies [i]; ++i) {
6364 if (m->data.assemblies [i] == assembly)
6369 newassemblies = g_new0 (MonoAssembly*, count - match_count);
6372 for (i = 0; i < count; ++i)
6373 if (m->data.assemblies [i] != assembly)
6374 newassemblies [pos ++] = m->data.assemblies [i];
6375 g_assert (pos == count - match_count);
6376 g_free (m->data.assemblies);
6377 m->data.assemblies = newassemblies;
6383 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
6387 for (i = 0; i < req->nmodifiers; ++i) {
6388 Modifier *m = &req->modifiers [i];
6390 clear_assembly_from_modifier (req, m, assembly);
6395 * clear_event_requests_for_assembly:
6397 * Clear all events requests which reference ASSEMBLY.
6400 clear_event_requests_for_assembly (MonoAssembly *assembly)
6405 mono_loader_lock ();
6409 for (i = 0; i < event_requests->len; ++i) {
6410 EventRequest *req = g_ptr_array_index (event_requests, i);
6412 clear_assembly_from_modifiers (req, assembly);
6414 if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly (req->info, assembly)) {
6415 clear_event_request (req->id, req->event_kind);
6420 if (req->event_kind == EVENT_KIND_STEP)
6421 ss_clear_for_assembly (req->info, assembly);
6424 mono_loader_unlock ();
6428 * type_comes_from_assembly:
6430 * GHRFunc that returns TRUE if klass comes from assembly
6433 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6435 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6439 * clear_types_for_assembly:
6441 * Clears types from loaded_classes for a given assembly
6444 clear_types_for_assembly (MonoAssembly *assembly)
6446 MonoDomain *domain = mono_domain_get ();
6447 AgentDomainInfo *info = NULL;
6449 mono_loader_lock ();
6450 info = get_agent_domain_info (domain);
6451 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6452 mono_loader_unlock ();
6456 add_thread (gpointer key, gpointer value, gpointer user_data)
6458 MonoInternalThread *thread = value;
6459 Buffer *buf = user_data;
6461 buffer_add_objid (buf, (MonoObject*)thread);
6465 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6467 guint8 *end = invoke->endp;
6470 MonoMethodSignature *sig;
6473 MonoObject *this, *res, *exc;
6476 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6479 MonoStopwatch watch;
6481 if (invoke->method) {
6483 * Invoke this method directly, currently only Environment.Exit () is supported.
6486 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>"));
6487 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
6488 g_assert_not_reached ();
6491 m = decode_methodid (p, &p, end, &domain, &err);
6494 sig = mono_method_signature (m);
6496 if (m->klass->valuetype)
6497 this_buf = g_alloca (mono_class_instance_size (m->klass));
6499 this_buf = g_alloca (sizeof (MonoObject*));
6500 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6501 /* Should be null */
6502 int type = decode_byte (p, &p, end);
6503 if (type != VALUE_TYPE_ID_NULL) {
6504 DEBUG (1, fprintf (log_file, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer)GetCurrentThreadId ()));
6505 return ERR_INVALID_ARGUMENT;
6507 memset (this_buf, 0, mono_class_instance_size (m->klass));
6509 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6514 if (!m->klass->valuetype)
6515 this = *(MonoObject**)this_buf;
6519 if (MONO_CLASS_IS_INTERFACE (m->klass)) {
6521 DEBUG (1, fprintf (log_file, "[%p] Error: Interface method invoked without this argument.\n", (gpointer)GetCurrentThreadId ()));
6522 return ERR_INVALID_ARGUMENT;
6524 m = mono_object_get_virtual_method (this, m);
6527 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>"));
6529 if (this && this->vtable->domain != domain)
6532 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
6533 if (!strcmp (m->name, ".ctor")) {
6534 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
6535 return ERR_INVALID_ARGUMENT;
6537 this = mono_object_new (domain, m->klass);
6539 return ERR_INVALID_ARGUMENT;
6543 if (this && !obj_is_of_type (this, &m->klass->byval_arg))
6544 return ERR_INVALID_ARGUMENT;
6546 nargs = decode_int (p, &p, end);
6547 if (nargs != sig->param_count)
6548 return ERR_INVALID_ARGUMENT;
6549 /* Use alloca to get gc tracking */
6550 arg_buf = g_alloca (nargs * sizeof (gpointer));
6551 memset (arg_buf, 0, nargs * sizeof (gpointer));
6552 args = g_alloca (nargs * sizeof (gpointer));
6553 for (i = 0; i < nargs; ++i) {
6554 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6555 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6559 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6562 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6563 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6566 args [i] = arg_buf [i];
6573 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6574 tls->disable_breakpoints = TRUE;
6576 tls->disable_breakpoints = FALSE;
6579 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6581 /* FIXME: Move this to arch specific code */
6582 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6583 if (invoke->has_ctx) {
6586 lmf_addr = mono_get_lmf_addr ();
6589 memset (&ext, 0, sizeof (ext));
6590 mono_arch_init_lmf_ext (&ext, *lmf_addr);
6592 ext.debugger_invoke = TRUE;
6593 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6595 mono_set_lmf ((MonoLMF*)&ext);
6599 mono_stopwatch_start (&watch);
6600 if (m->klass->valuetype)
6601 res = mono_runtime_invoke (m, this_buf, args, &exc);
6603 res = mono_runtime_invoke (m, this, args, &exc);
6604 mono_stopwatch_stop (&watch);
6605 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)));
6607 buffer_add_byte (buf, 0);
6608 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6610 buffer_add_byte (buf, 1);
6611 if (sig->ret->type == MONO_TYPE_VOID) {
6612 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
6613 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
6616 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6617 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6618 buffer_add_value (buf, sig->ret, &res, domain);
6619 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6620 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6621 MonoClass *k = mono_class_from_mono_type (sig->ret);
6622 guint8 *nullable_buf = g_alloca (mono_class_value_size (k, NULL));
6624 g_assert (nullable_buf);
6625 mono_nullable_init (nullable_buf, res, k);
6626 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6629 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6636 tls->disable_breakpoints = FALSE;
6638 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6639 if (invoke->has_ctx)
6640 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
6644 // FIXME: byref arguments
6652 * Invoke the method given by tls->pending_invoke in the current thread.
6655 invoke_method (void)
6657 DebuggerTlsData *tls;
6662 MonoContext restore_ctx;
6665 tls = mono_native_tls_get_value (debugger_tls_id);
6669 * Store the `InvokeData *' in `tls->invoke' until we're done with
6670 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6673 mono_loader_lock ();
6675 invoke = tls->pending_invoke;
6677 tls->pending_invoke = NULL;
6679 invoke->last_invoke = tls->invoke;
6680 tls->invoke = invoke;
6682 mono_loader_unlock ();
6684 tls->frames_up_to_date = FALSE;
6690 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6691 buffer_init (&buf, 128);
6694 /* Fail the other invokes as well */
6696 err = do_invoke_method (tls, &buf, invoke, p, &p);
6699 /* Start suspending before sending the reply */
6700 if (mindex == invoke->nmethods - 1) {
6701 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6702 for (i = 0; i < invoke->suspend_count; ++i)
6707 send_reply_packet (id, err, &buf);
6712 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6714 if (invoke->has_ctx)
6715 save_thread_context (&restore_ctx);
6717 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6718 g_assert (tls->resume_count);
6719 tls->resume_count -= invoke->suspend_count;
6722 DEBUG (1, fprintf (log_file, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer)GetCurrentThreadId (), err, tls->resume_count));
6725 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6727 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
6728 * after the mono_runtime_invoke() already returned, but it doesn't matter
6729 * because we reset the abort here.
6732 mono_loader_lock ();
6734 if (tls->abort_requested)
6735 mono_thread_internal_reset_abort (tls->thread);
6737 tls->invoke = tls->invoke->last_invoke;
6738 tls->abort_requested = FALSE;
6740 mono_loader_unlock ();
6749 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6751 MonoThread *thread = value;
6752 DebuggerTlsData *tls;
6755 mono_loader_lock ();
6756 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6758 res = tls->really_suspended;
6759 mono_loader_unlock ();
6765 get_source_files_for_type (MonoClass *klass)
6767 gpointer iter = NULL;
6769 MonoDebugSourceInfo *sinfo;
6773 files = g_ptr_array_new ();
6775 while ((method = mono_class_get_methods (klass, &iter))) {
6776 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6777 GPtrArray *source_file_list;
6780 mono_debug_symfile_get_line_numbers_full (minfo, NULL, &source_file_list, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
6781 for (j = 0; j < source_file_list->len; ++j) {
6782 sinfo = g_ptr_array_index (source_file_list, j);
6783 for (i = 0; i < files->len; ++i)
6784 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6786 if (i == files->len)
6787 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6789 g_ptr_array_free (source_file_list, TRUE);
6797 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6800 case CMD_VM_VERSION: {
6801 char *build_info, *version;
6803 build_info = mono_get_runtime_build_info ();
6804 version = g_strdup_printf ("mono %s", build_info);
6806 buffer_add_string (buf, version); /* vm version */
6807 buffer_add_int (buf, MAJOR_VERSION);
6808 buffer_add_int (buf, MINOR_VERSION);
6809 g_free (build_info);
6813 case CMD_VM_SET_PROTOCOL_VERSION: {
6814 major_version = decode_int (p, &p, end);
6815 minor_version = decode_int (p, &p, end);
6816 protocol_version_set = TRUE;
6817 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
6820 case CMD_VM_ALL_THREADS: {
6822 mono_loader_lock ();
6823 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6824 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6825 mono_loader_unlock ();
6828 case CMD_VM_SUSPEND:
6830 wait_for_suspend ();
6833 if (suspend_count == 0)
6834 return ERR_NOT_SUSPENDED;
6836 clear_suspended_objs ();
6838 case CMD_VM_DISPOSE:
6839 /* Clear all event requests */
6840 mono_loader_lock ();
6841 while (event_requests->len > 0) {
6842 EventRequest *req = g_ptr_array_index (event_requests, 0);
6844 clear_event_request (req->id, req->event_kind);
6846 mono_loader_unlock ();
6848 while (suspend_count > 0)
6850 disconnected = TRUE;
6851 vm_start_event_sent = FALSE;
6854 MonoInternalThread *thread;
6855 DebuggerTlsData *tls;
6856 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6857 MonoClass *env_class;
6859 MonoMethod *exit_method = NULL;
6863 exit_code = decode_int (p, &p, end);
6865 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6867 /* Have to send a reply before exiting */
6868 send_reply_packet (id, 0, buf);
6870 /* Clear all event requests */
6871 mono_loader_lock ();
6872 while (event_requests->len > 0) {
6873 EventRequest *req = g_ptr_array_index (event_requests, 0);
6875 clear_event_request (req->id, req->event_kind);
6877 mono_loader_unlock ();
6880 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6881 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6882 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6883 * better than doing the shutdown ourselves, since it avoids various races.
6887 wait_for_suspend ();
6889 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6890 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
6892 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6895 mono_loader_lock ();
6896 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6897 mono_loader_unlock ();
6899 if (thread && exit_method) {
6900 mono_loader_lock ();
6901 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6902 mono_loader_unlock ();
6904 args = g_new0 (gpointer, 1);
6905 args [0] = g_malloc (sizeof (int));
6906 *(int*)(args [0]) = exit_code;
6908 tls->pending_invoke = g_new0 (InvokeData, 1);
6909 tls->pending_invoke->method = exit_method;
6910 tls->pending_invoke->args = args;
6911 tls->pending_invoke->nmethods = 1;
6913 while (suspend_count > 0)
6917 * No thread found, do it ourselves.
6918 * FIXME: This can race with normal shutdown etc.
6920 while (suspend_count > 0)
6923 if (!mono_runtime_try_shutdown ())
6926 mono_environment_exitcode_set (exit_code);
6928 /* Suspend all managed threads since the runtime is going away */
6929 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
6930 mono_thread_suspend_all_other_threads ();
6931 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
6932 mono_runtime_quit ();
6933 transport_close2 ();
6934 DEBUG(1, fprintf (log_file, "Exiting...\n"));
6940 case CMD_VM_INVOKE_METHOD:
6941 case CMD_VM_INVOKE_METHODS: {
6942 int objid = decode_objid (p, &p, end);
6944 DebuggerTlsData *tls;
6945 int i, count, err, flags, nmethods;
6947 err = get_object (objid, (MonoObject**)&thread);
6951 flags = decode_int (p, &p, end);
6953 if (command == CMD_VM_INVOKE_METHODS)
6954 nmethods = decode_int (p, &p, end);
6958 // Wait for suspending if it already started
6960 wait_for_suspend ();
6961 if (!is_suspended ())
6962 return ERR_NOT_SUSPENDED;
6964 mono_loader_lock ();
6965 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6966 mono_loader_unlock ();
6969 if (!tls->really_suspended)
6970 /* The thread is still running native code, can't do invokes */
6971 return ERR_NOT_SUSPENDED;
6974 * Store the invoke data into tls, the thread will execute it after it is
6977 if (tls->pending_invoke)
6978 return ERR_NOT_SUSPENDED;
6979 tls->pending_invoke = g_new0 (InvokeData, 1);
6980 tls->pending_invoke->id = id;
6981 tls->pending_invoke->flags = flags;
6982 tls->pending_invoke->p = g_malloc (end - p);
6983 memcpy (tls->pending_invoke->p, p, end - p);
6984 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
6985 tls->pending_invoke->suspend_count = suspend_count;
6986 tls->pending_invoke->nmethods = nmethods;
6988 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
6989 resume_thread (THREAD_TO_INTERNAL (thread));
6992 count = suspend_count;
6993 for (i = 0; i < count; ++i)
6998 case CMD_VM_ABORT_INVOKE: {
6999 int objid = decode_objid (p, &p, end);
7001 DebuggerTlsData *tls;
7004 err = get_object (objid, (MonoObject**)&thread);
7008 invoke_id = decode_int (p, &p, end);
7010 mono_loader_lock ();
7011 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7014 if (tls->abort_requested) {
7015 mono_loader_unlock ();
7020 * Check whether we're still inside the mono_runtime_invoke() and that it's
7021 * actually the correct invocation.
7023 * Careful, we do not stop the thread that's doing the invocation, so we can't
7024 * inspect its stack. However, invoke_method() also acquires the loader lock
7025 * when it's done, so we're safe here.
7029 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
7030 mono_loader_unlock ();
7031 return ERR_NO_INVOCATION;
7034 tls->abort_requested = TRUE;
7036 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
7037 mono_loader_unlock ();
7041 case CMD_VM_SET_KEEPALIVE: {
7042 int timeout = decode_int (p, &p, end);
7043 agent_config.keepalive = timeout;
7045 #ifndef DISABLE_SOCKET_TRANSPORT
7052 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
7053 GHashTableIter iter, kiter;
7058 char *fname, *basename;
7059 gboolean ignore_case;
7060 GSList *class_list, *l;
7061 GPtrArray *res_classes, *res_domains;
7063 fname = decode_string (p, &p, end);
7064 ignore_case = decode_byte (p, &p, end);
7066 basename = g_path_get_basename (fname);
7068 res_classes = g_ptr_array_new ();
7069 res_domains = g_ptr_array_new ();
7071 mono_loader_lock ();
7072 g_hash_table_iter_init (&iter, domains);
7073 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7074 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
7076 /* Update 'source_file_to_class' cache */
7077 g_hash_table_iter_init (&kiter, info->loaded_classes);
7078 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
7079 if (!g_hash_table_lookup (info->source_files, klass)) {
7080 files = get_source_files_for_type (klass);
7081 g_hash_table_insert (info->source_files, klass, files);
7083 for (i = 0; i < files->len; ++i) {
7084 char *s = g_ptr_array_index (files, i);
7085 char *s2 = g_path_get_basename (s);
7088 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
7090 class_list = g_slist_prepend (class_list, klass);
7091 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
7093 class_list = g_slist_prepend (class_list, klass);
7094 g_hash_table_insert (info->source_file_to_class, s2, class_list);
7097 /* The _ignorecase hash contains the lowercase path */
7098 s3 = strdup_tolower (s2);
7099 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
7101 class_list = g_slist_prepend (class_list, klass);
7102 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
7104 class_list = g_slist_prepend (class_list, klass);
7105 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
7117 s = strdup_tolower (basename);
7118 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
7121 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
7124 for (l = class_list; l; l = l->next) {
7127 g_ptr_array_add (res_classes, klass);
7128 g_ptr_array_add (res_domains, domain);
7131 mono_loader_unlock ();
7136 buffer_add_int (buf, res_classes->len);
7137 for (i = 0; i < res_classes->len; ++i)
7138 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
7139 g_ptr_array_free (res_classes, TRUE);
7140 g_ptr_array_free (res_domains, TRUE);
7143 case CMD_VM_GET_TYPES: {
7144 GHashTableIter iter;
7148 gboolean ignore_case;
7149 GPtrArray *res_classes, *res_domains;
7150 MonoTypeNameParse info;
7152 name = decode_string (p, &p, end);
7153 ignore_case = decode_byte (p, &p, end);
7155 if (!mono_reflection_parse_type (name, &info)) {
7157 mono_reflection_free_type_info (&info);
7158 return ERR_INVALID_ARGUMENT;
7161 res_classes = g_ptr_array_new ();
7162 res_domains = g_ptr_array_new ();
7164 mono_loader_lock ();
7165 g_hash_table_iter_init (&iter, domains);
7166 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7168 gboolean type_resolve;
7172 mono_domain_assemblies_lock (domain);
7173 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7177 type_resolve = TRUE;
7178 t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
7180 g_ptr_array_add (res_classes, mono_type_get_class (t));
7181 g_ptr_array_add (res_domains, domain);
7185 mono_domain_assemblies_unlock (domain);
7187 mono_loader_unlock ();
7190 mono_reflection_free_type_info (&info);
7192 buffer_add_int (buf, res_classes->len);
7193 for (i = 0; i < res_classes->len; ++i)
7194 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
7195 g_ptr_array_free (res_classes, TRUE);
7196 g_ptr_array_free (res_domains, TRUE);
7199 case CMD_VM_START_BUFFERING:
7200 case CMD_VM_STOP_BUFFERING:
7201 /* Handled in the main loop */
7204 return ERR_NOT_IMPLEMENTED;
7211 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7217 case CMD_EVENT_REQUEST_SET: {
7219 int i, event_kind, suspend_policy, nmodifiers, mod;
7222 MonoThread *step_thread;
7223 int size = 0, depth = 0, filter = 0, step_thread_id = 0;
7227 event_kind = decode_byte (p, &p, end);
7228 suspend_policy = decode_byte (p, &p, end);
7229 nmodifiers = decode_byte (p, &p, end);
7231 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7232 req->id = InterlockedIncrement (&event_request_id);
7233 req->event_kind = event_kind;
7234 req->suspend_policy = suspend_policy;
7235 req->nmodifiers = nmodifiers;
7238 for (i = 0; i < nmodifiers; ++i) {
7239 mod = decode_byte (p, &p, end);
7241 req->modifiers [i].kind = mod;
7242 if (mod == MOD_KIND_COUNT) {
7243 req->modifiers [i].data.count = decode_int (p, &p, end);
7244 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7245 method = decode_methodid (p, &p, end, &domain, &err);
7248 location = decode_long (p, &p, end);
7249 } else if (mod == MOD_KIND_STEP) {
7250 step_thread_id = decode_id (p, &p, end);
7251 size = decode_int (p, &p, end);
7252 depth = decode_int (p, &p, end);
7253 if (CHECK_PROTOCOL_VERSION (2, 16))
7254 filter = decode_int (p, &p, end);
7255 req->modifiers [i].data.filter = filter;
7256 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7257 /* Treat STEP_THOUGH the same as HIDDEN */
7258 req->modifiers [i].data.filter |= STEP_FILTER_DEBUGGER_STEP_THROUGH;
7259 } else if (mod == MOD_KIND_THREAD_ONLY) {
7260 int id = decode_id (p, &p, end);
7262 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7267 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7268 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7272 req->modifiers [i].caught = decode_byte (p, &p, end);
7273 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7274 if (CHECK_PROTOCOL_VERSION (2, 25))
7275 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7277 req->modifiers [i].subclasses = TRUE;
7278 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" : ""));
7280 req->modifiers [i].data.exc_class = exc_class;
7282 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
7284 return ERR_INVALID_ARGUMENT;
7287 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7288 int n = decode_int (p, &p, end);
7291 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
7292 for (j = 0; j < n; ++j) {
7293 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7295 g_free (req->modifiers [i].data.assemblies);
7299 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7300 int n = decode_int (p, &p, end);
7303 modifier = &req->modifiers [i];
7304 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7305 for (j = 0; j < n; ++j) {
7306 char *s = decode_string (p, &p, end);
7310 s2 = strdup_tolower (s);
7311 g_hash_table_insert (modifier->data.source_files, s2, s2);
7315 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7316 int n = decode_int (p, &p, end);
7319 modifier = &req->modifiers [i];
7320 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7321 for (j = 0; j < n; ++j) {
7322 char *s = decode_string (p, &p, end);
7325 g_hash_table_insert (modifier->data.type_names, s, s);
7329 return ERR_NOT_IMPLEMENTED;
7333 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7336 req->info = set_breakpoint (method, location, req, &error);
7337 if (!mono_error_ok (&error)) {
7339 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
7340 mono_error_cleanup (&error);
7341 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7343 } else if (req->event_kind == EVENT_KIND_STEP) {
7344 g_assert (step_thread_id);
7346 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7352 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
7357 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7358 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7359 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7360 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7361 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7362 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7364 if (req->nmodifiers) {
7366 return ERR_NOT_IMPLEMENTED;
7370 mono_loader_lock ();
7371 g_ptr_array_add (event_requests, req);
7373 if (agent_config.defer) {
7374 /* Transmit cached data to the client on receipt of the event request */
7375 switch (req->event_kind) {
7376 case EVENT_KIND_APPDOMAIN_CREATE:
7377 /* Emit load events for currently loaded domains */
7378 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7380 case EVENT_KIND_ASSEMBLY_LOAD:
7381 /* Emit load events for currently loaded assemblies */
7382 mono_assembly_foreach (emit_assembly_load, NULL);
7384 case EVENT_KIND_THREAD_START:
7385 /* Emit start events for currently started threads */
7386 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7388 case EVENT_KIND_TYPE_LOAD:
7389 /* Emit type load events for currently loaded types */
7390 mono_domain_foreach (send_types_for_domain, NULL);
7396 mono_loader_unlock ();
7398 buffer_add_int (buf, req->id);
7401 case CMD_EVENT_REQUEST_CLEAR: {
7402 int etype = decode_byte (p, &p, end);
7403 int req_id = decode_int (p, &p, end);
7405 // FIXME: Make a faster mapping from req_id to request
7406 mono_loader_lock ();
7407 clear_event_request (req_id, etype);
7408 mono_loader_unlock ();
7411 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7414 mono_loader_lock ();
7416 while (i < event_requests->len) {
7417 EventRequest *req = g_ptr_array_index (event_requests, i);
7419 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7420 clear_breakpoint (req->info);
7422 g_ptr_array_remove_index_fast (event_requests, i);
7428 mono_loader_unlock ();
7432 return ERR_NOT_IMPLEMENTED;
7439 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7445 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7446 buffer_add_domainid (buf, mono_get_root_domain ());
7449 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7450 domain = decode_domainid (p, &p, end, NULL, &err);
7453 buffer_add_string (buf, domain->friendly_name);
7456 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7461 domain = decode_domainid (p, &p, end, NULL, &err);
7464 mono_loader_lock ();
7466 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7469 buffer_add_int (buf, count);
7470 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7472 buffer_add_assemblyid (buf, domain, ass);
7474 mono_loader_unlock ();
7477 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7478 domain = decode_domainid (p, &p, end, NULL, &err);
7482 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7485 case CMD_APPDOMAIN_GET_CORLIB: {
7486 domain = decode_domainid (p, &p, end, NULL, &err);
7490 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7493 case CMD_APPDOMAIN_CREATE_STRING: {
7497 domain = decode_domainid (p, &p, end, NULL, &err);
7500 s = decode_string (p, &p, end);
7502 o = mono_string_new (domain, s);
7503 buffer_add_objid (buf, (MonoObject*)o);
7506 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7508 MonoDomain *domain2;
7511 domain = decode_domainid (p, &p, end, NULL, &err);
7514 klass = decode_typeid (p, &p, end, &domain2, &err);
7519 g_assert (domain == domain2);
7521 o = mono_object_new (domain, klass);
7523 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
7527 buffer_add_objid (buf, o);
7531 return ERR_NOT_IMPLEMENTED;
7538 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7544 ass = decode_assemblyid (p, &p, end, &domain, &err);
7549 case CMD_ASSEMBLY_GET_LOCATION: {
7550 buffer_add_string (buf, mono_image_get_filename (ass->image));
7553 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7557 if (ass->image->dynamic) {
7558 buffer_add_id (buf, 0);
7560 token = mono_image_get_entry_point (ass->image);
7562 buffer_add_id (buf, 0);
7564 m = mono_get_method (ass->image, token, NULL);
7565 buffer_add_methodid (buf, domain, m);
7570 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7571 buffer_add_moduleid (buf, domain, ass->image);
7574 case CMD_ASSEMBLY_GET_OBJECT: {
7575 MonoObject *o = (MonoObject*)mono_assembly_get_object (domain, ass);
7576 buffer_add_objid (buf, o);
7579 case CMD_ASSEMBLY_GET_TYPE: {
7580 char *s = decode_string (p, &p, end);
7581 gboolean ignorecase = decode_byte (p, &p, end);
7582 MonoTypeNameParse info;
7584 gboolean type_resolve, res;
7585 MonoDomain *d = mono_domain_get ();
7587 /* This is needed to be able to find referenced assemblies */
7588 res = mono_domain_set (domain, FALSE);
7591 if (!mono_reflection_parse_type (s, &info)) {
7594 if (info.assembly.name)
7596 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
7598 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
7599 mono_reflection_free_type_info (&info);
7602 mono_domain_set (d, TRUE);
7606 case CMD_ASSEMBLY_GET_NAME: {
7608 MonoAssembly *mass = ass;
7610 name = g_strdup_printf (
7611 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7613 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7614 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7615 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7616 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7618 buffer_add_string (buf, name);
7623 return ERR_NOT_IMPLEMENTED;
7630 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7636 case CMD_MODULE_GET_INFO: {
7637 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7640 basename = g_path_get_basename (image->name);
7641 buffer_add_string (buf, basename); // name
7642 buffer_add_string (buf, image->module_name); // scopename
7643 buffer_add_string (buf, image->name); // fqname
7644 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7645 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7650 return ERR_NOT_IMPLEMENTED;
7657 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7663 case CMD_FIELD_GET_INFO: {
7664 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
7666 buffer_add_string (buf, f->name);
7667 buffer_add_typeid (buf, domain, f->parent);
7668 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7669 buffer_add_int (buf, f->type->attrs);
7673 return ERR_NOT_IMPLEMENTED;
7680 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7682 if (val && val->vtable->klass == mono_defaults.monotype_class) {
7683 /* Special case these so the client doesn't have to handle Type objects */
7685 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7686 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7687 } else if (MONO_TYPE_IS_REFERENCE (t))
7688 buffer_add_value (buf, t, &val, domain);
7690 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7694 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7700 buffer_add_int (buf, 0);
7704 for (i = 0; i < cinfo->num_attrs; ++i) {
7705 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7708 buffer_add_int (buf, nattrs);
7710 for (i = 0; i < cinfo->num_attrs; ++i) {
7711 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7712 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7713 MonoArray *typed_args, *named_args;
7715 CattrNamedArg *arginfo = NULL;
7718 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
7719 g_assert (mono_error_ok (&error));
7721 buffer_add_methodid (buf, domain, attr->ctor);
7725 buffer_add_int (buf, mono_array_length (typed_args));
7726 for (j = 0; j < mono_array_length (typed_args); ++j) {
7727 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7729 t = mono_method_signature (attr->ctor)->params [j];
7731 buffer_add_cattr_arg (buf, t, domain, val);
7734 buffer_add_int (buf, 0);
7739 buffer_add_int (buf, mono_array_length (named_args));
7741 for (j = 0; j < mono_array_length (named_args); ++j) {
7742 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7744 if (arginfo [j].prop) {
7745 buffer_add_byte (buf, 0x54);
7746 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7747 } else if (arginfo [j].field) {
7748 buffer_add_byte (buf, 0x53);
7749 buffer_add_fieldid (buf, domain, arginfo [j].field);
7751 g_assert_not_reached ();
7754 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7757 buffer_add_int (buf, 0);
7764 /* FIXME: Code duplication with icall.c */
7766 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7771 mono_class_setup_interfaces (klass, error);
7772 if (!mono_error_ok (error))
7775 for (i = 0; i < klass->interface_count; i++) {
7776 ic = klass->interfaces [i];
7777 g_hash_table_insert (ifaces, ic, ic);
7779 collect_interfaces (ic, ifaces, error);
7780 if (!mono_error_ok (error))
7786 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7796 case CMD_TYPE_GET_INFO: {
7797 buffer_add_string (buf, klass->name_space);
7798 buffer_add_string (buf, klass->name);
7800 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7801 buffer_add_string (buf, name);
7803 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7804 buffer_add_moduleid (buf, domain, klass->image);
7805 buffer_add_typeid (buf, domain, klass->parent);
7806 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7807 buffer_add_typeid (buf, domain, klass->element_class);
7809 buffer_add_id (buf, 0);
7810 buffer_add_int (buf, klass->type_token);
7811 buffer_add_byte (buf, klass->rank);
7812 buffer_add_int (buf, klass->flags);
7814 type = &klass->byval_arg;
7815 // FIXME: Can't decide whenever a class represents a byref type
7818 if (type->type == MONO_TYPE_PTR)
7820 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7822 if (type->type == MONO_TYPE_VALUETYPE)
7824 if (klass->enumtype)
7826 if (klass->generic_container)
7828 if (klass->generic_container || klass->generic_class)
7830 buffer_add_byte (buf, b);
7833 while ((nested = mono_class_get_nested_types (klass, &iter)))
7835 buffer_add_int (buf, nnested);
7837 while ((nested = mono_class_get_nested_types (klass, &iter)))
7838 buffer_add_typeid (buf, domain, nested);
7839 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7840 if (klass->generic_container)
7841 buffer_add_typeid (buf, domain, klass);
7842 else if (klass->generic_class)
7843 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7845 buffer_add_id (buf, 0);
7847 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7850 if (klass->generic_class) {
7851 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7853 count = inst->type_argc;
7854 buffer_add_int (buf, count);
7855 for (i = 0; i < count; i++)
7856 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7857 } else if (klass->generic_container) {
7858 MonoGenericContainer *container = klass->generic_container;
7861 count = container->type_argc;
7862 buffer_add_int (buf, count);
7863 for (i = 0; i < count; i++) {
7864 pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
7865 buffer_add_typeid (buf, domain, pklass);
7868 buffer_add_int (buf, 0);
7873 case CMD_TYPE_GET_METHODS: {
7876 gpointer iter = NULL;
7879 mono_class_setup_methods (klass);
7881 nmethods = mono_class_num_methods (klass);
7883 buffer_add_int (buf, nmethods);
7885 while ((m = mono_class_get_methods (klass, &iter))) {
7886 buffer_add_methodid (buf, domain, m);
7889 g_assert (i == nmethods);
7892 case CMD_TYPE_GET_FIELDS: {
7895 gpointer iter = NULL;
7898 nfields = mono_class_num_fields (klass);
7900 buffer_add_int (buf, nfields);
7902 while ((f = mono_class_get_fields (klass, &iter))) {
7903 buffer_add_fieldid (buf, domain, f);
7904 buffer_add_string (buf, f->name);
7905 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7906 buffer_add_int (buf, f->type->attrs);
7909 g_assert (i == nfields);
7912 case CMD_TYPE_GET_PROPERTIES: {
7915 gpointer iter = NULL;
7918 nprops = mono_class_num_properties (klass);
7920 buffer_add_int (buf, nprops);
7922 while ((p = mono_class_get_properties (klass, &iter))) {
7923 buffer_add_propertyid (buf, domain, p);
7924 buffer_add_string (buf, p->name);
7925 buffer_add_methodid (buf, domain, p->get);
7926 buffer_add_methodid (buf, domain, p->set);
7927 buffer_add_int (buf, p->attrs);
7930 g_assert (i == nprops);
7933 case CMD_TYPE_GET_CATTRS: {
7934 MonoClass *attr_klass;
7935 MonoCustomAttrInfo *cinfo;
7937 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7938 /* attr_klass can be NULL */
7942 cinfo = mono_custom_attrs_from_class (klass);
7944 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7947 case CMD_TYPE_GET_FIELD_CATTRS: {
7948 MonoClass *attr_klass;
7949 MonoCustomAttrInfo *cinfo;
7950 MonoClassField *field;
7952 field = decode_fieldid (p, &p, end, NULL, &err);
7955 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7959 cinfo = mono_custom_attrs_from_field (klass, field);
7961 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7964 case CMD_TYPE_GET_PROPERTY_CATTRS: {
7965 MonoClass *attr_klass;
7966 MonoCustomAttrInfo *cinfo;
7969 prop = decode_propertyid (p, &p, end, NULL, &err);
7972 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7976 cinfo = mono_custom_attrs_from_property (klass, prop);
7978 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7981 case CMD_TYPE_GET_VALUES:
7982 case CMD_TYPE_GET_VALUES_2: {
7989 MonoThread *thread_obj;
7990 MonoInternalThread *thread = NULL;
7991 guint32 special_static_type;
7993 if (command == CMD_TYPE_GET_VALUES_2) {
7994 int objid = decode_objid (p, &p, end);
7997 err = get_object (objid, (MonoObject**)&thread_obj);
8001 thread = THREAD_TO_INTERNAL (thread_obj);
8004 len = decode_int (p, &p, end);
8005 for (i = 0; i < len; ++i) {
8006 f = decode_fieldid (p, &p, end, NULL, &err);
8010 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8011 return ERR_INVALID_FIELDID;
8012 special_static_type = mono_class_field_get_special_static_type (f);
8013 if (special_static_type != SPECIAL_STATIC_NONE) {
8014 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
8015 return ERR_INVALID_FIELDID;
8018 /* Check that the field belongs to the object */
8020 for (k = klass; k; k = k->parent) {
8021 if (k == f->parent) {
8027 return ERR_INVALID_FIELDID;
8029 vtable = mono_class_vtable (domain, f->parent);
8030 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8031 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
8032 buffer_add_value (buf, f->type, val, domain);
8037 case CMD_TYPE_SET_VALUES: {
8045 len = decode_int (p, &p, end);
8046 for (i = 0; i < len; ++i) {
8047 f = decode_fieldid (p, &p, end, NULL, &err);
8051 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8052 return ERR_INVALID_FIELDID;
8053 if (mono_class_field_is_special_static (f))
8054 return ERR_INVALID_FIELDID;
8056 /* Check that the field belongs to the object */
8058 for (k = klass; k; k = k->parent) {
8059 if (k == f->parent) {
8065 return ERR_INVALID_FIELDID;
8067 // FIXME: Check for literal/const
8069 vtable = mono_class_vtable (domain, f->parent);
8070 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8071 err = decode_value (f->type, domain, val, p, &p, end);
8076 if (MONO_TYPE_IS_REFERENCE (f->type))
8077 mono_field_static_set_value (vtable, f, *(gpointer*)val);
8079 mono_field_static_set_value (vtable, f, val);
8084 case CMD_TYPE_GET_OBJECT: {
8085 MonoObject *o = (MonoObject*)mono_type_get_object (domain, &klass->byval_arg);
8086 buffer_add_objid (buf, o);
8089 case CMD_TYPE_GET_SOURCE_FILES:
8090 case CMD_TYPE_GET_SOURCE_FILES_2: {
8091 char *source_file, *base;
8095 files = get_source_files_for_type (klass);
8097 buffer_add_int (buf, files->len);
8098 for (i = 0; i < files->len; ++i) {
8099 source_file = g_ptr_array_index (files, i);
8100 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8101 buffer_add_string (buf, source_file);
8103 base = g_path_get_basename (source_file);
8104 buffer_add_string (buf, base);
8107 g_free (source_file);
8109 g_ptr_array_free (files, TRUE);
8112 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8113 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8117 if (mono_class_is_assignable_from (klass, oklass))
8118 buffer_add_byte (buf, 1);
8120 buffer_add_byte (buf, 0);
8123 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8124 char *name = decode_string (p, &p, end);
8125 int i, flags = decode_int (p, &p, end);
8126 MonoException *ex = NULL;
8127 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
8130 return ERR_LOADER_ERROR;
8131 buffer_add_int (buf, array->len);
8132 for (i = 0; i < array->len; ++i) {
8133 MonoMethod *method = g_ptr_array_index (array, i);
8134 buffer_add_methodid (buf, domain, method);
8137 g_ptr_array_free (array, TRUE);
8141 case CMD_TYPE_GET_INTERFACES: {
8143 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8145 MonoClass *tclass, *iface;
8146 GHashTableIter iter;
8150 for (parent = tclass; parent; parent = parent->parent) {
8151 mono_class_setup_interfaces (parent, &error);
8152 if (!mono_error_ok (&error))
8153 return ERR_LOADER_ERROR;
8154 collect_interfaces (parent, iface_hash, &error);
8155 if (!mono_error_ok (&error))
8156 return ERR_LOADER_ERROR;
8159 buffer_add_int (buf, g_hash_table_size (iface_hash));
8161 g_hash_table_iter_init (&iter, iface_hash);
8162 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8163 buffer_add_typeid (buf, domain, iface);
8164 g_hash_table_destroy (iface_hash);
8167 case CMD_TYPE_GET_INTERFACE_MAP: {
8168 int tindex, ioffset;
8169 gboolean variance_used;
8171 int len, nmethods, i;
8175 len = decode_int (p, &p, end);
8176 mono_class_setup_vtable (klass);
8178 for (tindex = 0; tindex < len; ++tindex) {
8179 iclass = decode_typeid (p, &p, end, NULL, &err);
8183 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8185 return ERR_INVALID_ARGUMENT;
8187 nmethods = mono_class_num_methods (iclass);
8188 buffer_add_int (buf, nmethods);
8191 while ((method = mono_class_get_methods (iclass, &iter))) {
8192 buffer_add_methodid (buf, domain, method);
8194 for (i = 0; i < nmethods; ++i)
8195 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
8199 case CMD_TYPE_IS_INITIALIZED: {
8200 MonoVTable *vtable = mono_class_vtable (domain, klass);
8203 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8205 buffer_add_int (buf, 0);
8208 case CMD_TYPE_CREATE_INSTANCE: {
8211 obj = mono_object_new (domain, klass);
8212 buffer_add_objid (buf, obj);
8216 return ERR_NOT_IMPLEMENTED;
8223 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8226 MonoDomain *old_domain;
8230 klass = decode_typeid (p, &p, end, &domain, &err);
8234 old_domain = mono_domain_get ();
8236 mono_domain_set (domain, TRUE);
8238 err = type_commands_internal (command, klass, domain, p, end, buf);
8240 mono_domain_set (old_domain, TRUE);
8246 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8248 MonoMethodHeader *header;
8252 case CMD_METHOD_GET_NAME: {
8253 buffer_add_string (buf, method->name);
8256 case CMD_METHOD_GET_DECLARING_TYPE: {
8257 buffer_add_typeid (buf, domain, method->klass);
8260 case CMD_METHOD_GET_DEBUG_INFO: {
8261 MonoDebugMethodInfo *minfo;
8263 int i, j, n_il_offsets;
8266 int *column_numbers;
8267 int *end_line_numbers;
8268 int *end_column_numbers;
8270 GPtrArray *source_file_list;
8272 header = mono_method_get_header (method);
8274 buffer_add_int (buf, 0);
8275 buffer_add_string (buf, "");
8276 buffer_add_int (buf, 0);
8280 minfo = mono_debug_lookup_method (method);
8282 buffer_add_int (buf, header->code_size);
8283 buffer_add_string (buf, "");
8284 buffer_add_int (buf, 0);
8285 mono_metadata_free_mh (header);
8289 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);
8290 buffer_add_int (buf, header->code_size);
8291 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8292 buffer_add_int (buf, source_file_list->len);
8293 for (i = 0; i < source_file_list->len; ++i) {
8294 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
8295 buffer_add_string (buf, sinfo->source_file);
8296 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8297 for (j = 0; j < 16; ++j)
8298 buffer_add_byte (buf, sinfo->hash [j]);
8302 buffer_add_string (buf, source_file);
8304 buffer_add_int (buf, n_il_offsets);
8305 DEBUG (10, fprintf (log_file, "Line number table for method %s:\n", mono_method_full_name (method, TRUE)));
8306 for (i = 0; i < n_il_offsets; ++i) {
8307 const char *srcfile = "";
8309 if (source_files [i] != -1) {
8310 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
8311 srcfile = sinfo->source_file;
8313 DEBUG (10, fprintf (log_file, "IL%x -> %s:%d %d\n", il_offsets [i], srcfile, line_numbers [i], column_numbers ? column_numbers [i] : -1));
8314 buffer_add_int (buf, il_offsets [i]);
8315 buffer_add_int (buf, line_numbers [i]);
8316 if (CHECK_PROTOCOL_VERSION (2, 13))
8317 buffer_add_int (buf, source_files [i]);
8318 if (CHECK_PROTOCOL_VERSION (2, 19))
8319 buffer_add_int (buf, column_numbers ? column_numbers [i] : -1);
8320 if (CHECK_PROTOCOL_VERSION (2, 32)) {
8321 buffer_add_int (buf, end_line_numbers ? end_line_numbers [i] : -1);
8322 buffer_add_int (buf, end_column_numbers ? end_column_numbers [i] : -1);
8325 g_free (source_file);
8326 g_free (il_offsets);
8327 g_free (line_numbers);
8328 g_free (column_numbers);
8329 g_free (end_line_numbers);
8330 g_free (end_column_numbers);
8331 g_free (source_files);
8332 g_ptr_array_free (source_file_list, TRUE);
8333 mono_metadata_free_mh (header);
8336 case CMD_METHOD_GET_PARAM_INFO: {
8337 MonoMethodSignature *sig = mono_method_signature (method);
8341 /* FIXME: mono_class_from_mono_type () and byrefs */
8343 /* FIXME: Use a smaller encoding */
8344 buffer_add_int (buf, sig->call_convention);
8345 buffer_add_int (buf, sig->param_count);
8346 buffer_add_int (buf, sig->generic_param_count);
8347 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
8348 for (i = 0; i < sig->param_count; ++i) {
8350 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
8353 /* Emit parameter names */
8354 names = g_new (char *, sig->param_count);
8355 mono_method_get_param_names (method, (const char **) names);
8356 for (i = 0; i < sig->param_count; ++i)
8357 buffer_add_string (buf, names [i]);
8362 case CMD_METHOD_GET_LOCALS_INFO: {
8363 int i, j, num_locals;
8364 MonoDebugLocalsInfo *locals;
8366 header = mono_method_get_header (method);
8368 return ERR_INVALID_ARGUMENT;
8370 buffer_add_int (buf, header->num_locals);
8373 for (i = 0; i < header->num_locals; ++i)
8374 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
8377 locals = mono_debug_lookup_locals (method);
8379 num_locals = locals->num_locals;
8382 for (i = 0; i < header->num_locals; ++i) {
8383 for (j = 0; j < num_locals; ++j)
8384 if (locals->locals [j].index == i)
8387 buffer_add_string (buf, locals->locals [j].name);
8389 buffer_add_string (buf, "");
8393 for (i = 0; i < header->num_locals; ++i) {
8394 for (j = 0; j < num_locals; ++j)
8395 if (locals->locals [j].index == i)
8397 if (j < num_locals && locals->locals [j].block) {
8398 buffer_add_int (buf, locals->locals [j].block->start_offset);
8399 buffer_add_int (buf, locals->locals [j].block->end_offset);
8401 buffer_add_int (buf, 0);
8402 buffer_add_int (buf, header->code_size);
8405 mono_metadata_free_mh (header);
8408 mono_debug_symfile_free_locals (locals);
8412 case CMD_METHOD_GET_INFO:
8413 buffer_add_int (buf, method->flags);
8414 buffer_add_int (buf, method->iflags);
8415 buffer_add_int (buf, method->token);
8416 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8418 if (method->is_generic)
8420 if (mono_method_signature (method)->generic_param_count)
8422 buffer_add_byte (buf, attrs);
8423 if (method->is_generic || method->is_inflated) {
8426 if (method->is_generic) {
8429 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8431 result = imethod->declaring;
8432 if (imethod->context.class_inst) {
8433 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8434 /*Generic methods gets the context of the GTD.*/
8435 if (mono_class_get_context (klass))
8436 result = mono_class_inflate_generic_method_full (result, klass, mono_class_get_context (klass));
8440 buffer_add_methodid (buf, domain, result);
8442 buffer_add_id (buf, 0);
8444 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8445 if (mono_method_signature (method)->generic_param_count) {
8448 if (method->is_inflated) {
8449 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
8451 count = inst->type_argc;
8452 buffer_add_int (buf, count);
8454 for (i = 0; i < count; i++)
8455 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8457 buffer_add_int (buf, 0);
8459 } else if (method->is_generic) {
8460 MonoGenericContainer *container = mono_method_get_generic_container (method);
8462 count = mono_method_signature (method)->generic_param_count;
8463 buffer_add_int (buf, count);
8464 for (i = 0; i < count; i++) {
8465 MonoGenericParam *param = mono_generic_container_get_param (container, i);
8466 MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
8467 buffer_add_typeid (buf, domain, pklass);
8470 buffer_add_int (buf, 0);
8473 buffer_add_int (buf, 0);
8478 case CMD_METHOD_GET_BODY: {
8481 header = mono_method_get_header (method);
8483 buffer_add_int (buf, 0);
8485 if (CHECK_PROTOCOL_VERSION (2, 18))
8486 buffer_add_int (buf, 0);
8488 buffer_add_int (buf, header->code_size);
8489 for (i = 0; i < header->code_size; ++i)
8490 buffer_add_byte (buf, header->code [i]);
8492 if (CHECK_PROTOCOL_VERSION (2, 18)) {
8493 buffer_add_int (buf, header->num_clauses);
8494 for (i = 0; i < header->num_clauses; ++i) {
8495 MonoExceptionClause *clause = &header->clauses [i];
8497 buffer_add_int (buf, clause->flags);
8498 buffer_add_int (buf, clause->try_offset);
8499 buffer_add_int (buf, clause->try_len);
8500 buffer_add_int (buf, clause->handler_offset);
8501 buffer_add_int (buf, clause->handler_len);
8502 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
8503 buffer_add_typeid (buf, domain, clause->data.catch_class);
8504 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8505 buffer_add_int (buf, clause->data.filter_offset);
8509 mono_metadata_free_mh (header);
8514 case CMD_METHOD_RESOLVE_TOKEN: {
8515 guint32 token = decode_int (p, &p, end);
8518 switch (mono_metadata_token_code (token)) {
8519 case MONO_TOKEN_STRING: {
8523 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
8526 s2 = mono_string_to_utf8 (s);
8528 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8529 buffer_add_string (buf, s2);
8535 MonoClass *handle_class;
8537 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8538 val = mono_method_get_wrapper_data (method, token);
8539 handle_class = mono_method_get_wrapper_data (method, token + 1);
8541 if (handle_class == NULL) {
8542 // Can't figure out the token type
8543 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8547 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
8551 if (handle_class == mono_defaults.typehandle_class) {
8552 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8553 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8554 buffer_add_typeid (buf, domain, (MonoClass *) val);
8556 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
8557 } else if (handle_class == mono_defaults.fieldhandle_class) {
8558 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8559 buffer_add_fieldid (buf, domain, val);
8560 } else if (handle_class == mono_defaults.methodhandle_class) {
8561 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8562 buffer_add_methodid (buf, domain, val);
8563 } else if (handle_class == mono_defaults.string_class) {
8566 s = mono_string_to_utf8 (val);
8567 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8568 buffer_add_string (buf, s);
8571 g_assert_not_reached ();
8578 case CMD_METHOD_GET_CATTRS: {
8579 MonoClass *attr_klass;
8580 MonoCustomAttrInfo *cinfo;
8582 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8583 /* attr_klass can be NULL */
8587 cinfo = mono_custom_attrs_from_method (method);
8589 buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
8592 case CMD_METHOD_MAKE_GENERIC_METHOD: {
8593 MonoType **type_argv;
8597 MonoGenericInst *ginst;
8598 MonoGenericContext tmp_context;
8599 MonoMethod *inflated;
8601 type_argc = decode_int (p, &p, end);
8602 type_argv = g_new0 (MonoType*, type_argc);
8603 for (i = 0; i < type_argc; ++i) {
8604 klass = decode_typeid (p, &p, end, &d, &err);
8611 return ERR_INVALID_ARGUMENT;
8613 type_argv [i] = &klass->byval_arg;
8615 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
8617 tmp_context.class_inst = method->klass->generic_class ? method->klass->generic_class->context.class_inst : NULL;
8618 tmp_context.method_inst = ginst;
8620 inflated = mono_class_inflate_generic_method (method, &tmp_context);
8621 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
8622 return ERR_INVALID_ARGUMENT;
8623 buffer_add_methodid (buf, domain, inflated);
8627 return ERR_NOT_IMPLEMENTED;
8634 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8637 MonoDomain *old_domain;
8641 method = decode_methodid (p, &p, end, &domain, &err);
8645 old_domain = mono_domain_get ();
8647 mono_domain_set (domain, TRUE);
8649 err = method_commands_internal (command, method, domain, p, end, buf);
8651 mono_domain_set (old_domain, TRUE);
8657 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8659 int objid = decode_objid (p, &p, end);
8661 MonoThread *thread_obj;
8662 MonoInternalThread *thread;
8664 err = get_object (objid, (MonoObject**)&thread_obj);
8668 thread = THREAD_TO_INTERNAL (thread_obj);
8671 case CMD_THREAD_GET_NAME: {
8673 gunichar2 *s = mono_thread_get_name (thread, &name_len);
8676 buffer_add_int (buf, 0);
8681 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
8683 buffer_add_int (buf, len);
8684 buffer_add_data (buf, (guint8*)name, len);
8689 case CMD_THREAD_GET_FRAME_INFO: {
8690 DebuggerTlsData *tls;
8691 int i, start_frame, length;
8693 // Wait for suspending if it already started
8694 // FIXME: Races with suspend_count
8695 while (!is_suspended ()) {
8697 wait_for_suspend ();
8701 wait_for_suspend ();
8702 if (!is_suspended ())
8703 return ERR_NOT_SUSPENDED;
8706 start_frame = decode_int (p, &p, end);
8707 length = decode_int (p, &p, end);
8709 if (start_frame != 0 || length != -1)
8710 return ERR_NOT_IMPLEMENTED;
8712 mono_loader_lock ();
8713 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8714 mono_loader_unlock ();
8717 compute_frame_info (thread, tls);
8719 buffer_add_int (buf, tls->frame_count);
8720 for (i = 0; i < tls->frame_count; ++i) {
8721 buffer_add_int (buf, tls->frames [i]->id);
8722 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
8723 buffer_add_int (buf, tls->frames [i]->il_offset);
8725 * Instead of passing the frame type directly to the client, we associate
8726 * it with the previous frame using a set of flags. This avoids lots of
8727 * conditional code in the client, since a frame whose type isn't
8728 * FRAME_TYPE_MANAGED has no method, location, etc.
8730 buffer_add_byte (buf, tls->frames [i]->flags);
8735 case CMD_THREAD_GET_STATE:
8736 buffer_add_int (buf, thread->state);
8738 case CMD_THREAD_GET_INFO:
8739 buffer_add_byte (buf, thread->threadpool_thread);
8741 case CMD_THREAD_GET_ID:
8742 buffer_add_long (buf, (guint64)(gsize)thread);
8744 case CMD_THREAD_GET_TID:
8745 buffer_add_long (buf, (guint64)thread->tid);
8747 case CMD_THREAD_SET_IP: {
8748 DebuggerTlsData *tls;
8751 MonoSeqPointInfo *seq_points;
8752 SeqPoint *sp = NULL;
8756 method = decode_methodid (p, &p, end, &domain, &err);
8759 il_offset = decode_long (p, &p, end);
8761 while (!is_suspended ()) {
8763 wait_for_suspend ();
8766 mono_loader_lock ();
8767 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8768 mono_loader_unlock ();
8771 compute_frame_info (thread, tls);
8772 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
8773 return ERR_INVALID_ARGUMENT;
8775 seq_points = get_seq_points (domain, method);
8776 g_assert (seq_points);
8778 for (i = 0; i < seq_points->len; ++i) {
8779 sp = &seq_points->seq_points [i];
8781 if (sp->il_offset == il_offset)
8784 if (i == seq_points->len)
8785 return ERR_INVALID_ARGUMENT;
8787 // FIXME: Check that the ip change is safe
8789 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));
8790 MONO_CONTEXT_SET_IP (&tls->restore_ctx, (guint8*)tls->frames [0]->ji->code_start + sp->native_offset);
8794 return ERR_NOT_IMPLEMENTED;
8801 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8805 MonoThread *thread_obj;
8806 MonoInternalThread *thread;
8807 int pos, i, len, frame_idx;
8808 DebuggerTlsData *tls;
8810 MonoDebugMethodJitInfo *jit;
8811 MonoDebugVarInfo *var;
8812 MonoMethodSignature *sig;
8814 MonoMethodHeader *header;
8816 objid = decode_objid (p, &p, end);
8817 err = get_object (objid, (MonoObject**)&thread_obj);
8821 thread = THREAD_TO_INTERNAL (thread_obj);
8823 id = decode_id (p, &p, end);
8825 mono_loader_lock ();
8826 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8827 mono_loader_unlock ();
8830 for (i = 0; i < tls->frame_count; ++i) {
8831 if (tls->frames [i]->id == id)
8834 if (i == tls->frame_count)
8835 return ERR_INVALID_FRAMEID;
8838 frame = tls->frames [frame_idx];
8840 if (!frame->has_ctx)
8841 return ERR_ABSENT_INFORMATION;
8844 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
8845 if (!frame->jit && frame->api_method->is_inflated)
8846 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
8850 /* This could happen for aot images with no jit debug info */
8851 s = mono_method_full_name (frame->api_method, TRUE);
8852 DEBUG (1, fprintf (log_file, "[dbg] No debug information found for '%s'.\n", s));
8854 return ERR_ABSENT_INFORMATION;
8859 sig = mono_method_signature (frame->actual_method);
8861 if (!get_seq_points (frame->domain, frame->actual_method))
8863 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
8865 return ERR_ABSENT_INFORMATION;
8868 case CMD_STACK_FRAME_GET_VALUES: {
8869 len = decode_int (p, &p, end);
8870 header = mono_method_get_header (frame->actual_method);
8872 for (i = 0; i < len; ++i) {
8873 pos = decode_int (p, &p, end);
8878 g_assert (pos >= 0 && pos < jit->num_params);
8880 var = &jit->params [pos];
8882 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
8884 g_assert (pos >= 0 && pos < jit->num_locals);
8886 var = &jit->locals [pos];
8888 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
8891 mono_metadata_free_mh (header);
8894 case CMD_STACK_FRAME_GET_THIS: {
8895 if (frame->api_method->klass->valuetype) {
8896 if (!sig->hasthis) {
8897 MonoObject *p = NULL;
8898 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
8900 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8903 if (!sig->hasthis) {
8904 MonoObject *p = NULL;
8905 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
8907 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8912 case CMD_STACK_FRAME_SET_VALUES: {
8915 MonoDebugVarInfo *var;
8917 len = decode_int (p, &p, end);
8918 header = mono_method_get_header (frame->actual_method);
8920 for (i = 0; i < len; ++i) {
8921 pos = decode_int (p, &p, end);
8926 g_assert (pos >= 0 && pos < jit->num_params);
8928 t = sig->params [pos];
8929 var = &jit->params [pos];
8931 g_assert (pos >= 0 && pos < jit->num_locals);
8933 t = header->locals [pos];
8934 var = &jit->locals [pos];
8937 if (MONO_TYPE_IS_REFERENCE (t))
8938 val_buf = g_alloca (sizeof (MonoObject*));
8940 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
8941 err = decode_value (t, frame->domain, val_buf, p, &p, end);
8945 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_ctx);
8947 mono_metadata_free_mh (header);
8951 return ERR_NOT_IMPLEMENTED;
8958 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8961 int objid, err, index, len, i, esize;
8964 objid = decode_objid (p, &p, end);
8965 err = get_object (objid, (MonoObject**)&arr);
8970 case CMD_ARRAY_REF_GET_LENGTH:
8971 buffer_add_int (buf, arr->obj.vtable->klass->rank);
8973 buffer_add_int (buf, arr->max_length);
8974 buffer_add_int (buf, 0);
8976 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
8977 buffer_add_int (buf, arr->bounds [i].length);
8978 buffer_add_int (buf, arr->bounds [i].lower_bound);
8982 case CMD_ARRAY_REF_GET_VALUES:
8983 index = decode_int (p, &p, end);
8984 len = decode_int (p, &p, end);
8986 g_assert (index >= 0 && len >= 0);
8987 // Reordered to avoid integer overflow
8988 g_assert (!(index > arr->max_length - len));
8990 esize = mono_array_element_size (arr->obj.vtable->klass);
8991 for (i = index; i < index + len; ++i) {
8992 elem = (gpointer*)((char*)arr->vector + (i * esize));
8993 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
8996 case CMD_ARRAY_REF_SET_VALUES:
8997 index = decode_int (p, &p, end);
8998 len = decode_int (p, &p, end);
9000 g_assert (index >= 0 && len >= 0);
9001 // Reordered to avoid integer overflow
9002 g_assert (!(index > arr->max_length - len));
9004 esize = mono_array_element_size (arr->obj.vtable->klass);
9005 for (i = index; i < index + len; ++i) {
9006 elem = (gpointer*)((char*)arr->vector + (i * esize));
9008 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
9012 return ERR_NOT_IMPLEMENTED;
9019 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9024 int i, index, length;
9027 objid = decode_objid (p, &p, end);
9028 err = get_object (objid, (MonoObject**)&str);
9033 case CMD_STRING_REF_GET_VALUE:
9034 s = mono_string_to_utf8 (str);
9035 buffer_add_string (buf, s);
9038 case CMD_STRING_REF_GET_LENGTH:
9039 buffer_add_long (buf, mono_string_length (str));
9041 case CMD_STRING_REF_GET_CHARS:
9042 index = decode_long (p, &p, end);
9043 length = decode_long (p, &p, end);
9044 if (index > mono_string_length (str) - length)
9045 return ERR_INVALID_ARGUMENT;
9046 c = mono_string_chars (str) + index;
9047 for (i = 0; i < length; ++i)
9048 buffer_add_short (buf, c [i]);
9051 return ERR_NOT_IMPLEMENTED;
9058 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9067 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9068 objid = decode_objid (p, &p, end);
9069 err = get_object (objid, &obj);
9071 buffer_add_int (buf, 1);
9073 buffer_add_int (buf, 0);
9077 objid = decode_objid (p, &p, end);
9078 err = get_object (objid, &obj);
9083 case CMD_OBJECT_REF_GET_TYPE:
9084 /* This handles transparent proxies too */
9085 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9087 case CMD_OBJECT_REF_GET_VALUES:
9088 len = decode_int (p, &p, end);
9090 for (i = 0; i < len; ++i) {
9091 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9095 /* Check that the field belongs to the object */
9097 for (k = obj->vtable->klass; k; k = k->parent) {
9098 if (k == f->parent) {
9104 return ERR_INVALID_FIELDID;
9106 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9110 if (mono_class_field_is_special_static (f))
9111 return ERR_INVALID_FIELDID;
9113 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9114 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9115 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9116 mono_field_static_get_value (vtable, f, val);
9117 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9120 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
9124 case CMD_OBJECT_REF_SET_VALUES:
9125 len = decode_int (p, &p, end);
9127 for (i = 0; i < len; ++i) {
9128 f = decode_fieldid (p, &p, end, NULL, &err);
9132 /* Check that the field belongs to the object */
9134 for (k = obj->vtable->klass; k; k = k->parent) {
9135 if (k == f->parent) {
9141 return ERR_INVALID_FIELDID;
9143 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9147 if (mono_class_field_is_special_static (f))
9148 return ERR_INVALID_FIELDID;
9150 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9151 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9153 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9154 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
9159 mono_field_static_set_value (vtable, f, val);
9162 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
9168 case CMD_OBJECT_REF_GET_ADDRESS:
9169 buffer_add_long (buf, (gssize)obj);
9171 case CMD_OBJECT_REF_GET_DOMAIN:
9172 buffer_add_domainid (buf, obj->vtable->domain);
9174 case CMD_OBJECT_REF_GET_INFO:
9175 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9176 buffer_add_domainid (buf, obj->vtable->domain);
9179 return ERR_NOT_IMPLEMENTED;
9186 command_set_to_string (CommandSet command_set)
9188 switch (command_set) {
9191 case CMD_SET_OBJECT_REF:
9192 return "OBJECT_REF";
9193 case CMD_SET_STRING_REF:
9194 return "STRING_REF";
9195 case CMD_SET_THREAD:
9197 case CMD_SET_ARRAY_REF:
9199 case CMD_SET_EVENT_REQUEST:
9200 return "EVENT_REQUEST";
9201 case CMD_SET_STACK_FRAME:
9202 return "STACK_FRAME";
9203 case CMD_SET_APPDOMAIN:
9205 case CMD_SET_ASSEMBLY:
9207 case CMD_SET_METHOD:
9211 case CMD_SET_MODULE:
9222 static const char* vm_cmds_str [] = {
9230 "SET_PROTOCOL_VERSION",
9233 "GET_TYPES_FOR_SOURCE_FILE",
9238 static const char* thread_cmds_str[] = {
9248 static const char* event_cmds_str[] = {
9251 "REQUEST_CLEAR_ALL_BREAKPOINTS"
9254 static const char* appdomain_cmds_str[] = {
9256 "GET_FRIENDLY_NAME",
9258 "GET_ENTRY_ASSEMBLY",
9261 "CREATE_BOXED_VALUE"
9264 static const char* assembly_cmds_str[] = {
9267 "GET_MANIFEST_MODULE",
9273 static const char* module_cmds_str[] = {
9277 static const char* field_cmds_str[] = {
9281 static const char* method_cmds_str[] = {
9283 "GET_DECLARING_TYPE",
9291 "MAKE_GENERIC_METHOD"
9294 static const char* type_cmds_str[] = {
9302 "IS_ASSIGNABLE_FROM",
9306 "GET_PROPERTY_CATTRS",
9307 "GET_SOURCE_FILES_2",
9309 "GET_METHODS_BY_NAME_FLAGS",
9311 "GET_INTERFACE_MAP",
9315 static const char* stack_frame_cmds_str[] = {
9321 static const char* array_cmds_str[] = {
9327 static const char* string_cmds_str[] = {
9333 static const char* object_cmds_str[] = {
9344 cmd_to_string (CommandSet set, int command)
9352 cmds_len = G_N_ELEMENTS (vm_cmds_str);
9354 case CMD_SET_OBJECT_REF:
9355 cmds = object_cmds_str;
9356 cmds_len = G_N_ELEMENTS (object_cmds_str);
9358 case CMD_SET_STRING_REF:
9359 cmds = string_cmds_str;
9360 cmds_len = G_N_ELEMENTS (string_cmds_str);
9362 case CMD_SET_THREAD:
9363 cmds = thread_cmds_str;
9364 cmds_len = G_N_ELEMENTS (thread_cmds_str);
9366 case CMD_SET_ARRAY_REF:
9367 cmds = array_cmds_str;
9368 cmds_len = G_N_ELEMENTS (array_cmds_str);
9370 case CMD_SET_EVENT_REQUEST:
9371 cmds = event_cmds_str;
9372 cmds_len = G_N_ELEMENTS (event_cmds_str);
9374 case CMD_SET_STACK_FRAME:
9375 cmds = stack_frame_cmds_str;
9376 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
9378 case CMD_SET_APPDOMAIN:
9379 cmds = appdomain_cmds_str;
9380 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
9382 case CMD_SET_ASSEMBLY:
9383 cmds = assembly_cmds_str;
9384 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
9386 case CMD_SET_METHOD:
9387 cmds = method_cmds_str;
9388 cmds_len = G_N_ELEMENTS (method_cmds_str);
9391 cmds = type_cmds_str;
9392 cmds_len = G_N_ELEMENTS (type_cmds_str);
9394 case CMD_SET_MODULE:
9395 cmds = module_cmds_str;
9396 cmds_len = G_N_ELEMENTS (module_cmds_str);
9399 cmds = field_cmds_str;
9400 cmds_len = G_N_ELEMENTS (field_cmds_str);
9403 cmds = event_cmds_str;
9404 cmds_len = G_N_ELEMENTS (event_cmds_str);
9409 if (command > 0 && command <= cmds_len)
9410 return cmds [command - 1];
9416 wait_for_attach (void)
9418 #ifndef DISABLE_SOCKET_TRANSPORT
9419 if (listen_fd == -1) {
9420 DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
9424 /* Block and wait for client connection */
9425 conn_fd = socket_transport_accept (listen_fd);
9426 DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
9427 if (conn_fd == -1) {
9428 DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
9432 g_assert_not_reached ();
9436 disconnected = !transport_handshake ();
9438 DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
9448 * This thread handles communication with the debugger client using a JDWP
9451 static guint32 WINAPI
9452 debugger_thread (void *arg)
9454 int res, len, id, flags, command_set = 0, command = 0;
9455 guint8 header [HEADER_LENGTH];
9456 guint8 *data, *p, *end;
9460 gboolean attach_failed = FALSE;
9462 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
9464 debugger_thread_id = GetCurrentThreadId ();
9466 mono_jit_thread_attach (mono_get_root_domain ());
9468 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
9470 mono_set_is_debugger_attached (TRUE);
9472 if (agent_config.defer) {
9473 if (!wait_for_attach ()) {
9474 DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
9475 attach_failed = TRUE; // Don't abort process when we can't listen
9477 /* Send start event to client */
9478 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
9482 while (!attach_failed) {
9483 res = transport_recv (header, HEADER_LENGTH);
9485 /* This will break if the socket is closed during shutdown too */
9486 if (res != HEADER_LENGTH) {
9487 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH));
9492 end = header + HEADER_LENGTH;
9494 len = decode_int (p, &p, end);
9495 id = decode_int (p, &p, end);
9496 flags = decode_byte (p, &p, end);
9497 command_set = decode_byte (p, &p, end);
9498 command = decode_byte (p, &p, end);
9500 g_assert (flags == 0);
9503 const char *cmd_str;
9506 cmd_str = cmd_to_string (command_set, command);
9508 sprintf (cmd_num, "%d", command);
9512 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));
9515 data = g_malloc (len - HEADER_LENGTH);
9516 if (len - HEADER_LENGTH > 0)
9518 res = transport_recv (data, len - HEADER_LENGTH);
9519 if (res != len - HEADER_LENGTH) {
9520 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH));
9526 end = data + (len - HEADER_LENGTH);
9528 buffer_init (&buf, 128);
9533 /* Process the request */
9534 switch (command_set) {
9536 err = vm_commands (command, id, p, end, &buf);
9537 if (!err && command == CMD_VM_INVOKE_METHOD)
9538 /* Sent after the invoke is complete */
9541 case CMD_SET_EVENT_REQUEST:
9542 err = event_commands (command, p, end, &buf);
9544 case CMD_SET_APPDOMAIN:
9545 err = domain_commands (command, p, end, &buf);
9547 case CMD_SET_ASSEMBLY:
9548 err = assembly_commands (command, p, end, &buf);
9550 case CMD_SET_MODULE:
9551 err = module_commands (command, p, end, &buf);
9554 err = field_commands (command, p, end, &buf);
9557 err = type_commands (command, p, end, &buf);
9559 case CMD_SET_METHOD:
9560 err = method_commands (command, p, end, &buf);
9562 case CMD_SET_THREAD:
9563 err = thread_commands (command, p, end, &buf);
9565 case CMD_SET_STACK_FRAME:
9566 err = frame_commands (command, p, end, &buf);
9568 case CMD_SET_ARRAY_REF:
9569 err = array_commands (command, p, end, &buf);
9571 case CMD_SET_STRING_REF:
9572 err = string_commands (command, p, end, &buf);
9574 case CMD_SET_OBJECT_REF:
9575 err = object_commands (command, p, end, &buf);
9578 err = ERR_NOT_IMPLEMENTED;
9581 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
9582 buffer_replies = TRUE;
9586 if (buffer_replies) {
9587 buffer_reply_packet (id, err, &buf);
9589 send_reply_packet (id, err, &buf);
9590 //DEBUG (1, fprintf (log_file, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000));
9594 if (!err && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
9595 send_buffered_reply_packets ();
9596 buffer_replies = FALSE;
9602 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
9606 mono_set_is_debugger_attached (FALSE);
9608 mono_mutex_lock (&debugger_thread_exited_mutex);
9609 debugger_thread_exited = TRUE;
9610 mono_cond_signal (&debugger_thread_exited_cond);
9611 mono_mutex_unlock (&debugger_thread_exited_mutex);
9613 DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
9615 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
9616 DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
9617 start_debugger_thread ();
9623 #else /* DISABLE_DEBUGGER_AGENT */
9626 mono_debugger_agent_parse_options (char *options)
9628 g_error ("This runtime is configured with the debugger agent disabled.");
9632 mono_debugger_agent_init (void)
9637 mono_debugger_agent_breakpoint_hit (void *sigctx)
9642 mono_debugger_agent_single_step_event (void *sigctx)
9647 mono_debugger_agent_free_domain_info (MonoDomain *domain)
9652 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
9658 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
9659 MonoContext *catch_ctx)
9664 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9669 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9674 mono_debugger_agent_user_break (void)
9680 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
9685 mono_debugger_agent_debug_log_is_enabled (void)