[mini] set MONO_ARCH_HAVE_INIT_LMF_EXT on architectures that implement mono_arch_init...
[mono-project.git] / mono / mini / debugger-agent.c
blobbfdddb37547e5dac5d9f4f094b1084d87b359826
1 /**
2 * \file
3 * Soft Debugger back-end module
5 * Author:
6 * Zoltan Varga (vargaz@gmail.com)
8 * Copyright 2009-2010 Novell, Inc.
9 * Copyright 2011 Xamarin Inc.
10 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
13 #include <config.h>
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <string.h>
17 #ifdef HAVE_SYS_TYPES_H
18 #include <sys/types.h>
19 #endif
20 #ifdef HAVE_SYS_SELECT_H
21 #include <sys/select.h>
22 #endif
23 #ifdef HAVE_SYS_SOCKET_H
24 #include <sys/socket.h>
25 #endif
26 #ifdef HAVE_NETINET_TCP_H
27 #include <netinet/tcp.h>
28 #endif
29 #ifdef HAVE_NETINET_IN_H
30 #include <netinet/in.h>
31 #endif
32 #ifdef HAVE_UNISTD_H
33 #include <unistd.h>
34 #endif
35 #include <errno.h>
36 #include <glib.h>
38 #ifdef HAVE_PTHREAD_H
39 #include <pthread.h>
40 #endif
42 #ifdef HOST_WIN32
43 #ifdef _MSC_VER
44 #include <winsock2.h>
45 #include <process.h>
46 #endif
47 #include <ws2tcpip.h>
48 #endif
50 #ifdef PLATFORM_ANDROID
51 #include <linux/in.h>
52 #include <linux/tcp.h>
53 #include <sys/endian.h>
54 #endif
56 #include <mono/metadata/mono-debug.h>
57 #include <mono/metadata/debug-internals.h>
58 #include <mono/metadata/gc-internals.h>
59 #include <mono/metadata/environment.h>
60 #include <mono/metadata/threads-types.h>
61 #include <mono/metadata/threadpool.h>
62 #include <mono/metadata/assembly.h>
63 #include <mono/metadata/runtime.h>
64 #include <mono/metadata/verify-internals.h>
65 #include <mono/metadata/reflection-internals.h>
66 #include <mono/metadata/w32socket.h>
67 #include <mono/utils/mono-coop-mutex.h>
68 #include <mono/utils/mono-coop-semaphore.h>
69 #include <mono/utils/mono-error-internals.h>
70 #include <mono/utils/mono-stack-unwinding.h>
71 #include <mono/utils/mono-time.h>
72 #include <mono/utils/mono-threads.h>
73 #include <mono/utils/networking.h>
74 #include <mono/utils/mono-proclib.h>
75 #include <mono/utils/w32api.h>
76 #include "debugger-agent.h"
77 #include "mini.h"
78 #include "seq-points.h"
79 #include "interp/interp.h"
82 * On iOS we can't use System.Environment.Exit () as it will do the wrong
83 * shutdown sequence.
85 #if !defined (TARGET_IOS)
86 #define TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
87 #endif
90 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
91 #define DISABLE_DEBUGGER_AGENT 1
92 #endif
94 #ifdef DISABLE_SOFT_DEBUG
95 #define DISABLE_DEBUGGER_AGENT 1
96 #endif
98 #ifndef DISABLE_DEBUGGER_AGENT
100 #include <mono/utils/mono-os-mutex.h>
102 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
104 typedef struct {
105 gboolean enabled;
106 char *transport;
107 char *address;
108 int log_level;
109 char *log_file;
110 gboolean suspend;
111 gboolean server;
112 gboolean onuncaught;
113 GSList *onthrow;
114 int timeout;
115 char *launch;
116 gboolean embedding;
117 gboolean defer;
118 int keepalive;
119 gboolean setpgid;
120 } AgentConfig;
122 typedef struct
124 int id;
125 guint32 il_offset, native_offset;
126 MonoDomain *domain;
127 MonoMethod *method;
129 * If method is gshared, this is the actual instance, otherwise this is equal to
130 * method.
132 MonoMethod *actual_method;
134 * This is the method which is visible to debugger clients. Same as method,
135 * except for native-to-managed wrappers.
137 MonoMethod *api_method;
138 MonoContext ctx;
139 MonoDebugMethodJitInfo *jit;
140 MonoJitInfo *ji;
141 MonoInterpFrameHandle interp_frame;
142 int flags;
143 mgreg_t *reg_locations [MONO_MAX_IREGS];
145 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
146 * the frame can become invalid.
148 gboolean has_ctx;
149 } StackFrame;
151 typedef struct _InvokeData InvokeData;
153 struct _InvokeData
155 int id;
156 int flags;
157 guint8 *p;
158 guint8 *endp;
159 /* This is the context which needs to be restored after the invoke */
160 MonoContext ctx;
161 gboolean has_ctx;
163 * If this is set, invoke this method with the arguments given by ARGS.
165 MonoMethod *method;
166 gpointer *args;
167 guint32 suspend_count;
168 int nmethods;
170 InvokeData *last_invoke;
173 typedef struct {
174 MonoThreadUnwindState context;
176 /* This is computed on demand when it is requested using the wire protocol */
177 /* It is freed up when the thread is resumed */
178 int frame_count;
179 StackFrame **frames;
181 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
182 * re-compute it.
184 gboolean frames_up_to_date;
186 * Points to data about a pending invoke which needs to be executed after the thread
187 * resumes.
189 InvokeData *pending_invoke;
191 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
192 * native code.
194 gboolean suspended;
196 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
197 * within a finite amount of time.
199 gboolean suspending;
201 * Set to TRUE if this thread is suspended in suspend_current ().
203 gboolean really_suspended;
204 /* Used to pass the context to the breakpoint/single step handler */
205 MonoContext handler_ctx;
206 /* Whenever thread_stop () was called for this thread */
207 gboolean terminated;
209 /* Whenever to disable breakpoints (used during invokes) */
210 gboolean disable_breakpoints;
213 * Number of times this thread has been resumed using resume_thread ().
215 guint32 resume_count;
217 MonoInternalThread *thread;
220 * Information about the frame which transitioned to native code for running
221 * threads.
223 StackFrameInfo async_last_frame;
226 * The context where the stack walk can be started for running threads.
228 MonoThreadUnwindState async_state;
231 * The context used for filter clauses
233 MonoThreadUnwindState filter_state;
235 gboolean abort_requested;
238 * The current mono_runtime_invoke_checked invocation.
240 InvokeData *invoke;
243 * The context where single stepping should resume while the thread is suspended because
244 * of an EXCEPTION event.
246 MonoThreadUnwindState catch_state;
249 * The context which needs to be restored after handling a single step/breakpoint
250 * event. This is the same as the ctx at step/breakpoint site, but includes changes
251 * to caller saved registers done by set_var ().
253 MonoThreadUnwindState restore_state;
254 /* Frames computed from restore_state */
255 int restore_frame_count;
256 StackFrame **restore_frames;
258 /* The currently unloading appdomain */
259 MonoDomain *domain_unloading;
260 } DebuggerTlsData;
262 typedef struct {
263 const char *name;
264 void (*connect) (const char *address);
265 void (*close1) (void);
266 void (*close2) (void);
267 gboolean (*send) (void *buf, int len);
268 int (*recv) (void *buf, int len);
269 } DebuggerTransport;
272 * Wire Protocol definitions
275 #define HEADER_LENGTH 11
277 #define MAJOR_VERSION 2
278 #define MINOR_VERSION 45
280 typedef enum {
281 CMD_SET_VM = 1,
282 CMD_SET_OBJECT_REF = 9,
283 CMD_SET_STRING_REF = 10,
284 CMD_SET_THREAD = 11,
285 CMD_SET_ARRAY_REF = 13,
286 CMD_SET_EVENT_REQUEST = 15,
287 CMD_SET_STACK_FRAME = 16,
288 CMD_SET_APPDOMAIN = 20,
289 CMD_SET_ASSEMBLY = 21,
290 CMD_SET_METHOD = 22,
291 CMD_SET_TYPE = 23,
292 CMD_SET_MODULE = 24,
293 CMD_SET_FIELD = 25,
294 CMD_SET_EVENT = 64
295 } CommandSet;
297 typedef enum {
298 EVENT_KIND_VM_START = 0,
299 EVENT_KIND_VM_DEATH = 1,
300 EVENT_KIND_THREAD_START = 2,
301 EVENT_KIND_THREAD_DEATH = 3,
302 EVENT_KIND_APPDOMAIN_CREATE = 4,
303 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
304 EVENT_KIND_METHOD_ENTRY = 6,
305 EVENT_KIND_METHOD_EXIT = 7,
306 EVENT_KIND_ASSEMBLY_LOAD = 8,
307 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
308 EVENT_KIND_BREAKPOINT = 10,
309 EVENT_KIND_STEP = 11,
310 EVENT_KIND_TYPE_LOAD = 12,
311 EVENT_KIND_EXCEPTION = 13,
312 EVENT_KIND_KEEPALIVE = 14,
313 EVENT_KIND_USER_BREAK = 15,
314 EVENT_KIND_USER_LOG = 16
315 } EventKind;
317 typedef enum {
318 SUSPEND_POLICY_NONE = 0,
319 SUSPEND_POLICY_EVENT_THREAD = 1,
320 SUSPEND_POLICY_ALL = 2
321 } SuspendPolicy;
323 typedef enum {
324 ERR_NONE = 0,
325 ERR_INVALID_OBJECT = 20,
326 ERR_INVALID_FIELDID = 25,
327 ERR_INVALID_FRAMEID = 30,
328 ERR_NOT_IMPLEMENTED = 100,
329 ERR_NOT_SUSPENDED = 101,
330 ERR_INVALID_ARGUMENT = 102,
331 ERR_UNLOADED = 103,
332 ERR_NO_INVOCATION = 104,
333 ERR_ABSENT_INFORMATION = 105,
334 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
335 ERR_INVOKE_ABORTED = 107,
336 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
337 } ErrorCode;
339 typedef enum {
340 MOD_KIND_COUNT = 1,
341 MOD_KIND_THREAD_ONLY = 3,
342 MOD_KIND_LOCATION_ONLY = 7,
343 MOD_KIND_EXCEPTION_ONLY = 8,
344 MOD_KIND_STEP = 10,
345 MOD_KIND_ASSEMBLY_ONLY = 11,
346 MOD_KIND_SOURCE_FILE_ONLY = 12,
347 MOD_KIND_TYPE_NAME_ONLY = 13,
348 MOD_KIND_NONE = 14
349 } ModifierKind;
351 typedef enum {
352 STEP_DEPTH_INTO = 0,
353 STEP_DEPTH_OVER = 1,
354 STEP_DEPTH_OUT = 2
355 } StepDepth;
357 typedef enum {
358 STEP_SIZE_MIN = 0,
359 STEP_SIZE_LINE = 1
360 } StepSize;
362 typedef enum {
363 STEP_FILTER_NONE = 0,
364 STEP_FILTER_STATIC_CTOR = 1,
365 STEP_FILTER_DEBUGGER_HIDDEN = 2,
366 STEP_FILTER_DEBUGGER_STEP_THROUGH = 4,
367 STEP_FILTER_DEBUGGER_NON_USER_CODE = 8
368 } StepFilter;
370 typedef enum {
371 TOKEN_TYPE_STRING = 0,
372 TOKEN_TYPE_TYPE = 1,
373 TOKEN_TYPE_FIELD = 2,
374 TOKEN_TYPE_METHOD = 3,
375 TOKEN_TYPE_UNKNOWN = 4
376 } DebuggerTokenType;
378 typedef enum {
379 VALUE_TYPE_ID_NULL = 0xf0,
380 VALUE_TYPE_ID_TYPE = 0xf1,
381 VALUE_TYPE_ID_PARENT_VTYPE = 0xf2
382 } ValueTypeId;
384 typedef enum {
385 FRAME_FLAG_DEBUGGER_INVOKE = 1,
386 FRAME_FLAG_NATIVE_TRANSITION = 2
387 } StackFrameFlags;
389 typedef enum {
390 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
391 INVOKE_FLAG_SINGLE_THREADED = 2,
392 INVOKE_FLAG_RETURN_OUT_THIS = 4,
393 INVOKE_FLAG_RETURN_OUT_ARGS = 8,
394 INVOKE_FLAG_VIRTUAL = 16
395 } InvokeFlags;
397 typedef enum {
398 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
399 } BindingFlagsExtensions;
401 typedef enum {
402 CMD_VM_VERSION = 1,
403 CMD_VM_ALL_THREADS = 2,
404 CMD_VM_SUSPEND = 3,
405 CMD_VM_RESUME = 4,
406 CMD_VM_EXIT = 5,
407 CMD_VM_DISPOSE = 6,
408 CMD_VM_INVOKE_METHOD = 7,
409 CMD_VM_SET_PROTOCOL_VERSION = 8,
410 CMD_VM_ABORT_INVOKE = 9,
411 CMD_VM_SET_KEEPALIVE = 10,
412 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
413 CMD_VM_GET_TYPES = 12,
414 CMD_VM_INVOKE_METHODS = 13,
415 CMD_VM_START_BUFFERING = 14,
416 CMD_VM_STOP_BUFFERING = 15
417 } CmdVM;
419 typedef enum {
420 CMD_THREAD_GET_FRAME_INFO = 1,
421 CMD_THREAD_GET_NAME = 2,
422 CMD_THREAD_GET_STATE = 3,
423 CMD_THREAD_GET_INFO = 4,
424 CMD_THREAD_GET_ID = 5,
425 CMD_THREAD_GET_TID = 6,
426 CMD_THREAD_SET_IP = 7
427 } CmdThread;
429 typedef enum {
430 CMD_EVENT_REQUEST_SET = 1,
431 CMD_EVENT_REQUEST_CLEAR = 2,
432 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
433 } CmdEvent;
435 typedef enum {
436 CMD_COMPOSITE = 100
437 } CmdComposite;
439 typedef enum {
440 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
441 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
442 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
443 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
444 CMD_APPDOMAIN_CREATE_STRING = 5,
445 CMD_APPDOMAIN_GET_CORLIB = 6,
446 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
447 } CmdAppDomain;
449 typedef enum {
450 CMD_ASSEMBLY_GET_LOCATION = 1,
451 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
452 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
453 CMD_ASSEMBLY_GET_OBJECT = 4,
454 CMD_ASSEMBLY_GET_TYPE = 5,
455 CMD_ASSEMBLY_GET_NAME = 6,
456 CMD_ASSEMBLY_GET_DOMAIN = 7
457 } CmdAssembly;
459 typedef enum {
460 CMD_MODULE_GET_INFO = 1,
461 } CmdModule;
463 typedef enum {
464 CMD_FIELD_GET_INFO = 1,
465 } CmdField;
467 typedef enum {
468 CMD_METHOD_GET_NAME = 1,
469 CMD_METHOD_GET_DECLARING_TYPE = 2,
470 CMD_METHOD_GET_DEBUG_INFO = 3,
471 CMD_METHOD_GET_PARAM_INFO = 4,
472 CMD_METHOD_GET_LOCALS_INFO = 5,
473 CMD_METHOD_GET_INFO = 6,
474 CMD_METHOD_GET_BODY = 7,
475 CMD_METHOD_RESOLVE_TOKEN = 8,
476 CMD_METHOD_GET_CATTRS = 9,
477 CMD_METHOD_MAKE_GENERIC_METHOD = 10
478 } CmdMethod;
480 typedef enum {
481 CMD_TYPE_GET_INFO = 1,
482 CMD_TYPE_GET_METHODS = 2,
483 CMD_TYPE_GET_FIELDS = 3,
484 CMD_TYPE_GET_VALUES = 4,
485 CMD_TYPE_GET_OBJECT = 5,
486 CMD_TYPE_GET_SOURCE_FILES = 6,
487 CMD_TYPE_SET_VALUES = 7,
488 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
489 CMD_TYPE_GET_PROPERTIES = 9,
490 CMD_TYPE_GET_CATTRS = 10,
491 CMD_TYPE_GET_FIELD_CATTRS = 11,
492 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
493 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
494 CMD_TYPE_GET_VALUES_2 = 14,
495 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
496 CMD_TYPE_GET_INTERFACES = 16,
497 CMD_TYPE_GET_INTERFACE_MAP = 17,
498 CMD_TYPE_IS_INITIALIZED = 18,
499 CMD_TYPE_CREATE_INSTANCE = 19
500 } CmdType;
502 typedef enum {
503 CMD_STACK_FRAME_GET_VALUES = 1,
504 CMD_STACK_FRAME_GET_THIS = 2,
505 CMD_STACK_FRAME_SET_VALUES = 3,
506 CMD_STACK_FRAME_GET_DOMAIN = 4,
507 CMD_STACK_FRAME_SET_THIS = 5,
508 } CmdStackFrame;
510 typedef enum {
511 CMD_ARRAY_REF_GET_LENGTH = 1,
512 CMD_ARRAY_REF_GET_VALUES = 2,
513 CMD_ARRAY_REF_SET_VALUES = 3,
514 } CmdArray;
516 typedef enum {
517 CMD_STRING_REF_GET_VALUE = 1,
518 CMD_STRING_REF_GET_LENGTH = 2,
519 CMD_STRING_REF_GET_CHARS = 3
520 } CmdString;
522 typedef enum {
523 CMD_OBJECT_REF_GET_TYPE = 1,
524 CMD_OBJECT_REF_GET_VALUES = 2,
525 CMD_OBJECT_REF_IS_COLLECTED = 3,
526 CMD_OBJECT_REF_GET_ADDRESS = 4,
527 CMD_OBJECT_REF_GET_DOMAIN = 5,
528 CMD_OBJECT_REF_SET_VALUES = 6,
529 CMD_OBJECT_REF_GET_INFO = 7,
530 } CmdObject;
532 typedef struct {
533 ModifierKind kind;
534 union {
535 int count; /* For kind == MOD_KIND_COUNT */
536 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
537 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
538 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
539 GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
540 GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
541 StepFilter filter; /* For kind == MOD_KIND_STEP */
542 } data;
543 gboolean caught, uncaught, subclasses; /* For kind == MOD_KIND_EXCEPTION_ONLY */
544 } Modifier;
546 typedef struct{
547 int id;
548 int event_kind;
549 int suspend_policy;
550 int nmodifiers;
551 gpointer info;
552 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
553 } EventRequest;
556 * Describes a single step request.
558 typedef struct {
559 EventRequest *req;
560 MonoInternalThread *thread;
561 StepDepth depth;
562 StepSize size;
563 StepFilter filter;
564 gpointer last_sp;
565 gpointer start_sp;
566 MonoMethod *start_method;
567 MonoMethod *last_method;
568 int last_line;
569 /* Whenever single stepping is performed using start/stop_single_stepping () */
570 gboolean global;
571 /* The list of breakpoints used to implement step-over */
572 GSList *bps;
573 /* The number of frames at the start of a step-over */
574 int nframes;
575 /* If set, don't stop in methods that are not part of user assemblies */
576 MonoAssembly** user_assemblies;
577 /* Used to distinguish stepping breakpoint hits in parallel tasks executions */
578 int async_id;
579 /* Used to know if we are in process of async step-out and distishing from exception breakpoints */
580 MonoMethod* async_stepout_method;
581 } SingleStepReq;
584 * Contains additional information for an event
586 typedef struct {
587 /* For EVENT_KIND_EXCEPTION */
588 MonoObject *exc;
589 MonoContext catch_ctx;
590 gboolean caught;
591 /* For EVENT_KIND_USER_LOG */
592 int level;
593 char *category, *message;
594 /* For EVENT_KIND_TYPE_LOAD */
595 MonoClass *klass;
596 } EventInfo;
598 /* Dummy structure used for the profiler callbacks */
599 typedef struct {
600 void* dummy;
601 } DebuggerProfiler;
603 typedef struct {
604 guint8 *buf, *p, *end;
605 } Buffer;
607 typedef struct ReplyPacket {
608 int id;
609 int error;
610 Buffer *data;
611 } ReplyPacket;
613 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
615 #ifdef PLATFORM_ANDROID
616 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { g_print (__VA_ARGS__); } } while (0)
617 #else
618 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { fprintf (log_file, __VA_ARGS__); fflush (log_file); } } while (0)
619 #endif
621 #ifdef HOST_WIN32
622 #define get_last_sock_error() WSAGetLastError()
623 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
624 #define MONO_EINTR WSAEINTR
625 #else
626 #define get_last_sock_error() errno
627 #define MONO_EWOULDBLOCK EWOULDBLOCK
628 #define MONO_EINTR EINTR
629 #endif
631 #define CHECK_PROTOCOL_VERSION(major,minor) \
632 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
635 * Globals
638 static AgentConfig agent_config;
641 * Whenever the agent is fully initialized.
642 * When using the onuncaught or onthrow options, only some parts of the agent are
643 * initialized on startup, and the full initialization which includes connection
644 * establishment and the startup of the agent thread is only done in response to
645 * an event.
647 static gint32 inited;
649 #ifndef DISABLE_SOCKET_TRANSPORT
650 static int conn_fd;
651 static int listen_fd;
652 #endif
654 static int packet_id = 0;
656 static int objref_id = 0;
658 static int event_request_id = 0;
660 static int frame_id = 0;
662 static GPtrArray *event_requests;
664 static MonoNativeTlsKey debugger_tls_id;
666 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
668 /* Maps MonoInternalThread -> DebuggerTlsData */
669 /* Protected by the loader lock */
670 static MonoGHashTable *thread_to_tls;
672 /* Maps tid -> MonoInternalThread */
673 /* Protected by the loader lock */
674 static MonoGHashTable *tid_to_thread;
676 /* Maps tid -> MonoThread (not MonoInternalThread) */
677 /* Protected by the loader lock */
678 static MonoGHashTable *tid_to_thread_obj;
680 static MonoNativeThreadId debugger_thread_id;
682 static MonoThreadHandle *debugger_thread_handle;
684 static int log_level;
686 static gboolean embedding;
688 static FILE *log_file;
690 /* Assemblies whose assembly load event has no been sent yet */
691 /* Protected by the dbg lock */
692 static GPtrArray *pending_assembly_loads;
694 /* Whenever the debugger thread has exited */
695 static gboolean debugger_thread_exited;
697 /* Cond variable used to wait for debugger_thread_exited becoming true */
698 static MonoCoopCond debugger_thread_exited_cond;
700 /* Mutex for the cond var above */
701 static MonoCoopMutex debugger_thread_exited_mutex;
703 static DebuggerProfiler debugger_profiler;
705 /* The single step request instance */
706 static SingleStepReq *ss_req;
708 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
709 /* Number of single stepping operations in progress */
710 static int ss_count;
711 #endif
713 /* The protocol version of the client */
714 static int major_version, minor_version;
716 /* Whenever the variables above are set by the client */
717 static gboolean protocol_version_set;
719 /* A hash table containing all active domains */
720 /* Protected by the loader lock */
721 static GHashTable *domains;
723 /* The number of times the runtime is suspended */
724 static gint32 suspend_count;
726 /* Whenever to buffer reply messages and send them together */
727 static gboolean buffer_replies;
729 /* Buffered reply packets */
730 static ReplyPacket reply_packets [128];
731 int nreply_packets;
733 #define dbg_lock() mono_coop_mutex_lock (&debug_mutex)
734 #define dbg_unlock() mono_coop_mutex_unlock (&debug_mutex)
735 static MonoCoopMutex debug_mutex;
737 static void transport_init (void);
738 static void transport_connect (const char *address);
739 static gboolean transport_handshake (void);
740 static void register_transport (DebuggerTransport *trans);
742 static gsize WINAPI debugger_thread (void *arg);
744 static void runtime_initialized (MonoProfiler *prof);
746 static void runtime_shutdown (MonoProfiler *prof);
748 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
750 static void thread_end (MonoProfiler *prof, uintptr_t tid);
752 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
754 static void appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain);
756 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
758 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
760 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
762 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
764 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
766 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
768 static void emit_assembly_load (gpointer assembly, gpointer user_data);
770 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
772 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
774 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
776 static void start_single_stepping (void);
778 static void stop_single_stepping (void);
780 static void suspend_current (void);
782 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
784 static void clear_types_for_assembly (MonoAssembly *assembly);
786 static void clear_breakpoints_for_domain (MonoDomain *domain);
788 static void process_profiler_event (EventKind event, gpointer arg);
790 /* Submodule init/cleanup */
791 static void breakpoints_init (void);
792 static void breakpoints_cleanup (void);
794 static void objrefs_init (void);
795 static void objrefs_cleanup (void);
797 static void ids_init (void);
798 static void ids_cleanup (void);
800 static void suspend_init (void);
802 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch,
803 StackFrame **frames, int nframes);
804 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req);
805 static void ss_destroy (SingleStepReq *req);
807 static void start_debugger_thread (void);
808 static void stop_debugger_thread (void);
810 static void finish_agent_init (gboolean on_startup);
812 static void process_profiler_event (EventKind event, gpointer arg);
814 static void invalidate_frames (DebuggerTlsData *tls);
816 #ifndef DISABLE_SOCKET_TRANSPORT
817 static void
818 register_socket_transport (void);
819 #endif
821 static inline gboolean
822 is_debugger_thread (void)
824 MonoInternalThread *internal;
826 internal = mono_thread_internal_current ();
827 if (!internal)
828 return FALSE;
830 return internal->debugger_thread;
833 static int
834 parse_address (char *address, char **host, int *port)
836 char *pos = strchr (address, ':');
838 if (pos == NULL || pos == address)
839 return 1;
841 size_t len = pos - address;
842 *host = (char *)g_malloc (len + 1);
843 memcpy (*host, address, len);
844 (*host) [len] = '\0';
846 *port = atoi (pos + 1);
848 return 0;
851 static void
852 print_usage (void)
854 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
855 fprintf (stderr, "Available options:\n");
856 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
857 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
858 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
859 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
860 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
861 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
862 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
863 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
864 fprintf (stderr, " setpgid=y/n\t\t\tWhether to call setpid(0, 0) after startup.\n");
865 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
868 static gboolean
869 parse_flag (const char *option, char *flag)
871 if (!strcmp (flag, "y"))
872 return TRUE;
873 else if (!strcmp (flag, "n"))
874 return FALSE;
875 else {
876 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
877 exit (1);
878 return FALSE;
882 void
883 mono_debugger_agent_parse_options (char *options)
885 char **args, **ptr;
886 char *host;
887 int port;
888 char *extra;
890 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
891 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
892 exit (1);
893 #endif
895 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
896 if (extra) {
897 options = g_strdup_printf ("%s,%s", options, extra);
898 g_free (extra);
901 agent_config.enabled = TRUE;
902 agent_config.suspend = TRUE;
903 agent_config.server = FALSE;
904 agent_config.defer = FALSE;
905 agent_config.address = NULL;
907 //agent_config.log_level = 10;
909 args = g_strsplit (options, ",", -1);
910 for (ptr = args; ptr && *ptr; ptr ++) {
911 char *arg = *ptr;
913 if (strncmp (arg, "transport=", 10) == 0) {
914 agent_config.transport = g_strdup (arg + 10);
915 } else if (strncmp (arg, "address=", 8) == 0) {
916 agent_config.address = g_strdup (arg + 8);
917 } else if (strncmp (arg, "loglevel=", 9) == 0) {
918 agent_config.log_level = atoi (arg + 9);
919 } else if (strncmp (arg, "logfile=", 8) == 0) {
920 agent_config.log_file = g_strdup (arg + 8);
921 } else if (strncmp (arg, "suspend=", 8) == 0) {
922 agent_config.suspend = parse_flag ("suspend", arg + 8);
923 } else if (strncmp (arg, "server=", 7) == 0) {
924 agent_config.server = parse_flag ("server", arg + 7);
925 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
926 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
927 } else if (strncmp (arg, "onthrow=", 8) == 0) {
928 /* We support multiple onthrow= options */
929 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
930 } else if (strncmp (arg, "onthrow", 7) == 0) {
931 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
932 } else if (strncmp (arg, "help", 4) == 0) {
933 print_usage ();
934 exit (0);
935 } else if (strncmp (arg, "timeout=", 8) == 0) {
936 agent_config.timeout = atoi (arg + 8);
937 } else if (strncmp (arg, "launch=", 7) == 0) {
938 agent_config.launch = g_strdup (arg + 7);
939 } else if (strncmp (arg, "embedding=", 10) == 0) {
940 agent_config.embedding = atoi (arg + 10) == 1;
941 } else if (strncmp (arg, "keepalive=", 10) == 0) {
942 agent_config.keepalive = atoi (arg + 10);
943 } else if (strncmp (arg, "setpgid=", 8) == 0) {
944 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
945 } else {
946 print_usage ();
947 exit (1);
951 if (agent_config.server && !agent_config.suspend) {
952 /* Waiting for deferred attachment */
953 agent_config.defer = TRUE;
954 if (agent_config.address == NULL) {
955 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (mono_process_current_pid () % 1000));
959 //agent_config.log_level = 0;
961 if (agent_config.transport == NULL) {
962 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
963 exit (1);
966 if (agent_config.address == NULL && !agent_config.server) {
967 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
968 exit (1);
971 // FIXME:
972 if (!strcmp (agent_config.transport, "dt_socket")) {
973 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
974 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
975 exit (1);
980 void
981 mono_debugger_agent_init (void)
983 mono_coop_mutex_init_recursive (&debug_mutex);
985 if (!agent_config.enabled)
986 return;
988 transport_init ();
990 /* Need to know whenever a thread has acquired the loader mutex */
991 mono_loader_lock_track_ownership (TRUE);
993 event_requests = g_ptr_array_new ();
995 mono_coop_mutex_init (&debugger_thread_exited_mutex);
996 mono_coop_cond_init (&debugger_thread_exited_cond);
998 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
999 mono_profiler_set_events ((MonoProfileFlags)(MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS));
1000 mono_profiler_install_runtime_initialized (runtime_initialized);
1001 mono_profiler_install_appdomain (NULL, appdomain_load, appdomain_start_unload, appdomain_unload);
1002 mono_profiler_install_thread (thread_startup, thread_end);
1003 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
1004 mono_profiler_install_jit_end (jit_end);
1006 mono_native_tls_alloc (&debugger_tls_id, NULL);
1008 /* Needed by the hash_table_new_type () call below */
1009 mono_gc_base_init ();
1011 thread_to_tls = mono_g_hash_table_new_type ((GHashFunc)mono_object_hash, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_DEBUGGER, "thread-to-tls table");
1013 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread table");
1015 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DEBUGGER, "tid-to-thread object table");
1017 pending_assembly_loads = g_ptr_array_new ();
1018 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
1020 log_level = agent_config.log_level;
1022 embedding = agent_config.embedding;
1023 disconnected = TRUE;
1025 if (agent_config.log_file) {
1026 log_file = fopen (agent_config.log_file, "w+");
1027 if (!log_file) {
1028 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
1029 exit (1);
1031 } else {
1032 log_file = stdout;
1035 ids_init ();
1036 objrefs_init ();
1037 breakpoints_init ();
1038 suspend_init ();
1040 mini_get_debug_options ()->gen_sdb_seq_points = TRUE;
1042 * This is needed because currently we don't handle liveness info.
1044 mini_get_debug_options ()->mdb_optimizations = TRUE;
1046 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
1047 /* This is needed because we can't set local variables in registers yet */
1048 mono_disable_optimizations (MONO_OPT_LINEARS);
1049 #endif
1052 * The stack walk done from thread_interrupt () needs to be signal safe, but it
1053 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
1054 * safe (#3411). So load AOT info eagerly when the debugger is running as a
1055 * workaround.
1057 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
1059 #ifdef HAVE_SETPGID
1060 if (agent_config.setpgid)
1061 setpgid (0, 0);
1062 #endif
1064 if (!agent_config.onuncaught && !agent_config.onthrow)
1065 finish_agent_init (TRUE);
1069 * finish_agent_init:
1071 * Finish the initialization of the agent. This involves connecting the transport
1072 * and starting the agent thread. This is either done at startup, or
1073 * in response to some event like an unhandled exception.
1075 static void
1076 finish_agent_init (gboolean on_startup)
1078 int res;
1080 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
1081 return;
1083 if (agent_config.launch) {
1084 char *argv [16];
1086 // FIXME: Generated address
1087 // FIXME: Races with transport_connect ()
1089 argv [0] = agent_config.launch;
1090 argv [1] = agent_config.transport;
1091 argv [2] = agent_config.address;
1092 argv [3] = NULL;
1094 res = g_spawn_async_with_pipes (NULL, argv, NULL, (GSpawnFlags)0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1095 if (!res) {
1096 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1097 exit (1);
1101 transport_connect (agent_config.address);
1103 if (!on_startup) {
1104 /* Do some which is usually done after sending the VMStart () event */
1105 vm_start_event_sent = TRUE;
1106 start_debugger_thread ();
1110 static void
1111 mono_debugger_agent_cleanup (void)
1113 if (!inited)
1114 return;
1116 stop_debugger_thread ();
1118 breakpoints_cleanup ();
1119 objrefs_cleanup ();
1120 ids_cleanup ();
1124 * SOCKET TRANSPORT
1127 #ifndef DISABLE_SOCKET_TRANSPORT
1130 * recv_length:
1132 * recv() + handle incomplete reads and EINTR
1134 static int
1135 socket_transport_recv (void *buf, int len)
1137 int res;
1138 int total = 0;
1139 int fd = conn_fd;
1140 int flags = 0;
1141 static gint64 last_keepalive;
1142 gint64 msecs;
1144 MONO_ENTER_GC_SAFE;
1146 do {
1147 again:
1148 res = recv (fd, (char *) buf + total, len - total, flags);
1149 if (res > 0)
1150 total += res;
1151 if (agent_config.keepalive) {
1152 gboolean need_keepalive = FALSE;
1153 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1154 need_keepalive = TRUE;
1155 } else if (res == -1) {
1156 /* This could happen if recv () is interrupted repeatedly */
1157 msecs = mono_msec_ticks ();
1158 if (msecs - last_keepalive >= agent_config.keepalive) {
1159 need_keepalive = TRUE;
1160 last_keepalive = msecs;
1163 if (need_keepalive) {
1164 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1165 goto again;
1168 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1170 MONO_EXIT_GC_SAFE;
1172 return total;
1175 static void
1176 set_keepalive (void)
1178 struct timeval tv;
1179 int result;
1181 if (!agent_config.keepalive || !conn_fd)
1182 return;
1184 tv.tv_sec = agent_config.keepalive / 1000;
1185 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1187 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1188 g_assert (result >= 0);
1191 static int
1192 socket_transport_accept (int socket_fd)
1194 MONO_ENTER_GC_SAFE;
1195 conn_fd = accept (socket_fd, NULL, NULL);
1196 MONO_EXIT_GC_SAFE;
1198 if (conn_fd == -1) {
1199 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1200 } else {
1201 DEBUG_PRINTF (1, "Accepted connection from client, connection fd=%d.\n", conn_fd);
1204 return conn_fd;
1207 static gboolean
1208 socket_transport_send (void *data, int len)
1210 int res;
1212 MONO_ENTER_GC_SAFE;
1214 do {
1215 res = send (conn_fd, data, len, 0);
1216 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1218 MONO_EXIT_GC_SAFE;
1220 if (res != len)
1221 return FALSE;
1222 else
1223 return TRUE;
1227 * socket_transport_connect:
1229 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1231 static void
1232 socket_transport_connect (const char *address)
1234 MonoAddressInfo *result;
1235 MonoAddressEntry *rp;
1236 int sfd = -1, s, res;
1237 char *host;
1238 int port;
1240 if (agent_config.address) {
1241 res = parse_address (agent_config.address, &host, &port);
1242 g_assert (res == 0);
1243 } else {
1244 host = NULL;
1245 port = 0;
1248 conn_fd = -1;
1249 listen_fd = -1;
1251 if (host) {
1253 mono_network_init ();
1255 /* Obtain address(es) matching host/port */
1256 s = mono_get_address_info (host, port, MONO_HINT_UNSPECIFIED, &result);
1257 if (s != 0) {
1258 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, s); // FIXME add portable error conversion functions
1259 exit (1);
1263 if (agent_config.server) {
1264 /* Wait for a connection */
1265 if (!host) {
1266 struct sockaddr_in addr;
1267 socklen_t addrlen;
1269 /* No address, generate one */
1270 sfd = socket (AF_INET, SOCK_STREAM, 0);
1271 g_assert (sfd);
1273 /* This will bind the socket to a random port */
1274 res = listen (sfd, 16);
1275 if (res == -1) {
1276 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1277 exit (1);
1279 listen_fd = sfd;
1281 addrlen = sizeof (addr);
1282 memset (&addr, 0, sizeof (addr));
1283 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1284 g_assert (res == 0);
1286 host = (char*)"127.0.0.1";
1287 port = ntohs (addr.sin_port);
1289 /* Emit the address to stdout */
1290 /* FIXME: Should print another interface, not localhost */
1291 printf ("%s:%d\n", host, port);
1292 } else {
1293 /* Listen on the provided address */
1294 for (rp = result->entries; rp != NULL; rp = rp->next) {
1295 MonoSocketAddress sockaddr;
1296 socklen_t sock_len;
1297 int n = 1;
1299 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1301 sfd = socket (rp->family, rp->socktype,
1302 rp->protocol);
1303 if (sfd == -1)
1304 continue;
1306 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1307 continue;
1309 res = bind (sfd, &sockaddr.addr, sock_len);
1310 if (res == -1)
1311 continue;
1313 res = listen (sfd, 16);
1314 if (res == -1)
1315 continue;
1316 listen_fd = sfd;
1317 break;
1320 mono_free_address_info (result);
1323 if (agent_config.defer)
1324 return;
1326 DEBUG_PRINTF (1, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout);
1328 if (agent_config.timeout) {
1329 fd_set readfds;
1330 struct timeval tv;
1332 tv.tv_sec = 0;
1333 tv.tv_usec = agent_config.timeout * 1000;
1334 FD_ZERO (&readfds);
1335 FD_SET (sfd, &readfds);
1337 MONO_ENTER_GC_SAFE;
1338 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1339 MONO_EXIT_GC_SAFE;
1341 if (res == 0) {
1342 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1343 exit (1);
1347 conn_fd = socket_transport_accept (sfd);
1348 if (conn_fd == -1)
1349 exit (1);
1351 DEBUG_PRINTF (1, "Accepted connection from client, socket fd=%d.\n", conn_fd);
1352 } else {
1353 /* Connect to the specified address */
1354 /* FIXME: Respect the timeout */
1355 for (rp = result->entries; rp != NULL; rp = rp->next) {
1356 MonoSocketAddress sockaddr;
1357 socklen_t sock_len;
1359 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1361 sfd = socket (rp->family, rp->socktype,
1362 rp->protocol);
1363 if (sfd == -1)
1364 continue;
1366 MONO_ENTER_GC_SAFE;
1367 res = connect (sfd, &sockaddr.addr, sock_len);
1368 MONO_EXIT_GC_SAFE;
1370 if (res != -1)
1371 break; /* Success */
1373 MONO_ENTER_GC_SAFE;
1374 close (sfd);
1375 MONO_EXIT_GC_SAFE;
1378 if (rp == 0) {
1379 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1380 exit (1);
1383 conn_fd = sfd;
1385 mono_free_address_info (result);
1388 if (!transport_handshake ())
1389 exit (1);
1392 static void
1393 socket_transport_close1 (void)
1395 /* This will interrupt the agent thread */
1396 /* Close the read part only so it can still send back replies */
1397 /* Also shut down the connection listener so that we can exit normally */
1398 #ifdef HOST_WIN32
1399 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1400 shutdown (conn_fd, SD_BOTH);
1401 shutdown (listen_fd, SD_BOTH);
1402 closesocket (listen_fd);
1403 #else
1404 shutdown (conn_fd, SHUT_RD);
1405 shutdown (listen_fd, SHUT_RDWR);
1406 MONO_ENTER_GC_SAFE;
1407 close (listen_fd);
1408 MONO_EXIT_GC_SAFE;
1409 #endif
1412 static void
1413 socket_transport_close2 (void)
1415 #ifdef HOST_WIN32
1416 shutdown (conn_fd, SD_BOTH);
1417 #else
1418 shutdown (conn_fd, SHUT_RDWR);
1419 #endif
1422 static void
1423 register_socket_transport (void)
1425 DebuggerTransport trans;
1427 trans.name = "dt_socket";
1428 trans.connect = socket_transport_connect;
1429 trans.close1 = socket_transport_close1;
1430 trans.close2 = socket_transport_close2;
1431 trans.send = socket_transport_send;
1432 trans.recv = socket_transport_recv;
1434 register_transport (&trans);
1438 * socket_fd_transport_connect:
1441 static void
1442 socket_fd_transport_connect (const char *address)
1444 int res;
1446 res = sscanf (address, "%d", &conn_fd);
1447 if (res != 1) {
1448 fprintf (stderr, "debugger-agent: socket-fd transport address is invalid: '%s'\n", address);
1449 exit (1);
1452 if (!transport_handshake ())
1453 exit (1);
1456 static void
1457 register_socket_fd_transport (void)
1459 DebuggerTransport trans;
1461 /* This is the same as the 'dt_socket' transport, but receives an already connected socket fd */
1462 trans.name = "socket-fd";
1463 trans.connect = socket_fd_transport_connect;
1464 trans.close1 = socket_transport_close1;
1465 trans.close2 = socket_transport_close2;
1466 trans.send = socket_transport_send;
1467 trans.recv = socket_transport_recv;
1469 register_transport (&trans);
1472 #endif /* DISABLE_SOCKET_TRANSPORT */
1475 * TRANSPORT CODE
1478 #define MAX_TRANSPORTS 16
1480 static DebuggerTransport *transport;
1482 static DebuggerTransport transports [MAX_TRANSPORTS];
1483 static int ntransports;
1485 MONO_API void
1486 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1488 void
1489 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1491 register_transport (trans);
1494 static void
1495 register_transport (DebuggerTransport *trans)
1497 g_assert (ntransports < MAX_TRANSPORTS);
1499 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1500 ntransports ++;
1503 static void
1504 transport_init (void)
1506 int i;
1508 #ifndef DISABLE_SOCKET_TRANSPORT
1509 register_socket_transport ();
1510 register_socket_fd_transport ();
1511 #endif
1513 for (i = 0; i < ntransports; ++i) {
1514 if (!strcmp (agent_config.transport, transports [i].name))
1515 break;
1517 if (i == ntransports) {
1518 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1519 for (i = 0; i < ntransports; ++i)
1520 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1521 fprintf (stderr, "\n");
1522 exit (1);
1524 transport = &transports [i];
1527 void
1528 transport_connect (const char *address)
1530 transport->connect (address);
1533 static void
1534 transport_close1 (void)
1536 transport->close1 ();
1539 static void
1540 transport_close2 (void)
1542 transport->close2 ();
1545 static int
1546 transport_send (void *buf, int len)
1548 return transport->send (buf, len);
1551 static int
1552 transport_recv (void *buf, int len)
1554 return transport->recv (buf, len);
1557 gboolean
1558 mono_debugger_agent_transport_handshake (void)
1560 return transport_handshake ();
1563 static gboolean
1564 transport_handshake (void)
1566 char handshake_msg [128];
1567 guint8 buf [128];
1568 int res;
1570 disconnected = TRUE;
1572 /* Write handshake message */
1573 sprintf (handshake_msg, "DWP-Handshake");
1575 do {
1576 res = transport_send (handshake_msg, strlen (handshake_msg));
1577 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1579 g_assert (res != -1);
1581 /* Read answer */
1582 res = transport_recv (buf, strlen (handshake_msg));
1583 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg)) != 0)) {
1584 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1585 return FALSE;
1589 * To support older clients, the client sends its protocol version after connecting
1590 * using a command. Until that is received, default to our protocol version.
1592 major_version = MAJOR_VERSION;
1593 minor_version = MINOR_VERSION;
1594 protocol_version_set = FALSE;
1596 #ifndef DISABLE_SOCKET_TRANSPORT
1597 // FIXME: Move this somewhere else
1599 * Set TCP_NODELAY on the socket so the client receives events/command
1600 * results immediately.
1602 if (conn_fd) {
1603 int flag = 1;
1604 int result = setsockopt (conn_fd,
1605 IPPROTO_TCP,
1606 TCP_NODELAY,
1607 (char *) &flag,
1608 sizeof(int));
1609 g_assert (result >= 0);
1612 set_keepalive ();
1613 #endif
1615 disconnected = FALSE;
1616 return TRUE;
1619 static void
1620 stop_debugger_thread (void)
1622 if (!inited)
1623 return;
1625 transport_close1 ();
1628 * Wait for the thread to exit.
1630 * If we continue with the shutdown without waiting for it, then the client might
1631 * not receive an answer to its last command like a resume.
1633 if (!is_debugger_thread ()) {
1634 do {
1635 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
1636 if (!debugger_thread_exited)
1637 mono_coop_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1638 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
1639 } while (!debugger_thread_exited);
1642 transport_close2 ();
1645 static void
1646 start_debugger_thread (void)
1648 MonoError error;
1649 MonoInternalThread *thread;
1651 thread = mono_thread_create_internal (mono_get_root_domain (), debugger_thread, NULL, MONO_THREAD_CREATE_FLAGS_DEBUGGER, &error);
1652 mono_error_assert_ok (&error);
1654 debugger_thread_handle = mono_threads_open_thread_handle (thread->handle);
1655 g_assert (debugger_thread_handle);
1659 * Functions to decode protocol data
1662 static inline int
1663 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1665 *endbuf = buf + 1;
1666 g_assert (*endbuf <= limit);
1667 return buf [0];
1670 static inline int
1671 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1673 *endbuf = buf + 4;
1674 g_assert (*endbuf <= limit);
1676 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1679 static inline gint64
1680 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1682 guint32 high = decode_int (buf, &buf, limit);
1683 guint32 low = decode_int (buf, &buf, limit);
1685 *endbuf = buf;
1687 return ((((guint64)high) << 32) | ((guint64)low));
1690 static inline int
1691 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1693 return decode_int (buf, endbuf, limit);
1696 static inline char*
1697 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1699 int len = decode_int (buf, &buf, limit);
1700 char *s;
1702 if (len < 0) {
1703 *endbuf = buf;
1704 return NULL;
1707 s = (char *)g_malloc (len + 1);
1708 g_assert (s);
1710 memcpy (s, buf, len);
1711 s [len] = '\0';
1712 buf += len;
1713 *endbuf = buf;
1715 return s;
1719 * Functions to encode protocol data
1722 static inline void
1723 buffer_init (Buffer *buf, int size)
1725 buf->buf = (guint8 *)g_malloc (size);
1726 buf->p = buf->buf;
1727 buf->end = buf->buf + size;
1730 static inline int
1731 buffer_len (Buffer *buf)
1733 return buf->p - buf->buf;
1736 static inline void
1737 buffer_make_room (Buffer *buf, int size)
1739 if (buf->end - buf->p < size) {
1740 int new_size = buf->end - buf->buf + size + 32;
1741 guint8 *p = (guint8 *)g_realloc (buf->buf, new_size);
1742 size = buf->p - buf->buf;
1743 buf->buf = p;
1744 buf->p = p + size;
1745 buf->end = buf->buf + new_size;
1749 static inline void
1750 buffer_add_byte (Buffer *buf, guint8 val)
1752 buffer_make_room (buf, 1);
1753 buf->p [0] = val;
1754 buf->p++;
1757 static inline void
1758 buffer_add_short (Buffer *buf, guint32 val)
1760 buffer_make_room (buf, 2);
1761 buf->p [0] = (val >> 8) & 0xff;
1762 buf->p [1] = (val >> 0) & 0xff;
1763 buf->p += 2;
1766 static inline void
1767 buffer_add_int (Buffer *buf, guint32 val)
1769 buffer_make_room (buf, 4);
1770 buf->p [0] = (val >> 24) & 0xff;
1771 buf->p [1] = (val >> 16) & 0xff;
1772 buf->p [2] = (val >> 8) & 0xff;
1773 buf->p [3] = (val >> 0) & 0xff;
1774 buf->p += 4;
1777 static inline void
1778 buffer_add_long (Buffer *buf, guint64 l)
1780 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1781 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1784 static inline void
1785 buffer_add_id (Buffer *buf, int id)
1787 buffer_add_int (buf, (guint64)id);
1790 static inline void
1791 buffer_add_data (Buffer *buf, guint8 *data, int len)
1793 buffer_make_room (buf, len);
1794 memcpy (buf->p, data, len);
1795 buf->p += len;
1798 static inline void
1799 buffer_add_string (Buffer *buf, const char *str)
1801 int len;
1803 if (str == NULL) {
1804 buffer_add_int (buf, 0);
1805 } else {
1806 len = strlen (str);
1807 buffer_add_int (buf, len);
1808 buffer_add_data (buf, (guint8*)str, len);
1812 static inline void
1813 buffer_add_buffer (Buffer *buf, Buffer *data)
1815 buffer_add_data (buf, data->buf, buffer_len (data));
1818 static inline void
1819 buffer_free (Buffer *buf)
1821 g_free (buf->buf);
1824 static gboolean
1825 send_packet (int command_set, int command, Buffer *data)
1827 Buffer buf;
1828 int len, id;
1829 gboolean res;
1831 id = InterlockedIncrement (&packet_id);
1833 len = data->p - data->buf + 11;
1834 buffer_init (&buf, len);
1835 buffer_add_int (&buf, len);
1836 buffer_add_int (&buf, id);
1837 buffer_add_byte (&buf, 0); /* flags */
1838 buffer_add_byte (&buf, command_set);
1839 buffer_add_byte (&buf, command);
1840 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1842 res = transport_send (buf.buf, len);
1844 buffer_free (&buf);
1846 return res;
1849 static gboolean
1850 send_reply_packets (int npackets, ReplyPacket *packets)
1852 Buffer buf;
1853 int i, len;
1854 gboolean res;
1856 len = 0;
1857 for (i = 0; i < npackets; ++i)
1858 len += buffer_len (packets [i].data) + 11;
1859 buffer_init (&buf, len);
1860 for (i = 0; i < npackets; ++i) {
1861 buffer_add_int (&buf, buffer_len (packets [i].data) + 11);
1862 buffer_add_int (&buf, packets [i].id);
1863 buffer_add_byte (&buf, 0x80); /* flags */
1864 buffer_add_byte (&buf, (packets [i].error >> 8) & 0xff);
1865 buffer_add_byte (&buf, packets [i].error);
1866 buffer_add_buffer (&buf, packets [i].data);
1869 res = transport_send (buf.buf, len);
1871 buffer_free (&buf);
1873 return res;
1876 static gboolean
1877 send_reply_packet (int id, int error, Buffer *data)
1879 ReplyPacket packet;
1881 memset (&packet, 0, sizeof (ReplyPacket));
1882 packet.id = id;
1883 packet.error = error;
1884 packet.data = data;
1886 return send_reply_packets (1, &packet);
1889 static void
1890 send_buffered_reply_packets (void)
1892 int i;
1894 send_reply_packets (nreply_packets, reply_packets);
1895 for (i = 0; i < nreply_packets; ++i)
1896 buffer_free (reply_packets [i].data);
1897 DEBUG_PRINTF (1, "[dbg] Sent %d buffered reply packets [at=%lx].\n", nreply_packets, (long)mono_100ns_ticks () / 10000);
1898 nreply_packets = 0;
1901 static void
1902 buffer_reply_packet (int id, int error, Buffer *data)
1904 ReplyPacket *p;
1906 if (nreply_packets == 128)
1907 send_buffered_reply_packets ();
1909 p = &reply_packets [nreply_packets];
1910 p->id = id;
1911 p->error = error;
1912 p->data = g_new0 (Buffer, 1);
1913 buffer_init (p->data, buffer_len (data));
1914 buffer_add_buffer (p->data, data);
1915 nreply_packets ++;
1919 * OBJECT IDS
1923 * Represents an object accessible by the debugger client.
1925 typedef struct {
1926 /* Unique id used in the wire protocol to refer to objects */
1927 int id;
1929 * A weakref gc handle pointing to the object. The gc handle is used to
1930 * detect if the object was garbage collected.
1932 guint32 handle;
1933 } ObjRef;
1935 /* Maps objid -> ObjRef */
1936 /* Protected by the loader lock */
1937 static GHashTable *objrefs;
1938 /* Protected by the loader lock */
1939 static GHashTable *obj_to_objref;
1940 /* Protected by the dbg lock */
1941 static MonoGHashTable *suspended_objs;
1943 static void
1944 free_objref (gpointer value)
1946 ObjRef *o = (ObjRef *)value;
1948 mono_gchandle_free (o->handle);
1950 g_free (o);
1953 static void
1954 objrefs_init (void)
1956 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1957 obj_to_objref = g_hash_table_new (NULL, NULL);
1958 suspended_objs = mono_g_hash_table_new_type ((GHashFunc)mono_object_hash, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_DEBUGGER, "suspended objects table");
1961 static void
1962 objrefs_cleanup (void)
1964 g_hash_table_destroy (objrefs);
1965 objrefs = NULL;
1969 * Return an ObjRef for OBJ.
1971 static ObjRef*
1972 get_objref (MonoObject *obj)
1974 ObjRef *ref;
1975 GSList *reflist = NULL, *l;
1976 int hash = 0;
1978 if (obj == NULL)
1979 return NULL;
1981 if (suspend_count) {
1983 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1985 dbg_lock ();
1986 mono_g_hash_table_insert (suspended_objs, obj, NULL);
1987 dbg_unlock ();
1990 mono_loader_lock ();
1992 /* FIXME: The tables can grow indefinitely */
1994 if (mono_gc_is_moving ()) {
1996 * Objects can move, so use a hash table mapping hash codes to lists of
1997 * ObjRef structures.
1999 hash = mono_object_hash (obj);
2001 reflist = (GSList *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
2002 for (l = reflist; l; l = l->next) {
2003 ref = (ObjRef *)l->data;
2004 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
2005 mono_loader_unlock ();
2006 return ref;
2009 } else {
2010 /* Use a hash table with masked pointers to internalize object references */
2011 ref = (ObjRef *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
2012 /* ref might refer to a different object with the same addr which was GCd */
2013 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
2014 mono_loader_unlock ();
2015 return ref;
2019 ref = g_new0 (ObjRef, 1);
2020 ref->id = InterlockedIncrement (&objref_id);
2021 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
2023 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
2025 if (mono_gc_is_moving ()) {
2026 reflist = g_slist_append (reflist, ref);
2027 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
2028 } else {
2029 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
2032 mono_loader_unlock ();
2034 return ref;
2037 static gboolean
2038 true_pred (gpointer key, gpointer value, gpointer user_data)
2040 return TRUE;
2043 static void
2044 clear_suspended_objs (void)
2046 dbg_lock ();
2047 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
2048 dbg_unlock ();
2051 static inline int
2052 get_objid (MonoObject *obj)
2054 if (!obj)
2055 return 0;
2056 else
2057 return get_objref (obj)->id;
2061 * Set OBJ to the object identified by OBJID.
2062 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
2063 * collected.
2065 static ErrorCode
2066 get_object_allow_null (int objid, MonoObject **obj)
2068 ObjRef *ref;
2070 if (objid == 0) {
2071 *obj = NULL;
2072 return ERR_NONE;
2075 if (!objrefs)
2076 return ERR_INVALID_OBJECT;
2078 mono_loader_lock ();
2080 ref = (ObjRef *)g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
2082 if (ref) {
2083 *obj = mono_gchandle_get_target (ref->handle);
2084 mono_loader_unlock ();
2085 if (!(*obj))
2086 return ERR_INVALID_OBJECT;
2087 return ERR_NONE;
2088 } else {
2089 mono_loader_unlock ();
2090 return ERR_INVALID_OBJECT;
2094 static ErrorCode
2095 get_object (int objid, MonoObject **obj)
2097 ErrorCode err = get_object_allow_null (objid, obj);
2099 if (err != ERR_NONE)
2100 return err;
2101 if (!(*obj))
2102 return ERR_INVALID_OBJECT;
2103 return ERR_NONE;
2106 static inline int
2107 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
2109 return decode_id (buf, endbuf, limit);
2112 static inline void
2113 buffer_add_objid (Buffer *buf, MonoObject *o)
2115 buffer_add_id (buf, get_objid (o));
2119 * IDS
2122 typedef enum {
2123 ID_ASSEMBLY = 0,
2124 ID_MODULE = 1,
2125 ID_TYPE = 2,
2126 ID_METHOD = 3,
2127 ID_FIELD = 4,
2128 ID_DOMAIN = 5,
2129 ID_PROPERTY = 6,
2130 ID_NUM
2131 } IdType;
2134 * Represents a runtime structure accessible to the debugger client
2136 typedef struct {
2137 /* Unique id used in the wire protocol */
2138 int id;
2139 /* Domain of the runtime structure, NULL if the domain was unloaded */
2140 MonoDomain *domain;
2141 union {
2142 gpointer val;
2143 MonoClass *klass;
2144 MonoMethod *method;
2145 MonoImage *image;
2146 MonoAssembly *assembly;
2147 MonoClassField *field;
2148 MonoDomain *domain;
2149 MonoProperty *property;
2150 } data;
2151 } Id;
2153 typedef struct {
2154 /* Maps runtime structure -> Id */
2155 /* Protected by the dbg lock */
2156 GHashTable *val_to_id [ID_NUM];
2157 /* Classes whose class load event has been sent */
2158 /* Protected by the loader lock */
2159 GHashTable *loaded_classes;
2160 /* Maps MonoClass->GPtrArray of file names */
2161 GHashTable *source_files;
2162 /* Maps source file basename -> GSList of classes */
2163 GHashTable *source_file_to_class;
2164 /* Same with ignore-case */
2165 GHashTable *source_file_to_class_ignorecase;
2166 } AgentDomainInfo;
2168 /* Maps id -> Id */
2169 /* Protected by the dbg lock */
2170 static GPtrArray *ids [ID_NUM];
2172 static void
2173 ids_init (void)
2175 int i;
2177 for (i = 0; i < ID_NUM; ++i)
2178 ids [i] = g_ptr_array_new ();
2181 static void
2182 ids_cleanup (void)
2184 int i, j;
2186 for (i = 0; i < ID_NUM; ++i) {
2187 if (ids [i]) {
2188 for (j = 0; j < ids [i]->len; ++j)
2189 g_free (g_ptr_array_index (ids [i], j));
2190 g_ptr_array_free (ids [i], TRUE);
2192 ids [i] = NULL;
2196 void
2197 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2199 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2200 int i, j;
2201 GHashTableIter iter;
2202 GPtrArray *file_names;
2203 char *basename;
2204 GSList *l;
2206 if (info) {
2207 for (i = 0; i < ID_NUM; ++i)
2208 if (info->val_to_id [i])
2209 g_hash_table_destroy (info->val_to_id [i]);
2210 g_hash_table_destroy (info->loaded_classes);
2212 g_hash_table_iter_init (&iter, info->source_files);
2213 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2214 for (i = 0; i < file_names->len; ++i)
2215 g_free (g_ptr_array_index (file_names, i));
2216 g_ptr_array_free (file_names, TRUE);
2219 g_hash_table_iter_init (&iter, info->source_file_to_class);
2220 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2221 g_free (basename);
2222 g_slist_free (l);
2225 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2226 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2227 g_free (basename);
2228 g_slist_free (l);
2231 g_free (info);
2234 domain_jit_info (domain)->agent_info = NULL;
2236 /* Clear ids referencing structures in the domain */
2237 dbg_lock ();
2238 for (i = 0; i < ID_NUM; ++i) {
2239 if (ids [i]) {
2240 for (j = 0; j < ids [i]->len; ++j) {
2241 Id *id = (Id *)g_ptr_array_index (ids [i], j);
2242 if (id->domain == domain)
2243 id->domain = NULL;
2247 dbg_unlock ();
2249 mono_loader_lock ();
2250 g_hash_table_remove (domains, domain);
2251 mono_loader_unlock ();
2254 static AgentDomainInfo*
2255 get_agent_domain_info (MonoDomain *domain)
2257 AgentDomainInfo *info = NULL;
2259 mono_domain_lock (domain);
2261 info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2262 if (!info) {
2263 info = g_new0 (AgentDomainInfo, 1);
2264 domain_jit_info (domain)->agent_info = info;
2265 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2266 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2267 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2268 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2271 mono_domain_unlock (domain);
2273 return info;
2276 static int
2277 get_id (MonoDomain *domain, IdType type, gpointer val)
2279 Id *id;
2280 AgentDomainInfo *info;
2282 if (val == NULL)
2283 return 0;
2285 info = get_agent_domain_info (domain);
2287 dbg_lock ();
2289 if (info->val_to_id [type] == NULL)
2290 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2292 id = (Id *)g_hash_table_lookup (info->val_to_id [type], val);
2293 if (id) {
2294 dbg_unlock ();
2295 return id->id;
2298 id = g_new0 (Id, 1);
2299 /* Reserve id 0 */
2300 id->id = ids [type]->len + 1;
2301 id->domain = domain;
2302 id->data.val = val;
2304 g_hash_table_insert (info->val_to_id [type], val, id);
2305 g_ptr_array_add (ids [type], id);
2307 dbg_unlock ();
2309 return id->id;
2312 static inline gpointer
2313 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, ErrorCode *err)
2315 Id *res;
2317 int id = decode_id (buf, endbuf, limit);
2319 *err = ERR_NONE;
2320 if (domain)
2321 *domain = NULL;
2323 if (id == 0)
2324 return NULL;
2326 // FIXME: error handling
2327 dbg_lock ();
2328 g_assert (id > 0 && id <= ids [type]->len);
2330 res = (Id *)g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2331 dbg_unlock ();
2333 if (res->domain == NULL || res->domain->state == MONO_APPDOMAIN_UNLOADED) {
2334 DEBUG_PRINTF (1, "ERR_UNLOADED, id=%d, type=%d.\n", id, type);
2335 *err = ERR_UNLOADED;
2336 return NULL;
2339 if (domain)
2340 *domain = res->domain;
2342 return res->data.val;
2345 static inline int
2346 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2348 int id = get_id (domain, type, val);
2350 buffer_add_id (buf, id);
2351 return id;
2354 static inline MonoClass*
2355 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2357 MonoClass *klass;
2359 klass = (MonoClass *)decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2360 if (G_UNLIKELY (log_level >= 2) && klass) {
2361 char *s;
2363 s = mono_type_full_name (&klass->byval_arg);
2364 DEBUG_PRINTF (2, "[dbg] recv class [%s]\n", s);
2365 g_free (s);
2367 return klass;
2370 static inline MonoAssembly*
2371 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2373 return (MonoAssembly *)decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2376 static inline MonoImage*
2377 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2379 return (MonoImage *)decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2382 static inline MonoMethod*
2383 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2385 MonoMethod *m;
2387 m = (MonoMethod *)decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2388 if (G_UNLIKELY (log_level >= 2) && m) {
2389 char *s;
2391 s = mono_method_full_name (m, TRUE);
2392 DEBUG_PRINTF (2, "[dbg] recv method [%s]\n", s);
2393 g_free (s);
2395 return m;
2398 static inline MonoClassField*
2399 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2401 return (MonoClassField *)decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2404 static inline MonoDomain*
2405 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2407 return (MonoDomain *)decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2410 static inline MonoProperty*
2411 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2413 return (MonoProperty *)decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2416 static inline void
2417 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2419 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2420 if (G_UNLIKELY (log_level >= 2) && klass) {
2421 char *s;
2423 s = mono_type_full_name (&klass->byval_arg);
2424 if (is_debugger_thread ())
2425 DEBUG_PRINTF (2, "[dbg] send class [%s]\n", s);
2426 else
2427 DEBUG_PRINTF (2, "[%p] send class [%s]\n", (gpointer) (gsize) mono_native_thread_id_get (), s);
2428 g_free (s);
2432 static inline void
2433 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2435 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2436 if (G_UNLIKELY (log_level >= 2) && method) {
2437 char *s;
2439 s = mono_method_full_name (method, 1);
2440 DEBUG_PRINTF (2, "[dbg] send method [%s]\n", s);
2441 g_free (s);
2445 static inline void
2446 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2448 int id;
2450 id = buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2451 if (G_UNLIKELY (log_level >= 2) && assembly)
2452 DEBUG_PRINTF (2, "[dbg] send assembly [%s][%s][%d]\n", assembly->aname.name, domain->friendly_name, id);
2455 static inline void
2456 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2458 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2461 static inline void
2462 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2464 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2467 static inline void
2468 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2470 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2473 static inline void
2474 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2476 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2479 static void invoke_method (void);
2482 * SUSPEND/RESUME
2485 static MonoJitInfo*
2486 get_top_method_ji (gpointer ip, MonoDomain **domain, gpointer *out_ip)
2488 MonoJitInfo *ji;
2490 if (out_ip)
2491 *out_ip = ip;
2493 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, domain);
2494 if (!ji) {
2495 /* Could be an interpreter method */
2497 MonoLMF *lmf = mono_get_lmf ();
2498 MonoInterpFrameHandle *frame;
2500 g_assert (((guint64)lmf->previous_lmf) & 2);
2501 MonoLMFExt *ext = (MonoLMFExt*)lmf;
2503 g_assert (ext->interp_exit);
2504 frame = ext->interp_exit_data;
2505 ji = mono_interp_frame_get_jit_info (frame);
2506 if (domain)
2507 *domain = mono_domain_get ();
2508 if (out_ip)
2509 *out_ip = mono_interp_frame_get_ip (frame);
2511 return ji;
2515 * save_thread_context:
2517 * Set CTX as the current threads context which is used for computing stack traces.
2518 * This function is signal-safe.
2520 static void
2521 save_thread_context (MonoContext *ctx)
2523 DebuggerTlsData *tls;
2525 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2526 g_assert (tls);
2528 if (ctx)
2529 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2530 else
2531 mono_thread_state_init_from_current (&tls->context);
2534 /* Number of threads suspended */
2536 * If this is equal to the size of thread_to_tls, the runtime is considered
2537 * suspended.
2539 static gint32 threads_suspend_count;
2541 static MonoCoopMutex suspend_mutex;
2543 /* Cond variable used to wait for suspend_count becoming 0 */
2544 static MonoCoopCond suspend_cond;
2546 /* Semaphore used to wait for a thread becoming suspended */
2547 static MonoCoopSem suspend_sem;
2549 static void
2550 suspend_init (void)
2552 mono_coop_mutex_init (&suspend_mutex);
2553 mono_coop_cond_init (&suspend_cond);
2554 mono_coop_sem_init (&suspend_sem, 0);
2557 typedef struct
2559 StackFrameInfo last_frame;
2560 gboolean last_frame_set;
2561 MonoContext ctx;
2562 gpointer lmf;
2563 MonoDomain *domain;
2564 } GetLastFrameUserData;
2566 static gboolean
2567 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2569 GetLastFrameUserData *data = (GetLastFrameUserData *)user_data;
2571 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE || info->type == FRAME_TYPE_TRAMPOLINE)
2572 return FALSE;
2574 if (!data->last_frame_set) {
2575 /* Store the last frame */
2576 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2577 data->last_frame_set = TRUE;
2578 return FALSE;
2579 } else {
2580 /* Store the context/lmf for the frame above the last frame */
2581 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2582 data->lmf = info->lmf;
2583 data->domain = info->domain;
2584 return TRUE;
2588 static void
2589 copy_unwind_state_from_frame_data (MonoThreadUnwindState *to, GetLastFrameUserData *data, gpointer jit_tls)
2591 memcpy (&to->ctx, &data->ctx, sizeof (MonoContext));
2593 to->unwind_data [MONO_UNWIND_DATA_DOMAIN] = data->domain;
2594 to->unwind_data [MONO_UNWIND_DATA_LMF] = data->lmf;
2595 to->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = jit_tls;
2596 to->valid = TRUE;
2600 * thread_interrupt:
2602 * Process interruption of a thread. This should be signal safe.
2604 * This always runs in the debugger thread.
2606 static void
2607 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, MonoJitInfo *ji)
2609 gpointer ip;
2610 MonoNativeThreadId tid;
2612 g_assert (info);
2614 ip = MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx);
2615 tid = mono_thread_info_get_tid (info);
2617 // FIXME: Races when the thread leaves managed code before hitting a single step
2618 // event.
2620 if (ji && !ji->is_trampoline) {
2621 /* Running managed code, will be suspended by the single step code */
2622 DEBUG_PRINTF (1, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip);
2623 } else {
2625 * Running native code, will be suspended when it returns to/enters
2626 * managed code. Treat it as already suspended.
2627 * This might interrupt the code in process_single_step_inner (), we use the
2628 * tls->suspending flag to avoid races when that happens.
2630 if (!tls->suspended && !tls->suspending) {
2631 GetLastFrameUserData data;
2633 // FIXME: printf is not signal safe, but this is only used during
2634 // debugger debugging
2635 if (ip)
2636 DEBUG_PRINTF (1, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip);
2637 //save_thread_context (&ctx);
2639 if (!tls->thread)
2640 /* Already terminated */
2641 return;
2644 * We are in a difficult position: we want to be able to provide stack
2645 * traces for this thread, but we can't use the current ctx+lmf, since
2646 * the thread is still running, so it might return to managed code,
2647 * making these invalid.
2648 * So we start a stack walk and save the first frame, along with the
2649 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2650 * suspended when it returns to managed code, so the parent's ctx should
2651 * remain valid.
2653 MonoThreadUnwindState *state = mono_thread_info_get_suspend_state (info);
2655 data.last_frame_set = FALSE;
2656 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, state, MONO_UNWIND_SIGNAL_SAFE, &data);
2657 if (data.last_frame_set) {
2658 gpointer jit_tls = ((MonoThreadInfo*)tls->thread->thread_info)->jit_data;
2660 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2662 if (data.last_frame.type == FRAME_TYPE_INTERP_TO_MANAGED) {
2664 * Store the current lmf instead of the parent one, since that
2665 * contains the interp exit data.
2667 data.lmf = state->unwind_data [MONO_UNWIND_DATA_LMF];
2670 copy_unwind_state_from_frame_data (&tls->async_state, &data, jit_tls);
2671 copy_unwind_state_from_frame_data (&tls->context, &data, jit_tls);
2672 } else {
2673 tls->async_state.valid = FALSE;
2676 mono_memory_barrier ();
2678 tls->suspended = TRUE;
2679 mono_coop_sem_post (&suspend_sem);
2685 * reset_native_thread_suspend_state:
2687 * Reset the suspended flag and state on native threads
2689 static void
2690 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2692 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2694 if (!tls->really_suspended && tls->suspended) {
2695 tls->suspended = FALSE;
2697 * The thread might still be running if it was executing native code, so the state won't be invalided by
2698 * suspend_current ().
2700 tls->context.valid = FALSE;
2701 tls->async_state.valid = FALSE;
2702 invalidate_frames (tls);
2706 typedef struct {
2707 DebuggerTlsData *tls;
2708 gboolean valid_info;
2709 } InterruptData;
2711 static SuspendThreadResult
2712 debugger_interrupt_critical (MonoThreadInfo *info, gpointer user_data)
2714 InterruptData *data = (InterruptData *)user_data;
2715 MonoJitInfo *ji;
2717 data->valid_info = TRUE;
2718 ji = mono_jit_info_table_find_internal (
2719 (MonoDomain *)mono_thread_info_get_suspend_state (info)->unwind_data [MONO_UNWIND_DATA_DOMAIN],
2720 (char *)MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx),
2721 TRUE,
2722 TRUE);
2724 /* This is signal safe */
2725 thread_interrupt (data->tls, info, ji);
2726 return MonoResumeThread;
2730 * notify_thread:
2732 * Notify a thread that it needs to suspend.
2734 static void
2735 notify_thread (gpointer key, gpointer value, gpointer user_data)
2737 MonoInternalThread *thread = (MonoInternalThread *)key;
2738 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2739 MonoNativeThreadId tid = MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid);
2741 if (mono_thread_internal_is_current (thread) || tls->terminated)
2742 return;
2744 DEBUG_PRINTF (1, "[%p] Interrupting %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2746 /* This is _not_ equivalent to mono_thread_internal_abort () */
2747 InterruptData interrupt_data = { 0 };
2748 interrupt_data.tls = tls;
2750 mono_thread_info_safe_suspend_and_run ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE, debugger_interrupt_critical, &interrupt_data);
2751 if (!interrupt_data.valid_info) {
2752 DEBUG_PRINTF (1, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2754 * Attached thread which died without detaching.
2756 tls->terminated = TRUE;
2760 static void
2761 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2763 guint8 *ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
2764 MonoJitInfo *ji;
2765 MonoMethod *method;
2767 if (mono_loader_lock_is_owned_by_self ()) {
2769 * Shortcut for the check in suspend_current (). This speeds up processing
2770 * when executing long running code inside the loader lock, i.e. assembly load
2771 * hooks.
2773 return;
2776 if (is_debugger_thread ())
2777 return;
2779 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2780 if (suspend_count - tls->resume_count > 0)
2781 tls->suspending = TRUE;
2783 DEBUG_PRINTF (1, "[%p] Received single step event for suspending.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2785 if (suspend_count - tls->resume_count == 0) {
2787 * We are executing a single threaded invoke but the single step for
2788 * suspending is still active.
2789 * FIXME: This slows down single threaded invokes.
2791 DEBUG_PRINTF (1, "[%p] Ignored during single threaded invoke.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2792 return;
2795 ji = get_top_method_ji (ip, NULL, NULL);
2796 g_assert (ji);
2797 /* Can't suspend in these methods */
2798 method = jinfo_get_method (ji);
2799 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2800 return;
2802 save_thread_context (ctx);
2804 suspend_current ();
2808 * suspend_vm:
2810 * Increase the suspend count of the VM. While the suspend count is greater
2811 * than 0, runtime threads are suspended at certain points during execution.
2813 static void
2814 suspend_vm (void)
2816 mono_loader_lock ();
2818 mono_coop_mutex_lock (&suspend_mutex);
2820 suspend_count ++;
2822 DEBUG_PRINTF (1, "[%p] Suspending vm...\n", (gpointer) (gsize) mono_native_thread_id_get ());
2824 if (suspend_count == 1) {
2825 // FIXME: Is it safe to call this inside the lock ?
2826 start_single_stepping ();
2827 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2830 mono_coop_mutex_unlock (&suspend_mutex);
2832 if (suspend_count == 1)
2834 * Suspend creation of new threadpool threads, since they cannot run
2836 mono_threadpool_suspend ();
2838 mono_loader_unlock ();
2842 * resume_vm:
2844 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2845 * are resumed.
2847 static void
2848 resume_vm (void)
2850 g_assert (is_debugger_thread ());
2852 mono_loader_lock ();
2854 mono_coop_mutex_lock (&suspend_mutex);
2856 g_assert (suspend_count > 0);
2857 suspend_count --;
2859 DEBUG_PRINTF (1, "[%p] Resuming vm, suspend count=%d...\n", (gpointer) (gsize) mono_native_thread_id_get (), suspend_count);
2861 if (suspend_count == 0) {
2862 // FIXME: Is it safe to call this inside the lock ?
2863 stop_single_stepping ();
2864 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2867 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2868 mono_coop_cond_broadcast (&suspend_cond);
2870 mono_coop_mutex_unlock (&suspend_mutex);
2871 //g_assert (err == 0);
2873 if (suspend_count == 0)
2874 mono_threadpool_resume ();
2876 mono_loader_unlock ();
2880 * resume_thread:
2882 * Resume just one thread.
2884 static void
2885 resume_thread (MonoInternalThread *thread)
2887 DebuggerTlsData *tls;
2889 g_assert (is_debugger_thread ());
2891 mono_loader_lock ();
2893 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
2894 g_assert (tls);
2896 mono_coop_mutex_lock (&suspend_mutex);
2898 g_assert (suspend_count > 0);
2900 DEBUG_PRINTF (1, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid);
2902 tls->resume_count += suspend_count;
2905 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2906 * but only the one whose resume_count field is > 0 will be resumed.
2908 mono_coop_cond_broadcast (&suspend_cond);
2910 mono_coop_mutex_unlock (&suspend_mutex);
2911 //g_assert (err == 0);
2913 mono_loader_unlock ();
2916 static void
2917 free_frames (StackFrame **frames, int nframes)
2919 int i;
2921 for (i = 0; i < nframes; ++i) {
2922 if (frames [i]->jit)
2923 mono_debug_free_method_jit_info (frames [i]->jit);
2924 g_free (frames [i]);
2926 g_free (frames);
2929 static void
2930 invalidate_frames (DebuggerTlsData *tls)
2932 if (!tls)
2933 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2934 g_assert (tls);
2936 free_frames (tls->frames, tls->frame_count);
2937 tls->frame_count = 0;
2938 tls->frames = NULL;
2940 free_frames (tls->restore_frames, tls->restore_frame_count);
2941 tls->restore_frame_count = 0;
2942 tls->restore_frames = NULL;
2946 * suspend_current:
2948 * Suspend the current thread until the runtime is resumed. If the thread has a
2949 * pending invoke, then the invoke is executed before this function returns.
2951 static void
2952 suspend_current (void)
2954 DebuggerTlsData *tls;
2956 g_assert (!is_debugger_thread ());
2958 if (mono_loader_lock_is_owned_by_self ()) {
2960 * If we own the loader mutex, can't suspend until we release it, since the
2961 * whole runtime can deadlock otherwise.
2963 return;
2966 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2967 g_assert (tls);
2969 mono_coop_mutex_lock (&suspend_mutex);
2971 tls->suspending = FALSE;
2972 tls->really_suspended = TRUE;
2974 if (!tls->suspended) {
2975 tls->suspended = TRUE;
2976 mono_coop_sem_post (&suspend_sem);
2979 DEBUG_PRINTF (1, "[%p] Suspended.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2981 while (suspend_count - tls->resume_count > 0) {
2982 mono_coop_cond_wait (&suspend_cond, &suspend_mutex);
2985 tls->suspended = FALSE;
2986 tls->really_suspended = FALSE;
2988 threads_suspend_count --;
2990 mono_coop_mutex_unlock (&suspend_mutex);
2992 DEBUG_PRINTF (1, "[%p] Resumed.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2994 if (tls->pending_invoke) {
2995 /* Save the original context */
2996 tls->pending_invoke->has_ctx = TRUE;
2997 tls->pending_invoke->ctx = tls->context.ctx;
2999 invoke_method ();
3002 /* The frame info becomes invalid after a resume */
3003 tls->context.valid = FALSE;
3004 tls->async_state.valid = FALSE;
3005 invalidate_frames (tls);
3008 static void
3009 count_thread (gpointer key, gpointer value, gpointer user_data)
3011 DebuggerTlsData *tls = (DebuggerTlsData *)value;
3013 if (!tls->suspended && !tls->terminated && !mono_thread_internal_is_current (tls->thread))
3014 *(int*)user_data = *(int*)user_data + 1;
3017 static int
3018 count_threads_to_wait_for (void)
3020 int count = 0;
3022 mono_loader_lock ();
3023 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
3024 mono_loader_unlock ();
3026 return count;
3030 * wait_for_suspend:
3032 * Wait until the runtime is completely suspended.
3034 static void
3035 wait_for_suspend (void)
3037 int nthreads, nwait, err;
3038 gboolean waited = FALSE;
3040 // FIXME: Threads starting/stopping ?
3041 mono_loader_lock ();
3042 nthreads = mono_g_hash_table_size (thread_to_tls);
3043 mono_loader_unlock ();
3045 while (TRUE) {
3046 nwait = count_threads_to_wait_for ();
3047 if (nwait) {
3048 DEBUG_PRINTF (1, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads);
3049 err = mono_coop_sem_wait (&suspend_sem, MONO_SEM_FLAGS_NONE);
3050 g_assert (err == 0);
3051 waited = TRUE;
3052 } else {
3053 break;
3057 if (waited)
3058 DEBUG_PRINTF (1, "%d threads suspended.\n", nthreads);
3062 * is_suspended:
3064 * Return whenever the runtime is suspended.
3066 static gboolean
3067 is_suspended (void)
3069 return count_threads_to_wait_for () == 0;
3072 static void
3073 no_seq_points_found (MonoMethod *method, int offset)
3076 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3078 printf ("Unable to find seq points for method '%s', offset 0x%x.\n", mono_method_full_name (method, TRUE), offset);
3081 typedef struct {
3082 DebuggerTlsData *tls;
3083 GSList *frames;
3084 } ComputeFramesUserData;
3086 static gboolean
3087 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3089 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3090 StackFrame *frame;
3091 MonoMethod *method, *actual_method, *api_method;
3092 SeqPoint sp;
3093 int flags = 0;
3095 if (info->type != FRAME_TYPE_MANAGED && info->type != FRAME_TYPE_INTERP) {
3096 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3097 /* Mark the last frame as an invoke frame */
3098 if (ud->frames)
3099 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3101 return FALSE;
3104 if (info->ji)
3105 method = jinfo_get_method (info->ji);
3106 else
3107 method = info->method;
3108 actual_method = info->actual_method;
3109 api_method = method;
3111 if (!method)
3112 return FALSE;
3114 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3115 return FALSE;
3117 if (info->il_offset == -1) {
3118 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3119 if (ud->frames == NULL) {
3120 if (mono_find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL, &sp))
3121 info->il_offset = sp.il_offset;
3123 if (info->il_offset == -1)
3124 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3127 DEBUG_PRINTF (1, "\tFrame: %s:[il=0x%x, native=0x%x] %d\n", mono_method_full_name (method, TRUE), info->il_offset, info->native_offset, info->managed);
3129 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3130 if (!CHECK_PROTOCOL_VERSION (2, 17))
3131 /* Older clients can't handle this flag */
3132 return FALSE;
3133 api_method = mono_marshal_method_from_wrapper (method);
3134 if (!api_method)
3135 return FALSE;
3136 actual_method = api_method;
3137 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3140 frame = g_new0 (StackFrame, 1);
3141 frame->method = method;
3142 frame->actual_method = actual_method;
3143 frame->api_method = api_method;
3144 frame->il_offset = info->il_offset;
3145 frame->native_offset = info->native_offset;
3146 frame->flags = flags;
3147 frame->ji = info->ji;
3148 frame->interp_frame = info->interp_frame;
3149 if (info->reg_locations)
3150 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3151 if (ctx) {
3152 frame->ctx = *ctx;
3153 frame->has_ctx = TRUE;
3155 frame->domain = info->domain;
3157 ud->frames = g_slist_append (ud->frames, frame);
3159 return FALSE;
3162 static gboolean
3163 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3165 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3168 * 'tls->filter_ctx' is the location of the throw site.
3170 * mono_walk_stack() will never actually hit the throw site, but unwind
3171 * directly from the filter to the call site; we abort stack unwinding here
3172 * once this happens and resume from the throw site.
3175 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3176 return TRUE;
3178 return process_frame (info, ctx, user_data);
3182 * Return a malloc-ed list of StackFrame structures.
3184 static StackFrame**
3185 compute_frame_info_from (MonoInternalThread *thread, DebuggerTlsData *tls, MonoThreadUnwindState *state, int *out_nframes)
3187 ComputeFramesUserData user_data;
3188 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3189 StackFrame **res;
3190 int i, nframes;
3191 GSList *l;
3193 user_data.tls = tls;
3194 user_data.frames = NULL;
3196 mono_walk_stack_with_state (process_frame, state, opts, &user_data);
3198 nframes = g_slist_length (user_data.frames);
3199 res = g_new0 (StackFrame*, nframes);
3200 l = user_data.frames;
3201 for (i = 0; i < nframes; ++i) {
3202 res [i] = (StackFrame *)l->data;
3203 l = l->next;
3205 *out_nframes = nframes;
3207 return res;
3210 static void
3211 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3213 ComputeFramesUserData user_data;
3214 GSList *tmp;
3215 int i, findex, new_frame_count;
3216 StackFrame **new_frames, *f;
3217 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3219 // FIXME: Locking on tls
3220 if (tls->frames && tls->frames_up_to_date)
3221 return;
3223 DEBUG_PRINTF (1, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid);
3225 user_data.tls = tls;
3226 user_data.frames = NULL;
3227 if (tls->terminated) {
3228 tls->frame_count = 0;
3229 return;
3230 } if (!tls->really_suspended && tls->async_state.valid) {
3231 /* Have to use the state saved by the signal handler */
3232 process_frame (&tls->async_last_frame, NULL, &user_data);
3233 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3234 } else if (tls->filter_state.valid) {
3236 * We are inside an exception filter.
3238 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3240 if (tls->context.valid)
3241 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3243 * After that, we resume unwinding from the location where the exception has been thrown.
3245 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3246 } else if (tls->context.valid) {
3247 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3248 } else {
3249 // FIXME:
3250 tls->frame_count = 0;
3251 return;
3254 new_frame_count = g_slist_length (user_data.frames);
3255 new_frames = g_new0 (StackFrame*, new_frame_count);
3256 findex = 0;
3257 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3258 f = (StackFrame *)tmp->data;
3261 * Reuse the id for already existing stack frames, so invokes don't invalidate
3262 * the still valid stack frames.
3264 for (i = 0; i < tls->frame_count; ++i) {
3265 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3266 f->id = tls->frames [i]->id;
3267 break;
3271 if (i >= tls->frame_count)
3272 f->id = InterlockedIncrement (&frame_id);
3274 new_frames [findex ++] = f;
3277 g_slist_free (user_data.frames);
3279 invalidate_frames (tls);
3281 tls->frames = new_frames;
3282 tls->frame_count = new_frame_count;
3283 tls->frames_up_to_date = TRUE;
3287 * GHFunc to emit an appdomain creation event
3288 * @param key Don't care
3289 * @param value A loaded appdomain
3290 * @param user_data Don't care
3292 static void
3293 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3295 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3296 g_hash_table_foreach (get_agent_domain_info ((MonoDomain *)value)->loaded_classes, emit_type_load, NULL);
3300 * GHFunc to emit a thread start event
3301 * @param key A thread id
3302 * @param value A thread object
3303 * @param user_data Don't care
3305 static void
3306 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3308 g_assert (!mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (GPOINTER_TO_UINT (key)), debugger_thread_id));
3309 process_profiler_event (EVENT_KIND_THREAD_START, value);
3313 * GFunc to emit an assembly load event
3314 * @param value A loaded assembly
3315 * @param user_data Don't care
3317 static void
3318 emit_assembly_load (gpointer value, gpointer user_data)
3320 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3324 * GFunc to emit a type load event
3325 * @param value A loaded type
3326 * @param user_data Don't care
3328 static void
3329 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3331 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3334 static char*
3335 strdup_tolower (char *s)
3337 char *s2, *p;
3339 s2 = g_strdup (s);
3340 for (p = s2; *p; ++p)
3341 *p = tolower (*p);
3342 return s2;
3346 * Same as g_path_get_basename () but handles windows paths as well,
3347 * which can occur in .mdb files created by pdb2mdb.
3349 static char*
3350 dbg_path_get_basename (const char *filename)
3352 char *r;
3354 if (!filename || strchr (filename, '/') || !strchr (filename, '\\'))
3355 return g_path_get_basename (filename);
3357 /* From gpath.c */
3359 /* No separator -> filename */
3360 r = strrchr (filename, '\\');
3361 if (r == NULL)
3362 return g_strdup (filename);
3364 /* Trailing slash, remove component */
3365 if (r [1] == 0){
3366 char *copy = g_strdup (filename);
3367 copy [r-filename] = 0;
3368 r = strrchr (copy, '\\');
3370 if (r == NULL){
3371 g_free (copy);
3372 return g_strdup ("/");
3374 r = g_strdup (&r[1]);
3375 g_free (copy);
3376 return r;
3379 return g_strdup (&r[1]);
3382 static void
3383 init_jit_info_dbg_attrs (MonoJitInfo *ji)
3385 static MonoClass *hidden_klass, *step_through_klass, *non_user_klass;
3386 MonoError error;
3387 MonoCustomAttrInfo *ainfo;
3389 if (ji->dbg_attrs_inited)
3390 return;
3392 if (!hidden_klass)
3393 hidden_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3395 if (!step_through_klass)
3396 step_through_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3398 if (!non_user_klass)
3399 non_user_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute");
3401 ainfo = mono_custom_attrs_from_method_checked (jinfo_get_method (ji), &error);
3402 mono_error_cleanup (&error); /* FIXME don't swallow the error? */
3403 if (ainfo) {
3404 if (mono_custom_attrs_has_attr (ainfo, hidden_klass))
3405 ji->dbg_hidden = TRUE;
3406 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3407 ji->dbg_step_through = TRUE;
3408 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3409 ji->dbg_non_user_code = TRUE;
3410 mono_custom_attrs_free (ainfo);
3413 ainfo = mono_custom_attrs_from_class_checked (jinfo_get_method (ji)->klass, &error);
3414 mono_error_cleanup (&error); /* FIXME don't swallow the error? */
3415 if (ainfo) {
3416 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3417 ji->dbg_step_through = TRUE;
3418 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3419 ji->dbg_non_user_code = TRUE;
3420 mono_custom_attrs_free (ainfo);
3423 mono_memory_barrier ();
3424 ji->dbg_attrs_inited = TRUE;
3428 * EVENT HANDLING
3432 * create_event_list:
3434 * Return a list of event request ids matching EVENT, starting from REQS, which
3435 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3436 * policy.
3437 * We return request ids, instead of requests, to simplify threading, since
3438 * requests could be deleted anytime when the loader lock is not held.
3439 * LOCKING: Assumes the loader lock is held.
3441 static GSList*
3442 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3444 int i, j;
3445 GSList *events = NULL;
3447 *suspend_policy = SUSPEND_POLICY_NONE;
3449 if (!reqs)
3450 reqs = event_requests;
3452 if (!reqs)
3453 return NULL;
3455 for (i = 0; i < reqs->len; ++i) {
3456 EventRequest *req = (EventRequest *)g_ptr_array_index (reqs, i);
3457 if (req->event_kind == event) {
3458 gboolean filtered = FALSE;
3460 /* Apply filters */
3461 for (j = 0; j < req->nmodifiers; ++j) {
3462 Modifier *mod = &req->modifiers [j];
3464 if (mod->kind == MOD_KIND_COUNT) {
3465 filtered = TRUE;
3466 if (mod->data.count > 0) {
3467 if (mod->data.count > 0) {
3468 mod->data.count --;
3469 if (mod->data.count == 0)
3470 filtered = FALSE;
3473 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3474 if (mod->data.thread != mono_thread_internal_current ())
3475 filtered = TRUE;
3476 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3477 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3478 filtered = TRUE;
3479 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3480 filtered = TRUE;
3481 if (ei->caught && !mod->caught)
3482 filtered = TRUE;
3483 if (!ei->caught && !mod->uncaught)
3484 filtered = TRUE;
3485 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3486 int k;
3487 gboolean found = FALSE;
3488 MonoAssembly **assemblies = mod->data.assemblies;
3490 if (assemblies) {
3491 for (k = 0; assemblies [k]; ++k)
3492 if (assemblies [k] == jinfo_get_method (ji)->klass->image->assembly)
3493 found = TRUE;
3495 if (!found)
3496 filtered = TRUE;
3497 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3498 gpointer iter = NULL;
3499 MonoMethod *method;
3500 MonoDebugSourceInfo *sinfo;
3501 char *source_file, *s;
3502 gboolean found = FALSE;
3503 int i;
3504 GPtrArray *source_file_list;
3506 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3507 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3509 if (minfo) {
3510 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, NULL, NULL, NULL);
3511 for (i = 0; i < source_file_list->len; ++i) {
3512 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
3514 * Do a case-insesitive match by converting the file name to
3515 * lowercase.
3517 s = strdup_tolower (sinfo->source_file);
3518 if (g_hash_table_lookup (mod->data.source_files, s))
3519 found = TRUE;
3520 else {
3521 char *s2 = dbg_path_get_basename (sinfo->source_file);
3522 char *s3 = strdup_tolower (s2);
3524 if (g_hash_table_lookup (mod->data.source_files, s3))
3525 found = TRUE;
3526 g_free (s2);
3527 g_free (s3);
3529 g_free (s);
3531 g_ptr_array_free (source_file_list, TRUE);
3534 if (!found)
3535 filtered = TRUE;
3536 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3537 char *s;
3539 s = mono_type_full_name (&ei->klass->byval_arg);
3540 if (!g_hash_table_lookup (mod->data.type_names, s))
3541 filtered = TRUE;
3542 g_free (s);
3543 } else if (mod->kind == MOD_KIND_STEP) {
3544 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3545 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3546 !strcmp (jinfo_get_method (ji)->name, ".cctor") &&
3547 (jinfo_get_method (ji) != ((SingleStepReq*)req->info)->start_method))
3548 filtered = TRUE;
3549 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3550 init_jit_info_dbg_attrs (ji);
3551 if (ji->dbg_hidden)
3552 filtered = TRUE;
3554 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3555 init_jit_info_dbg_attrs (ji);
3556 if (ji->dbg_step_through)
3557 filtered = TRUE;
3559 if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3560 init_jit_info_dbg_attrs (ji);
3561 if (ji->dbg_non_user_code)
3562 filtered = TRUE;
3567 if (!filtered) {
3568 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3569 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3574 /* Send a VM START/DEATH event by default */
3575 if (event == EVENT_KIND_VM_START)
3576 events = g_slist_append (events, GINT_TO_POINTER (0));
3577 if (event == EVENT_KIND_VM_DEATH)
3578 events = g_slist_append (events, GINT_TO_POINTER (0));
3580 return events;
3583 static G_GNUC_UNUSED const char*
3584 event_to_string (EventKind event)
3586 switch (event) {
3587 case EVENT_KIND_VM_START: return "VM_START";
3588 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3589 case EVENT_KIND_THREAD_START: return "THREAD_START";
3590 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3591 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3592 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3593 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3594 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3595 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3596 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3597 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3598 case EVENT_KIND_STEP: return "STEP";
3599 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3600 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3601 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3602 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3603 case EVENT_KIND_USER_LOG: return "USER_LOG";
3604 default:
3605 g_assert_not_reached ();
3606 return "";
3611 * process_event:
3613 * Send an event to the client, suspending the vm if needed.
3614 * LOCKING: Since this can suspend the calling thread, no locks should be held
3615 * by the caller.
3616 * The EVENTS list is freed by this function.
3618 static void
3619 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3621 Buffer buf;
3622 GSList *l;
3623 MonoDomain *domain = mono_domain_get ();
3624 MonoThread *thread = NULL;
3625 MonoObject *keepalive_obj = NULL;
3626 gboolean send_success = FALSE;
3627 static int ecount;
3628 int nevents;
3630 if (!inited) {
3631 DEBUG_PRINTF (2, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event));
3632 return;
3635 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3636 // FIXME: We miss those events
3637 DEBUG_PRINTF (2, "VM start event not sent yet: dropping %s\n", event_to_string (event));
3638 return;
3641 if (vm_death_event_sent) {
3642 DEBUG_PRINTF (2, "VM death event has been sent: dropping %s\n", event_to_string (event));
3643 return;
3646 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3647 DEBUG_PRINTF (2, "Mono runtime is shutting down: dropping %s\n", event_to_string (event));
3648 return;
3651 if (disconnected) {
3652 DEBUG_PRINTF (2, "Debugger client is not connected: dropping %s\n", event_to_string (event));
3653 return;
3656 if (event == EVENT_KIND_KEEPALIVE)
3657 suspend_policy = SUSPEND_POLICY_NONE;
3658 else {
3659 if (events == NULL)
3660 return;
3662 if (agent_config.defer) {
3663 /* Make sure the thread id is always set when doing deferred debugging */
3664 if (is_debugger_thread ()) {
3665 /* Don't suspend on events from the debugger thread */
3666 suspend_policy = SUSPEND_POLICY_NONE;
3667 thread = mono_thread_get_main ();
3669 else thread = mono_thread_current ();
3670 } else {
3671 if (is_debugger_thread () && event != EVENT_KIND_VM_DEATH)
3672 // FIXME: Send these with a NULL thread, don't suspend the current thread
3673 return;
3677 nevents = g_slist_length (events);
3678 buffer_init (&buf, 128);
3679 buffer_add_byte (&buf, suspend_policy);
3680 buffer_add_int (&buf, nevents);
3682 for (l = events; l; l = l->next) {
3683 buffer_add_byte (&buf, event); // event kind
3684 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3686 ecount ++;
3688 if (event == EVENT_KIND_VM_DEATH) {
3689 thread = NULL;
3690 } else {
3691 if (!thread)
3692 thread = mono_thread_current ();
3694 if (event == EVENT_KIND_VM_START && arg != NULL)
3695 thread = (MonoThread *)arg;
3698 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3700 switch (event) {
3701 case EVENT_KIND_THREAD_START:
3702 case EVENT_KIND_THREAD_DEATH:
3703 break;
3704 case EVENT_KIND_APPDOMAIN_CREATE:
3705 case EVENT_KIND_APPDOMAIN_UNLOAD:
3706 buffer_add_domainid (&buf, (MonoDomain *)arg);
3707 break;
3708 case EVENT_KIND_METHOD_ENTRY:
3709 case EVENT_KIND_METHOD_EXIT:
3710 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3711 break;
3712 case EVENT_KIND_ASSEMBLY_LOAD:
3713 buffer_add_assemblyid (&buf, domain, (MonoAssembly *)arg);
3714 break;
3715 case EVENT_KIND_ASSEMBLY_UNLOAD: {
3716 DebuggerTlsData *tls;
3718 /* The domain the assembly belonged to is not equal to the current domain */
3719 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3720 g_assert (tls);
3721 g_assert (tls->domain_unloading);
3723 buffer_add_assemblyid (&buf, tls->domain_unloading, (MonoAssembly *)arg);
3724 break;
3726 case EVENT_KIND_TYPE_LOAD:
3727 buffer_add_typeid (&buf, domain, (MonoClass *)arg);
3728 break;
3729 case EVENT_KIND_BREAKPOINT:
3730 case EVENT_KIND_STEP:
3731 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3732 buffer_add_long (&buf, il_offset);
3733 break;
3734 case EVENT_KIND_VM_START:
3735 buffer_add_domainid (&buf, mono_get_root_domain ());
3736 break;
3737 case EVENT_KIND_VM_DEATH:
3738 if (CHECK_PROTOCOL_VERSION (2, 27))
3739 buffer_add_int (&buf, mono_environment_exitcode_get ());
3740 break;
3741 case EVENT_KIND_EXCEPTION: {
3742 EventInfo *ei = (EventInfo *)arg;
3743 buffer_add_objid (&buf, ei->exc);
3745 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3746 * later after the suspension. (#12494).
3748 keepalive_obj = ei->exc;
3749 break;
3751 case EVENT_KIND_USER_BREAK:
3752 break;
3753 case EVENT_KIND_USER_LOG: {
3754 EventInfo *ei = (EventInfo *)arg;
3755 buffer_add_int (&buf, ei->level);
3756 buffer_add_string (&buf, ei->category ? ei->category : "");
3757 buffer_add_string (&buf, ei->message ? ei->message : "");
3758 break;
3760 case EVENT_KIND_KEEPALIVE:
3761 suspend_policy = SUSPEND_POLICY_NONE;
3762 break;
3763 default:
3764 g_assert_not_reached ();
3768 if (event == EVENT_KIND_VM_START) {
3769 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3770 if (!agent_config.defer)
3771 start_debugger_thread ();
3774 if (event == EVENT_KIND_VM_DEATH) {
3775 vm_death_event_sent = TRUE;
3776 suspend_policy = SUSPEND_POLICY_NONE;
3779 if (mono_runtime_is_shutting_down ())
3780 suspend_policy = SUSPEND_POLICY_NONE;
3782 if (suspend_policy != SUSPEND_POLICY_NONE) {
3784 * Save the thread context and start suspending before sending the packet,
3785 * since we could be receiving the resume request before send_packet ()
3786 * returns.
3788 save_thread_context (ctx);
3789 suspend_vm ();
3791 if (keepalive_obj)
3792 /* This will keep this object alive */
3793 get_objref (keepalive_obj);
3796 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3798 buffer_free (&buf);
3800 g_slist_free (events);
3801 events = NULL;
3803 if (!send_success) {
3804 DEBUG_PRINTF (2, "Sending command %s failed.\n", event_to_string (event));
3805 return;
3808 if (event == EVENT_KIND_VM_START) {
3809 vm_start_event_sent = TRUE;
3812 DEBUG_PRINTF (1, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer) (gsize) mono_native_thread_id_get (), nevents, event_to_string (event), ecount, suspend_policy);
3814 switch (suspend_policy) {
3815 case SUSPEND_POLICY_NONE:
3816 break;
3817 case SUSPEND_POLICY_ALL:
3818 suspend_current ();
3819 break;
3820 case SUSPEND_POLICY_EVENT_THREAD:
3821 NOT_IMPLEMENTED;
3822 break;
3823 default:
3824 g_assert_not_reached ();
3828 static void
3829 process_profiler_event (EventKind event, gpointer arg)
3831 int suspend_policy;
3832 GSList *events;
3833 EventInfo ei, *ei_arg = NULL;
3835 if (event == EVENT_KIND_TYPE_LOAD) {
3836 ei.klass = (MonoClass *)arg;
3837 ei_arg = &ei;
3840 mono_loader_lock ();
3841 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3842 mono_loader_unlock ();
3844 process_event (event, arg, 0, NULL, events, suspend_policy);
3847 static void
3848 runtime_initialized (MonoProfiler *prof)
3850 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3851 if (agent_config.defer)
3852 start_debugger_thread ();
3855 static void
3856 runtime_shutdown (MonoProfiler *prof)
3858 process_profiler_event (EVENT_KIND_VM_DEATH, NULL);
3860 mono_debugger_agent_cleanup ();
3863 static void
3864 thread_startup (MonoProfiler *prof, uintptr_t tid)
3866 MonoInternalThread *thread = mono_thread_internal_current ();
3867 MonoInternalThread *old_thread;
3868 DebuggerTlsData *tls;
3870 if (is_debugger_thread ())
3871 return;
3873 g_assert (mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (tid), MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid)));
3875 mono_loader_lock ();
3876 old_thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3877 mono_loader_unlock ();
3878 if (old_thread) {
3879 if (thread == old_thread) {
3881 * For some reason, thread_startup () might be called for the same thread
3882 * multiple times (attach ?).
3884 DEBUG_PRINTF (1, "[%p] thread_start () called multiple times for %p, ignored.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3885 return;
3886 } else {
3888 * thread_end () might not be called for some threads, and the tid could
3889 * get reused.
3891 DEBUG_PRINTF (1, "[%p] Removing stale data for tid %p.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
3892 mono_loader_lock ();
3893 mono_g_hash_table_remove (thread_to_tls, old_thread);
3894 mono_g_hash_table_remove (tid_to_thread, GUINT_TO_POINTER (tid));
3895 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3896 mono_loader_unlock ();
3900 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3901 g_assert (!tls);
3902 // FIXME: Free this somewhere
3903 tls = g_new0 (DebuggerTlsData, 1);
3904 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread, MONO_ROOT_SOURCE_DEBUGGER, "debugger thread reference");
3905 tls->thread = thread;
3906 mono_native_tls_set_value (debugger_tls_id, tls);
3908 DEBUG_PRINTF (1, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3910 mono_loader_lock ();
3911 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3912 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3913 mono_g_hash_table_insert (tid_to_thread_obj, GUINT_TO_POINTER (tid), mono_thread_current ());
3914 mono_loader_unlock ();
3916 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3919 * suspend_vm () could have missed this thread, so wait for a resume.
3921 suspend_current ();
3924 static void
3925 thread_end (MonoProfiler *prof, uintptr_t tid)
3927 MonoInternalThread *thread;
3928 DebuggerTlsData *tls = NULL;
3930 mono_loader_lock ();
3931 thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
3932 if (thread) {
3933 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
3934 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
3935 if (tls) {
3936 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
3937 tls->terminated = TRUE;
3938 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
3939 MONO_GC_UNREGISTER_ROOT (tls->thread);
3940 tls->thread = NULL;
3943 mono_loader_unlock ();
3945 /* We might be called for threads started before we registered the start callback */
3946 if (thread) {
3947 DEBUG_PRINTF (1, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
3949 if (mono_thread_internal_is_current (thread) && !mono_native_tls_get_value (debugger_tls_id)
3952 * This can happen on darwin since we deregister threads using pthread dtors.
3953 * process_profiler_event () and the code it calls cannot handle a null TLS value.
3955 return;
3958 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
3962 static void
3963 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
3965 mono_loader_lock ();
3966 g_hash_table_insert (domains, domain, domain);
3967 mono_loader_unlock ();
3969 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
3972 static void
3973 appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain)
3975 DebuggerTlsData *tls;
3977 /* This might be called during shutdown on the debugger thread from the CMD_VM_EXIT code */
3978 if (is_debugger_thread ())
3979 return;
3982 * Remember the currently unloading appdomain as it is needed to generate
3983 * proper ids for unloading assemblies.
3985 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3986 g_assert (tls);
3987 tls->domain_unloading = domain;
3990 static void
3991 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
3993 DebuggerTlsData *tls;
3995 if (is_debugger_thread ())
3996 return;
3998 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3999 g_assert (tls);
4000 tls->domain_unloading = NULL;
4002 clear_breakpoints_for_domain (domain);
4004 mono_loader_lock ();
4005 /* Invalidate each thread's frame stack */
4006 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
4007 mono_loader_unlock ();
4009 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
4013 * invalidate_each_thread:
4015 * A GHFunc to invalidate frames.
4016 * value must be a DebuggerTlsData*
4018 static void
4019 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
4021 invalidate_frames ((DebuggerTlsData *)value);
4024 static void
4025 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
4027 /* Sent later in jit_end () */
4028 dbg_lock ();
4029 g_ptr_array_add (pending_assembly_loads, assembly);
4030 dbg_unlock ();
4033 static void
4034 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
4036 if (is_debugger_thread ())
4037 return;
4039 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
4041 clear_event_requests_for_assembly (assembly);
4042 clear_types_for_assembly (assembly);
4045 static void
4046 send_type_load (MonoClass *klass)
4048 gboolean type_load = FALSE;
4049 MonoDomain *domain = mono_domain_get ();
4050 AgentDomainInfo *info = NULL;
4052 info = get_agent_domain_info (domain);
4054 mono_loader_lock ();
4056 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
4057 type_load = TRUE;
4058 g_hash_table_insert (info->loaded_classes, klass, klass);
4061 mono_loader_unlock ();
4063 if (type_load)
4064 emit_type_load (klass, klass, NULL);
4068 * Emit load events for all types currently loaded in the domain.
4069 * Takes the loader and domain locks.
4070 * user_data is unused.
4072 static void
4073 send_types_for_domain (MonoDomain *domain, void *user_data)
4075 MonoDomain* old_domain;
4076 AgentDomainInfo *info = NULL;
4078 info = get_agent_domain_info (domain);
4079 g_assert (info);
4081 old_domain = mono_domain_get ();
4083 mono_domain_set (domain, TRUE);
4085 mono_loader_lock ();
4086 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4087 mono_loader_unlock ();
4089 mono_domain_set (old_domain, TRUE);
4092 static void
4093 send_assemblies_for_domain (MonoDomain *domain, void *user_data)
4095 GSList *tmp;
4096 MonoDomain* old_domain;
4098 old_domain = mono_domain_get ();
4100 mono_domain_set (domain, TRUE);
4102 mono_domain_assemblies_lock (domain);
4103 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
4104 MonoAssembly* ass = (MonoAssembly *)tmp->data;
4105 emit_assembly_load (ass, NULL);
4107 mono_domain_assemblies_unlock (domain);
4109 mono_domain_set (old_domain, TRUE);
4112 static void
4113 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
4116 * We emit type load events when the first method of the type is JITted,
4117 * since the class load profiler callbacks might be called with the
4118 * loader lock held. They could also occur in the debugger thread.
4119 * Same for assembly load events.
4121 while (TRUE) {
4122 MonoAssembly *assembly = NULL;
4124 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4125 dbg_lock ();
4126 if (pending_assembly_loads->len > 0) {
4127 assembly = (MonoAssembly *)g_ptr_array_index (pending_assembly_loads, 0);
4128 g_ptr_array_remove_index (pending_assembly_loads, 0);
4130 dbg_unlock ();
4132 if (assembly) {
4133 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4134 } else {
4135 break;
4139 send_type_load (method->klass);
4141 if (!result && jinfo)
4142 add_pending_breakpoints (method, jinfo);
4146 * BREAKPOINTS/SINGLE STEPPING
4150 * Contains information about an inserted breakpoint.
4152 typedef struct {
4153 long il_offset, native_offset;
4154 guint8 *ip;
4155 MonoJitInfo *ji;
4156 MonoDomain *domain;
4157 } BreakpointInstance;
4160 * Contains generic information about a breakpoint.
4162 typedef struct {
4164 * The method where the breakpoint is placed. Can be NULL in which case it
4165 * is inserted into every method. This is used to implement method entry/
4166 * exit events. Can be a generic method definition, in which case the
4167 * breakpoint is inserted into every instance.
4169 MonoMethod *method;
4170 long il_offset;
4171 EventRequest *req;
4173 * A list of BreakpointInstance structures describing where the breakpoint
4174 * was inserted. There could be more than one because of
4175 * generics/appdomains/method entry/exit.
4177 GPtrArray *children;
4178 } MonoBreakpoint;
4180 /* List of breakpoints */
4181 /* Protected by the loader lock */
4182 static GPtrArray *breakpoints;
4183 /* Maps breakpoint locations to the number of breakpoints at that location */
4184 static GHashTable *bp_locs;
4186 static void
4187 breakpoints_init (void)
4189 breakpoints = g_ptr_array_new ();
4190 bp_locs = g_hash_table_new (NULL, NULL);
4194 * insert_breakpoint:
4196 * Insert the breakpoint described by BP into the method described by
4197 * JI.
4199 static void
4200 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4202 int count;
4203 BreakpointInstance *inst;
4204 SeqPointIterator it;
4205 gboolean it_has_sp = FALSE;
4207 if (error)
4208 error_init (error);
4210 mono_seq_point_iterator_init (&it, seq_points);
4211 while (mono_seq_point_iterator_next (&it)) {
4212 if (it.seq_point.il_offset == bp->il_offset) {
4213 it_has_sp = TRUE;
4214 break;
4218 if (!it_has_sp) {
4220 * The set of IL offsets with seq points doesn't completely match the
4221 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4223 mono_seq_point_iterator_init (&it, seq_points);
4224 while (mono_seq_point_iterator_next (&it)) {
4225 if (it.seq_point.il_offset != METHOD_ENTRY_IL_OFFSET &&
4226 it.seq_point.il_offset != METHOD_EXIT_IL_OFFSET &&
4227 it.seq_point.il_offset + 1 == bp->il_offset) {
4228 it_has_sp = TRUE;
4229 break;
4234 if (!it_has_sp) {
4235 char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d", mono_method_full_name (jinfo_get_method (ji), TRUE), bp->il_offset);
4237 mono_seq_point_iterator_init (&it, seq_points);
4238 while (mono_seq_point_iterator_next (&it))
4239 DEBUG_PRINTF (1, "%d\n", it.seq_point.il_offset);
4241 if (error) {
4242 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4243 g_warning ("%s", s);
4244 g_free (s);
4245 return;
4246 } else {
4247 g_warning ("%s", s);
4248 g_free (s);
4249 return;
4253 inst = g_new0 (BreakpointInstance, 1);
4254 inst->il_offset = it.seq_point.il_offset;
4255 inst->native_offset = it.seq_point.native_offset;
4256 inst->ip = (guint8*)ji->code_start + it.seq_point.native_offset;
4257 inst->ji = ji;
4258 inst->domain = domain;
4260 mono_loader_lock ();
4262 g_ptr_array_add (bp->children, inst);
4264 mono_loader_unlock ();
4266 dbg_lock ();
4267 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4268 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4269 dbg_unlock ();
4271 if (it.seq_point.native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4272 DEBUG_PRINTF (1, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset);
4273 } else if (count == 0) {
4274 if (ji->is_interp) {
4275 mono_interp_set_breakpoint (ji, inst->ip);
4276 } else {
4277 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4278 mono_arch_set_breakpoint (ji, inst->ip);
4279 #else
4280 NOT_IMPLEMENTED;
4281 #endif
4285 DEBUG_PRINTF (1, "[dbg] Inserted breakpoint at %s:[il=0x%x,native=0x%x] [%p](%d).\n", mono_method_full_name (jinfo_get_method (ji), TRUE), (int)it.seq_point.il_offset, (int)it.seq_point.native_offset, inst->ip, count);
4288 static void
4289 remove_breakpoint (BreakpointInstance *inst)
4291 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4292 int count;
4293 MonoJitInfo *ji = inst->ji;
4294 guint8 *ip = inst->ip;
4296 dbg_lock ();
4297 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4298 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4299 dbg_unlock ();
4301 g_assert (count > 0);
4303 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4304 if (ji->is_interp)
4305 mono_interp_clear_breakpoint (ji, ip);
4306 else
4307 mono_arch_clear_breakpoint (ji, ip);
4308 DEBUG_PRINTF (1, "[dbg] Clear breakpoint at %s [%p].\n", mono_method_full_name (jinfo_get_method (ji), TRUE), ip);
4310 #else
4311 NOT_IMPLEMENTED;
4312 #endif
4316 * This doesn't take any locks.
4318 static inline gboolean
4319 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4321 int i;
4323 if (!bp->method)
4324 return TRUE;
4325 if (method == bp->method)
4326 return TRUE;
4327 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4328 return TRUE;
4330 if (bp->method->is_inflated && method->is_inflated) {
4331 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4332 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4334 /* Open generic methods should match closed generic methods of the same class */
4335 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4336 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4337 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4339 /* FIXME: Handle !mvar */
4340 if (t1->type != MONO_TYPE_MVAR)
4341 return FALSE;
4343 return TRUE;
4347 return FALSE;
4351 * add_pending_breakpoints:
4353 * Insert pending breakpoints into the newly JITted method METHOD.
4355 static void
4356 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4358 int i, j;
4359 MonoSeqPointInfo *seq_points;
4360 MonoDomain *domain;
4361 MonoMethod *jmethod;
4363 if (!breakpoints)
4364 return;
4366 domain = mono_domain_get ();
4368 mono_loader_lock ();
4370 for (i = 0; i < breakpoints->len; ++i) {
4371 MonoBreakpoint *bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4372 gboolean found = FALSE;
4374 if (!bp_matches_method (bp, method))
4375 continue;
4377 for (j = 0; j < bp->children->len; ++j) {
4378 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4380 if (inst->ji == ji)
4381 found = TRUE;
4384 if (!found) {
4385 MonoMethod *declaring = NULL;
4387 jmethod = jinfo_get_method (ji);
4388 if (jmethod->is_inflated)
4389 declaring = mono_method_get_declaring_generic_method (jmethod);
4391 mono_domain_lock (domain);
4392 seq_points = (MonoSeqPointInfo *)g_hash_table_lookup (domain_jit_info (domain)->seq_points, jmethod);
4393 if (!seq_points && declaring)
4394 seq_points = (MonoSeqPointInfo *)g_hash_table_lookup (domain_jit_info (domain)->seq_points, declaring);
4395 mono_domain_unlock (domain);
4396 if (!seq_points)
4397 /* Could be AOT code */
4398 continue;
4399 g_assert (seq_points);
4401 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4405 mono_loader_unlock ();
4408 static void
4409 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4411 gpointer code;
4412 MonoJitInfo *ji;
4414 if (error)
4415 error_init (error);
4417 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4418 if (!code) {
4419 MonoError oerror;
4421 /* Might be AOTed code */
4422 mono_class_init (method->klass);
4423 code = mono_aot_get_method_checked (domain, method, &oerror);
4424 if (code) {
4425 mono_error_assert_ok (&oerror);
4426 ji = mono_jit_info_table_find (domain, (char *)code);
4427 } else {
4428 /* Might be interpreted */
4429 ji = mono_interp_find_jit_info (domain, method);
4431 g_assert (ji);
4434 insert_breakpoint (seq_points, domain, ji, bp, error);
4437 static void
4438 clear_breakpoint (MonoBreakpoint *bp);
4441 * set_breakpoint:
4443 * Set a breakpoint at IL_OFFSET in METHOD.
4444 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4445 * METHOD can also be a generic method definition, in which case a breakpoint
4446 * is placed in all instances of the method.
4447 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4448 * inserted.
4450 static MonoBreakpoint*
4451 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4453 MonoBreakpoint *bp;
4454 GHashTableIter iter, iter2;
4455 MonoDomain *domain;
4456 MonoMethod *m;
4457 MonoSeqPointInfo *seq_points;
4458 GPtrArray *methods;
4459 GPtrArray *method_domains;
4460 GPtrArray *method_seq_points;
4461 int i;
4463 if (error)
4464 error_init (error);
4466 // FIXME:
4467 // - suspend/resume the vm to prevent code patching problems
4468 // - multiple breakpoints on the same location
4469 // - dynamic methods
4470 // - races
4472 bp = g_new0 (MonoBreakpoint, 1);
4473 bp->method = method;
4474 bp->il_offset = il_offset;
4475 bp->req = req;
4476 bp->children = g_ptr_array_new ();
4478 DEBUG_PRINTF (1, "[dbg] Setting %sbreakpoint at %s:0x%x.\n", (req->event_kind == EVENT_KIND_STEP) ? "single step " : "", method ? mono_method_full_name (method, TRUE) : "<all>", (int)il_offset);
4480 methods = g_ptr_array_new ();
4481 method_domains = g_ptr_array_new ();
4482 method_seq_points = g_ptr_array_new ();
4484 mono_loader_lock ();
4485 g_hash_table_iter_init (&iter, domains);
4486 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4487 mono_domain_lock (domain);
4488 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4489 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4490 if (bp_matches_method (bp, m)) {
4491 /* Save the info locally to simplify the code inside the domain lock */
4492 g_ptr_array_add (methods, m);
4493 g_ptr_array_add (method_domains, domain);
4494 g_ptr_array_add (method_seq_points, seq_points);
4497 mono_domain_unlock (domain);
4500 for (i = 0; i < methods->len; ++i) {
4501 m = (MonoMethod *)g_ptr_array_index (methods, i);
4502 domain = (MonoDomain *)g_ptr_array_index (method_domains, i);
4503 seq_points = (MonoSeqPointInfo *)g_ptr_array_index (method_seq_points, i);
4504 set_bp_in_method (domain, m, seq_points, bp, error);
4507 g_ptr_array_add (breakpoints, bp);
4508 mono_loader_unlock ();
4510 g_ptr_array_free (methods, TRUE);
4511 g_ptr_array_free (method_domains, TRUE);
4512 g_ptr_array_free (method_seq_points, TRUE);
4514 if (error && !mono_error_ok (error)) {
4515 clear_breakpoint (bp);
4516 return NULL;
4519 return bp;
4522 static void
4523 clear_breakpoint (MonoBreakpoint *bp)
4525 int i;
4527 // FIXME: locking, races
4528 for (i = 0; i < bp->children->len; ++i) {
4529 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, i);
4531 remove_breakpoint (inst);
4533 g_free (inst);
4536 mono_loader_lock ();
4537 g_ptr_array_remove (breakpoints, bp);
4538 mono_loader_unlock ();
4540 g_ptr_array_free (bp->children, TRUE);
4541 g_free (bp);
4544 static void
4545 breakpoints_cleanup (void)
4547 int i;
4549 mono_loader_lock ();
4550 i = 0;
4551 while (i < event_requests->len) {
4552 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
4554 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4555 clear_breakpoint ((MonoBreakpoint *)req->info);
4556 g_ptr_array_remove_index_fast (event_requests, i);
4557 g_free (req);
4558 } else {
4559 i ++;
4563 for (i = 0; i < breakpoints->len; ++i)
4564 g_free (g_ptr_array_index (breakpoints, i));
4566 g_ptr_array_free (breakpoints, TRUE);
4567 g_hash_table_destroy (bp_locs);
4569 breakpoints = NULL;
4570 bp_locs = NULL;
4572 mono_loader_unlock ();
4576 * clear_breakpoints_for_domain:
4578 * Clear breakpoint instances which reference DOMAIN.
4580 static void
4581 clear_breakpoints_for_domain (MonoDomain *domain)
4583 int i, j;
4585 /* This could be called after shutdown */
4586 if (!breakpoints)
4587 return;
4589 mono_loader_lock ();
4590 for (i = 0; i < breakpoints->len; ++i) {
4591 MonoBreakpoint *bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4593 j = 0;
4594 while (j < bp->children->len) {
4595 BreakpointInstance *inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4597 if (inst->domain == domain) {
4598 remove_breakpoint (inst);
4600 g_free (inst);
4602 g_ptr_array_remove_index_fast (bp->children, j);
4603 } else {
4604 j ++;
4608 mono_loader_unlock ();
4612 * ss_calculate_framecount:
4614 * Ensure DebuggerTlsData fields are filled out.
4616 static void ss_calculate_framecount (DebuggerTlsData *tls, MonoContext *ctx)
4618 if (!tls->context.valid)
4619 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4620 compute_frame_info (tls->thread, tls);
4623 static gboolean
4624 ensure_jit (StackFrame* frame)
4626 if (!frame->jit) {
4627 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
4628 if (!frame->jit && frame->api_method->is_inflated)
4629 frame->jit = mono_debug_find_method(mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
4630 if (!frame->jit) {
4631 char *s;
4633 /* This could happen for aot images with no jit debug info */
4634 s = mono_method_full_name (frame->api_method, TRUE);
4635 DEBUG_PRINTF(1, "[dbg] No debug information found for '%s'.\n", s);
4636 g_free (s);
4637 return FALSE;
4640 return TRUE;
4644 * ss_update:
4646 * Return FALSE if single stepping needs to continue.
4648 static gboolean
4649 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp, DebuggerTlsData *tls, MonoContext *ctx, MonoMethod* method)
4651 MonoDebugMethodInfo *minfo;
4652 MonoDebugSourceLocation *loc = NULL;
4653 gboolean hit = TRUE;
4655 if (req->async_stepout_method == method) {
4656 DEBUG_PRINTF (1, "[%p] Breakpoint hit during async step-out at %s hit, continuing stepping out.\n", (gpointer)(gsize)mono_native_thread_id_get (), method->name);
4657 return FALSE;
4660 if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK)) {
4662 * These seq points are inserted by the JIT after calls, step over needs to skip them.
4664 DEBUG_PRINTF (1, "[%p] Seq point at nonempty stack %x while stepping over, continuing single stepping.\n", (gpointer) (gsize) mono_native_thread_id_get (), sp->il_offset);
4665 return FALSE;
4668 if ((req->depth == STEP_DEPTH_OVER || req->depth == STEP_DEPTH_OUT) && hit && !req->async_stepout_method) {
4669 gboolean is_step_out = req->depth == STEP_DEPTH_OUT;
4671 ss_calculate_framecount (tls, ctx);
4673 // Because functions can call themselves recursively, we need to make sure we're stopping at the right stack depth.
4674 // In case of step out, the target is the frame *enclosing* the one where the request was made.
4675 int target_frames = req->nframes + (is_step_out ? -1 : 0);
4676 if (req->nframes > 0 && tls->frame_count > 0 && tls->frame_count > target_frames) {
4677 /* Hit the breakpoint in a recursive call, don't halt */
4678 DEBUG_PRINTF (1, "[%p] Breakpoint at lower frame while stepping %s, continuing single stepping.\n", (gpointer) (gsize) mono_native_thread_id_get (), is_step_out ? "out" : "over");
4679 return FALSE;
4683 if (req->depth == STEP_DEPTH_INTO && req->size == STEP_SIZE_MIN && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) && ss_req->start_method){
4684 ss_calculate_framecount (tls, ctx);
4685 if (ss_req->start_method == method && req->nframes && tls->frame_count == req->nframes) {//Check also frame count(could be recursion)
4686 DEBUG_PRINTF (1, "[%p] Seq point at nonempty stack %x while stepping in, continuing single stepping.\n", (gpointer) (gsize) mono_native_thread_id_get (), sp->il_offset);
4687 return FALSE;
4691 MonoDebugMethodAsyncInfo* async_method = mono_debug_lookup_method_async_debug_info (method);
4692 if (async_method) {
4693 for (int i = 0; i < async_method->num_awaits; i++) {
4694 if (async_method->yield_offsets[i] == sp->il_offset || async_method->resume_offsets[i] == sp->il_offset) {
4695 mono_debug_free_method_async_debug_info (async_method);
4696 return FALSE;
4699 mono_debug_free_method_async_debug_info (async_method);
4702 if (req->size != STEP_SIZE_LINE)
4703 return TRUE;
4705 /* Have to check whenever a different source line was reached */
4706 minfo = mono_debug_lookup_method (method);
4708 if (minfo)
4709 loc = mono_debug_method_lookup_location (minfo, sp->il_offset);
4711 if (!loc) {
4712 DEBUG_PRINTF (1, "[%p] No line number info for il offset %x, continuing single stepping.\n", (gpointer) (gsize) mono_native_thread_id_get (), sp->il_offset);
4713 ss_req->last_method = method;
4714 hit = FALSE;
4715 } else if (loc && method == ss_req->last_method && loc->row == ss_req->last_line) {
4716 ss_calculate_framecount (tls, ctx);
4717 if (tls->frame_count == req->nframes) { // If the frame has changed we're clearly not on the same source line.
4718 DEBUG_PRINTF (1, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer) (gsize) mono_native_thread_id_get (), loc->row);
4719 hit = FALSE;
4723 if (loc) {
4724 ss_req->last_method = method;
4725 ss_req->last_line = loc->row;
4726 mono_debug_free_source_location (loc);
4729 return hit;
4732 static gboolean
4733 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4735 return bp->method && bp->method->klass->image->assembly == assembly;
4738 static MonoObject*
4739 get_this (StackFrame *frame)
4741 //Logic inspiered by "add_var" method and took out path that happens in async method for getting this
4742 MonoDebugVarInfo *var = frame->jit->this_var;
4743 if ((var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS) != MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET)
4744 return NULL;
4746 guint8 * addr = (guint8 *)mono_arch_context_get_int_reg (&frame->ctx, var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS);
4747 addr += (gint32)var->offset;
4748 return *(MonoObject**)addr;
4751 //This ID is used to figure out if breakpoint hit on resumeOffset belongs to us or not
4752 //since thread probably changed...
4753 static int
4754 get_this_async_id (StackFrame *frame)
4756 return get_objid (get_this (frame));
4759 static MonoMethod*
4760 get_set_notification_method (MonoClass* async_builder_class)
4762 MonoError error;
4763 GPtrArray* array = mono_class_get_methods_by_name (async_builder_class, "SetNotificationForWaitCompletion", 0x24, FALSE, FALSE, &error);
4764 mono_error_assert_ok (&error);
4765 g_assert (array->len == 1);
4766 MonoMethod* set_notification_method = (MonoMethod *)g_ptr_array_index (array, 0);
4767 g_ptr_array_free (array, TRUE);
4768 return set_notification_method;
4771 static void
4772 set_set_notification_for_wait_completion_flag (StackFrame *frame)
4774 MonoObject* obj = get_this (frame);
4775 g_assert (obj);
4776 MonoClassField *builder_field = mono_class_get_field_from_name (obj->vtable->klass, "<>t__builder");
4777 g_assert (builder_field);
4778 MonoObject* builder;
4779 MonoError error;
4780 builder = mono_field_get_value_object_checked (frame->domain, builder_field, obj, &error);
4781 mono_error_assert_ok (&error);
4782 g_assert (builder);
4784 void* args [1];
4785 gboolean arg = TRUE;
4786 args [0] = &arg;
4787 mono_runtime_invoke_checked (get_set_notification_method (builder->vtable->klass), mono_object_unbox (builder), args, &error);
4788 mono_error_assert_ok (&error);
4789 mono_field_set_value (obj, builder_field, mono_object_unbox (builder));
4792 static MonoMethod* notify_debugger_of_wait_completion_method_cache = NULL;
4794 static MonoMethod*
4795 get_notify_debugger_of_wait_completion_method ()
4797 if (notify_debugger_of_wait_completion_method_cache != NULL)
4798 return notify_debugger_of_wait_completion_method_cache;
4799 MonoError error;
4800 MonoClass* task_class = mono_class_load_from_name (mono_defaults.corlib, "System.Threading.Tasks", "Task");
4801 GPtrArray* array = mono_class_get_methods_by_name (task_class, "NotifyDebuggerOfWaitCompletion", 0x24, FALSE, FALSE, &error);
4802 mono_error_assert_ok (&error);
4803 g_assert (array->len == 1);
4804 notify_debugger_of_wait_completion_method_cache = (MonoMethod *)g_ptr_array_index (array, 0);
4805 g_ptr_array_free (array, TRUE);
4806 return notify_debugger_of_wait_completion_method_cache;
4809 static void
4810 process_breakpoint (DebuggerTlsData *tls, gboolean from_signal)
4812 MonoJitInfo *ji;
4813 guint8 *ip;
4814 int i, j, suspend_policy;
4815 guint32 native_offset;
4816 MonoBreakpoint *bp;
4817 BreakpointInstance *inst;
4818 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4819 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4820 EventKind kind = EVENT_KIND_BREAKPOINT;
4821 MonoContext *ctx = &tls->restore_state.ctx;
4822 MonoMethod *method;
4823 MonoSeqPointInfo *info;
4824 SeqPoint sp;
4825 gboolean found_sp;
4827 // FIXME: Speed this up
4829 ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
4830 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4832 if (!ji) {
4833 /* Interpreter */
4834 // FIXME: Pass a flag instead to detect this
4835 MonoLMF *lmf = mono_get_lmf ();
4836 MonoInterpFrameHandle *frame;
4838 g_assert (((guint64)lmf->previous_lmf) & 2);
4839 MonoLMFExt *ext = (MonoLMFExt*)lmf;
4841 g_assert (ext->interp_exit);
4842 frame = ext->interp_exit_data;
4843 ji = mono_interp_frame_get_jit_info (frame);
4844 ip = mono_interp_frame_get_ip (frame);
4847 g_assert (ji && !ji->is_trampoline);
4848 method = jinfo_get_method (ji);
4850 /* Compute the native offset of the breakpoint from the ip */
4851 native_offset = ip - (guint8*)ji->code_start;
4854 * Skip the instruction causing the breakpoint signal.
4856 if (from_signal)
4857 mono_arch_skip_breakpoint (ctx, ji);
4859 if (method->wrapper_type || tls->disable_breakpoints)
4860 return;
4862 bp_reqs = g_ptr_array_new ();
4863 ss_reqs = g_ptr_array_new ();
4864 ss_reqs_orig = g_ptr_array_new ();
4866 mono_loader_lock ();
4869 * The ip points to the instruction causing the breakpoint event, which is after
4870 * the offset recorded in the seq point map, so find the prev seq point before ip.
4872 found_sp = mono_find_prev_seq_point_for_native_offset (mono_domain_get (), method, native_offset, &info, &sp);
4874 if (!found_sp)
4875 no_seq_points_found (method, native_offset);
4877 g_assert (found_sp);
4879 DEBUG_PRINTF (1, "[%p] Breakpoint hit, method=%s, ip=%p, [il=0x%x,native=0x%x].\n", (gpointer) (gsize) mono_native_thread_id_get (), method->name, ip, sp.il_offset, native_offset);
4881 bp = NULL;
4882 for (i = 0; i < breakpoints->len; ++i) {
4883 bp = (MonoBreakpoint *)g_ptr_array_index (breakpoints, i);
4885 if (!bp->method)
4886 continue;
4888 for (j = 0; j < bp->children->len; ++j) {
4889 inst = (BreakpointInstance *)g_ptr_array_index (bp->children, j);
4890 if (inst->ji == ji && inst->il_offset == sp.il_offset && inst->native_offset == sp.native_offset) {
4891 if (bp->req->event_kind == EVENT_KIND_STEP) {
4892 g_ptr_array_add (ss_reqs_orig, bp->req);
4893 } else {
4894 g_ptr_array_add (bp_reqs, bp->req);
4899 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4900 /* Maybe a method entry/exit event */
4901 if (sp.il_offset == METHOD_ENTRY_IL_OFFSET)
4902 kind = EVENT_KIND_METHOD_ENTRY;
4903 else if (sp.il_offset == METHOD_EXIT_IL_OFFSET)
4904 kind = EVENT_KIND_METHOD_EXIT;
4907 /* Process single step requests */
4908 for (i = 0; i < ss_reqs_orig->len; ++i) {
4909 EventRequest *req = (EventRequest *)g_ptr_array_index (ss_reqs_orig, i);
4910 SingleStepReq *ss_req = (SingleStepReq *)req->info;
4911 gboolean hit;
4913 //if we hit async_stepout_method, it's our no matter which thread
4914 if ((ss_req->async_stepout_method != method) && (ss_req->async_id || mono_thread_internal_current () != ss_req->thread)) {
4915 //We have different thread and we don't have async stepping in progress
4916 //it's breakpoint in parallel thread, ignore it
4917 if (ss_req->async_id == 0)
4918 continue;
4920 tls->context.valid = FALSE;
4921 tls->async_state.valid = FALSE;
4922 invalidate_frames (tls);
4923 ss_calculate_framecount(tls, ctx);
4924 //make sure we have enough data to get current async method instance id
4925 if (tls->frame_count == 0 || !ensure_jit (tls->frames [0]))
4926 continue;
4928 //Check method is async before calling get_this_async_id
4929 MonoDebugMethodAsyncInfo* asyncMethod = mono_debug_lookup_method_async_debug_info (method);
4930 if (!asyncMethod)
4931 continue;
4932 else
4933 mono_debug_free_method_async_debug_info (asyncMethod);
4935 //breakpoint was hit in parallelly executing async method, ignore it
4936 if (ss_req->async_id != get_this_async_id (tls->frames [0]))
4937 continue;
4940 //Update stepping request to new thread/frame_count that we are continuing on
4941 //so continuing with normal stepping works as expected
4942 if (ss_req->async_stepout_method || ss_req->async_id) {
4943 tls->context.valid = FALSE;
4944 tls->async_state.valid = FALSE;
4945 invalidate_frames (tls);
4946 ss_calculate_framecount (tls, ctx);
4947 ss_req->thread = mono_thread_internal_current ();
4948 ss_req->nframes = tls->frame_count;
4951 hit = ss_update (ss_req, ji, &sp, tls, ctx, method);
4952 if (hit)
4953 g_ptr_array_add (ss_reqs, req);
4955 /* Start single stepping again from the current sequence point */
4956 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
4959 if (ss_reqs->len > 0)
4960 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4961 if (bp_reqs->len > 0)
4962 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4963 if (kind != EVENT_KIND_BREAKPOINT)
4964 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4966 mono_loader_unlock ();
4968 g_ptr_array_free (bp_reqs, TRUE);
4969 g_ptr_array_free (ss_reqs, TRUE);
4972 * FIXME: The first event will suspend, so the second will only be sent after the
4973 * resume.
4975 if (ss_events)
4976 process_event (EVENT_KIND_STEP, method, 0, ctx, ss_events, suspend_policy);
4977 if (bp_events)
4978 process_event (kind, method, 0, ctx, bp_events, suspend_policy);
4979 if (enter_leave_events)
4980 process_event (kind, method, 0, ctx, enter_leave_events, suspend_policy);
4983 /* Process a breakpoint/single step event after resuming from a signal handler */
4984 static void
4985 process_signal_event (void (*func) (DebuggerTlsData*, gboolean))
4987 DebuggerTlsData *tls;
4988 MonoThreadUnwindState orig_restore_state;
4989 MonoContext ctx;
4991 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4992 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4993 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4994 mono_thread_state_init_from_monoctx (&tls->restore_state, &tls->handler_ctx);
4996 func (tls, TRUE);
4998 /* This is called when resuming from a signal handler, so it shouldn't return */
4999 memcpy (&ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5000 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5001 mono_restore_context (&ctx);
5002 g_assert_not_reached ();
5005 static void
5006 process_breakpoint_from_signal (void)
5008 process_signal_event (process_breakpoint);
5011 static void
5012 resume_from_signal_handler (void *sigctx, void *func)
5014 DebuggerTlsData *tls;
5015 MonoContext ctx;
5017 /* Save the original context in TLS */
5018 // FIXME: This might not work on an altstack ?
5019 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5020 if (!tls)
5021 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer) (gsize) mono_native_thread_id_get ());
5022 g_assert (tls);
5024 // FIXME: MonoContext usually doesn't include the fp registers, so these are
5025 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
5026 // clob:c could be added to op_seq_point.
5028 mono_sigctx_to_monoctx (sigctx, &ctx);
5029 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
5030 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
5031 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
5032 #else
5033 MONO_CONTEXT_SET_IP (&ctx, func);
5034 #endif
5035 mono_monoctx_to_sigctx (&ctx, sigctx);
5037 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
5038 mono_ppc_set_func_into_sigctx (sigctx, func);
5039 #endif
5042 void
5043 mono_debugger_agent_breakpoint_hit (void *sigctx)
5046 * We are called from a signal handler, and running code there causes all kinds of
5047 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
5048 * So set up the signal context to return to the real breakpoint handler function.
5050 resume_from_signal_handler (sigctx, process_breakpoint_from_signal);
5053 typedef struct {
5054 gboolean found;
5055 MonoContext *ctx;
5056 } UserBreakCbData;
5058 static gboolean
5059 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer user_data)
5061 UserBreakCbData *data = user_data;
5063 if (frame->type == FRAME_TYPE_INTERP_TO_MANAGED) {
5064 data->found = TRUE;
5065 return TRUE;
5067 if (frame->managed) {
5068 data->found = TRUE;
5069 *data->ctx = *ctx;
5071 return TRUE;
5073 return FALSE;
5077 * Called by System.Diagnostics.Debugger:Break ().
5079 void
5080 mono_debugger_agent_user_break (void)
5082 if (agent_config.enabled) {
5083 MonoContext ctx;
5084 int suspend_policy;
5085 GSList *events;
5086 UserBreakCbData data;
5088 memset (&data, 0, sizeof (UserBreakCbData));
5089 data.ctx = &ctx;
5091 /* Obtain a context */
5092 MONO_CONTEXT_SET_IP (&ctx, NULL);
5093 mono_walk_stack_with_ctx (user_break_cb, NULL, (MonoUnwindOptions)0, &data);
5094 g_assert (data.found);
5096 mono_loader_lock ();
5097 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
5098 mono_loader_unlock ();
5100 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
5101 } else if (debug_options.native_debugger_break) {
5102 G_BREAKPOINT ();
5106 static const char*
5107 ss_depth_to_string (StepDepth depth)
5109 switch (depth) {
5110 case STEP_DEPTH_OVER:
5111 return "over";
5112 case STEP_DEPTH_OUT:
5113 return "out";
5114 case STEP_DEPTH_INTO:
5115 return "into";
5116 default:
5117 g_assert_not_reached ();
5118 return NULL;
5122 static void
5123 process_single_step_inner (DebuggerTlsData *tls, gboolean from_signal)
5125 MonoJitInfo *ji;
5126 guint8 *ip;
5127 GPtrArray *reqs;
5128 int il_offset, suspend_policy;
5129 MonoDomain *domain;
5130 GSList *events;
5131 MonoContext *ctx = &tls->restore_state.ctx;
5132 MonoMethod *method;
5133 SeqPoint sp;
5134 MonoSeqPointInfo *info;
5136 /* Skip the instruction causing the single step */
5137 if (from_signal)
5138 mono_arch_skip_single_step (ctx);
5140 if (suspend_count > 0) {
5141 /* Fastpath during invokes, see in process_suspend () */
5142 if (suspend_count - tls->resume_count == 0)
5143 return;
5144 process_suspend (tls, ctx);
5145 return;
5148 if (!ss_req)
5149 // FIXME: A suspend race
5150 return;
5152 if (mono_thread_internal_current () != ss_req->thread)
5153 return;
5155 ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
5157 ji = get_top_method_ji (ip, &domain, (gpointer*)&ip);
5158 g_assert (ji && !ji->is_trampoline);
5160 if (log_level > 0) {
5161 DEBUG_PRINTF (1, "[%p] Single step event (depth=%s) at %s (%p)[0x%x], sp %p, last sp %p\n", (gpointer) (gsize) mono_native_thread_id_get (), ss_depth_to_string (ss_req->depth), mono_method_full_name (jinfo_get_method (ji), TRUE), MONO_CONTEXT_GET_IP (ctx), (int)((guint8*)MONO_CONTEXT_GET_IP (ctx) - (guint8*)ji->code_start), MONO_CONTEXT_GET_SP (ctx), ss_req->last_sp);
5164 method = jinfo_get_method (ji);
5165 g_assert (method);
5167 if (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
5168 return;
5171 * FIXME:
5172 * Stopping in memset makes half-initialized vtypes visible.
5173 * Stopping in memcpy makes half-copied vtypes visible.
5175 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
5176 return;
5179 * This could be in ss_update method, but mono_find_next_seq_point_for_native_offset is pretty expensive method,
5180 * hence we prefer this check here.
5182 if (ss_req->user_assemblies) {
5183 gboolean found = FALSE;
5184 for (int k = 0; ss_req->user_assemblies[k]; k++)
5185 if (ss_req->user_assemblies[k] == method->klass->image->assembly) {
5186 found = TRUE;
5187 break;
5189 if (!found)
5190 return;
5195 * The ip points to the instruction causing the single step event, which is before
5196 * the offset recorded in the seq point map, so find the next seq point after ip.
5198 if (!mono_find_next_seq_point_for_native_offset (domain, method, (guint8*)ip - (guint8*)ji->code_start, &info, &sp)) {
5199 g_assert_not_reached ();
5200 return;
5203 il_offset = sp.il_offset;
5205 if (!ss_update (ss_req, ji, &sp, tls, ctx, method))
5206 return;
5208 /* Start single stepping again from the current sequence point */
5209 ss_start (ss_req, method, &sp, info, ctx, tls, FALSE, NULL, 0);
5211 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
5212 (method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
5213 !strcmp (method->name, ".cctor"))
5214 return;
5216 // FIXME: Has to lock earlier
5218 reqs = g_ptr_array_new ();
5220 mono_loader_lock ();
5222 g_ptr_array_add (reqs, ss_req->req);
5224 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
5226 g_ptr_array_free (reqs, TRUE);
5228 mono_loader_unlock ();
5230 process_event (EVENT_KIND_STEP, jinfo_get_method (ji), il_offset, ctx, events, suspend_policy);
5233 static void
5234 process_single_step (void)
5236 process_signal_event (process_single_step_inner);
5240 * mono_debugger_agent_single_step_event:
5242 * Called from a signal handler to handle a single step event.
5244 void
5245 mono_debugger_agent_single_step_event (void *sigctx)
5247 /* Resume to process_single_step through the signal context */
5249 // FIXME: Since step out/over is implemented using step in, the step in case should
5250 // be as fast as possible. Move the relevant code from process_single_step_inner ()
5251 // here
5253 if (is_debugger_thread ()) {
5255 * This could happen despite our best effors when the runtime calls
5256 * assembly/type resolve hooks.
5257 * FIXME: Breakpoints too.
5259 MonoContext ctx;
5261 mono_sigctx_to_monoctx (sigctx, &ctx);
5262 mono_arch_skip_single_step (&ctx);
5263 mono_monoctx_to_sigctx (&ctx, sigctx);
5264 return;
5267 resume_from_signal_handler (sigctx, process_single_step);
5270 void
5271 debugger_agent_single_step_from_context (MonoContext *ctx)
5273 DebuggerTlsData *tls;
5274 MonoThreadUnwindState orig_restore_state;
5276 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5277 /* Fastpath during invokes, see in process_suspend () */
5278 if (tls && suspend_count && suspend_count - tls->resume_count == 0)
5279 return;
5281 if (is_debugger_thread ())
5282 return;
5284 g_assert (tls);
5286 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
5287 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5288 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5289 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5291 process_single_step_inner (tls, FALSE);
5293 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5294 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5297 void
5298 debugger_agent_breakpoint_from_context (MonoContext *ctx)
5300 DebuggerTlsData *tls;
5301 MonoThreadUnwindState orig_restore_state;
5302 guint8 *orig_ip;
5304 if (is_debugger_thread ())
5305 return;
5307 orig_ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
5308 MONO_CONTEXT_SET_IP (ctx, orig_ip - 1);
5310 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5311 g_assert (tls);
5312 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
5313 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
5314 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
5316 process_breakpoint (tls, FALSE);
5318 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
5319 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
5320 if (MONO_CONTEXT_GET_IP (ctx) == orig_ip - 1)
5321 MONO_CONTEXT_SET_IP (ctx, orig_ip);
5325 * start_single_stepping:
5327 * Turn on single stepping. Can be called multiple times, for example,
5328 * by a single step event request + a suspend.
5330 static void
5331 start_single_stepping (void)
5333 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5334 int val = InterlockedIncrement (&ss_count);
5336 if (val == 1) {
5337 mono_arch_start_single_stepping ();
5338 mono_interp_start_single_stepping ();
5340 #else
5341 g_assert_not_reached ();
5342 #endif
5345 static void
5346 stop_single_stepping (void)
5348 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5349 int val = InterlockedDecrement (&ss_count);
5351 if (val == 0) {
5352 mono_arch_stop_single_stepping ();
5353 mono_interp_stop_single_stepping ();
5355 #else
5356 g_assert_not_reached ();
5357 #endif
5361 * ss_stop:
5363 * Stop the single stepping operation given by SS_REQ.
5365 static void
5366 ss_stop (SingleStepReq *ss_req)
5368 if (ss_req->bps) {
5369 GSList *l;
5371 for (l = ss_req->bps; l; l = l->next) {
5372 clear_breakpoint ((MonoBreakpoint *)l->data);
5374 g_slist_free (ss_req->bps);
5375 ss_req->bps = NULL;
5378 ss_req->async_id = 0;
5379 ss_req->async_stepout_method = NULL;
5380 if (ss_req->global) {
5381 stop_single_stepping ();
5382 ss_req->global = FALSE;
5387 * ss_bp_is_unique:
5389 * Reject breakpoint if it is a duplicate of one already in list or hash table.
5391 static gboolean
5392 ss_bp_is_unique (GSList *bps, GHashTable *ss_req_bp_cache, MonoMethod *method, guint32 il_offset)
5394 if (ss_req_bp_cache) {
5395 MonoBreakpoint dummy = {method, il_offset, NULL, NULL};
5396 return !g_hash_table_lookup (ss_req_bp_cache, &dummy);
5398 for (GSList *l = bps; l; l = l->next) {
5399 MonoBreakpoint *bp = (MonoBreakpoint *)l->data;
5400 if (bp->method == method && bp->il_offset == il_offset)
5401 return FALSE;
5403 return TRUE;
5407 * ss_bp_eq:
5409 * GHashTable equality for a MonoBreakpoint (only care about method and il_offset fields)
5411 static gint
5412 ss_bp_eq (gconstpointer ka, gconstpointer kb)
5414 const MonoBreakpoint *s1 = (const MonoBreakpoint *)ka;
5415 const MonoBreakpoint *s2 = (const MonoBreakpoint *)kb;
5416 return (s1->method == s2->method && s1->il_offset == s2->il_offset) ? 1 : 0;
5420 * ss_bp_eq:
5422 * GHashTable hash for a MonoBreakpoint (only care about method and il_offset fields)
5424 static guint
5425 ss_bp_hash (gconstpointer data)
5427 const MonoBreakpoint *s = (const MonoBreakpoint *)data;
5428 guint hash = (guint) (uintptr_t) s->method;
5429 hash ^= ((guint)s->il_offset) << 16; // Assume low bits are more interesting
5430 hash ^= ((guint)s->il_offset) >> 16;
5431 return hash;
5434 #define MAX_LINEAR_SCAN_BPS 7
5437 * ss_bp_add_one:
5439 * Create a new breakpoint and add it to a step request.
5440 * Will adjust the bp count and cache used by ss_start.
5442 static void
5443 ss_bp_add_one (SingleStepReq *ss_req, int *ss_req_bp_count, GHashTable **ss_req_bp_cache,
5444 MonoMethod *method, guint32 il_offset)
5446 // This list is getting too long, switch to using the hash table
5447 if (!*ss_req_bp_cache && *ss_req_bp_count > MAX_LINEAR_SCAN_BPS) {
5448 *ss_req_bp_cache = g_hash_table_new (ss_bp_hash, ss_bp_eq);
5449 for (GSList *l = ss_req->bps; l; l = l->next)
5450 g_hash_table_insert (*ss_req_bp_cache, l->data, l->data);
5453 if (ss_bp_is_unique (ss_req->bps, *ss_req_bp_cache, method, il_offset)) {
5454 // Create and add breakpoint
5455 MonoBreakpoint *bp = set_breakpoint (method, il_offset, ss_req->req, NULL);
5456 ss_req->bps = g_slist_append (ss_req->bps, bp);
5457 if (*ss_req_bp_cache)
5458 g_hash_table_insert (*ss_req_bp_cache, bp, bp);
5459 (*ss_req_bp_count)++;
5460 } else {
5461 DEBUG_PRINTF (1, "[dbg] Candidate breakpoint at %s:[il=0x%x] is a duplicate for this step request, will not add.\n", mono_method_full_name (method, TRUE), (int)il_offset);
5465 static gboolean
5466 is_last_non_empty (SeqPoint* sp, MonoSeqPointInfo *info)
5468 if (!sp->next_len)
5469 return TRUE;
5470 SeqPoint* next = g_new (SeqPoint, sp->next_len);
5471 mono_seq_point_init_next (info, *sp, next);
5472 for (int i = 0; i < sp->next_len; i++) {
5473 if (next [i].flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK) {
5474 if (!is_last_non_empty (&next [i], info)) {
5475 g_free (next);
5476 return FALSE;
5478 } else {
5479 g_free (next);
5480 return FALSE;
5483 g_free (next);
5484 return TRUE;
5488 * ss_start:
5490 * Start the single stepping operation given by SS_REQ from the sequence point SP.
5491 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
5492 * belong to the same thread as CTX.
5493 * If FRAMES is not-null, use that instead of tls->frames for placing breakpoints etc.
5495 static void
5496 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint* sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls,
5497 gboolean step_to_catch, StackFrame **frames, int nframes)
5499 int i, j, frame_index;
5500 SeqPoint *next_sp, *parent_sp = NULL;
5501 SeqPoint local_sp, local_parent_sp;
5502 gboolean found_sp;
5503 MonoSeqPointInfo *parent_info;
5504 MonoMethod *parent_sp_method = NULL;
5505 gboolean enable_global = FALSE;
5507 // When 8 or more entries are in bps, we build a hash table to serve as a set of breakpoints.
5508 // Recreating this on each pass is a little wasteful but at least keeps behavior linear.
5509 int ss_req_bp_count = g_slist_length (ss_req->bps);
5510 GHashTable *ss_req_bp_cache = NULL;
5512 /* Stop the previous operation */
5513 ss_stop (ss_req);
5516 * Implement single stepping using breakpoints if possible.
5518 if (step_to_catch) {
5519 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, sp->il_offset);
5520 } else {
5521 frame_index = 1;
5523 if (ctx && !frames) {
5524 /* Need parent frames */
5525 if (!tls->context.valid)
5526 mono_thread_state_init_from_monoctx (&tls->context, ctx);
5527 compute_frame_info (tls->thread, tls);
5528 frames = tls->frames;
5529 nframes = tls->frame_count;
5532 MonoDebugMethodAsyncInfo* asyncMethod = mono_debug_lookup_method_async_debug_info (method);
5534 /* Need to stop in catch clauses as well */
5535 for (i = ss_req->depth == STEP_DEPTH_OUT ? 1 : 0; i < nframes; ++i) {
5536 StackFrame *frame = frames [i];
5538 if (frame->ji) {
5539 MonoJitInfo *jinfo = frame->ji;
5540 for (j = 0; j < jinfo->num_clauses; ++j) {
5541 // In case of async method we don't want to place breakpoint on last catch handler(which state machine added for whole method)
5542 if (asyncMethod && asyncMethod->num_awaits && i == 0 && j + 1 == jinfo->num_clauses)
5543 break;
5544 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5546 if (mono_find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL, &local_sp))
5547 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, frame->method, local_sp.il_offset);
5552 if (asyncMethod && asyncMethod->num_awaits && nframes && ensure_jit (frames [0])) {
5553 //asyncMethod has value and num_awaits > 0, this means we are inside async method with awaits
5555 // Check if we hit yield_offset during normal stepping, because if we did...
5556 // Go into special async stepping mode which places breakpoint on resumeOffset
5557 // of this await call and sets async_id so we can distinguish it from parallel executions
5558 for (i = 0; i < asyncMethod->num_awaits; i++) {
5559 if (sp->il_offset == asyncMethod->yield_offsets [i]) {
5560 ss_req->async_id = get_this_async_id (frames [0]);
5561 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, asyncMethod->resume_offsets [i]);
5562 if (ss_req_bp_cache)
5563 g_hash_table_destroy (ss_req_bp_cache);
5564 mono_debug_free_method_async_debug_info (asyncMethod);
5565 return;
5568 //If we are at end of async method and doing step-in or step-over...
5569 //Switch to step-out, so whole NotifyDebuggerOfWaitCompletion magic happens...
5570 if (is_last_non_empty (sp, info)) {
5571 ss_req->depth = STEP_DEPTH_OUT;//setting depth to step-out is important, don't inline IF, because code later depends on this
5573 if (ss_req->depth == STEP_DEPTH_OUT) {
5574 set_set_notification_for_wait_completion_flag (frames [0]);
5575 ss_req->async_id = get_this_async_id (frames [0]);
5576 ss_req->async_stepout_method = get_notify_debugger_of_wait_completion_method ();
5577 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, ss_req->async_stepout_method, 0);
5578 if (ss_req_bp_cache)
5579 g_hash_table_destroy (ss_req_bp_cache);
5580 mono_debug_free_method_async_debug_info (asyncMethod);
5581 return;
5585 if (asyncMethod)
5586 mono_debug_free_method_async_debug_info (asyncMethod);
5589 * Find the first sequence point in the current or in a previous frame which
5590 * is not the last in its method.
5592 if (ss_req->depth == STEP_DEPTH_OUT) {
5593 /* Ignore seq points in current method */
5594 while (frame_index < nframes) {
5595 StackFrame *frame = frames [frame_index];
5597 method = frame->method;
5598 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5599 sp = (found_sp)? &local_sp : NULL;
5600 frame_index ++;
5601 if (sp && sp->next_len != 0)
5602 break;
5604 // There could be method calls before the next seq point in the caller when using nested calls
5605 //enable_global = TRUE;
5606 } else {
5607 if (sp && sp->next_len == 0) {
5608 sp = NULL;
5609 while (frame_index < nframes) {
5610 StackFrame *frame = frames [frame_index];
5612 method = frame->method;
5613 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5614 sp = (found_sp)? &local_sp : NULL;
5615 if (sp && sp->next_len != 0)
5616 break;
5617 sp = NULL;
5618 frame_index ++;
5620 } else {
5621 /* Have to put a breakpoint into a parent frame since the seq points might not cover all control flow out of the method */
5622 while (frame_index < nframes) {
5623 StackFrame *frame = frames [frame_index];
5625 parent_sp_method = frame->method;
5626 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &parent_info, &local_parent_sp);
5627 parent_sp = found_sp ? &local_parent_sp : NULL;
5628 if (found_sp && parent_sp->next_len != 0)
5629 break;
5630 parent_sp = NULL;
5631 frame_index ++;
5636 if (sp && sp->next_len > 0) {
5637 SeqPoint* next = g_new(SeqPoint, sp->next_len);
5639 mono_seq_point_init_next (info, *sp, next);
5640 for (i = 0; i < sp->next_len; i++) {
5641 next_sp = &next[i];
5643 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, method, next_sp->il_offset);
5645 g_free (next);
5648 if (parent_sp) {
5649 SeqPoint* next = g_new(SeqPoint, parent_sp->next_len);
5651 mono_seq_point_init_next (parent_info, *parent_sp, next);
5652 for (i = 0; i < parent_sp->next_len; i++) {
5653 next_sp = &next[i];
5655 ss_bp_add_one (ss_req, &ss_req_bp_count, &ss_req_bp_cache, parent_sp_method, next_sp->il_offset);
5657 g_free (next);
5660 if (ss_req->nframes == 0)
5661 ss_req->nframes = nframes;
5663 if ((ss_req->depth == STEP_DEPTH_OVER) && (!sp && !parent_sp)) {
5664 DEBUG_PRINTF (1, "[dbg] No parent frame for step over, transition to step into.\n");
5666 * This is needed since if we leave managed code, and later return to it, step over
5667 * is not going to stop.
5668 * This approach is a bit ugly, since we change the step depth, but it only affects
5669 * clients who reuse the same step request, and only in this special case.
5671 ss_req->depth = STEP_DEPTH_INTO;
5674 if (ss_req->depth == STEP_DEPTH_INTO) {
5675 /* Enable global stepping so we stop at method entry too */
5676 enable_global = TRUE;
5680 * The ctx/frame info computed above will become invalid when we continue.
5682 tls->context.valid = FALSE;
5683 tls->async_state.valid = FALSE;
5684 invalidate_frames (tls);
5687 if (enable_global) {
5688 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5689 ss_req->global = TRUE;
5690 start_single_stepping ();
5691 } else if (!ss_req->bps) {
5692 DEBUG_PRINTF (1, "[dbg] Turning on global single stepping.\n");
5693 ss_req->global = TRUE;
5694 start_single_stepping ();
5695 } else {
5696 ss_req->global = FALSE;
5699 if (ss_req_bp_cache)
5700 g_hash_table_destroy (ss_req_bp_cache);
5704 * Start single stepping of thread THREAD
5706 static ErrorCode
5707 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, StepFilter filter, EventRequest *req)
5709 DebuggerTlsData *tls;
5710 MonoSeqPointInfo *info = NULL;
5711 SeqPoint *sp = NULL;
5712 SeqPoint local_sp;
5713 gboolean found_sp;
5714 MonoMethod *method = NULL;
5715 MonoDebugMethodInfo *minfo;
5716 gboolean step_to_catch = FALSE;
5717 gboolean set_ip = FALSE;
5718 StackFrame **frames = NULL;
5719 int nframes = 0;
5721 if (suspend_count == 0)
5722 return ERR_NOT_SUSPENDED;
5724 wait_for_suspend ();
5726 // FIXME: Multiple requests
5727 if (ss_req) {
5728 DEBUG_PRINTF (0, "Received a single step request while the previous one was still active.\n");
5729 return ERR_NOT_IMPLEMENTED;
5732 DEBUG_PRINTF (1, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth));
5734 ss_req = g_new0 (SingleStepReq, 1);
5735 ss_req->req = req;
5736 ss_req->thread = thread;
5737 ss_req->size = size;
5738 ss_req->depth = depth;
5739 ss_req->filter = filter;
5740 req->info = ss_req;
5742 for (int i = 0; i < req->nmodifiers; i++) {
5743 if (req->modifiers[i].kind == MOD_KIND_ASSEMBLY_ONLY) {
5744 ss_req->user_assemblies = req->modifiers[i].data.assemblies;
5745 break;
5749 mono_loader_lock ();
5750 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5751 mono_loader_unlock ();
5752 g_assert (tls);
5753 if (!tls->context.valid) {
5754 DEBUG_PRINTF (1, "Received a single step request on a thread with no managed frames.");
5755 return ERR_INVALID_ARGUMENT;
5758 if (tls->restore_state.valid && MONO_CONTEXT_GET_IP (&tls->context.ctx) != MONO_CONTEXT_GET_IP (&tls->restore_state.ctx)) {
5760 * Need to start single stepping from restore_state and not from the current state
5762 set_ip = TRUE;
5763 frames = compute_frame_info_from (thread, tls, &tls->restore_state, &nframes);
5766 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5768 if (tls->catch_state.valid) {
5769 gboolean res;
5770 StackFrameInfo frame;
5771 MonoContext new_ctx;
5772 MonoLMF *lmf = NULL;
5775 * We are stopped at a throw site. Stepping should go to the catch site.
5778 /* Find the the jit info for the catch context */
5779 res = mono_find_jit_info_ext (
5780 (MonoDomain *)tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN],
5781 (MonoJitTlsData *)((MonoThreadInfo*)thread->thread_info)->jit_data,
5782 NULL, &tls->catch_state.ctx, &new_ctx, NULL, &lmf, NULL, &frame);
5783 g_assert (res);
5784 g_assert (frame.type == FRAME_TYPE_MANAGED);
5787 * Find the seq point corresponding to the landing site ip, which is the first seq
5788 * point after ip.
5790 found_sp = mono_find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info, &local_sp);
5791 sp = (found_sp)? &local_sp : NULL;
5792 if (!sp)
5793 no_seq_points_found (frame.method, frame.native_offset);
5794 g_assert (sp);
5796 method = frame.method;
5798 step_to_catch = TRUE;
5799 /* This make sure the seq point is not skipped by process_single_step () */
5800 ss_req->last_sp = NULL;
5803 if (!step_to_catch) {
5804 StackFrame *frame = NULL;
5806 if (set_ip) {
5807 if (frames && nframes)
5808 frame = frames [0];
5809 } else {
5810 compute_frame_info (thread, tls);
5812 if (tls->frame_count)
5813 frame = tls->frames [0];
5816 if (ss_req->size == STEP_SIZE_LINE) {
5817 if (frame) {
5818 ss_req->last_method = frame->method;
5819 ss_req->last_line = -1;
5821 minfo = mono_debug_lookup_method (frame->method);
5822 if (minfo && frame->il_offset != -1) {
5823 MonoDebugSourceLocation *loc = mono_debug_method_lookup_location (minfo, frame->il_offset);
5825 if (loc) {
5826 ss_req->last_line = loc->row;
5827 g_free (loc);
5833 if (frame) {
5834 if (!method && frame->il_offset != -1) {
5835 /* FIXME: Sort the table and use a binary search */
5836 found_sp = mono_find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info, &local_sp);
5837 sp = (found_sp)? &local_sp : NULL;
5838 if (!sp)
5839 no_seq_points_found (frame->method, frame->native_offset);
5840 g_assert (sp);
5841 method = frame->method;
5846 ss_req->start_method = method;
5848 ss_start (ss_req, method, sp, info, set_ip ? &tls->restore_state.ctx : &tls->context.ctx, tls, step_to_catch, frames, nframes);
5850 if (frames)
5851 free_frames (frames, nframes);
5853 return ERR_NONE;
5856 static void
5857 ss_destroy (SingleStepReq *req)
5859 // FIXME: Locking
5860 g_assert (ss_req == req);
5862 ss_stop (ss_req);
5864 g_free (ss_req);
5865 ss_req = NULL;
5868 static void
5869 ss_clear_for_assembly (SingleStepReq *req, MonoAssembly *assembly)
5871 GSList *l;
5872 gboolean found = TRUE;
5874 while (found) {
5875 found = FALSE;
5876 for (l = ss_req->bps; l; l = l->next) {
5877 if (breakpoint_matches_assembly ((MonoBreakpoint *)l->data, assembly)) {
5878 clear_breakpoint ((MonoBreakpoint *)l->data);
5879 ss_req->bps = g_slist_delete_link (ss_req->bps, l);
5880 found = TRUE;
5881 break;
5888 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5890 void
5891 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5893 MonoError error;
5894 int suspend_policy;
5895 GSList *events;
5896 EventInfo ei;
5898 if (!agent_config.enabled)
5899 return;
5901 mono_loader_lock ();
5902 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5903 mono_loader_unlock ();
5905 ei.level = level;
5906 ei.category = NULL;
5907 if (category) {
5908 ei.category = mono_string_to_utf8_checked (category, &error);
5909 mono_error_cleanup (&error);
5911 ei.message = NULL;
5912 if (message) {
5913 ei.message = mono_string_to_utf8_checked (message, &error);
5914 mono_error_cleanup (&error);
5917 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5919 g_free (ei.category);
5920 g_free (ei.message);
5923 gboolean
5924 mono_debugger_agent_debug_log_is_enabled (void)
5926 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5927 return agent_config.enabled;
5930 #if defined(PLATFORM_ANDROID) || defined(TARGET_ANDROID)
5931 void
5932 mono_debugger_agent_unhandled_exception (MonoException *exc)
5934 int suspend_policy;
5935 GSList *events;
5936 EventInfo ei;
5938 if (!inited)
5939 return;
5941 memset (&ei, 0, sizeof (EventInfo));
5942 ei.exc = (MonoObject*)exc;
5944 mono_loader_lock ();
5945 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5946 mono_loader_unlock ();
5948 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5950 #endif
5952 void
5953 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5954 MonoContext *catch_ctx)
5956 int i, j, suspend_policy;
5957 GSList *events;
5958 MonoJitInfo *ji, *catch_ji;
5959 EventInfo ei;
5960 DebuggerTlsData *tls = NULL;
5962 if (thread_to_tls != NULL) {
5963 MonoInternalThread *thread = mono_thread_internal_current ();
5965 mono_loader_lock ();
5966 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5967 mono_loader_unlock ();
5969 if (tls && tls->abort_requested)
5970 return;
5971 if (tls && tls->disable_breakpoints)
5972 return;
5975 memset (&ei, 0, sizeof (EventInfo));
5977 /* Just-In-Time debugging */
5978 if (!catch_ctx) {
5979 if (agent_config.onuncaught && !inited) {
5980 finish_agent_init (FALSE);
5983 * Send an unsolicited EXCEPTION event with a dummy request id.
5985 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5986 ei.exc = (MonoObject*)exc;
5987 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5988 return;
5990 } else if (agent_config.onthrow && !inited) {
5991 GSList *l;
5992 gboolean found = FALSE;
5994 for (l = agent_config.onthrow; l; l = l->next) {
5995 char *ex_type = (char *)l->data;
5996 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5998 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5999 found = TRUE;
6001 g_free (f);
6004 if (found) {
6005 finish_agent_init (FALSE);
6008 * Send an unsolicited EXCEPTION event with a dummy request id.
6010 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
6011 ei.exc = (MonoObject*)exc;
6012 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
6013 return;
6017 if (!inited)
6018 return;
6020 ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (throw_ctx), NULL);
6021 if (catch_ctx)
6022 catch_ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (catch_ctx), NULL);
6023 else
6024 catch_ji = NULL;
6026 ei.exc = (MonoObject*)exc;
6027 ei.caught = catch_ctx != NULL;
6029 mono_loader_lock ();
6031 /* Treat exceptions which are caught in non-user code as unhandled */
6032 for (i = 0; i < event_requests->len; ++i) {
6033 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6034 if (req->event_kind != EVENT_KIND_EXCEPTION)
6035 continue;
6037 for (j = 0; j < req->nmodifiers; ++j) {
6038 Modifier *mod = &req->modifiers [j];
6040 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
6041 int k;
6042 gboolean found = FALSE;
6043 MonoAssembly **assemblies = mod->data.assemblies;
6045 if (assemblies) {
6046 for (k = 0; assemblies [k]; ++k)
6047 if (assemblies [k] == jinfo_get_method (catch_ji)->klass->image->assembly)
6048 found = TRUE;
6050 if (!found)
6051 ei.caught = FALSE;
6056 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
6057 mono_loader_unlock ();
6059 if (tls && ei.caught && catch_ctx) {
6060 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
6061 tls->catch_state.ctx = *catch_ctx;
6062 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
6063 tls->catch_state.valid = TRUE;
6066 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
6068 if (tls)
6069 tls->catch_state.valid = FALSE;
6072 void
6073 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
6075 DebuggerTlsData *tls;
6077 if (!inited)
6078 return;
6080 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
6081 if (!tls)
6082 return;
6085 * We're about to invoke an exception filter during the first pass of exception handling.
6087 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
6088 * 'orig_ctx' is the context where the exception has been thrown.
6091 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
6093 * If we're stopped in Filter(), normal stack unwinding would first unwind to
6094 * the call site (line 37) and then continue to Main(), but it would never
6095 * include the throw site (line 32).
6097 * Since exception filters are invoked during the first pass of exception handling,
6098 * the stack frames of the throw site are still intact, so we should include them
6099 * in a stack trace.
6101 * We do this here by saving the context of the throw site in 'tls->filter_state'.
6103 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
6104 * but report the location of the 'throw' to the user.
6108 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
6111 void
6112 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
6114 DebuggerTlsData *tls;
6116 if (!inited)
6117 return;
6119 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
6120 if (!tls)
6121 return;
6123 tls->filter_state.valid = FALSE;
6127 * buffer_add_value_full:
6129 * Add the encoding of the value at ADDR described by T to the buffer.
6130 * AS_VTYPE determines whenever to treat primitive types as primitive types or
6131 * vtypes.
6133 static void
6134 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
6135 gboolean as_vtype, GHashTable *parent_vtypes)
6137 MonoObject *obj;
6138 gboolean boxed_vtype = FALSE;
6140 if (t->byref) {
6141 if (!(*(void**)addr)) {
6142 /* This can happen with compiler generated locals */
6143 //printf ("%s\n", mono_type_full_name (t));
6144 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
6145 return;
6147 g_assert (*(void**)addr);
6148 addr = *(void**)addr;
6151 if (as_vtype) {
6152 switch (t->type) {
6153 case MONO_TYPE_BOOLEAN:
6154 case MONO_TYPE_I1:
6155 case MONO_TYPE_U1:
6156 case MONO_TYPE_CHAR:
6157 case MONO_TYPE_I2:
6158 case MONO_TYPE_U2:
6159 case MONO_TYPE_I4:
6160 case MONO_TYPE_U4:
6161 case MONO_TYPE_R4:
6162 case MONO_TYPE_I8:
6163 case MONO_TYPE_U8:
6164 case MONO_TYPE_R8:
6165 case MONO_TYPE_I:
6166 case MONO_TYPE_U:
6167 case MONO_TYPE_PTR:
6168 goto handle_vtype;
6169 break;
6170 default:
6171 break;
6175 switch (t->type) {
6176 case MONO_TYPE_VOID:
6177 buffer_add_byte (buf, t->type);
6178 break;
6179 case MONO_TYPE_BOOLEAN:
6180 case MONO_TYPE_I1:
6181 case MONO_TYPE_U1:
6182 buffer_add_byte (buf, t->type);
6183 buffer_add_int (buf, *(gint8*)addr);
6184 break;
6185 case MONO_TYPE_CHAR:
6186 case MONO_TYPE_I2:
6187 case MONO_TYPE_U2:
6188 buffer_add_byte (buf, t->type);
6189 buffer_add_int (buf, *(gint16*)addr);
6190 break;
6191 case MONO_TYPE_I4:
6192 case MONO_TYPE_U4:
6193 case MONO_TYPE_R4:
6194 buffer_add_byte (buf, t->type);
6195 buffer_add_int (buf, *(gint32*)addr);
6196 break;
6197 case MONO_TYPE_I8:
6198 case MONO_TYPE_U8:
6199 case MONO_TYPE_R8:
6200 buffer_add_byte (buf, t->type);
6201 buffer_add_long (buf, *(gint64*)addr);
6202 break;
6203 case MONO_TYPE_I:
6204 case MONO_TYPE_U:
6205 /* Treat it as a vtype */
6206 goto handle_vtype;
6207 case MONO_TYPE_PTR: {
6208 gssize val = *(gssize*)addr;
6210 buffer_add_byte (buf, t->type);
6211 buffer_add_long (buf, val);
6212 break;
6214 handle_ref:
6215 case MONO_TYPE_STRING:
6216 case MONO_TYPE_SZARRAY:
6217 case MONO_TYPE_OBJECT:
6218 case MONO_TYPE_CLASS:
6219 case MONO_TYPE_ARRAY:
6220 obj = *(MonoObject**)addr;
6222 if (!obj) {
6223 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
6224 } else {
6225 if (obj->vtable->klass->valuetype) {
6226 t = &obj->vtable->klass->byval_arg;
6227 addr = mono_object_unbox (obj);
6228 boxed_vtype = TRUE;
6229 goto handle_vtype;
6230 } else if (obj->vtable->klass->rank) {
6231 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
6232 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
6233 buffer_add_byte (buf, MONO_TYPE_CLASS);
6234 } else {
6235 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
6237 buffer_add_objid (buf, obj);
6239 break;
6240 handle_vtype:
6241 case MONO_TYPE_VALUETYPE:
6242 case MONO_TYPE_TYPEDBYREF: {
6243 int nfields;
6244 gpointer iter;
6245 MonoClassField *f;
6246 MonoClass *klass = mono_class_from_mono_type (t);
6247 int vtype_index;
6249 if (boxed_vtype) {
6251 * Handle boxed vtypes recursively referencing themselves using fields.
6253 if (!parent_vtypes)
6254 parent_vtypes = g_hash_table_new (NULL, NULL);
6255 vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
6256 if (vtype_index) {
6257 if (CHECK_PROTOCOL_VERSION (2, 33)) {
6258 buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
6259 buffer_add_int (buf, vtype_index - 1);
6260 } else {
6261 /* The client can't handle PARENT_VTYPE */
6262 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
6264 break;
6265 } else {
6266 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
6270 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
6271 buffer_add_byte (buf, klass->enumtype);
6272 buffer_add_typeid (buf, domain, klass);
6274 nfields = 0;
6275 iter = NULL;
6276 while ((f = mono_class_get_fields (klass, &iter))) {
6277 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6278 continue;
6279 if (mono_field_is_deleted (f))
6280 continue;
6281 nfields ++;
6283 buffer_add_int (buf, nfields);
6285 iter = NULL;
6286 while ((f = mono_class_get_fields (klass, &iter))) {
6287 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6288 continue;
6289 if (mono_field_is_deleted (f))
6290 continue;
6291 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE, parent_vtypes);
6294 if (boxed_vtype) {
6295 g_hash_table_remove (parent_vtypes, addr);
6296 if (g_hash_table_size (parent_vtypes) == 0) {
6297 g_hash_table_destroy (parent_vtypes);
6298 parent_vtypes = NULL;
6301 break;
6303 case MONO_TYPE_GENERICINST:
6304 if (mono_type_generic_inst_is_valuetype (t)) {
6305 goto handle_vtype;
6306 } else {
6307 goto handle_ref;
6309 break;
6310 default:
6311 NOT_IMPLEMENTED;
6315 static void
6316 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
6318 buffer_add_value_full (buf, t, addr, domain, FALSE, NULL);
6321 static gboolean
6322 obj_is_of_type (MonoObject *obj, MonoType *t)
6324 MonoClass *klass = obj->vtable->klass;
6325 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
6326 if (mono_class_is_transparent_proxy (klass)) {
6327 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
6328 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
6329 return TRUE;
6332 return FALSE;
6334 return TRUE;
6337 static ErrorCode
6338 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
6340 static ErrorCode
6341 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6343 gboolean is_enum;
6344 MonoClass *klass;
6345 MonoClassField *f;
6346 int nfields;
6347 gpointer iter = NULL;
6348 MonoDomain *d;
6349 ErrorCode err;
6351 is_enum = decode_byte (buf, &buf, limit);
6352 /* Enums are sent as a normal vtype */
6353 if (is_enum)
6354 return ERR_NOT_IMPLEMENTED;
6355 klass = decode_typeid (buf, &buf, limit, &d, &err);
6356 if (err != ERR_NONE)
6357 return err;
6359 if (t && klass != mono_class_from_mono_type (t)) {
6360 char *name = mono_type_full_name (t);
6361 char *name2 = mono_type_full_name (&klass->byval_arg);
6362 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got %s.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, name2);
6363 g_free (name);
6364 g_free (name2);
6365 return ERR_INVALID_ARGUMENT;
6368 nfields = decode_int (buf, &buf, limit);
6369 while ((f = mono_class_get_fields (klass, &iter))) {
6370 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
6371 continue;
6372 if (mono_field_is_deleted (f))
6373 continue;
6374 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
6375 if (err != ERR_NONE)
6376 return err;
6377 nfields --;
6379 g_assert (nfields == 0);
6381 *endbuf = buf;
6383 return ERR_NONE;
6386 static ErrorCode
6387 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6389 ErrorCode err;
6391 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
6392 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
6393 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
6394 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
6395 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE) &&
6396 !(t->type == MONO_TYPE_VALUETYPE && type == MONO_TYPE_OBJECT)) {
6397 char *name = mono_type_full_name (t);
6398 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
6399 g_free (name);
6400 return ERR_INVALID_ARGUMENT;
6403 switch (t->type) {
6404 case MONO_TYPE_BOOLEAN:
6405 *(guint8*)addr = decode_int (buf, &buf, limit);
6406 break;
6407 case MONO_TYPE_CHAR:
6408 *(gunichar2*)addr = decode_int (buf, &buf, limit);
6409 break;
6410 case MONO_TYPE_I1:
6411 *(gint8*)addr = decode_int (buf, &buf, limit);
6412 break;
6413 case MONO_TYPE_U1:
6414 *(guint8*)addr = decode_int (buf, &buf, limit);
6415 break;
6416 case MONO_TYPE_I2:
6417 *(gint16*)addr = decode_int (buf, &buf, limit);
6418 break;
6419 case MONO_TYPE_U2:
6420 *(guint16*)addr = decode_int (buf, &buf, limit);
6421 break;
6422 case MONO_TYPE_I4:
6423 *(gint32*)addr = decode_int (buf, &buf, limit);
6424 break;
6425 case MONO_TYPE_U4:
6426 *(guint32*)addr = decode_int (buf, &buf, limit);
6427 break;
6428 case MONO_TYPE_I8:
6429 *(gint64*)addr = decode_long (buf, &buf, limit);
6430 break;
6431 case MONO_TYPE_U8:
6432 *(guint64*)addr = decode_long (buf, &buf, limit);
6433 break;
6434 case MONO_TYPE_R4:
6435 *(guint32*)addr = decode_int (buf, &buf, limit);
6436 break;
6437 case MONO_TYPE_R8:
6438 *(guint64*)addr = decode_long (buf, &buf, limit);
6439 break;
6440 case MONO_TYPE_PTR:
6441 /* We send these as I8, so we get them back as such */
6442 g_assert (type == MONO_TYPE_I8);
6443 *(gssize*)addr = decode_long (buf, &buf, limit);
6444 break;
6445 case MONO_TYPE_GENERICINST:
6446 if (MONO_TYPE_ISSTRUCT (t)) {
6447 /* The client sends these as a valuetype */
6448 goto handle_vtype;
6449 } else {
6450 goto handle_ref;
6452 break;
6453 case MONO_TYPE_I:
6454 case MONO_TYPE_U:
6455 /* We send these as vtypes, so we get them back as such */
6456 g_assert (type == MONO_TYPE_VALUETYPE);
6457 /* Fall through */
6458 handle_vtype:
6459 case MONO_TYPE_VALUETYPE:
6460 if (type == MONO_TYPE_OBJECT) {
6461 /* Boxed vtype */
6462 int objid = decode_objid (buf, &buf, limit);
6463 ErrorCode err;
6464 MonoObject *obj;
6466 err = get_object (objid, (MonoObject**)&obj);
6467 if (err != ERR_NONE)
6468 return err;
6469 if (!obj)
6470 return ERR_INVALID_ARGUMENT;
6471 if (obj->vtable->klass != mono_class_from_mono_type (t)) {
6472 DEBUG_PRINTF (1, "Expected type '%s', got object '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6473 return ERR_INVALID_ARGUMENT;
6475 memcpy (addr, mono_object_unbox (obj), mono_class_value_size (obj->vtable->klass, NULL));
6476 } else {
6477 err = decode_vtype (t, domain, addr, buf, &buf, limit);
6478 if (err != ERR_NONE)
6479 return err;
6481 break;
6482 handle_ref:
6483 default:
6484 if (MONO_TYPE_IS_REFERENCE (t)) {
6485 if (type == MONO_TYPE_OBJECT) {
6486 int objid = decode_objid (buf, &buf, limit);
6487 ErrorCode err;
6488 MonoObject *obj;
6490 err = get_object (objid, (MonoObject**)&obj);
6491 if (err != ERR_NONE)
6492 return err;
6494 if (obj) {
6495 if (!obj_is_of_type (obj, t)) {
6496 DEBUG_PRINTF (1, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name);
6497 return ERR_INVALID_ARGUMENT;
6500 if (obj && obj->vtable->domain != domain)
6501 return ERR_INVALID_ARGUMENT;
6503 mono_gc_wbarrier_generic_store (addr, obj);
6504 } else if (type == VALUE_TYPE_ID_NULL) {
6505 *(MonoObject**)addr = NULL;
6506 } else if (type == MONO_TYPE_VALUETYPE) {
6507 MonoError error;
6508 guint8 *buf2;
6509 gboolean is_enum;
6510 MonoClass *klass;
6511 MonoDomain *d;
6512 guint8 *vtype_buf;
6513 int vtype_buf_size;
6515 /* This can happen when round-tripping boxed vtypes */
6517 * Obtain vtype class.
6518 * Same as the beginning of the handle_vtype case above.
6520 buf2 = buf;
6521 is_enum = decode_byte (buf, &buf, limit);
6522 if (is_enum)
6523 return ERR_NOT_IMPLEMENTED;
6524 klass = decode_typeid (buf, &buf, limit, &d, &err);
6525 if (err != ERR_NONE)
6526 return err;
6528 /* Decode the vtype into a temporary buffer, then box it. */
6529 vtype_buf_size = mono_class_value_size (klass, NULL);
6530 vtype_buf = (guint8 *)g_malloc0 (vtype_buf_size);
6531 g_assert (vtype_buf);
6533 buf = buf2;
6534 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
6535 if (err != ERR_NONE) {
6536 g_free (vtype_buf);
6537 return err;
6539 *(MonoObject**)addr = mono_value_box_checked (d, klass, vtype_buf, &error);
6540 mono_error_cleanup (&error);
6541 g_free (vtype_buf);
6542 } else {
6543 char *name = mono_type_full_name (t);
6544 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
6545 g_free (name);
6546 return ERR_INVALID_ARGUMENT;
6548 } else {
6549 NOT_IMPLEMENTED;
6551 break;
6554 *endbuf = buf;
6556 return ERR_NONE;
6559 static ErrorCode
6560 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6562 MonoError error;
6563 ErrorCode err;
6564 int type = decode_byte (buf, &buf, limit);
6566 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
6567 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
6568 guint8 *nullable_buf;
6571 * First try decoding it as a Nullable`1
6573 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6574 if (err == ERR_NONE)
6575 return err;
6578 * Then try decoding as a primitive value or null.
6580 if (targ->type == type) {
6581 nullable_buf = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
6582 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
6583 if (err != ERR_NONE) {
6584 g_free (nullable_buf);
6585 return err;
6587 MonoObject *boxed = mono_value_box_checked (domain, mono_class_from_mono_type (targ), nullable_buf, &error);
6588 if (!is_ok (&error)) {
6589 mono_error_cleanup (&error);
6590 return ERR_INVALID_OBJECT;
6592 mono_nullable_init (addr, boxed, mono_class_from_mono_type (t));
6593 g_free (nullable_buf);
6594 *endbuf = buf;
6595 return ERR_NONE;
6596 } else if (type == VALUE_TYPE_ID_NULL) {
6597 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
6598 *endbuf = buf;
6599 return ERR_NONE;
6603 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6606 static void
6607 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
6609 guint32 flags;
6610 int reg;
6611 guint8 *addr, *gaddr;
6612 mgreg_t reg_val;
6614 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6615 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6617 switch (flags) {
6618 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
6619 reg_val = mono_arch_context_get_int_reg (ctx, reg);
6621 buffer_add_value_full (buf, t, &reg_val, domain, as_vtype, NULL);
6622 break;
6623 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6624 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6625 addr += (gint32)var->offset;
6627 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6629 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6630 break;
6631 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6632 NOT_IMPLEMENTED;
6633 break;
6634 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6635 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
6636 /* Same as regoffset, but with an indirection */
6637 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6638 addr += (gint32)var->offset;
6640 gaddr = (guint8 *)*(gpointer*)addr;
6641 g_assert (gaddr);
6642 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL);
6643 break;
6644 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
6645 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
6646 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
6647 MonoGSharedVtMethodRuntimeInfo *info;
6648 guint8 *locals;
6649 int idx;
6651 idx = reg;
6653 g_assert (info_var);
6654 g_assert (locals_var);
6656 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6657 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6658 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6659 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6660 addr += (gint32)info_var->offset;
6661 info = (MonoGSharedVtMethodRuntimeInfo *)*(gpointer*)addr;
6662 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6663 info = (MonoGSharedVtMethodRuntimeInfo *)mono_arch_context_get_int_reg (ctx, reg);
6664 } else {
6665 g_assert_not_reached ();
6667 g_assert (info);
6669 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6670 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6671 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6672 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6673 addr += (gint32)locals_var->offset;
6674 locals = (guint8 *)*(gpointer*)addr;
6675 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6676 locals = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6677 } else {
6678 g_assert_not_reached ();
6680 g_assert (locals);
6682 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6684 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6685 break;
6688 default:
6689 g_assert_not_reached ();
6693 static void
6694 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
6696 guint32 flags;
6697 int reg, size;
6698 guint8 *addr, *gaddr;
6700 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6701 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6703 if (MONO_TYPE_IS_REFERENCE (t))
6704 size = sizeof (gpointer);
6705 else
6706 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6708 switch (flags) {
6709 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6710 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6711 mgreg_t v;
6712 gboolean is_signed = FALSE;
6714 if (t->byref) {
6715 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6717 if (addr) {
6718 // FIXME: Write barriers
6719 mono_gc_memmove_atomic (addr, val, size);
6721 break;
6724 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6725 is_signed = TRUE;
6727 switch (size) {
6728 case 1:
6729 v = is_signed ? *(gint8*)val : *(guint8*)val;
6730 break;
6731 case 2:
6732 v = is_signed ? *(gint16*)val : *(guint16*)val;
6733 break;
6734 case 4:
6735 v = is_signed ? *(gint32*)val : *(guint32*)val;
6736 break;
6737 case 8:
6738 v = is_signed ? *(gint64*)val : *(guint64*)val;
6739 break;
6740 default:
6741 g_assert_not_reached ();
6744 /* Set value on the stack or in the return ctx */
6745 if (reg_locations [reg]) {
6746 /* Saved on the stack */
6747 DEBUG_PRINTF (1, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v);
6748 *(reg_locations [reg]) = v;
6749 } else {
6750 /* Not saved yet */
6751 DEBUG_PRINTF (1, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v);
6752 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6755 // FIXME: Move these to mono-context.h/c.
6756 mono_arch_context_set_int_reg (ctx, reg, v);
6757 #else
6758 // FIXME: Can't set registers, so we disable linears
6759 NOT_IMPLEMENTED;
6760 #endif
6761 break;
6763 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6764 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6765 addr += (gint32)var->offset;
6767 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6769 if (t->byref) {
6770 addr = *(guint8**)addr;
6772 if (!addr)
6773 break;
6776 // FIXME: Write barriers
6777 mono_gc_memmove_atomic (addr, val, size);
6778 break;
6779 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6780 /* Same as regoffset, but with an indirection */
6781 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6782 addr += (gint32)var->offset;
6784 gaddr = (guint8 *)*(gpointer*)addr;
6785 g_assert (gaddr);
6786 // FIXME: Write barriers
6787 mono_gc_memmove_atomic (gaddr, val, size);
6788 break;
6789 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6790 NOT_IMPLEMENTED;
6791 break;
6792 default:
6793 g_assert_not_reached ();
6797 static void
6798 set_interp_var (MonoType *t, gpointer addr, guint8 *val_buf)
6800 int size;
6802 if (t->byref) {
6803 addr = *(gpointer*)addr;
6804 g_assert (addr);
6807 if (MONO_TYPE_IS_REFERENCE (t))
6808 size = sizeof (gpointer);
6809 else
6810 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6812 memcpy (addr, val_buf, size);
6815 static void
6816 clear_event_request (int req_id, int etype)
6818 int i;
6820 mono_loader_lock ();
6821 for (i = 0; i < event_requests->len; ++i) {
6822 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6824 if (req->id == req_id && req->event_kind == etype) {
6825 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6826 clear_breakpoint ((MonoBreakpoint *)req->info);
6827 if (req->event_kind == EVENT_KIND_STEP)
6828 ss_destroy ((SingleStepReq *)req->info);
6829 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6830 clear_breakpoint ((MonoBreakpoint *)req->info);
6831 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6832 clear_breakpoint ((MonoBreakpoint *)req->info);
6833 g_ptr_array_remove_index_fast (event_requests, i);
6834 g_free (req);
6835 break;
6838 mono_loader_unlock ();
6841 static void
6842 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
6844 int i;
6846 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6847 m->kind = MOD_KIND_NONE;
6848 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6849 int count = 0, match_count = 0, pos;
6850 MonoAssembly **newassemblies;
6852 for (i = 0; m->data.assemblies [i]; ++i) {
6853 count ++;
6854 if (m->data.assemblies [i] == assembly)
6855 match_count ++;
6858 if (match_count) {
6859 // +1 because we don't know length and we use last element to check for end
6860 newassemblies = g_new0 (MonoAssembly*, count - match_count + 1);
6862 pos = 0;
6863 for (i = 0; i < count; ++i)
6864 if (m->data.assemblies [i] != assembly)
6865 newassemblies [pos ++] = m->data.assemblies [i];
6866 g_assert (pos == count - match_count);
6867 g_free (m->data.assemblies);
6868 m->data.assemblies = newassemblies;
6873 static void
6874 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
6876 int i;
6878 for (i = 0; i < req->nmodifiers; ++i) {
6879 Modifier *m = &req->modifiers [i];
6881 clear_assembly_from_modifier (req, m, assembly);
6886 * clear_event_requests_for_assembly:
6888 * Clear all events requests which reference ASSEMBLY.
6890 static void
6891 clear_event_requests_for_assembly (MonoAssembly *assembly)
6893 int i;
6894 gboolean found;
6896 mono_loader_lock ();
6897 found = TRUE;
6898 while (found) {
6899 found = FALSE;
6900 for (i = 0; i < event_requests->len; ++i) {
6901 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6903 clear_assembly_from_modifiers (req, assembly);
6905 if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly ((MonoBreakpoint *)req->info, assembly)) {
6906 clear_event_request (req->id, req->event_kind);
6907 found = TRUE;
6908 break;
6911 if (req->event_kind == EVENT_KIND_STEP)
6912 ss_clear_for_assembly ((SingleStepReq *)req->info, assembly);
6915 mono_loader_unlock ();
6919 * type_comes_from_assembly:
6921 * GHRFunc that returns TRUE if klass comes from assembly
6923 static gboolean
6924 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6926 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6930 * clear_types_for_assembly:
6932 * Clears types from loaded_classes for a given assembly
6934 static void
6935 clear_types_for_assembly (MonoAssembly *assembly)
6937 MonoDomain *domain = mono_domain_get ();
6938 AgentDomainInfo *info = NULL;
6940 if (!domain || !domain_jit_info (domain))
6941 /* Can happen during shutdown */
6942 return;
6944 info = get_agent_domain_info (domain);
6946 mono_loader_lock ();
6947 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6948 mono_loader_unlock ();
6951 static void
6952 add_thread (gpointer key, gpointer value, gpointer user_data)
6954 MonoInternalThread *thread = (MonoInternalThread *)value;
6955 Buffer *buf = (Buffer *)user_data;
6957 buffer_add_objid (buf, (MonoObject*)thread);
6960 static ErrorCode
6961 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6963 MonoError error;
6964 guint8 *end = invoke->endp;
6965 MonoMethod *m;
6966 int i, nargs;
6967 ErrorCode err;
6968 MonoMethodSignature *sig;
6969 guint8 **arg_buf;
6970 void **args;
6971 MonoObject *this_arg, *res, *exc;
6972 MonoDomain *domain;
6973 guint8 *this_buf;
6974 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6975 MonoLMFExt ext;
6976 #endif
6977 MonoStopwatch watch;
6979 if (invoke->method) {
6981 * Invoke this method directly, currently only Environment.Exit () is supported.
6983 this_arg = NULL;
6984 DEBUG_PRINTF (1, "[%p] Invoking method '%s' on receiver '%s'.\n", (gpointer) (gsize) mono_native_thread_id_get (), mono_method_full_name (invoke->method, TRUE), this_arg ? this_arg->vtable->klass->name : "<null>");
6986 mono_runtime_try_invoke (invoke->method, NULL, invoke->args, &exc, &error);
6987 mono_error_assert_ok (&error);
6989 g_assert_not_reached ();
6992 m = decode_methodid (p, &p, end, &domain, &err);
6993 if (err != ERR_NONE)
6994 return err;
6995 sig = mono_method_signature (m);
6997 if (m->klass->valuetype)
6998 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6999 else
7000 this_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
7001 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
7002 /* Should be null */
7003 int type = decode_byte (p, &p, end);
7004 if (type != VALUE_TYPE_ID_NULL) {
7005 DEBUG_PRINTF (1, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
7006 return ERR_INVALID_ARGUMENT;
7008 memset (this_buf, 0, mono_class_instance_size (m->klass));
7009 } else if (m->klass->valuetype && !strcmp (m->name, ".ctor")) {
7010 /* Could be null */
7011 guint8 *tmp_p;
7013 int type = decode_byte (p, &tmp_p, end);
7014 if (type == VALUE_TYPE_ID_NULL) {
7015 memset (this_buf, 0, mono_class_instance_size (m->klass));
7016 p = tmp_p;
7017 } else {
7018 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
7019 if (err != ERR_NONE)
7020 return err;
7022 } else {
7023 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
7024 if (err != ERR_NONE)
7025 return err;
7028 if (!m->klass->valuetype)
7029 this_arg = *(MonoObject**)this_buf;
7030 else
7031 this_arg = NULL;
7033 if (MONO_CLASS_IS_INTERFACE (m->klass)) {
7034 if (!this_arg) {
7035 DEBUG_PRINTF (1, "[%p] Error: Interface method invoked without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
7036 return ERR_INVALID_ARGUMENT;
7038 m = mono_object_get_virtual_method (this_arg, m);
7039 /* Transform this to the format the rest of the code expects it to be */
7040 if (m->klass->valuetype) {
7041 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
7042 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
7044 } else if ((m->flags & METHOD_ATTRIBUTE_VIRTUAL) && !m->klass->valuetype && invoke->flags & INVOKE_FLAG_VIRTUAL) {
7045 if (!this_arg) {
7046 DEBUG_PRINTF (1, "[%p] Error: invoke with INVOKE_FLAG_VIRTUAL flag set without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
7047 return ERR_INVALID_ARGUMENT;
7049 m = mono_object_get_virtual_method (this_arg, m);
7050 if (m->klass->valuetype) {
7051 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
7052 memcpy (this_buf, mono_object_unbox (this_arg), mono_class_instance_size (m->klass));
7056 DEBUG_PRINTF (1, "[%p] Invoking method '%s' on receiver '%s'.\n", (gpointer) (gsize) mono_native_thread_id_get (), mono_method_full_name (m, TRUE), this_arg ? this_arg->vtable->klass->name : "<null>");
7058 if (this_arg && this_arg->vtable->domain != domain)
7059 NOT_IMPLEMENTED;
7061 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this_arg) {
7062 if (!strcmp (m->name, ".ctor")) {
7063 if (mono_class_is_abstract (m->klass))
7064 return ERR_INVALID_ARGUMENT;
7065 else {
7066 MonoError error;
7067 this_arg = mono_object_new_checked (domain, m->klass, &error);
7068 mono_error_assert_ok (&error);
7070 } else {
7071 return ERR_INVALID_ARGUMENT;
7075 if (this_arg && !obj_is_of_type (this_arg, &m->klass->byval_arg))
7076 return ERR_INVALID_ARGUMENT;
7078 nargs = decode_int (p, &p, end);
7079 if (nargs != sig->param_count)
7080 return ERR_INVALID_ARGUMENT;
7081 /* Use alloca to get gc tracking */
7082 arg_buf = (guint8 **)g_alloca (nargs * sizeof (gpointer));
7083 memset (arg_buf, 0, nargs * sizeof (gpointer));
7084 args = (gpointer *)g_alloca (nargs * sizeof (gpointer));
7085 for (i = 0; i < nargs; ++i) {
7086 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
7087 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
7088 if (err != ERR_NONE)
7089 break;
7090 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
7091 NOT_IMPLEMENTED;
7093 if (sig->params [i]->byref) {
7094 arg_buf [i] = (guint8 *)g_alloca (sizeof (mgreg_t));
7095 *(gpointer*)arg_buf [i] = args [i];
7096 args [i] = arg_buf [i];
7098 } else {
7099 arg_buf [i] = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
7100 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
7101 if (err != ERR_NONE)
7102 break;
7103 args [i] = arg_buf [i];
7107 if (i < nargs)
7108 return err;
7110 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
7111 tls->disable_breakpoints = TRUE;
7112 else
7113 tls->disable_breakpoints = FALSE;
7116 * Add an LMF frame to link the stack frames on the invoke method with our caller.
7118 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
7119 if (invoke->has_ctx) {
7120 MonoLMF **lmf_addr;
7122 lmf_addr = mono_get_lmf_addr ();
7124 /* Setup our lmf */
7125 memset (&ext, 0, sizeof (ext));
7126 mono_arch_init_lmf_ext (&ext, *lmf_addr);
7128 ext.debugger_invoke = TRUE;
7129 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
7131 mono_set_lmf ((MonoLMF*)&ext);
7133 #endif
7135 mono_stopwatch_start (&watch);
7136 res = mono_runtime_try_invoke (m, m->klass->valuetype ? (gpointer) this_buf : (gpointer) this_arg, args, &exc, &error);
7137 if (exc == NULL && !mono_error_ok (&error)) {
7138 exc = (MonoObject*) mono_error_convert_to_exception (&error);
7139 } else {
7140 mono_error_cleanup (&error); /* FIXME report error */
7142 mono_stopwatch_stop (&watch);
7143 DEBUG_PRINTF (1, "[%p] Invoke result: %p, exc: %s, time: %ld ms.\n", (gpointer) (gsize) mono_native_thread_id_get (), res, exc ? exc->vtable->klass->name : NULL, (long)mono_stopwatch_elapsed_ms (&watch));
7144 if (exc) {
7145 buffer_add_byte (buf, 0);
7146 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
7147 } else {
7148 gboolean out_this = FALSE;
7149 gboolean out_args = FALSE;
7151 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_THIS) && CHECK_PROTOCOL_VERSION (2, 35))
7152 out_this = TRUE;
7153 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_ARGS) && CHECK_PROTOCOL_VERSION (2, 35))
7154 out_args = TRUE;
7155 buffer_add_byte (buf, 1 + (out_this ? 2 : 0) + (out_args ? 4 : 0));
7156 if (sig->ret->type == MONO_TYPE_VOID) {
7157 if (!strcmp (m->name, ".ctor")) {
7158 if (!m->klass->valuetype)
7159 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this_arg, domain);
7160 else
7161 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
7162 } else {
7163 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
7165 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
7166 buffer_add_value (buf, sig->ret, &res, domain);
7167 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
7168 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
7169 MonoClass *k = mono_class_from_mono_type (sig->ret);
7170 guint8 *nullable_buf = (guint8 *)g_alloca (mono_class_value_size (k, NULL));
7172 g_assert (nullable_buf);
7173 mono_nullable_init (nullable_buf, res, k);
7174 buffer_add_value (buf, sig->ret, nullable_buf, domain);
7175 } else {
7176 g_assert (res);
7177 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
7179 } else {
7180 NOT_IMPLEMENTED;
7182 if (out_this)
7183 /* Return the new value of the receiver after the call */
7184 buffer_add_value (buf, &m->klass->byval_arg, this_buf, domain);
7185 if (out_args) {
7186 buffer_add_int (buf, nargs);
7187 for (i = 0; i < nargs; ++i) {
7188 if (MONO_TYPE_IS_REFERENCE (sig->params [i]))
7189 buffer_add_value (buf, sig->params [i], &args [i], domain);
7190 else if (sig->params [i]->byref)
7191 /* add_value () does an indirection */
7192 buffer_add_value (buf, sig->params [i], &arg_buf [i], domain);
7193 else
7194 buffer_add_value (buf, sig->params [i], arg_buf [i], domain);
7199 tls->disable_breakpoints = FALSE;
7201 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
7202 if (invoke->has_ctx)
7203 mono_set_lmf ((MonoLMF *)(((gssize)ext.lmf.previous_lmf) & ~3));
7204 #endif
7206 *endp = p;
7207 // FIXME: byref arguments
7208 // FIXME: varargs
7209 return ERR_NONE;
7213 * invoke_method:
7215 * Invoke the method given by tls->pending_invoke in the current thread.
7217 static void
7218 invoke_method (void)
7220 DebuggerTlsData *tls;
7221 InvokeData *invoke;
7222 int id;
7223 int i, mindex;
7224 ErrorCode err;
7225 Buffer buf;
7226 MonoContext restore_ctx;
7227 guint8 *p;
7229 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
7230 g_assert (tls);
7233 * Store the `InvokeData *' in `tls->invoke' until we're done with
7234 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
7237 mono_loader_lock ();
7239 invoke = tls->pending_invoke;
7240 g_assert (invoke);
7241 tls->pending_invoke = NULL;
7243 invoke->last_invoke = tls->invoke;
7244 tls->invoke = invoke;
7246 mono_loader_unlock ();
7248 tls->frames_up_to_date = FALSE;
7250 id = invoke->id;
7252 p = invoke->p;
7253 err = ERR_NONE;
7254 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
7255 buffer_init (&buf, 128);
7257 if (err) {
7258 /* Fail the other invokes as well */
7259 } else {
7260 err = do_invoke_method (tls, &buf, invoke, p, &p);
7263 if (tls->abort_requested) {
7264 if (CHECK_PROTOCOL_VERSION (2, 42))
7265 err = ERR_INVOKE_ABORTED;
7268 /* Start suspending before sending the reply */
7269 if (mindex == invoke->nmethods - 1) {
7270 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
7271 for (i = 0; i < invoke->suspend_count; ++i)
7272 suspend_vm ();
7276 send_reply_packet (id, err, &buf);
7278 buffer_free (&buf);
7281 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
7283 if (invoke->has_ctx)
7284 save_thread_context (&restore_ctx);
7286 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
7287 g_assert (tls->resume_count);
7288 tls->resume_count -= invoke->suspend_count;
7291 DEBUG_PRINTF (1, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer) (gsize) mono_native_thread_id_get (), err, tls->resume_count);
7294 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
7296 * It is possible that mono_thread_internal_abort () was called
7297 * after the mono_runtime_invoke_checked() already returned, but it doesn't matter
7298 * because we reset the abort here.
7301 mono_loader_lock ();
7303 if (tls->abort_requested)
7304 mono_thread_internal_reset_abort (tls->thread);
7306 tls->invoke = tls->invoke->last_invoke;
7307 tls->abort_requested = FALSE;
7309 mono_loader_unlock ();
7311 g_free (invoke->p);
7312 g_free (invoke);
7314 suspend_current ();
7317 static gboolean
7318 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
7320 MonoThread *thread = (MonoThread *)value;
7321 DebuggerTlsData *tls;
7322 gboolean res;
7324 mono_loader_lock ();
7325 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
7326 g_assert (tls);
7327 res = tls->really_suspended;
7328 mono_loader_unlock ();
7330 return res;
7333 static GPtrArray*
7334 get_source_files_for_type (MonoClass *klass)
7336 gpointer iter = NULL;
7337 MonoMethod *method;
7338 MonoDebugSourceInfo *sinfo;
7339 GPtrArray *files;
7340 int i, j;
7342 files = g_ptr_array_new ();
7344 while ((method = mono_class_get_methods (klass, &iter))) {
7345 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
7346 GPtrArray *source_file_list;
7348 if (minfo) {
7349 mono_debug_get_seq_points (minfo, NULL, &source_file_list, NULL, NULL, NULL);
7350 for (j = 0; j < source_file_list->len; ++j) {
7351 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, j);
7352 for (i = 0; i < files->len; ++i)
7353 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
7354 break;
7355 if (i == files->len)
7356 g_ptr_array_add (files, g_strdup (sinfo->source_file));
7358 g_ptr_array_free (source_file_list, TRUE);
7362 return files;
7365 static ErrorCode
7366 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
7368 switch (command) {
7369 case CMD_VM_VERSION: {
7370 char *build_info, *version;
7372 build_info = mono_get_runtime_build_info ();
7373 version = g_strdup_printf ("mono %s", build_info);
7375 buffer_add_string (buf, version); /* vm version */
7376 buffer_add_int (buf, MAJOR_VERSION);
7377 buffer_add_int (buf, MINOR_VERSION);
7378 g_free (build_info);
7379 g_free (version);
7380 break;
7382 case CMD_VM_SET_PROTOCOL_VERSION: {
7383 major_version = decode_int (p, &p, end);
7384 minor_version = decode_int (p, &p, end);
7385 protocol_version_set = TRUE;
7386 DEBUG_PRINTF (1, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version);
7387 break;
7389 case CMD_VM_ALL_THREADS: {
7390 // FIXME: Domains
7391 mono_loader_lock ();
7392 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
7393 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
7394 mono_loader_unlock ();
7395 break;
7397 case CMD_VM_SUSPEND:
7398 suspend_vm ();
7399 wait_for_suspend ();
7400 break;
7401 case CMD_VM_RESUME:
7402 if (suspend_count == 0)
7403 return ERR_NOT_SUSPENDED;
7404 resume_vm ();
7405 clear_suspended_objs ();
7406 break;
7407 case CMD_VM_DISPOSE:
7408 /* Clear all event requests */
7409 mono_loader_lock ();
7410 while (event_requests->len > 0) {
7411 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
7413 clear_event_request (req->id, req->event_kind);
7415 mono_loader_unlock ();
7417 while (suspend_count > 0)
7418 resume_vm ();
7419 disconnected = TRUE;
7420 vm_start_event_sent = FALSE;
7421 break;
7422 case CMD_VM_EXIT: {
7423 MonoInternalThread *thread;
7424 DebuggerTlsData *tls;
7425 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7426 MonoClass *env_class;
7427 #endif
7428 MonoMethod *exit_method = NULL;
7429 gpointer *args;
7430 int exit_code;
7432 exit_code = decode_int (p, &p, end);
7434 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
7436 /* Have to send a reply before exiting */
7437 send_reply_packet (id, 0, buf);
7439 /* Clear all event requests */
7440 mono_loader_lock ();
7441 while (event_requests->len > 0) {
7442 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
7444 clear_event_request (req->id, req->event_kind);
7446 mono_loader_unlock ();
7449 * The JDWP documentation says that the shutdown is not orderly. It doesn't
7450 * specify whenever a VM_DEATH event is sent. We currently do an orderly
7451 * shutdown by hijacking a thread to execute Environment.Exit (). This is
7452 * better than doing the shutdown ourselves, since it avoids various races.
7455 suspend_vm ();
7456 wait_for_suspend ();
7458 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7459 env_class = mono_class_try_load_from_name (mono_defaults.corlib, "System", "Environment");
7460 if (env_class)
7461 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
7462 #endif
7464 mono_loader_lock ();
7465 thread = (MonoInternalThread *)mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
7466 mono_loader_unlock ();
7468 if (thread && exit_method) {
7469 mono_loader_lock ();
7470 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
7471 mono_loader_unlock ();
7473 args = g_new0 (gpointer, 1);
7474 args [0] = g_malloc (sizeof (int));
7475 *(int*)(args [0]) = exit_code;
7477 tls->pending_invoke = g_new0 (InvokeData, 1);
7478 tls->pending_invoke->method = exit_method;
7479 tls->pending_invoke->args = args;
7480 tls->pending_invoke->nmethods = 1;
7482 while (suspend_count > 0)
7483 resume_vm ();
7484 } else {
7486 * No thread found, do it ourselves.
7487 * FIXME: This can race with normal shutdown etc.
7489 while (suspend_count > 0)
7490 resume_vm ();
7492 if (!mono_runtime_try_shutdown ())
7493 break;
7495 mono_environment_exitcode_set (exit_code);
7497 /* Suspend all managed threads since the runtime is going away */
7498 DEBUG_PRINTF (1, "Suspending all threads...\n");
7499 mono_thread_suspend_all_other_threads ();
7500 DEBUG_PRINTF (1, "Shutting down the runtime...\n");
7501 mono_runtime_quit ();
7502 transport_close2 ();
7503 DEBUG_PRINTF (1, "Exiting...\n");
7505 exit (exit_code);
7507 break;
7509 case CMD_VM_INVOKE_METHOD:
7510 case CMD_VM_INVOKE_METHODS: {
7511 int objid = decode_objid (p, &p, end);
7512 MonoThread *thread;
7513 DebuggerTlsData *tls;
7514 int i, count, flags, nmethods;
7515 ErrorCode err;
7517 err = get_object (objid, (MonoObject**)&thread);
7518 if (err != ERR_NONE)
7519 return err;
7521 flags = decode_int (p, &p, end);
7523 if (command == CMD_VM_INVOKE_METHODS)
7524 nmethods = decode_int (p, &p, end);
7525 else
7526 nmethods = 1;
7528 // Wait for suspending if it already started
7529 if (suspend_count)
7530 wait_for_suspend ();
7531 if (!is_suspended ())
7532 return ERR_NOT_SUSPENDED;
7534 mono_loader_lock ();
7535 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7536 mono_loader_unlock ();
7537 g_assert (tls);
7539 if (!tls->really_suspended)
7540 /* The thread is still running native code, can't do invokes */
7541 return ERR_NOT_SUSPENDED;
7544 * Store the invoke data into tls, the thread will execute it after it is
7545 * resumed.
7547 if (tls->pending_invoke)
7548 return ERR_NOT_SUSPENDED;
7549 tls->pending_invoke = g_new0 (InvokeData, 1);
7550 tls->pending_invoke->id = id;
7551 tls->pending_invoke->flags = flags;
7552 tls->pending_invoke->p = (guint8 *)g_malloc (end - p);
7553 memcpy (tls->pending_invoke->p, p, end - p);
7554 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
7555 tls->pending_invoke->suspend_count = suspend_count;
7556 tls->pending_invoke->nmethods = nmethods;
7558 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
7559 resume_thread (THREAD_TO_INTERNAL (thread));
7561 else {
7562 count = suspend_count;
7563 for (i = 0; i < count; ++i)
7564 resume_vm ();
7566 break;
7568 case CMD_VM_ABORT_INVOKE: {
7569 int objid = decode_objid (p, &p, end);
7570 MonoThread *thread;
7571 DebuggerTlsData *tls;
7572 int invoke_id;
7573 ErrorCode err;
7575 err = get_object (objid, (MonoObject**)&thread);
7576 if (err != ERR_NONE)
7577 return err;
7579 invoke_id = decode_int (p, &p, end);
7581 mono_loader_lock ();
7582 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7583 g_assert (tls);
7585 if (tls->abort_requested) {
7586 DEBUG_PRINTF (1, "Abort already requested.\n");
7587 mono_loader_unlock ();
7588 break;
7592 * Check whether we're still inside the mono_runtime_invoke_checked() and that it's
7593 * actually the correct invocation.
7595 * Careful, we do not stop the thread that's doing the invocation, so we can't
7596 * inspect its stack. However, invoke_method() also acquires the loader lock
7597 * when it's done, so we're safe here.
7601 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
7602 mono_loader_unlock ();
7603 return ERR_NO_INVOCATION;
7606 tls->abort_requested = TRUE;
7608 mono_thread_internal_abort (THREAD_TO_INTERNAL (thread));
7609 mono_loader_unlock ();
7610 break;
7613 case CMD_VM_SET_KEEPALIVE: {
7614 int timeout = decode_int (p, &p, end);
7615 agent_config.keepalive = timeout;
7616 // FIXME:
7617 #ifndef DISABLE_SOCKET_TRANSPORT
7618 set_keepalive ();
7619 #else
7620 NOT_IMPLEMENTED;
7621 #endif
7622 break;
7624 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
7625 GHashTableIter iter, kiter;
7626 MonoDomain *domain;
7627 MonoClass *klass;
7628 GPtrArray *files;
7629 int i;
7630 char *fname, *basename;
7631 gboolean ignore_case;
7632 GSList *class_list, *l;
7633 GPtrArray *res_classes, *res_domains;
7635 fname = decode_string (p, &p, end);
7636 ignore_case = decode_byte (p, &p, end);
7638 basename = dbg_path_get_basename (fname);
7640 res_classes = g_ptr_array_new ();
7641 res_domains = g_ptr_array_new ();
7643 mono_loader_lock ();
7644 g_hash_table_iter_init (&iter, domains);
7645 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7646 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
7648 /* Update 'source_file_to_class' cache */
7649 g_hash_table_iter_init (&kiter, info->loaded_classes);
7650 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
7651 if (!g_hash_table_lookup (info->source_files, klass)) {
7652 files = get_source_files_for_type (klass);
7653 g_hash_table_insert (info->source_files, klass, files);
7655 for (i = 0; i < files->len; ++i) {
7656 char *s = (char *)g_ptr_array_index (files, i);
7657 char *s2 = dbg_path_get_basename (s);
7658 char *s3;
7660 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, s2);
7661 if (!class_list) {
7662 class_list = g_slist_prepend (class_list, klass);
7663 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
7664 } else {
7665 class_list = g_slist_prepend (class_list, klass);
7666 g_hash_table_insert (info->source_file_to_class, s2, class_list);
7669 /* The _ignorecase hash contains the lowercase path */
7670 s3 = strdup_tolower (s2);
7671 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
7672 if (!class_list) {
7673 class_list = g_slist_prepend (class_list, klass);
7674 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
7675 } else {
7676 class_list = g_slist_prepend (class_list, klass);
7677 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
7680 g_free (s2);
7681 g_free (s3);
7686 if (ignore_case) {
7687 char *s;
7689 s = strdup_tolower (basename);
7690 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
7691 g_free (s);
7692 } else {
7693 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, basename);
7696 for (l = class_list; l; l = l->next) {
7697 klass = (MonoClass *)l->data;
7699 g_ptr_array_add (res_classes, klass);
7700 g_ptr_array_add (res_domains, domain);
7703 mono_loader_unlock ();
7705 g_free (fname);
7706 g_free (basename);
7708 buffer_add_int (buf, res_classes->len);
7709 for (i = 0; i < res_classes->len; ++i)
7710 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7711 g_ptr_array_free (res_classes, TRUE);
7712 g_ptr_array_free (res_domains, TRUE);
7713 break;
7715 case CMD_VM_GET_TYPES: {
7716 GHashTableIter iter;
7717 MonoDomain *domain;
7718 int i;
7719 char *name;
7720 gboolean ignore_case;
7721 GPtrArray *res_classes, *res_domains;
7722 MonoTypeNameParse info;
7724 name = decode_string (p, &p, end);
7725 ignore_case = decode_byte (p, &p, end);
7727 if (!mono_reflection_parse_type (name, &info)) {
7728 g_free (name);
7729 mono_reflection_free_type_info (&info);
7730 return ERR_INVALID_ARGUMENT;
7733 res_classes = g_ptr_array_new ();
7734 res_domains = g_ptr_array_new ();
7736 mono_loader_lock ();
7737 g_hash_table_iter_init (&iter, domains);
7738 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7739 MonoAssembly *ass;
7740 gboolean type_resolve;
7741 MonoType *t;
7742 GSList *tmp;
7744 mono_domain_assemblies_lock (domain);
7745 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7746 ass = (MonoAssembly *)tmp->data;
7748 if (ass->image) {
7749 MonoError error;
7750 type_resolve = TRUE;
7751 /* FIXME really okay to call while holding locks? */
7752 t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignore_case, &type_resolve, &error);
7753 mono_error_cleanup (&error);
7754 if (t) {
7755 g_ptr_array_add (res_classes, mono_type_get_class (t));
7756 g_ptr_array_add (res_domains, domain);
7760 mono_domain_assemblies_unlock (domain);
7762 mono_loader_unlock ();
7764 g_free (name);
7765 mono_reflection_free_type_info (&info);
7767 buffer_add_int (buf, res_classes->len);
7768 for (i = 0; i < res_classes->len; ++i)
7769 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7770 g_ptr_array_free (res_classes, TRUE);
7771 g_ptr_array_free (res_domains, TRUE);
7772 break;
7774 case CMD_VM_START_BUFFERING:
7775 case CMD_VM_STOP_BUFFERING:
7776 /* Handled in the main loop */
7777 break;
7778 default:
7779 return ERR_NOT_IMPLEMENTED;
7782 return ERR_NONE;
7785 static ErrorCode
7786 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7788 ErrorCode err;
7789 MonoError error;
7791 switch (command) {
7792 case CMD_EVENT_REQUEST_SET: {
7793 EventRequest *req;
7794 int i, event_kind, suspend_policy, nmodifiers;
7795 ModifierKind mod;
7796 MonoMethod *method;
7797 long location = 0;
7798 MonoThread *step_thread;
7799 int step_thread_id = 0;
7800 StepDepth depth = STEP_DEPTH_INTO;
7801 StepSize size = STEP_SIZE_MIN;
7802 StepFilter filter = STEP_FILTER_NONE;
7803 MonoDomain *domain;
7804 Modifier *modifier;
7806 event_kind = decode_byte (p, &p, end);
7807 suspend_policy = decode_byte (p, &p, end);
7808 nmodifiers = decode_byte (p, &p, end);
7810 req = (EventRequest *)g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7811 req->id = InterlockedIncrement (&event_request_id);
7812 req->event_kind = event_kind;
7813 req->suspend_policy = suspend_policy;
7814 req->nmodifiers = nmodifiers;
7816 method = NULL;
7817 for (i = 0; i < nmodifiers; ++i) {
7818 mod = (ModifierKind)decode_byte (p, &p, end);
7820 req->modifiers [i].kind = mod;
7821 if (mod == MOD_KIND_COUNT) {
7822 req->modifiers [i].data.count = decode_int (p, &p, end);
7823 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7824 method = decode_methodid (p, &p, end, &domain, &err);
7825 if (err != ERR_NONE)
7826 return err;
7827 location = decode_long (p, &p, end);
7828 } else if (mod == MOD_KIND_STEP) {
7829 step_thread_id = decode_id (p, &p, end);
7830 size = (StepSize)decode_int (p, &p, end);
7831 depth = (StepDepth)decode_int (p, &p, end);
7832 if (CHECK_PROTOCOL_VERSION (2, 16))
7833 filter = (StepFilter)decode_int (p, &p, end);
7834 req->modifiers [i].data.filter = filter;
7835 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7836 /* Treat STEP_THOUGH the same as HIDDEN */
7837 req->modifiers [i].data.filter = (StepFilter)(req->modifiers [i].data.filter | STEP_FILTER_DEBUGGER_STEP_THROUGH);
7838 } else if (mod == MOD_KIND_THREAD_ONLY) {
7839 int id = decode_id (p, &p, end);
7841 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7842 if (err != ERR_NONE) {
7843 g_free (req);
7844 return err;
7846 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7847 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7849 if (err != ERR_NONE)
7850 return err;
7851 req->modifiers [i].caught = decode_byte (p, &p, end);
7852 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7853 if (CHECK_PROTOCOL_VERSION (2, 25))
7854 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7855 else
7856 req->modifiers [i].subclasses = TRUE;
7857 DEBUG_PRINTF (1, "[dbg] \tEXCEPTION_ONLY filter (%s%s%s%s).\n", exc_class ? exc_class->name : "all", req->modifiers [i].caught ? ", caught" : "", req->modifiers [i].uncaught ? ", uncaught" : "", req->modifiers [i].subclasses ? ", include-subclasses" : "");
7858 if (exc_class) {
7859 req->modifiers [i].data.exc_class = exc_class;
7861 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
7862 g_free (req);
7863 return ERR_INVALID_ARGUMENT;
7866 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7867 int n = decode_int (p, &p, end);
7868 int j;
7870 // +1 because we don't know length and we use last element to check for end
7871 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n + 1);
7872 for (j = 0; j < n; ++j) {
7873 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7874 if (err != ERR_NONE) {
7875 g_free (req->modifiers [i].data.assemblies);
7876 return err;
7879 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7880 int n = decode_int (p, &p, end);
7881 int j;
7883 modifier = &req->modifiers [i];
7884 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7885 for (j = 0; j < n; ++j) {
7886 char *s = decode_string (p, &p, end);
7887 char *s2;
7889 if (s) {
7890 s2 = strdup_tolower (s);
7891 g_hash_table_insert (modifier->data.source_files, s2, s2);
7892 g_free (s);
7895 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7896 int n = decode_int (p, &p, end);
7897 int j;
7899 modifier = &req->modifiers [i];
7900 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7901 for (j = 0; j < n; ++j) {
7902 char *s = decode_string (p, &p, end);
7904 if (s)
7905 g_hash_table_insert (modifier->data.type_names, s, s);
7907 } else {
7908 g_free (req);
7909 return ERR_NOT_IMPLEMENTED;
7913 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7914 g_assert (method);
7916 req->info = set_breakpoint (method, location, req, &error);
7917 if (!mono_error_ok (&error)) {
7918 g_free (req);
7919 DEBUG_PRINTF (1, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error));
7920 mono_error_cleanup (&error);
7921 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7923 } else if (req->event_kind == EVENT_KIND_STEP) {
7924 g_assert (step_thread_id);
7926 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7927 if (err != ERR_NONE) {
7928 g_free (req);
7929 return err;
7932 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, filter, req);
7933 if (err != ERR_NONE) {
7934 g_free (req);
7935 return err;
7937 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7938 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7939 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7940 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7941 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7942 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7943 } else {
7944 if (req->nmodifiers) {
7945 g_free (req);
7946 return ERR_NOT_IMPLEMENTED;
7950 mono_loader_lock ();
7951 g_ptr_array_add (event_requests, req);
7953 if (agent_config.defer) {
7954 /* Transmit cached data to the client on receipt of the event request */
7955 switch (req->event_kind) {
7956 case EVENT_KIND_APPDOMAIN_CREATE:
7957 /* Emit load events for currently loaded domains */
7958 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7959 break;
7960 case EVENT_KIND_ASSEMBLY_LOAD:
7961 /* Emit load events for currently loaded assemblies */
7962 mono_domain_foreach (send_assemblies_for_domain, NULL);
7963 break;
7964 case EVENT_KIND_THREAD_START:
7965 /* Emit start events for currently started threads */
7966 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7967 break;
7968 case EVENT_KIND_TYPE_LOAD:
7969 /* Emit type load events for currently loaded types */
7970 mono_domain_foreach (send_types_for_domain, NULL);
7971 break;
7972 default:
7973 break;
7976 mono_loader_unlock ();
7978 buffer_add_int (buf, req->id);
7979 break;
7981 case CMD_EVENT_REQUEST_CLEAR: {
7982 int etype = decode_byte (p, &p, end);
7983 int req_id = decode_int (p, &p, end);
7985 // FIXME: Make a faster mapping from req_id to request
7986 mono_loader_lock ();
7987 clear_event_request (req_id, etype);
7988 mono_loader_unlock ();
7989 break;
7991 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7992 int i;
7994 mono_loader_lock ();
7995 i = 0;
7996 while (i < event_requests->len) {
7997 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
7999 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
8000 clear_breakpoint ((MonoBreakpoint *)req->info);
8002 g_ptr_array_remove_index_fast (event_requests, i);
8003 g_free (req);
8004 } else {
8005 i ++;
8008 mono_loader_unlock ();
8009 break;
8011 default:
8012 return ERR_NOT_IMPLEMENTED;
8015 return ERR_NONE;
8018 static ErrorCode
8019 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8021 ErrorCode err;
8022 MonoDomain *domain;
8024 switch (command) {
8025 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
8026 buffer_add_domainid (buf, mono_get_root_domain ());
8027 break;
8029 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
8030 domain = decode_domainid (p, &p, end, NULL, &err);
8031 if (err != ERR_NONE)
8032 return err;
8033 buffer_add_string (buf, domain->friendly_name);
8034 break;
8036 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
8037 GSList *tmp;
8038 MonoAssembly *ass;
8039 int count;
8041 domain = decode_domainid (p, &p, end, NULL, &err);
8042 if (err != ERR_NONE)
8043 return err;
8044 mono_loader_lock ();
8045 count = 0;
8046 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
8047 count ++;
8049 buffer_add_int (buf, count);
8050 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
8051 ass = (MonoAssembly *)tmp->data;
8052 buffer_add_assemblyid (buf, domain, ass);
8054 mono_loader_unlock ();
8055 break;
8057 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
8058 domain = decode_domainid (p, &p, end, NULL, &err);
8059 if (err != ERR_NONE)
8060 return err;
8062 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
8063 break;
8065 case CMD_APPDOMAIN_GET_CORLIB: {
8066 domain = decode_domainid (p, &p, end, NULL, &err);
8067 if (err != ERR_NONE)
8068 return err;
8070 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
8071 break;
8073 case CMD_APPDOMAIN_CREATE_STRING: {
8074 char *s;
8075 MonoString *o;
8076 MonoError error;
8078 domain = decode_domainid (p, &p, end, NULL, &err);
8079 if (err != ERR_NONE)
8080 return err;
8081 s = decode_string (p, &p, end);
8083 o = mono_string_new_checked (domain, s, &error);
8084 if (!is_ok (&error)) {
8085 DEBUG_PRINTF (1, "[dbg] Failed to allocate String object '%s': %s\n", s, mono_error_get_message (&error));
8086 mono_error_cleanup (&error);
8087 return ERR_INVALID_OBJECT;
8089 buffer_add_objid (buf, (MonoObject*)o);
8090 break;
8092 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
8093 MonoError error;
8094 MonoClass *klass;
8095 MonoDomain *domain2;
8096 MonoObject *o;
8098 domain = decode_domainid (p, &p, end, NULL, &err);
8099 if (err != ERR_NONE)
8100 return err;
8101 klass = decode_typeid (p, &p, end, &domain2, &err);
8102 if (err != ERR_NONE)
8103 return err;
8105 // FIXME:
8106 g_assert (domain == domain2);
8108 o = mono_object_new_checked (domain, klass, &error);
8109 mono_error_assert_ok (&error);
8111 err = decode_value (&klass->byval_arg, domain, (guint8 *)mono_object_unbox (o), p, &p, end);
8112 if (err != ERR_NONE)
8113 return err;
8115 buffer_add_objid (buf, o);
8116 break;
8118 default:
8119 return ERR_NOT_IMPLEMENTED;
8122 return ERR_NONE;
8125 static ErrorCode
8126 get_assembly_object_command (MonoDomain *domain, MonoAssembly *ass, Buffer *buf, MonoError *error)
8128 HANDLE_FUNCTION_ENTER();
8129 ErrorCode err = ERR_NONE;
8130 error_init (error);
8131 MonoReflectionAssemblyHandle o = mono_assembly_get_object_handle (domain, ass, error);
8132 if (MONO_HANDLE_IS_NULL (o)) {
8133 err = ERR_INVALID_OBJECT;
8134 goto leave;
8136 buffer_add_objid (buf, MONO_HANDLE_RAW (MONO_HANDLE_CAST (MonoObject, o)));
8137 leave:
8138 HANDLE_FUNCTION_RETURN_VAL (err);
8142 static ErrorCode
8143 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8145 ErrorCode err;
8146 MonoAssembly *ass;
8147 MonoDomain *domain;
8149 ass = decode_assemblyid (p, &p, end, &domain, &err);
8150 if (err != ERR_NONE)
8151 return err;
8153 switch (command) {
8154 case CMD_ASSEMBLY_GET_LOCATION: {
8155 buffer_add_string (buf, mono_image_get_filename (ass->image));
8156 break;
8158 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
8159 guint32 token;
8160 MonoMethod *m;
8162 if (ass->image->dynamic) {
8163 buffer_add_id (buf, 0);
8164 } else {
8165 token = mono_image_get_entry_point (ass->image);
8166 if (token == 0) {
8167 buffer_add_id (buf, 0);
8168 } else {
8169 MonoError error;
8170 m = mono_get_method_checked (ass->image, token, NULL, NULL, &error);
8171 if (!m)
8172 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8173 buffer_add_methodid (buf, domain, m);
8176 break;
8178 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
8179 buffer_add_moduleid (buf, domain, ass->image);
8180 break;
8182 case CMD_ASSEMBLY_GET_OBJECT: {
8183 MonoError error;
8184 err = get_assembly_object_command (domain, ass, buf, &error);
8185 mono_error_cleanup (&error);
8186 return err;
8188 case CMD_ASSEMBLY_GET_DOMAIN: {
8189 buffer_add_domainid (buf, domain);
8190 break;
8192 case CMD_ASSEMBLY_GET_TYPE: {
8193 MonoError error;
8194 char *s = decode_string (p, &p, end);
8195 gboolean ignorecase = decode_byte (p, &p, end);
8196 MonoTypeNameParse info;
8197 MonoType *t;
8198 gboolean type_resolve, res;
8199 MonoDomain *d = mono_domain_get ();
8201 /* This is needed to be able to find referenced assemblies */
8202 res = mono_domain_set (domain, FALSE);
8203 g_assert (res);
8205 if (!mono_reflection_parse_type (s, &info)) {
8206 t = NULL;
8207 } else {
8208 if (info.assembly.name)
8209 NOT_IMPLEMENTED;
8210 t = mono_reflection_get_type_checked (ass->image, ass->image, &info, ignorecase, &type_resolve, &error);
8211 if (!is_ok (&error)) {
8212 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8213 mono_reflection_free_type_info (&info);
8214 g_free (s);
8215 return ERR_INVALID_ARGUMENT;
8218 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
8219 mono_reflection_free_type_info (&info);
8220 g_free (s);
8222 mono_domain_set (d, TRUE);
8224 break;
8226 case CMD_ASSEMBLY_GET_NAME: {
8227 gchar *name;
8228 MonoAssembly *mass = ass;
8230 name = g_strdup_printf (
8231 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
8232 mass->aname.name,
8233 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
8234 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
8235 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
8236 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
8238 buffer_add_string (buf, name);
8239 g_free (name);
8240 break;
8242 default:
8243 return ERR_NOT_IMPLEMENTED;
8246 return ERR_NONE;
8249 static ErrorCode
8250 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8252 ErrorCode err;
8253 MonoDomain *domain;
8255 switch (command) {
8256 case CMD_MODULE_GET_INFO: {
8257 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
8258 char *basename;
8260 basename = g_path_get_basename (image->name);
8261 buffer_add_string (buf, basename); // name
8262 buffer_add_string (buf, image->module_name); // scopename
8263 buffer_add_string (buf, image->name); // fqname
8264 buffer_add_string (buf, mono_image_get_guid (image)); // guid
8265 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
8266 g_free (basename);
8267 break;
8269 default:
8270 return ERR_NOT_IMPLEMENTED;
8273 return ERR_NONE;
8276 static ErrorCode
8277 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8279 ErrorCode err;
8280 MonoDomain *domain;
8282 switch (command) {
8283 case CMD_FIELD_GET_INFO: {
8284 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
8286 buffer_add_string (buf, f->name);
8287 buffer_add_typeid (buf, domain, f->parent);
8288 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
8289 buffer_add_int (buf, f->type->attrs);
8290 break;
8292 default:
8293 return ERR_NOT_IMPLEMENTED;
8296 return ERR_NONE;
8299 static void
8300 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
8302 if (val && val->vtable->klass == mono_defaults.runtimetype_class) {
8303 /* Special case these so the client doesn't have to handle Type objects */
8305 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
8306 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
8307 } else if (MONO_TYPE_IS_REFERENCE (t))
8308 buffer_add_value (buf, t, &val, domain);
8309 else
8310 buffer_add_value (buf, t, mono_object_unbox (val), domain);
8313 static ErrorCode
8314 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
8316 int i, j;
8317 int nattrs = 0;
8319 if (!cinfo) {
8320 buffer_add_int (buf, 0);
8321 return ERR_NONE;
8324 for (i = 0; i < cinfo->num_attrs; ++i) {
8325 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
8326 nattrs ++;
8328 buffer_add_int (buf, nattrs);
8330 for (i = 0; i < cinfo->num_attrs; ++i) {
8331 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
8332 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
8333 MonoArray *typed_args, *named_args;
8334 MonoType *t;
8335 CattrNamedArg *arginfo = NULL;
8336 MonoError error;
8338 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
8339 if (!mono_error_ok (&error)) {
8340 DEBUG_PRINTF (2, "[dbg] mono_reflection_create_custom_attr_data_args () failed with: '%s'\n", mono_error_get_message (&error));
8341 mono_error_cleanup (&error);
8342 return ERR_LOADER_ERROR;
8345 buffer_add_methodid (buf, domain, attr->ctor);
8347 /* Ctor args */
8348 if (typed_args) {
8349 buffer_add_int (buf, mono_array_length (typed_args));
8350 for (j = 0; j < mono_array_length (typed_args); ++j) {
8351 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
8353 t = mono_method_signature (attr->ctor)->params [j];
8355 buffer_add_cattr_arg (buf, t, domain, val);
8357 } else {
8358 buffer_add_int (buf, 0);
8361 /* Named args */
8362 if (named_args) {
8363 buffer_add_int (buf, mono_array_length (named_args));
8365 for (j = 0; j < mono_array_length (named_args); ++j) {
8366 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
8368 if (arginfo [j].prop) {
8369 buffer_add_byte (buf, 0x54);
8370 buffer_add_propertyid (buf, domain, arginfo [j].prop);
8371 } else if (arginfo [j].field) {
8372 buffer_add_byte (buf, 0x53);
8373 buffer_add_fieldid (buf, domain, arginfo [j].field);
8374 } else {
8375 g_assert_not_reached ();
8378 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
8380 } else {
8381 buffer_add_int (buf, 0);
8383 g_free (arginfo);
8387 return ERR_NONE;
8390 /* FIXME: Code duplication with icall.c */
8391 static void
8392 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
8394 int i;
8395 MonoClass *ic;
8397 mono_class_setup_interfaces (klass, error);
8398 if (!mono_error_ok (error))
8399 return;
8401 for (i = 0; i < klass->interface_count; i++) {
8402 ic = klass->interfaces [i];
8403 g_hash_table_insert (ifaces, ic, ic);
8405 collect_interfaces (ic, ifaces, error);
8406 if (!mono_error_ok (error))
8407 return;
8411 static ErrorCode
8412 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8414 MonoError error;
8415 MonoClass *nested;
8416 MonoType *type;
8417 gpointer iter;
8418 guint8 b;
8419 int nnested;
8420 ErrorCode err;
8421 char *name;
8423 switch (command) {
8424 case CMD_TYPE_GET_INFO: {
8425 buffer_add_string (buf, klass->name_space);
8426 buffer_add_string (buf, klass->name);
8427 // FIXME: byref
8428 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
8429 buffer_add_string (buf, name);
8430 g_free (name);
8431 buffer_add_assemblyid (buf, domain, klass->image->assembly);
8432 buffer_add_moduleid (buf, domain, klass->image);
8433 buffer_add_typeid (buf, domain, klass->parent);
8434 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
8435 buffer_add_typeid (buf, domain, klass->element_class);
8436 else
8437 buffer_add_id (buf, 0);
8438 buffer_add_int (buf, klass->type_token);
8439 buffer_add_byte (buf, klass->rank);
8440 buffer_add_int (buf, mono_class_get_flags (klass));
8441 b = 0;
8442 type = &klass->byval_arg;
8443 // FIXME: Can't decide whenever a class represents a byref type
8444 if (FALSE)
8445 b |= (1 << 0);
8446 if (type->type == MONO_TYPE_PTR)
8447 b |= (1 << 1);
8448 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
8449 b |= (1 << 2);
8450 if (type->type == MONO_TYPE_VALUETYPE)
8451 b |= (1 << 3);
8452 if (klass->enumtype)
8453 b |= (1 << 4);
8454 if (mono_class_is_gtd (klass))
8455 b |= (1 << 5);
8456 if (mono_class_is_gtd (klass) || mono_class_is_ginst (klass))
8457 b |= (1 << 6);
8458 buffer_add_byte (buf, b);
8459 nnested = 0;
8460 iter = NULL;
8461 while ((nested = mono_class_get_nested_types (klass, &iter)))
8462 nnested ++;
8463 buffer_add_int (buf, nnested);
8464 iter = NULL;
8465 while ((nested = mono_class_get_nested_types (klass, &iter)))
8466 buffer_add_typeid (buf, domain, nested);
8467 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8468 if (mono_class_is_gtd (klass))
8469 buffer_add_typeid (buf, domain, klass);
8470 else if (mono_class_is_ginst (klass))
8471 buffer_add_typeid (buf, domain, mono_class_get_generic_class (klass)->container_class);
8472 else
8473 buffer_add_id (buf, 0);
8475 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8476 int count, i;
8478 if (mono_class_is_ginst (klass)) {
8479 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
8481 count = inst->type_argc;
8482 buffer_add_int (buf, count);
8483 for (i = 0; i < count; i++)
8484 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8485 } else if (mono_class_is_gtd (klass)) {
8486 MonoGenericContainer *container = mono_class_get_generic_container (klass);
8487 MonoClass *pklass;
8489 count = container->type_argc;
8490 buffer_add_int (buf, count);
8491 for (i = 0; i < count; i++) {
8492 pklass = mono_class_from_generic_parameter_internal (mono_generic_container_get_param (container, i));
8493 buffer_add_typeid (buf, domain, pklass);
8495 } else {
8496 buffer_add_int (buf, 0);
8499 break;
8501 case CMD_TYPE_GET_METHODS: {
8502 int nmethods;
8503 int i = 0;
8504 gpointer iter = NULL;
8505 MonoMethod *m;
8507 mono_class_setup_methods (klass);
8509 nmethods = mono_class_num_methods (klass);
8511 buffer_add_int (buf, nmethods);
8513 while ((m = mono_class_get_methods (klass, &iter))) {
8514 buffer_add_methodid (buf, domain, m);
8515 i ++;
8517 g_assert (i == nmethods);
8518 break;
8520 case CMD_TYPE_GET_FIELDS: {
8521 int nfields;
8522 int i = 0;
8523 gpointer iter = NULL;
8524 MonoClassField *f;
8526 nfields = mono_class_num_fields (klass);
8528 buffer_add_int (buf, nfields);
8530 while ((f = mono_class_get_fields (klass, &iter))) {
8531 buffer_add_fieldid (buf, domain, f);
8532 buffer_add_string (buf, f->name);
8533 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
8534 buffer_add_int (buf, f->type->attrs);
8535 i ++;
8537 g_assert (i == nfields);
8538 break;
8540 case CMD_TYPE_GET_PROPERTIES: {
8541 int nprops;
8542 int i = 0;
8543 gpointer iter = NULL;
8544 MonoProperty *p;
8546 nprops = mono_class_num_properties (klass);
8548 buffer_add_int (buf, nprops);
8550 while ((p = mono_class_get_properties (klass, &iter))) {
8551 buffer_add_propertyid (buf, domain, p);
8552 buffer_add_string (buf, p->name);
8553 buffer_add_methodid (buf, domain, p->get);
8554 buffer_add_methodid (buf, domain, p->set);
8555 buffer_add_int (buf, p->attrs);
8556 i ++;
8558 g_assert (i == nprops);
8559 break;
8561 case CMD_TYPE_GET_CATTRS: {
8562 MonoClass *attr_klass;
8563 MonoCustomAttrInfo *cinfo;
8565 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8566 /* attr_klass can be NULL */
8567 if (err != ERR_NONE)
8568 return err;
8570 cinfo = mono_custom_attrs_from_class_checked (klass, &error);
8571 if (!is_ok (&error)) {
8572 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8573 return ERR_LOADER_ERROR;
8576 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8577 if (err != ERR_NONE)
8578 return err;
8579 break;
8581 case CMD_TYPE_GET_FIELD_CATTRS: {
8582 MonoClass *attr_klass;
8583 MonoCustomAttrInfo *cinfo;
8584 MonoClassField *field;
8586 field = decode_fieldid (p, &p, end, NULL, &err);
8587 if (err != ERR_NONE)
8588 return err;
8589 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8590 if (err != ERR_NONE)
8591 return err;
8593 cinfo = mono_custom_attrs_from_field_checked (klass, field, &error);
8594 if (!is_ok (&error)) {
8595 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8596 return ERR_LOADER_ERROR;
8599 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8600 if (err != ERR_NONE)
8601 return err;
8602 break;
8604 case CMD_TYPE_GET_PROPERTY_CATTRS: {
8605 MonoClass *attr_klass;
8606 MonoCustomAttrInfo *cinfo;
8607 MonoProperty *prop;
8609 prop = decode_propertyid (p, &p, end, NULL, &err);
8610 if (err != ERR_NONE)
8611 return err;
8612 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8613 if (err != ERR_NONE)
8614 return err;
8616 cinfo = mono_custom_attrs_from_property_checked (klass, prop, &error);
8617 if (!is_ok (&error)) {
8618 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
8619 return ERR_LOADER_ERROR;
8622 err = buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
8623 if (err != ERR_NONE)
8624 return err;
8625 break;
8627 case CMD_TYPE_GET_VALUES:
8628 case CMD_TYPE_GET_VALUES_2: {
8629 guint8 *val;
8630 MonoClassField *f;
8631 MonoVTable *vtable;
8632 MonoClass *k;
8633 int len, i;
8634 gboolean found;
8635 MonoThread *thread_obj;
8636 MonoInternalThread *thread = NULL;
8637 guint32 special_static_type;
8639 if (command == CMD_TYPE_GET_VALUES_2) {
8640 int objid = decode_objid (p, &p, end);
8641 ErrorCode err;
8643 err = get_object (objid, (MonoObject**)&thread_obj);
8644 if (err != ERR_NONE)
8645 return err;
8647 thread = THREAD_TO_INTERNAL (thread_obj);
8650 len = decode_int (p, &p, end);
8651 for (i = 0; i < len; ++i) {
8652 f = decode_fieldid (p, &p, end, NULL, &err);
8653 if (err != ERR_NONE)
8654 return err;
8656 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8657 return ERR_INVALID_FIELDID;
8658 special_static_type = mono_class_field_get_special_static_type (f);
8659 if (special_static_type != SPECIAL_STATIC_NONE) {
8660 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
8661 return ERR_INVALID_FIELDID;
8664 /* Check that the field belongs to the object */
8665 found = FALSE;
8666 for (k = klass; k; k = k->parent) {
8667 if (k == f->parent) {
8668 found = TRUE;
8669 break;
8672 if (!found)
8673 return ERR_INVALID_FIELDID;
8675 vtable = mono_class_vtable (domain, f->parent);
8676 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8677 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val, &error);
8678 if (!is_ok (&error))
8679 return ERR_INVALID_FIELDID;
8680 buffer_add_value (buf, f->type, val, domain);
8681 g_free (val);
8683 break;
8685 case CMD_TYPE_SET_VALUES: {
8686 guint8 *val;
8687 MonoClassField *f;
8688 MonoVTable *vtable;
8689 MonoClass *k;
8690 int len, i;
8691 gboolean found;
8693 len = decode_int (p, &p, end);
8694 for (i = 0; i < len; ++i) {
8695 f = decode_fieldid (p, &p, end, NULL, &err);
8696 if (err != ERR_NONE)
8697 return err;
8699 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8700 return ERR_INVALID_FIELDID;
8701 if (mono_class_field_is_special_static (f))
8702 return ERR_INVALID_FIELDID;
8704 /* Check that the field belongs to the object */
8705 found = FALSE;
8706 for (k = klass; k; k = k->parent) {
8707 if (k == f->parent) {
8708 found = TRUE;
8709 break;
8712 if (!found)
8713 return ERR_INVALID_FIELDID;
8715 // FIXME: Check for literal/const
8717 vtable = mono_class_vtable (domain, f->parent);
8718 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8719 err = decode_value (f->type, domain, val, p, &p, end);
8720 if (err != ERR_NONE) {
8721 g_free (val);
8722 return err;
8724 if (MONO_TYPE_IS_REFERENCE (f->type))
8725 mono_field_static_set_value (vtable, f, *(gpointer*)val);
8726 else
8727 mono_field_static_set_value (vtable, f, val);
8728 g_free (val);
8730 break;
8732 case CMD_TYPE_GET_OBJECT: {
8733 MonoObject *o = (MonoObject*)mono_type_get_object_checked (domain, &klass->byval_arg, &error);
8734 if (!mono_error_ok (&error)) {
8735 mono_error_cleanup (&error);
8736 return ERR_INVALID_OBJECT;
8738 buffer_add_objid (buf, o);
8739 break;
8741 case CMD_TYPE_GET_SOURCE_FILES:
8742 case CMD_TYPE_GET_SOURCE_FILES_2: {
8743 char *source_file, *base;
8744 GPtrArray *files;
8745 int i;
8747 files = get_source_files_for_type (klass);
8749 buffer_add_int (buf, files->len);
8750 for (i = 0; i < files->len; ++i) {
8751 source_file = (char *)g_ptr_array_index (files, i);
8752 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8753 buffer_add_string (buf, source_file);
8754 } else {
8755 base = dbg_path_get_basename (source_file);
8756 buffer_add_string (buf, base);
8757 g_free (base);
8759 g_free (source_file);
8761 g_ptr_array_free (files, TRUE);
8762 break;
8764 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8765 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8767 if (err != ERR_NONE)
8768 return err;
8769 if (mono_class_is_assignable_from (klass, oklass))
8770 buffer_add_byte (buf, 1);
8771 else
8772 buffer_add_byte (buf, 0);
8773 break;
8775 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8776 char *name = decode_string (p, &p, end);
8777 int i, flags = decode_int (p, &p, end);
8778 MonoError error;
8779 GPtrArray *array;
8781 error_init (&error);
8782 array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &error);
8783 if (!is_ok (&error)) {
8784 mono_error_cleanup (&error);
8785 return ERR_LOADER_ERROR;
8787 buffer_add_int (buf, array->len);
8788 for (i = 0; i < array->len; ++i) {
8789 MonoMethod *method = (MonoMethod *)g_ptr_array_index (array, i);
8790 buffer_add_methodid (buf, domain, method);
8793 g_ptr_array_free (array, TRUE);
8794 g_free (name);
8795 break;
8797 case CMD_TYPE_GET_INTERFACES: {
8798 MonoClass *parent;
8799 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8800 MonoClass *tclass, *iface;
8801 GHashTableIter iter;
8803 tclass = klass;
8805 for (parent = tclass; parent; parent = parent->parent) {
8806 mono_class_setup_interfaces (parent, &error);
8807 if (!mono_error_ok (&error))
8808 return ERR_LOADER_ERROR;
8809 collect_interfaces (parent, iface_hash, &error);
8810 if (!mono_error_ok (&error))
8811 return ERR_LOADER_ERROR;
8814 buffer_add_int (buf, g_hash_table_size (iface_hash));
8816 g_hash_table_iter_init (&iter, iface_hash);
8817 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8818 buffer_add_typeid (buf, domain, iface);
8819 g_hash_table_destroy (iface_hash);
8820 break;
8822 case CMD_TYPE_GET_INTERFACE_MAP: {
8823 int tindex, ioffset;
8824 gboolean variance_used;
8825 MonoClass *iclass;
8826 int len, nmethods, i;
8827 gpointer iter;
8828 MonoMethod *method;
8830 len = decode_int (p, &p, end);
8831 mono_class_setup_vtable (klass);
8833 for (tindex = 0; tindex < len; ++tindex) {
8834 iclass = decode_typeid (p, &p, end, NULL, &err);
8835 if (err != ERR_NONE)
8836 return err;
8838 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8839 if (ioffset == -1)
8840 return ERR_INVALID_ARGUMENT;
8842 nmethods = mono_class_num_methods (iclass);
8843 buffer_add_int (buf, nmethods);
8845 iter = NULL;
8846 while ((method = mono_class_get_methods (iclass, &iter))) {
8847 buffer_add_methodid (buf, domain, method);
8849 for (i = 0; i < nmethods; ++i)
8850 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
8852 break;
8854 case CMD_TYPE_IS_INITIALIZED: {
8855 MonoVTable *vtable = mono_class_vtable (domain, klass);
8857 if (vtable)
8858 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8859 else
8860 buffer_add_int (buf, 0);
8861 break;
8863 case CMD_TYPE_CREATE_INSTANCE: {
8864 MonoError error;
8865 MonoObject *obj;
8867 obj = mono_object_new_checked (domain, klass, &error);
8868 mono_error_assert_ok (&error);
8869 buffer_add_objid (buf, obj);
8870 break;
8872 default:
8873 return ERR_NOT_IMPLEMENTED;
8876 return ERR_NONE;
8879 static ErrorCode
8880 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8882 MonoClass *klass;
8883 MonoDomain *old_domain;
8884 MonoDomain *domain;
8885 ErrorCode err;
8887 klass = decode_typeid (p, &p, end, &domain, &err);
8888 if (err != ERR_NONE)
8889 return err;
8891 old_domain = mono_domain_get ();
8893 mono_domain_set (domain, TRUE);
8895 err = type_commands_internal (command, klass, domain, p, end, buf);
8897 mono_domain_set (old_domain, TRUE);
8899 return err;
8902 static ErrorCode
8903 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8905 MonoMethodHeader *header;
8906 ErrorCode err;
8908 switch (command) {
8909 case CMD_METHOD_GET_NAME: {
8910 buffer_add_string (buf, method->name);
8911 break;
8913 case CMD_METHOD_GET_DECLARING_TYPE: {
8914 buffer_add_typeid (buf, domain, method->klass);
8915 break;
8917 case CMD_METHOD_GET_DEBUG_INFO: {
8918 MonoError error;
8919 MonoDebugMethodInfo *minfo;
8920 char *source_file;
8921 int i, j, n_il_offsets;
8922 int *source_files;
8923 GPtrArray *source_file_list;
8924 MonoSymSeqPoint *sym_seq_points;
8926 header = mono_method_get_header_checked (method, &error);
8927 if (!header) {
8928 mono_error_cleanup (&error); /* FIXME don't swallow the error */
8929 buffer_add_int (buf, 0);
8930 buffer_add_string (buf, "");
8931 buffer_add_int (buf, 0);
8932 break;
8935 minfo = mono_debug_lookup_method (method);
8936 if (!minfo) {
8937 buffer_add_int (buf, header->code_size);
8938 buffer_add_string (buf, "");
8939 buffer_add_int (buf, 0);
8940 mono_metadata_free_mh (header);
8941 break;
8944 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, &source_files, &sym_seq_points, &n_il_offsets);
8945 buffer_add_int (buf, header->code_size);
8946 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8947 buffer_add_int (buf, source_file_list->len);
8948 for (i = 0; i < source_file_list->len; ++i) {
8949 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
8950 buffer_add_string (buf, sinfo->source_file);
8951 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8952 for (j = 0; j < 16; ++j)
8953 buffer_add_byte (buf, sinfo->hash [j]);
8956 } else {
8957 buffer_add_string (buf, source_file);
8959 buffer_add_int (buf, n_il_offsets);
8960 DEBUG_PRINTF (10, "Line number table for method %s:\n", mono_method_full_name (method, TRUE));
8961 for (i = 0; i < n_il_offsets; ++i) {
8962 MonoSymSeqPoint *sp = &sym_seq_points [i];
8963 const char *srcfile = "";
8965 if (source_files [i] != -1) {
8966 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, source_files [i]);
8967 srcfile = sinfo->source_file;
8969 DEBUG_PRINTF (10, "IL%x -> %s:%d %d %d %d\n", sp->il_offset, srcfile, sp->line, sp->column, sp->end_line, sp->end_column);
8970 buffer_add_int (buf, sp->il_offset);
8971 buffer_add_int (buf, sp->line);
8972 if (CHECK_PROTOCOL_VERSION (2, 13))
8973 buffer_add_int (buf, source_files [i]);
8974 if (CHECK_PROTOCOL_VERSION (2, 19))
8975 buffer_add_int (buf, sp->column);
8976 if (CHECK_PROTOCOL_VERSION (2, 32)) {
8977 buffer_add_int (buf, sp->end_line);
8978 buffer_add_int (buf, sp->end_column);
8981 g_free (source_file);
8982 g_free (source_files);
8983 g_free (sym_seq_points);
8984 g_ptr_array_free (source_file_list, TRUE);
8985 mono_metadata_free_mh (header);
8986 break;
8988 case CMD_METHOD_GET_PARAM_INFO: {
8989 MonoMethodSignature *sig = mono_method_signature (method);
8990 guint32 i;
8991 char **names;
8993 /* FIXME: mono_class_from_mono_type () and byrefs */
8995 /* FIXME: Use a smaller encoding */
8996 buffer_add_int (buf, sig->call_convention);
8997 buffer_add_int (buf, sig->param_count);
8998 buffer_add_int (buf, sig->generic_param_count);
8999 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
9000 for (i = 0; i < sig->param_count; ++i) {
9001 /* FIXME: vararg */
9002 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
9005 /* Emit parameter names */
9006 names = g_new (char *, sig->param_count);
9007 mono_method_get_param_names (method, (const char **) names);
9008 for (i = 0; i < sig->param_count; ++i)
9009 buffer_add_string (buf, names [i]);
9010 g_free (names);
9012 break;
9014 case CMD_METHOD_GET_LOCALS_INFO: {
9015 MonoError error;
9016 int i, num_locals;
9017 MonoDebugLocalsInfo *locals;
9018 int *locals_map = NULL;
9020 header = mono_method_get_header_checked (method, &error);
9021 if (!header) {
9022 mono_error_cleanup (&error); /* FIXME don't swallow the error */
9023 return ERR_INVALID_ARGUMENT;
9026 locals = mono_debug_lookup_locals (method);
9027 if (!locals) {
9028 if (CHECK_PROTOCOL_VERSION (2, 43)) {
9029 /* Scopes */
9030 buffer_add_int (buf, 1);
9031 buffer_add_int (buf, 0);
9032 buffer_add_int (buf, header->code_size);
9034 buffer_add_int (buf, header->num_locals);
9035 /* Types */
9036 for (i = 0; i < header->num_locals; ++i) {
9037 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
9039 /* Names */
9040 for (i = 0; i < header->num_locals; ++i) {
9041 char lname [128];
9042 sprintf (lname, "V_%d", i);
9043 buffer_add_string (buf, lname);
9045 /* Scopes */
9046 for (i = 0; i < header->num_locals; ++i) {
9047 buffer_add_int (buf, 0);
9048 buffer_add_int (buf, header->code_size);
9050 } else {
9051 if (CHECK_PROTOCOL_VERSION (2, 43)) {
9052 /* Scopes */
9053 buffer_add_int (buf, locals->num_blocks);
9054 int last_start = 0;
9055 for (i = 0; i < locals->num_blocks; ++i) {
9056 buffer_add_int (buf, locals->code_blocks [i].start_offset - last_start);
9057 buffer_add_int (buf, locals->code_blocks [i].end_offset - locals->code_blocks [i].start_offset);
9058 last_start = locals->code_blocks [i].start_offset;
9062 num_locals = locals->num_locals;
9063 buffer_add_int (buf, num_locals);
9065 /* Types */
9066 for (i = 0; i < num_locals; ++i) {
9067 g_assert (locals->locals [i].index < header->num_locals);
9068 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [locals->locals [i].index]));
9070 /* Names */
9071 for (i = 0; i < num_locals; ++i)
9072 buffer_add_string (buf, locals->locals [i].name);
9073 /* Scopes */
9074 for (i = 0; i < num_locals; ++i) {
9075 if (locals->locals [i].block) {
9076 buffer_add_int (buf, locals->locals [i].block->start_offset);
9077 buffer_add_int (buf, locals->locals [i].block->end_offset);
9078 } else {
9079 buffer_add_int (buf, 0);
9080 buffer_add_int (buf, header->code_size);
9084 mono_metadata_free_mh (header);
9086 if (locals)
9087 mono_debug_free_locals (locals);
9088 g_free (locals_map);
9090 break;
9092 case CMD_METHOD_GET_INFO:
9093 buffer_add_int (buf, method->flags);
9094 buffer_add_int (buf, method->iflags);
9095 buffer_add_int (buf, method->token);
9096 if (CHECK_PROTOCOL_VERSION (2, 12)) {
9097 guint8 attrs = 0;
9098 if (method->is_generic)
9099 attrs |= (1 << 0);
9100 if (mono_method_signature (method)->generic_param_count)
9101 attrs |= (1 << 1);
9102 buffer_add_byte (buf, attrs);
9103 if (method->is_generic || method->is_inflated) {
9104 MonoMethod *result;
9106 if (method->is_generic) {
9107 result = method;
9108 } else {
9109 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
9111 result = imethod->declaring;
9112 if (imethod->context.class_inst) {
9113 MonoClass *klass = ((MonoMethod *) imethod)->klass;
9114 /*Generic methods gets the context of the GTD.*/
9115 if (mono_class_get_context (klass)) {
9116 MonoError error;
9117 result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), &error);
9118 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9123 buffer_add_methodid (buf, domain, result);
9124 } else {
9125 buffer_add_id (buf, 0);
9127 if (CHECK_PROTOCOL_VERSION (2, 15)) {
9128 if (mono_method_signature (method)->generic_param_count) {
9129 int count, i;
9131 if (method->is_inflated) {
9132 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
9133 if (inst) {
9134 count = inst->type_argc;
9135 buffer_add_int (buf, count);
9137 for (i = 0; i < count; i++)
9138 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
9139 } else {
9140 buffer_add_int (buf, 0);
9142 } else if (method->is_generic) {
9143 MonoGenericContainer *container = mono_method_get_generic_container (method);
9145 count = mono_method_signature (method)->generic_param_count;
9146 buffer_add_int (buf, count);
9147 for (i = 0; i < count; i++) {
9148 MonoGenericParam *param = mono_generic_container_get_param (container, i);
9149 MonoClass *pklass = mono_class_from_generic_parameter_internal (param);
9150 buffer_add_typeid (buf, domain, pklass);
9152 } else {
9153 buffer_add_int (buf, 0);
9155 } else {
9156 buffer_add_int (buf, 0);
9160 break;
9161 case CMD_METHOD_GET_BODY: {
9162 MonoError error;
9163 int i;
9165 header = mono_method_get_header_checked (method, &error);
9166 if (!header) {
9167 mono_error_cleanup (&error); /* FIXME don't swallow the error */
9168 buffer_add_int (buf, 0);
9170 if (CHECK_PROTOCOL_VERSION (2, 18))
9171 buffer_add_int (buf, 0);
9172 } else {
9173 buffer_add_int (buf, header->code_size);
9174 for (i = 0; i < header->code_size; ++i)
9175 buffer_add_byte (buf, header->code [i]);
9177 if (CHECK_PROTOCOL_VERSION (2, 18)) {
9178 buffer_add_int (buf, header->num_clauses);
9179 for (i = 0; i < header->num_clauses; ++i) {
9180 MonoExceptionClause *clause = &header->clauses [i];
9182 buffer_add_int (buf, clause->flags);
9183 buffer_add_int (buf, clause->try_offset);
9184 buffer_add_int (buf, clause->try_len);
9185 buffer_add_int (buf, clause->handler_offset);
9186 buffer_add_int (buf, clause->handler_len);
9187 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
9188 buffer_add_typeid (buf, domain, clause->data.catch_class);
9189 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
9190 buffer_add_int (buf, clause->data.filter_offset);
9194 mono_metadata_free_mh (header);
9197 break;
9199 case CMD_METHOD_RESOLVE_TOKEN: {
9200 guint32 token = decode_int (p, &p, end);
9202 // FIXME: Generics
9203 switch (mono_metadata_token_code (token)) {
9204 case MONO_TOKEN_STRING: {
9205 MonoError error;
9206 MonoString *s;
9207 char *s2;
9209 s = mono_ldstr_checked (domain, method->klass->image, mono_metadata_token_index (token), &error);
9210 mono_error_assert_ok (&error); /* FIXME don't swallow the error */
9212 s2 = mono_string_to_utf8_checked (s, &error);
9213 mono_error_assert_ok (&error);
9215 buffer_add_byte (buf, TOKEN_TYPE_STRING);
9216 buffer_add_string (buf, s2);
9217 g_free (s2);
9218 break;
9220 default: {
9221 MonoError error;
9222 gpointer val;
9223 MonoClass *handle_class;
9225 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
9226 val = mono_method_get_wrapper_data (method, token);
9227 handle_class = (MonoClass *)mono_method_get_wrapper_data (method, token + 1);
9229 if (handle_class == NULL) {
9230 // Can't figure out the token type
9231 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
9232 break;
9234 } else {
9235 val = mono_ldtoken_checked (method->klass->image, token, &handle_class, NULL, &error);
9236 if (!val)
9237 g_error ("Could not load token due to %s", mono_error_get_message (&error));
9240 if (handle_class == mono_defaults.typehandle_class) {
9241 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
9242 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
9243 buffer_add_typeid (buf, domain, (MonoClass *) val);
9244 else
9245 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
9246 } else if (handle_class == mono_defaults.fieldhandle_class) {
9247 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
9248 buffer_add_fieldid (buf, domain, (MonoClassField *)val);
9249 } else if (handle_class == mono_defaults.methodhandle_class) {
9250 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
9251 buffer_add_methodid (buf, domain, (MonoMethod *)val);
9252 } else if (handle_class == mono_defaults.string_class) {
9253 char *s;
9255 s = mono_string_to_utf8_checked ((MonoString *)val, &error);
9256 mono_error_assert_ok (&error);
9257 buffer_add_byte (buf, TOKEN_TYPE_STRING);
9258 buffer_add_string (buf, s);
9259 g_free (s);
9260 } else {
9261 g_assert_not_reached ();
9263 break;
9266 break;
9268 case CMD_METHOD_GET_CATTRS: {
9269 MonoError error;
9270 MonoClass *attr_klass;
9271 MonoCustomAttrInfo *cinfo;
9273 attr_klass = decode_typeid (p, &p, end, NULL, &err);
9274 /* attr_klass can be NULL */
9275 if (err != ERR_NONE)
9276 return err;
9278 cinfo = mono_custom_attrs_from_method_checked (method, &error);
9279 if (!is_ok (&error)) {
9280 mono_error_cleanup (&error); /* FIXME don't swallow the error message */
9281 return ERR_LOADER_ERROR;
9284 err = buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
9285 if (err != ERR_NONE)
9286 return err;
9287 break;
9289 case CMD_METHOD_MAKE_GENERIC_METHOD: {
9290 MonoError error;
9291 MonoType **type_argv;
9292 int i, type_argc;
9293 MonoDomain *d;
9294 MonoClass *klass;
9295 MonoGenericInst *ginst;
9296 MonoGenericContext tmp_context;
9297 MonoMethod *inflated;
9299 type_argc = decode_int (p, &p, end);
9300 type_argv = g_new0 (MonoType*, type_argc);
9301 for (i = 0; i < type_argc; ++i) {
9302 klass = decode_typeid (p, &p, end, &d, &err);
9303 if (err != ERR_NONE) {
9304 g_free (type_argv);
9305 return err;
9307 if (domain != d) {
9308 g_free (type_argv);
9309 return ERR_INVALID_ARGUMENT;
9311 type_argv [i] = &klass->byval_arg;
9313 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
9314 g_free (type_argv);
9315 tmp_context.class_inst = mono_class_is_ginst (method->klass) ? mono_class_get_generic_class (method->klass)->context.class_inst : NULL;
9316 tmp_context.method_inst = ginst;
9318 inflated = mono_class_inflate_generic_method_checked (method, &tmp_context, &error);
9319 g_assert (mono_error_ok (&error)); /* FIXME don't swallow the error */
9320 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
9321 return ERR_INVALID_ARGUMENT;
9322 buffer_add_methodid (buf, domain, inflated);
9323 break;
9325 default:
9326 return ERR_NOT_IMPLEMENTED;
9329 return ERR_NONE;
9332 static ErrorCode
9333 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9335 ErrorCode err;
9336 MonoDomain *old_domain;
9337 MonoDomain *domain;
9338 MonoMethod *method;
9340 method = decode_methodid (p, &p, end, &domain, &err);
9341 if (err != ERR_NONE)
9342 return err;
9344 old_domain = mono_domain_get ();
9346 mono_domain_set (domain, TRUE);
9348 err = method_commands_internal (command, method, domain, p, end, buf);
9350 mono_domain_set (old_domain, TRUE);
9352 return err;
9355 static ErrorCode
9356 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9358 int objid = decode_objid (p, &p, end);
9359 ErrorCode err;
9360 MonoThread *thread_obj;
9361 MonoInternalThread *thread;
9363 err = get_object (objid, (MonoObject**)&thread_obj);
9364 if (err != ERR_NONE)
9365 return err;
9367 thread = THREAD_TO_INTERNAL (thread_obj);
9369 switch (command) {
9370 case CMD_THREAD_GET_NAME: {
9371 guint32 name_len;
9372 gunichar2 *s = mono_thread_get_name (thread, &name_len);
9374 if (!s) {
9375 buffer_add_int (buf, 0);
9376 } else {
9377 char *name;
9378 glong len;
9380 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
9381 g_assert (name);
9382 buffer_add_int (buf, len);
9383 buffer_add_data (buf, (guint8*)name, len);
9384 g_free (s);
9386 break;
9388 case CMD_THREAD_GET_FRAME_INFO: {
9389 DebuggerTlsData *tls;
9390 int i, start_frame, length;
9392 // Wait for suspending if it already started
9393 // FIXME: Races with suspend_count
9394 while (!is_suspended ()) {
9395 if (suspend_count)
9396 wait_for_suspend ();
9399 if (suspend_count)
9400 wait_for_suspend ();
9401 if (!is_suspended ())
9402 return ERR_NOT_SUSPENDED;
9405 start_frame = decode_int (p, &p, end);
9406 length = decode_int (p, &p, end);
9408 if (start_frame != 0 || length != -1)
9409 return ERR_NOT_IMPLEMENTED;
9411 mono_loader_lock ();
9412 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9413 mono_loader_unlock ();
9414 g_assert (tls);
9416 compute_frame_info (thread, tls);
9418 buffer_add_int (buf, tls->frame_count);
9419 for (i = 0; i < tls->frame_count; ++i) {
9420 buffer_add_int (buf, tls->frames [i]->id);
9421 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
9422 buffer_add_int (buf, tls->frames [i]->il_offset);
9424 * Instead of passing the frame type directly to the client, we associate
9425 * it with the previous frame using a set of flags. This avoids lots of
9426 * conditional code in the client, since a frame whose type isn't
9427 * FRAME_TYPE_MANAGED has no method, location, etc.
9429 buffer_add_byte (buf, tls->frames [i]->flags);
9432 break;
9434 case CMD_THREAD_GET_STATE:
9435 buffer_add_int (buf, thread->state);
9436 break;
9437 case CMD_THREAD_GET_INFO:
9438 buffer_add_byte (buf, thread->threadpool_thread);
9439 break;
9440 case CMD_THREAD_GET_ID:
9441 buffer_add_long (buf, (guint64)(gsize)thread);
9442 break;
9443 case CMD_THREAD_GET_TID:
9444 buffer_add_long (buf, (guint64)thread->tid);
9445 break;
9446 case CMD_THREAD_SET_IP: {
9447 DebuggerTlsData *tls;
9448 MonoMethod *method;
9449 MonoDomain *domain;
9450 MonoSeqPointInfo *seq_points;
9451 SeqPoint sp;
9452 gboolean found_sp;
9453 gint64 il_offset;
9455 method = decode_methodid (p, &p, end, &domain, &err);
9456 if (err != ERR_NONE)
9457 return err;
9458 il_offset = decode_long (p, &p, end);
9460 while (!is_suspended ()) {
9461 if (suspend_count)
9462 wait_for_suspend ();
9465 mono_loader_lock ();
9466 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9467 mono_loader_unlock ();
9468 g_assert (tls);
9470 compute_frame_info (thread, tls);
9471 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
9472 return ERR_INVALID_ARGUMENT;
9474 found_sp = mono_find_seq_point (domain, method, il_offset, &seq_points, &sp);
9476 g_assert (seq_points);
9478 if (!found_sp)
9479 return ERR_INVALID_ARGUMENT;
9481 // FIXME: Check that the ip change is safe
9483 DEBUG_PRINTF (1, "[dbg] Setting IP to %s:0x%0x(0x%0x)\n", tls->frames [0]->actual_method->name, (int)sp.il_offset, (int)sp.native_offset);
9485 if (tls->frames [0]->ji->is_interp) {
9486 MonoJitTlsData *jit_data = ((MonoThreadInfo*)thread->thread_info)->jit_data;
9487 mono_interp_set_resume_state (jit_data, NULL, tls->frames [0]->interp_frame, (guint8*)tls->frames [0]->ji->code_start + sp.native_offset);
9488 } else {
9489 MONO_CONTEXT_SET_IP (&tls->restore_state.ctx, (guint8*)tls->frames [0]->ji->code_start + sp.native_offset);
9491 break;
9493 default:
9494 return ERR_NOT_IMPLEMENTED;
9497 return ERR_NONE;
9500 static ErrorCode
9501 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9503 int objid;
9504 ErrorCode err;
9505 MonoThread *thread_obj;
9506 MonoInternalThread *thread;
9507 int pos, i, len, frame_idx;
9508 DebuggerTlsData *tls;
9509 StackFrame *frame;
9510 MonoDebugMethodJitInfo *jit;
9511 MonoMethodSignature *sig;
9512 gssize id;
9513 MonoMethodHeader *header;
9515 objid = decode_objid (p, &p, end);
9516 err = get_object (objid, (MonoObject**)&thread_obj);
9517 if (err != ERR_NONE)
9518 return err;
9520 thread = THREAD_TO_INTERNAL (thread_obj);
9522 id = decode_id (p, &p, end);
9524 mono_loader_lock ();
9525 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9526 mono_loader_unlock ();
9527 g_assert (tls);
9529 for (i = 0; i < tls->frame_count; ++i) {
9530 if (tls->frames [i]->id == id)
9531 break;
9533 if (i == tls->frame_count)
9534 return ERR_INVALID_FRAMEID;
9536 frame_idx = i;
9537 frame = tls->frames [frame_idx];
9539 /* This is supported for frames without has_ctx etc. set */
9540 if (command == CMD_STACK_FRAME_GET_DOMAIN) {
9541 if (CHECK_PROTOCOL_VERSION (2, 38))
9542 buffer_add_domainid (buf, frame->domain);
9543 return ERR_NONE;
9546 if (!frame->has_ctx)
9547 return ERR_ABSENT_INFORMATION;
9549 if (!ensure_jit (frame))
9550 return ERR_ABSENT_INFORMATION;
9552 jit = frame->jit;
9554 sig = mono_method_signature (frame->actual_method);
9556 if (!(jit->has_var_info || frame->ji->is_interp) || !mono_get_seq_points (frame->domain, frame->actual_method))
9558 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
9560 return ERR_ABSENT_INFORMATION;
9562 switch (command) {
9563 case CMD_STACK_FRAME_GET_VALUES: {
9564 MonoError error;
9565 len = decode_int (p, &p, end);
9566 header = mono_method_get_header_checked (frame->actual_method, &error);
9567 mono_error_assert_ok (&error); /* FIXME report error */
9569 for (i = 0; i < len; ++i) {
9570 pos = decode_int (p, &p, end);
9572 if (pos < 0) {
9573 pos = - pos - 1;
9575 DEBUG_PRINTF (4, "[dbg] send arg %d.\n", pos);
9577 if (frame->ji->is_interp) {
9578 guint8 *addr;
9580 addr = mono_interp_frame_get_arg (frame->interp_frame, pos);
9582 buffer_add_value_full (buf, sig->params [pos], addr, frame->domain, FALSE, NULL);
9583 } else {
9584 g_assert (pos >= 0 && pos < jit->num_params);
9586 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
9588 } else {
9589 MonoDebugLocalsInfo *locals;
9591 locals = mono_debug_lookup_locals (frame->method);
9592 if (locals) {
9593 g_assert (pos < locals->num_locals);
9594 pos = locals->locals [pos].index;
9595 mono_debug_free_locals (locals);
9598 DEBUG_PRINTF (4, "[dbg] send local %d.\n", pos);
9600 if (frame->ji->is_interp) {
9601 guint8 *addr;
9603 addr = mono_interp_frame_get_local (frame->interp_frame, pos);
9605 buffer_add_value_full (buf, header->locals [pos], addr, frame->domain, FALSE, NULL);
9606 } else {
9607 g_assert (pos >= 0 && pos < jit->num_locals);
9609 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
9613 mono_metadata_free_mh (header);
9614 break;
9616 case CMD_STACK_FRAME_GET_THIS: {
9617 if (frame->method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE)
9618 return ERR_ABSENT_INFORMATION;
9619 if (frame->api_method->klass->valuetype) {
9620 if (!sig->hasthis) {
9621 MonoObject *p = NULL;
9622 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
9623 } else {
9624 if (frame->ji->is_interp) {
9625 guint8 *addr;
9627 addr = mono_interp_frame_get_this (frame->interp_frame);
9629 buffer_add_value_full (buf, &frame->actual_method->klass->this_arg, addr, frame->domain, FALSE, NULL);
9630 } else {
9631 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9634 } else {
9635 if (!sig->hasthis) {
9636 MonoObject *p = NULL;
9637 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
9638 } else {
9639 if (frame->ji->is_interp) {
9640 guint8 *addr;
9642 addr = mono_interp_frame_get_this (frame->interp_frame);
9644 buffer_add_value_full (buf, &frame->api_method->klass->byval_arg, addr, frame->domain, FALSE, NULL);
9645 } else {
9646 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
9650 break;
9652 case CMD_STACK_FRAME_SET_VALUES: {
9653 MonoError error;
9654 guint8 *val_buf;
9655 MonoType *t;
9656 MonoDebugVarInfo *var = NULL;
9657 gboolean is_arg = FALSE;
9659 len = decode_int (p, &p, end);
9660 header = mono_method_get_header_checked (frame->actual_method, &error);
9661 mono_error_assert_ok (&error); /* FIXME report error */
9663 for (i = 0; i < len; ++i) {
9664 pos = decode_int (p, &p, end);
9666 if (pos < 0) {
9667 pos = - pos - 1;
9669 g_assert (pos >= 0 && pos < jit->num_params);
9671 t = sig->params [pos];
9672 var = &jit->params [pos];
9673 is_arg = TRUE;
9674 } else {
9675 MonoDebugLocalsInfo *locals;
9677 locals = mono_debug_lookup_locals (frame->method);
9678 if (locals) {
9679 g_assert (pos < locals->num_locals);
9680 pos = locals->locals [pos].index;
9681 mono_debug_free_locals (locals);
9683 g_assert (pos >= 0 && pos < jit->num_locals);
9685 t = header->locals [pos];
9686 var = &jit->locals [pos];
9689 if (MONO_TYPE_IS_REFERENCE (t))
9690 val_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
9691 else
9692 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9693 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9694 if (err != ERR_NONE)
9695 return err;
9697 if (frame->ji->is_interp) {
9698 guint8 *addr;
9700 if (is_arg)
9701 addr = mono_interp_frame_get_arg (frame->interp_frame, pos);
9702 else
9703 addr = mono_interp_frame_get_local (frame->interp_frame, pos);
9704 set_interp_var (t, addr, val_buf);
9705 } else {
9706 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9709 mono_metadata_free_mh (header);
9710 break;
9712 case CMD_STACK_FRAME_GET_DOMAIN: {
9713 if (CHECK_PROTOCOL_VERSION (2, 38))
9714 buffer_add_domainid (buf, frame->domain);
9715 break;
9717 case CMD_STACK_FRAME_SET_THIS: {
9718 guint8 *val_buf;
9719 MonoType *t;
9720 MonoDebugVarInfo *var;
9722 t = &frame->actual_method->klass->byval_arg;
9723 /* Checked by the sender */
9724 g_assert (MONO_TYPE_ISSTRUCT (t));
9726 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
9727 err = decode_value (t, frame->domain, val_buf, p, &p, end);
9728 if (err != ERR_NONE)
9729 return err;
9731 if (frame->ji->is_interp) {
9732 guint8 *addr;
9734 addr = mono_interp_frame_get_this (frame->interp_frame);
9735 set_interp_var (&frame->actual_method->klass->this_arg, addr, val_buf);
9736 } else {
9737 var = jit->this_var;
9738 g_assert (var);
9740 set_var (&frame->actual_method->klass->this_arg, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9742 break;
9744 default:
9745 return ERR_NOT_IMPLEMENTED;
9748 return ERR_NONE;
9751 static ErrorCode
9752 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9754 MonoArray *arr;
9755 int objid, index, len, i, esize;
9756 ErrorCode err;
9757 gpointer elem;
9759 objid = decode_objid (p, &p, end);
9760 err = get_object (objid, (MonoObject**)&arr);
9761 if (err != ERR_NONE)
9762 return err;
9764 switch (command) {
9765 case CMD_ARRAY_REF_GET_LENGTH:
9766 buffer_add_int (buf, arr->obj.vtable->klass->rank);
9767 if (!arr->bounds) {
9768 buffer_add_int (buf, arr->max_length);
9769 buffer_add_int (buf, 0);
9770 } else {
9771 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
9772 buffer_add_int (buf, arr->bounds [i].length);
9773 buffer_add_int (buf, arr->bounds [i].lower_bound);
9776 break;
9777 case CMD_ARRAY_REF_GET_VALUES:
9778 index = decode_int (p, &p, end);
9779 len = decode_int (p, &p, end);
9781 g_assert (index >= 0 && len >= 0);
9782 // Reordered to avoid integer overflow
9783 g_assert (!(index > arr->max_length - len));
9785 esize = mono_array_element_size (arr->obj.vtable->klass);
9786 for (i = index; i < index + len; ++i) {
9787 elem = (gpointer*)((char*)arr->vector + (i * esize));
9788 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
9790 break;
9791 case CMD_ARRAY_REF_SET_VALUES:
9792 index = decode_int (p, &p, end);
9793 len = decode_int (p, &p, end);
9795 g_assert (index >= 0 && len >= 0);
9796 // Reordered to avoid integer overflow
9797 g_assert (!(index > arr->max_length - len));
9799 esize = mono_array_element_size (arr->obj.vtable->klass);
9800 for (i = index; i < index + len; ++i) {
9801 elem = (gpointer*)((char*)arr->vector + (i * esize));
9803 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, (guint8 *)elem, p, &p, end);
9805 break;
9806 default:
9807 return ERR_NOT_IMPLEMENTED;
9810 return ERR_NONE;
9813 static ErrorCode
9814 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9816 int objid;
9817 ErrorCode err;
9818 MonoString *str;
9819 char *s;
9820 int i, index, length;
9821 gunichar2 *c;
9822 gboolean use_utf16 = FALSE;
9824 objid = decode_objid (p, &p, end);
9825 err = get_object (objid, (MonoObject**)&str);
9826 if (err != ERR_NONE)
9827 return err;
9829 switch (command) {
9830 case CMD_STRING_REF_GET_VALUE:
9831 if (CHECK_PROTOCOL_VERSION (2, 41)) {
9832 for (i = 0; i < mono_string_length (str); ++i)
9833 if (mono_string_chars (str)[i] == 0)
9834 use_utf16 = TRUE;
9835 buffer_add_byte (buf, use_utf16 ? 1 : 0);
9837 if (use_utf16) {
9838 buffer_add_int (buf, mono_string_length (str) * 2);
9839 buffer_add_data (buf, (guint8*)mono_string_chars (str), mono_string_length (str) * 2);
9840 } else {
9841 MonoError error;
9842 s = mono_string_to_utf8_checked (str, &error);
9843 mono_error_assert_ok (&error);
9844 buffer_add_string (buf, s);
9845 g_free (s);
9847 break;
9848 case CMD_STRING_REF_GET_LENGTH:
9849 buffer_add_long (buf, mono_string_length (str));
9850 break;
9851 case CMD_STRING_REF_GET_CHARS:
9852 index = decode_long (p, &p, end);
9853 length = decode_long (p, &p, end);
9854 if (index > mono_string_length (str) - length)
9855 return ERR_INVALID_ARGUMENT;
9856 c = mono_string_chars (str) + index;
9857 for (i = 0; i < length; ++i)
9858 buffer_add_short (buf, c [i]);
9859 break;
9860 default:
9861 return ERR_NOT_IMPLEMENTED;
9864 return ERR_NONE;
9867 static ErrorCode
9868 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9870 MonoError error;
9871 int objid;
9872 ErrorCode err;
9873 MonoObject *obj;
9874 int len, i;
9875 MonoClassField *f;
9876 MonoClass *k;
9877 gboolean found;
9879 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9880 objid = decode_objid (p, &p, end);
9881 err = get_object (objid, &obj);
9882 if (err != ERR_NONE)
9883 buffer_add_int (buf, 1);
9884 else
9885 buffer_add_int (buf, 0);
9886 return ERR_NONE;
9889 objid = decode_objid (p, &p, end);
9890 err = get_object (objid, &obj);
9891 if (err != ERR_NONE)
9892 return err;
9894 MonoClass *obj_type;
9895 gboolean remote_obj = FALSE;
9897 obj_type = obj->vtable->klass;
9898 if (mono_class_is_transparent_proxy (obj_type)) {
9899 obj_type = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
9900 remote_obj = TRUE;
9903 g_assert (obj_type);
9905 switch (command) {
9906 case CMD_OBJECT_REF_GET_TYPE:
9907 /* This handles transparent proxies too */
9908 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9909 break;
9910 case CMD_OBJECT_REF_GET_VALUES:
9911 len = decode_int (p, &p, end);
9913 for (i = 0; i < len; ++i) {
9914 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9915 if (err != ERR_NONE)
9916 return err;
9918 /* Check that the field belongs to the object */
9919 found = FALSE;
9920 for (k = obj_type; k; k = k->parent) {
9921 if (k == f->parent) {
9922 found = TRUE;
9923 break;
9926 if (!found)
9927 return ERR_INVALID_FIELDID;
9929 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9930 guint8 *val;
9931 MonoVTable *vtable;
9933 if (mono_class_field_is_special_static (f))
9934 return ERR_INVALID_FIELDID;
9936 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9937 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9938 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9939 mono_field_static_get_value_checked (vtable, f, val, &error);
9940 if (!is_ok (&error)) {
9941 mono_error_cleanup (&error); /* FIXME report the error */
9942 return ERR_INVALID_OBJECT;
9944 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9945 g_free (val);
9946 } else {
9947 guint8 *field_value = NULL;
9949 if (remote_obj) {
9950 #ifndef DISABLE_REMOTING
9951 void *field_storage = NULL;
9952 field_value = mono_load_remote_field_checked(obj, obj_type, f, &field_storage, &error);
9953 if (!is_ok (&error)) {
9954 mono_error_cleanup (&error); /* FIXME report the error */
9955 return ERR_INVALID_OBJECT;
9957 #else
9958 g_assert_not_reached ();
9959 #endif
9960 } else
9961 field_value = (guint8*)obj + f->offset;
9963 buffer_add_value (buf, f->type, field_value, obj->vtable->domain);
9966 break;
9967 case CMD_OBJECT_REF_SET_VALUES:
9968 len = decode_int (p, &p, end);
9970 for (i = 0; i < len; ++i) {
9971 f = decode_fieldid (p, &p, end, NULL, &err);
9972 if (err != ERR_NONE)
9973 return err;
9975 /* Check that the field belongs to the object */
9976 found = FALSE;
9977 for (k = obj_type; k; k = k->parent) {
9978 if (k == f->parent) {
9979 found = TRUE;
9980 break;
9983 if (!found)
9984 return ERR_INVALID_FIELDID;
9986 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9987 guint8 *val;
9988 MonoVTable *vtable;
9990 if (mono_class_field_is_special_static (f))
9991 return ERR_INVALID_FIELDID;
9993 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9994 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9996 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9997 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
9998 if (err != ERR_NONE) {
9999 g_free (val);
10000 return err;
10002 mono_field_static_set_value (vtable, f, val);
10003 g_free (val);
10004 } else {
10005 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
10006 if (err != ERR_NONE)
10007 return err;
10010 break;
10011 case CMD_OBJECT_REF_GET_ADDRESS:
10012 buffer_add_long (buf, (gssize)obj);
10013 break;
10014 case CMD_OBJECT_REF_GET_DOMAIN:
10015 buffer_add_domainid (buf, obj->vtable->domain);
10016 break;
10017 case CMD_OBJECT_REF_GET_INFO:
10018 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
10019 buffer_add_domainid (buf, obj->vtable->domain);
10020 break;
10021 default:
10022 return ERR_NOT_IMPLEMENTED;
10025 return ERR_NONE;
10028 static const char*
10029 command_set_to_string (CommandSet command_set)
10031 switch (command_set) {
10032 case CMD_SET_VM:
10033 return "VM";
10034 case CMD_SET_OBJECT_REF:
10035 return "OBJECT_REF";
10036 case CMD_SET_STRING_REF:
10037 return "STRING_REF";
10038 case CMD_SET_THREAD:
10039 return "THREAD";
10040 case CMD_SET_ARRAY_REF:
10041 return "ARRAY_REF";
10042 case CMD_SET_EVENT_REQUEST:
10043 return "EVENT_REQUEST";
10044 case CMD_SET_STACK_FRAME:
10045 return "STACK_FRAME";
10046 case CMD_SET_APPDOMAIN:
10047 return "APPDOMAIN";
10048 case CMD_SET_ASSEMBLY:
10049 return "ASSEMBLY";
10050 case CMD_SET_METHOD:
10051 return "METHOD";
10052 case CMD_SET_TYPE:
10053 return "TYPE";
10054 case CMD_SET_MODULE:
10055 return "MODULE";
10056 case CMD_SET_FIELD:
10057 return "FIELD";
10058 case CMD_SET_EVENT:
10059 return "EVENT";
10060 default:
10061 return "";
10065 static const char* vm_cmds_str [] = {
10066 "VERSION",
10067 "ALL_THREADS",
10068 "SUSPEND",
10069 "RESUME",
10070 "EXIT",
10071 "DISPOSE",
10072 "INVOKE_METHOD",
10073 "SET_PROTOCOL_VERSION",
10074 "ABORT_INVOKE",
10075 "SET_KEEPALIVE"
10076 "GET_TYPES_FOR_SOURCE_FILE",
10077 "GET_TYPES",
10078 "INVOKE_METHODS"
10081 static const char* thread_cmds_str[] = {
10082 "GET_FRAME_INFO",
10083 "GET_NAME",
10084 "GET_STATE",
10085 "GET_INFO",
10086 "GET_ID",
10087 "GET_TID",
10088 "SET_IP"
10091 static const char* event_cmds_str[] = {
10092 "REQUEST_SET",
10093 "REQUEST_CLEAR",
10094 "REQUEST_CLEAR_ALL_BREAKPOINTS"
10097 static const char* appdomain_cmds_str[] = {
10098 "GET_ROOT_DOMAIN",
10099 "GET_FRIENDLY_NAME",
10100 "GET_ASSEMBLIES",
10101 "GET_ENTRY_ASSEMBLY",
10102 "CREATE_STRING",
10103 "GET_CORLIB",
10104 "CREATE_BOXED_VALUE"
10107 static const char* assembly_cmds_str[] = {
10108 "GET_LOCATION",
10109 "GET_ENTRY_POINT",
10110 "GET_MANIFEST_MODULE",
10111 "GET_OBJECT",
10112 "GET_TYPE",
10113 "GET_NAME",
10114 "GET_DOMAIN"
10117 static const char* module_cmds_str[] = {
10118 "GET_INFO",
10121 static const char* field_cmds_str[] = {
10122 "GET_INFO",
10125 static const char* method_cmds_str[] = {
10126 "GET_NAME",
10127 "GET_DECLARING_TYPE",
10128 "GET_DEBUG_INFO",
10129 "GET_PARAM_INFO",
10130 "GET_LOCALS_INFO",
10131 "GET_INFO",
10132 "GET_BODY",
10133 "RESOLVE_TOKEN",
10134 "GET_CATTRS ",
10135 "MAKE_GENERIC_METHOD"
10138 static const char* type_cmds_str[] = {
10139 "GET_INFO",
10140 "GET_METHODS",
10141 "GET_FIELDS",
10142 "GET_VALUES",
10143 "GET_OBJECT",
10144 "GET_SOURCE_FILES",
10145 "SET_VALUES",
10146 "IS_ASSIGNABLE_FROM",
10147 "GET_PROPERTIES ",
10148 "GET_CATTRS",
10149 "GET_FIELD_CATTRS",
10150 "GET_PROPERTY_CATTRS",
10151 "GET_SOURCE_FILES_2",
10152 "GET_VALUES_2",
10153 "GET_METHODS_BY_NAME_FLAGS",
10154 "GET_INTERFACES",
10155 "GET_INTERFACE_MAP",
10156 "IS_INITIALIZED"
10159 static const char* stack_frame_cmds_str[] = {
10160 "GET_VALUES",
10161 "GET_THIS",
10162 "SET_VALUES",
10163 "GET_DOMAIN",
10164 "SET_THIS"
10167 static const char* array_cmds_str[] = {
10168 "GET_LENGTH",
10169 "GET_VALUES",
10170 "SET_VALUES",
10173 static const char* string_cmds_str[] = {
10174 "GET_VALUE",
10175 "GET_LENGTH",
10176 "GET_CHARS"
10179 static const char* object_cmds_str[] = {
10180 "GET_TYPE",
10181 "GET_VALUES",
10182 "IS_COLLECTED",
10183 "GET_ADDRESS",
10184 "GET_DOMAIN",
10185 "SET_VALUES",
10186 "GET_INFO",
10189 static const char*
10190 cmd_to_string (CommandSet set, int command)
10192 const char **cmds;
10193 int cmds_len = 0;
10195 switch (set) {
10196 case CMD_SET_VM:
10197 cmds = vm_cmds_str;
10198 cmds_len = G_N_ELEMENTS (vm_cmds_str);
10199 break;
10200 case CMD_SET_OBJECT_REF:
10201 cmds = object_cmds_str;
10202 cmds_len = G_N_ELEMENTS (object_cmds_str);
10203 break;
10204 case CMD_SET_STRING_REF:
10205 cmds = string_cmds_str;
10206 cmds_len = G_N_ELEMENTS (string_cmds_str);
10207 break;
10208 case CMD_SET_THREAD:
10209 cmds = thread_cmds_str;
10210 cmds_len = G_N_ELEMENTS (thread_cmds_str);
10211 break;
10212 case CMD_SET_ARRAY_REF:
10213 cmds = array_cmds_str;
10214 cmds_len = G_N_ELEMENTS (array_cmds_str);
10215 break;
10216 case CMD_SET_EVENT_REQUEST:
10217 cmds = event_cmds_str;
10218 cmds_len = G_N_ELEMENTS (event_cmds_str);
10219 break;
10220 case CMD_SET_STACK_FRAME:
10221 cmds = stack_frame_cmds_str;
10222 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
10223 break;
10224 case CMD_SET_APPDOMAIN:
10225 cmds = appdomain_cmds_str;
10226 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
10227 break;
10228 case CMD_SET_ASSEMBLY:
10229 cmds = assembly_cmds_str;
10230 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
10231 break;
10232 case CMD_SET_METHOD:
10233 cmds = method_cmds_str;
10234 cmds_len = G_N_ELEMENTS (method_cmds_str);
10235 break;
10236 case CMD_SET_TYPE:
10237 cmds = type_cmds_str;
10238 cmds_len = G_N_ELEMENTS (type_cmds_str);
10239 break;
10240 case CMD_SET_MODULE:
10241 cmds = module_cmds_str;
10242 cmds_len = G_N_ELEMENTS (module_cmds_str);
10243 break;
10244 case CMD_SET_FIELD:
10245 cmds = field_cmds_str;
10246 cmds_len = G_N_ELEMENTS (field_cmds_str);
10247 break;
10248 case CMD_SET_EVENT:
10249 cmds = event_cmds_str;
10250 cmds_len = G_N_ELEMENTS (event_cmds_str);
10251 break;
10252 default:
10253 return NULL;
10255 if (command > 0 && command <= cmds_len)
10256 return cmds [command - 1];
10257 else
10258 return NULL;
10261 static gboolean
10262 wait_for_attach (void)
10264 #ifndef DISABLE_SOCKET_TRANSPORT
10265 if (listen_fd == -1) {
10266 DEBUG_PRINTF (1, "[dbg] Invalid listening socket\n");
10267 return FALSE;
10270 /* Block and wait for client connection */
10271 conn_fd = socket_transport_accept (listen_fd);
10273 DEBUG_PRINTF (1, "Accepted connection on %d\n", conn_fd);
10274 if (conn_fd == -1) {
10275 DEBUG_PRINTF (1, "[dbg] Bad client connection\n");
10276 return FALSE;
10278 #else
10279 g_assert_not_reached ();
10280 #endif
10282 /* Handshake */
10283 disconnected = !transport_handshake ();
10284 if (disconnected) {
10285 DEBUG_PRINTF (1, "Transport handshake failed!\n");
10286 return FALSE;
10289 return TRUE;
10293 * debugger_thread:
10295 * This thread handles communication with the debugger client using a JDWP
10296 * like protocol.
10298 static gsize WINAPI
10299 debugger_thread (void *arg)
10301 MonoError error;
10302 int res, len, id, flags, command = 0;
10303 CommandSet command_set = (CommandSet)0;
10304 guint8 header [HEADER_LENGTH];
10305 guint8 *data, *p, *end;
10306 Buffer buf;
10307 ErrorCode err;
10308 gboolean no_reply;
10309 gboolean attach_failed = FALSE;
10311 DEBUG_PRINTF (1, "[dbg] Agent thread started, pid=%p\n", (gpointer) (gsize) mono_native_thread_id_get ());
10313 debugger_thread_id = mono_native_thread_id_get ();
10315 MonoInternalThread *internal = mono_thread_internal_current ();
10316 MonoString *str = mono_string_new_checked (mono_domain_get (), "Debugger agent", &error);
10317 mono_error_assert_ok (&error);
10318 mono_thread_set_name_internal (internal, str, TRUE, FALSE, &error);
10319 mono_error_assert_ok (&error);
10321 internal->state |= ThreadState_Background;
10322 internal->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
10324 if (agent_config.defer) {
10325 if (!wait_for_attach ()) {
10326 DEBUG_PRINTF (1, "[dbg] Can't attach, aborting debugger thread.\n");
10327 attach_failed = TRUE; // Don't abort process when we can't listen
10328 } else {
10329 mono_set_is_debugger_attached (TRUE);
10330 /* Send start event to client */
10331 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
10333 } else {
10334 mono_set_is_debugger_attached (TRUE);
10337 while (!attach_failed) {
10338 res = transport_recv (header, HEADER_LENGTH);
10340 /* This will break if the socket is closed during shutdown too */
10341 if (res != HEADER_LENGTH) {
10342 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH);
10343 break;
10346 p = header;
10347 end = header + HEADER_LENGTH;
10349 len = decode_int (p, &p, end);
10350 id = decode_int (p, &p, end);
10351 flags = decode_byte (p, &p, end);
10352 command_set = (CommandSet)decode_byte (p, &p, end);
10353 command = decode_byte (p, &p, end);
10355 g_assert (flags == 0);
10357 if (log_level) {
10358 const char *cmd_str;
10359 char cmd_num [256];
10361 cmd_str = cmd_to_string (command_set, command);
10362 if (!cmd_str) {
10363 sprintf (cmd_num, "%d", command);
10364 cmd_str = cmd_num;
10367 DEBUG_PRINTF (1, "[dbg] Command %s(%s) [%d][at=%lx].\n", command_set_to_string (command_set), cmd_str, id, (long)mono_100ns_ticks () / 10000);
10370 data = (guint8 *)g_malloc (len - HEADER_LENGTH);
10371 if (len - HEADER_LENGTH > 0)
10373 res = transport_recv (data, len - HEADER_LENGTH);
10374 if (res != len - HEADER_LENGTH) {
10375 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH);
10376 break;
10380 p = data;
10381 end = data + (len - HEADER_LENGTH);
10383 buffer_init (&buf, 128);
10385 err = ERR_NONE;
10386 no_reply = FALSE;
10388 /* Process the request */
10389 switch (command_set) {
10390 case CMD_SET_VM:
10391 err = vm_commands (command, id, p, end, &buf);
10392 if (err == ERR_NONE && command == CMD_VM_INVOKE_METHOD)
10393 /* Sent after the invoke is complete */
10394 no_reply = TRUE;
10395 break;
10396 case CMD_SET_EVENT_REQUEST:
10397 err = event_commands (command, p, end, &buf);
10398 break;
10399 case CMD_SET_APPDOMAIN:
10400 err = domain_commands (command, p, end, &buf);
10401 break;
10402 case CMD_SET_ASSEMBLY:
10403 err = assembly_commands (command, p, end, &buf);
10404 break;
10405 case CMD_SET_MODULE:
10406 err = module_commands (command, p, end, &buf);
10407 break;
10408 case CMD_SET_FIELD:
10409 err = field_commands (command, p, end, &buf);
10410 break;
10411 case CMD_SET_TYPE:
10412 err = type_commands (command, p, end, &buf);
10413 break;
10414 case CMD_SET_METHOD:
10415 err = method_commands (command, p, end, &buf);
10416 break;
10417 case CMD_SET_THREAD:
10418 err = thread_commands (command, p, end, &buf);
10419 break;
10420 case CMD_SET_STACK_FRAME:
10421 err = frame_commands (command, p, end, &buf);
10422 break;
10423 case CMD_SET_ARRAY_REF:
10424 err = array_commands (command, p, end, &buf);
10425 break;
10426 case CMD_SET_STRING_REF:
10427 err = string_commands (command, p, end, &buf);
10428 break;
10429 case CMD_SET_OBJECT_REF:
10430 err = object_commands (command, p, end, &buf);
10431 break;
10432 default:
10433 err = ERR_NOT_IMPLEMENTED;
10436 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
10437 buffer_replies = TRUE;
10440 if (!no_reply) {
10441 if (buffer_replies) {
10442 buffer_reply_packet (id, err, &buf);
10443 } else {
10444 send_reply_packet (id, err, &buf);
10445 //DEBUG_PRINTF (1, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000);
10449 if (err == ERR_NONE && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
10450 send_buffered_reply_packets ();
10451 buffer_replies = FALSE;
10454 g_free (data);
10455 buffer_free (&buf);
10457 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
10458 break;
10461 mono_set_is_debugger_attached (FALSE);
10463 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
10464 debugger_thread_exited = TRUE;
10465 mono_coop_cond_signal (&debugger_thread_exited_cond);
10466 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
10468 DEBUG_PRINTF (1, "[dbg] Debugger thread exited.\n");
10470 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
10471 DEBUG_PRINTF (2, "[dbg] Detached - restarting clean debugger thread.\n");
10472 start_debugger_thread ();
10475 return 0;
10478 #else /* DISABLE_DEBUGGER_AGENT */
10480 void
10481 mono_debugger_agent_parse_options (char *options)
10483 g_error ("This runtime is configured with the debugger agent disabled.");
10486 void
10487 mono_debugger_agent_init (void)
10491 void
10492 mono_debugger_agent_breakpoint_hit (void *sigctx)
10496 void
10497 mono_debugger_agent_single_step_event (void *sigctx)
10501 void
10502 mono_debugger_agent_free_domain_info (MonoDomain *domain)
10506 void
10507 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
10508 MonoContext *catch_ctx)
10512 void
10513 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
10517 void
10518 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
10522 void
10523 mono_debugger_agent_user_break (void)
10525 G_BREAKPOINT ();
10528 void
10529 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
10533 gboolean
10534 mono_debugger_agent_debug_log_is_enabled (void)
10536 return FALSE;
10539 void
10540 mono_debugger_agent_unhandled_exception (MonoException *exc)
10542 g_assert_not_reached ();
10545 void
10546 debugger_agent_single_step_from_context (MonoContext *ctx)
10548 g_assert_not_reached ();
10551 void
10552 debugger_agent_breakpoint_from_context (MonoContext *ctx)
10554 g_assert_not_reached ();
10557 #endif