2009-11-13 Zoltan Varga <vargaz@gmail.com>
[mono-project.git] / mono / mini / debugger-agent.c
blobc70464da68c42f0d277418ec35dd4cf5dd391fdf
1 /*
2 * debugger-agent.c: Debugger back-end module
4 * Author:
5 * Zoltan Varga (vargaz@gmail.com)
7 * (C) 2009 Novell, Inc.
8 */
10 #include <config.h>
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #ifdef HAVE_SYS_TYPES_H
15 #include <sys/types.h>
16 #endif
17 #ifdef HAVE_SYS_SOCKET_H
18 #include <sys/socket.h>
19 #endif
20 #ifdef HAVE_NETINET_TCP_H
21 #include <netinet/tcp.h>
22 #endif
23 #ifdef HAVE_NETINET_IN_H
24 #include <netinet/in.h>
25 #endif
26 #ifdef HAVE_NETDB_H
27 #include <netdb.h>
28 #endif
29 #ifdef HAVE_UNISTD_H
30 #include <unistd.h>
31 #endif
32 #include <errno.h>
33 #include <glib.h>
35 #ifdef HAVE_PTHREAD_H
36 #include <pthread.h>
37 #endif
39 #ifdef HAVE_UCONTEXT_H
40 #include <ucontext.h>
41 #endif
43 #ifdef PLATFORM_ANDROID
44 #include <linux/in.h>
45 #include <linux/tcp.h>
46 #include <sys/endian.h>
47 #endif
49 #include <mono/metadata/mono-debug.h>
50 #include <mono/metadata/mono-debug-debugger.h>
51 #include <mono/metadata/debug-mono-symfile.h>
52 #include <mono/metadata/gc-internal.h>
53 #include <mono/metadata/threads-types.h>
54 #include <mono/utils/mono-semaphore.h>
55 #include "debugger-agent.h"
56 #include "mini.h"
58 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
59 #define DISABLE_DEBUGGER_AGENT 1
60 #endif
62 #ifndef DISABLE_DEBUGGER_AGENT
63 #include <mono/io-layer/mono-mutex.h>
65 /* Definitions to make backporting to 2.6 easier */
66 #define MonoInternalThread MonoThread
67 #define mono_thread_internal_current mono_thread_current
68 #define THREAD_TO_INTERNAL(thread) (thread)
70 typedef struct {
71 gboolean enabled;
72 char *transport;
73 char *address;
74 int log_level;
75 char *log_file;
76 gboolean suspend;
77 gboolean server;
78 gboolean onuncaught;
79 GSList *onthrow;
80 int timeout;
81 char *launch;
82 } AgentConfig;
84 typedef struct
86 int id;
87 guint32 il_offset;
88 MonoDomain *domain;
89 MonoMethod *method;
90 MonoContext ctx;
91 MonoDebugMethodJitInfo *jit;
92 int flags;
93 } StackFrame;
95 typedef struct
97 int id;
98 guint8 *p;
99 guint8 *endp;
100 /* This is the context which needs to be restored after the invoke */
101 MonoContext ctx;
102 gboolean has_ctx;
103 } InvokeData;
105 typedef struct {
106 MonoContext ctx;
107 MonoLMF *lmf;
108 MonoDomain *domain;
109 gboolean has_context;
110 gpointer resume_event;
111 /* This is computed on demand when it is requested using the wire protocol */
112 /* It is freed up when the thread is resumed */
113 int frame_count;
114 StackFrame **frames;
116 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
117 * re-compute it.
119 gboolean frames_up_to_date;
121 * Points to data about a pending invoke which needs to be executed after the thread
122 * resumes.
124 InvokeData *invoke;
126 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
127 * native code.
129 gboolean suspended;
130 /* Used to pass the context to the breakpoint/single step handler */
131 MonoContext handler_ctx;
132 /* Whenever thread_stop () was called for this thread */
133 gboolean terminated;
135 /* Number of thread interruptions not yet processed */
136 gint32 interrupt_count;
137 } DebuggerTlsData;
140 * Wire Protocol definitions
143 #define HEADER_LENGTH 11
145 #define MAJOR_VERSION 0
146 #define MINOR_VERSION 2
148 typedef enum {
149 CMD_SET_VM = 1,
150 CMD_SET_OBJECT_REF = 9,
151 CMD_SET_STRING_REF = 10,
152 CMD_SET_THREAD = 11,
153 CMD_SET_ARRAY_REF = 13,
154 CMD_SET_EVENT_REQUEST = 15,
155 CMD_SET_STACK_FRAME = 16,
156 CMD_SET_APPDOMAIN = 20,
157 CMD_SET_ASSEMBLY = 21,
158 CMD_SET_METHOD = 22,
159 CMD_SET_TYPE = 23,
160 CMD_SET_MODULE = 24,
161 CMD_SET_EVENT = 64
162 } CommandSet;
164 typedef enum {
165 EVENT_KIND_VM_START = 0,
166 EVENT_KIND_VM_DEATH = 1,
167 EVENT_KIND_THREAD_START = 2,
168 EVENT_KIND_THREAD_DEATH = 3,
169 EVENT_KIND_APPDOMAIN_CREATE = 4,
170 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
171 EVENT_KIND_METHOD_ENTRY = 6,
172 EVENT_KIND_METHOD_EXIT = 7,
173 EVENT_KIND_ASSEMBLY_LOAD = 8,
174 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
175 EVENT_KIND_BREAKPOINT = 10,
176 EVENT_KIND_STEP = 11,
177 EVENT_KIND_TYPE_LOAD = 12,
178 EVENT_KIND_EXCEPTION = 13
179 } EventKind;
181 typedef enum {
182 SUSPEND_POLICY_NONE = 0,
183 SUSPEND_POLICY_EVENT_THREAD = 1,
184 SUSPEND_POLICY_ALL = 2
185 } SuspendPolicy;
187 typedef enum {
188 ERR_NONE = 0,
189 ERR_INVALID_OBJECT = 20,
190 ERR_INVALID_FIELDID = 25,
191 ERR_INVALID_FRAMEID = 30,
192 ERR_NOT_IMPLEMENTED = 100,
193 ERR_NOT_SUSPENDED = 101,
194 ERR_INVALID_ARGUMENT = 102,
195 ERR_UNLOADED = 103
196 } ErrorCode;
198 typedef enum {
199 MOD_KIND_COUNT = 1,
200 MOD_KIND_THREAD_ONLY = 3,
201 MOD_KIND_LOCATION_ONLY = 7,
202 MOD_KIND_EXCEPTION_ONLY = 8,
203 MOD_KIND_STEP = 10,
204 MOD_KIND_ASSEMBLY_ONLY = 11
205 } ModifierKind;
207 typedef enum {
208 STEP_DEPTH_INTO = 0,
209 STEP_DEPTH_OVER = 1,
210 STEP_DEPTH_OUT = 2
211 } StepDepth;
213 typedef enum {
214 STEP_SIZE_MIN = 0,
215 STEP_SIZE_LINE = 1
216 } StepSize;
218 typedef enum {
219 TOKEN_TYPE_STRING = 0,
220 TOKEN_TYPE_TYPE = 1,
221 TOKEN_TYPE_FIELD = 2,
222 TOKEN_TYPE_METHOD = 3,
223 TOKEN_TYPE_UNKNOWN = 4
224 } DebuggerTokenType;
226 typedef enum {
227 VALUE_TYPE_ID_NULL = 0xf0,
228 VALUE_TYPE_ID_TYPE = 0xf1
229 } ValueTypeId;
231 typedef enum {
232 FRAME_FLAG_DEBUGGER_INVOKE = 1
233 } StackFrameFlags;
235 typedef enum {
236 CMD_VM_VERSION = 1,
237 CMD_VM_ALL_THREADS = 2,
238 CMD_VM_SUSPEND = 3,
239 CMD_VM_RESUME = 4,
240 CMD_VM_EXIT = 5,
241 CMD_VM_DISPOSE = 6,
242 CMD_VM_INVOKE_METHOD = 7
243 } CmdVM;
245 typedef enum {
246 CMD_THREAD_GET_FRAME_INFO = 1,
247 CMD_THREAD_GET_NAME = 2,
248 CMD_THREAD_GET_STATE = 3,
249 CMD_THREAD_GET_INFO = 4
250 } CmdThread;
252 typedef enum {
253 CMD_EVENT_REQUEST_SET = 1,
254 CMD_EVENT_REQUEST_CLEAR = 2,
255 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
256 } CmdEvent;
258 typedef enum {
259 CMD_COMPOSITE = 100
260 } CmdComposite;
262 typedef enum {
263 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
264 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
265 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
266 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
267 CMD_APPDOMAIN_CREATE_STRING = 5,
268 CMD_APPDOMAIN_GET_CORLIB = 6
269 } CmdAppDomain;
271 typedef enum {
272 CMD_ASSEMBLY_GET_LOCATION = 1,
273 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
274 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
275 CMD_ASSEMBLY_GET_OBJECT = 4,
276 CMD_ASSEMBLY_GET_TYPE = 5,
277 } CmdAssembly;
279 typedef enum {
280 CMD_MODULE_GET_INFO = 1,
281 } CmdModule;
283 typedef enum {
284 CMD_METHOD_GET_NAME = 1,
285 CMD_METHOD_GET_DECLARING_TYPE = 2,
286 CMD_METHOD_GET_DEBUG_INFO = 3,
287 CMD_METHOD_GET_PARAM_INFO = 4,
288 CMD_METHOD_GET_LOCALS_INFO = 5,
289 CMD_METHOD_GET_INFO = 6,
290 CMD_METHOD_GET_BODY = 7,
291 CMD_METHOD_RESOLVE_TOKEN = 8,
292 } CmdMethod;
294 typedef enum {
295 CMD_TYPE_GET_INFO = 1,
296 CMD_TYPE_GET_METHODS = 2,
297 CMD_TYPE_GET_FIELDS = 3,
298 CMD_TYPE_GET_VALUES = 4,
299 CMD_TYPE_GET_OBJECT = 5,
300 CMD_TYPE_GET_SOURCE_FILES = 6,
301 CMD_TYPE_SET_VALUES = 7,
302 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
303 CMD_TYPE_GET_PROPERTIES = 9,
304 CMD_TYPE_GET_CATTRS = 10,
305 CMD_TYPE_GET_FIELD_CATTRS = 11,
306 CMD_TYPE_GET_PROPERTY_CATTRS = 12
307 } CmdType;
309 typedef enum {
310 CMD_STACK_FRAME_GET_VALUES = 1,
311 CMD_STACK_FRAME_GET_THIS = 2,
312 CMD_STACK_FRAME_SET_VALUES = 3
313 } CmdStackFrame;
315 typedef enum {
316 CMD_ARRAY_REF_GET_LENGTH = 1,
317 CMD_ARRAY_REF_GET_VALUES = 2,
318 CMD_ARRAY_REF_SET_VALUES = 3,
319 } CmdArray;
321 typedef enum {
322 CMD_STRING_REF_GET_VALUE = 1,
323 } CmdString;
325 typedef enum {
326 CMD_OBJECT_REF_GET_TYPE = 1,
327 CMD_OBJECT_REF_GET_VALUES = 2,
328 CMD_OBJECT_REF_IS_COLLECTED = 3,
329 CMD_OBJECT_REF_GET_ADDRESS = 4,
330 CMD_OBJECT_REF_GET_DOMAIN = 5,
331 CMD_OBJECT_REF_SET_VALUES = 6
332 } CmdObject;
334 typedef struct {
335 ModifierKind kind;
336 union {
337 int count; /* For kind == MOD_KIND_COUNT */
338 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
339 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
340 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
341 } data;
342 } Modifier;
344 typedef struct{
345 int id;
346 int event_kind;
347 int suspend_policy;
348 int nmodifiers;
349 gpointer info;
350 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
351 } EventRequest;
354 * Describes a single step request.
356 typedef struct {
357 EventRequest *req;
358 MonoInternalThread *thread;
359 StepDepth depth;
360 StepSize size;
361 gpointer last_sp;
362 gpointer start_sp;
363 MonoMethod *last_method;
364 int last_line;
365 } MonoSingleStepReq;
367 /* Dummy structure used for the profiler callbacks */
368 typedef struct {
369 void* dummy;
370 } DebuggerProfiler;
372 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
375 * Globals
378 static AgentConfig agent_config;
381 * Whenever the agent is fully initialized.
382 * When using the onuncaught or onthrow options, only some parts of the agent are
383 * initialized on startup, and the full initialization which includes connection
384 * establishment and the startup of the agent thread is only done in response to
385 * an event.
387 static gint32 inited;
389 static int conn_fd;
391 static int packet_id = 0;
393 static int objref_id = 0;
395 static int event_request_id = 0;
397 static int frame_id = 0;
399 static GPtrArray *event_requests;
401 static guint32 debugger_tls_id;
403 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
405 /* Maps MonoInternalThread -> DebuggerTlsData */
406 static MonoGHashTable *thread_to_tls;
408 /* Maps tid -> MonoInternalThread */
409 static MonoGHashTable *tid_to_thread;
411 /* Maps tid -> MonoThread (not MonoInternalThread) */
412 static MonoGHashTable *tid_to_thread_obj;
414 static gsize debugger_thread_id;
416 static HANDLE debugger_thread_handle;
418 static int log_level;
420 static FILE *log_file;
422 /* Classes whose class load event has been sent */
423 static GHashTable *loaded_classes;
425 /* Assemblies whose assembly load event has no been sent yet */
426 static GPtrArray *pending_assembly_loads;
428 /* Whenever the debugger thread has exited */
429 static gboolean debugger_thread_exited;
431 /* Cond variable used to wait for debugger_thread_exited becoming true */
432 static mono_cond_t debugger_thread_exited_cond = MONO_COND_INITIALIZER;
434 /* Mutex for the cond var above */
435 static mono_mutex_t debugger_thread_exited_mutex = MONO_MUTEX_INITIALIZER;
437 static DebuggerProfiler debugger_profiler;
439 /* The single step request instance */
440 static MonoSingleStepReq *ss_req = NULL;
442 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
443 /* Number of single stepping operations in progress */
444 static int ss_count;
445 #endif
447 static void transport_connect (const char *host, int port);
449 static guint32 WINAPI debugger_thread (void *arg);
451 static void runtime_initialized (MonoProfiler *prof);
453 static void runtime_shutdown (MonoProfiler *prof);
455 static void thread_startup (MonoProfiler *prof, gsize tid);
457 static void thread_end (MonoProfiler *prof, gsize tid);
459 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
461 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
463 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
465 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
467 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
469 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
471 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
473 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
475 static void start_single_stepping (void);
477 static void stop_single_stepping (void);
479 static void suspend_current (void);
481 /* Submodule init/cleanup */
482 static void breakpoints_init (void);
483 static void breakpoints_cleanup (void);
485 static void objrefs_init (void);
486 static void objrefs_cleanup (void);
488 static void ids_init (void);
489 static void ids_cleanup (void);
491 static void suspend_init (void);
493 static ErrorCode ss_start (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
494 static void ss_stop (EventRequest *req);
496 static void start_debugger_thread (void);
498 static void finish_agent_init (gboolean on_startup);
500 static int
501 parse_address (char *address, char **host, int *port)
503 char *pos = strchr (address, ':');
505 if (pos == NULL || pos == address)
506 return 1;
508 *host = g_malloc (pos - address + 1);
509 strncpy (*host, address, pos - address);
510 (*host) [pos - address] = '\0';
512 *port = atoi (pos + 1);
514 return 0;
517 static void
518 print_usage (void)
520 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
521 fprintf (stderr, "Available options:\n");
522 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
523 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
524 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
525 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
526 fprintf (stderr, " suspend=y/n\t\t\tWhenever to suspend after startup.\n");
527 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
528 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
531 static gboolean
532 parse_flag (const char *option, char *flag)
534 if (!strcmp (flag, "y"))
535 return TRUE;
536 else if (!strcmp (flag, "n"))
537 return FALSE;
538 else {
539 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
540 exit (1);
541 return FALSE;
545 void
546 mono_debugger_agent_parse_options (char *options)
548 char **args, **ptr;
549 char *host;
550 int port;
552 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
553 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
554 exit (1);
555 #endif
557 agent_config.enabled = TRUE;
558 agent_config.suspend = TRUE;
559 agent_config.server = FALSE;
561 args = g_strsplit (options, ",", -1);
562 for (ptr = args; ptr && *ptr; ptr ++) {
563 char *arg = *ptr;
565 if (strncmp (arg, "transport=", 10) == 0) {
566 agent_config.transport = g_strdup (arg + 10);
567 } else if (strncmp (arg, "address=", 8) == 0) {
568 agent_config.address = g_strdup (arg + 8);
569 } else if (strncmp (arg, "loglevel=", 9) == 0) {
570 agent_config.log_level = atoi (arg + 9);
571 } else if (strncmp (arg, "logfile=", 8) == 0) {
572 agent_config.log_file = g_strdup (arg + 8);
573 } else if (strncmp (arg, "suspend=", 8) == 0) {
574 agent_config.suspend = parse_flag ("suspend", arg + 8);
575 } else if (strncmp (arg, "server=", 7) == 0) {
576 agent_config.server = parse_flag ("server", arg + 7);
577 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
578 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
579 } else if (strncmp (arg, "onthrow=", 8) == 0) {
580 /* We support multiple onthrow= options */
581 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
582 } else if (strncmp (arg, "help", 4) == 0) {
583 print_usage ();
584 exit (0);
585 } else if (strncmp (arg, "timeout=", 8) == 0) {
586 agent_config.timeout = atoi (arg + 8);
587 } else if (strncmp (arg, "launch=", 7) == 0) {
588 agent_config.launch = g_strdup (arg + 7);
589 } else {
590 print_usage ();
591 exit (1);
595 if (agent_config.transport == NULL) {
596 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
597 exit (1);
599 if (strcmp (agent_config.transport, "dt_socket") != 0) {
600 fprintf (stderr, "debugger-agent: The only supported value for the 'transport' option is 'dt_socket'.\n");
601 exit (1);
604 if (agent_config.address == NULL && !agent_config.server) {
605 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
606 exit (1);
609 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
610 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
611 exit (1);
615 void
616 mono_debugger_agent_init (void)
618 if (!agent_config.enabled)
619 return;
621 /* Need to know whenever a thread has acquired the loader mutex */
622 mono_loader_lock_track_ownership (TRUE);
624 event_requests = g_ptr_array_new ();
626 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
627 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
628 mono_profiler_install_runtime_initialized (runtime_initialized);
629 mono_profiler_install_appdomain (NULL, appdomain_load, appdomain_unload, NULL);
630 mono_profiler_install_thread (thread_startup, thread_end);
631 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
632 mono_profiler_install_jit_end (jit_end);
633 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
635 debugger_tls_id = TlsAlloc ();
637 thread_to_tls = mono_g_hash_table_new (NULL, NULL);
638 MONO_GC_REGISTER_ROOT (thread_to_tls);
640 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
641 MONO_GC_REGISTER_ROOT (tid_to_thread);
643 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
644 MONO_GC_REGISTER_ROOT (tid_to_thread_obj);
646 loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
647 pending_assembly_loads = g_ptr_array_new ();
649 log_level = agent_config.log_level;
651 if (agent_config.log_file) {
652 log_file = fopen (agent_config.log_file, "w+");
653 if (!log_file) {
654 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
655 exit (1);
657 } else {
658 log_file = stdout;
661 ids_init ();
662 objrefs_init ();
663 breakpoints_init ();
664 suspend_init ();
666 mini_get_debug_options ()->gen_seq_points = TRUE;
668 * This is needed because currently we don't handle liveness info.
670 mini_get_debug_options ()->mdb_optimizations = TRUE;
672 /* This is needed because we can't set local variables in registers yet */
673 mono_disable_optimizations (MONO_OPT_LINEARS);
675 if (!agent_config.onuncaught && !agent_config.onthrow)
676 finish_agent_init (TRUE);
680 * finish_agent_init:
682 * Finish the initialization of the agent. This involves connecting the transport
683 * and starting the agent thread. This is either done at startup, or
684 * in response to some event like an unhandled exception.
686 static void
687 finish_agent_init (gboolean on_startup)
689 char *host;
690 int port;
691 int res;
693 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
694 return;
696 if (agent_config.launch) {
697 char *argv [16];
699 // FIXME: Generated address
700 // FIXME: Races with transport_connect ()
702 argv [0] = agent_config.launch;
703 argv [1] = agent_config.transport;
704 argv [2] = agent_config.address;
705 argv [3] = NULL;
707 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
708 if (!res) {
709 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
710 exit (1);
714 if (agent_config.address) {
715 res = parse_address (agent_config.address, &host, &port);
716 g_assert (res == 0);
717 } else {
718 host = NULL;
719 port = 0;
722 transport_connect (host, port);
724 if (!on_startup) {
725 /* Do some which is usually done after sending the VMStart () event */
726 vm_start_event_sent = TRUE;
727 start_debugger_thread ();
731 static void
732 mono_debugger_agent_cleanup (void)
734 if (!inited)
735 return;
737 /* This will interrupt the agent thread */
738 /* Close the read part only so it can still send back replies */
739 #ifdef PLATFORM_WIN32
740 shutdown (conn_fd, SD_RECEIVE);
741 #else
742 shutdown (conn_fd, SHUT_RD);
743 #endif
746 * Wait for the thread to exit.
748 * If we continue with the shutdown without waiting for it, then the client might
749 * not receive an answer to its last command like a resume.
750 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
751 * use pthreads.
753 //WaitForSingleObject (debugger_thread_handle, INFINITE);
754 if (GetCurrentThreadId () != debugger_thread_id) {
755 mono_mutex_lock (&debugger_thread_exited_mutex);
756 if (!debugger_thread_exited)
757 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
758 mono_mutex_unlock (&debugger_thread_exited_mutex);
761 breakpoints_cleanup ();
762 objrefs_cleanup ();
763 ids_cleanup ();
767 * transport_connect:
769 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
771 static void
772 transport_connect (const char *host, int port)
774 struct addrinfo hints;
775 struct addrinfo *result, *rp;
776 int sfd, s, res;
777 char port_string [128];
778 char handshake_msg [128];
779 guint8 buf [128];
781 conn_fd = -1;
783 if (host) {
784 sprintf (port_string, "%d", port);
786 /* Obtain address(es) matching host/port */
788 memset (&hints, 0, sizeof (struct addrinfo));
789 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
790 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
791 hints.ai_flags = 0;
792 hints.ai_protocol = 0; /* Any protocol */
794 s = getaddrinfo (host, port_string, &hints, &result);
795 if (s != 0) {
796 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d: %s\n", host, port, gai_strerror (s));
797 exit (1);
801 if (agent_config.server) {
802 /* Wait for a connection */
803 if (!host) {
804 struct sockaddr_in addr;
805 socklen_t addrlen;
807 /* No address, generate one */
808 sfd = socket (AF_INET, SOCK_STREAM, 0);
809 g_assert (sfd);
811 /* This will bind the socket to a random port */
812 res = listen (sfd, 16);
813 if (res == -1) {
814 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (errno));
815 exit (1);
818 addrlen = sizeof (addr);
819 memset (&addr, 0, sizeof (addr));
820 res = getsockname (sfd, &addr, &addrlen);
821 g_assert (res == 0);
823 host = "127.0.0.1";
824 port = ntohs (addr.sin_port);
826 /* Emit the address to stdout */
827 /* FIXME: Should print another interface, not localhost */
828 printf ("%s:%d\n", host, port);
829 } else {
830 /* Listen on the provided address */
831 for (rp = result; rp != NULL; rp = rp->ai_next) {
832 sfd = socket (rp->ai_family, rp->ai_socktype,
833 rp->ai_protocol);
834 if (sfd == -1)
835 continue;
837 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
838 if (res == -1)
839 continue;
841 res = listen (sfd, 16);
842 if (res == -1)
843 continue;
844 break;
847 freeaddrinfo (result);
850 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
852 if (agent_config.timeout) {
853 fd_set readfds;
854 struct timeval tv;
856 tv.tv_sec = 0;
857 tv.tv_usec = agent_config.timeout * 1000;
858 FD_ZERO (&readfds);
859 FD_SET (sfd, &readfds);
860 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
861 if (res == 0) {
862 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
863 exit (1);
867 conn_fd = accept (sfd, NULL, NULL);
868 if (conn_fd == -1) {
869 fprintf (stderr, "debugger-agent: Unable to listen on %s:%d\n", host, port);
870 exit (1);
873 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
874 } else {
875 /* Connect to the specified address */
876 /* FIXME: Respect the timeout */
877 for (rp = result; rp != NULL; rp = rp->ai_next) {
878 sfd = socket (rp->ai_family, rp->ai_socktype,
879 rp->ai_protocol);
880 if (sfd == -1)
881 continue;
883 if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
884 break; /* Success */
886 close (sfd);
889 conn_fd = sfd;
891 freeaddrinfo (result);
893 if (rp == 0) {
894 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
895 exit (1);
899 /* Write handshake message */
900 sprintf (handshake_msg, "DWP-Handshake");
901 res = write (conn_fd, handshake_msg, strlen (handshake_msg));
902 g_assert (res != -1);
904 /* Read answer */
905 res = read (conn_fd, buf, strlen (handshake_msg));
906 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg) != 0))) {
907 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
908 exit (1);
912 * Set TCP_NODELAY on the socket so the client receives events/command
913 * results immediately.
916 int flag = 1;
917 int result = setsockopt(conn_fd,
918 IPPROTO_TCP,
919 TCP_NODELAY,
920 (char *) &flag,
921 sizeof(int));
922 g_assert (result >= 0);
926 static gboolean
927 transport_send (guint8 *data, int len)
929 int res;
931 res = write (conn_fd, data, len);
932 if (res != len)
933 return FALSE;
934 else
935 return TRUE;
938 static void
939 start_debugger_thread (void)
941 gsize tid;
943 debugger_thread_handle = mono_create_thread (NULL, 0, debugger_thread, NULL, 0, &tid);
944 g_assert (debugger_thread_handle);
948 * Functions to decode protocol data
951 static inline int
952 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
954 *endbuf = buf + 1;
955 g_assert (*endbuf <= limit);
956 return buf [0];
959 static inline int
960 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
962 *endbuf = buf + 4;
963 g_assert (*endbuf <= limit);
965 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
968 static inline gint64
969 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
971 guint32 high = decode_int (buf, &buf, limit);
972 guint32 low = decode_int (buf, &buf, limit);
974 *endbuf = buf;
976 return ((((guint64)high) << 32) | ((guint64)low));
979 static inline int
980 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
982 return decode_int (buf, endbuf, limit);
985 static inline char*
986 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
988 int len = decode_int (buf, &buf, limit);
989 char *s;
991 s = g_malloc (len + 1);
992 g_assert (s);
994 memcpy (s, buf, len);
995 s [len] = '\0';
996 buf += len;
997 *endbuf = buf;
999 return s;
1003 * Functions to encode protocol data
1006 typedef struct {
1007 guint8 *buf, *p, *end;
1008 } Buffer;
1010 static inline void
1011 buffer_init (Buffer *buf, int size)
1013 buf->buf = g_malloc (size);
1014 buf->p = buf->buf;
1015 buf->end = buf->buf + size;
1018 static inline void
1019 buffer_make_room (Buffer *buf, int size)
1021 if (buf->end - buf->p < size) {
1022 int new_size = buf->end - buf->buf + size + 32;
1023 guint8 *p = g_realloc (buf->buf, new_size);
1024 size = buf->p - buf->buf;
1025 buf->buf = p;
1026 buf->p = p + size;
1027 buf->end = buf->buf + new_size;
1031 static inline void
1032 buffer_add_byte (Buffer *buf, guint8 val)
1034 buffer_make_room (buf, 1);
1035 buf->p [0] = val;
1036 buf->p++;
1039 static inline void
1040 buffer_add_int (Buffer *buf, guint32 val)
1042 buffer_make_room (buf, 4);
1043 buf->p [0] = (val >> 24) & 0xff;
1044 buf->p [1] = (val >> 16) & 0xff;
1045 buf->p [2] = (val >> 8) & 0xff;
1046 buf->p [3] = (val >> 0) & 0xff;
1047 buf->p += 4;
1050 static inline void
1051 buffer_add_long (Buffer *buf, guint64 l)
1053 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1054 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1057 static inline void
1058 buffer_add_id (Buffer *buf, int id)
1060 buffer_add_int (buf, (guint64)id);
1063 static inline void
1064 buffer_add_data (Buffer *buf, guint8 *data, int len)
1066 buffer_make_room (buf, len);
1067 memcpy (buf->p, data, len);
1068 buf->p += len;
1071 static inline void
1072 buffer_add_string (Buffer *buf, const char *str)
1074 int len;
1076 if (str == NULL) {
1077 buffer_add_int (buf, 0);
1078 } else {
1079 len = strlen (str);
1080 buffer_add_int (buf, len);
1081 buffer_add_data (buf, (guint8*)str, len);
1085 static inline void
1086 buffer_free (Buffer *buf)
1088 g_free (buf->buf);
1091 static gboolean
1092 send_packet (int command_set, int command, Buffer *data)
1094 Buffer buf;
1095 int len, id;
1096 gboolean res;
1098 id = InterlockedIncrement (&packet_id);
1100 len = data->p - data->buf + 11;
1101 buffer_init (&buf, len);
1102 buffer_add_int (&buf, len);
1103 buffer_add_int (&buf, id);
1104 buffer_add_byte (&buf, 0); /* flags */
1105 buffer_add_byte (&buf, command_set);
1106 buffer_add_byte (&buf, command);
1107 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1109 res = transport_send (buf.buf, len);
1111 buffer_free (&buf);
1113 return res;
1116 static gboolean
1117 send_reply_packet (int id, int error, Buffer *data)
1119 Buffer buf;
1120 int len;
1121 gboolean res;
1123 len = data->p - data->buf + 11;
1124 buffer_init (&buf, len);
1125 buffer_add_int (&buf, len);
1126 buffer_add_int (&buf, id);
1127 buffer_add_byte (&buf, 0x80); /* flags */
1128 buffer_add_byte (&buf, (error >> 8) & 0xff);
1129 buffer_add_byte (&buf, error);
1130 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1132 res = transport_send (buf.buf, len);
1134 buffer_free (&buf);
1136 return res;
1140 * OBJECT IDS
1144 * Represents an object accessible by the debugger client.
1146 typedef struct {
1147 /* Unique id used in the wire protocol to refer to objects */
1148 int id;
1150 * A weakref gc handle pointing to the object. The gc handle is used to
1151 * detect if the object was garbage collected.
1153 guint32 handle;
1154 } ObjRef;
1156 /* Maps objid -> ObjRef */
1157 static GHashTable *objrefs;
1159 static void
1160 free_objref (gpointer value)
1162 ObjRef *o = value;
1164 mono_gchandle_free (o->handle);
1166 g_free (o);
1169 static void
1170 objrefs_init (void)
1172 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1175 static void
1176 objrefs_cleanup (void)
1178 g_hash_table_destroy (objrefs);
1179 objrefs = NULL;
1182 static GHashTable *obj_to_objref;
1185 * Return an ObjRef for OBJ.
1187 static ObjRef*
1188 get_objref (MonoObject *obj)
1190 ObjRef *ref;
1192 if (obj == NULL)
1193 return 0;
1195 #ifdef HAVE_SGEN_GC
1196 NOT_IMPLEMENTED;
1197 #endif
1199 /* Use a hash table with masked pointers to internalize object references */
1200 /* FIXME: This can grow indefinitely */
1201 mono_loader_lock ();
1203 if (!obj_to_objref)
1204 obj_to_objref = g_hash_table_new (NULL, NULL);
1206 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1207 /* ref might refer to a different object with the same addr which was GCd */
1208 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1209 mono_loader_unlock ();
1210 return ref;
1213 ref = g_new0 (ObjRef, 1);
1214 ref->id = InterlockedIncrement (&objref_id);
1215 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1217 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
1218 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
1220 mono_loader_unlock ();
1222 return ref;
1225 static inline int
1226 get_objid (MonoObject *obj)
1228 return get_objref (obj)->id;
1232 * Set OBJ to the object identified by OBJID.
1233 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
1234 * collected.
1236 static ErrorCode
1237 get_object_allow_null (int objid, MonoObject **obj)
1239 ObjRef *ref;
1241 if (objid == 0) {
1242 *obj = NULL;
1243 return 0;
1246 if (!objrefs)
1247 return ERR_INVALID_OBJECT;
1249 mono_loader_lock ();
1251 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
1253 if (ref) {
1254 *obj = mono_gchandle_get_target (ref->handle);
1255 mono_loader_unlock ();
1256 if (!(*obj))
1257 return ERR_INVALID_OBJECT;
1258 return 0;
1259 } else {
1260 mono_loader_unlock ();
1261 return ERR_INVALID_OBJECT;
1265 static ErrorCode
1266 get_object (int objid, MonoObject **obj)
1268 int err = get_object_allow_null (objid, obj);
1270 if (err)
1271 return err;
1272 if (!(*obj))
1273 return ERR_INVALID_OBJECT;
1274 return 0;
1277 static inline int
1278 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
1280 return decode_id (buf, endbuf, limit);
1283 static inline void
1284 buffer_add_objid (Buffer *buf, MonoObject *o)
1286 buffer_add_id (buf, get_objid (o));
1290 * IDS
1293 typedef enum {
1294 ID_ASSEMBLY = 0,
1295 ID_MODULE = 1,
1296 ID_TYPE = 2,
1297 ID_METHOD = 3,
1298 ID_FIELD = 4,
1299 ID_DOMAIN = 5,
1300 ID_PROPERTY = 6,
1301 ID_NUM
1302 } IdType;
1305 * Represents a runtime structure accessible to the debugger client
1307 typedef struct {
1308 /* Unique id used in the wire protocol */
1309 int id;
1310 /* Domain of the runtime structure, NULL if the domain was unloaded */
1311 MonoDomain *domain;
1312 union {
1313 gpointer val;
1314 MonoClass *klass;
1315 MonoMethod *method;
1316 MonoImage *image;
1317 MonoAssembly *assembly;
1318 MonoClassField *field;
1319 MonoDomain *domain;
1320 MonoProperty *property;
1321 } data;
1322 } Id;
1324 typedef struct {
1325 /* Maps runtime structure -> Id */
1326 GHashTable *val_to_id [ID_NUM];
1327 } AgentDomainInfo;
1329 /* Maps id -> Id */
1330 static GPtrArray *ids [ID_NUM];
1332 static void
1333 ids_init (void)
1335 int i;
1337 for (i = 0; i < ID_NUM; ++i)
1338 ids [i] = g_ptr_array_new ();
1341 static void
1342 ids_cleanup (void)
1344 int i, j;
1346 for (i = 0; i < ID_NUM; ++i) {
1347 if (ids [i]) {
1348 for (j = 0; j < ids [i]->len; ++j)
1349 g_free (g_ptr_array_index (ids [i], j));
1350 g_ptr_array_free (ids [i], TRUE);
1352 ids [i] = NULL;
1356 void
1357 mono_debugger_agent_free_domain_info (MonoDomain *domain)
1359 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
1360 int i, j;
1362 if (info) {
1363 for (i = 0; i < ID_NUM; ++i)
1364 if (info->val_to_id [i])
1365 g_hash_table_destroy (info->val_to_id [i]);
1366 g_free (info);
1369 domain_jit_info (domain)->agent_info = NULL;
1371 /* Clear ids referencing structures in the domain */
1372 for (i = 0; i < ID_NUM; ++i) {
1373 if (ids [i]) {
1374 for (j = 0; j < ids [i]->len; ++j) {
1375 Id *id = g_ptr_array_index (ids [i], j);
1376 if (id->domain == domain)
1377 id->domain = NULL;
1383 static int
1384 get_id (MonoDomain *domain, IdType type, gpointer val)
1386 Id *id;
1387 AgentDomainInfo *info;
1389 if (val == NULL)
1390 return 0;
1392 mono_loader_lock ();
1394 mono_domain_lock (domain);
1396 if (!domain_jit_info (domain)->agent_info)
1397 domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
1398 info = domain_jit_info (domain)->agent_info;
1399 if (info->val_to_id [type] == NULL)
1400 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
1402 id = g_hash_table_lookup (info->val_to_id [type], val);
1403 if (id) {
1404 mono_domain_unlock (domain);
1405 mono_loader_unlock ();
1406 return id->id;
1409 id = g_new0 (Id, 1);
1410 /* Reserve id 0 */
1411 id->id = ids [type]->len + 1;
1412 id->domain = domain;
1413 id->data.val = val;
1415 g_hash_table_insert (info->val_to_id [type], val, id);
1417 mono_domain_unlock (domain);
1419 g_ptr_array_add (ids [type], id);
1421 mono_loader_unlock ();
1423 return id->id;
1426 static inline gpointer
1427 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
1429 Id *res;
1431 int id = decode_id (buf, endbuf, limit);
1433 *err = 0;
1434 if (domain)
1435 *domain = NULL;
1437 if (id == 0)
1438 return NULL;
1440 // FIXME: error handling
1441 mono_loader_lock ();
1442 g_assert (id > 0 && id <= ids [type]->len);
1444 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
1445 mono_loader_unlock ();
1447 if (res->domain == NULL) {
1448 *err = ERR_UNLOADED;
1449 return NULL;
1452 if (domain)
1453 *domain = res->domain;
1455 return res->data.val;
1458 static inline void
1459 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
1461 buffer_add_id (buf, get_id (domain, type, val));
1464 static inline MonoClass*
1465 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1467 return decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
1470 static inline MonoAssembly*
1471 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1473 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
1476 static inline MonoImage*
1477 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1479 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
1482 static inline MonoMethod*
1483 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1485 return decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
1488 static inline MonoClassField*
1489 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1491 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
1494 static inline MonoDomain*
1495 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1497 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
1500 static inline MonoProperty*
1501 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
1503 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
1506 static inline void
1507 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
1509 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
1512 static inline void
1513 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
1515 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
1518 static inline void
1519 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
1521 buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
1524 static inline void
1525 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
1527 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
1530 static inline void
1531 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
1533 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
1536 static inline void
1537 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
1539 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
1542 static inline void
1543 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
1545 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
1548 static void invoke_method (void);
1551 * SUSPEND/RESUME
1554 static void
1555 save_thread_context (MonoContext *ctx)
1557 DebuggerTlsData *tls;
1559 tls = TlsGetValue (debugger_tls_id);
1560 g_assert (tls);
1562 if (ctx) {
1563 memcpy (&tls->ctx, ctx, sizeof (MonoContext));
1564 } else {
1565 #ifdef MONO_INIT_CONTEXT_FROM_CURRENT
1566 MONO_INIT_CONTEXT_FROM_CURRENT (&tls->ctx);
1567 #else
1568 MONO_INIT_CONTEXT_FROM_FUNC (&tls->ctx, save_thread_context);
1569 #endif
1572 tls->lmf = mono_get_lmf ();
1573 tls->domain = mono_domain_get ();
1574 tls->has_context = TRUE;
1577 /* The number of times the runtime is suspended */
1578 static gint32 suspend_count;
1580 /* Number of threads suspended */
1582 * If this is equal to the size of thread_to_tls, the runtime is considered
1583 * suspended.
1585 static gint32 threads_suspend_count;
1587 static mono_mutex_t suspend_mutex = MONO_MUTEX_INITIALIZER;
1589 /* Cond variable used to wait for suspend_count becoming 0 */
1590 static mono_cond_t suspend_cond = MONO_COND_INITIALIZER;
1592 /* Semaphore used to wait for a thread becoming suspended */
1593 static MonoSemType suspend_sem;
1595 static void
1596 suspend_init (void)
1598 MONO_SEM_INIT (&suspend_sem, 0);
1602 * mono_debugger_agent_thread_interrupt:
1604 * Called by the abort signal handler.
1606 gboolean
1607 mono_debugger_agent_thread_interrupt (MonoJitInfo *ji)
1609 DebuggerTlsData *tls;
1611 if (!inited)
1612 return FALSE;
1614 tls = TlsGetValue (debugger_tls_id);
1615 if (!tls)
1616 return FALSE;
1619 * We use interrupt_count to determine whenever this interrupt should be processed
1620 * by us or the normal interrupt processing code in the signal handler.
1621 * There is no race here with notify_thread (), since the signal is sent after
1622 * incrementing interrupt_count.
1624 if (tls->interrupt_count == 0)
1625 return FALSE;
1627 InterlockedDecrement (&tls->interrupt_count);
1629 // FIXME: Races when the thread leaves managed code before hitting a single step
1630 // event.
1632 if (ji) {
1633 /* Running managed code, will be suspended by the single step code */
1634 //printf ("S1: %p\n", GetCurrentThreadId ());
1635 return TRUE;
1636 } else {
1638 * Running native code, will be suspended when it returns to/enters
1639 * managed code. Treat it as already suspended.
1641 //printf ("S2: %p\n", GetCurrentThreadId ());
1642 if (!tls->suspended) {
1643 tls->suspended = TRUE;
1644 MONO_SEM_POST (&suspend_sem);
1646 return TRUE;
1651 * notify_thread:
1653 * Notify a thread that it needs to suspend.
1655 static void
1656 notify_thread (gpointer key, gpointer value, gpointer user_data)
1658 MonoInternalThread *thread = key;
1659 DebuggerTlsData *tls = value;
1660 gsize tid = thread->tid;
1662 if (GetCurrentThreadId () != tid) {
1663 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
1665 * Maybe we could use the normal interrupt infrastructure, but that does a lot
1666 * of things like breaking waits etc. which we don't want.
1668 InterlockedIncrement (&tls->interrupt_count);
1669 #ifdef PLATFORM_WIN32
1670 /*FIXME: Abort thread */
1671 #else
1672 pthread_kill ((pthread_t) tid, mono_thread_get_abort_signal ());
1673 #endif
1678 * suspend_vm:
1680 * Increase the suspend count of the VM. While the suspend count is greater
1681 * than 0, runtime threads are suspended at certain points during execution.
1683 static void
1684 suspend_vm (void)
1686 mono_loader_lock ();
1688 mono_mutex_lock (&suspend_mutex);
1690 suspend_count ++;
1692 DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
1694 if (suspend_count == 1) {
1695 // FIXME: Is it safe to call this inside the lock ?
1696 start_single_stepping ();
1697 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
1700 mono_mutex_unlock (&suspend_mutex);
1702 mono_loader_unlock ();
1706 * resume_vm:
1708 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
1709 * are resumed.
1711 static void
1712 resume_vm (void)
1714 int err;
1716 g_assert (debugger_thread_id == GetCurrentThreadId ());
1718 mono_loader_lock ();
1720 mono_mutex_lock (&suspend_mutex);
1722 g_assert (suspend_count > 0);
1723 suspend_count --;
1725 DEBUG(1, fprintf (log_file, "[%p] Resuming vm...\n", (gpointer)GetCurrentThreadId ()));
1727 if (suspend_count == 0) {
1728 // FIXME: Is it safe to call this inside the lock ?
1729 stop_single_stepping ();
1730 err = mono_cond_broadcast (&suspend_cond);
1731 g_assert (err == 0);
1734 err = mono_mutex_unlock (&suspend_mutex);
1735 g_assert (err == 0);
1737 mono_loader_unlock ();
1740 static void
1741 invalidate_frames (DebuggerTlsData *tls)
1743 int i;
1745 if (!tls)
1746 tls = TlsGetValue (debugger_tls_id);
1747 g_assert (tls);
1749 for (i = 0; i < tls->frame_count; ++i) {
1750 if (tls->frames [i]->jit)
1751 mono_debug_free_method_jit_info (tls->frames [i]->jit);
1752 g_free (tls->frames [i]);
1754 g_free (tls->frames);
1755 tls->frame_count = 0;
1756 tls->frames = NULL;
1760 * suspend_current:
1762 * Suspend the current thread until the runtime is resumed. If the thread has a
1763 * pending invoke, then the invoke is executed before this function returns.
1765 static void
1766 suspend_current (void)
1768 int err;
1769 DebuggerTlsData *tls;
1771 g_assert (debugger_thread_id != GetCurrentThreadId ());
1773 if (mono_loader_lock_is_owned_by_self ()) {
1775 * If we own the loader mutex, can't suspend until we release it, since the
1776 * whole runtime can deadlock otherwise.
1778 return;
1781 tls = TlsGetValue (debugger_tls_id);
1782 g_assert (tls);
1784 mono_mutex_lock (&suspend_mutex);
1786 if (!tls->suspended) {
1787 tls->suspended = TRUE;
1788 MONO_SEM_POST (&suspend_sem);
1791 DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
1793 while (suspend_count > 0) {
1794 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
1795 g_assert (err == 0);
1798 tls->suspended = FALSE;
1800 threads_suspend_count --;
1802 mono_mutex_unlock (&suspend_mutex);
1804 DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
1806 if (tls->invoke) {
1807 /* Save the original context */
1808 tls->invoke->has_ctx = TRUE;
1809 memcpy (&tls->invoke->ctx, &tls->ctx, sizeof (MonoContext));
1811 invoke_method ();
1814 /* The frame info becomes invalid after a resume */
1815 tls->has_context = FALSE;
1816 invalidate_frames (NULL);
1819 static void
1820 count_thread (gpointer key, gpointer value, gpointer user_data)
1822 DebuggerTlsData *tls = value;
1824 if (!tls->suspended && !tls->terminated)
1825 *(int*)user_data = *(int*)user_data + 1;
1828 static int
1829 count_threads_to_wait_for (void)
1831 int count = 0;
1833 mono_loader_lock ();
1834 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
1835 mono_loader_unlock ();
1837 return count;
1841 * wait_for_suspend:
1843 * Wait until the runtime is completely suspended.
1845 static void
1846 wait_for_suspend (void)
1848 int nthreads, nwait, err;
1849 gboolean waited = FALSE;
1851 // FIXME: Threads starting/stopping ?
1852 mono_loader_lock ();
1853 nthreads = mono_g_hash_table_size (thread_to_tls);
1854 mono_loader_unlock ();
1856 while (TRUE) {
1857 nwait = count_threads_to_wait_for ();
1858 if (nwait) {
1859 DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
1860 err = MONO_SEM_WAIT (&suspend_sem);
1861 g_assert (err == 0);
1862 waited = TRUE;
1863 } else {
1864 break;
1868 if (waited)
1869 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
1873 * is_suspended:
1875 * Return whenever the runtime is suspended.
1877 static gboolean
1878 is_suspended (void)
1880 return count_threads_to_wait_for () == 0;
1884 * compute_il_offset:
1886 * Compute the IL offset corresponding to NATIVE_OFFSET, which should be
1887 * a location of a sequence point.
1888 * We use this function instead of mono_debug_il_offset_from_address () etc,
1889 * which doesn't seem to work in a lot of cases.
1891 static gint32
1892 compute_il_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset)
1894 GPtrArray *seq_points;
1895 int i, last_il_offset, seq_il_offset, seq_native_offset;
1897 mono_domain_lock (domain);
1898 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
1899 mono_domain_unlock (domain);
1900 g_assert (seq_points);
1902 last_il_offset = -1;
1904 /* Find the sequence point */
1905 for (i = 0; i < seq_points->len; i += 2) {
1906 seq_il_offset = GPOINTER_TO_UINT (g_ptr_array_index (seq_points, i));
1907 seq_native_offset = GPOINTER_TO_UINT (g_ptr_array_index (seq_points, i + 1));
1909 if (seq_native_offset > native_offset)
1910 break;
1911 last_il_offset = seq_il_offset;
1914 return last_il_offset;
1917 typedef struct {
1918 DebuggerTlsData *tls;
1919 GSList *frames;
1920 } ComputeFramesUserData;
1922 static gboolean
1923 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
1925 ComputeFramesUserData *ud = user_data;
1926 StackFrame *frame;
1927 MonoMethod *method;
1929 if (info->type != FRAME_TYPE_MANAGED) {
1930 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
1931 /* Mark the last frame as an invoke frame */
1932 if (ud->frames)
1933 ((StackFrame*)ud->frames->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
1935 return FALSE;
1938 if (info->ji)
1939 method = info->ji->method;
1940 else
1941 method = info->method;
1943 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD))
1944 return FALSE;
1946 if (info->il_offset == -1) {
1947 /* Can't use compute_il_offset () since ip doesn't point precisely at at a seq point */
1948 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
1951 DEBUG (1, fprintf (stderr, "\tFrame: %s %d %d %d\n", mono_method_full_name (method, TRUE), info->native_offset, info->il_offset, info->managed));
1953 if (!info->managed && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD) {
1955 * mono_arch_find_jit_info () returns the context stored in the LMF for
1956 * native frames, but it should unwind once. This is why we have duplicate
1957 * frames on the stack sometimes.
1958 * !managed also seems to be set for dynamic methods.
1960 return FALSE;
1963 frame = g_new0 (StackFrame, 1);
1964 frame->method = method;
1965 frame->il_offset = info->il_offset;
1966 frame->ctx = *ctx;
1967 frame->domain = info->domain;
1969 ud->frames = g_slist_append (ud->frames, frame);
1971 return FALSE;
1974 static void
1975 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
1977 ComputeFramesUserData user_data;
1978 GSList *tmp;
1979 int i, findex, new_frame_count;
1980 StackFrame **new_frames, *f;
1982 // FIXME: Locking on tls
1983 if (tls->frames && tls->frames_up_to_date)
1984 return;
1986 DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
1988 user_data.tls = tls;
1989 user_data.frames = NULL;
1990 if (tls->has_context) {
1991 mono_jit_walk_stack_from_ctx_in_thread (process_frame, tls->domain, &tls->ctx, FALSE, thread, tls->lmf, &user_data);
1992 } else {
1993 // FIXME:
1994 tls->frame_count = 0;
1995 return;
1998 new_frame_count = g_slist_length (user_data.frames);
1999 new_frames = g_new0 (StackFrame*, new_frame_count);
2000 findex = 0;
2001 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
2002 f = tmp->data;
2005 * Reuse the id for already existing stack frames, so invokes don't invalidate
2006 * the still valid stack frames.
2008 for (i = 0; i < tls->frame_count; ++i) {
2009 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
2010 f->id = tls->frames [i]->id;
2011 break;
2015 if (i >= tls->frame_count)
2016 f->id = InterlockedIncrement (&frame_id);
2018 new_frames [findex ++] = f;
2021 g_slist_free (user_data.frames);
2023 invalidate_frames (tls);
2025 tls->frames = new_frames;
2026 tls->frame_count = new_frame_count;
2027 tls->frames_up_to_date = TRUE;
2031 * EVENT HANDLING
2035 * create_event_list:
2037 * Return a list of event request ids matching EVENT, starting from REQS, which
2038 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
2039 * policy.
2040 * We return request ids, instead of requests, to simplify threading, since
2041 * requests could be deleted anytime when the loader lock is not held.
2042 * LOCKING: Assumes the loader lock is held.
2044 static GSList*
2045 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, MonoException *exc, int *suspend_policy)
2047 int i, j;
2048 GSList *events = NULL;
2050 *suspend_policy = SUSPEND_POLICY_NONE;
2052 if (!reqs)
2053 reqs = event_requests;
2055 if (!reqs)
2056 return NULL;
2058 for (i = 0; i < reqs->len; ++i) {
2059 EventRequest *req = g_ptr_array_index (reqs, i);
2060 if (req->event_kind == event) {
2061 gboolean filtered = FALSE;
2063 /* Apply filters */
2064 for (j = 0; j < req->nmodifiers; ++j) {
2065 Modifier *mod = &req->modifiers [j];
2067 if (mod->kind == MOD_KIND_COUNT) {
2068 filtered = TRUE;
2069 if (mod->data.count > 0) {
2070 if (mod->data.count > 0) {
2071 mod->data.count --;
2072 if (mod->data.count == 0)
2073 filtered = FALSE;
2076 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
2077 if (mod->data.thread != mono_thread_internal_current ())
2078 filtered = TRUE;
2079 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && exc) {
2080 if (mod->data.exc_class && !mono_class_is_assignable_from (mod->data.exc_class, exc->object.vtable->klass))
2081 filtered = TRUE;
2082 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
2083 int k;
2084 gboolean found = FALSE;
2085 MonoAssembly **assemblies = mod->data.assemblies;
2087 for (k = 0; assemblies [k]; ++k)
2088 if (assemblies [k] == ji->method->klass->image->assembly)
2089 found = TRUE;
2090 if (!found)
2091 filtered = TRUE;
2095 if (!filtered) {
2096 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
2097 events = g_slist_append (events, GINT_TO_POINTER (req->id));
2102 /* Send a VM START/DEATH event by default */
2103 if (event == EVENT_KIND_VM_START)
2104 events = g_slist_append (events, GINT_TO_POINTER (0));
2105 if (event == EVENT_KIND_VM_DEATH)
2106 events = g_slist_append (events, GINT_TO_POINTER (0));
2108 return events;
2111 static G_GNUC_UNUSED const char*
2112 event_to_string (EventKind event)
2114 switch (event) {
2115 case EVENT_KIND_VM_START: return "VM_START";
2116 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
2117 case EVENT_KIND_THREAD_START: return "THREAD_START";
2118 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
2119 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
2120 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
2121 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
2122 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
2123 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
2124 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
2125 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
2126 case EVENT_KIND_STEP: return "STEP";
2127 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
2128 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
2129 default:
2130 g_assert_not_reached ();
2135 * process_event:
2137 * Send an event to the client, suspending the vm if needed.
2138 * LOCKING: Since this can suspend the calling thread, no locks should be held
2139 * by the caller.
2140 * The EVENTS list is freed by this function.
2142 static void
2143 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
2145 Buffer buf;
2146 GSList *l;
2147 MonoDomain *domain = mono_domain_get ();
2148 MonoThread *thread;
2150 if (!inited)
2151 return;
2153 if (!vm_start_event_sent && event != EVENT_KIND_VM_START)
2154 // FIXME: We miss those events
2155 return;
2157 if (vm_death_event_sent)
2158 return;
2160 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH)
2161 return;
2163 if (disconnected)
2164 return;
2166 if (events == NULL)
2167 return;
2169 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
2170 // FIXME: Send these with a NULL thread, don't suspend the current thread
2171 return;
2173 buffer_init (&buf, 128);
2174 buffer_add_byte (&buf, suspend_policy);
2175 buffer_add_int (&buf, g_slist_length (events)); // n of events
2177 for (l = events; l; l = l->next) {
2178 buffer_add_byte (&buf, event); // event kind
2179 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
2181 thread = mono_thread_current ();
2183 if (event == EVENT_KIND_VM_START)
2184 thread = arg;
2185 else if (event == EVENT_KIND_THREAD_START)
2186 g_assert (mono_thread_internal_current () == arg);
2188 buffer_add_objid (&buf, (MonoObject*)thread); // thread
2190 switch (event) {
2191 case EVENT_KIND_THREAD_START:
2192 case EVENT_KIND_THREAD_DEATH:
2193 break;
2194 case EVENT_KIND_APPDOMAIN_CREATE:
2195 case EVENT_KIND_APPDOMAIN_UNLOAD:
2196 buffer_add_domainid (&buf, arg);
2197 break;
2198 case EVENT_KIND_METHOD_ENTRY:
2199 case EVENT_KIND_METHOD_EXIT:
2200 buffer_add_methodid (&buf, domain, arg);
2201 break;
2202 case EVENT_KIND_ASSEMBLY_LOAD:
2203 case EVENT_KIND_ASSEMBLY_UNLOAD:
2204 buffer_add_assemblyid (&buf, domain, arg);
2205 break;
2206 case EVENT_KIND_TYPE_LOAD:
2207 buffer_add_typeid (&buf, domain, arg);
2208 break;
2209 case EVENT_KIND_BREAKPOINT:
2210 case EVENT_KIND_STEP:
2211 buffer_add_methodid (&buf, domain, arg);
2212 buffer_add_long (&buf, il_offset);
2213 break;
2214 case EVENT_KIND_VM_START:
2215 buffer_add_domainid (&buf, mono_get_root_domain ());
2216 break;
2217 case EVENT_KIND_VM_DEATH:
2218 break;
2219 case EVENT_KIND_EXCEPTION:
2220 buffer_add_objid (&buf, (MonoObject*)arg);
2221 break;
2222 default:
2223 g_assert_not_reached ();
2227 if (event == EVENT_KIND_VM_START) {
2228 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
2229 start_debugger_thread ();
2232 if (event == EVENT_KIND_VM_DEATH) {
2233 vm_death_event_sent = TRUE;
2235 suspend_policy = SUSPEND_POLICY_NONE;
2238 if (mono_runtime_is_shutting_down ())
2239 suspend_policy = SUSPEND_POLICY_NONE;
2241 if (suspend_policy != SUSPEND_POLICY_NONE) {
2243 * Save the thread context and start suspending before sending the packet,
2244 * since we could be receiving the resume request before send_packet ()
2245 * returns.
2247 save_thread_context (ctx);
2248 suspend_vm ();
2251 send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
2253 g_slist_free (events);
2254 events = NULL;
2256 if (event == EVENT_KIND_VM_START)
2257 vm_start_event_sent = TRUE;
2259 DEBUG (1, fprintf (log_file, "[%p] Sent event %s, suspend=%d.\n", (gpointer)GetCurrentThreadId (), event_to_string (event), suspend_policy));
2261 buffer_free (&buf);
2263 switch (suspend_policy) {
2264 case SUSPEND_POLICY_NONE:
2265 break;
2266 case SUSPEND_POLICY_ALL:
2267 suspend_current ();
2268 break;
2269 case SUSPEND_POLICY_EVENT_THREAD:
2270 NOT_IMPLEMENTED;
2271 break;
2272 default:
2273 g_assert_not_reached ();
2277 static void
2278 process_profiler_event (EventKind event, gpointer arg)
2280 int suspend_policy;
2281 GSList *events;
2283 mono_loader_lock ();
2284 events = create_event_list (event, NULL, NULL, NULL, &suspend_policy);
2285 mono_loader_unlock ();
2287 process_event (event, arg, 0, NULL, events, suspend_policy);
2290 static void
2291 runtime_initialized (MonoProfiler *prof)
2293 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
2296 static void
2297 runtime_shutdown (MonoProfiler *prof)
2299 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
2301 mono_debugger_agent_cleanup ();
2304 static void
2305 thread_startup (MonoProfiler *prof, gsize tid)
2307 MonoInternalThread *thread = mono_thread_internal_current ();
2308 MonoInternalThread *old_thread;
2309 DebuggerTlsData *tls;
2311 if (tid == debugger_thread_id)
2312 return;
2314 g_assert (thread->tid == tid);
2316 mono_loader_lock ();
2317 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
2318 mono_loader_unlock ();
2319 if (old_thread) {
2320 if (thread == old_thread) {
2322 * For some reason, thread_startup () might be called for the same thread
2323 * multiple times (attach ?).
2325 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
2326 return;
2327 } else {
2329 * thread_end () might not be called for some threads, and the tid could
2330 * get reused.
2332 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
2333 mono_loader_lock ();
2334 mono_g_hash_table_remove (thread_to_tls, old_thread);
2335 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
2336 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
2337 mono_loader_unlock ();
2341 tls = TlsGetValue (debugger_tls_id);
2342 g_assert (!tls);
2343 // FIXME: Free this somewhere
2344 tls = g_new0 (DebuggerTlsData, 1);
2345 tls->resume_event = CreateEvent (NULL, FALSE, FALSE, NULL);
2346 TlsSetValue (debugger_tls_id, tls);
2348 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
2350 mono_loader_lock ();
2351 mono_g_hash_table_insert (thread_to_tls, thread, tls);
2352 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
2353 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
2354 mono_loader_unlock ();
2356 process_profiler_event (EVENT_KIND_THREAD_START, thread);
2359 * suspend_vm () could have missed this thread, so wait for a resume.
2361 suspend_current ();
2364 static void
2365 thread_end (MonoProfiler *prof, gsize tid)
2367 MonoInternalThread *thread;
2368 DebuggerTlsData *tls = NULL;
2370 mono_loader_lock ();
2371 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
2372 if (thread) {
2373 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2374 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
2375 tls->terminated = TRUE;
2376 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
2377 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
2379 mono_loader_unlock ();
2381 /* We might be called for threads started before we registered the start callback */
2382 if (thread) {
2383 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
2384 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
2388 static void
2389 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
2391 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
2394 static void
2395 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
2397 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
2400 static void
2401 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
2403 /* Sent later in jit_end () */
2404 mono_loader_lock ();
2405 g_ptr_array_add (pending_assembly_loads, assembly);
2406 mono_loader_unlock ();
2409 static void
2410 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
2412 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
2415 static void
2416 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
2420 static void
2421 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
2423 int i;
2424 #ifdef PLATFORM_WIN32
2425 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
2426 #else
2427 gpointer stackptr = __builtin_frame_address (0);
2428 #endif
2430 if (ss_req == NULL || ss_req->start_sp > stackptr || ss_req->thread != mono_thread_internal_current ())
2431 return;
2434 * We need to stop single stepping when exiting a runtime invoke, since if it is
2435 * a step out, it may return to native code, and thus never end.
2437 mono_loader_lock ();
2438 for (i = 0; i < event_requests->len; ++i) {
2439 EventRequest *req = g_ptr_array_index (event_requests, i);
2441 if (req->event_kind == EVENT_KIND_STEP) {
2442 ss_stop (req);
2443 g_ptr_array_remove_index_fast (event_requests, i);
2444 g_free (req);
2445 break;
2448 mono_loader_unlock ();
2452 static void
2453 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
2456 * We emit type load events when the first method of the type is JITted,
2457 * since the class load profiler callbacks might be called with the
2458 * loader lock held. They could also occur in the debugger thread.
2459 * Same for assembly load events.
2461 gboolean type_load = FALSE;
2463 while (TRUE) {
2464 MonoAssembly *assembly = NULL;
2466 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
2467 mono_loader_lock ();
2468 if (pending_assembly_loads->len > 0) {
2469 assembly = g_ptr_array_index (pending_assembly_loads, 0);
2470 g_ptr_array_remove_index (pending_assembly_loads, 0);
2472 mono_loader_unlock ();
2474 if (assembly)
2475 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
2476 else
2477 break;
2480 mono_loader_lock ();
2481 if (!g_hash_table_lookup (loaded_classes, method->klass)) {
2482 type_load = TRUE;
2483 g_hash_table_insert (loaded_classes, method->klass, method->klass);
2485 mono_loader_unlock ();
2486 if (type_load)
2487 process_profiler_event (EVENT_KIND_TYPE_LOAD, method->klass);
2489 if (!result)
2490 add_pending_breakpoints (method, jinfo);
2494 * BREAKPOINTS/SINGLE STEPPING
2498 * Contains information about an inserted breakpoint.
2500 typedef struct {
2501 long il_offset, native_offset;
2502 guint8 *ip;
2503 gboolean pending, entry;
2504 MonoJitInfo *ji;
2505 } BreakpointInstance;
2508 * Contains generic information about a breakpoint.
2510 typedef struct {
2512 * The method where the breakpoint is placed. Can be NULL in which case it
2513 * is inserted into every method. This is used to implement method entry/
2514 * exit events. Can be a generic method definition, in which case the
2515 * breakpoint is inserted into every instance.
2517 MonoMethod *method;
2518 long il_offset;
2519 gboolean pending, entry;
2520 EventRequest *req;
2522 * A list of BreakpointInstance structures describing where the breakpoint
2523 * was inserted. There could be more than one because of
2524 * generics/appdomains/method entry/exit.
2526 GPtrArray *children;
2527 } MonoBreakpoint;
2529 /* List of breakpoints */
2530 static GPtrArray *breakpoints;
2531 /* Maps breakpoint locations to the number of breakpoints at that location */
2532 static GHashTable *bp_locs;
2534 static void
2535 breakpoints_init (void)
2537 breakpoints = g_ptr_array_new ();
2538 bp_locs = g_hash_table_new (NULL, NULL);
2541 static void
2542 breakpoints_cleanup (void)
2544 int i;
2546 mono_loader_lock ();
2548 for (i = 0; i < breakpoints->len; ++i)
2549 g_free (g_ptr_array_index (breakpoints, i));
2551 g_ptr_array_free (breakpoints, TRUE);
2552 g_hash_table_destroy (bp_locs);
2554 mono_loader_unlock ();
2558 * insert_breakpoint:
2560 * Insert the breakpoint described by BP into the method described by
2561 * JI.
2563 static void
2564 insert_breakpoint (GPtrArray *seq_points, MonoJitInfo *ji, MonoBreakpoint *bp)
2566 int i, count;
2567 gint32 il_offset, native_offset;
2568 BreakpointInstance *inst;
2570 native_offset = 0;
2571 for (i = 0; i < seq_points->len; i += 2) {
2572 il_offset = GPOINTER_TO_INT (g_ptr_array_index (seq_points, i));
2573 native_offset = GPOINTER_TO_INT (g_ptr_array_index (seq_points, i + 1));
2575 if (il_offset == bp->il_offset)
2576 break;
2579 if (i == seq_points->len)
2580 /* Have to handle this somehow */
2581 NOT_IMPLEMENTED;
2583 inst = g_new0 (BreakpointInstance, 1);
2584 inst->native_offset = native_offset;
2585 inst->ip = (guint8*)ji->code_start + native_offset;
2586 inst->ji = ji;
2588 mono_loader_lock ();
2590 g_ptr_array_add (bp->children, inst);
2592 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
2593 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
2594 mono_loader_unlock ();
2596 if (count == 0) {
2597 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
2598 mono_arch_set_breakpoint (ji, inst->ip);
2599 #else
2600 NOT_IMPLEMENTED;
2601 #endif
2605 static void
2606 remove_breakpoint (BreakpointInstance *inst)
2608 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
2609 int count;
2610 MonoJitInfo *ji = inst->ji;
2611 guint8 *ip = inst->ip;
2613 mono_loader_lock ();
2614 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
2615 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
2616 mono_loader_unlock ();
2618 g_assert (count > 0);
2620 if (count == 1) {
2621 mono_arch_clear_breakpoint (ji, ip);
2623 #else
2624 NOT_IMPLEMENTED;
2625 #endif
2629 * add_pending_breakpoints:
2631 * Insert pending breakpoints into the newly JITted method METHOD.
2633 static void
2634 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
2636 int i;
2637 GPtrArray *seq_points;
2638 MonoDomain *domain;
2640 if (!breakpoints)
2641 return;
2643 domain = mono_domain_get ();
2645 mono_loader_lock ();
2647 for (i = 0; i < breakpoints->len; ++i) {
2648 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
2650 if (bp->pending && (bp->method == method || !bp->method || (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method))) {
2651 mono_domain_lock (domain);
2652 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
2653 mono_domain_unlock (domain);
2654 if (!seq_points)
2655 /* Could be AOT code */
2656 continue;
2657 g_assert (seq_points);
2659 insert_breakpoint (seq_points, ji, bp);
2663 mono_loader_unlock ();
2666 static void
2667 set_bp_in_method (MonoDomain *domain, MonoMethod *method, GPtrArray *seq_points, MonoBreakpoint *bp)
2669 gpointer code;
2670 MonoJitInfo *ji;
2672 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
2673 if (!code) {
2674 /* Might be AOTed code */
2675 code = mono_aot_get_method (domain, method);
2676 g_assert (code);
2677 ji = mono_jit_info_table_find (domain, code);
2678 g_assert (ji);
2680 g_assert (code);
2682 insert_breakpoint (seq_points, ji, bp);
2685 static void
2686 set_bp_in_method_cb (gpointer key, gpointer value, gpointer user_data)
2688 MonoMethod *method = key;
2689 GPtrArray *seq_points = value;
2690 MonoBreakpoint *bp = user_data;
2691 MonoDomain *domain = mono_domain_get ();
2693 if (bp->method) {
2694 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method) {
2695 /* Generic instance */
2696 set_bp_in_method (domain, method, seq_points, bp);
2698 } else {
2699 /* Method entry/exit */
2700 set_bp_in_method (domain, method, seq_points, bp);
2705 * set_breakpoint:
2707 * Set a breakpoint at IL_OFFSET in METHOD.
2708 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
2709 * METHOD can also be a generic method definition, in which case a breakpoint
2710 * is placed in all instances of the method.
2712 static MonoBreakpoint*
2713 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req)
2715 GPtrArray *seq_points;
2716 MonoDomain *domain;
2717 MonoBreakpoint *bp;
2719 // FIXME:
2720 // - suspend/resume the vm to prevent code patching problems
2721 // - appdomains
2722 // - multiple breakpoints on the same location
2723 // - dynamic methods
2724 // - races
2726 bp = g_new0 (MonoBreakpoint, 1);
2727 bp->method = method;
2728 bp->il_offset = il_offset;
2729 bp->req = req;
2730 bp->children = g_ptr_array_new ();
2732 DEBUG(1, fprintf (log_file, "[dbg] Setting breakpoint at %s:0x%x.\n", mono_method_full_name (method, TRUE), (int)il_offset));
2734 domain = mono_domain_get ();
2735 mono_domain_lock (domain);
2736 if (method) {
2737 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
2738 if (seq_points) {
2739 set_bp_in_method (domain, method, seq_points, bp);
2740 } else {
2741 if (method->is_generic)
2742 /* There might be already JITted instances */
2743 g_hash_table_foreach (domain_jit_info (domain)->seq_points, set_bp_in_method_cb, bp);
2745 /* Not yet JITted */
2746 bp->pending = TRUE;
2748 } else {
2749 g_hash_table_foreach (domain_jit_info (domain)->seq_points, set_bp_in_method_cb, bp);
2750 bp->pending = TRUE;
2752 mono_domain_unlock (domain);
2754 mono_loader_lock ();
2755 g_ptr_array_add (breakpoints, bp);
2756 mono_loader_unlock ();
2758 return bp;
2761 static void
2762 clear_breakpoint (MonoBreakpoint *bp)
2764 int i;
2766 // FIXME: locking, races
2767 for (i = 0; i < bp->children->len; ++i) {
2768 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
2770 remove_breakpoint (inst);
2772 g_free (inst);
2775 mono_loader_lock ();
2776 g_ptr_array_remove (breakpoints, bp);
2777 mono_loader_unlock ();
2779 g_ptr_array_free (bp->children, TRUE);
2780 g_free (bp);
2783 static void
2784 process_breakpoint_inner (MonoContext *ctx)
2786 MonoJitInfo *ji;
2787 guint8 *orig_ip, *ip;
2788 int i, j, suspend_policy;
2789 guint32 native_offset;
2790 MonoBreakpoint *bp;
2791 BreakpointInstance *inst;
2792 GPtrArray *reqs;
2793 GSList *events = NULL;
2794 EventKind kind = EVENT_KIND_BREAKPOINT;
2796 // FIXME: Speed this up
2798 orig_ip = ip = MONO_CONTEXT_GET_IP (ctx);
2799 ji = mono_jit_info_table_find (mono_domain_get (), (char*)ip);
2800 g_assert (ji);
2801 g_assert (ji->method);
2803 /* Compute the native offset of the breakpoint from the ip */
2804 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
2805 ip = mono_arch_get_ip_for_breakpoint (ji, ctx);
2806 native_offset = ip - (guint8*)ji->code_start;
2807 #else
2808 NOT_IMPLEMENTED;
2809 #endif
2812 * Skip the instruction causing the breakpoint signal.
2814 mono_arch_skip_breakpoint (ctx);
2816 if (ji->method->wrapper_type)
2817 return;
2819 reqs = g_ptr_array_new ();
2821 DEBUG(1, fprintf (log_file, "[%p] Breakpoint hit, method=%s, offset=0x%x.\n", (gpointer)GetCurrentThreadId (), ji->method->name, native_offset));
2823 mono_loader_lock ();
2825 bp = NULL;
2826 for (i = 0; i < breakpoints->len; ++i) {
2827 bp = g_ptr_array_index (breakpoints, i);
2829 if (!bp->method)
2830 continue;
2832 for (j = 0; j < bp->children->len; ++j) {
2833 inst = g_ptr_array_index (bp->children, j);
2834 if (inst->ji == ji && inst->native_offset == native_offset)
2835 g_ptr_array_add (reqs, bp->req);
2838 if (reqs->len == 0) {
2839 GPtrArray *seq_points;
2840 int seq_il_offset, seq_native_offset;
2841 MonoDomain *domain = mono_domain_get ();
2843 /* Maybe a method entry/exit event */
2844 mono_domain_lock (domain);
2845 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, ji->method);
2846 mono_domain_unlock (domain);
2847 if (!seq_points) {
2848 // FIXME: Generic sharing */
2849 mono_loader_unlock ();
2850 return;
2852 g_assert (seq_points);
2854 for (i = 0; i < seq_points->len; i += 2) {
2855 seq_il_offset = GPOINTER_TO_INT (g_ptr_array_index (seq_points, i));
2856 seq_native_offset = GPOINTER_TO_INT (g_ptr_array_index (seq_points, i + 1));
2858 if (native_offset == seq_native_offset) {
2859 if (seq_il_offset == METHOD_ENTRY_IL_OFFSET)
2860 kind = EVENT_KIND_METHOD_ENTRY;
2861 else if (seq_il_offset == METHOD_EXIT_IL_OFFSET)
2862 kind = EVENT_KIND_METHOD_EXIT;
2863 break;
2868 if (reqs->len > 0)
2869 events = create_event_list (EVENT_KIND_BREAKPOINT, reqs, ji, NULL, &suspend_policy);
2870 else if (kind != EVENT_KIND_BREAKPOINT)
2871 events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
2873 g_ptr_array_free (reqs, TRUE);
2875 mono_loader_unlock ();
2877 if (events)
2878 process_event (kind, ji->method, 0, ctx, events, suspend_policy);
2881 static void
2882 process_breakpoint (void)
2884 DebuggerTlsData *tls;
2885 MonoContext ctx;
2886 static void (*restore_context) (void *);
2888 if (!restore_context)
2889 restore_context = mono_get_restore_context ();
2891 tls = TlsGetValue (debugger_tls_id);
2892 memcpy (&ctx, &tls->handler_ctx, sizeof (MonoContext));
2894 process_breakpoint_inner (&ctx);
2896 /* This is called when resuming from a signal handler, so it shouldn't return */
2897 restore_context (&ctx);
2898 g_assert_not_reached ();
2901 static void
2902 resume_from_signal_handler (void *sigctx, void *func)
2904 DebuggerTlsData *tls;
2905 MonoContext ctx;
2907 /* Save the original context in TLS */
2908 // FIXME: This might not work on an altstack ?
2909 tls = TlsGetValue (debugger_tls_id);
2910 g_assert (tls);
2912 // FIXME: MonoContext usually doesn't include the fp registers, so these are
2913 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
2914 // clob:c could be added to op_seq_point.
2916 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
2917 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
2918 MONO_CONTEXT_SET_IP (&ctx, func);
2920 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
2923 void
2924 mono_debugger_agent_breakpoint_hit (void *sigctx)
2927 * We are called from a signal handler, and running code there causes all kinds of
2928 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
2929 * So set up the signal context to return to the real breakpoint handler function.
2932 resume_from_signal_handler (sigctx, process_breakpoint);
2935 static void
2936 process_single_step_inner (MonoContext *ctx)
2938 MonoJitInfo *ji;
2939 guint8 *ip;
2940 GPtrArray *reqs;
2941 int il_offset, suspend_policy;
2942 MonoDomain *domain = mono_domain_get ();
2943 GSList *events;
2945 // FIXME: Speed this up
2947 ip = MONO_CONTEXT_GET_IP (ctx);
2949 /* Skip the instruction causing the single step */
2950 mono_arch_skip_single_step (ctx);
2952 if (suspend_count > 0) {
2953 if (debugger_thread_id == GetCurrentThreadId ())
2954 return;
2956 DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2958 ji = mono_jit_info_table_find (mono_domain_get (), (char*)ip);
2960 /* See the comment below */
2961 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
2962 return;
2964 save_thread_context (ctx);
2965 suspend_current ();
2966 return;
2969 if (!ss_req)
2970 // FIXME: A suspend race
2971 return;
2973 if (mono_thread_internal_current () != ss_req->thread)
2974 return;
2976 if (log_level > 0) {
2977 const char *depth = NULL;
2979 ji = mono_jit_info_table_find (mono_domain_get (), (char*)ip);
2981 switch (ss_req->depth) {
2982 case STEP_DEPTH_OVER:
2983 depth = "over";
2984 break;
2985 case STEP_DEPTH_OUT:
2986 depth = "out";
2987 break;
2988 case STEP_DEPTH_INTO:
2989 depth = "into";
2990 break;
2991 default:
2992 g_assert_not_reached ();
2995 DEBUG (1, fprintf (log_file, "[%p] Single step event (depth=%s) at %s (%p), sp %p, last sp %p\n", (gpointer)GetCurrentThreadId (), ss_req->depth == STEP_DEPTH_OVER ? "over" : "out", mono_method_full_name (ji->method, TRUE), MONO_CONTEXT_GET_IP (ctx), MONO_CONTEXT_GET_SP (ctx), ss_req->last_sp));
2999 * We implement step over/out by single stepping until we reach the same
3000 * frame/parent frame.
3001 * FIXME:
3002 * - this is slow
3003 * - stack growing upward
3004 * - localloc
3005 * - exceptions
3007 if (ss_req->depth != STEP_DEPTH_INTO) {
3008 if (ss_req->depth == STEP_DEPTH_OVER && MONO_CONTEXT_GET_SP (ctx) < ss_req->last_sp)
3009 return;
3010 if (ss_req->depth == STEP_DEPTH_OUT && MONO_CONTEXT_GET_SP (ctx) <= ss_req->last_sp)
3011 return;
3013 ss_req->last_sp = MONO_CONTEXT_GET_SP (ctx);
3016 ji = mono_jit_info_table_find (mono_domain_get (), (char*)ip);
3017 g_assert (ji);
3018 g_assert (ji->method);
3020 if (ji->method->wrapper_type && ji->method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
3021 return;
3024 * FIXME:
3025 * Stopping in memset makes half-initialized vtypes visible.
3026 * Stopping in memcpy makes half-copied vtypes visible.
3028 if (ji->method->klass == mono_defaults.string_class && (!strcmp (ji->method->name, "memset") || strstr (ji->method->name, "memcpy")))
3029 return;
3032 * The ip points to the instruction causing the single step event, convert it
3033 * to the offset stored in seq_points.
3035 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3036 ip = mono_arch_get_ip_for_single_step (ji, ctx);
3037 #else
3038 g_assert_not_reached ();
3039 #endif
3042 * mono_debug_lookup_source_location () doesn't work for IL offset 0 for
3043 * example, so do things by hand.
3045 il_offset = compute_il_offset (domain, ji->method, (guint8*)ip - (guint8*)ji->code_start);
3047 if (il_offset == -1)
3048 return;
3050 if (ss_req->size == STEP_SIZE_LINE) {
3051 /* Step until a different source line is reached */
3052 MonoDebugMethodInfo *minfo;
3054 minfo = mono_debug_lookup_method (ji->method);
3056 if (minfo) {
3057 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, il_offset);
3059 if (loc && ji->method == ss_req->last_method && loc->row == ss_req->last_line) {
3060 mono_debug_free_source_location (loc);
3061 return;
3063 if (!loc)
3065 * Step until we reach a location with line number info,
3066 * otherwise the client can't show a location.
3067 * This can happen for example with statics initialized inline
3068 * outside of a cctor.
3070 return;
3072 if (loc) {
3073 ss_req->last_method = ji->method;
3074 ss_req->last_line = loc->row;
3075 mono_debug_free_source_location (loc);
3080 // FIXME: Has to lock earlier
3082 reqs = g_ptr_array_new ();
3084 mono_loader_lock ();
3086 g_ptr_array_add (reqs, ss_req->req);
3088 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
3090 g_ptr_array_free (reqs, TRUE);
3092 mono_loader_unlock ();
3094 process_event (EVENT_KIND_STEP, ji->method, il_offset, ctx, events, suspend_policy);
3097 static void
3098 process_single_step (void)
3100 DebuggerTlsData *tls;
3101 MonoContext ctx;
3102 static void (*restore_context) (void *);
3104 if (!restore_context)
3105 restore_context = mono_get_restore_context ();
3107 tls = TlsGetValue (debugger_tls_id);
3108 memcpy (&ctx, &tls->handler_ctx, sizeof (MonoContext));
3110 process_single_step_inner (&ctx);
3112 /* This is called when resuming from a signal handler, so it shouldn't return */
3113 restore_context (&ctx);
3114 g_assert_not_reached ();
3118 * mono_debugger_agent_single_step_event:
3120 * Called from a signal handler to handle a single step event.
3122 void
3123 mono_debugger_agent_single_step_event (void *sigctx)
3125 /* Resume to process_single_step through the signal context */
3127 // FIXME: Since step out/over is implemented using step in, the step in case should
3128 // be as fast as possible. Move the relevant code from process_single_step_inner ()
3129 // here
3131 if (GetCurrentThreadId () == debugger_thread_id) {
3133 * This could happen despite our best effors when the runtime calls
3134 * assembly/type resolve hooks.
3135 * FIXME: Breakpoints too.
3137 MonoContext ctx;
3139 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
3140 mono_arch_skip_single_step (&ctx);
3141 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
3142 return;
3145 resume_from_signal_handler (sigctx, process_single_step);
3149 * start_single_stepping:
3151 * Turn on single stepping. Can be called multiple times, for example,
3152 * by a single step event request + a suspend.
3154 static void
3155 start_single_stepping (void)
3157 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3158 int val = InterlockedIncrement (&ss_count);
3160 if (val == 1)
3161 mono_arch_start_single_stepping ();
3162 #else
3163 g_assert_not_reached ();
3164 #endif
3167 static void
3168 stop_single_stepping (void)
3170 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
3171 int val = InterlockedDecrement (&ss_count);
3173 if (val == 0)
3174 mono_arch_stop_single_stepping ();
3175 #else
3176 g_assert_not_reached ();
3177 #endif
3181 * Start single stepping of thread THREAD
3183 static ErrorCode
3184 ss_start (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
3186 DebuggerTlsData *tls;
3188 if (suspend_count == 0)
3189 return ERR_NOT_SUSPENDED;
3191 wait_for_suspend ();
3193 // FIXME: Multiple requests
3194 if (ss_req)
3195 return ERR_NOT_IMPLEMENTED;
3197 ss_req = g_new0 (MonoSingleStepReq, 1);
3198 ss_req->req = req;
3199 ss_req->thread = thread;
3200 ss_req->size = size;
3201 ss_req->depth = depth;
3202 req->info = ss_req;
3204 mono_loader_lock ();
3205 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
3206 mono_loader_unlock ();
3207 g_assert (tls);
3208 g_assert (tls->has_context);
3209 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->ctx);
3211 if (ss_req->size == STEP_SIZE_LINE) {
3212 StackFrame *frame;
3213 MonoDebugMethodInfo *minfo;
3215 /* Compute the initial line info */
3216 compute_frame_info (thread, tls);
3218 g_assert (tls->frame_count);
3219 frame = tls->frames [0];
3221 ss_req->last_method = frame->method;
3222 ss_req->last_line = -1;
3224 minfo = mono_debug_lookup_method (frame->method);
3225 if (minfo && frame->il_offset != -1) {
3226 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
3228 if (loc) {
3229 ss_req->last_line = loc->row;
3230 g_free (loc);
3235 start_single_stepping ();
3237 return 0;
3240 static void
3241 ss_stop (EventRequest *req)
3243 // FIXME: Locking
3244 g_assert (ss_req);
3245 g_assert (ss_req->req == req);
3247 g_free (ss_req);
3248 ss_req = NULL;
3250 stop_single_stepping ();
3253 void
3254 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *ctx)
3256 int suspend_policy;
3257 GSList *events;
3259 /* Just-In-Time debugging */
3260 if (agent_config.onthrow && !inited) {
3261 GSList *l;
3262 gboolean found = FALSE;
3264 for (l = agent_config.onthrow; l; l = l->next) {
3265 char *ex_type = l->data;
3266 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
3268 if (!strcmp (ex_type, f))
3269 found = TRUE;
3271 g_free (f);
3274 if (found) {
3275 finish_agent_init (FALSE);
3278 * Send an unsolicited EXCEPTION event with a dummy request id.
3280 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
3281 process_event (EVENT_KIND_EXCEPTION, exc, 0, ctx, events, SUSPEND_POLICY_ALL);
3282 return;
3286 if (!inited)
3287 return;
3289 mono_loader_lock ();
3290 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, exc, &suspend_policy);
3291 mono_loader_unlock ();
3293 process_event (EVENT_KIND_EXCEPTION, exc, 0, ctx, events, suspend_policy);
3296 void
3297 mono_debugger_agent_handle_unhandled_exception (MonoException *exc, MonoContext *ctx)
3299 GSList *events;
3301 if (!agent_config.onuncaught)
3302 return;
3304 finish_agent_init (FALSE);
3307 * Send an unsolicited EXCEPTION event with a dummy request id.
3309 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
3310 process_event (EVENT_KIND_EXCEPTION, exc, 0, ctx, events, SUSPEND_POLICY_ALL);
3314 * buffer_add_value:
3316 * Add the encoding of the value at ADDR described by T to the buffer.
3318 static void
3319 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
3321 MonoObject *obj;
3323 if (t->byref) {
3324 g_assert (*(void**)addr);
3325 addr = *(void**)addr;
3328 switch (t->type) {
3329 case MONO_TYPE_VOID:
3330 buffer_add_byte (buf, t->type);
3331 break;
3332 case MONO_TYPE_BOOLEAN:
3333 case MONO_TYPE_I1:
3334 case MONO_TYPE_U1:
3335 buffer_add_byte (buf, t->type);
3336 buffer_add_int (buf, *(gint8*)addr);
3337 break;
3338 case MONO_TYPE_CHAR:
3339 case MONO_TYPE_I2:
3340 case MONO_TYPE_U2:
3341 buffer_add_byte (buf, t->type);
3342 buffer_add_int (buf, *(gint16*)addr);
3343 break;
3344 case MONO_TYPE_I4:
3345 case MONO_TYPE_U4:
3346 case MONO_TYPE_R4:
3347 buffer_add_byte (buf, t->type);
3348 buffer_add_int (buf, *(gint32*)addr);
3349 break;
3350 case MONO_TYPE_I8:
3351 case MONO_TYPE_U8:
3352 case MONO_TYPE_R8:
3353 buffer_add_byte (buf, t->type);
3354 buffer_add_long (buf, *(gint64*)addr);
3355 break;
3356 case MONO_TYPE_I:
3357 case MONO_TYPE_U:
3358 case MONO_TYPE_PTR: {
3359 gssize val = *(gssize*)addr;
3361 buffer_add_byte (buf, t->type);
3362 buffer_add_long (buf, val);
3363 break;
3365 handle_ref:
3366 case MONO_TYPE_STRING:
3367 case MONO_TYPE_SZARRAY:
3368 case MONO_TYPE_OBJECT:
3369 case MONO_TYPE_CLASS:
3370 case MONO_TYPE_ARRAY:
3371 obj = *(MonoObject**)addr;
3373 if (!obj) {
3374 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
3375 } else {
3376 if (obj->vtable->klass->valuetype) {
3377 t = &obj->vtable->klass->byval_arg;
3378 addr = mono_object_unbox (obj);
3379 goto handle_vtype;
3380 } else if (obj->vtable->klass->rank) {
3381 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
3382 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
3383 buffer_add_byte (buf, MONO_TYPE_CLASS);
3384 } else {
3385 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
3387 buffer_add_objid (buf, obj);
3389 break;
3390 handle_vtype:
3391 case MONO_TYPE_VALUETYPE: {
3392 int nfields;
3393 gpointer iter;
3394 MonoClassField *f;
3395 MonoClass *klass = mono_class_from_mono_type (t);
3397 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
3398 buffer_add_byte (buf, klass->enumtype);
3399 buffer_add_typeid (buf, domain, klass);
3401 nfields = 0;
3402 iter = NULL;
3403 while ((f = mono_class_get_fields (klass, &iter))) {
3404 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
3405 continue;
3406 if (mono_field_is_deleted (f))
3407 continue;
3408 nfields ++;
3410 buffer_add_int (buf, nfields);
3412 iter = NULL;
3413 while ((f = mono_class_get_fields (klass, &iter))) {
3414 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
3415 continue;
3416 if (mono_field_is_deleted (f))
3417 continue;
3418 buffer_add_value (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain);
3420 break;
3422 case MONO_TYPE_GENERICINST:
3423 if (mono_type_generic_inst_is_valuetype (t)) {
3424 goto handle_vtype;
3425 } else {
3426 goto handle_ref;
3428 break;
3429 default:
3430 NOT_IMPLEMENTED;
3434 static ErrorCode
3435 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
3437 int err;
3438 int type = decode_byte (buf, &buf, limit);
3440 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t)) {
3441 DEBUG(1, fprintf (log_file, "Expected value of type %d, got %d.\n", t->type, type));
3442 return ERR_INVALID_ARGUMENT;
3445 switch (t->type) {
3446 case MONO_TYPE_BOOLEAN:
3447 *(guint8*)addr = decode_int (buf, &buf, limit);
3448 break;
3449 case MONO_TYPE_CHAR:
3450 *(gunichar2*)addr = decode_int (buf, &buf, limit);
3451 break;
3452 case MONO_TYPE_I1:
3453 *(gint8*)addr = decode_int (buf, &buf, limit);
3454 break;
3455 case MONO_TYPE_U1:
3456 *(guint8*)addr = decode_int (buf, &buf, limit);
3457 break;
3458 case MONO_TYPE_I2:
3459 *(gint16*)addr = decode_int (buf, &buf, limit);
3460 break;
3461 case MONO_TYPE_U2:
3462 *(guint16*)addr = decode_int (buf, &buf, limit);
3463 break;
3464 case MONO_TYPE_I4:
3465 *(gint32*)addr = decode_int (buf, &buf, limit);
3466 break;
3467 case MONO_TYPE_U4:
3468 *(guint32*)addr = decode_int (buf, &buf, limit);
3469 break;
3470 case MONO_TYPE_I8:
3471 *(gint64*)addr = decode_long (buf, &buf, limit);
3472 break;
3473 case MONO_TYPE_U8:
3474 *(guint64*)addr = decode_long (buf, &buf, limit);
3475 break;
3476 case MONO_TYPE_R4:
3477 *(guint32*)addr = decode_int (buf, &buf, limit);
3478 break;
3479 case MONO_TYPE_R8:
3480 *(guint64*)addr = decode_long (buf, &buf, limit);
3481 break;
3482 case MONO_TYPE_VALUETYPE: {
3483 gboolean is_enum = decode_byte (buf, &buf, limit);
3484 MonoClass *klass;
3485 MonoClassField *f;
3486 int nfields;
3487 gpointer iter = NULL;
3488 MonoDomain *d;
3490 /* Enums are sent as a normal vtype */
3491 if (is_enum)
3492 return ERR_NOT_IMPLEMENTED;
3493 klass = decode_typeid (buf, &buf, limit, &d, &err);
3494 if (err)
3495 return err;
3497 if (klass != mono_class_from_mono_type (t))
3498 return ERR_INVALID_ARGUMENT;
3500 nfields = decode_int (buf, &buf, limit);
3501 while ((f = mono_class_get_fields (klass, &iter))) {
3502 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
3503 continue;
3504 if (mono_field_is_deleted (f))
3505 continue;
3506 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
3507 if (err)
3508 return err;
3509 nfields --;
3511 g_assert (nfields == 0);
3512 break;
3514 default:
3515 if (MONO_TYPE_IS_REFERENCE (t)) {
3516 if (type == MONO_TYPE_OBJECT) {
3517 int objid = decode_objid (buf, &buf, limit);
3518 int err;
3519 MonoObject *obj;
3521 err = get_object (objid, (MonoObject**)&obj);
3522 if (err)
3523 return err;
3525 if (obj && !mono_class_is_assignable_from (mono_class_from_mono_type (t), obj->vtable->klass))
3526 return ERR_INVALID_ARGUMENT;
3527 if (obj && obj->vtable->domain != domain)
3528 return ERR_INVALID_ARGUMENT;
3530 mono_gc_wbarrier_generic_store (addr, obj);
3531 } else if (type == VALUE_TYPE_ID_NULL) {
3532 *(MonoObject**)addr = NULL;
3533 } else {
3534 return ERR_INVALID_ARGUMENT;
3536 } else {
3537 NOT_IMPLEMENTED;
3539 break;
3542 *endbuf = buf;
3544 return 0;
3547 static void
3548 add_var (Buffer *buf, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain)
3550 guint32 flags;
3551 int reg;
3552 guint8 *addr;
3553 gpointer reg_val;
3555 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
3556 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
3558 switch (flags) {
3559 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
3560 reg_val = mono_arch_context_get_int_reg (ctx, reg);
3562 buffer_add_value (buf, t, &reg_val, domain);
3563 break;
3564 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
3565 addr = mono_arch_context_get_int_reg (ctx, reg);
3566 addr += (gint32)var->offset;
3568 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
3570 buffer_add_value (buf, t, addr, domain);
3571 break;
3572 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
3573 NOT_IMPLEMENTED;
3574 break;
3575 default:
3576 g_assert_not_reached ();
3580 static void
3581 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val)
3583 guint32 flags;
3584 int reg, size;
3585 guint8 *addr;
3587 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
3588 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
3590 if (MONO_TYPE_IS_REFERENCE (t))
3591 size = sizeof (gpointer);
3592 else
3593 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
3595 switch (flags) {
3596 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
3597 // FIXME: Can't set registers, so we disable linears
3598 NOT_IMPLEMENTED;
3599 break;
3600 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
3601 addr = mono_arch_context_get_int_reg (ctx, reg);
3602 addr += (gint32)var->offset;
3604 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
3606 // FIXME: Write barriers
3607 memcpy (addr, val, size);
3608 break;
3609 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
3610 NOT_IMPLEMENTED;
3611 break;
3612 default:
3613 g_assert_not_reached ();
3617 static void
3618 clear_event_request (int req_id, int etype)
3620 int i;
3622 mono_loader_lock ();
3623 for (i = 0; i < event_requests->len; ++i) {
3624 EventRequest *req = g_ptr_array_index (event_requests, i);
3626 if (req->id == req_id && req->event_kind == etype) {
3627 if (req->event_kind == EVENT_KIND_BREAKPOINT)
3628 clear_breakpoint (req->info);
3629 if (req->event_kind == EVENT_KIND_STEP)
3630 ss_stop (req);
3631 g_ptr_array_remove_index_fast (event_requests, i);
3632 g_free (req);
3633 break;
3636 mono_loader_unlock ();
3639 static void
3640 add_thread (gpointer key, gpointer value, gpointer user_data)
3642 MonoInternalThread *thread = value;
3643 Buffer *buf = user_data;
3645 buffer_add_objid (buf, (MonoObject*)thread);
3648 static ErrorCode
3649 do_invoke_method (Buffer *buf, InvokeData *invoke)
3651 guint8 *p = invoke->p;
3652 guint8 *end = invoke->endp;
3653 MonoMethod *m;
3654 int i, err, nargs;
3655 MonoMethodSignature *sig;
3656 guint8 **arg_buf;
3657 void **args;
3658 MonoObject *this, *res, *exc;
3659 MonoDomain *domain;
3660 guint8 *this_buf;
3661 #ifdef MONO_ARCH_HAVE_FIND_JIT_INFO_EXT
3662 MonoLMFExt ext;
3663 #endif
3665 m = decode_methodid (p, &p, end, &domain, &err);
3666 if (err)
3667 return err;
3668 sig = mono_method_signature (m);
3670 if (m->klass->valuetype)
3671 this_buf = g_alloca (mono_class_instance_size (m->klass));
3672 else
3673 this_buf = g_alloca (sizeof (MonoObject*));
3674 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
3675 if (err)
3676 return err;
3678 if (!m->klass->valuetype)
3679 this = *(MonoObject**)this_buf;
3680 else
3681 this = NULL;
3683 DEBUG (1, printf ("[%p] Invoking method '%s' on receiver '%s'.\n", (gpointer)GetCurrentThreadId (), mono_method_full_name (m, TRUE), this ? this->vtable->klass->name : "<null>"));
3685 if (this && this->vtable->domain != domain)
3686 NOT_IMPLEMENTED;
3688 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
3689 if (!strcmp (m->name, ".ctor")) {
3690 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
3691 return ERR_INVALID_ARGUMENT;
3692 else
3693 this = mono_object_new (domain, m->klass);
3694 } else {
3695 return ERR_INVALID_ARGUMENT;
3699 if (this && !mono_class_is_assignable_from (m->klass, this->vtable->klass))
3700 return ERR_INVALID_ARGUMENT;
3702 nargs = decode_int (p, &p, end);
3703 if (nargs != sig->param_count)
3704 return ERR_INVALID_ARGUMENT;
3705 /* Use alloca to get gc tracking */
3706 arg_buf = g_alloca (nargs * sizeof (gpointer));
3707 memset (arg_buf, 0, nargs * sizeof (gpointer));
3708 args = g_alloca (nargs * sizeof (gpointer));
3709 for (i = 0; i < nargs; ++i) {
3710 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
3711 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
3712 if (err)
3713 break;
3715 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
3716 NOT_IMPLEMENTED;
3717 } else {
3718 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
3719 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
3720 if (err)
3721 break;
3722 args [i] = arg_buf [i];
3726 if (i < nargs)
3727 return err;
3730 * Add an LMF frame to link the stack frames on the invoke method with our caller.
3732 /* FIXME: Move this to arch specific code */
3733 #ifdef MONO_ARCH_HAVE_FIND_JIT_INFO_EXT
3734 if (invoke->has_ctx) {
3735 MonoLMF **lmf_addr;
3737 lmf_addr = mono_get_lmf_addr ();
3739 /* Setup our lmf */
3740 memset (&ext, 0, sizeof (ext));
3741 #ifdef TARGET_AMD64
3742 ext.lmf.previous_lmf = *(lmf_addr);
3743 /* Mark that this is a MonoLMFExt */
3744 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
3745 ext.lmf.rsp = (gssize)&ext;
3746 #elif defined(TARGET_X86)
3747 ext.lmf.previous_lmf = (gsize)*(lmf_addr);
3748 /* Mark that this is a MonoLMFExt */
3749 ext.lmf.previous_lmf = (gsize)(gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
3750 ext.lmf.ebp = (gssize)&ext;
3751 #elif defined(TARGET_ARM)
3752 ext.lmf.previous_lmf = *(lmf_addr);
3753 /* Mark that this is a MonoLMFExt */
3754 ext.lmf.previous_lmf = (gpointer)(((gssize)ext.lmf.previous_lmf) | 2);
3755 ext.lmf.ebp = (gssize)&ext;
3756 #else
3757 g_assert_not_reached ();
3758 #endif
3760 ext.debugger_invoke = TRUE;
3761 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
3763 mono_set_lmf ((MonoLMF*)&ext);
3765 #endif
3767 if (m->klass->valuetype)
3768 res = mono_runtime_invoke (m, this_buf, args, &exc);
3769 else
3770 res = mono_runtime_invoke (m, this, args, &exc);
3771 if (exc) {
3772 buffer_add_byte (buf, 0);
3773 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
3774 } else {
3775 buffer_add_byte (buf, 1);
3776 if (sig->ret->type == MONO_TYPE_VOID) {
3777 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
3778 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
3780 else
3781 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
3782 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
3783 buffer_add_value (buf, sig->ret, &res, domain);
3784 } else if (mono_class_from_mono_type (sig->ret)->valuetype) {
3785 g_assert (res);
3786 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
3787 } else {
3788 NOT_IMPLEMENTED;
3792 #ifdef MONO_ARCH_HAVE_FIND_JIT_INFO_EXT
3793 if (invoke->has_ctx)
3794 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
3795 #endif
3797 // FIXME: byref arguments
3798 // FIXME: varargs
3799 return ERR_NONE;
3803 * invoke_method:
3805 * Invoke the method given by tls->invoke in the current thread.
3807 static void
3808 invoke_method (void)
3810 DebuggerTlsData *tls;
3811 InvokeData *invoke;
3812 int id;
3813 int err;
3814 Buffer buf;
3815 static void (*restore_context) (void *);
3816 MonoContext restore_ctx;
3818 if (!restore_context)
3819 restore_context = mono_get_restore_context ();
3821 tls = TlsGetValue (debugger_tls_id);
3822 g_assert (tls);
3824 invoke = tls->invoke;
3825 g_assert (invoke);
3826 tls->invoke = NULL;
3828 tls->frames_up_to_date = FALSE;
3830 id = invoke->id;
3832 buffer_init (&buf, 128);
3834 err = do_invoke_method (&buf, invoke);
3836 /* Start suspending before sending the reply */
3837 suspend_vm ();
3839 send_reply_packet (id, err, &buf);
3841 buffer_free (&buf);
3843 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
3845 if (invoke->has_ctx)
3846 save_thread_context (&restore_ctx);
3848 g_free (invoke->p);
3849 g_free (invoke);
3851 suspend_current ();
3854 static ErrorCode
3855 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
3857 switch (command) {
3858 case CMD_VM_VERSION: {
3859 char *build_info, *version;
3861 build_info = mono_get_runtime_build_info ();
3862 version = g_strdup_printf ("mono %s", build_info);
3864 buffer_add_string (buf, version); /* vm version */
3865 buffer_add_int (buf, MAJOR_VERSION);
3866 buffer_add_int (buf, MINOR_VERSION);
3867 g_free (build_info);
3868 g_free (version);
3869 break;
3871 case CMD_VM_ALL_THREADS: {
3872 // FIXME: Domains
3873 mono_loader_lock ();
3874 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
3875 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
3876 mono_loader_unlock ();
3877 break;
3879 case CMD_VM_SUSPEND:
3880 suspend_vm ();
3881 wait_for_suspend ();
3882 break;
3883 case CMD_VM_RESUME:
3884 if (suspend_count == 0)
3885 return ERR_NOT_SUSPENDED;
3886 resume_vm ();
3887 break;
3888 case CMD_VM_DISPOSE:
3889 /* Clear all event requests */
3890 mono_loader_lock ();
3891 while (event_requests->len > 0) {
3892 EventRequest *req = g_ptr_array_index (event_requests, 0);
3894 clear_event_request (req->id, req->event_kind);
3896 mono_loader_unlock ();
3898 // FIXME: Count resumes
3899 resume_vm ();
3900 disconnected = TRUE;
3901 break;
3902 case CMD_VM_EXIT: {
3903 int exit_code = decode_int (p, &p, end);
3905 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
3907 /* Have to send a reply before exiting */
3908 send_reply_packet (id, 0, buf);
3910 /* Clear all event requests */
3911 mono_loader_lock ();
3912 while (event_requests->len > 0) {
3913 EventRequest *req = g_ptr_array_index (event_requests, 0);
3915 clear_event_request (req->id, req->event_kind);
3917 mono_loader_unlock ();
3919 /* FIXME: Races with normal shutdown */
3920 while (suspend_count > 0)
3921 resume_vm ();
3924 * The JDWP documentation says that the shutdown is not orderly. It doesn't
3925 * specify whenever a VM_DEATH event is sent. We currently do an orderly
3926 * shutdown similar to Environment.Exit ().
3928 mono_runtime_set_shutting_down ();
3930 mono_threads_set_shutting_down ();
3932 /* Suspend all managed threads since the runtime is going away */
3933 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
3934 mono_thread_suspend_all_other_threads ();
3935 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
3936 mono_runtime_quit ();
3937 #ifdef PLATFORM_WIN32
3938 shutdown (conn_fd, SD_BOTH);
3939 #else
3940 shutdown (conn_fd, SHUT_RDWR);
3941 #endif
3942 DEBUG(1, fprintf (log_file, "Exiting...\n"));
3944 exit (exit_code);
3946 case CMD_VM_INVOKE_METHOD: {
3947 int objid = decode_objid (p, &p, end);
3948 MonoThread *thread;
3949 DebuggerTlsData *tls;
3950 int err;
3952 err = get_object (objid, (MonoObject**)&thread);
3953 if (err)
3954 return err;
3956 // Wait for suspending if it already started
3957 if (suspend_count)
3958 wait_for_suspend ();
3959 if (!is_suspended ())
3960 return ERR_NOT_SUSPENDED;
3962 mono_loader_lock ();
3963 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
3964 mono_loader_unlock ();
3965 g_assert (tls);
3968 * Store the invoke data into tls, the thread will execute it after it is
3969 * resumed.
3971 if (tls->invoke)
3972 NOT_IMPLEMENTED;
3973 tls->invoke = g_new0 (InvokeData, 1);
3974 tls->invoke->id = id;
3975 tls->invoke->p = g_malloc (end - p);
3976 memcpy (tls->invoke->p, p, end - p);
3977 tls->invoke->endp = tls->invoke->p + (end - p);
3979 resume_vm ();
3980 break;
3982 default:
3983 return ERR_NOT_IMPLEMENTED;
3986 return ERR_NONE;
3989 static ErrorCode
3990 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
3992 int err;
3994 switch (command) {
3995 case CMD_EVENT_REQUEST_SET: {
3996 EventRequest *req;
3997 int i, event_kind, suspend_policy, nmodifiers, mod;
3998 MonoMethod *method;
3999 long location;
4000 MonoThread *step_thread;
4001 int size, depth, step_thread_id;
4002 MonoDomain *domain;
4004 event_kind = decode_byte (p, &p, end);
4005 suspend_policy = decode_byte (p, &p, end);
4006 nmodifiers = decode_byte (p, &p, end);
4008 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
4009 req->id = InterlockedIncrement (&event_request_id);
4010 req->event_kind = event_kind;
4011 req->suspend_policy = suspend_policy;
4012 req->nmodifiers = nmodifiers;
4014 method = NULL;
4015 for (i = 0; i < nmodifiers; ++i) {
4016 mod = decode_byte (p, &p, end);
4018 req->modifiers [i].kind = mod;
4019 if (mod == MOD_KIND_COUNT) {
4020 req->modifiers [i].data.count = decode_int (p, &p, end);
4021 } else if (mod == MOD_KIND_LOCATION_ONLY) {
4022 method = decode_methodid (p, &p, end, &domain, &err);
4023 if (err)
4024 return err;
4025 location = decode_long (p, &p, end);
4026 } else if (mod == MOD_KIND_STEP) {
4027 step_thread_id = decode_id (p, &p, end);
4028 size = decode_int (p, &p, end);
4029 depth = decode_int (p, &p, end);
4030 } else if (mod == MOD_KIND_THREAD_ONLY) {
4031 int id = decode_id (p, &p, end);
4033 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
4034 if (err) {
4035 g_free (req);
4036 return err;
4038 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
4039 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
4041 if (err)
4042 return err;
4043 if (exc_class) {
4044 req->modifiers [i].data.exc_class = exc_class;
4046 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
4047 g_free (req);
4048 return ERR_INVALID_ARGUMENT;
4051 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
4052 int n = decode_int (p, &p, end);
4053 int j;
4055 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
4056 for (j = 0; j < n; ++j) {
4057 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
4058 if (err) {
4059 g_free (req->modifiers [i].data.assemblies);
4060 return err;
4063 } else {
4064 g_free (req);
4065 return ERR_NOT_IMPLEMENTED;
4069 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4070 g_assert (method);
4072 req->info = set_breakpoint (method, location, req);
4073 } else if (req->event_kind == EVENT_KIND_STEP) {
4074 g_assert (step_thread_id);
4076 err = get_object (step_thread_id, (MonoObject**)&step_thread);
4077 if (err) {
4078 g_free (req);
4079 return err;
4082 err = ss_start (THREAD_TO_INTERNAL (step_thread), size, depth, req);
4083 if (err) {
4084 g_free (req);
4085 return err;
4087 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
4088 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req);
4089 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
4090 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req);
4091 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
4092 } else {
4093 if (req->nmodifiers) {
4094 g_free (req);
4095 return ERR_NOT_IMPLEMENTED;
4099 mono_loader_lock ();
4100 g_ptr_array_add (event_requests, req);
4101 mono_loader_unlock ();
4103 buffer_add_int (buf, req->id);
4104 break;
4106 case CMD_EVENT_REQUEST_CLEAR: {
4107 int etype = decode_byte (p, &p, end);
4108 int req_id = decode_int (p, &p, end);
4110 // FIXME: Make a faster mapping from req_id to request
4111 mono_loader_lock ();
4112 clear_event_request (req_id, etype);
4113 mono_loader_unlock ();
4114 break;
4116 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
4117 int i;
4119 mono_loader_lock ();
4120 i = 0;
4121 while (i < event_requests->len) {
4122 EventRequest *req = g_ptr_array_index (event_requests, i);
4124 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4125 clear_breakpoint (req->info);
4127 g_ptr_array_remove_index_fast (event_requests, i);
4128 g_free (req);
4129 } else {
4130 i ++;
4133 mono_loader_unlock ();
4134 break;
4136 default:
4137 return ERR_NOT_IMPLEMENTED;
4140 return ERR_NONE;
4143 static ErrorCode
4144 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
4146 int err;
4147 MonoDomain *domain;
4149 switch (command) {
4150 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
4151 buffer_add_domainid (buf, mono_get_root_domain ());
4152 break;
4154 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
4155 domain = decode_domainid (p, &p, end, NULL, &err);
4156 if (err)
4157 return err;
4158 buffer_add_string (buf, domain->friendly_name);
4159 break;
4161 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
4162 GSList *tmp;
4163 MonoAssembly *ass;
4164 int count;
4166 domain = decode_domainid (p, &p, end, NULL, &err);
4167 if (err)
4168 return err;
4169 mono_loader_lock ();
4170 count = 0;
4171 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
4172 count ++;
4174 buffer_add_int (buf, count);
4175 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
4176 ass = tmp->data;
4177 buffer_add_assemblyid (buf, domain, ass);
4179 mono_loader_unlock ();
4180 break;
4182 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
4183 domain = decode_domainid (p, &p, end, NULL, &err);
4184 if (err)
4185 return err;
4187 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
4188 break;
4190 case CMD_APPDOMAIN_GET_CORLIB: {
4191 domain = decode_domainid (p, &p, end, NULL, &err);
4192 if (err)
4193 return err;
4195 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
4196 break;
4198 case CMD_APPDOMAIN_CREATE_STRING: {
4199 char *s;
4200 MonoString *o;
4202 domain = decode_domainid (p, &p, end, NULL, &err);
4203 if (err)
4204 return err;
4205 s = decode_string (p, &p, end);
4207 o = mono_string_new (domain, s);
4208 buffer_add_objid (buf, (MonoObject*)o);
4209 break;
4211 default:
4212 return ERR_NOT_IMPLEMENTED;
4215 return ERR_NONE;
4218 static ErrorCode
4219 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
4221 int err;
4222 MonoAssembly *ass;
4223 MonoDomain *domain;
4225 ass = decode_assemblyid (p, &p, end, &domain, &err);
4226 if (err)
4227 return err;
4229 switch (command) {
4230 case CMD_ASSEMBLY_GET_LOCATION: {
4231 buffer_add_string (buf, mono_image_get_filename (ass->image));
4232 break;
4234 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
4235 guint32 token;
4236 MonoMethod *m;
4238 if (ass->image->dynamic) {
4239 buffer_add_id (buf, 0);
4240 } else {
4241 token = mono_image_get_entry_point (ass->image);
4242 if (token == 0) {
4243 buffer_add_id (buf, 0);
4244 } else {
4245 m = mono_get_method (ass->image, token, NULL);
4246 buffer_add_methodid (buf, domain, m);
4249 break;
4251 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
4252 buffer_add_moduleid (buf, domain, ass->image);
4253 break;
4255 case CMD_ASSEMBLY_GET_OBJECT: {
4256 MonoObject *o = (MonoObject*)mono_assembly_get_object (mono_domain_get (), ass);
4257 buffer_add_objid (buf, o);
4258 break;
4260 case CMD_ASSEMBLY_GET_TYPE: {
4261 char *s = decode_string (p, &p, end);
4262 gboolean ignorecase = decode_byte (p, &p, end);
4263 MonoTypeNameParse info;
4264 MonoType *t;
4265 gboolean type_resolve;
4267 if (!mono_reflection_parse_type (s, &info)) {
4268 t = NULL;
4269 } else {
4270 if (info.assembly.name)
4271 NOT_IMPLEMENTED;
4272 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
4274 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
4275 mono_reflection_free_type_info (&info);
4276 g_free (s);
4278 break;
4280 default:
4281 return ERR_NOT_IMPLEMENTED;
4284 return ERR_NONE;
4287 static ErrorCode
4288 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
4290 int err;
4291 MonoDomain *domain;
4293 switch (command) {
4294 case CMD_MODULE_GET_INFO: {
4295 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
4296 char *basename;
4298 basename = g_path_get_basename (image->name);
4299 buffer_add_string (buf, basename); // name
4300 buffer_add_string (buf, image->module_name); // scopename
4301 buffer_add_string (buf, image->name); // fqname
4302 buffer_add_string (buf, mono_image_get_guid (image)); // guid
4303 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
4304 g_free (basename);
4305 break;
4307 default:
4308 return ERR_NOT_IMPLEMENTED;
4311 return ERR_NONE;
4314 static void
4315 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
4317 if (val && val->vtable->klass == mono_defaults.monotype_class) {
4318 /* Special case these so the client doesn't have to handle Type objects */
4320 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
4321 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
4322 } else if (MONO_TYPE_IS_REFERENCE (t))
4323 buffer_add_value (buf, t, &val, domain);
4324 else
4325 buffer_add_value (buf, t, mono_object_unbox (val), domain);
4328 static void
4329 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
4331 int i, j;
4332 int nattrs = 0;
4334 if (!cinfo) {
4335 buffer_add_int (buf, 0);
4336 return;
4339 for (i = 0; i < cinfo->num_attrs; ++i) {
4340 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
4341 nattrs ++;
4343 buffer_add_int (buf, nattrs);
4345 for (i = 0; i < cinfo->num_attrs; ++i) {
4346 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
4347 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
4348 MonoArray *typed_args, *named_args;
4349 MonoType *t;
4350 CattrNamedArg *arginfo;
4352 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo);
4354 buffer_add_methodid (buf, domain, attr->ctor);
4356 /* Ctor args */
4357 if (typed_args) {
4358 buffer_add_int (buf, mono_array_length (typed_args));
4359 for (j = 0; j < mono_array_length (typed_args); ++j) {
4360 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
4362 t = mono_method_signature (attr->ctor)->params [j];
4364 buffer_add_cattr_arg (buf, t, domain, val);
4366 } else {
4367 buffer_add_int (buf, 0);
4370 /* Named args */
4371 if (named_args) {
4372 buffer_add_int (buf, mono_array_length (named_args));
4374 for (j = 0; j < mono_array_length (named_args); ++j) {
4375 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
4377 if (arginfo [j].prop) {
4378 buffer_add_byte (buf, 0x54);
4379 buffer_add_propertyid (buf, domain, arginfo [j].prop);
4380 } else if (arginfo [j].field) {
4381 buffer_add_byte (buf, 0x53);
4382 } else {
4383 g_assert_not_reached ();
4386 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
4388 } else {
4389 buffer_add_int (buf, 0);
4395 static ErrorCode
4396 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
4398 MonoClass *klass;
4399 MonoDomain *domain;
4400 MonoClass *nested;
4401 MonoType *type;
4402 gpointer iter;
4403 guint8 b;
4404 int err, nnested;
4405 char *name;
4407 klass = decode_typeid (p, &p, end, &domain, &err);
4408 if (err)
4409 return err;
4411 switch (command) {
4412 case CMD_TYPE_GET_INFO: {
4413 buffer_add_string (buf, klass->name_space);
4414 buffer_add_string (buf, klass->name);
4415 // FIXME: byref
4416 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
4417 buffer_add_string (buf, name);
4418 g_free (name);
4419 buffer_add_assemblyid (buf, domain, klass->image->assembly);
4420 buffer_add_moduleid (buf, domain, klass->image);
4421 buffer_add_typeid (buf, domain, klass->parent);
4422 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
4423 buffer_add_typeid (buf, domain, klass->element_class);
4424 else
4425 buffer_add_id (buf, 0);
4426 buffer_add_int (buf, klass->type_token);
4427 buffer_add_byte (buf, klass->rank);
4428 buffer_add_int (buf, klass->flags);
4429 b = 0;
4430 type = &klass->byval_arg;
4431 // FIXME: Can't decide whenever a class represents a byref type
4432 if (FALSE)
4433 b |= (1 << 0);
4434 if (type->type == MONO_TYPE_PTR)
4435 b |= (1 << 1);
4436 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
4437 b |= (1 << 2);
4438 if (type->type == MONO_TYPE_VALUETYPE)
4439 b |= (1 << 3);
4440 buffer_add_byte (buf, b);
4441 nnested = 0;
4442 iter = NULL;
4443 while ((nested = mono_class_get_nested_types (klass, &iter)))
4444 nnested ++;
4445 buffer_add_int (buf, nnested);
4446 iter = NULL;
4447 while ((nested = mono_class_get_nested_types (klass, &iter)))
4448 buffer_add_typeid (buf, domain, nested);
4449 break;
4451 case CMD_TYPE_GET_METHODS: {
4452 int nmethods;
4453 int i = 0;
4454 gpointer iter = NULL;
4455 MonoMethod *m;
4457 nmethods = mono_class_num_methods (klass);
4459 buffer_add_int (buf, nmethods);
4461 while ((m = mono_class_get_methods (klass, &iter))) {
4462 buffer_add_methodid (buf, domain, m);
4463 i ++;
4465 g_assert (i == nmethods);
4466 break;
4468 case CMD_TYPE_GET_FIELDS: {
4469 int nfields;
4470 int i = 0;
4471 gpointer iter = NULL;
4472 MonoClassField *f;
4474 nfields = mono_class_num_fields (klass);
4476 buffer_add_int (buf, nfields);
4478 while ((f = mono_class_get_fields (klass, &iter))) {
4479 buffer_add_fieldid (buf, domain, f);
4480 buffer_add_string (buf, f->name);
4481 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
4482 buffer_add_int (buf, f->type->attrs);
4483 i ++;
4485 g_assert (i == nfields);
4486 break;
4488 case CMD_TYPE_GET_PROPERTIES: {
4489 int nprops;
4490 int i = 0;
4491 gpointer iter = NULL;
4492 MonoProperty *p;
4494 nprops = mono_class_num_properties (klass);
4496 buffer_add_int (buf, nprops);
4498 while ((p = mono_class_get_properties (klass, &iter))) {
4499 buffer_add_propertyid (buf, domain, p);
4500 buffer_add_string (buf, p->name);
4501 buffer_add_methodid (buf, domain, p->get);
4502 buffer_add_methodid (buf, domain, p->set);
4503 buffer_add_int (buf, p->attrs);
4504 i ++;
4506 g_assert (i == nprops);
4507 break;
4509 case CMD_TYPE_GET_CATTRS: {
4510 MonoClass *attr_klass = decode_typeid (p, &p, end, NULL, &err);
4511 MonoCustomAttrInfo *cinfo;
4513 cinfo = mono_custom_attrs_from_class (klass);
4515 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
4516 break;
4518 case CMD_TYPE_GET_FIELD_CATTRS: {
4519 MonoClass *attr_klass;
4520 MonoCustomAttrInfo *cinfo;
4521 MonoClassField *field;
4523 field = decode_fieldid (p, &p, end, NULL, &err);
4524 if (err)
4525 return err;
4526 attr_klass = decode_typeid (p, &p, end, NULL, &err);
4527 if (err)
4528 return err;
4530 cinfo = mono_custom_attrs_from_field (klass, field);
4532 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
4533 break;
4535 case CMD_TYPE_GET_PROPERTY_CATTRS: {
4536 MonoClass *attr_klass;
4537 MonoCustomAttrInfo *cinfo;
4538 MonoProperty *prop;
4540 prop = decode_propertyid (p, &p, end, NULL, &err);
4541 if (err)
4542 return err;
4543 attr_klass = decode_typeid (p, &p, end, NULL, &err);
4544 if (err)
4545 return err;
4547 cinfo = mono_custom_attrs_from_property (klass, prop);
4549 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
4550 break;
4552 case CMD_TYPE_GET_VALUES: {
4553 guint8 *val;
4554 MonoClassField *f;
4555 MonoVTable *vtable;
4556 MonoClass *k;
4557 int len, i;
4558 gboolean found;
4560 len = decode_int (p, &p, end);
4561 for (i = 0; i < len; ++i) {
4562 f = decode_fieldid (p, &p, end, NULL, &err);
4563 if (err)
4564 return err;
4566 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
4567 return ERR_INVALID_FIELDID;
4568 if (mono_class_field_is_special_static (f))
4569 return ERR_INVALID_FIELDID;
4571 /* Check that the field belongs to the object */
4572 found = FALSE;
4573 for (k = klass; k; k = k->parent) {
4574 if (k == f->parent) {
4575 found = TRUE;
4576 break;
4579 if (!found)
4580 return ERR_INVALID_FIELDID;
4582 vtable = mono_class_vtable (domain, f->parent);
4583 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
4584 mono_field_static_get_value (vtable, f, val);
4585 buffer_add_value (buf, f->type, val, domain);
4586 g_free (val);
4588 break;
4590 case CMD_TYPE_SET_VALUES: {
4591 guint8 *val;
4592 MonoClassField *f;
4593 MonoVTable *vtable;
4594 MonoClass *k;
4595 int len, i;
4596 gboolean found;
4598 len = decode_int (p, &p, end);
4599 for (i = 0; i < len; ++i) {
4600 f = decode_fieldid (p, &p, end, NULL, &err);
4601 if (err)
4602 return err;
4604 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
4605 return ERR_INVALID_FIELDID;
4606 if (mono_class_field_is_special_static (f))
4607 return ERR_INVALID_FIELDID;
4609 /* Check that the field belongs to the object */
4610 found = FALSE;
4611 for (k = klass; k; k = k->parent) {
4612 if (k == f->parent) {
4613 found = TRUE;
4614 break;
4617 if (!found)
4618 return ERR_INVALID_FIELDID;
4620 // FIXME: Check for literal/const
4622 vtable = mono_class_vtable (domain, f->parent);
4623 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
4624 err = decode_value (f->type, domain, val, p, &p, end);
4625 if (err) {
4626 g_free (val);
4627 return err;
4629 mono_field_static_set_value (vtable, f, val);
4630 g_free (val);
4632 break;
4634 case CMD_TYPE_GET_OBJECT: {
4635 MonoObject *o = (MonoObject*)mono_type_get_object (mono_domain_get (), &klass->byval_arg);
4636 buffer_add_objid (buf, o);
4637 break;
4639 case CMD_TYPE_GET_SOURCE_FILES: {
4640 gpointer iter = NULL;
4641 MonoMethod *method;
4642 char *source_file, *base;
4643 GPtrArray *files;
4644 int i;
4646 files = g_ptr_array_new ();
4648 while ((method = mono_class_get_methods (klass, &iter))) {
4649 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
4651 if (minfo) {
4652 mono_debug_symfile_get_line_numbers (minfo, &source_file, NULL, NULL, NULL);
4654 for (i = 0; i < files->len; ++i)
4655 if (!strcmp (g_ptr_array_index (files, i), source_file))
4656 break;
4657 if (i == files->len)
4658 g_ptr_array_add (files, g_strdup (source_file));
4659 g_free (source_file);
4663 buffer_add_int (buf, files->len);
4664 for (i = 0; i < files->len; ++i) {
4665 source_file = g_ptr_array_index (files, i);
4666 base = g_path_get_basename (source_file);
4667 buffer_add_string (buf, base);
4668 g_free (base);
4669 g_free (source_file);
4671 g_ptr_array_free (files, TRUE);
4672 break;
4674 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
4675 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
4677 if (err)
4678 return err;
4679 if (mono_class_is_assignable_from (klass, oklass))
4680 buffer_add_byte (buf, 1);
4681 else
4682 buffer_add_byte (buf, 0);
4683 break;
4685 default:
4686 return ERR_NOT_IMPLEMENTED;
4689 return ERR_NONE;
4692 static ErrorCode
4693 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
4695 int err;
4696 MonoDomain *domain;
4697 MonoMethod *method;
4698 MonoMethodHeader *header;
4700 method = decode_methodid (p, &p, end, &domain, &err);
4701 if (err)
4702 return err;
4704 switch (command) {
4705 case CMD_METHOD_GET_NAME: {
4706 buffer_add_string (buf, method->name);
4707 break;
4709 case CMD_METHOD_GET_DECLARING_TYPE: {
4710 buffer_add_typeid (buf, domain, method->klass);
4711 break;
4713 case CMD_METHOD_GET_DEBUG_INFO: {
4714 MonoDebugMethodInfo *minfo;
4715 char *source_file;
4716 int i, n_il_offsets;
4717 int *il_offsets;
4718 int *line_numbers;
4720 header = mono_method_get_header (method);
4721 if (!header) {
4722 buffer_add_int (buf, 0);
4723 buffer_add_string (buf, "");
4724 buffer_add_int (buf, 0);
4725 break;
4728 minfo = mono_debug_lookup_method (method);
4729 if (!minfo) {
4730 buffer_add_int (buf, header->code_size);
4731 buffer_add_string (buf, "");
4732 buffer_add_int (buf, 0);
4733 break;
4736 mono_debug_symfile_get_line_numbers (minfo, &source_file, &n_il_offsets, &il_offsets, &line_numbers);
4737 buffer_add_int (buf, header->code_size);
4738 buffer_add_string (buf, source_file);
4739 buffer_add_int (buf, n_il_offsets);
4740 //printf ("Line number table for method %s:\n", mono_method_full_name (method, TRUE));
4741 for (i = 0; i < n_il_offsets; ++i) {
4742 //printf ("IL%d -> %d\n", il_offsets [i], line_numbers [i]);
4743 buffer_add_int (buf, il_offsets [i]);
4744 buffer_add_int (buf, line_numbers [i]);
4746 g_free (source_file);
4747 g_free (il_offsets);
4748 g_free (line_numbers);
4749 break;
4751 case CMD_METHOD_GET_PARAM_INFO: {
4752 MonoMethodSignature *sig = mono_method_signature (method);
4753 guint32 i;
4754 char **names;
4756 /* FIXME: mono_class_from_mono_type () and byrefs */
4758 /* FIXME: Use a smaller encoding */
4759 buffer_add_int (buf, sig->call_convention);
4760 buffer_add_int (buf, sig->param_count);
4761 buffer_add_int (buf, sig->generic_param_count);
4762 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
4763 for (i = 0; i < sig->param_count; ++i) {
4764 /* FIXME: vararg */
4765 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
4768 /* Emit parameter names */
4769 names = g_new (char *, sig->param_count);
4770 mono_method_get_param_names (method, (const char **) names);
4771 for (i = 0; i < sig->param_count; ++i)
4772 buffer_add_string (buf, names [i]);
4773 g_free (names);
4775 break;
4777 case CMD_METHOD_GET_LOCALS_INFO: {
4778 int i, j, num_locals;
4779 char **local_names;
4780 int *local_indexes;
4782 header = mono_method_get_header (method);
4783 g_assert (header);
4785 buffer_add_int (buf, header->num_locals);
4787 /* Types */
4788 for (i = 0; i < header->num_locals; ++i)
4789 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
4791 /* Names */
4792 num_locals = mono_debug_lookup_locals (method, &local_names, &local_indexes);
4793 for (i = 0; i < header->num_locals; ++i) {
4794 for (j = 0; j < num_locals; ++j)
4795 if (local_indexes [j] == i)
4796 break;
4797 if (j < num_locals)
4798 buffer_add_string (buf, local_names [j]);
4799 else
4800 buffer_add_string (buf, "");
4802 g_free (local_names);
4803 g_free (local_indexes);
4805 /* Live ranges */
4806 /* FIXME: This works because we set debug_options.mdb_optimizations */
4807 for (i = 0; i < header->num_locals; ++i) {
4808 buffer_add_int (buf, 0);
4809 buffer_add_int (buf, header->code_size);
4812 break;
4814 case CMD_METHOD_GET_INFO:
4815 buffer_add_int (buf, method->flags);
4816 buffer_add_int (buf, method->iflags);
4817 buffer_add_int (buf, method->token);
4818 break;
4819 case CMD_METHOD_GET_BODY: {
4820 int i;
4822 header = mono_method_get_header (method);
4823 if (!header) {
4824 buffer_add_int (buf, 0);
4825 } else {
4826 buffer_add_int (buf, header->code_size);
4827 for (i = 0; i < header->code_size; ++i)
4828 buffer_add_byte (buf, header->code [i]);
4830 break;
4832 case CMD_METHOD_RESOLVE_TOKEN: {
4833 guint32 token = decode_int (p, &p, end);
4835 // FIXME: Generics
4836 switch (mono_metadata_token_code (token)) {
4837 case MONO_TOKEN_STRING: {
4838 MonoString *s;
4839 char *s2;
4841 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
4842 g_assert (s);
4844 s2 = mono_string_to_utf8 (s);
4846 buffer_add_byte (buf, TOKEN_TYPE_STRING);
4847 buffer_add_string (buf, s2);
4848 g_free (s2);
4849 break;
4851 default: {
4852 gpointer val;
4853 MonoClass *handle_class;
4855 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
4856 val = mono_method_get_wrapper_data (method, token);
4857 handle_class = mono_method_get_wrapper_data (method, token + 1);
4859 if (handle_class == NULL) {
4860 // Can't figure out the token type
4861 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
4862 break;
4864 } else {
4865 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
4866 g_assert (val);
4869 if (handle_class == mono_defaults.typehandle_class) {
4870 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
4871 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
4872 } else if (handle_class == mono_defaults.fieldhandle_class) {
4873 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
4874 buffer_add_fieldid (buf, domain, val);
4875 } else if (handle_class == mono_defaults.methodhandle_class) {
4876 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
4877 buffer_add_methodid (buf, domain, val);
4878 } else if (handle_class == mono_defaults.string_class) {
4879 char *s;
4881 s = mono_string_to_utf8 (val);
4882 buffer_add_byte (buf, TOKEN_TYPE_STRING);
4883 buffer_add_string (buf, s);
4884 g_free (s);
4885 } else {
4886 g_assert_not_reached ();
4888 break;
4891 break;
4893 default:
4894 return ERR_NOT_IMPLEMENTED;
4897 return ERR_NONE;
4900 static ErrorCode
4901 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
4903 int objid = decode_objid (p, &p, end);
4904 int err;
4905 MonoThread *thread_obj;
4906 MonoInternalThread *thread;
4908 err = get_object (objid, (MonoObject**)&thread_obj);
4909 if (err)
4910 return err;
4912 thread = THREAD_TO_INTERNAL (thread_obj);
4914 switch (command) {
4915 case CMD_THREAD_GET_NAME: {
4916 guint32 name_len;
4917 gunichar2 *s = mono_thread_get_name (thread, &name_len);
4919 if (!s) {
4920 buffer_add_int (buf, 0);
4921 } else {
4922 char *name;
4923 glong len;
4925 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
4926 g_assert (name);
4927 buffer_add_int (buf, len);
4928 buffer_add_data (buf, (guint8*)name, len);
4929 g_free (s);
4931 break;
4933 case CMD_THREAD_GET_FRAME_INFO: {
4934 DebuggerTlsData *tls;
4935 int i, start_frame, length;
4937 // Wait for suspending if it already started
4938 if (suspend_count)
4939 wait_for_suspend ();
4940 if (!is_suspended ())
4941 return ERR_NOT_SUSPENDED;
4943 start_frame = decode_int (p, &p, end);
4944 length = decode_int (p, &p, end);
4946 if (start_frame != 0 || length != -1)
4947 return ERR_NOT_IMPLEMENTED;
4949 mono_loader_lock ();
4950 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4951 mono_loader_unlock ();
4952 g_assert (tls);
4954 compute_frame_info (thread, tls);
4956 buffer_add_int (buf, tls->frame_count);
4957 for (i = 0; i < tls->frame_count; ++i) {
4958 buffer_add_int (buf, tls->frames [i]->id);
4959 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->method);
4960 buffer_add_int (buf, tls->frames [i]->il_offset);
4962 * Instead of passing the frame type directly to the client, we associate
4963 * it with the previous frame using a set of flags. This avoids lots of
4964 * conditional code in the client, since a frame whose type isn't
4965 * FRAME_TYPE_MANAGED has no method, location, etc.
4967 buffer_add_byte (buf, tls->frames [i]->flags);
4970 break;
4972 case CMD_THREAD_GET_STATE:
4973 buffer_add_int (buf, thread->state);
4974 break;
4975 case CMD_THREAD_GET_INFO:
4976 buffer_add_byte (buf, thread->threadpool_thread);
4977 break;
4978 default:
4979 return ERR_NOT_IMPLEMENTED;
4982 return ERR_NONE;
4985 static ErrorCode
4986 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
4988 int objid;
4989 int err;
4990 MonoThread *thread_obj;
4991 MonoInternalThread *thread;
4992 int pos, i, len;
4993 DebuggerTlsData *tls;
4994 StackFrame *frame;
4995 MonoDebugMethodJitInfo *jit;
4996 MonoDebugVarInfo *var;
4997 MonoMethodSignature *sig;
4998 gssize id;
4999 MonoMethodHeader *header;
5001 objid = decode_objid (p, &p, end);
5002 err = get_object (objid, (MonoObject**)&thread_obj);
5003 if (err)
5004 return err;
5006 thread = THREAD_TO_INTERNAL (thread_obj);
5008 id = decode_id (p, &p, end);
5010 mono_loader_lock ();
5011 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5012 mono_loader_unlock ();
5013 g_assert (tls);
5015 for (i = 0; i < tls->frame_count; ++i) {
5016 if (tls->frames [i]->id == id)
5017 break;
5019 if (i == tls->frame_count)
5020 return ERR_INVALID_FRAMEID;
5022 frame = tls->frames [i];
5024 if (!frame->jit) {
5025 frame->jit = mono_debug_find_method (frame->method, frame->domain);
5026 g_assert (frame->jit);
5028 jit = frame->jit;
5030 sig = mono_method_signature (frame->method);
5032 switch (command) {
5033 case CMD_STACK_FRAME_GET_VALUES: {
5034 len = decode_int (p, &p, end);
5035 header = mono_method_get_header (frame->method);
5037 for (i = 0; i < len; ++i) {
5038 pos = decode_int (p, &p, end);
5040 if (pos < 0) {
5041 pos = - pos - 1;
5043 g_assert (pos >= 0 && pos < jit->num_params);
5045 var = &jit->params [pos];
5047 add_var (buf, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain);
5048 } else {
5049 g_assert (pos >= 0 && pos < jit->num_locals);
5051 var = &jit->locals [pos];
5053 add_var (buf, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain);
5056 break;
5058 case CMD_STACK_FRAME_GET_THIS: {
5059 if (frame->method->klass->valuetype) {
5060 if (!sig->hasthis) {
5061 MonoObject *p = NULL;
5062 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
5063 } else {
5064 add_var (buf, &frame->method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain);
5066 } else {
5067 if (!sig->hasthis) {
5068 MonoObject *p = NULL;
5069 buffer_add_value (buf, &frame->method->klass->byval_arg, &p, frame->domain);
5070 } else {
5071 add_var (buf, &frame->method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain);
5074 break;
5076 case CMD_STACK_FRAME_SET_VALUES: {
5077 guint8 *val_buf;
5078 MonoType *t;
5079 MonoDebugVarInfo *var;
5081 len = decode_int (p, &p, end);
5082 header = mono_method_get_header (frame->method);
5084 for (i = 0; i < len; ++i) {
5085 pos = decode_int (p, &p, end);
5087 if (pos < 0) {
5088 pos = - pos - 1;
5090 g_assert (pos >= 0 && pos < jit->num_params);
5092 t = sig->params [pos];
5093 var = &jit->params [pos];
5094 } else {
5095 g_assert (pos >= 0 && pos < jit->num_locals);
5097 t = header->locals [pos];
5098 var = &jit->locals [pos];
5101 if (MONO_TYPE_IS_REFERENCE (t))
5102 val_buf = g_alloca (sizeof (MonoObject*));
5103 else
5104 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
5105 err = decode_value (t, frame->domain, val_buf, p, &p, end);
5106 if (err)
5107 return err;
5109 set_var (t, var, &frame->ctx, frame->domain, val_buf);
5111 break;
5113 default:
5114 return ERR_NOT_IMPLEMENTED;
5117 return ERR_NONE;
5120 static ErrorCode
5121 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5123 MonoArray *arr;
5124 int objid, err, index, len, i, esize;
5125 gpointer elem;
5127 objid = decode_objid (p, &p, end);
5128 err = get_object (objid, (MonoObject**)&arr);
5129 if (err)
5130 return err;
5132 switch (command) {
5133 case CMD_ARRAY_REF_GET_LENGTH:
5134 buffer_add_int (buf, arr->obj.vtable->klass->rank);
5135 if (!arr->bounds) {
5136 buffer_add_int (buf, arr->max_length);
5137 buffer_add_int (buf, 0);
5138 } else {
5139 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
5140 buffer_add_int (buf, arr->bounds [i].length);
5141 buffer_add_int (buf, arr->bounds [i].lower_bound);
5144 break;
5145 case CMD_ARRAY_REF_GET_VALUES:
5146 index = decode_int (p, &p, end);
5147 len = decode_int (p, &p, end);
5149 g_assert (index >= 0 && len >= 0);
5150 // Reordered to avoid integer overflow
5151 g_assert (!(index > arr->max_length - len));
5153 esize = mono_array_element_size (arr->obj.vtable->klass);
5154 for (i = index; i < index + len; ++i) {
5155 elem = (gpointer*)((char*)arr->vector + (i * esize));
5156 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
5158 break;
5159 case CMD_ARRAY_REF_SET_VALUES:
5160 index = decode_int (p, &p, end);
5161 len = decode_int (p, &p, end);
5163 g_assert (index >= 0 && len >= 0);
5164 // Reordered to avoid integer overflow
5165 g_assert (!(index > arr->max_length - len));
5167 esize = mono_array_element_size (arr->obj.vtable->klass);
5168 for (i = index; i < index + len; ++i) {
5169 elem = (gpointer*)((char*)arr->vector + (i * esize));
5171 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
5173 break;
5174 default:
5175 return ERR_NOT_IMPLEMENTED;
5178 return ERR_NONE;
5181 static ErrorCode
5182 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5184 int objid, err;
5185 MonoString *str;
5186 char *s;
5188 objid = decode_objid (p, &p, end);
5189 err = get_object (objid, (MonoObject**)&str);
5190 if (err)
5191 return err;
5193 switch (command) {
5194 case CMD_STRING_REF_GET_VALUE:
5195 s = mono_string_to_utf8 (str);
5196 buffer_add_string (buf, s);
5197 g_free (s);
5198 break;
5199 default:
5200 return ERR_NOT_IMPLEMENTED;
5203 return ERR_NONE;
5206 static ErrorCode
5207 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
5209 int objid, err;
5210 MonoObject *obj;
5211 int len, i;
5212 MonoClassField *f;
5213 MonoClass *k;
5214 gboolean found;
5216 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
5217 objid = decode_objid (p, &p, end);
5218 err = get_object (objid, &obj);
5219 if (err)
5220 buffer_add_int (buf, 1);
5221 else
5222 buffer_add_int (buf, 0);
5223 return 0;
5226 objid = decode_objid (p, &p, end);
5227 err = get_object (objid, &obj);
5228 if (err)
5229 return err;
5231 switch (command) {
5232 case CMD_OBJECT_REF_GET_TYPE:
5233 buffer_add_typeid (buf, obj->vtable->domain, obj->vtable->klass);
5234 break;
5235 case CMD_OBJECT_REF_GET_VALUES:
5236 len = decode_int (p, &p, end);
5238 for (i = 0; i < len; ++i) {
5239 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
5240 if (err)
5241 return err;
5243 /* Check that the field belongs to the object */
5244 found = FALSE;
5245 for (k = obj->vtable->klass; k; k = k->parent) {
5246 if (k == f->parent) {
5247 found = TRUE;
5248 break;
5251 if (!found)
5252 return ERR_INVALID_FIELDID;
5254 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
5255 guint8 *val;
5256 MonoVTable *vtable;
5258 if (mono_class_field_is_special_static (f))
5259 return ERR_INVALID_FIELDID;
5261 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
5262 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
5263 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
5264 mono_field_static_get_value (vtable, f, val);
5265 buffer_add_value (buf, f->type, val, obj->vtable->domain);
5266 g_free (val);
5267 } else {
5268 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
5271 break;
5272 case CMD_OBJECT_REF_SET_VALUES:
5273 len = decode_int (p, &p, end);
5275 for (i = 0; i < len; ++i) {
5276 f = decode_fieldid (p, &p, end, NULL, &err);
5277 if (err)
5278 return err;
5280 /* Check that the field belongs to the object */
5281 found = FALSE;
5282 for (k = obj->vtable->klass; k; k = k->parent) {
5283 if (k == f->parent) {
5284 found = TRUE;
5285 break;
5288 if (!found)
5289 return ERR_INVALID_FIELDID;
5291 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
5292 guint8 *val;
5293 MonoVTable *vtable;
5295 if (mono_class_field_is_special_static (f))
5296 return ERR_INVALID_FIELDID;
5298 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
5299 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
5301 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
5302 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
5303 if (err) {
5304 g_free (val);
5305 return err;
5307 mono_field_static_set_value (vtable, f, val);
5308 g_free (val);
5309 } else {
5310 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
5311 if (err)
5312 return err;
5315 break;
5316 case CMD_OBJECT_REF_GET_ADDRESS:
5317 buffer_add_long (buf, (gssize)obj);
5318 break;
5319 case CMD_OBJECT_REF_GET_DOMAIN:
5320 buffer_add_domainid (buf, obj->vtable->domain);
5321 break;
5322 default:
5323 return ERR_NOT_IMPLEMENTED;
5326 return ERR_NONE;
5329 static const char*
5330 command_set_to_string (CommandSet command_set)
5332 switch (command_set) {
5333 case CMD_SET_VM:
5334 return "VM";
5335 case CMD_SET_OBJECT_REF:
5336 return "OBJECT_REF";
5337 case CMD_SET_STRING_REF:
5338 return "STRING_REF";
5339 case CMD_SET_THREAD:
5340 return "THREAD";
5341 case CMD_SET_ARRAY_REF:
5342 return "ARRAY_REF";
5343 case CMD_SET_EVENT_REQUEST:
5344 return "EVENT_REQUEST";
5345 case CMD_SET_STACK_FRAME:
5346 return "STACK_FRAME";
5347 case CMD_SET_APPDOMAIN:
5348 return "APPDOMAIN";
5349 case CMD_SET_ASSEMBLY:
5350 return "ASSEMBLY";
5351 case CMD_SET_METHOD:
5352 return "METHOD";
5353 case CMD_SET_TYPE:
5354 return "TYPE";
5355 case CMD_SET_MODULE:
5356 return "MODULE";
5357 case CMD_SET_EVENT:
5358 return "EVENT";
5359 default:
5360 return "";
5365 * debugger_thread:
5367 * This thread handles communication with the debugger client using a JDWP
5368 * like protocol.
5370 static guint32 WINAPI
5371 debugger_thread (void *arg)
5373 int res, len, id, flags, command_set, command;
5374 guint8 header [HEADER_LENGTH];
5375 guint8 *data, *p, *end;
5376 Buffer buf;
5377 ErrorCode err;
5378 gboolean no_reply;
5380 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
5382 debugger_thread_id = GetCurrentThreadId ();
5384 mono_jit_thread_attach (mono_get_root_domain ());
5386 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
5388 mono_set_is_debugger_attached (TRUE);
5390 while (TRUE) {
5391 res = read (conn_fd, header, HEADER_LENGTH);
5393 /* This will break if the socket is closed during shutdown too */
5394 if (res != HEADER_LENGTH)
5395 break;
5397 p = header;
5398 end = header + HEADER_LENGTH;
5400 len = decode_int (p, &p, end);
5401 id = decode_int (p, &p, end);
5402 flags = decode_byte (p, &p, end);
5403 command_set = decode_byte (p, &p, end);
5404 command = decode_byte (p, &p, end);
5406 g_assert (flags == 0);
5408 DEBUG (1, fprintf (log_file, "[dbg] Received command %s(%d), id=%d.\n", command_set_to_string (command_set), command, id));
5410 data = g_malloc (len - HEADER_LENGTH);
5411 res = read (conn_fd, data, len - HEADER_LENGTH);
5412 if (res != len - HEADER_LENGTH)
5413 break;
5415 p = data;
5416 end = data + (len - HEADER_LENGTH);
5418 buffer_init (&buf, 128);
5420 err = ERR_NONE;
5421 no_reply = FALSE;
5423 /* Process the request */
5424 switch (command_set) {
5425 case CMD_SET_VM:
5426 err = vm_commands (command, id, p, end, &buf);
5427 if (!err && command == CMD_VM_INVOKE_METHOD)
5428 /* Sent after the invoke is complete */
5429 no_reply = TRUE;
5430 break;
5431 case CMD_SET_EVENT_REQUEST:
5432 err = event_commands (command, p, end, &buf);
5433 break;
5434 case CMD_SET_APPDOMAIN:
5435 err = domain_commands (command, p, end, &buf);
5436 break;
5437 case CMD_SET_ASSEMBLY:
5438 err = assembly_commands (command, p, end, &buf);
5439 break;
5440 case CMD_SET_MODULE:
5441 err = module_commands (command, p, end, &buf);
5442 break;
5443 case CMD_SET_TYPE:
5444 err = type_commands (command, p, end, &buf);
5445 break;
5446 case CMD_SET_METHOD:
5447 err = method_commands (command, p, end, &buf);
5448 break;
5449 case CMD_SET_THREAD:
5450 err = thread_commands (command, p, end, &buf);
5451 break;
5452 case CMD_SET_STACK_FRAME:
5453 err = frame_commands (command, p, end, &buf);
5454 break;
5455 case CMD_SET_ARRAY_REF:
5456 err = array_commands (command, p, end, &buf);
5457 break;
5458 case CMD_SET_STRING_REF:
5459 err = string_commands (command, p, end, &buf);
5460 break;
5461 case CMD_SET_OBJECT_REF:
5462 err = object_commands (command, p, end, &buf);
5463 break;
5464 default:
5465 err = ERR_NOT_IMPLEMENTED;
5468 if (!no_reply)
5469 send_reply_packet (id, err, &buf);
5471 g_free (data);
5472 buffer_free (&buf);
5474 if (command_set == CMD_SET_VM && command == CMD_VM_DISPOSE)
5475 break;
5478 mono_set_is_debugger_attached (FALSE);
5480 mono_mutex_lock (&debugger_thread_exited_mutex);
5481 debugger_thread_exited = TRUE;
5482 mono_cond_signal (&debugger_thread_exited_cond);
5483 mono_mutex_unlock (&debugger_thread_exited_mutex);
5485 #ifdef PLATFORM_WIN32
5486 shutdown (conn_fd, SD_BOTH);
5487 #else
5488 shutdown (conn_fd, SHUT_RDWR);
5489 #endif
5491 return 0;
5494 #else /* DISABLE_DEBUGGER_AGENT */
5496 void
5497 mono_debugger_agent_parse_options (char *options)
5499 g_error ("This runtime is configure with the debugger agent disabled.");
5502 void
5503 mono_debugger_agent_init (void)
5507 void
5508 mono_debugger_agent_cleanup (void)
5512 void
5513 mono_debugger_agent_breakpoint_hit (void *sigctx)
5517 void
5518 mono_debugger_agent_single_step_event (void *sigctx)
5522 void
5523 mono_debugger_agent_free_domain_info (MonoDomain *domain)
5527 gboolean mono_debugger_agent_thread_interrupt (MonoJitInfo *ji)
5531 void
5532 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *ctx)
5536 void
5537 mono_debugger_agent_handle_unhandled_exception (MonoException *exc, MonoContext *ctx)
5541 #endif