2 * debugger-agent.c: Soft Debugger back-end module
5 * Zoltan Varga (vargaz@gmail.com)
7 * Copyright 2009-2010 Novell, Inc.
8 * Copyright 2011 Xamarin Inc.
15 #ifdef HAVE_SYS_TYPES_H
16 #include <sys/types.h>
18 #ifdef HAVE_SYS_SELECT_H
19 #include <sys/select.h>
21 #ifdef HAVE_SYS_SOCKET_H
22 #include <sys/socket.h>
24 #ifdef HAVE_NETINET_TCP_H
25 #include <netinet/tcp.h>
27 #ifdef HAVE_NETINET_IN_H
28 #include <netinet/in.h>
43 #ifdef HAVE_UCONTEXT_H
53 /* cygwin's headers do not seem to define these */
54 void WSAAPI freeaddrinfo (struct addrinfo*);
55 int WSAAPI getaddrinfo (const char*,const char*,const struct addrinfo*,
57 int WSAAPI getnameinfo(const struct sockaddr*,socklen_t,char*,DWORD,
62 #ifdef PLATFORM_ANDROID
64 #include <linux/tcp.h>
65 #include <sys/endian.h>
68 #include <mono/metadata/mono-debug.h>
69 #include <mono/metadata/mono-debug-debugger.h>
70 #include <mono/metadata/debug-mono-symfile.h>
71 #include <mono/metadata/gc-internal.h>
72 #include <mono/metadata/threads-types.h>
73 #include <mono/metadata/socket-io.h>
74 #include <mono/metadata/assembly.h>
75 #include <mono/utils/mono-semaphore.h>
76 #include <mono/utils/mono-error-internals.h>
77 #include <mono/utils/mono-stack-unwinding.h>
78 #include <mono/utils/mono-time.h>
79 #include <mono/utils/mono-threads.h>
80 #include "debugger-agent.h"
84 On iOS we can't use System.Environment.Exit () as it will do the wrong
87 #if !defined (TARGET_IOS)
88 #define TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
92 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
93 #define DISABLE_DEBUGGER_AGENT 1
96 #ifdef DISABLE_SOFT_DEBUG
97 #define DISABLE_DEBUGGER_AGENT 1
100 #ifndef DISABLE_DEBUGGER_AGENT
102 #include <mono/io-layer/mono-mutex.h>
104 /* Definitions to make backporting to 2.6 easier */
105 //#define MonoInternalThread MonoThread
106 //#define mono_thread_internal_current mono_thread_current
107 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
129 guint32 il_offset, native_offset;
133 * If method is gshared, this is the actual instance, otherwise this is equal to
136 MonoMethod *actual_method;
138 * This is the method which is visible to debugger clients. Same as method,
139 * except for native-to-managed wrappers.
141 MonoMethod *api_method;
143 MonoDebugMethodJitInfo *jit;
146 mgreg_t *reg_locations [MONO_MAX_IREGS];
148 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
149 * the frame can become invalid.
154 typedef struct _InvokeData InvokeData;
162 /* This is the context which needs to be restored after the invoke */
166 * If this is set, invoke this method with the arguments given by ARGS.
170 guint32 suspend_count;
173 InvokeData *last_invoke;
177 MonoThreadUnwindState context;
179 /* This is computed on demand when it is requested using the wire protocol */
180 /* It is freed up when the thread is resumed */
184 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
187 gboolean frames_up_to_date;
189 * Points to data about a pending invoke which needs to be executed after the thread
192 InvokeData *pending_invoke;
194 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
199 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
200 * within a finite amount of time.
204 * Set to TRUE if this thread is suspended in suspend_current ().
206 gboolean really_suspended;
207 /* Used to pass the context to the breakpoint/single step handler */
208 MonoContext handler_ctx;
209 /* Whenever thread_stop () was called for this thread */
212 /* Number of thread interruptions not yet processed */
213 gint32 interrupt_count;
215 /* Whenever to disable breakpoints (used during invokes) */
216 gboolean disable_breakpoints;
219 * Number of times this thread has been resumed using resume_thread ().
221 guint32 resume_count;
223 MonoInternalThread *thread;
226 * Information about the frame which transitioned to native code for running
229 StackFrameInfo async_last_frame;
232 * The context where the stack walk can be started for running threads.
234 MonoThreadUnwindState async_state;
237 * The context used for filter clauses
239 MonoThreadUnwindState filter_state;
242 * The callee address of the last mono_runtime_invoke call
244 gpointer invoke_addr;
246 gboolean abort_requested;
249 * The current mono_runtime_invoke invocation.
254 * The context where single stepping should resume while the thread is suspended because
255 * of an EXCEPTION event.
257 MonoThreadUnwindState catch_state;
260 * The context which needs to be restored after handling a single step/breakpoint
261 * event. This is the same as the ctx at step/breakpoint site, but includes changes
262 * to caller saved registers done by set_var ().
264 MonoContext restore_ctx;
269 void (*connect) (const char *address);
270 void (*close1) (void);
271 void (*close2) (void);
272 gboolean (*send) (void *buf, int len);
273 int (*recv) (void *buf, int len);
277 * Wire Protocol definitions
280 #define HEADER_LENGTH 11
282 #define MAJOR_VERSION 2
283 #define MINOR_VERSION 23
287 CMD_SET_OBJECT_REF = 9,
288 CMD_SET_STRING_REF = 10,
290 CMD_SET_ARRAY_REF = 13,
291 CMD_SET_EVENT_REQUEST = 15,
292 CMD_SET_STACK_FRAME = 16,
293 CMD_SET_APPDOMAIN = 20,
294 CMD_SET_ASSEMBLY = 21,
302 EVENT_KIND_VM_START = 0,
303 EVENT_KIND_VM_DEATH = 1,
304 EVENT_KIND_THREAD_START = 2,
305 EVENT_KIND_THREAD_DEATH = 3,
306 EVENT_KIND_APPDOMAIN_CREATE = 4,
307 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
308 EVENT_KIND_METHOD_ENTRY = 6,
309 EVENT_KIND_METHOD_EXIT = 7,
310 EVENT_KIND_ASSEMBLY_LOAD = 8,
311 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
312 EVENT_KIND_BREAKPOINT = 10,
313 EVENT_KIND_STEP = 11,
314 EVENT_KIND_TYPE_LOAD = 12,
315 EVENT_KIND_EXCEPTION = 13,
316 EVENT_KIND_KEEPALIVE = 14,
317 EVENT_KIND_USER_BREAK = 15,
318 EVENT_KIND_USER_LOG = 16
322 SUSPEND_POLICY_NONE = 0,
323 SUSPEND_POLICY_EVENT_THREAD = 1,
324 SUSPEND_POLICY_ALL = 2
329 ERR_INVALID_OBJECT = 20,
330 ERR_INVALID_FIELDID = 25,
331 ERR_INVALID_FRAMEID = 30,
332 ERR_NOT_IMPLEMENTED = 100,
333 ERR_NOT_SUSPENDED = 101,
334 ERR_INVALID_ARGUMENT = 102,
336 ERR_NO_INVOCATION = 104,
337 ERR_ABSENT_INFORMATION = 105,
338 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
339 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
344 MOD_KIND_THREAD_ONLY = 3,
345 MOD_KIND_LOCATION_ONLY = 7,
346 MOD_KIND_EXCEPTION_ONLY = 8,
348 MOD_KIND_ASSEMBLY_ONLY = 11,
349 MOD_KIND_SOURCE_FILE_ONLY = 12,
350 MOD_KIND_TYPE_NAME_ONLY = 13
365 STEP_FILTER_NONE = 0,
366 STEP_FILTER_STATIC_CTOR = 1,
367 STEP_FILTER_DEBUGGER_HIDDEN = 2
371 TOKEN_TYPE_STRING = 0,
373 TOKEN_TYPE_FIELD = 2,
374 TOKEN_TYPE_METHOD = 3,
375 TOKEN_TYPE_UNKNOWN = 4
379 VALUE_TYPE_ID_NULL = 0xf0,
380 VALUE_TYPE_ID_TYPE = 0xf1
384 FRAME_FLAG_DEBUGGER_INVOKE = 1,
385 FRAME_FLAG_NATIVE_TRANSITION = 2
389 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
390 INVOKE_FLAG_SINGLE_THREADED = 2
394 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
395 } BindingFlagsExtensions;
399 CMD_VM_ALL_THREADS = 2,
404 CMD_VM_INVOKE_METHOD = 7,
405 CMD_VM_SET_PROTOCOL_VERSION = 8,
406 CMD_VM_ABORT_INVOKE = 9,
407 CMD_VM_SET_KEEPALIVE = 10,
408 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
409 CMD_VM_GET_TYPES = 12,
410 CMD_VM_INVOKE_METHODS = 13
414 CMD_THREAD_GET_FRAME_INFO = 1,
415 CMD_THREAD_GET_NAME = 2,
416 CMD_THREAD_GET_STATE = 3,
417 CMD_THREAD_GET_INFO = 4,
418 CMD_THREAD_GET_ID = 5,
419 CMD_THREAD_GET_TID = 6
423 CMD_EVENT_REQUEST_SET = 1,
424 CMD_EVENT_REQUEST_CLEAR = 2,
425 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
433 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
434 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
435 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
436 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
437 CMD_APPDOMAIN_CREATE_STRING = 5,
438 CMD_APPDOMAIN_GET_CORLIB = 6,
439 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
443 CMD_ASSEMBLY_GET_LOCATION = 1,
444 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
445 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
446 CMD_ASSEMBLY_GET_OBJECT = 4,
447 CMD_ASSEMBLY_GET_TYPE = 5,
448 CMD_ASSEMBLY_GET_NAME = 6
452 CMD_MODULE_GET_INFO = 1,
456 CMD_METHOD_GET_NAME = 1,
457 CMD_METHOD_GET_DECLARING_TYPE = 2,
458 CMD_METHOD_GET_DEBUG_INFO = 3,
459 CMD_METHOD_GET_PARAM_INFO = 4,
460 CMD_METHOD_GET_LOCALS_INFO = 5,
461 CMD_METHOD_GET_INFO = 6,
462 CMD_METHOD_GET_BODY = 7,
463 CMD_METHOD_RESOLVE_TOKEN = 8,
464 CMD_METHOD_GET_CATTRS = 9,
468 CMD_TYPE_GET_INFO = 1,
469 CMD_TYPE_GET_METHODS = 2,
470 CMD_TYPE_GET_FIELDS = 3,
471 CMD_TYPE_GET_VALUES = 4,
472 CMD_TYPE_GET_OBJECT = 5,
473 CMD_TYPE_GET_SOURCE_FILES = 6,
474 CMD_TYPE_SET_VALUES = 7,
475 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
476 CMD_TYPE_GET_PROPERTIES = 9,
477 CMD_TYPE_GET_CATTRS = 10,
478 CMD_TYPE_GET_FIELD_CATTRS = 11,
479 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
480 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
481 CMD_TYPE_GET_VALUES_2 = 14,
482 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
483 CMD_TYPE_GET_INTERFACES = 16,
484 CMD_TYPE_GET_INTERFACE_MAP = 17,
485 CMD_TYPE_IS_INITIALIZED = 18
489 CMD_STACK_FRAME_GET_VALUES = 1,
490 CMD_STACK_FRAME_GET_THIS = 2,
491 CMD_STACK_FRAME_SET_VALUES = 3
495 CMD_ARRAY_REF_GET_LENGTH = 1,
496 CMD_ARRAY_REF_GET_VALUES = 2,
497 CMD_ARRAY_REF_SET_VALUES = 3,
501 CMD_STRING_REF_GET_VALUE = 1,
502 CMD_STRING_REF_GET_LENGTH = 2,
503 CMD_STRING_REF_GET_CHARS = 3
507 CMD_OBJECT_REF_GET_TYPE = 1,
508 CMD_OBJECT_REF_GET_VALUES = 2,
509 CMD_OBJECT_REF_IS_COLLECTED = 3,
510 CMD_OBJECT_REF_GET_ADDRESS = 4,
511 CMD_OBJECT_REF_GET_DOMAIN = 5,
512 CMD_OBJECT_REF_SET_VALUES = 6,
513 CMD_OBJECT_REF_GET_INFO = 7,
519 int count; /* For kind == MOD_KIND_COUNT */
520 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
521 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
522 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
523 GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
524 GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
525 StepFilter filter; /* For kind == MOD_KIND_STEP */
527 gboolean caught, uncaught; /* For kind == MOD_KIND_EXCEPTION_ONLY */
536 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
540 * Describes a single step request.
544 MonoInternalThread *thread;
550 MonoMethod *last_method;
552 /* Whenever single stepping is performed using start/stop_single_stepping () */
554 /* The list of breakpoints used to implement step-over */
559 * Contains additional information for an event
562 /* For EVENT_KIND_EXCEPTION */
564 MonoContext catch_ctx;
566 /* For EVENT_KIND_USER_LOG */
568 char *category, *message;
569 /* For EVENT_KIND_TYPE_LOAD */
573 /* Dummy structure used for the profiler callbacks */
578 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
581 #define get_last_sock_error() WSAGetLastError()
582 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
583 #define MONO_EINTR WSAEINTR
585 #define get_last_sock_error() errno
586 #define MONO_EWOULDBLOCK EWOULDBLOCK
587 #define MONO_EINTR EINTR
590 #define CHECK_PROTOCOL_VERSION(major,minor) \
591 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
597 static AgentConfig agent_config;
600 * Whenever the agent is fully initialized.
601 * When using the onuncaught or onthrow options, only some parts of the agent are
602 * initialized on startup, and the full initialization which includes connection
603 * establishment and the startup of the agent thread is only done in response to
606 static gint32 inited;
608 #ifndef DISABLE_SOCKET_TRANSPORT
610 static int listen_fd;
613 static int packet_id = 0;
615 static int objref_id = 0;
617 static int event_request_id = 0;
619 static int frame_id = 0;
621 static GPtrArray *event_requests;
623 static MonoNativeTlsKey debugger_tls_id;
625 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
627 /* Maps MonoInternalThread -> DebuggerTlsData */
628 static MonoGHashTable *thread_to_tls;
630 /* Maps tid -> MonoInternalThread */
631 static MonoGHashTable *tid_to_thread;
633 /* Maps tid -> MonoThread (not MonoInternalThread) */
634 static MonoGHashTable *tid_to_thread_obj;
636 static gsize debugger_thread_id;
638 static HANDLE debugger_thread_handle;
640 static int log_level;
642 static gboolean embedding;
644 static FILE *log_file;
646 /* Assemblies whose assembly load event has no been sent yet */
647 static GPtrArray *pending_assembly_loads;
649 /* Whenever the debugger thread has exited */
650 static gboolean debugger_thread_exited;
652 /* Cond variable used to wait for debugger_thread_exited becoming true */
653 static mono_cond_t debugger_thread_exited_cond;
655 /* Mutex for the cond var above */
656 static mono_mutex_t debugger_thread_exited_mutex;
658 static DebuggerProfiler debugger_profiler;
660 /* The single step request instance */
661 static SingleStepReq *ss_req = NULL;
662 static gpointer ss_invoke_addr = NULL;
664 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
665 /* Number of single stepping operations in progress */
669 /* The protocol version of the client */
670 static int major_version, minor_version;
672 /* Whenever the variables above are set by the client */
673 static gboolean protocol_version_set;
675 /* A hash table containing all active domains */
676 static GHashTable *domains;
678 /* The number of times the runtime is suspended */
679 static gint32 suspend_count;
681 static void transport_init (void);
682 static void transport_connect (const char *address);
683 static gboolean transport_handshake (void);
684 static void register_transport (DebuggerTransport *trans);
686 static guint32 WINAPI debugger_thread (void *arg);
688 static void runtime_initialized (MonoProfiler *prof);
690 static void runtime_shutdown (MonoProfiler *prof);
692 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
694 static void thread_end (MonoProfiler *prof, uintptr_t tid);
696 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
698 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
700 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
702 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
704 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
706 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
708 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
710 static void emit_assembly_load (gpointer assembly, gpointer user_data);
712 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
714 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
716 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
718 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
720 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
722 static void start_single_stepping (void);
724 static void stop_single_stepping (void);
726 static void suspend_current (void);
728 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
730 static void clear_types_for_assembly (MonoAssembly *assembly);
732 static void clear_breakpoints_for_domain (MonoDomain *domain);
734 static void process_profiler_event (EventKind event, gpointer arg);
736 /* Submodule init/cleanup */
737 static void breakpoints_init (void);
738 static void breakpoints_cleanup (void);
740 static void objrefs_init (void);
741 static void objrefs_cleanup (void);
743 static void ids_init (void);
744 static void ids_cleanup (void);
746 static void suspend_init (void);
748 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch);
749 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
750 static void ss_destroy (SingleStepReq *req);
752 static void start_debugger_thread (void);
753 static void stop_debugger_thread (void);
755 static void finish_agent_init (gboolean on_startup);
757 static void process_profiler_event (EventKind event, gpointer arg);
759 static void invalidate_frames (DebuggerTlsData *tls);
761 #ifndef DISABLE_SOCKET_TRANSPORT
763 register_socket_transport (void);
767 parse_address (char *address, char **host, int *port)
769 char *pos = strchr (address, ':');
771 if (pos == NULL || pos == address)
774 *host = g_malloc (pos - address + 1);
775 strncpy (*host, address, pos - address);
776 (*host) [pos - address] = '\0';
778 *port = atoi (pos + 1);
786 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
787 fprintf (stderr, "Available options:\n");
788 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
789 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
790 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
791 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
792 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
793 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
794 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
795 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
796 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
800 parse_flag (const char *option, char *flag)
802 if (!strcmp (flag, "y"))
804 else if (!strcmp (flag, "n"))
807 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
814 mono_debugger_agent_parse_options (char *options)
821 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
822 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
826 extra = getenv ("MONO_SDB_ENV_OPTIONS");
828 options = g_strdup_printf ("%s,%s", options, extra);
830 agent_config.enabled = TRUE;
831 agent_config.suspend = TRUE;
832 agent_config.server = FALSE;
833 agent_config.defer = FALSE;
834 agent_config.address = NULL;
836 args = g_strsplit (options, ",", -1);
837 for (ptr = args; ptr && *ptr; ptr ++) {
840 if (strncmp (arg, "transport=", 10) == 0) {
841 agent_config.transport = g_strdup (arg + 10);
842 } else if (strncmp (arg, "address=", 8) == 0) {
843 agent_config.address = g_strdup (arg + 8);
844 } else if (strncmp (arg, "loglevel=", 9) == 0) {
845 agent_config.log_level = atoi (arg + 9);
846 } else if (strncmp (arg, "logfile=", 8) == 0) {
847 agent_config.log_file = g_strdup (arg + 8);
848 } else if (strncmp (arg, "suspend=", 8) == 0) {
849 agent_config.suspend = parse_flag ("suspend", arg + 8);
850 } else if (strncmp (arg, "server=", 7) == 0) {
851 agent_config.server = parse_flag ("server", arg + 7);
852 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
853 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
854 } else if (strncmp (arg, "onthrow=", 8) == 0) {
855 /* We support multiple onthrow= options */
856 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
857 } else if (strncmp (arg, "onthrow", 7) == 0) {
858 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
859 } else if (strncmp (arg, "help", 4) == 0) {
862 } else if (strncmp (arg, "timeout=", 8) == 0) {
863 agent_config.timeout = atoi (arg + 8);
864 } else if (strncmp (arg, "launch=", 7) == 0) {
865 agent_config.launch = g_strdup (arg + 7);
866 } else if (strncmp (arg, "embedding=", 10) == 0) {
867 agent_config.embedding = atoi (arg + 10) == 1;
868 } else if (strncmp (arg, "keepalive=", 10) == 0) {
869 agent_config.keepalive = atoi (arg + 10);
876 if (agent_config.server && !agent_config.suspend) {
877 /* Waiting for deferred attachment */
878 agent_config.defer = TRUE;
879 if (agent_config.address == NULL) {
880 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (GetCurrentProcessId () % 1000));
884 //agent_config.log_level = 0;
886 if (agent_config.transport == NULL) {
887 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
891 if (agent_config.address == NULL && !agent_config.server) {
892 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
897 if (!strcmp (agent_config.transport, "dt_socket")) {
898 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
899 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
906 mono_debugger_agent_init (void)
908 if (!agent_config.enabled)
913 /* Need to know whenever a thread has acquired the loader mutex */
914 mono_loader_lock_track_ownership (TRUE);
916 event_requests = g_ptr_array_new ();
918 mono_mutex_init (&debugger_thread_exited_mutex, NULL);
919 mono_cond_init (&debugger_thread_exited_cond, NULL);
921 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
922 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
923 mono_profiler_install_runtime_initialized (runtime_initialized);
924 mono_profiler_install_appdomain (NULL, appdomain_load, NULL, appdomain_unload);
925 mono_profiler_install_thread (thread_startup, thread_end);
926 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
927 mono_profiler_install_jit_end (jit_end);
928 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
930 mono_native_tls_alloc (&debugger_tls_id, NULL);
932 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
933 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls);
935 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
936 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread);
938 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
939 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj);
941 pending_assembly_loads = g_ptr_array_new ();
942 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
944 log_level = agent_config.log_level;
946 embedding = agent_config.embedding;
949 if (agent_config.log_file) {
950 log_file = fopen (agent_config.log_file, "w+");
952 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
964 mini_get_debug_options ()->gen_seq_points = TRUE;
966 * This is needed because currently we don't handle liveness info.
968 mini_get_debug_options ()->mdb_optimizations = TRUE;
970 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
971 /* This is needed because we can't set local variables in registers yet */
972 mono_disable_optimizations (MONO_OPT_LINEARS);
976 * The stack walk done from thread_interrupt () needs to be signal safe, but it
977 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
978 * safe (#3411). So load AOT info eagerly when the debugger is running as a
981 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
983 if (!agent_config.onuncaught && !agent_config.onthrow)
984 finish_agent_init (TRUE);
990 * Finish the initialization of the agent. This involves connecting the transport
991 * and starting the agent thread. This is either done at startup, or
992 * in response to some event like an unhandled exception.
995 finish_agent_init (gboolean on_startup)
999 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
1002 if (agent_config.launch) {
1005 // FIXME: Generated address
1006 // FIXME: Races with transport_connect ()
1008 argv [0] = agent_config.launch;
1009 argv [1] = agent_config.transport;
1010 argv [2] = agent_config.address;
1013 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1015 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1020 transport_connect (agent_config.address);
1023 /* Do some which is usually done after sending the VMStart () event */
1024 vm_start_event_sent = TRUE;
1025 start_debugger_thread ();
1030 mono_debugger_agent_cleanup (void)
1035 stop_debugger_thread ();
1037 breakpoints_cleanup ();
1041 mono_mutex_destroy (&debugger_thread_exited_mutex);
1042 mono_cond_destroy (&debugger_thread_exited_cond);
1049 #ifndef DISABLE_SOCKET_TRANSPORT
1054 * recv() + handle incomplete reads and EINTR
1057 socket_transport_recv (void *buf, int len)
1063 static gint32 last_keepalive;
1068 res = recv (fd, (char *) buf + total, len - total, flags);
1071 if (agent_config.keepalive) {
1072 gboolean need_keepalive = FALSE;
1073 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1074 need_keepalive = TRUE;
1075 } else if (res == -1) {
1076 /* This could happen if recv () is interrupted repeatedly */
1077 msecs = mono_msec_ticks ();
1078 if (msecs - last_keepalive >= agent_config.keepalive) {
1079 need_keepalive = TRUE;
1080 last_keepalive = msecs;
1083 if (need_keepalive) {
1084 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1088 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1093 #define HAVE_GETADDRINFO 1
1097 set_keepalive (void)
1102 if (!agent_config.keepalive || !conn_fd)
1105 tv.tv_sec = agent_config.keepalive / 1000;
1106 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1108 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1109 g_assert (result >= 0);
1113 socket_transport_accept (int socket_fd)
1115 conn_fd = accept (socket_fd, NULL, NULL);
1116 if (conn_fd == -1) {
1117 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1119 DEBUG (1, fprintf (log_file, "Accepted connection from client, connection fd=%d.\n", conn_fd));
1126 socket_transport_send (void *data, int len)
1131 res = send (conn_fd, data, len, 0);
1132 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1140 * socket_transport_connect:
1142 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1145 socket_transport_connect (const char *address)
1147 #ifdef HAVE_GETADDRINFO
1148 struct addrinfo hints;
1149 struct addrinfo *result, *rp;
1151 struct hostent *result;
1153 int sfd = -1, s, res;
1154 char port_string [128];
1158 if (agent_config.address) {
1159 res = parse_address (agent_config.address, &host, &port);
1160 g_assert (res == 0);
1170 sprintf (port_string, "%d", port);
1172 mono_network_init ();
1174 /* Obtain address(es) matching host/port */
1175 #ifdef HAVE_GETADDRINFO
1176 memset (&hints, 0, sizeof (struct addrinfo));
1177 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
1178 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
1180 hints.ai_protocol = 0; /* Any protocol */
1182 s = getaddrinfo (host, port_string, &hints, &result);
1184 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %s\n", host, port, gai_strerror (s));
1188 /* The PS3 doesn't even have _r or hstrerror () */
1189 result = gethostbyname (host);
1191 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, h_errno);
1196 if (agent_config.server) {
1197 #ifdef HAVE_GETADDRINFO
1198 /* Wait for a connection */
1200 struct sockaddr_in addr;
1203 /* No address, generate one */
1204 sfd = socket (AF_INET, SOCK_STREAM, 0);
1207 /* This will bind the socket to a random port */
1208 res = listen (sfd, 16);
1210 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1215 addrlen = sizeof (addr);
1216 memset (&addr, 0, sizeof (addr));
1217 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1218 g_assert (res == 0);
1220 host = (char*)"127.0.0.1";
1221 port = ntohs (addr.sin_port);
1223 /* Emit the address to stdout */
1224 /* FIXME: Should print another interface, not localhost */
1225 printf ("%s:%d\n", host, port);
1227 /* Listen on the provided address */
1228 for (rp = result; rp != NULL; rp = rp->ai_next) {
1231 sfd = socket (rp->ai_family, rp->ai_socktype,
1236 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1239 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
1243 res = listen (sfd, 16);
1252 * this function is not present on win2000 which we still support, and the
1253 * workaround described here:
1254 * http://msdn.microsoft.com/en-us/library/ms737931(VS.85).aspx
1255 * only works with MSVC.
1257 #ifdef HAVE_GETADDRINFO
1258 freeaddrinfo (result);
1263 if (agent_config.defer)
1266 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
1268 if (agent_config.timeout) {
1273 tv.tv_usec = agent_config.timeout * 1000;
1275 FD_SET (sfd, &readfds);
1276 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1278 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1283 conn_fd = socket_transport_accept (sfd);
1287 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
1290 #endif /* HAVE_GETADDRINFO */
1292 /* Connect to the specified address */
1293 #ifdef HAVE_GETADDRINFO
1294 /* FIXME: Respect the timeout */
1295 for (rp = result; rp != NULL; rp = rp->ai_next) {
1296 sfd = socket (rp->ai_family, rp->ai_socktype,
1301 if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
1302 break; /* Success */
1308 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1312 sfd = socket (result->h_addrtype, SOCK_STREAM, 0);
1314 g_assert_not_reached ();
1315 res = connect (sfd, (void*)result->h_addr_list [0], result->h_length);
1317 g_assert_not_reached ();
1323 /* See the comment above */
1324 #ifdef HAVE_GETADDRINFO
1325 freeaddrinfo (result);
1330 if (!transport_handshake ())
1335 socket_transport_close1 (void)
1337 /* This will interrupt the agent thread */
1338 /* Close the read part only so it can still send back replies */
1339 /* Also shut down the connection listener so that we can exit normally */
1341 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1342 shutdown (conn_fd, SD_BOTH);
1343 shutdown (listen_fd, SD_BOTH);
1344 closesocket (listen_fd);
1346 shutdown (conn_fd, SHUT_RD);
1347 shutdown (listen_fd, SHUT_RDWR);
1353 socket_transport_close2 (void)
1356 shutdown (conn_fd, SD_BOTH);
1358 shutdown (conn_fd, SHUT_RDWR);
1363 register_socket_transport (void)
1365 DebuggerTransport trans;
1367 trans.name = "dt_socket";
1368 trans.connect = socket_transport_connect;
1369 trans.close1 = socket_transport_close1;
1370 trans.close2 = socket_transport_close2;
1371 trans.send = socket_transport_send;
1372 trans.recv = socket_transport_recv;
1374 register_transport (&trans);
1377 #endif /* DISABLE_SOCKET_TRANSPORT */
1383 #define MAX_TRANSPORTS 16
1385 static DebuggerTransport *transport;
1387 static DebuggerTransport transports [MAX_TRANSPORTS];
1388 static int ntransports;
1391 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1394 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1396 register_transport (trans);
1400 register_transport (DebuggerTransport *trans)
1402 g_assert (ntransports < MAX_TRANSPORTS);
1404 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1409 transport_init (void)
1413 #ifndef DISABLE_SOCKET_TRANSPORT
1414 register_socket_transport ();
1417 for (i = 0; i < ntransports; ++i) {
1418 if (!strcmp (agent_config.transport, transports [i].name))
1421 if (i == ntransports) {
1422 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1423 for (i = 0; i < ntransports; ++i)
1424 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1425 fprintf (stderr, "\n");
1428 transport = &transports [i];
1432 transport_connect (const char *address)
1434 transport->connect (address);
1438 transport_close1 (void)
1440 transport->close1 ();
1444 transport_close2 (void)
1446 transport->close2 ();
1450 transport_send (void *buf, int len)
1452 return transport->send (buf, len);
1456 transport_recv (void *buf, int len)
1458 return transport->recv (buf, len);
1462 mono_debugger_agent_transport_handshake (void)
1464 return transport_handshake ();
1468 transport_handshake (void)
1470 char handshake_msg [128];
1474 disconnected = TRUE;
1476 /* Write handshake message */
1477 sprintf (handshake_msg, "DWP-Handshake");
1479 res = transport_send (handshake_msg, strlen (handshake_msg));
1480 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1481 g_assert (res != -1);
1484 res = transport_recv (buf, strlen (handshake_msg));
1485 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg) != 0))) {
1486 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1491 * To support older clients, the client sends its protocol version after connecting
1492 * using a command. Until that is received, default to our protocol version.
1494 major_version = MAJOR_VERSION;
1495 minor_version = MINOR_VERSION;
1496 protocol_version_set = FALSE;
1498 #ifndef DISABLE_SOCKET_TRANSPORT
1499 // FIXME: Move this somewhere else
1501 * Set TCP_NODELAY on the socket so the client receives events/command
1502 * results immediately.
1506 int result = setsockopt (conn_fd,
1511 g_assert (result >= 0);
1517 disconnected = FALSE;
1522 stop_debugger_thread (void)
1527 transport_close1 ();
1530 * Wait for the thread to exit.
1532 * If we continue with the shutdown without waiting for it, then the client might
1533 * not receive an answer to its last command like a resume.
1534 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
1537 //WaitForSingleObject (debugger_thread_handle, INFINITE);
1538 if (GetCurrentThreadId () != debugger_thread_id) {
1540 mono_mutex_lock (&debugger_thread_exited_mutex);
1541 if (!debugger_thread_exited) {
1543 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
1544 mono_mutex_unlock (&debugger_thread_exited_mutex);
1546 mono_mutex_lock (&debugger_thread_exited_mutex);
1549 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1552 mono_mutex_unlock (&debugger_thread_exited_mutex);
1553 } while (!debugger_thread_exited);
1556 transport_close2 ();
1560 start_debugger_thread (void)
1564 debugger_thread_handle = mono_create_thread (NULL, 0, debugger_thread, NULL, 0, &tid);
1565 g_assert (debugger_thread_handle);
1569 * Functions to decode protocol data
1573 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1576 g_assert (*endbuf <= limit);
1581 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1584 g_assert (*endbuf <= limit);
1586 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1589 static inline gint64
1590 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1592 guint32 high = decode_int (buf, &buf, limit);
1593 guint32 low = decode_int (buf, &buf, limit);
1597 return ((((guint64)high) << 32) | ((guint64)low));
1601 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1603 return decode_int (buf, endbuf, limit);
1607 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1609 int len = decode_int (buf, &buf, limit);
1617 s = g_malloc (len + 1);
1620 memcpy (s, buf, len);
1629 * Functions to encode protocol data
1633 guint8 *buf, *p, *end;
1637 buffer_init (Buffer *buf, int size)
1639 buf->buf = g_malloc (size);
1641 buf->end = buf->buf + size;
1645 buffer_make_room (Buffer *buf, int size)
1647 if (buf->end - buf->p < size) {
1648 int new_size = buf->end - buf->buf + size + 32;
1649 guint8 *p = g_realloc (buf->buf, new_size);
1650 size = buf->p - buf->buf;
1653 buf->end = buf->buf + new_size;
1658 buffer_add_byte (Buffer *buf, guint8 val)
1660 buffer_make_room (buf, 1);
1666 buffer_add_short (Buffer *buf, guint32 val)
1668 buffer_make_room (buf, 2);
1669 buf->p [0] = (val >> 8) & 0xff;
1670 buf->p [1] = (val >> 0) & 0xff;
1675 buffer_add_int (Buffer *buf, guint32 val)
1677 buffer_make_room (buf, 4);
1678 buf->p [0] = (val >> 24) & 0xff;
1679 buf->p [1] = (val >> 16) & 0xff;
1680 buf->p [2] = (val >> 8) & 0xff;
1681 buf->p [3] = (val >> 0) & 0xff;
1686 buffer_add_long (Buffer *buf, guint64 l)
1688 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1689 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1693 buffer_add_id (Buffer *buf, int id)
1695 buffer_add_int (buf, (guint64)id);
1699 buffer_add_data (Buffer *buf, guint8 *data, int len)
1701 buffer_make_room (buf, len);
1702 memcpy (buf->p, data, len);
1707 buffer_add_string (Buffer *buf, const char *str)
1712 buffer_add_int (buf, 0);
1715 buffer_add_int (buf, len);
1716 buffer_add_data (buf, (guint8*)str, len);
1721 buffer_free (Buffer *buf)
1727 send_packet (int command_set, int command, Buffer *data)
1733 id = InterlockedIncrement (&packet_id);
1735 len = data->p - data->buf + 11;
1736 buffer_init (&buf, len);
1737 buffer_add_int (&buf, len);
1738 buffer_add_int (&buf, id);
1739 buffer_add_byte (&buf, 0); /* flags */
1740 buffer_add_byte (&buf, command_set);
1741 buffer_add_byte (&buf, command);
1742 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1744 res = transport_send (buf.buf, len);
1752 send_reply_packet (int id, int error, Buffer *data)
1758 len = data->p - data->buf + 11;
1759 buffer_init (&buf, len);
1760 buffer_add_int (&buf, len);
1761 buffer_add_int (&buf, id);
1762 buffer_add_byte (&buf, 0x80); /* flags */
1763 buffer_add_byte (&buf, (error >> 8) & 0xff);
1764 buffer_add_byte (&buf, error);
1765 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1767 res = transport_send (buf.buf, len);
1779 * Represents an object accessible by the debugger client.
1782 /* Unique id used in the wire protocol to refer to objects */
1785 * A weakref gc handle pointing to the object. The gc handle is used to
1786 * detect if the object was garbage collected.
1791 /* Maps objid -> ObjRef */
1792 static GHashTable *objrefs;
1795 free_objref (gpointer value)
1799 mono_gchandle_free (o->handle);
1807 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1811 objrefs_cleanup (void)
1813 g_hash_table_destroy (objrefs);
1817 static GHashTable *obj_to_objref;
1818 static MonoGHashTable *suspended_objs;
1821 * Return an ObjRef for OBJ.
1824 get_objref (MonoObject *obj)
1827 GSList *reflist = NULL, *l;
1833 mono_loader_lock ();
1835 if (!obj_to_objref) {
1836 obj_to_objref = g_hash_table_new (NULL, NULL);
1837 suspended_objs = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
1838 MONO_GC_REGISTER_ROOT_FIXED (suspended_objs);
1841 if (suspend_count) {
1843 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1845 mono_g_hash_table_insert (suspended_objs, obj, NULL);
1848 /* FIXME: The tables can grow indefinitely */
1850 if (mono_gc_is_moving ()) {
1852 * Objects can move, so use a hash table mapping hash codes to lists of
1853 * ObjRef structures.
1855 hash = mono_object_hash (obj);
1857 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1858 for (l = reflist; l; l = l->next) {
1860 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1861 mono_loader_unlock ();
1866 /* Use a hash table with masked pointers to internalize object references */
1867 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1868 /* ref might refer to a different object with the same addr which was GCd */
1869 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1870 mono_loader_unlock ();
1875 ref = g_new0 (ObjRef, 1);
1876 ref->id = InterlockedIncrement (&objref_id);
1877 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1879 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
1881 if (mono_gc_is_moving ()) {
1882 reflist = g_slist_append (reflist, ref);
1883 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
1885 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
1888 mono_loader_unlock ();
1894 true_pred (gpointer key, gpointer value, gpointer user_data)
1900 clear_suspended_objs (void)
1902 mono_loader_lock ();
1903 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
1904 mono_loader_unlock ();
1908 get_objid (MonoObject *obj)
1910 return get_objref (obj)->id;
1914 * Set OBJ to the object identified by OBJID.
1915 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
1919 get_object_allow_null (int objid, MonoObject **obj)
1929 return ERR_INVALID_OBJECT;
1931 mono_loader_lock ();
1933 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
1936 *obj = mono_gchandle_get_target (ref->handle);
1937 mono_loader_unlock ();
1939 return ERR_INVALID_OBJECT;
1942 mono_loader_unlock ();
1943 return ERR_INVALID_OBJECT;
1948 get_object (int objid, MonoObject **obj)
1950 int err = get_object_allow_null (objid, obj);
1955 return ERR_INVALID_OBJECT;
1960 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
1962 return decode_id (buf, endbuf, limit);
1966 buffer_add_objid (Buffer *buf, MonoObject *o)
1968 buffer_add_id (buf, get_objid (o));
1987 * Represents a runtime structure accessible to the debugger client
1990 /* Unique id used in the wire protocol */
1992 /* Domain of the runtime structure, NULL if the domain was unloaded */
1999 MonoAssembly *assembly;
2000 MonoClassField *field;
2002 MonoProperty *property;
2007 /* Maps runtime structure -> Id */
2008 GHashTable *val_to_id [ID_NUM];
2009 /* Classes whose class load event has been sent */
2010 GHashTable *loaded_classes;
2011 /* Maps MonoClass->GPtrArray of file names */
2012 GHashTable *source_files;
2013 /* Maps source file basename -> GSList of classes */
2014 GHashTable *source_file_to_class;
2015 /* Same with ignore-case */
2016 GHashTable *source_file_to_class_ignorecase;
2020 static GPtrArray *ids [ID_NUM];
2027 for (i = 0; i < ID_NUM; ++i)
2028 ids [i] = g_ptr_array_new ();
2036 for (i = 0; i < ID_NUM; ++i) {
2038 for (j = 0; j < ids [i]->len; ++j)
2039 g_free (g_ptr_array_index (ids [i], j));
2040 g_ptr_array_free (ids [i], TRUE);
2047 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2049 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
2051 GHashTableIter iter;
2052 GPtrArray *file_names;
2057 for (i = 0; i < ID_NUM; ++i)
2058 if (info->val_to_id [i])
2059 g_hash_table_destroy (info->val_to_id [i]);
2060 g_hash_table_destroy (info->loaded_classes);
2062 g_hash_table_iter_init (&iter, info->source_files);
2063 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2064 for (i = 0; i < file_names->len; ++i)
2065 g_free (g_ptr_array_index (file_names, i));
2066 g_ptr_array_free (file_names, TRUE);
2069 g_hash_table_iter_init (&iter, info->source_file_to_class);
2070 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2075 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2076 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2084 domain_jit_info (domain)->agent_info = NULL;
2086 /* Clear ids referencing structures in the domain */
2087 for (i = 0; i < ID_NUM; ++i) {
2089 for (j = 0; j < ids [i]->len; ++j) {
2090 Id *id = g_ptr_array_index (ids [i], j);
2091 if (id->domain == domain)
2097 mono_loader_lock ();
2098 g_hash_table_remove (domains, domain);
2099 mono_loader_unlock ();
2102 static AgentDomainInfo*
2103 get_agent_domain_info (MonoDomain *domain)
2105 AgentDomainInfo *info = NULL;
2107 mono_domain_lock (domain);
2109 info = domain_jit_info (domain)->agent_info;
2111 info = domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
2112 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2113 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2114 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2115 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2118 mono_domain_unlock (domain);
2124 get_id (MonoDomain *domain, IdType type, gpointer val)
2127 AgentDomainInfo *info;
2132 mono_loader_lock ();
2134 mono_domain_lock (domain);
2136 info = get_agent_domain_info (domain);
2138 if (info->val_to_id [type] == NULL)
2139 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2141 id = g_hash_table_lookup (info->val_to_id [type], val);
2143 mono_domain_unlock (domain);
2144 mono_loader_unlock ();
2148 id = g_new0 (Id, 1);
2150 id->id = ids [type]->len + 1;
2151 id->domain = domain;
2154 g_hash_table_insert (info->val_to_id [type], val, id);
2156 mono_domain_unlock (domain);
2158 g_ptr_array_add (ids [type], id);
2160 mono_loader_unlock ();
2165 static inline gpointer
2166 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
2170 int id = decode_id (buf, endbuf, limit);
2179 // FIXME: error handling
2180 mono_loader_lock ();
2181 g_assert (id > 0 && id <= ids [type]->len);
2183 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2184 mono_loader_unlock ();
2186 if (res->domain == NULL) {
2187 *err = ERR_UNLOADED;
2192 *domain = res->domain;
2194 return res->data.val;
2198 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2200 buffer_add_id (buf, get_id (domain, type, val));
2203 static inline MonoClass*
2204 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2206 return decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2209 static inline MonoAssembly*
2210 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2212 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2215 static inline MonoImage*
2216 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2218 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2221 static inline MonoMethod*
2222 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2224 return decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2227 static inline MonoClassField*
2228 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2230 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2233 static inline MonoDomain*
2234 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2236 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2239 static inline MonoProperty*
2240 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2242 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2246 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2248 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2252 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2254 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2258 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2260 buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2264 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2266 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2270 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2272 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2276 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2278 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2282 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2284 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2287 static void invoke_method (void);
2294 * save_thread_context:
2296 * Set CTX as the current threads context which is used for computing stack traces.
2297 * This function is signal-safe.
2300 save_thread_context (MonoContext *ctx)
2302 DebuggerTlsData *tls;
2304 tls = mono_native_tls_get_value (debugger_tls_id);
2308 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2310 mono_thread_state_init_from_current (&tls->context);
2313 /* Number of threads suspended */
2315 * If this is equal to the size of thread_to_tls, the runtime is considered
2318 static gint32 threads_suspend_count;
2320 static mono_mutex_t suspend_mutex;
2322 /* Cond variable used to wait for suspend_count becoming 0 */
2323 static mono_cond_t suspend_cond;
2325 /* Semaphore used to wait for a thread becoming suspended */
2326 static MonoSemType suspend_sem;
2331 mono_mutex_init (&suspend_mutex, NULL);
2332 mono_cond_init (&suspend_cond, NULL);
2333 MONO_SEM_INIT (&suspend_sem, 0);
2338 StackFrameInfo last_frame;
2339 gboolean last_frame_set;
2342 } GetLastFrameUserData;
2345 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2347 GetLastFrameUserData *data = user_data;
2349 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
2352 if (!data->last_frame_set) {
2353 /* Store the last frame */
2354 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2355 data->last_frame_set = TRUE;
2358 /* Store the context/lmf for the frame above the last frame */
2359 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2360 data->lmf = info->lmf;
2368 * Process interruption of a thread. If SIGCTX is set, process the current thread. If
2369 * INFO is set, process the thread described by INFO.
2370 * This should be signal safe.
2373 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, void *sigctx, MonoJitInfo *ji)
2377 MonoNativeThreadId tid;
2380 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2381 * guarantee the signal handler will be called that many times. Instead of tracking
2382 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2383 * has been requested that hasn't been handled yet, otherwise we can have threads
2384 * refuse to die when VM_EXIT is called
2386 #if defined(__APPLE__)
2387 if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
2391 * We use interrupt_count to determine whenever this interrupt should be processed
2392 * by us or the normal interrupt processing code in the signal handler.
2393 * There is no race here with notify_thread (), since the signal is sent after
2394 * incrementing interrupt_count.
2396 if (tls->interrupt_count == 0)
2399 InterlockedDecrement (&tls->interrupt_count);
2403 ip = mono_arch_ip_from_context (sigctx);
2405 ip = MONO_CONTEXT_GET_IP (&info->suspend_state.ctx);
2410 tid = mono_thread_info_get_tid (info);
2412 tid = (MonoNativeThreadId)GetCurrentThreadId ();
2414 // FIXME: Races when the thread leaves managed code before hitting a single step
2418 /* Running managed code, will be suspended by the single step code */
2419 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, ji->method->name, ip));
2423 * Running native code, will be suspended when it returns to/enters
2424 * managed code. Treat it as already suspended.
2425 * This might interrupt the code in process_single_step_inner (), we use the
2426 * tls->suspending flag to avoid races when that happens.
2428 if (!tls->suspended && !tls->suspending) {
2430 GetLastFrameUserData data;
2432 // FIXME: printf is not signal safe, but this is only used during
2433 // debugger debugging
2435 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip));
2436 //save_thread_context (&ctx);
2439 /* Already terminated */
2442 tls->context.valid = FALSE;
2445 * We are in a difficult position: we want to be able to provide stack
2446 * traces for this thread, but we can't use the current ctx+lmf, since
2447 * the thread is still running, so it might return to managed code,
2448 * making these invalid.
2449 * So we start a stack walk and save the first frame, along with the
2450 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2451 * suspended when it returns to managed code, so the parent's ctx should
2454 data.last_frame_set = FALSE;
2456 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
2458 * Don't pass MONO_UNWIND_ACTUAL_METHOD, its not signal safe, and
2459 * get_last_frame () doesn't need it, the last frame cannot be a ginst
2460 * since we are not in a JITted method.
2462 mono_walk_stack_with_ctx (get_last_frame, &ctx, MONO_UNWIND_NONE, &data);
2464 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, &info->suspend_state, MONO_UNWIND_SIGNAL_SAFE, &data);
2466 if (data.last_frame_set) {
2467 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2468 res = mono_thread_state_init_from_monoctx (&tls->async_state, &ctx);
2470 mono_thread_state_init_from_monoctx (&tls->context, &ctx);
2473 memcpy (&tls->async_state.ctx, &data.ctx, sizeof (MonoContext));
2474 tls->async_state.unwind_data [MONO_UNWIND_DATA_LMF] = data.lmf;
2475 tls->async_state.unwind_data [MONO_UNWIND_DATA_JIT_TLS] = tls->thread->jit_data;
2477 /* No managed frames */
2478 tls->async_state.valid = FALSE;
2480 mono_memory_barrier ();
2482 tls->suspended = TRUE;
2483 MONO_SEM_POST (&suspend_sem);
2490 * mono_debugger_agent_thread_interrupt:
2492 * Called by the abort signal handler.
2493 * Should be signal safe.
2496 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
2498 DebuggerTlsData *tls;
2503 tls = mono_native_tls_get_value (debugger_tls_id);
2505 DEBUG (1, fprintf (log_file, "[%p] Received interrupt with no TLS, continuing.\n", (gpointer)GetCurrentThreadId ()));
2509 return thread_interrupt (tls, NULL, sigctx, ji);
2513 static void CALLBACK notify_thread_apc (ULONG_PTR param)
2516 mono_debugger_agent_thread_interrupt (NULL, NULL);
2518 #endif /* HOST_WIN32 */
2521 * reset_native_thread_suspend_state:
2523 * Reset the suspended flag and state on native threads
2526 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2528 DebuggerTlsData *tls = value;
2530 if (!tls->really_suspended && tls->suspended) {
2531 tls->suspended = FALSE;
2533 * The thread might still be running if it was executing native code, so the state won't be invalided by
2534 * suspend_current ().
2536 tls->context.valid = FALSE;
2537 tls->async_state.valid = FALSE;
2538 invalidate_frames (tls);
2545 * Notify a thread that it needs to suspend.
2548 notify_thread (gpointer key, gpointer value, gpointer user_data)
2550 MonoInternalThread *thread = key;
2551 DebuggerTlsData *tls = value;
2552 gsize tid = thread->tid;
2555 if (GetCurrentThreadId () == tid || tls->terminated)
2558 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2561 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2562 * guarantee the signal handler will be called that many times. Instead of tracking
2563 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2564 * has been requested that hasn't been handled yet, otherwise we can have threads
2565 * refuse to die when VM_EXIT is called
2567 #if defined(__APPLE__)
2568 if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
2572 * Maybe we could use the normal interrupt infrastructure, but that does a lot
2573 * of things like breaking waits etc. which we don't want.
2575 InterlockedIncrement (&tls->interrupt_count);
2578 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2580 QueueUserAPC (notify_thread_apc, thread->handle, NULL);
2582 if (mono_thread_info_new_interrupt_enabled ()) {
2583 MonoThreadInfo *info;
2586 info = mono_thread_info_safe_suspend_sync ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE);
2588 DEBUG(1, fprintf (log_file, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2590 * Attached thread which died without detaching.
2592 tls->terminated = TRUE;
2594 ji = mono_jit_info_table_find (info->suspend_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], MONO_CONTEXT_GET_IP (&info->suspend_state.ctx));
2596 thread_interrupt (tls, info, NULL, ji);
2598 mono_thread_info_resume (mono_thread_info_get_tid (info));
2601 res = mono_thread_kill (thread, mono_thread_get_abort_signal ());
2603 DEBUG(1, fprintf (log_file, "[%p] mono_thread_kill () failed for %p: %d...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid, res));
2605 * Attached thread which died without detaching.
2607 tls->terminated = TRUE;
2614 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2616 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2619 if (mono_loader_lock_is_owned_by_self ()) {
2621 * Shortcut for the check in suspend_current (). This speeds up processing
2622 * when executing long running code inside the loader lock, i.e. assembly load
2628 if (debugger_thread_id == GetCurrentThreadId ())
2631 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2632 if (suspend_count - tls->resume_count > 0)
2633 tls->suspending = TRUE;
2635 DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2637 if (suspend_count - tls->resume_count == 0) {
2639 * We are executing a single threaded invoke but the single step for
2640 * suspending is still active.
2641 * FIXME: This slows down single threaded invokes.
2643 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
2647 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2649 /* Can't suspend in these methods */
2650 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
2653 save_thread_context (ctx);
2661 * Increase the suspend count of the VM. While the suspend count is greater
2662 * than 0, runtime threads are suspended at certain points during execution.
2667 mono_loader_lock ();
2669 mono_mutex_lock (&suspend_mutex);
2673 DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
2675 if (suspend_count == 1) {
2676 // FIXME: Is it safe to call this inside the lock ?
2677 start_single_stepping ();
2678 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2681 mono_mutex_unlock (&suspend_mutex);
2683 mono_loader_unlock ();
2689 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2697 g_assert (debugger_thread_id == GetCurrentThreadId ());
2699 mono_loader_lock ();
2701 mono_mutex_lock (&suspend_mutex);
2703 g_assert (suspend_count > 0);
2706 DEBUG(1, fprintf (log_file, "[%p] Resuming vm, suspend count=%d...\n", (gpointer)GetCurrentThreadId (), suspend_count));
2708 if (suspend_count == 0) {
2709 // FIXME: Is it safe to call this inside the lock ?
2710 stop_single_stepping ();
2711 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2714 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2715 err = mono_cond_broadcast (&suspend_cond);
2716 g_assert (err == 0);
2718 mono_mutex_unlock (&suspend_mutex);
2719 //g_assert (err == 0);
2721 mono_loader_unlock ();
2727 * Resume just one thread.
2730 resume_thread (MonoInternalThread *thread)
2733 DebuggerTlsData *tls;
2735 g_assert (debugger_thread_id == GetCurrentThreadId ());
2737 mono_loader_lock ();
2739 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2742 mono_mutex_lock (&suspend_mutex);
2744 g_assert (suspend_count > 0);
2746 DEBUG(1, fprintf (log_file, "[%p] Resuming thread...\n", (gpointer)(gssize)thread->tid));
2748 tls->resume_count += suspend_count;
2751 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2752 * but only the one whose resume_count field is > 0 will be resumed.
2754 err = mono_cond_broadcast (&suspend_cond);
2755 g_assert (err == 0);
2757 mono_mutex_unlock (&suspend_mutex);
2758 //g_assert (err == 0);
2760 mono_loader_unlock ();
2764 invalidate_frames (DebuggerTlsData *tls)
2769 tls = mono_native_tls_get_value (debugger_tls_id);
2772 for (i = 0; i < tls->frame_count; ++i) {
2773 if (tls->frames [i]->jit)
2774 mono_debug_free_method_jit_info (tls->frames [i]->jit);
2775 g_free (tls->frames [i]);
2777 g_free (tls->frames);
2778 tls->frame_count = 0;
2785 * Suspend the current thread until the runtime is resumed. If the thread has a
2786 * pending invoke, then the invoke is executed before this function returns.
2789 suspend_current (void)
2792 DebuggerTlsData *tls;
2794 g_assert (debugger_thread_id != GetCurrentThreadId ());
2796 if (mono_loader_lock_is_owned_by_self ()) {
2798 * If we own the loader mutex, can't suspend until we release it, since the
2799 * whole runtime can deadlock otherwise.
2804 tls = mono_native_tls_get_value (debugger_tls_id);
2807 mono_mutex_lock (&suspend_mutex);
2809 tls->suspending = FALSE;
2810 tls->really_suspended = TRUE;
2812 if (!tls->suspended) {
2813 tls->suspended = TRUE;
2814 MONO_SEM_POST (&suspend_sem);
2817 DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
2819 while (suspend_count - tls->resume_count > 0) {
2821 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
2823 mono_mutex_unlock (&suspend_mutex);
2825 mono_mutex_lock (&suspend_mutex);
2831 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
2832 g_assert (err == 0);
2836 tls->suspended = FALSE;
2837 tls->really_suspended = FALSE;
2839 threads_suspend_count --;
2841 mono_mutex_unlock (&suspend_mutex);
2843 DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
2845 if (tls->pending_invoke) {
2846 /* Save the original context */
2847 tls->pending_invoke->has_ctx = TRUE;
2848 tls->pending_invoke->ctx = tls->context.ctx;
2853 /* The frame info becomes invalid after a resume */
2854 tls->context.valid = FALSE;
2855 tls->async_state.valid = FALSE;
2856 invalidate_frames (tls);
2860 count_thread (gpointer key, gpointer value, gpointer user_data)
2862 DebuggerTlsData *tls = value;
2864 if (!tls->suspended && !tls->terminated)
2865 *(int*)user_data = *(int*)user_data + 1;
2869 count_threads_to_wait_for (void)
2873 mono_loader_lock ();
2874 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
2875 mono_loader_unlock ();
2883 * Wait until the runtime is completely suspended.
2886 wait_for_suspend (void)
2888 int nthreads, nwait, err;
2889 gboolean waited = FALSE;
2891 // FIXME: Threads starting/stopping ?
2892 mono_loader_lock ();
2893 nthreads = mono_g_hash_table_size (thread_to_tls);
2894 mono_loader_unlock ();
2897 nwait = count_threads_to_wait_for ();
2899 DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
2900 err = MONO_SEM_WAIT (&suspend_sem);
2901 g_assert (err == 0);
2909 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
2915 * Return whenever the runtime is suspended.
2920 return count_threads_to_wait_for () == 0;
2923 static MonoSeqPointInfo*
2924 get_seq_points (MonoDomain *domain, MonoMethod *method)
2926 MonoSeqPointInfo *seq_points;
2928 mono_domain_lock (domain);
2929 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2930 if (!seq_points && method->is_inflated) {
2931 /* generic sharing + aot */
2932 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (method));
2934 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mini_get_shared_method (method));
2936 mono_domain_unlock (domain);
2941 static MonoSeqPointInfo*
2942 find_seq_points (MonoDomain *domain, MonoMethod *method)
2944 MonoSeqPointInfo *seq_points = get_seq_points (domain, method);
2947 printf ("Unable to find seq points for method '%s'.\n", mono_method_full_name (method, TRUE));
2948 g_assert (seq_points);
2954 * find_next_seq_point_for_native_offset:
2956 * Find the first sequence point after NATIVE_OFFSET.
2959 find_next_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2961 MonoSeqPointInfo *seq_points;
2964 seq_points = find_seq_points (domain, method);
2965 g_assert (seq_points);
2969 for (i = 0; i < seq_points->len; ++i) {
2970 if (seq_points->seq_points [i].native_offset >= native_offset)
2971 return &seq_points->seq_points [i];
2978 * find_prev_seq_point_for_native_offset:
2980 * Find the first sequence point before NATIVE_OFFSET.
2983 find_prev_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
2985 MonoSeqPointInfo *seq_points;
2988 seq_points = get_seq_points (domain, method);
2994 for (i = seq_points->len - 1; i >= 0; --i) {
2995 if (seq_points->seq_points [i].native_offset <= native_offset)
2996 return &seq_points->seq_points [i];
3005 * Find the sequence point corresponding to the IL offset IL_OFFSET, which
3006 * should be the location of a sequence point.
3008 static G_GNUC_UNUSED SeqPoint*
3009 find_seq_point (MonoDomain *domain, MonoMethod *method, gint32 il_offset, MonoSeqPointInfo **info)
3011 MonoSeqPointInfo *seq_points;
3016 seq_points = get_seq_points (domain, method);
3021 for (i = 0; i < seq_points->len; ++i) {
3022 if (seq_points->seq_points [i].il_offset == il_offset)
3023 return &seq_points->seq_points [i];
3030 DebuggerTlsData *tls;
3032 } ComputeFramesUserData;
3035 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3037 ComputeFramesUserData *ud = user_data;
3039 MonoMethod *method, *actual_method, *api_method;
3043 if (info->type != FRAME_TYPE_MANAGED) {
3044 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3045 /* Mark the last frame as an invoke frame */
3047 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3053 method = info->ji->method;
3055 method = info->method;
3056 actual_method = info->actual_method;
3057 api_method = method;
3062 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3065 if (info->il_offset == -1) {
3066 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3067 if (ud->frames == NULL) {
3068 sp = find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL);
3070 info->il_offset = sp->il_offset;
3072 if (info->il_offset == -1)
3073 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3076 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));
3078 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3079 if (!CHECK_PROTOCOL_VERSION (2, 17))
3080 /* Older clients can't handle this flag */
3082 api_method = mono_marshal_method_from_wrapper (method);
3085 actual_method = api_method;
3086 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3089 frame = g_new0 (StackFrame, 1);
3090 frame->method = method;
3091 frame->actual_method = actual_method;
3092 frame->api_method = api_method;
3093 frame->il_offset = info->il_offset;
3094 frame->native_offset = info->native_offset;
3095 frame->flags = flags;
3096 frame->ji = info->ji;
3097 if (info->reg_locations)
3098 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3101 frame->has_ctx = TRUE;
3103 frame->domain = info->domain;
3105 ud->frames = g_slist_append (ud->frames, frame);
3111 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3113 ComputeFramesUserData *ud = user_data;
3116 * 'tls->filter_ctx' is the location of the throw site.
3118 * mono_walk_stack() will never actually hit the throw site, but unwind
3119 * directly from the filter to the call site; we abort stack unwinding here
3120 * once this happens and resume from the throw site.
3123 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3126 return process_frame (info, ctx, user_data);
3130 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3132 ComputeFramesUserData user_data;
3134 int i, findex, new_frame_count;
3135 StackFrame **new_frames, *f;
3136 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3138 // FIXME: Locking on tls
3139 if (tls->frames && tls->frames_up_to_date)
3142 DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
3144 user_data.tls = tls;
3145 user_data.frames = NULL;
3146 if (tls->terminated) {
3147 tls->frame_count = 0;
3149 } if (!tls->really_suspended && tls->async_state.valid) {
3150 /* Have to use the state saved by the signal handler */
3151 process_frame (&tls->async_last_frame, NULL, &user_data);
3152 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3153 } else if (tls->filter_state.valid) {
3155 * We are inside an exception filter.
3157 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3159 if (tls->context.valid)
3160 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3162 * After that, we resume unwinding from the location where the exception has been thrown.
3164 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3165 } else if (tls->context.valid) {
3166 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3169 tls->frame_count = 0;
3173 new_frame_count = g_slist_length (user_data.frames);
3174 new_frames = g_new0 (StackFrame*, new_frame_count);
3176 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3180 * Reuse the id for already existing stack frames, so invokes don't invalidate
3181 * the still valid stack frames.
3183 for (i = 0; i < tls->frame_count; ++i) {
3184 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3185 f->id = tls->frames [i]->id;
3190 if (i >= tls->frame_count)
3191 f->id = InterlockedIncrement (&frame_id);
3193 new_frames [findex ++] = f;
3196 g_slist_free (user_data.frames);
3198 invalidate_frames (tls);
3200 tls->frames = new_frames;
3201 tls->frame_count = new_frame_count;
3202 tls->frames_up_to_date = TRUE;
3206 * GHFunc to emit an appdomain creation event
3207 * @param key Don't care
3208 * @param value A loaded appdomain
3209 * @param user_data Don't care
3212 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3214 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3215 g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
3219 * GHFunc to emit a thread start event
3220 * @param key A thread id
3221 * @param value A thread object
3222 * @param user_data Don't care
3225 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3227 if (GPOINTER_TO_INT (key) != debugger_thread_id)
3228 process_profiler_event (EVENT_KIND_THREAD_START, value);
3232 * GFunc to emit an assembly load event
3233 * @param value A loaded assembly
3234 * @param user_data Don't care
3237 emit_assembly_load (gpointer value, gpointer user_data)
3239 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3243 * GFunc to emit a type load event
3244 * @param value A loaded type
3245 * @param user_data Don't care
3248 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3250 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3254 strdup_tolower (char *s)
3259 for (p = s2; *p; ++p)
3269 * create_event_list:
3271 * Return a list of event request ids matching EVENT, starting from REQS, which
3272 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3274 * We return request ids, instead of requests, to simplify threading, since
3275 * requests could be deleted anytime when the loader lock is not held.
3276 * LOCKING: Assumes the loader lock is held.
3279 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3282 GSList *events = NULL;
3284 *suspend_policy = SUSPEND_POLICY_NONE;
3287 reqs = event_requests;
3292 for (i = 0; i < reqs->len; ++i) {
3293 EventRequest *req = g_ptr_array_index (reqs, i);
3294 if (req->event_kind == event) {
3295 gboolean filtered = FALSE;
3298 for (j = 0; j < req->nmodifiers; ++j) {
3299 Modifier *mod = &req->modifiers [j];
3301 if (mod->kind == MOD_KIND_COUNT) {
3303 if (mod->data.count > 0) {
3304 if (mod->data.count > 0) {
3306 if (mod->data.count == 0)
3310 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3311 if (mod->data.thread != mono_thread_internal_current ())
3313 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3314 if (mod->data.exc_class && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3316 if (ei->caught && !mod->caught)
3318 if (!ei->caught && !mod->uncaught)
3320 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3322 gboolean found = FALSE;
3323 MonoAssembly **assemblies = mod->data.assemblies;
3326 for (k = 0; assemblies [k]; ++k)
3327 if (assemblies [k] == ji->method->klass->image->assembly)
3332 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3333 gpointer iter = NULL;
3335 MonoDebugSourceInfo *sinfo;
3336 char *source_file, *s;
3337 gboolean found = FALSE;
3339 GPtrArray *source_file_list;
3341 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3342 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3345 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, NULL, NULL, NULL, NULL, NULL);
3346 for (i = 0; i < source_file_list->len; ++i) {
3347 sinfo = g_ptr_array_index (source_file_list, i);
3349 * Do a case-insesitive match by converting the file name to
3352 s = strdup_tolower (sinfo->source_file);
3353 if (g_hash_table_lookup (mod->data.source_files, s))
3356 char *s2 = g_path_get_basename (sinfo->source_file);
3357 char *s3 = strdup_tolower (s2);
3359 if (g_hash_table_lookup (mod->data.source_files, s3))
3366 g_ptr_array_free (source_file_list, TRUE);
3371 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3374 s = mono_type_full_name (&ei->klass->byval_arg);
3375 if (!g_hash_table_lookup (mod->data.type_names, s))
3378 } else if (mod->kind == MOD_KIND_STEP) {
3379 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3380 (ji->method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3381 !strcmp (ji->method->name, ".cctor"))
3383 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3384 MonoCustomAttrInfo *ainfo;
3385 static MonoClass *klass;
3388 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3391 if (!ji->dbg_hidden_inited) {
3392 ainfo = mono_custom_attrs_from_method (ji->method);
3394 if (mono_custom_attrs_has_attr (ainfo, klass))
3395 ji->dbg_hidden = TRUE;
3396 mono_custom_attrs_free (ainfo);
3398 ji->dbg_hidden_inited = TRUE;
3407 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3408 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3413 /* Send a VM START/DEATH event by default */
3414 if (event == EVENT_KIND_VM_START)
3415 events = g_slist_append (events, GINT_TO_POINTER (0));
3416 if (event == EVENT_KIND_VM_DEATH)
3417 events = g_slist_append (events, GINT_TO_POINTER (0));
3422 static G_GNUC_UNUSED const char*
3423 event_to_string (EventKind event)
3426 case EVENT_KIND_VM_START: return "VM_START";
3427 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3428 case EVENT_KIND_THREAD_START: return "THREAD_START";
3429 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3430 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3431 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3432 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3433 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3434 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3435 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3436 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3437 case EVENT_KIND_STEP: return "STEP";
3438 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3439 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3440 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3441 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3442 case EVENT_KIND_USER_LOG: return "USER_LOG";
3444 g_assert_not_reached ();
3451 * Send an event to the client, suspending the vm if needed.
3452 * LOCKING: Since this can suspend the calling thread, no locks should be held
3454 * The EVENTS list is freed by this function.
3457 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3461 MonoDomain *domain = mono_domain_get ();
3462 MonoThread *thread = NULL;
3463 gboolean send_success = FALSE;
3468 DEBUG (2, fprintf (log_file, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event)));
3472 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3473 // FIXME: We miss those events
3474 DEBUG (2, fprintf (log_file, "VM start event not sent yet: dropping %s\n", event_to_string (event)));
3478 if (vm_death_event_sent) {
3479 DEBUG (2, fprintf (log_file, "VM death event has been sent: dropping %s\n", event_to_string (event)));
3483 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3484 DEBUG (2, fprintf (log_file, "Mono runtime is shutting down: dropping %s\n", event_to_string (event)));
3489 DEBUG (2, fprintf (log_file, "Debugger client is not connected: dropping %s\n", event_to_string (event)));
3493 if (event == EVENT_KIND_KEEPALIVE)
3494 suspend_policy = SUSPEND_POLICY_NONE;
3499 if (agent_config.defer) {
3500 /* Make sure the thread id is always set when doing deferred debugging */
3501 if (debugger_thread_id == GetCurrentThreadId ()) {
3502 /* Don't suspend on events from the debugger thread */
3503 suspend_policy = SUSPEND_POLICY_NONE;
3504 thread = mono_thread_get_main ();
3506 else thread = mono_thread_current ();
3508 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3509 // FIXME: Send these with a NULL thread, don't suspend the current thread
3514 nevents = g_slist_length (events);
3515 buffer_init (&buf, 128);
3516 buffer_add_byte (&buf, suspend_policy);
3517 buffer_add_int (&buf, nevents);
3519 for (l = events; l; l = l->next) {
3520 buffer_add_byte (&buf, event); // event kind
3521 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3526 thread = mono_thread_current ();
3528 if (event == EVENT_KIND_VM_START && arg != NULL)
3531 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3534 case EVENT_KIND_THREAD_START:
3535 case EVENT_KIND_THREAD_DEATH:
3537 case EVENT_KIND_APPDOMAIN_CREATE:
3538 case EVENT_KIND_APPDOMAIN_UNLOAD:
3539 buffer_add_domainid (&buf, arg);
3541 case EVENT_KIND_METHOD_ENTRY:
3542 case EVENT_KIND_METHOD_EXIT:
3543 buffer_add_methodid (&buf, domain, arg);
3545 case EVENT_KIND_ASSEMBLY_LOAD:
3546 case EVENT_KIND_ASSEMBLY_UNLOAD:
3547 buffer_add_assemblyid (&buf, domain, arg);
3549 case EVENT_KIND_TYPE_LOAD:
3550 buffer_add_typeid (&buf, domain, arg);
3552 case EVENT_KIND_BREAKPOINT:
3553 case EVENT_KIND_STEP:
3554 buffer_add_methodid (&buf, domain, arg);
3555 buffer_add_long (&buf, il_offset);
3557 case EVENT_KIND_VM_START:
3558 buffer_add_domainid (&buf, mono_get_root_domain ());
3560 case EVENT_KIND_VM_DEATH:
3562 case EVENT_KIND_EXCEPTION: {
3563 EventInfo *ei = arg;
3564 buffer_add_objid (&buf, ei->exc);
3567 case EVENT_KIND_USER_BREAK:
3569 case EVENT_KIND_USER_LOG: {
3570 EventInfo *ei = arg;
3571 buffer_add_int (&buf, ei->level);
3572 buffer_add_string (&buf, ei->category ? ei->category : "");
3573 buffer_add_string (&buf, ei->message ? ei->message : "");
3576 case EVENT_KIND_KEEPALIVE:
3577 suspend_policy = SUSPEND_POLICY_NONE;
3580 g_assert_not_reached ();
3584 if (event == EVENT_KIND_VM_START) {
3585 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3586 if (!agent_config.defer)
3587 start_debugger_thread ();
3590 if (event == EVENT_KIND_VM_DEATH) {
3591 vm_death_event_sent = TRUE;
3592 suspend_policy = SUSPEND_POLICY_NONE;
3595 if (mono_runtime_is_shutting_down ())
3596 suspend_policy = SUSPEND_POLICY_NONE;
3598 if (suspend_policy != SUSPEND_POLICY_NONE) {
3600 * Save the thread context and start suspending before sending the packet,
3601 * since we could be receiving the resume request before send_packet ()
3604 save_thread_context (ctx);
3608 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3612 g_slist_free (events);
3615 if (!send_success) {
3616 DEBUG (2, fprintf (log_file, "Sending command %s failed.\n", event_to_string (event)));
3620 if (event == EVENT_KIND_VM_START) {
3621 vm_start_event_sent = TRUE;
3624 DEBUG (1, fprintf (log_file, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer)GetCurrentThreadId (), nevents, event_to_string (event), ecount, suspend_policy));
3626 switch (suspend_policy) {
3627 case SUSPEND_POLICY_NONE:
3629 case SUSPEND_POLICY_ALL:
3632 case SUSPEND_POLICY_EVENT_THREAD:
3636 g_assert_not_reached ();
3641 process_profiler_event (EventKind event, gpointer arg)
3645 EventInfo ei, *ei_arg = NULL;
3647 if (event == EVENT_KIND_TYPE_LOAD) {
3652 mono_loader_lock ();
3653 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3654 mono_loader_unlock ();
3656 process_event (event, arg, 0, NULL, events, suspend_policy);
3660 runtime_initialized (MonoProfiler *prof)
3662 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3663 if (agent_config.defer)
3664 start_debugger_thread ();
3668 runtime_shutdown (MonoProfiler *prof)
3670 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3672 mono_debugger_agent_cleanup ();
3676 thread_startup (MonoProfiler *prof, uintptr_t tid)
3678 MonoInternalThread *thread = mono_thread_internal_current ();
3679 MonoInternalThread *old_thread;
3680 DebuggerTlsData *tls;
3682 if (tid == debugger_thread_id)
3685 g_assert (thread->tid == tid);
3687 mono_loader_lock ();
3688 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3689 mono_loader_unlock ();
3691 if (thread == old_thread) {
3693 * For some reason, thread_startup () might be called for the same thread
3694 * multiple times (attach ?).
3696 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
3700 * thread_end () might not be called for some threads, and the tid could
3703 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
3704 mono_loader_lock ();
3705 mono_g_hash_table_remove (thread_to_tls, old_thread);
3706 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3707 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3708 mono_loader_unlock ();
3712 tls = mono_native_tls_get_value (debugger_tls_id);
3714 // FIXME: Free this somewhere
3715 tls = g_new0 (DebuggerTlsData, 1);
3716 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3717 tls->thread = thread;
3718 mono_native_tls_set_value (debugger_tls_id, tls);
3720 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3722 mono_loader_lock ();
3723 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3724 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3725 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3726 mono_loader_unlock ();
3728 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3731 * suspend_vm () could have missed this thread, so wait for a resume.
3737 thread_end (MonoProfiler *prof, uintptr_t tid)
3739 MonoInternalThread *thread;
3740 DebuggerTlsData *tls = NULL;
3742 mono_loader_lock ();
3743 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3745 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3746 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3748 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3749 tls->terminated = TRUE;
3750 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3751 MONO_GC_UNREGISTER_ROOT (tls->thread);
3755 mono_loader_unlock ();
3757 /* We might be called for threads started before we registered the start callback */
3759 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3760 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3765 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3767 mono_loader_lock ();
3768 g_hash_table_insert (domains, domain, domain);
3769 mono_loader_unlock ();
3771 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3775 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3777 clear_breakpoints_for_domain (domain);
3779 mono_loader_lock ();
3780 /* Invalidate each thread's frame stack */
3781 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
3782 mono_loader_unlock ();
3784 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
3788 * invalidate_each_thread:
3790 * A GHFunc to invalidate frames.
3791 * value must be a DebuggerTlsData*
3794 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
3796 invalidate_frames (value);
3800 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
3802 /* Sent later in jit_end () */
3803 mono_loader_lock ();
3804 g_ptr_array_add (pending_assembly_loads, assembly);
3805 mono_loader_unlock ();
3809 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
3811 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
3813 clear_event_requests_for_assembly (assembly);
3814 clear_types_for_assembly (assembly);
3818 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3820 #if defined(HOST_WIN32) && !defined(__GNUC__)
3821 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3823 gpointer stackptr = __builtin_frame_address (1);
3825 MonoInternalThread *thread = mono_thread_internal_current ();
3826 DebuggerTlsData *tls;
3828 mono_loader_lock ();
3830 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3831 /* Could be the debugger thread with assembly/type load hooks */
3833 tls->invoke_addr = stackptr;
3835 mono_loader_unlock ();
3839 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
3842 #if defined(HOST_WIN32) && !defined(__GNUC__)
3843 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
3845 gpointer stackptr = __builtin_frame_address (1);
3848 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
3852 * We need to stop single stepping when exiting a runtime invoke, since if it is
3853 * a step out, it may return to native code, and thus never end.
3855 mono_loader_lock ();
3856 ss_invoke_addr = NULL;
3858 for (i = 0; i < event_requests->len; ++i) {
3859 EventRequest *req = g_ptr_array_index (event_requests, i);
3861 if (req->event_kind == EVENT_KIND_STEP) {
3862 ss_destroy (req->info);
3863 g_ptr_array_remove_index_fast (event_requests, i);
3868 mono_loader_unlock ();
3872 send_type_load (MonoClass *klass)
3874 gboolean type_load = FALSE;
3875 MonoDomain *domain = mono_domain_get ();
3876 AgentDomainInfo *info = NULL;
3878 mono_loader_lock ();
3879 mono_domain_lock (domain);
3881 info = get_agent_domain_info (domain);
3883 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
3885 g_hash_table_insert (info->loaded_classes, klass, klass);
3888 mono_domain_unlock (domain);
3889 mono_loader_unlock ();
3891 emit_type_load (klass, klass, NULL);
3895 * Emit load events for all types currently loaded in the domain.
3896 * Takes the loader and domain locks.
3897 * user_data is unused.
3900 send_types_for_domain (MonoDomain *domain, void *user_data)
3902 AgentDomainInfo *info = NULL;
3904 mono_loader_lock ();
3905 mono_domain_lock (domain);
3906 info = get_agent_domain_info (domain);
3908 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
3909 mono_domain_unlock (domain);
3910 mono_loader_unlock ();
3914 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
3917 * We emit type load events when the first method of the type is JITted,
3918 * since the class load profiler callbacks might be called with the
3919 * loader lock held. They could also occur in the debugger thread.
3920 * Same for assembly load events.
3923 MonoAssembly *assembly = NULL;
3925 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
3926 mono_loader_lock ();
3927 if (pending_assembly_loads->len > 0) {
3928 assembly = g_ptr_array_index (pending_assembly_loads, 0);
3929 g_ptr_array_remove_index (pending_assembly_loads, 0);
3931 mono_loader_unlock ();
3934 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
3940 send_type_load (method->klass);
3943 add_pending_breakpoints (method, jinfo);
3947 * BREAKPOINTS/SINGLE STEPPING
3951 * Contains information about an inserted breakpoint.
3954 long il_offset, native_offset;
3959 } BreakpointInstance;
3962 * Contains generic information about a breakpoint.
3966 * The method where the breakpoint is placed. Can be NULL in which case it
3967 * is inserted into every method. This is used to implement method entry/
3968 * exit events. Can be a generic method definition, in which case the
3969 * breakpoint is inserted into every instance.
3975 * A list of BreakpointInstance structures describing where the breakpoint
3976 * was inserted. There could be more than one because of
3977 * generics/appdomains/method entry/exit.
3979 GPtrArray *children;
3982 /* List of breakpoints */
3983 static GPtrArray *breakpoints;
3984 /* Maps breakpoint locations to the number of breakpoints at that location */
3985 static GHashTable *bp_locs;
3988 breakpoints_init (void)
3990 breakpoints = g_ptr_array_new ();
3991 bp_locs = g_hash_table_new (NULL, NULL);
3995 * insert_breakpoint:
3997 * Insert the breakpoint described by BP into the method described by
4001 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4004 BreakpointInstance *inst;
4005 SeqPoint *sp = NULL;
4008 mono_error_init (error);
4010 for (i = 0; i < seq_points->len; ++i) {
4011 sp = &seq_points->seq_points [i];
4013 if (sp->il_offset == bp->il_offset)
4017 if (i == seq_points->len) {
4019 * The set of IL offsets with seq points doesn't completely match the
4020 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4022 for (i = 0; i < seq_points->len; ++i) {
4023 sp = &seq_points->seq_points [i];
4025 if (sp->il_offset != METHOD_ENTRY_IL_OFFSET && sp->il_offset != METHOD_EXIT_IL_OFFSET && sp->il_offset + 1 == bp->il_offset)
4030 if (i == seq_points->len) {
4031 char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d, seq_points=%d\n", mono_method_full_name (ji->method, TRUE), bp->il_offset, seq_points->len);
4033 for (i = 0; i < seq_points->len; ++i)
4034 DEBUG (1, fprintf (log_file, "%d\n", seq_points->seq_points [i].il_offset));
4037 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4046 inst = g_new0 (BreakpointInstance, 1);
4048 inst->native_offset = sp->native_offset;
4049 inst->ip = (guint8*)ji->code_start + sp->native_offset;
4051 inst->domain = domain;
4053 mono_loader_lock ();
4055 g_ptr_array_add (bp->children, inst);
4057 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4058 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4059 mono_loader_unlock ();
4062 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4063 mono_arch_set_breakpoint (ji, inst->ip);
4069 DEBUG(1, fprintf (log_file, "[dbg] Inserted breakpoint at %s:0x%x.\n", mono_method_full_name (ji->method, TRUE), (int)sp->il_offset));
4073 remove_breakpoint (BreakpointInstance *inst)
4075 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4077 MonoJitInfo *ji = inst->ji;
4078 guint8 *ip = inst->ip;
4080 mono_loader_lock ();
4081 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4082 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4083 mono_loader_unlock ();
4085 g_assert (count > 0);
4088 mono_arch_clear_breakpoint (ji, ip);
4095 static inline gboolean
4096 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4102 if (method == bp->method)
4104 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4107 if (bp->method->is_inflated && method->is_inflated) {
4108 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4109 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4111 /* Open generic methods should match closed generic methods of the same class */
4112 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4113 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4114 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4116 /* FIXME: Handle !mvar */
4117 if (t1->type != MONO_TYPE_MVAR)
4128 * add_pending_breakpoints:
4130 * Insert pending breakpoints into the newly JITted method METHOD.
4133 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4136 MonoSeqPointInfo *seq_points;
4142 domain = mono_domain_get ();
4144 mono_loader_lock ();
4146 for (i = 0; i < breakpoints->len; ++i) {
4147 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4148 gboolean found = FALSE;
4150 if (!bp_matches_method (bp, method))
4153 for (j = 0; j < bp->children->len; ++j) {
4154 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4161 mono_domain_lock (domain);
4162 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
4163 if (!seq_points && ji->method->is_inflated)
4164 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (ji->method));
4165 mono_domain_unlock (domain);
4167 /* Could be AOT code */
4169 g_assert (seq_points);
4171 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4175 mono_loader_unlock ();
4179 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4185 mono_error_init (error);
4187 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4189 /* Might be AOTed code */
4190 code = mono_aot_get_method (domain, method);
4192 ji = mono_jit_info_table_find (domain, code);
4197 insert_breakpoint (seq_points, domain, ji, bp, error);
4201 clear_breakpoint (MonoBreakpoint *bp);
4206 * Set a breakpoint at IL_OFFSET in METHOD.
4207 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4208 * METHOD can also be a generic method definition, in which case a breakpoint
4209 * is placed in all instances of the method.
4210 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4213 static MonoBreakpoint*
4214 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4217 GHashTableIter iter, iter2;
4220 MonoSeqPointInfo *seq_points;
4223 mono_error_init (error);
4226 // - suspend/resume the vm to prevent code patching problems
4227 // - multiple breakpoints on the same location
4228 // - dynamic methods
4231 bp = g_new0 (MonoBreakpoint, 1);
4232 bp->method = method;
4233 bp->il_offset = il_offset;
4235 bp->children = g_ptr_array_new ();
4237 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));
4239 mono_loader_lock ();
4241 g_hash_table_iter_init (&iter, domains);
4242 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4243 mono_domain_lock (domain);
4245 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4246 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4247 if (bp_matches_method (bp, m))
4248 set_bp_in_method (domain, m, seq_points, bp, error);
4251 mono_domain_unlock (domain);
4254 mono_loader_unlock ();
4256 mono_loader_lock ();
4257 g_ptr_array_add (breakpoints, bp);
4258 mono_loader_unlock ();
4260 if (error && !mono_error_ok (error)) {
4261 clear_breakpoint (bp);
4269 clear_breakpoint (MonoBreakpoint *bp)
4273 // FIXME: locking, races
4274 for (i = 0; i < bp->children->len; ++i) {
4275 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4277 remove_breakpoint (inst);
4282 mono_loader_lock ();
4283 g_ptr_array_remove (breakpoints, bp);
4284 mono_loader_unlock ();
4286 g_ptr_array_free (bp->children, TRUE);
4291 breakpoints_cleanup (void)
4295 mono_loader_lock ();
4297 while (i < event_requests->len) {
4298 EventRequest *req = g_ptr_array_index (event_requests, i);
4300 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4301 clear_breakpoint (req->info);
4302 g_ptr_array_remove_index_fast (event_requests, i);
4309 for (i = 0; i < breakpoints->len; ++i)
4310 g_free (g_ptr_array_index (breakpoints, i));
4312 g_ptr_array_free (breakpoints, TRUE);
4313 g_hash_table_destroy (bp_locs);
4318 mono_loader_unlock ();
4322 * clear_breakpoints_for_domain:
4324 * Clear breakpoint instances which reference DOMAIN.
4327 clear_breakpoints_for_domain (MonoDomain *domain)
4331 /* This could be called after shutdown */
4335 mono_loader_lock ();
4336 for (i = 0; i < breakpoints->len; ++i) {
4337 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4340 while (j < bp->children->len) {
4341 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4343 if (inst->domain == domain) {
4344 remove_breakpoint (inst);
4348 g_ptr_array_remove_index_fast (bp->children, j);
4354 mono_loader_unlock ();
4358 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4360 return bp->method && bp->method->klass->image->assembly == assembly;
4364 process_breakpoint_inner (DebuggerTlsData *tls)
4368 int i, j, suspend_policy;
4369 guint32 native_offset;
4371 BreakpointInstance *inst;
4372 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4373 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4374 EventKind kind = EVENT_KIND_BREAKPOINT;
4375 MonoContext *ctx = &tls->restore_ctx;
4376 MonoSeqPointInfo *info;
4379 // FIXME: Speed this up
4381 ip = MONO_CONTEXT_GET_IP (ctx);
4382 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4384 g_assert (ji->method);
4386 /* Compute the native offset of the breakpoint from the ip */
4387 native_offset = ip - (guint8*)ji->code_start;
4390 * Skip the instruction causing the breakpoint signal.
4392 mono_arch_skip_breakpoint (ctx, ji);
4394 if (ji->method->wrapper_type || tls->disable_breakpoints)
4397 bp_reqs = g_ptr_array_new ();
4398 ss_reqs = g_ptr_array_new ();
4399 ss_reqs_orig = g_ptr_array_new ();
4401 mono_loader_lock ();
4404 * The ip points to the instruction causing the breakpoint event, which is after
4405 * the offset recorded in the seq point map, so find the prev seq point before ip.
4407 sp = find_prev_seq_point_for_native_offset (mono_domain_get (), ji->method, native_offset, &info);
4410 DEBUG(1, fprintf (log_file, "[%p] Breakpoint hit, method=%s, ip=%p, offset=0x%x, sp il offset=0x%x.\n", (gpointer)GetCurrentThreadId (), ji->method->name, ip, native_offset, sp ? sp->il_offset : -1));
4413 for (i = 0; i < breakpoints->len; ++i) {
4414 bp = g_ptr_array_index (breakpoints, i);
4419 for (j = 0; j < bp->children->len; ++j) {
4420 inst = g_ptr_array_index (bp->children, j);
4421 if (inst->ji == ji && inst->sp == sp) {
4422 if (bp->req->event_kind == EVENT_KIND_STEP) {
4423 g_ptr_array_add (ss_reqs_orig, bp->req);
4425 g_ptr_array_add (bp_reqs, bp->req);
4430 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4431 /* Maybe a method entry/exit event */
4432 if (sp->il_offset == METHOD_ENTRY_IL_OFFSET)
4433 kind = EVENT_KIND_METHOD_ENTRY;
4434 else if (sp->il_offset == METHOD_EXIT_IL_OFFSET)
4435 kind = EVENT_KIND_METHOD_EXIT;
4438 /* Process single step requests */
4439 for (i = 0; i < ss_reqs_orig->len; ++i) {
4440 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4441 SingleStepReq *ss_req = req->info;
4442 gboolean hit = TRUE;
4444 if (ss_req->size == STEP_SIZE_LINE) {
4445 /* Have to check whenever a different source line was reached */
4446 MonoDebugMethodInfo *minfo;
4447 MonoDebugSourceLocation *loc = NULL;
4449 minfo = mono_debug_lookup_method (ji->method);
4452 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4454 if (!loc || (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line)) {
4455 /* Have to continue single stepping */
4456 DEBUG(1, fprintf (log_file, "[%p] Same source line, continuing single stepping.\n", (gpointer)GetCurrentThreadId ()));
4461 ss_req->last_method = ji->method;
4462 ss_req->last_line = loc->row;
4463 mono_debug_free_source_location (loc);
4468 g_ptr_array_add (ss_reqs, req);
4470 /* Start single stepping again from the current sequence point */
4471 ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4474 if (ss_reqs->len > 0)
4475 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4476 if (bp_reqs->len > 0)
4477 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4478 if (kind != EVENT_KIND_BREAKPOINT)
4479 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4481 mono_loader_unlock ();
4483 g_ptr_array_free (bp_reqs, TRUE);
4484 g_ptr_array_free (ss_reqs, TRUE);
4487 * FIXME: The first event will suspend, so the second will only be sent after the
4491 process_event (EVENT_KIND_STEP, ji->method, 0, ctx, ss_events, suspend_policy);
4493 process_event (kind, ji->method, 0, ctx, bp_events, suspend_policy);
4494 if (enter_leave_events)
4495 process_event (kind, ji->method, 0, ctx, enter_leave_events, suspend_policy);
4498 /* Process a breakpoint/single step event after resuming from a signal handler */
4500 process_signal_event (void (*func) (DebuggerTlsData*))
4502 DebuggerTlsData *tls;
4503 MonoContext orig_restore_ctx, ctx;
4504 static void (*restore_context) (void *);
4506 if (!restore_context)
4507 restore_context = mono_get_restore_context ();
4509 tls = mono_native_tls_get_value (debugger_tls_id);
4510 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4511 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4512 memcpy (&tls->restore_ctx, &tls->handler_ctx, sizeof (MonoContext));
4516 /* This is called when resuming from a signal handler, so it shouldn't return */
4517 memcpy (&ctx, &tls->restore_ctx, sizeof (MonoContext));
4518 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4519 restore_context (&ctx);
4520 g_assert_not_reached ();
4524 process_breakpoint (void)
4526 process_signal_event (process_breakpoint_inner);
4530 resume_from_signal_handler (void *sigctx, void *func)
4532 DebuggerTlsData *tls;
4535 /* Save the original context in TLS */
4536 // FIXME: This might not work on an altstack ?
4537 tls = mono_native_tls_get_value (debugger_tls_id);
4539 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer)GetCurrentThreadId ());
4542 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4543 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4544 // clob:c could be added to op_seq_point.
4546 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4547 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4548 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4549 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4551 MONO_CONTEXT_SET_IP (&ctx, func);
4553 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4555 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4556 mono_ppc_set_func_into_sigctx (sigctx, func);
4561 mono_debugger_agent_breakpoint_hit (void *sigctx)
4564 * We are called from a signal handler, and running code there causes all kinds of
4565 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4566 * So set up the signal context to return to the real breakpoint handler function.
4568 resume_from_signal_handler (sigctx, process_breakpoint);
4572 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4574 if (frame->managed) {
4575 *(MonoContext*)data = *ctx;
4584 * Called by System.Diagnostics.Debugger:Break ().
4587 mono_debugger_agent_user_break (void)
4589 if (agent_config.enabled) {
4594 /* Obtain a context */
4595 MONO_CONTEXT_SET_IP (&ctx, NULL);
4596 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4597 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4599 mono_loader_lock ();
4600 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4601 mono_loader_unlock ();
4603 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4610 ss_depth_to_string (StepDepth depth)
4613 case STEP_DEPTH_OVER:
4615 case STEP_DEPTH_OUT:
4617 case STEP_DEPTH_INTO:
4620 g_assert_not_reached ();
4626 process_single_step_inner (DebuggerTlsData *tls)
4631 int il_offset, suspend_policy;
4634 MonoContext *ctx = &tls->restore_ctx;
4636 MonoSeqPointInfo *info;
4638 ip = MONO_CONTEXT_GET_IP (ctx);
4640 /* Skip the instruction causing the single step */
4641 mono_arch_skip_single_step (ctx);
4643 if (suspend_count > 0) {
4644 process_suspend (tls, ctx);
4649 // FIXME: A suspend race
4652 if (mono_thread_internal_current () != ss_req->thread)
4655 if (log_level > 0) {
4656 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4658 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 (ji->method, TRUE), MONO_CONTEXT_GET_IP (ctx), MONO_CONTEXT_GET_SP (ctx), ss_req->last_sp));
4661 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4663 g_assert (ji->method);
4665 if (ji->method->wrapper_type && ji->method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4670 * Stopping in memset makes half-initialized vtypes visible.
4671 * Stopping in memcpy makes half-copied vtypes visible.
4673 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
4677 * The ip points to the instruction causing the single step event, which is before
4678 * the offset recorded in the seq point map, so find the next seq point after ip.
4680 sp = find_next_seq_point_for_native_offset (domain, ji->method, (guint8*)ip - (guint8*)ji->code_start, &info);
4683 il_offset = sp->il_offset;
4685 // FIXME: No tests fail if this is disabled
4687 if (ss_req->size == STEP_SIZE_LINE) {
4691 /* Step until a different source line is reached */
4692 MonoDebugMethodInfo *minfo;
4694 minfo = mono_debug_lookup_method (ji->method);
4697 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, il_offset);
4699 if (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line) {
4700 mono_debug_free_source_location (loc);
4705 * Step until we reach a location with line number info,
4706 * otherwise the client can't show a location.
4707 * This can happen for example with statics initialized inline
4708 * outside of a cctor.
4713 ss_req->last_method = ji->method;
4714 ss_req->last_line = loc->row;
4715 mono_debug_free_source_location (loc);
4721 /* Start single stepping again from the current sequence point */
4722 ss_start (ss_req, ji->method, sp, info, ctx, tls, FALSE);
4724 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
4725 (ji->method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
4726 !strcmp (ji->method->name, ".cctor"))
4729 // FIXME: Has to lock earlier
4731 reqs = g_ptr_array_new ();
4733 mono_loader_lock ();
4735 g_ptr_array_add (reqs, ss_req->req);
4737 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
4739 g_ptr_array_free (reqs, TRUE);
4741 mono_loader_unlock ();
4743 process_event (EVENT_KIND_STEP, ji->method, il_offset, ctx, events, suspend_policy);
4747 process_single_step (void)
4749 process_signal_event (process_single_step_inner);
4753 * mono_debugger_agent_single_step_event:
4755 * Called from a signal handler to handle a single step event.
4758 mono_debugger_agent_single_step_event (void *sigctx)
4760 /* Resume to process_single_step through the signal context */
4762 // FIXME: Since step out/over is implemented using step in, the step in case should
4763 // be as fast as possible. Move the relevant code from process_single_step_inner ()
4766 if (GetCurrentThreadId () == debugger_thread_id) {
4768 * This could happen despite our best effors when the runtime calls
4769 * assembly/type resolve hooks.
4770 * FIXME: Breakpoints too.
4774 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4775 mono_arch_skip_single_step (&ctx);
4776 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4780 resume_from_signal_handler (sigctx, process_single_step);
4784 debugger_agent_single_step_from_context (MonoContext *ctx)
4786 DebuggerTlsData *tls;
4787 MonoContext orig_restore_ctx;
4789 tls = mono_native_tls_get_value (debugger_tls_id);
4792 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4793 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4794 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4796 process_single_step_inner (tls);
4798 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4799 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4803 debugger_agent_breakpoint_from_context (MonoContext *ctx)
4805 DebuggerTlsData *tls;
4806 MonoContext orig_restore_ctx;
4808 tls = mono_native_tls_get_value (debugger_tls_id);
4810 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4811 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
4813 process_breakpoint_inner (tls);
4815 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
4816 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4820 * start_single_stepping:
4822 * Turn on single stepping. Can be called multiple times, for example,
4823 * by a single step event request + a suspend.
4826 start_single_stepping (void)
4828 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4829 int val = InterlockedIncrement (&ss_count);
4832 mono_arch_start_single_stepping ();
4834 if (ss_req != NULL && ss_invoke_addr == NULL) {
4835 DebuggerTlsData *tls;
4837 mono_loader_lock ();
4839 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
4840 ss_invoke_addr = tls->invoke_addr;
4842 mono_loader_unlock ();
4845 g_assert_not_reached ();
4850 stop_single_stepping (void)
4852 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4853 int val = InterlockedDecrement (&ss_count);
4856 mono_arch_stop_single_stepping ();
4858 g_assert_not_reached ();
4865 * Stop the single stepping operation given by SS_REQ.
4868 ss_stop (SingleStepReq *ss_req)
4873 for (l = ss_req->bps; l; l = l->next) {
4874 clear_breakpoint (l->data);
4876 g_slist_free (ss_req->bps);
4880 if (ss_req->global) {
4881 stop_single_stepping ();
4882 ss_req->global = FALSE;
4889 * Start the single stepping operation given by SS_REQ from the sequence point SP.
4890 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
4891 * belong to the same thread as CTX.
4894 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
4896 int i, j, frame_index;
4899 gboolean enable_global = FALSE;
4901 /* Stop the previous operation */
4905 * Implement single stepping using breakpoints if possible.
4907 if (step_to_catch) {
4908 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
4909 ss_req->bps = g_slist_append (ss_req->bps, bp);
4913 if ((!sp || sp->next_len == 0 || ss_req->depth == STEP_DEPTH_OUT || ss_req->depth == STEP_DEPTH_OVER) && ctx) {
4914 /* Need parent frames */
4915 if (!tls->context.valid)
4916 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4917 compute_frame_info (tls->thread, tls);
4921 * Find the first sequence point in the current or in a previous frame which
4922 * is not the last in its method.
4924 if (ss_req->depth == STEP_DEPTH_OUT) {
4925 /* Ignore seq points in current method */
4926 while (frame_index < tls->frame_count) {
4927 StackFrame *frame = tls->frames [frame_index];
4929 method = frame->method;
4930 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4932 if (sp && sp->next_len != 0)
4935 // There could be method calls before the next seq point in the caller when using nested calls
4936 //enable_global = TRUE;
4938 while (sp && sp->next_len == 0) {
4940 if (frame_index < tls->frame_count) {
4941 StackFrame *frame = tls->frames [frame_index];
4943 method = frame->method;
4944 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
4950 if (sp && sp->next_len > 0) {
4951 for (i = 0; i < sp->next_len; ++i) {
4952 next_sp = &info->seq_points [sp->next [i]];
4954 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
4955 ss_req->bps = g_slist_append (ss_req->bps, bp);
4959 if (ss_req->depth == STEP_DEPTH_OVER) {
4960 /* Need to stop in catch clauses as well */
4961 for (i = 0; i < tls->frame_count; ++i) {
4962 StackFrame *frame = tls->frames [i];
4965 MonoJitInfo *jinfo = frame->ji;
4966 for (j = 0; j < jinfo->num_clauses; ++j) {
4967 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
4969 sp = find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL);
4971 bp = set_breakpoint (frame->method, sp->il_offset, ss_req->req, NULL);
4972 ss_req->bps = g_slist_append (ss_req->bps, bp);
4980 if (ss_req->depth == STEP_DEPTH_INTO) {
4981 /* Enable global stepping so we stop at method entry too */
4982 enable_global = TRUE;
4986 * The ctx/frame info computed above will become invalid when we continue.
4988 tls->context.valid = FALSE;
4989 tls->async_state.valid = FALSE;
4990 invalidate_frames (tls);
4993 if (enable_global) {
4994 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
4995 ss_req->global = TRUE;
4996 start_single_stepping ();
4997 } else if (!ss_req->bps) {
4998 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
4999 ss_req->global = TRUE;
5000 start_single_stepping ();
5002 ss_req->global = FALSE;
5007 * Start single stepping of thread THREAD
5010 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
5012 DebuggerTlsData *tls;
5013 MonoSeqPointInfo *info = NULL;
5014 SeqPoint *sp = NULL;
5015 MonoMethod *method = NULL;
5016 MonoDebugMethodInfo *minfo;
5017 gboolean step_to_catch = FALSE;
5019 if (suspend_count == 0)
5020 return ERR_NOT_SUSPENDED;
5022 wait_for_suspend ();
5024 // FIXME: Multiple requests
5026 DEBUG (0, fprintf (log_file, "Received a single step request while the previous one was still active.\n"));
5027 return ERR_NOT_IMPLEMENTED;
5030 DEBUG (1, fprintf (log_file, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
5032 ss_req = g_new0 (SingleStepReq, 1);
5034 ss_req->thread = thread;
5035 ss_req->size = size;
5036 ss_req->depth = depth;
5039 mono_loader_lock ();
5040 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5041 mono_loader_unlock ();
5043 g_assert (tls->context.valid);
5044 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5046 if (tls->catch_state.valid) {
5048 StackFrameInfo frame;
5049 MonoContext new_ctx;
5050 MonoLMF *lmf = NULL;
5053 * We are stopped at a throw site. Stepping should go to the catch site.
5056 /* Find the the jit info for the catch context */
5057 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);
5059 g_assert (frame.type == FRAME_TYPE_MANAGED);
5062 * Find the seq point corresponding to the landing site ip, which is the first seq
5065 sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
5068 method = frame.method;
5070 step_to_catch = TRUE;
5071 /* This make sure the seq point is not skipped by process_single_step () */
5072 ss_req->last_sp = NULL;
5075 if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
5078 /* Compute the initial line info */
5079 compute_frame_info (thread, tls);
5081 if (tls->frame_count) {
5082 frame = tls->frames [0];
5084 ss_req->last_method = frame->method;
5085 ss_req->last_line = -1;
5087 minfo = mono_debug_lookup_method (frame->method);
5088 if (minfo && frame->il_offset != -1) {
5089 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
5092 ss_req->last_line = loc->row;
5099 if (!step_to_catch) {
5102 compute_frame_info (thread, tls);
5104 if (tls->frame_count) {
5105 frame = tls->frames [0];
5107 if (!method && frame->il_offset != -1) {
5108 /* FIXME: Sort the table and use a binary search */
5109 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5111 method = frame->method;
5116 ss_start (ss_req, method, sp, info, &tls->context.ctx, tls, step_to_catch);
5122 ss_destroy (SingleStepReq *req)
5125 g_assert (ss_req == req);
5134 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5137 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5143 if (!agent_config.enabled)
5146 mono_loader_lock ();
5147 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5148 mono_loader_unlock ();
5151 ei.category = category ? mono_string_to_utf8 (category) : NULL;
5152 ei.message = message ? mono_string_to_utf8 (message) : NULL;
5154 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5156 g_free (ei.category);
5157 g_free (ei.message);
5161 mono_debugger_agent_debug_log_is_enabled (void)
5163 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5164 return agent_config.enabled;
5167 #ifdef PLATFORM_ANDROID
5169 mono_debugger_agent_unhandled_exception (MonoException *exc)
5178 memset (&ei, 0, sizeof (EventInfo));
5179 ei.exc = (MonoObject*)exc;
5181 mono_loader_lock ();
5182 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5183 mono_loader_unlock ();
5185 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5190 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5191 MonoContext *catch_ctx)
5193 int i, j, suspend_policy;
5195 MonoJitInfo *ji, *catch_ji;
5197 DebuggerTlsData *tls = NULL;
5199 if (thread_to_tls != NULL) {
5200 MonoInternalThread *thread = mono_thread_internal_current ();
5202 mono_loader_lock ();
5203 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5204 mono_loader_unlock ();
5206 if (tls && tls->abort_requested)
5208 if (tls && tls->disable_breakpoints)
5212 memset (&ei, 0, sizeof (EventInfo));
5214 /* Just-In-Time debugging */
5216 if (agent_config.onuncaught && !inited) {
5217 finish_agent_init (FALSE);
5220 * Send an unsolicited EXCEPTION event with a dummy request id.
5222 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5223 ei.exc = (MonoObject*)exc;
5224 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5227 } else if (agent_config.onthrow && !inited) {
5229 gboolean found = FALSE;
5231 for (l = agent_config.onthrow; l; l = l->next) {
5232 char *ex_type = l->data;
5233 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5235 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5242 finish_agent_init (FALSE);
5245 * Send an unsolicited EXCEPTION event with a dummy request id.
5247 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5248 ei.exc = (MonoObject*)exc;
5249 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5257 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5259 catch_ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5263 ei.exc = (MonoObject*)exc;
5264 ei.caught = catch_ctx != NULL;
5266 mono_loader_lock ();
5268 /* Treat exceptions which are caught in non-user code as unhandled */
5269 for (i = 0; i < event_requests->len; ++i) {
5270 EventRequest *req = g_ptr_array_index (event_requests, i);
5271 if (req->event_kind != EVENT_KIND_EXCEPTION)
5274 for (j = 0; j < req->nmodifiers; ++j) {
5275 Modifier *mod = &req->modifiers [j];
5277 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5279 gboolean found = FALSE;
5280 MonoAssembly **assemblies = mod->data.assemblies;
5283 for (k = 0; assemblies [k]; ++k)
5284 if (assemblies [k] == catch_ji->method->klass->image->assembly)
5293 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5294 mono_loader_unlock ();
5296 if (tls && ei.caught && catch_ctx) {
5297 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5298 tls->catch_state.ctx = *catch_ctx;
5299 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5300 tls->catch_state.valid = TRUE;
5303 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5306 tls->catch_state.valid = FALSE;
5310 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5312 DebuggerTlsData *tls;
5317 tls = mono_native_tls_get_value (debugger_tls_id);
5322 * We're about to invoke an exception filter during the first pass of exception handling.
5324 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5325 * 'orig_ctx' is the context where the exception has been thrown.
5328 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5330 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5331 * the call site (line 37) and then continue to Main(), but it would never
5332 * include the throw site (line 32).
5334 * Since exception filters are invoked during the first pass of exception handling,
5335 * the stack frames of the throw site are still intact, so we should include them
5338 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5340 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5341 * but report the location of the 'throw' to the user.
5345 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5349 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5351 DebuggerTlsData *tls;
5356 tls = mono_native_tls_get_value (debugger_tls_id);
5360 tls->filter_state.valid = FALSE;
5364 * buffer_add_value_full:
5366 * Add the encoding of the value at ADDR described by T to the buffer.
5367 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5371 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5377 if (!(*(void**)addr))
5378 printf ("%s\n", mono_type_full_name (t));
5379 g_assert (*(void**)addr);
5380 addr = *(void**)addr;
5385 case MONO_TYPE_BOOLEAN:
5388 case MONO_TYPE_CHAR:
5408 case MONO_TYPE_VOID:
5409 buffer_add_byte (buf, t->type);
5411 case MONO_TYPE_BOOLEAN:
5414 buffer_add_byte (buf, t->type);
5415 buffer_add_int (buf, *(gint8*)addr);
5417 case MONO_TYPE_CHAR:
5420 buffer_add_byte (buf, t->type);
5421 buffer_add_int (buf, *(gint16*)addr);
5426 buffer_add_byte (buf, t->type);
5427 buffer_add_int (buf, *(gint32*)addr);
5432 buffer_add_byte (buf, t->type);
5433 buffer_add_long (buf, *(gint64*)addr);
5437 /* Treat it as a vtype */
5439 case MONO_TYPE_PTR: {
5440 gssize val = *(gssize*)addr;
5442 buffer_add_byte (buf, t->type);
5443 buffer_add_long (buf, val);
5447 case MONO_TYPE_STRING:
5448 case MONO_TYPE_SZARRAY:
5449 case MONO_TYPE_OBJECT:
5450 case MONO_TYPE_CLASS:
5451 case MONO_TYPE_ARRAY:
5452 obj = *(MonoObject**)addr;
5455 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5457 if (obj->vtable->klass->valuetype) {
5458 t = &obj->vtable->klass->byval_arg;
5459 addr = mono_object_unbox (obj);
5461 } else if (obj->vtable->klass->rank) {
5462 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5463 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5464 buffer_add_byte (buf, MONO_TYPE_CLASS);
5466 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5468 buffer_add_objid (buf, obj);
5472 case MONO_TYPE_VALUETYPE: {
5476 MonoClass *klass = mono_class_from_mono_type (t);
5478 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5479 buffer_add_byte (buf, klass->enumtype);
5480 buffer_add_typeid (buf, domain, klass);
5484 while ((f = mono_class_get_fields (klass, &iter))) {
5485 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5487 if (mono_field_is_deleted (f))
5491 buffer_add_int (buf, nfields);
5494 while ((f = mono_class_get_fields (klass, &iter))) {
5495 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5497 if (mono_field_is_deleted (f))
5499 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE);
5503 case MONO_TYPE_GENERICINST:
5504 if (mono_type_generic_inst_is_valuetype (t)) {
5516 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5518 buffer_add_value_full (buf, t, addr, domain, FALSE);
5522 obj_is_of_type (MonoObject *obj, MonoType *t)
5524 MonoClass *klass = obj->vtable->klass;
5525 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5526 if (mono_class_is_transparent_proxy (klass)) {
5527 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5528 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5538 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5541 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5545 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5546 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5547 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5548 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5549 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
5550 char *name = mono_type_full_name (t);
5551 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5553 return ERR_INVALID_ARGUMENT;
5557 case MONO_TYPE_BOOLEAN:
5558 *(guint8*)addr = decode_int (buf, &buf, limit);
5560 case MONO_TYPE_CHAR:
5561 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5564 *(gint8*)addr = decode_int (buf, &buf, limit);
5567 *(guint8*)addr = decode_int (buf, &buf, limit);
5570 *(gint16*)addr = decode_int (buf, &buf, limit);
5573 *(guint16*)addr = decode_int (buf, &buf, limit);
5576 *(gint32*)addr = decode_int (buf, &buf, limit);
5579 *(guint32*)addr = decode_int (buf, &buf, limit);
5582 *(gint64*)addr = decode_long (buf, &buf, limit);
5585 *(guint64*)addr = decode_long (buf, &buf, limit);
5588 *(guint32*)addr = decode_int (buf, &buf, limit);
5591 *(guint64*)addr = decode_long (buf, &buf, limit);
5594 /* We send these as I8, so we get them back as such */
5595 g_assert (type == MONO_TYPE_I8);
5596 *(gssize*)addr = decode_long (buf, &buf, limit);
5598 case MONO_TYPE_GENERICINST:
5599 if (MONO_TYPE_ISSTRUCT (t)) {
5600 /* The client sends these as a valuetype */
5608 /* We send these as vtypes, so we get them back as such */
5609 g_assert (type == MONO_TYPE_VALUETYPE);
5612 case MONO_TYPE_VALUETYPE: {
5613 gboolean is_enum = decode_byte (buf, &buf, limit);
5617 gpointer iter = NULL;
5620 /* Enums are sent as a normal vtype */
5622 return ERR_NOT_IMPLEMENTED;
5623 klass = decode_typeid (buf, &buf, limit, &d, &err);
5627 if (klass != mono_class_from_mono_type (t))
5628 return ERR_INVALID_ARGUMENT;
5630 nfields = decode_int (buf, &buf, limit);
5631 while ((f = mono_class_get_fields (klass, &iter))) {
5632 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5634 if (mono_field_is_deleted (f))
5636 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5641 g_assert (nfields == 0);
5646 if (MONO_TYPE_IS_REFERENCE (t)) {
5647 if (type == MONO_TYPE_OBJECT) {
5648 int objid = decode_objid (buf, &buf, limit);
5652 err = get_object (objid, (MonoObject**)&obj);
5657 if (!obj_is_of_type (obj, t)) {
5658 DEBUG (1, fprintf (log_file, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name));
5659 return ERR_INVALID_ARGUMENT;
5662 if (obj && obj->vtable->domain != domain)
5663 return ERR_INVALID_ARGUMENT;
5665 mono_gc_wbarrier_generic_store (addr, obj);
5666 } else if (type == VALUE_TYPE_ID_NULL) {
5667 *(MonoObject**)addr = NULL;
5669 return ERR_INVALID_ARGUMENT;
5683 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5686 int type = decode_byte (buf, &buf, limit);
5688 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
5689 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
5690 guint8 *nullable_buf;
5693 * First try decoding it as a Nullable`1
5695 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5700 * Then try decoding as a primitive value or null.
5702 if (targ->type == type) {
5703 nullable_buf = g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
5704 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
5706 g_free (nullable_buf);
5709 mono_nullable_init (addr, mono_value_box (domain, mono_class_from_mono_type (targ), nullable_buf), mono_class_from_mono_type (t));
5710 g_free (nullable_buf);
5713 } else if (type == VALUE_TYPE_ID_NULL) {
5714 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
5720 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
5724 add_var (Buffer *buf, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
5731 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5732 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5735 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
5736 reg_val = mono_arch_context_get_int_reg (ctx, reg);
5738 buffer_add_value_full (buf, t, ®_val, domain, as_vtype);
5740 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5741 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5742 addr += (gint32)var->offset;
5744 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5746 buffer_add_value_full (buf, t, addr, domain, as_vtype);
5748 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5752 g_assert_not_reached ();
5757 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
5763 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5764 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5766 if (MONO_TYPE_IS_REFERENCE (t))
5767 size = sizeof (gpointer);
5769 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
5772 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
5773 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
5775 gboolean is_signed = FALSE;
5777 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
5782 v = is_signed ? *(gint8*)val : *(guint8*)val;
5785 v = is_signed ? *(gint16*)val : *(guint16*)val;
5788 v = is_signed ? *(gint32*)val : *(guint32*)val;
5791 v = is_signed ? *(gint64*)val : *(guint64*)val;
5794 g_assert_not_reached ();
5800 /* Set value on the stack or in the return ctx */
5801 if (reg_locations [reg]) {
5802 /* Saved on the stack */
5803 DEBUG (1, fprintf (log_file, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v));
5804 *(reg_locations [reg]) = v;
5807 DEBUG (1, fprintf (log_file, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v));
5808 mono_arch_context_set_int_reg (restore_ctx, reg, v);
5811 // FIXME: Move these to mono-context.h/c.
5812 mono_arch_context_set_int_reg (ctx, reg, v);
5814 // FIXME: Can't set registers, so we disable linears
5819 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5820 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
5821 addr += (gint32)var->offset;
5823 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
5826 addr = *(guint8**)addr;
5832 // FIXME: Write barriers
5833 mono_gc_memmove (addr, val, size);
5835 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5839 g_assert_not_reached ();
5844 clear_event_request (int req_id, int etype)
5848 mono_loader_lock ();
5849 for (i = 0; i < event_requests->len; ++i) {
5850 EventRequest *req = g_ptr_array_index (event_requests, i);
5852 if (req->id == req_id && req->event_kind == etype) {
5853 if (req->event_kind == EVENT_KIND_BREAKPOINT)
5854 clear_breakpoint (req->info);
5855 if (req->event_kind == EVENT_KIND_STEP)
5856 ss_destroy (req->info);
5857 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
5858 clear_breakpoint (req->info);
5859 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
5860 clear_breakpoint (req->info);
5861 g_ptr_array_remove_index_fast (event_requests, i);
5866 mono_loader_unlock ();
5870 event_req_matches_assembly (EventRequest *req, MonoAssembly *assembly)
5872 if (req->event_kind == EVENT_KIND_BREAKPOINT)
5873 return breakpoint_matches_assembly (req->info, assembly);
5877 for (i = 0; i < req->nmodifiers; ++i) {
5878 Modifier *m = &req->modifiers [i];
5880 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
5882 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
5883 for (j = 0; m->data.assemblies [j]; ++j)
5884 if (m->data.assemblies [j] == assembly)
5894 * clear_event_requests_for_assembly:
5896 * Clear all events requests which reference ASSEMBLY.
5899 clear_event_requests_for_assembly (MonoAssembly *assembly)
5904 mono_loader_lock ();
5908 for (i = 0; i < event_requests->len; ++i) {
5909 EventRequest *req = g_ptr_array_index (event_requests, i);
5911 if (event_req_matches_assembly (req, assembly)) {
5912 clear_event_request (req->id, req->event_kind);
5918 mono_loader_unlock ();
5922 * type_comes_from_assembly:
5924 * GHRFunc that returns TRUE if klass comes from assembly
5927 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
5929 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
5933 * clear_types_for_assembly:
5935 * Clears types from loaded_classes for a given assembly
5938 clear_types_for_assembly (MonoAssembly *assembly)
5940 MonoDomain *domain = mono_domain_get ();
5941 AgentDomainInfo *info = NULL;
5943 mono_loader_lock ();
5944 info = get_agent_domain_info (domain);
5945 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
5946 mono_loader_unlock ();
5950 add_thread (gpointer key, gpointer value, gpointer user_data)
5952 MonoInternalThread *thread = value;
5953 Buffer *buf = user_data;
5955 buffer_add_objid (buf, (MonoObject*)thread);
5959 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
5961 guint8 *end = invoke->endp;
5964 MonoMethodSignature *sig;
5967 MonoObject *this, *res, *exc;
5970 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5973 MonoStopwatch watch;
5975 if (invoke->method) {
5977 * Invoke this method directly, currently only Environment.Exit () is supported.
5980 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>"));
5981 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
5982 g_assert_not_reached ();
5985 m = decode_methodid (p, &p, end, &domain, &err);
5988 sig = mono_method_signature (m);
5990 if (m->klass->valuetype)
5991 this_buf = g_alloca (mono_class_instance_size (m->klass));
5993 this_buf = g_alloca (sizeof (MonoObject*));
5994 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
5995 /* Should be null */
5996 int type = decode_byte (p, &p, end);
5997 if (type != VALUE_TYPE_ID_NULL)
5998 return ERR_INVALID_ARGUMENT;
5999 memset (this_buf, 0, mono_class_instance_size (m->klass));
6001 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6006 if (!m->klass->valuetype)
6007 this = *(MonoObject**)this_buf;
6011 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>"));
6013 if (this && this->vtable->domain != domain)
6016 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
6017 if (!strcmp (m->name, ".ctor")) {
6018 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
6019 return ERR_INVALID_ARGUMENT;
6021 this = mono_object_new (domain, m->klass);
6023 return ERR_INVALID_ARGUMENT;
6027 if (this && !obj_is_of_type (this, &m->klass->byval_arg))
6028 return ERR_INVALID_ARGUMENT;
6030 nargs = decode_int (p, &p, end);
6031 if (nargs != sig->param_count)
6032 return ERR_INVALID_ARGUMENT;
6033 /* Use alloca to get gc tracking */
6034 arg_buf = g_alloca (nargs * sizeof (gpointer));
6035 memset (arg_buf, 0, nargs * sizeof (gpointer));
6036 args = g_alloca (nargs * sizeof (gpointer));
6037 for (i = 0; i < nargs; ++i) {
6038 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6039 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6043 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6046 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6047 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6050 args [i] = arg_buf [i];
6057 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6058 tls->disable_breakpoints = TRUE;
6060 tls->disable_breakpoints = FALSE;
6063 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6065 /* FIXME: Move this to arch specific code */
6066 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6067 if (invoke->has_ctx) {
6070 lmf_addr = mono_get_lmf_addr ();
6073 memset (&ext, 0, sizeof (ext));
6075 ext.lmf.previous_lmf = *(lmf_addr);
6076 /* Mark that this is a MonoLMFExt */
6077 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6078 ext.lmf.rsp = (gssize)&ext;
6079 #elif defined(TARGET_X86)
6080 ext.lmf.previous_lmf = (gsize)*(lmf_addr);
6081 /* Mark that this is a MonoLMFExt */
6082 ext.lmf.previous_lmf = (gsize)(gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6083 ext.lmf.ebp = (gssize)&ext;
6084 #elif defined(TARGET_ARM)
6085 ext.lmf.previous_lmf = *(lmf_addr);
6086 /* Mark that this is a MonoLMFExt */
6087 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6088 ext.lmf.sp = (gssize)&ext;
6089 #elif defined(TARGET_POWERPC)
6090 ext.lmf.previous_lmf = *(lmf_addr);
6091 /* Mark that this is a MonoLMFExt */
6092 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6093 ext.lmf.ebp = (gssize)&ext;
6094 #elif defined(TARGET_S390X)
6095 ext.lmf.previous_lmf = *(lmf_addr);
6096 /* Mark that this is a MonoLMFExt */
6097 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6098 ext.lmf.ebp = (gssize)&ext;
6099 #elif defined(TARGET_MIPS)
6100 ext.lmf.previous_lmf = *(lmf_addr);
6101 /* Mark that this is a MonoLMFExt */
6102 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
6103 ext.lmf.iregs [mips_sp] = (gssize)&ext;
6105 g_assert_not_reached ();
6108 ext.debugger_invoke = TRUE;
6109 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6111 mono_set_lmf ((MonoLMF*)&ext);
6115 mono_stopwatch_start (&watch);
6116 if (m->klass->valuetype)
6117 res = mono_runtime_invoke (m, this_buf, args, &exc);
6119 res = mono_runtime_invoke (m, this, args, &exc);
6120 mono_stopwatch_stop (&watch);
6121 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)));
6123 buffer_add_byte (buf, 0);
6124 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6126 buffer_add_byte (buf, 1);
6127 if (sig->ret->type == MONO_TYPE_VOID) {
6128 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
6129 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
6132 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6133 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6134 buffer_add_value (buf, sig->ret, &res, domain);
6135 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6136 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6137 MonoClass *k = mono_class_from_mono_type (sig->ret);
6138 guint8 *nullable_buf = g_alloca (mono_class_value_size (k, NULL));
6140 g_assert (nullable_buf);
6141 mono_nullable_init (nullable_buf, res, k);
6142 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6145 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6152 tls->disable_breakpoints = FALSE;
6154 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6155 if (invoke->has_ctx)
6156 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
6160 // FIXME: byref arguments
6168 * Invoke the method given by tls->pending_invoke in the current thread.
6171 invoke_method (void)
6173 DebuggerTlsData *tls;
6178 static void (*restore_context) (void *);
6179 MonoContext restore_ctx;
6182 if (!restore_context)
6183 restore_context = mono_get_restore_context ();
6185 tls = mono_native_tls_get_value (debugger_tls_id);
6189 * Store the `InvokeData *' in `tls->invoke' until we're done with
6190 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6193 mono_loader_lock ();
6195 invoke = tls->pending_invoke;
6197 tls->pending_invoke = NULL;
6199 invoke->last_invoke = tls->invoke;
6200 tls->invoke = invoke;
6202 mono_loader_unlock ();
6204 tls->frames_up_to_date = FALSE;
6210 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6211 buffer_init (&buf, 128);
6214 /* Fail the other invokes as well */
6216 err = do_invoke_method (tls, &buf, invoke, p, &p);
6219 /* Start suspending before sending the reply */
6220 if (mindex == invoke->nmethods - 1) {
6221 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6222 for (i = 0; i < invoke->suspend_count; ++i)
6227 send_reply_packet (id, err, &buf);
6232 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6234 if (invoke->has_ctx)
6235 save_thread_context (&restore_ctx);
6237 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6238 g_assert (tls->resume_count);
6239 tls->resume_count -= invoke->suspend_count;
6242 DEBUG (1, fprintf (log_file, "[%p] Invoke finished, resume_count = %d.\n", (gpointer)GetCurrentThreadId (), tls->resume_count));
6245 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6247 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
6248 * after the mono_runtime_invoke() already returned, but it doesn't matter
6249 * because we reset the abort here.
6252 mono_loader_lock ();
6254 if (tls->abort_requested)
6255 mono_thread_internal_reset_abort (tls->thread);
6257 tls->invoke = tls->invoke->last_invoke;
6258 tls->abort_requested = FALSE;
6260 mono_loader_unlock ();
6269 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6271 MonoThread *thread = value;
6272 DebuggerTlsData *tls;
6275 mono_loader_lock ();
6276 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6278 res = tls->really_suspended;
6279 mono_loader_unlock ();
6285 get_source_files_for_type (MonoClass *klass)
6287 gpointer iter = NULL;
6289 MonoDebugSourceInfo *sinfo;
6293 files = g_ptr_array_new ();
6295 while ((method = mono_class_get_methods (klass, &iter))) {
6296 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6297 GPtrArray *source_file_list;
6300 mono_debug_symfile_get_line_numbers_full (minfo, NULL, &source_file_list, NULL, NULL, NULL, NULL, NULL);
6301 for (j = 0; j < source_file_list->len; ++j) {
6302 sinfo = g_ptr_array_index (source_file_list, j);
6303 for (i = 0; i < files->len; ++i)
6304 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6306 if (i == files->len)
6307 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6309 g_ptr_array_free (source_file_list, TRUE);
6317 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6320 case CMD_VM_VERSION: {
6321 char *build_info, *version;
6323 build_info = mono_get_runtime_build_info ();
6324 version = g_strdup_printf ("mono %s", build_info);
6326 buffer_add_string (buf, version); /* vm version */
6327 buffer_add_int (buf, MAJOR_VERSION);
6328 buffer_add_int (buf, MINOR_VERSION);
6329 g_free (build_info);
6333 case CMD_VM_SET_PROTOCOL_VERSION: {
6334 major_version = decode_int (p, &p, end);
6335 minor_version = decode_int (p, &p, end);
6336 protocol_version_set = TRUE;
6337 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
6340 case CMD_VM_ALL_THREADS: {
6342 mono_loader_lock ();
6343 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6344 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6345 mono_loader_unlock ();
6348 case CMD_VM_SUSPEND:
6350 wait_for_suspend ();
6353 if (suspend_count == 0)
6354 return ERR_NOT_SUSPENDED;
6356 clear_suspended_objs ();
6358 case CMD_VM_DISPOSE:
6359 /* Clear all event requests */
6360 mono_loader_lock ();
6361 while (event_requests->len > 0) {
6362 EventRequest *req = g_ptr_array_index (event_requests, 0);
6364 clear_event_request (req->id, req->event_kind);
6366 mono_loader_unlock ();
6368 while (suspend_count > 0)
6370 disconnected = TRUE;
6371 vm_start_event_sent = FALSE;
6374 MonoInternalThread *thread;
6375 DebuggerTlsData *tls;
6376 MonoClass *env_class;
6377 MonoMethod *exit_method = NULL;
6381 exit_code = decode_int (p, &p, end);
6383 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6385 /* Have to send a reply before exiting */
6386 send_reply_packet (id, 0, buf);
6388 /* Clear all event requests */
6389 mono_loader_lock ();
6390 while (event_requests->len > 0) {
6391 EventRequest *req = g_ptr_array_index (event_requests, 0);
6393 clear_event_request (req->id, req->event_kind);
6395 mono_loader_unlock ();
6398 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6399 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6400 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6401 * better than doing the shutdown ourselves, since it avoids various races.
6405 wait_for_suspend ();
6407 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6408 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
6410 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6413 mono_loader_lock ();
6414 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6415 mono_loader_unlock ();
6417 if (thread && exit_method) {
6418 mono_loader_lock ();
6419 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6420 mono_loader_unlock ();
6422 args = g_new0 (gpointer, 1);
6423 args [0] = g_malloc (sizeof (int));
6424 *(int*)(args [0]) = exit_code;
6426 tls->pending_invoke = g_new0 (InvokeData, 1);
6427 tls->pending_invoke->method = exit_method;
6428 tls->pending_invoke->args = args;
6429 tls->pending_invoke->nmethods = 1;
6431 while (suspend_count > 0)
6435 * No thread found, do it ourselves.
6436 * FIXME: This can race with normal shutdown etc.
6438 while (suspend_count > 0)
6441 mono_runtime_set_shutting_down ();
6443 mono_threads_set_shutting_down ();
6445 /* Suspend all managed threads since the runtime is going away */
6446 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
6447 mono_thread_suspend_all_other_threads ();
6448 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
6449 mono_runtime_quit ();
6450 transport_close2 ();
6451 DEBUG(1, fprintf (log_file, "Exiting...\n"));
6457 case CMD_VM_INVOKE_METHOD:
6458 case CMD_VM_INVOKE_METHODS: {
6459 int objid = decode_objid (p, &p, end);
6461 DebuggerTlsData *tls;
6462 int i, count, err, flags, nmethods;
6464 err = get_object (objid, (MonoObject**)&thread);
6468 flags = decode_int (p, &p, end);
6470 if (command == CMD_VM_INVOKE_METHODS)
6471 nmethods = decode_int (p, &p, end);
6475 // Wait for suspending if it already started
6477 wait_for_suspend ();
6478 if (!is_suspended ())
6479 return ERR_NOT_SUSPENDED;
6481 mono_loader_lock ();
6482 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6483 mono_loader_unlock ();
6486 if (!tls->really_suspended)
6487 /* The thread is still running native code, can't do invokes */
6488 return ERR_NOT_SUSPENDED;
6491 * Store the invoke data into tls, the thread will execute it after it is
6494 if (tls->pending_invoke)
6495 return ERR_NOT_SUSPENDED;
6496 tls->pending_invoke = g_new0 (InvokeData, 1);
6497 tls->pending_invoke->id = id;
6498 tls->pending_invoke->flags = flags;
6499 tls->pending_invoke->p = g_malloc (end - p);
6500 memcpy (tls->pending_invoke->p, p, end - p);
6501 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
6502 tls->pending_invoke->suspend_count = suspend_count;
6503 tls->pending_invoke->nmethods = nmethods;
6505 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
6506 resume_thread (THREAD_TO_INTERNAL (thread));
6509 count = suspend_count;
6510 for (i = 0; i < count; ++i)
6515 case CMD_VM_ABORT_INVOKE: {
6516 int objid = decode_objid (p, &p, end);
6518 DebuggerTlsData *tls;
6521 err = get_object (objid, (MonoObject**)&thread);
6525 invoke_id = decode_int (p, &p, end);
6527 mono_loader_lock ();
6528 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6531 if (tls->abort_requested) {
6532 mono_loader_unlock ();
6537 * Check whether we're still inside the mono_runtime_invoke() and that it's
6538 * actually the correct invocation.
6540 * Careful, we do not stop the thread that's doing the invocation, so we can't
6541 * inspect its stack. However, invoke_method() also acquires the loader lock
6542 * when it's done, so we're safe here.
6546 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
6547 mono_loader_unlock ();
6548 return ERR_NO_INVOCATION;
6551 tls->abort_requested = TRUE;
6553 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
6554 mono_loader_unlock ();
6558 case CMD_VM_SET_KEEPALIVE: {
6559 int timeout = decode_int (p, &p, end);
6560 agent_config.keepalive = timeout;
6562 #ifndef DISABLE_SOCKET_TRANSPORT
6569 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
6570 GHashTableIter iter, kiter;
6575 char *fname, *basename;
6576 gboolean ignore_case;
6577 GSList *class_list, *l;
6578 GPtrArray *res_classes, *res_domains;
6580 fname = decode_string (p, &p, end);
6581 ignore_case = decode_byte (p, &p, end);
6583 basename = g_path_get_basename (fname);
6585 res_classes = g_ptr_array_new ();
6586 res_domains = g_ptr_array_new ();
6588 mono_loader_lock ();
6589 g_hash_table_iter_init (&iter, domains);
6590 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6591 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
6593 /* Update 'source_file_to_class' cache */
6594 g_hash_table_iter_init (&kiter, info->loaded_classes);
6595 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
6596 if (!g_hash_table_lookup (info->source_files, klass)) {
6597 files = get_source_files_for_type (klass);
6598 g_hash_table_insert (info->source_files, klass, files);
6600 for (i = 0; i < files->len; ++i) {
6601 char *s = g_ptr_array_index (files, i);
6602 char *s2 = g_path_get_basename (s);
6605 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
6607 class_list = g_slist_prepend (class_list, klass);
6608 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
6610 class_list = g_slist_prepend (class_list, klass);
6611 g_hash_table_insert (info->source_file_to_class, s2, class_list);
6614 /* The _ignorecase hash contains the lowercase path */
6615 s3 = strdup_tolower (s2);
6616 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
6618 class_list = g_slist_prepend (class_list, klass);
6619 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
6621 class_list = g_slist_prepend (class_list, klass);
6622 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
6634 s = strdup_tolower (basename);
6635 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
6638 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
6641 for (l = class_list; l; l = l->next) {
6644 g_ptr_array_add (res_classes, klass);
6645 g_ptr_array_add (res_domains, domain);
6648 mono_loader_unlock ();
6653 buffer_add_int (buf, res_classes->len);
6654 for (i = 0; i < res_classes->len; ++i)
6655 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6656 g_ptr_array_free (res_classes, TRUE);
6657 g_ptr_array_free (res_domains, TRUE);
6660 case CMD_VM_GET_TYPES: {
6661 GHashTableIter iter;
6665 gboolean ignore_case;
6666 GPtrArray *res_classes, *res_domains;
6667 MonoTypeNameParse info;
6669 name = decode_string (p, &p, end);
6670 ignore_case = decode_byte (p, &p, end);
6672 if (!mono_reflection_parse_type (name, &info)) {
6674 mono_reflection_free_type_info (&info);
6675 return ERR_INVALID_ARGUMENT;
6678 res_classes = g_ptr_array_new ();
6679 res_domains = g_ptr_array_new ();
6681 mono_loader_lock ();
6682 g_hash_table_iter_init (&iter, domains);
6683 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
6685 gboolean type_resolve;
6689 mono_domain_assemblies_lock (domain);
6690 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6694 type_resolve = TRUE;
6695 t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
6697 g_ptr_array_add (res_classes, mono_type_get_class (t));
6698 g_ptr_array_add (res_domains, domain);
6702 mono_domain_assemblies_unlock (domain);
6704 mono_loader_unlock ();
6707 mono_reflection_free_type_info (&info);
6709 buffer_add_int (buf, res_classes->len);
6710 for (i = 0; i < res_classes->len; ++i)
6711 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
6712 g_ptr_array_free (res_classes, TRUE);
6713 g_ptr_array_free (res_domains, TRUE);
6718 return ERR_NOT_IMPLEMENTED;
6725 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6731 case CMD_EVENT_REQUEST_SET: {
6733 int i, event_kind, suspend_policy, nmodifiers, mod;
6736 MonoThread *step_thread;
6737 int size = 0, depth = 0, filter = 0, step_thread_id = 0;
6741 event_kind = decode_byte (p, &p, end);
6742 suspend_policy = decode_byte (p, &p, end);
6743 nmodifiers = decode_byte (p, &p, end);
6745 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
6746 req->id = InterlockedIncrement (&event_request_id);
6747 req->event_kind = event_kind;
6748 req->suspend_policy = suspend_policy;
6749 req->nmodifiers = nmodifiers;
6752 for (i = 0; i < nmodifiers; ++i) {
6753 mod = decode_byte (p, &p, end);
6755 req->modifiers [i].kind = mod;
6756 if (mod == MOD_KIND_COUNT) {
6757 req->modifiers [i].data.count = decode_int (p, &p, end);
6758 } else if (mod == MOD_KIND_LOCATION_ONLY) {
6759 method = decode_methodid (p, &p, end, &domain, &err);
6762 location = decode_long (p, &p, end);
6763 } else if (mod == MOD_KIND_STEP) {
6764 step_thread_id = decode_id (p, &p, end);
6765 size = decode_int (p, &p, end);
6766 depth = decode_int (p, &p, end);
6767 if (CHECK_PROTOCOL_VERSION (2, 16))
6768 filter = decode_int (p, &p, end);
6769 req->modifiers [i].data.filter = filter;
6770 } else if (mod == MOD_KIND_THREAD_ONLY) {
6771 int id = decode_id (p, &p, end);
6773 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
6778 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
6779 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
6783 req->modifiers [i].caught = decode_byte (p, &p, end);
6784 req->modifiers [i].uncaught = decode_byte (p, &p, end);
6785 DEBUG(1, fprintf (log_file, "[dbg] \tEXCEPTION_ONLY filter (%s%s%s).\n", exc_class ? exc_class->name : "all", req->modifiers [i].caught ? ", caught" : "", req->modifiers [i].uncaught ? ", uncaught" : ""));
6787 req->modifiers [i].data.exc_class = exc_class;
6789 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
6791 return ERR_INVALID_ARGUMENT;
6794 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
6795 int n = decode_int (p, &p, end);
6798 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
6799 for (j = 0; j < n; ++j) {
6800 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
6802 g_free (req->modifiers [i].data.assemblies);
6806 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
6807 int n = decode_int (p, &p, end);
6810 modifier = &req->modifiers [i];
6811 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
6812 for (j = 0; j < n; ++j) {
6813 char *s = decode_string (p, &p, end);
6817 s2 = strdup_tolower (s);
6818 g_hash_table_insert (modifier->data.source_files, s2, s2);
6822 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
6823 int n = decode_int (p, &p, end);
6826 modifier = &req->modifiers [i];
6827 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
6828 for (j = 0; j < n; ++j) {
6829 char *s = decode_string (p, &p, end);
6832 g_hash_table_insert (modifier->data.type_names, s, s);
6836 return ERR_NOT_IMPLEMENTED;
6840 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
6843 req->info = set_breakpoint (method, location, req, &error);
6844 if (!mono_error_ok (&error)) {
6846 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
6847 mono_error_cleanup (&error);
6848 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
6850 } else if (req->event_kind == EVENT_KIND_STEP) {
6851 g_assert (step_thread_id);
6853 err = get_object (step_thread_id, (MonoObject**)&step_thread);
6859 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
6864 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
6865 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
6866 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
6867 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
6868 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
6869 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
6871 if (req->nmodifiers) {
6873 return ERR_NOT_IMPLEMENTED;
6877 mono_loader_lock ();
6878 g_ptr_array_add (event_requests, req);
6880 if (agent_config.defer) {
6881 /* Transmit cached data to the client on receipt of the event request */
6882 switch (req->event_kind) {
6883 case EVENT_KIND_APPDOMAIN_CREATE:
6884 /* Emit load events for currently loaded domains */
6885 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
6887 case EVENT_KIND_ASSEMBLY_LOAD:
6888 /* Emit load events for currently loaded assemblies */
6889 mono_assembly_foreach (emit_assembly_load, NULL);
6891 case EVENT_KIND_THREAD_START:
6892 /* Emit start events for currently started threads */
6893 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
6895 case EVENT_KIND_TYPE_LOAD:
6896 /* Emit type load events for currently loaded types */
6897 mono_domain_foreach (send_types_for_domain, NULL);
6903 mono_loader_unlock ();
6905 buffer_add_int (buf, req->id);
6908 case CMD_EVENT_REQUEST_CLEAR: {
6909 int etype = decode_byte (p, &p, end);
6910 int req_id = decode_int (p, &p, end);
6912 // FIXME: Make a faster mapping from req_id to request
6913 mono_loader_lock ();
6914 clear_event_request (req_id, etype);
6915 mono_loader_unlock ();
6918 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
6921 mono_loader_lock ();
6923 while (i < event_requests->len) {
6924 EventRequest *req = g_ptr_array_index (event_requests, i);
6926 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
6927 clear_breakpoint (req->info);
6929 g_ptr_array_remove_index_fast (event_requests, i);
6935 mono_loader_unlock ();
6939 return ERR_NOT_IMPLEMENTED;
6946 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
6952 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
6953 buffer_add_domainid (buf, mono_get_root_domain ());
6956 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
6957 domain = decode_domainid (p, &p, end, NULL, &err);
6960 buffer_add_string (buf, domain->friendly_name);
6963 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
6968 domain = decode_domainid (p, &p, end, NULL, &err);
6971 mono_loader_lock ();
6973 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6976 buffer_add_int (buf, count);
6977 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6979 buffer_add_assemblyid (buf, domain, ass);
6981 mono_loader_unlock ();
6984 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
6985 domain = decode_domainid (p, &p, end, NULL, &err);
6989 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
6992 case CMD_APPDOMAIN_GET_CORLIB: {
6993 domain = decode_domainid (p, &p, end, NULL, &err);
6997 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7000 case CMD_APPDOMAIN_CREATE_STRING: {
7004 domain = decode_domainid (p, &p, end, NULL, &err);
7007 s = decode_string (p, &p, end);
7009 o = mono_string_new (domain, s);
7010 buffer_add_objid (buf, (MonoObject*)o);
7013 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7015 MonoDomain *domain2;
7018 domain = decode_domainid (p, &p, end, NULL, &err);
7021 klass = decode_typeid (p, &p, end, &domain2, &err);
7026 g_assert (domain == domain2);
7028 o = mono_object_new (domain, klass);
7030 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
7034 buffer_add_objid (buf, o);
7038 return ERR_NOT_IMPLEMENTED;
7045 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7051 ass = decode_assemblyid (p, &p, end, &domain, &err);
7056 case CMD_ASSEMBLY_GET_LOCATION: {
7057 buffer_add_string (buf, mono_image_get_filename (ass->image));
7060 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7064 if (ass->image->dynamic) {
7065 buffer_add_id (buf, 0);
7067 token = mono_image_get_entry_point (ass->image);
7069 buffer_add_id (buf, 0);
7071 m = mono_get_method (ass->image, token, NULL);
7072 buffer_add_methodid (buf, domain, m);
7077 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7078 buffer_add_moduleid (buf, domain, ass->image);
7081 case CMD_ASSEMBLY_GET_OBJECT: {
7082 MonoObject *o = (MonoObject*)mono_assembly_get_object (domain, ass);
7083 buffer_add_objid (buf, o);
7086 case CMD_ASSEMBLY_GET_TYPE: {
7087 char *s = decode_string (p, &p, end);
7088 gboolean ignorecase = decode_byte (p, &p, end);
7089 MonoTypeNameParse info;
7091 gboolean type_resolve, res;
7092 MonoDomain *d = mono_domain_get ();
7094 /* This is needed to be able to find referenced assemblies */
7095 res = mono_domain_set (domain, FALSE);
7098 if (!mono_reflection_parse_type (s, &info)) {
7101 if (info.assembly.name)
7103 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
7105 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
7106 mono_reflection_free_type_info (&info);
7109 mono_domain_set (d, TRUE);
7113 case CMD_ASSEMBLY_GET_NAME: {
7115 MonoAssembly *mass = ass;
7117 name = g_strdup_printf (
7118 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7120 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7121 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7122 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7123 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7125 buffer_add_string (buf, name);
7130 return ERR_NOT_IMPLEMENTED;
7137 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7143 case CMD_MODULE_GET_INFO: {
7144 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7147 basename = g_path_get_basename (image->name);
7148 buffer_add_string (buf, basename); // name
7149 buffer_add_string (buf, image->module_name); // scopename
7150 buffer_add_string (buf, image->name); // fqname
7151 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7152 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7157 return ERR_NOT_IMPLEMENTED;
7164 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7166 if (val && val->vtable->klass == mono_defaults.monotype_class) {
7167 /* Special case these so the client doesn't have to handle Type objects */
7169 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7170 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7171 } else if (MONO_TYPE_IS_REFERENCE (t))
7172 buffer_add_value (buf, t, &val, domain);
7174 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7178 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7184 buffer_add_int (buf, 0);
7188 for (i = 0; i < cinfo->num_attrs; ++i) {
7189 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7192 buffer_add_int (buf, nattrs);
7194 for (i = 0; i < cinfo->num_attrs; ++i) {
7195 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7196 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7197 MonoArray *typed_args, *named_args;
7199 CattrNamedArg *arginfo;
7201 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo);
7203 buffer_add_methodid (buf, domain, attr->ctor);
7207 buffer_add_int (buf, mono_array_length (typed_args));
7208 for (j = 0; j < mono_array_length (typed_args); ++j) {
7209 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7211 t = mono_method_signature (attr->ctor)->params [j];
7213 buffer_add_cattr_arg (buf, t, domain, val);
7216 buffer_add_int (buf, 0);
7221 buffer_add_int (buf, mono_array_length (named_args));
7223 for (j = 0; j < mono_array_length (named_args); ++j) {
7224 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7226 if (arginfo [j].prop) {
7227 buffer_add_byte (buf, 0x54);
7228 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7229 } else if (arginfo [j].field) {
7230 buffer_add_byte (buf, 0x53);
7231 buffer_add_fieldid (buf, domain, arginfo [j].field);
7233 g_assert_not_reached ();
7236 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7239 buffer_add_int (buf, 0);
7245 /* FIXME: Code duplication with icall.c */
7247 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7252 mono_class_setup_interfaces (klass, error);
7253 if (!mono_error_ok (error))
7256 for (i = 0; i < klass->interface_count; i++) {
7257 ic = klass->interfaces [i];
7258 g_hash_table_insert (ifaces, ic, ic);
7260 collect_interfaces (ic, ifaces, error);
7261 if (!mono_error_ok (error))
7267 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7277 case CMD_TYPE_GET_INFO: {
7278 buffer_add_string (buf, klass->name_space);
7279 buffer_add_string (buf, klass->name);
7281 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7282 buffer_add_string (buf, name);
7284 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7285 buffer_add_moduleid (buf, domain, klass->image);
7286 buffer_add_typeid (buf, domain, klass->parent);
7287 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7288 buffer_add_typeid (buf, domain, klass->element_class);
7290 buffer_add_id (buf, 0);
7291 buffer_add_int (buf, klass->type_token);
7292 buffer_add_byte (buf, klass->rank);
7293 buffer_add_int (buf, klass->flags);
7295 type = &klass->byval_arg;
7296 // FIXME: Can't decide whenever a class represents a byref type
7299 if (type->type == MONO_TYPE_PTR)
7301 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7303 if (type->type == MONO_TYPE_VALUETYPE)
7305 if (klass->enumtype)
7307 if (klass->generic_container)
7309 if (klass->generic_container || klass->generic_class)
7311 buffer_add_byte (buf, b);
7314 while ((nested = mono_class_get_nested_types (klass, &iter)))
7316 buffer_add_int (buf, nnested);
7318 while ((nested = mono_class_get_nested_types (klass, &iter)))
7319 buffer_add_typeid (buf, domain, nested);
7320 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7321 if (klass->generic_container)
7322 buffer_add_typeid (buf, domain, klass);
7323 else if (klass->generic_class)
7324 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7326 buffer_add_id (buf, 0);
7328 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7331 if (klass->generic_class) {
7332 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7334 count = inst->type_argc;
7335 buffer_add_int (buf, count);
7336 for (i = 0; i < count; i++)
7337 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7338 } else if (klass->generic_container) {
7339 MonoGenericContainer *container = klass->generic_container;
7342 count = container->type_argc;
7343 buffer_add_int (buf, count);
7344 for (i = 0; i < count; i++) {
7345 pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
7346 buffer_add_typeid (buf, domain, pklass);
7349 buffer_add_int (buf, 0);
7354 case CMD_TYPE_GET_METHODS: {
7357 gpointer iter = NULL;
7360 mono_class_setup_methods (klass);
7362 nmethods = mono_class_num_methods (klass);
7364 buffer_add_int (buf, nmethods);
7366 while ((m = mono_class_get_methods (klass, &iter))) {
7367 buffer_add_methodid (buf, domain, m);
7370 g_assert (i == nmethods);
7373 case CMD_TYPE_GET_FIELDS: {
7376 gpointer iter = NULL;
7379 nfields = mono_class_num_fields (klass);
7381 buffer_add_int (buf, nfields);
7383 while ((f = mono_class_get_fields (klass, &iter))) {
7384 buffer_add_fieldid (buf, domain, f);
7385 buffer_add_string (buf, f->name);
7386 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7387 buffer_add_int (buf, f->type->attrs);
7390 g_assert (i == nfields);
7393 case CMD_TYPE_GET_PROPERTIES: {
7396 gpointer iter = NULL;
7399 nprops = mono_class_num_properties (klass);
7401 buffer_add_int (buf, nprops);
7403 while ((p = mono_class_get_properties (klass, &iter))) {
7404 buffer_add_propertyid (buf, domain, p);
7405 buffer_add_string (buf, p->name);
7406 buffer_add_methodid (buf, domain, p->get);
7407 buffer_add_methodid (buf, domain, p->set);
7408 buffer_add_int (buf, p->attrs);
7411 g_assert (i == nprops);
7414 case CMD_TYPE_GET_CATTRS: {
7415 MonoClass *attr_klass;
7416 MonoCustomAttrInfo *cinfo;
7418 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7419 /* attr_klass can be NULL */
7423 cinfo = mono_custom_attrs_from_class (klass);
7425 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7428 case CMD_TYPE_GET_FIELD_CATTRS: {
7429 MonoClass *attr_klass;
7430 MonoCustomAttrInfo *cinfo;
7431 MonoClassField *field;
7433 field = decode_fieldid (p, &p, end, NULL, &err);
7436 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7440 cinfo = mono_custom_attrs_from_field (klass, field);
7442 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7445 case CMD_TYPE_GET_PROPERTY_CATTRS: {
7446 MonoClass *attr_klass;
7447 MonoCustomAttrInfo *cinfo;
7450 prop = decode_propertyid (p, &p, end, NULL, &err);
7453 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7457 cinfo = mono_custom_attrs_from_property (klass, prop);
7459 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7462 case CMD_TYPE_GET_VALUES:
7463 case CMD_TYPE_GET_VALUES_2: {
7470 MonoThread *thread_obj;
7471 MonoInternalThread *thread = NULL;
7472 guint32 special_static_type;
7474 if (command == CMD_TYPE_GET_VALUES_2) {
7475 int objid = decode_objid (p, &p, end);
7478 err = get_object (objid, (MonoObject**)&thread_obj);
7482 thread = THREAD_TO_INTERNAL (thread_obj);
7485 len = decode_int (p, &p, end);
7486 for (i = 0; i < len; ++i) {
7487 f = decode_fieldid (p, &p, end, NULL, &err);
7491 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7492 return ERR_INVALID_FIELDID;
7493 special_static_type = mono_class_field_get_special_static_type (f);
7494 if (special_static_type != SPECIAL_STATIC_NONE) {
7495 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
7496 return ERR_INVALID_FIELDID;
7499 /* Check that the field belongs to the object */
7501 for (k = klass; k; k = k->parent) {
7502 if (k == f->parent) {
7508 return ERR_INVALID_FIELDID;
7510 vtable = mono_class_vtable (domain, f->parent);
7511 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7512 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
7513 buffer_add_value (buf, f->type, val, domain);
7518 case CMD_TYPE_SET_VALUES: {
7526 len = decode_int (p, &p, end);
7527 for (i = 0; i < len; ++i) {
7528 f = decode_fieldid (p, &p, end, NULL, &err);
7532 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
7533 return ERR_INVALID_FIELDID;
7534 if (mono_class_field_is_special_static (f))
7535 return ERR_INVALID_FIELDID;
7537 /* Check that the field belongs to the object */
7539 for (k = klass; k; k = k->parent) {
7540 if (k == f->parent) {
7546 return ERR_INVALID_FIELDID;
7548 // FIXME: Check for literal/const
7550 vtable = mono_class_vtable (domain, f->parent);
7551 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
7552 err = decode_value (f->type, domain, val, p, &p, end);
7557 if (MONO_TYPE_IS_REFERENCE (f->type))
7558 mono_field_static_set_value (vtable, f, *(gpointer*)val);
7560 mono_field_static_set_value (vtable, f, val);
7565 case CMD_TYPE_GET_OBJECT: {
7566 MonoObject *o = (MonoObject*)mono_type_get_object (domain, &klass->byval_arg);
7567 buffer_add_objid (buf, o);
7570 case CMD_TYPE_GET_SOURCE_FILES:
7571 case CMD_TYPE_GET_SOURCE_FILES_2: {
7572 char *source_file, *base;
7576 files = get_source_files_for_type (klass);
7578 buffer_add_int (buf, files->len);
7579 for (i = 0; i < files->len; ++i) {
7580 source_file = g_ptr_array_index (files, i);
7581 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
7582 buffer_add_string (buf, source_file);
7584 base = g_path_get_basename (source_file);
7585 buffer_add_string (buf, base);
7588 g_free (source_file);
7590 g_ptr_array_free (files, TRUE);
7593 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
7594 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
7598 if (mono_class_is_assignable_from (klass, oklass))
7599 buffer_add_byte (buf, 1);
7601 buffer_add_byte (buf, 0);
7604 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
7605 char *name = decode_string (p, &p, end);
7606 int i, flags = decode_int (p, &p, end);
7607 MonoException *ex = NULL;
7608 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
7611 return ERR_LOADER_ERROR;
7612 buffer_add_int (buf, array->len);
7613 for (i = 0; i < array->len; ++i) {
7614 MonoMethod *method = g_ptr_array_index (array, i);
7615 buffer_add_methodid (buf, domain, method);
7618 g_ptr_array_free (array, TRUE);
7622 case CMD_TYPE_GET_INTERFACES: {
7624 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
7626 MonoClass *tclass, *iface;
7627 GHashTableIter iter;
7631 for (parent = tclass; parent; parent = parent->parent) {
7632 mono_class_setup_interfaces (parent, &error);
7633 if (!mono_error_ok (&error))
7634 return ERR_LOADER_ERROR;
7635 collect_interfaces (parent, iface_hash, &error);
7636 if (!mono_error_ok (&error))
7637 return ERR_LOADER_ERROR;
7640 buffer_add_int (buf, g_hash_table_size (iface_hash));
7642 g_hash_table_iter_init (&iter, iface_hash);
7643 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
7644 buffer_add_typeid (buf, domain, iface);
7645 g_hash_table_destroy (iface_hash);
7648 case CMD_TYPE_GET_INTERFACE_MAP: {
7649 int tindex, ioffset;
7650 gboolean variance_used;
7652 int len, nmethods, i;
7656 len = decode_int (p, &p, end);
7657 mono_class_setup_vtable (klass);
7659 for (tindex = 0; tindex < len; ++tindex) {
7660 iclass = decode_typeid (p, &p, end, NULL, &err);
7664 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
7666 return ERR_INVALID_ARGUMENT;
7668 nmethods = mono_class_num_methods (iclass);
7669 buffer_add_int (buf, nmethods);
7672 while ((method = mono_class_get_methods (iclass, &iter))) {
7673 buffer_add_methodid (buf, domain, method);
7675 for (i = 0; i < nmethods; ++i)
7676 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
7680 case CMD_TYPE_IS_INITIALIZED: {
7681 MonoVTable *vtable = mono_class_vtable (domain, klass);
7684 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
7686 buffer_add_int (buf, 0);
7690 return ERR_NOT_IMPLEMENTED;
7697 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7700 MonoDomain *old_domain;
7704 klass = decode_typeid (p, &p, end, &domain, &err);
7708 old_domain = mono_domain_get ();
7710 mono_domain_set (domain, TRUE);
7712 err = type_commands_internal (command, klass, domain, p, end, buf);
7714 mono_domain_set (old_domain, TRUE);
7720 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7722 MonoMethodHeader *header;
7726 case CMD_METHOD_GET_NAME: {
7727 buffer_add_string (buf, method->name);
7730 case CMD_METHOD_GET_DECLARING_TYPE: {
7731 buffer_add_typeid (buf, domain, method->klass);
7734 case CMD_METHOD_GET_DEBUG_INFO: {
7735 MonoDebugMethodInfo *minfo;
7737 int i, j, n_il_offsets;
7740 int *column_numbers;
7742 GPtrArray *source_file_list;
7744 header = mono_method_get_header (method);
7746 buffer_add_int (buf, 0);
7747 buffer_add_string (buf, "");
7748 buffer_add_int (buf, 0);
7752 minfo = mono_debug_lookup_method (method);
7754 buffer_add_int (buf, header->code_size);
7755 buffer_add_string (buf, "");
7756 buffer_add_int (buf, 0);
7757 mono_metadata_free_mh (header);
7761 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, &n_il_offsets, &il_offsets, &line_numbers, &column_numbers, &source_files);
7762 buffer_add_int (buf, header->code_size);
7763 if (CHECK_PROTOCOL_VERSION (2, 13)) {
7764 buffer_add_int (buf, source_file_list->len);
7765 for (i = 0; i < source_file_list->len; ++i) {
7766 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
7767 buffer_add_string (buf, sinfo->source_file);
7768 if (CHECK_PROTOCOL_VERSION (2, 14)) {
7769 for (j = 0; j < 16; ++j)
7770 buffer_add_byte (buf, sinfo->hash [j]);
7774 buffer_add_string (buf, source_file);
7776 buffer_add_int (buf, n_il_offsets);
7777 DEBUG (10, fprintf (log_file, "Line number table for method %s:\n", mono_method_full_name (method, TRUE)));
7778 for (i = 0; i < n_il_offsets; ++i) {
7779 const char *srcfile = "";
7781 if (source_files [i] != -1) {
7782 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
7783 srcfile = sinfo->source_file;
7785 DEBUG (10, fprintf (log_file, "IL%x -> %s:%d %d\n", il_offsets [i], srcfile, line_numbers [i], column_numbers ? column_numbers [i] : -1));
7786 buffer_add_int (buf, il_offsets [i]);
7787 buffer_add_int (buf, line_numbers [i]);
7788 if (CHECK_PROTOCOL_VERSION (2, 13))
7789 buffer_add_int (buf, source_files [i]);
7790 if (CHECK_PROTOCOL_VERSION (2, 19))
7791 buffer_add_int (buf, column_numbers ? column_numbers [i] : -1);
7793 g_free (source_file);
7794 g_free (il_offsets);
7795 g_free (line_numbers);
7796 g_free (source_files);
7797 g_ptr_array_free (source_file_list, TRUE);
7798 mono_metadata_free_mh (header);
7801 case CMD_METHOD_GET_PARAM_INFO: {
7802 MonoMethodSignature *sig = mono_method_signature (method);
7806 /* FIXME: mono_class_from_mono_type () and byrefs */
7808 /* FIXME: Use a smaller encoding */
7809 buffer_add_int (buf, sig->call_convention);
7810 buffer_add_int (buf, sig->param_count);
7811 buffer_add_int (buf, sig->generic_param_count);
7812 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
7813 for (i = 0; i < sig->param_count; ++i) {
7815 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
7818 /* Emit parameter names */
7819 names = g_new (char *, sig->param_count);
7820 mono_method_get_param_names (method, (const char **) names);
7821 for (i = 0; i < sig->param_count; ++i)
7822 buffer_add_string (buf, names [i]);
7827 case CMD_METHOD_GET_LOCALS_INFO: {
7828 int i, j, num_locals;
7829 MonoDebugLocalsInfo *locals;
7831 header = mono_method_get_header (method);
7833 return ERR_INVALID_ARGUMENT;
7835 buffer_add_int (buf, header->num_locals);
7838 for (i = 0; i < header->num_locals; ++i)
7839 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
7842 locals = mono_debug_lookup_locals (method);
7844 num_locals = locals->num_locals;
7847 for (i = 0; i < header->num_locals; ++i) {
7848 for (j = 0; j < num_locals; ++j)
7849 if (locals->locals [j].index == i)
7852 buffer_add_string (buf, locals->locals [j].name);
7854 buffer_add_string (buf, "");
7858 for (i = 0; i < header->num_locals; ++i) {
7859 for (j = 0; j < num_locals; ++j)
7860 if (locals->locals [j].index == i)
7862 if (j < num_locals && locals->locals [j].block) {
7863 buffer_add_int (buf, locals->locals [j].block->start_offset);
7864 buffer_add_int (buf, locals->locals [j].block->end_offset);
7866 buffer_add_int (buf, 0);
7867 buffer_add_int (buf, header->code_size);
7870 mono_metadata_free_mh (header);
7873 mono_debug_symfile_free_locals (locals);
7877 case CMD_METHOD_GET_INFO:
7878 buffer_add_int (buf, method->flags);
7879 buffer_add_int (buf, method->iflags);
7880 buffer_add_int (buf, method->token);
7881 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7883 if (method->is_generic)
7885 if (mono_method_signature (method)->generic_param_count)
7887 buffer_add_byte (buf, attrs);
7888 if (method->is_generic || method->is_inflated) {
7891 if (method->is_generic) {
7894 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
7896 result = imethod->declaring;
7897 if (imethod->context.class_inst) {
7898 MonoClass *klass = ((MonoMethod *) imethod)->klass;
7899 /*Generic methods gets the context of the GTD.*/
7900 if (mono_class_get_context (klass))
7901 result = mono_class_inflate_generic_method_full (result, klass, mono_class_get_context (klass));
7905 buffer_add_methodid (buf, domain, result);
7907 buffer_add_id (buf, 0);
7909 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7910 if (mono_method_signature (method)->generic_param_count) {
7913 if (method->is_inflated) {
7914 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
7916 count = inst->type_argc;
7917 buffer_add_int (buf, count);
7919 for (i = 0; i < count; i++)
7920 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7922 buffer_add_int (buf, 0);
7924 } else if (method->is_generic) {
7925 MonoGenericContainer *container = mono_method_get_generic_container (method);
7927 count = mono_method_signature (method)->generic_param_count;
7928 buffer_add_int (buf, count);
7929 for (i = 0; i < count; i++) {
7930 MonoGenericParam *param = mono_generic_container_get_param (container, i);
7931 MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
7932 buffer_add_typeid (buf, domain, pklass);
7935 buffer_add_int (buf, 0);
7938 buffer_add_int (buf, 0);
7943 case CMD_METHOD_GET_BODY: {
7946 header = mono_method_get_header (method);
7948 buffer_add_int (buf, 0);
7950 if (CHECK_PROTOCOL_VERSION (2, 18))
7951 buffer_add_int (buf, 0);
7953 buffer_add_int (buf, header->code_size);
7954 for (i = 0; i < header->code_size; ++i)
7955 buffer_add_byte (buf, header->code [i]);
7957 if (CHECK_PROTOCOL_VERSION (2, 18)) {
7958 buffer_add_int (buf, header->num_clauses);
7959 for (i = 0; i < header->num_clauses; ++i) {
7960 MonoExceptionClause *clause = &header->clauses [i];
7962 buffer_add_int (buf, clause->flags);
7963 buffer_add_int (buf, clause->try_offset);
7964 buffer_add_int (buf, clause->try_len);
7965 buffer_add_int (buf, clause->handler_offset);
7966 buffer_add_int (buf, clause->handler_len);
7967 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
7968 buffer_add_typeid (buf, domain, clause->data.catch_class);
7969 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
7970 buffer_add_int (buf, clause->data.filter_offset);
7974 mono_metadata_free_mh (header);
7979 case CMD_METHOD_RESOLVE_TOKEN: {
7980 guint32 token = decode_int (p, &p, end);
7983 switch (mono_metadata_token_code (token)) {
7984 case MONO_TOKEN_STRING: {
7988 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
7991 s2 = mono_string_to_utf8 (s);
7993 buffer_add_byte (buf, TOKEN_TYPE_STRING);
7994 buffer_add_string (buf, s2);
8000 MonoClass *handle_class;
8002 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8003 val = mono_method_get_wrapper_data (method, token);
8004 handle_class = mono_method_get_wrapper_data (method, token + 1);
8006 if (handle_class == NULL) {
8007 // Can't figure out the token type
8008 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8012 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
8016 if (handle_class == mono_defaults.typehandle_class) {
8017 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8018 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8019 buffer_add_typeid (buf, domain, (MonoClass *) val);
8021 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
8022 } else if (handle_class == mono_defaults.fieldhandle_class) {
8023 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8024 buffer_add_fieldid (buf, domain, val);
8025 } else if (handle_class == mono_defaults.methodhandle_class) {
8026 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8027 buffer_add_methodid (buf, domain, val);
8028 } else if (handle_class == mono_defaults.string_class) {
8031 s = mono_string_to_utf8 (val);
8032 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8033 buffer_add_string (buf, s);
8036 g_assert_not_reached ();
8043 case CMD_METHOD_GET_CATTRS: {
8044 MonoClass *attr_klass;
8045 MonoCustomAttrInfo *cinfo;
8047 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8048 /* attr_klass can be NULL */
8052 cinfo = mono_custom_attrs_from_method (method);
8054 buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
8058 return ERR_NOT_IMPLEMENTED;
8065 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8068 MonoDomain *old_domain;
8072 method = decode_methodid (p, &p, end, &domain, &err);
8076 old_domain = mono_domain_get ();
8078 mono_domain_set (domain, TRUE);
8080 err = method_commands_internal (command, method, domain, p, end, buf);
8082 mono_domain_set (old_domain, TRUE);
8088 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8090 int objid = decode_objid (p, &p, end);
8092 MonoThread *thread_obj;
8093 MonoInternalThread *thread;
8095 err = get_object (objid, (MonoObject**)&thread_obj);
8099 thread = THREAD_TO_INTERNAL (thread_obj);
8102 case CMD_THREAD_GET_NAME: {
8104 gunichar2 *s = mono_thread_get_name (thread, &name_len);
8107 buffer_add_int (buf, 0);
8112 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
8114 buffer_add_int (buf, len);
8115 buffer_add_data (buf, (guint8*)name, len);
8120 case CMD_THREAD_GET_FRAME_INFO: {
8121 DebuggerTlsData *tls;
8122 int i, start_frame, length;
8124 // Wait for suspending if it already started
8125 // FIXME: Races with suspend_count
8126 while (!is_suspended ()) {
8128 wait_for_suspend ();
8132 wait_for_suspend ();
8133 if (!is_suspended ())
8134 return ERR_NOT_SUSPENDED;
8137 start_frame = decode_int (p, &p, end);
8138 length = decode_int (p, &p, end);
8140 if (start_frame != 0 || length != -1)
8141 return ERR_NOT_IMPLEMENTED;
8143 mono_loader_lock ();
8144 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8145 mono_loader_unlock ();
8148 compute_frame_info (thread, tls);
8150 buffer_add_int (buf, tls->frame_count);
8151 for (i = 0; i < tls->frame_count; ++i) {
8152 buffer_add_int (buf, tls->frames [i]->id);
8153 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
8154 buffer_add_int (buf, tls->frames [i]->il_offset);
8156 * Instead of passing the frame type directly to the client, we associate
8157 * it with the previous frame using a set of flags. This avoids lots of
8158 * conditional code in the client, since a frame whose type isn't
8159 * FRAME_TYPE_MANAGED has no method, location, etc.
8161 buffer_add_byte (buf, tls->frames [i]->flags);
8166 case CMD_THREAD_GET_STATE:
8167 buffer_add_int (buf, thread->state);
8169 case CMD_THREAD_GET_INFO:
8170 buffer_add_byte (buf, thread->threadpool_thread);
8172 case CMD_THREAD_GET_ID:
8173 buffer_add_long (buf, (guint64)(gsize)thread);
8175 case CMD_THREAD_GET_TID:
8176 buffer_add_long (buf, (guint64)thread->tid);
8179 return ERR_NOT_IMPLEMENTED;
8186 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8190 MonoThread *thread_obj;
8191 MonoInternalThread *thread;
8192 int pos, i, len, frame_idx;
8193 DebuggerTlsData *tls;
8195 MonoDebugMethodJitInfo *jit;
8196 MonoDebugVarInfo *var;
8197 MonoMethodSignature *sig;
8199 MonoMethodHeader *header;
8201 objid = decode_objid (p, &p, end);
8202 err = get_object (objid, (MonoObject**)&thread_obj);
8206 thread = THREAD_TO_INTERNAL (thread_obj);
8208 id = decode_id (p, &p, end);
8210 mono_loader_lock ();
8211 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8212 mono_loader_unlock ();
8215 for (i = 0; i < tls->frame_count; ++i) {
8216 if (tls->frames [i]->id == id)
8219 if (i == tls->frame_count)
8220 return ERR_INVALID_FRAMEID;
8223 frame = tls->frames [frame_idx];
8225 if (!frame->has_ctx)
8227 return ERR_INVALID_FRAMEID;
8230 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
8231 if (!frame->jit && frame->api_method->is_inflated)
8232 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
8236 /* This could happen for aot images with no jit debug info */
8237 s = mono_method_full_name (frame->api_method, TRUE);
8238 DEBUG (1, fprintf (log_file, "[dbg] No debug information found for '%s'.\n", s));
8240 return ERR_ABSENT_INFORMATION;
8245 sig = mono_method_signature (frame->actual_method);
8247 if (!get_seq_points (frame->domain, frame->actual_method))
8249 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
8251 return ERR_ABSENT_INFORMATION;
8254 case CMD_STACK_FRAME_GET_VALUES: {
8255 len = decode_int (p, &p, end);
8256 header = mono_method_get_header (frame->actual_method);
8258 for (i = 0; i < len; ++i) {
8259 pos = decode_int (p, &p, end);
8264 g_assert (pos >= 0 && pos < jit->num_params);
8266 var = &jit->params [pos];
8268 add_var (buf, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
8270 g_assert (pos >= 0 && pos < jit->num_locals);
8272 var = &jit->locals [pos];
8274 add_var (buf, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
8277 mono_metadata_free_mh (header);
8280 case CMD_STACK_FRAME_GET_THIS: {
8281 if (frame->api_method->klass->valuetype) {
8282 if (!sig->hasthis) {
8283 MonoObject *p = NULL;
8284 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
8286 add_var (buf, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8289 if (!sig->hasthis) {
8290 MonoObject *p = NULL;
8291 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
8293 add_var (buf, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8298 case CMD_STACK_FRAME_SET_VALUES: {
8301 MonoDebugVarInfo *var;
8303 len = decode_int (p, &p, end);
8304 header = mono_method_get_header (frame->actual_method);
8306 for (i = 0; i < len; ++i) {
8307 pos = decode_int (p, &p, end);
8312 g_assert (pos >= 0 && pos < jit->num_params);
8314 t = sig->params [pos];
8315 var = &jit->params [pos];
8317 g_assert (pos >= 0 && pos < jit->num_locals);
8319 t = header->locals [pos];
8320 var = &jit->locals [pos];
8323 if (MONO_TYPE_IS_REFERENCE (t))
8324 val_buf = g_alloca (sizeof (MonoObject*));
8326 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
8327 err = decode_value (t, frame->domain, val_buf, p, &p, end);
8331 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_ctx);
8333 mono_metadata_free_mh (header);
8337 return ERR_NOT_IMPLEMENTED;
8344 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8347 int objid, err, index, len, i, esize;
8350 objid = decode_objid (p, &p, end);
8351 err = get_object (objid, (MonoObject**)&arr);
8356 case CMD_ARRAY_REF_GET_LENGTH:
8357 buffer_add_int (buf, arr->obj.vtable->klass->rank);
8359 buffer_add_int (buf, arr->max_length);
8360 buffer_add_int (buf, 0);
8362 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
8363 buffer_add_int (buf, arr->bounds [i].length);
8364 buffer_add_int (buf, arr->bounds [i].lower_bound);
8368 case CMD_ARRAY_REF_GET_VALUES:
8369 index = decode_int (p, &p, end);
8370 len = decode_int (p, &p, end);
8372 g_assert (index >= 0 && len >= 0);
8373 // Reordered to avoid integer overflow
8374 g_assert (!(index > arr->max_length - len));
8376 esize = mono_array_element_size (arr->obj.vtable->klass);
8377 for (i = index; i < index + len; ++i) {
8378 elem = (gpointer*)((char*)arr->vector + (i * esize));
8379 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
8382 case CMD_ARRAY_REF_SET_VALUES:
8383 index = decode_int (p, &p, end);
8384 len = decode_int (p, &p, end);
8386 g_assert (index >= 0 && len >= 0);
8387 // Reordered to avoid integer overflow
8388 g_assert (!(index > arr->max_length - len));
8390 esize = mono_array_element_size (arr->obj.vtable->klass);
8391 for (i = index; i < index + len; ++i) {
8392 elem = (gpointer*)((char*)arr->vector + (i * esize));
8394 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
8398 return ERR_NOT_IMPLEMENTED;
8405 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8410 int i, index, length;
8413 objid = decode_objid (p, &p, end);
8414 err = get_object (objid, (MonoObject**)&str);
8419 case CMD_STRING_REF_GET_VALUE:
8420 s = mono_string_to_utf8 (str);
8421 buffer_add_string (buf, s);
8424 case CMD_STRING_REF_GET_LENGTH:
8425 buffer_add_long (buf, mono_string_length (str));
8427 case CMD_STRING_REF_GET_CHARS:
8428 index = decode_long (p, &p, end);
8429 length = decode_long (p, &p, end);
8430 if (index > mono_string_length (str) - length)
8431 return ERR_INVALID_ARGUMENT;
8432 c = mono_string_chars (str) + index;
8433 for (i = 0; i < length; ++i)
8434 buffer_add_short (buf, c [i]);
8437 return ERR_NOT_IMPLEMENTED;
8444 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8453 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
8454 objid = decode_objid (p, &p, end);
8455 err = get_object (objid, &obj);
8457 buffer_add_int (buf, 1);
8459 buffer_add_int (buf, 0);
8463 objid = decode_objid (p, &p, end);
8464 err = get_object (objid, &obj);
8469 case CMD_OBJECT_REF_GET_TYPE:
8470 /* This handles transparent proxies too */
8471 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8473 case CMD_OBJECT_REF_GET_VALUES:
8474 len = decode_int (p, &p, end);
8476 for (i = 0; i < len; ++i) {
8477 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
8481 /* Check that the field belongs to the object */
8483 for (k = obj->vtable->klass; k; k = k->parent) {
8484 if (k == f->parent) {
8490 return ERR_INVALID_FIELDID;
8492 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8496 if (mono_class_field_is_special_static (f))
8497 return ERR_INVALID_FIELDID;
8499 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8500 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8501 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8502 mono_field_static_get_value (vtable, f, val);
8503 buffer_add_value (buf, f->type, val, obj->vtable->domain);
8506 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
8510 case CMD_OBJECT_REF_SET_VALUES:
8511 len = decode_int (p, &p, end);
8513 for (i = 0; i < len; ++i) {
8514 f = decode_fieldid (p, &p, end, NULL, &err);
8518 /* Check that the field belongs to the object */
8520 for (k = obj->vtable->klass; k; k = k->parent) {
8521 if (k == f->parent) {
8527 return ERR_INVALID_FIELDID;
8529 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
8533 if (mono_class_field_is_special_static (f))
8534 return ERR_INVALID_FIELDID;
8536 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
8537 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
8539 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8540 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
8545 mono_field_static_set_value (vtable, f, val);
8548 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
8554 case CMD_OBJECT_REF_GET_ADDRESS:
8555 buffer_add_long (buf, (gssize)obj);
8557 case CMD_OBJECT_REF_GET_DOMAIN:
8558 buffer_add_domainid (buf, obj->vtable->domain);
8560 case CMD_OBJECT_REF_GET_INFO:
8561 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
8562 buffer_add_domainid (buf, obj->vtable->domain);
8565 return ERR_NOT_IMPLEMENTED;
8572 command_set_to_string (CommandSet command_set)
8574 switch (command_set) {
8577 case CMD_SET_OBJECT_REF:
8578 return "OBJECT_REF";
8579 case CMD_SET_STRING_REF:
8580 return "STRING_REF";
8581 case CMD_SET_THREAD:
8583 case CMD_SET_ARRAY_REF:
8585 case CMD_SET_EVENT_REQUEST:
8586 return "EVENT_REQUEST";
8587 case CMD_SET_STACK_FRAME:
8588 return "STACK_FRAME";
8589 case CMD_SET_APPDOMAIN:
8591 case CMD_SET_ASSEMBLY:
8593 case CMD_SET_METHOD:
8597 case CMD_SET_MODULE:
8607 cmd_to_string (CommandSet set, int command)
8612 case CMD_VM_VERSION:
8614 case CMD_VM_ALL_THREADS:
8615 return "ALL_THREADS";
8616 case CMD_VM_SUSPEND:
8622 case CMD_VM_DISPOSE:
8624 case CMD_VM_INVOKE_METHOD:
8625 return "INVOKE_METHOD";
8626 case CMD_VM_SET_PROTOCOL_VERSION:
8627 return "SET_PROTOCOL_VERSION";
8628 case CMD_VM_ABORT_INVOKE:
8629 return "ABORT_INVOKE";
8630 case CMD_VM_SET_KEEPALIVE:
8631 return "SET_KEEPALIVE";
8644 wait_for_attach (void)
8646 #ifndef DISABLE_SOCKET_TRANSPORT
8647 if (listen_fd == -1) {
8648 DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
8652 /* Block and wait for client connection */
8653 conn_fd = socket_transport_accept (listen_fd);
8654 DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
8655 if (conn_fd == -1) {
8656 DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
8660 g_assert_not_reached ();
8664 disconnected = !transport_handshake ();
8666 DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
8676 * This thread handles communication with the debugger client using a JDWP
8679 static guint32 WINAPI
8680 debugger_thread (void *arg)
8682 int res, len, id, flags, command_set = 0, command = 0;
8683 guint8 header [HEADER_LENGTH];
8684 guint8 *data, *p, *end;
8688 gboolean attach_failed = FALSE;
8690 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
8692 debugger_thread_id = GetCurrentThreadId ();
8694 mono_jit_thread_attach (mono_get_root_domain ());
8696 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
8698 mono_set_is_debugger_attached (TRUE);
8700 if (agent_config.defer) {
8701 if (!wait_for_attach ()) {
8702 DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
8703 attach_failed = TRUE; // Don't abort process when we can't listen
8705 /* Send start event to client */
8706 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
8710 while (!attach_failed) {
8711 res = transport_recv (header, HEADER_LENGTH);
8713 /* This will break if the socket is closed during shutdown too */
8714 if (res != HEADER_LENGTH) {
8715 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH));
8720 end = header + HEADER_LENGTH;
8722 len = decode_int (p, &p, end);
8723 id = decode_int (p, &p, end);
8724 flags = decode_byte (p, &p, end);
8725 command_set = decode_byte (p, &p, end);
8726 command = decode_byte (p, &p, end);
8728 g_assert (flags == 0);
8731 const char *cmd_str;
8734 cmd_str = cmd_to_string (command_set, command);
8736 sprintf (cmd_num, "%d", command);
8740 DEBUG (1, fprintf (log_file, "[dbg] Received command %s(%s), id=%d.\n", command_set_to_string (command_set), cmd_str, id));
8743 data = g_malloc (len - HEADER_LENGTH);
8744 if (len - HEADER_LENGTH > 0)
8746 res = transport_recv (data, len - HEADER_LENGTH);
8747 if (res != len - HEADER_LENGTH) {
8748 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH));
8754 end = data + (len - HEADER_LENGTH);
8756 buffer_init (&buf, 128);
8761 /* Process the request */
8762 switch (command_set) {
8764 err = vm_commands (command, id, p, end, &buf);
8765 if (!err && command == CMD_VM_INVOKE_METHOD)
8766 /* Sent after the invoke is complete */
8769 case CMD_SET_EVENT_REQUEST:
8770 err = event_commands (command, p, end, &buf);
8772 case CMD_SET_APPDOMAIN:
8773 err = domain_commands (command, p, end, &buf);
8775 case CMD_SET_ASSEMBLY:
8776 err = assembly_commands (command, p, end, &buf);
8778 case CMD_SET_MODULE:
8779 err = module_commands (command, p, end, &buf);
8782 err = type_commands (command, p, end, &buf);
8784 case CMD_SET_METHOD:
8785 err = method_commands (command, p, end, &buf);
8787 case CMD_SET_THREAD:
8788 err = thread_commands (command, p, end, &buf);
8790 case CMD_SET_STACK_FRAME:
8791 err = frame_commands (command, p, end, &buf);
8793 case CMD_SET_ARRAY_REF:
8794 err = array_commands (command, p, end, &buf);
8796 case CMD_SET_STRING_REF:
8797 err = string_commands (command, p, end, &buf);
8799 case CMD_SET_OBJECT_REF:
8800 err = object_commands (command, p, end, &buf);
8803 err = ERR_NOT_IMPLEMENTED;
8807 send_reply_packet (id, err, &buf);
8812 if (command_set == CMD_SET_VM && command == CMD_VM_DISPOSE)
8816 mono_set_is_debugger_attached (FALSE);
8818 mono_mutex_lock (&debugger_thread_exited_mutex);
8819 debugger_thread_exited = TRUE;
8820 mono_cond_signal (&debugger_thread_exited_cond);
8821 mono_mutex_unlock (&debugger_thread_exited_mutex);
8823 DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
8825 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
8826 DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
8827 start_debugger_thread ();
8833 #else /* DISABLE_DEBUGGER_AGENT */
8836 mono_debugger_agent_parse_options (char *options)
8838 g_error ("This runtime is configured with the debugger agent disabled.");
8842 mono_debugger_agent_init (void)
8847 mono_debugger_agent_breakpoint_hit (void *sigctx)
8852 mono_debugger_agent_single_step_event (void *sigctx)
8857 mono_debugger_agent_free_domain_info (MonoDomain *domain)
8862 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
8868 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
8869 MonoContext *catch_ctx)
8874 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
8879 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
8884 mono_debugger_agent_user_break (void)
8890 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
8895 mono_debugger_agent_debug_log_is_enabled (void)