[amd64] Remove the callee saved registers from MonoLMF, save/restore them normally...
[mono-project.git] / mono / mini / debugger-agent.c
blobd9032db69a637e93dac7f3e27af43a8318df4b5d
1 /*
2 * debugger-agent.c: Soft Debugger back-end module
4 * Author:
5 * Zoltan Varga (vargaz@gmail.com)
7 * Copyright 2009-2010 Novell, Inc.
8 * Copyright 2011 Xamarin Inc.
9 */
11 #include <config.h>
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #ifdef HAVE_SYS_TYPES_H
16 #include <sys/types.h>
17 #endif
18 #ifdef HAVE_SYS_SELECT_H
19 #include <sys/select.h>
20 #endif
21 #ifdef HAVE_SYS_SOCKET_H
22 #include <sys/socket.h>
23 #endif
24 #ifdef HAVE_NETINET_TCP_H
25 #include <netinet/tcp.h>
26 #endif
27 #ifdef HAVE_NETINET_IN_H
28 #include <netinet/in.h>
29 #endif
30 #ifdef HAVE_NETDB_H
31 #include <netdb.h>
32 #endif
33 #ifdef HAVE_UNISTD_H
34 #include <unistd.h>
35 #endif
36 #include <errno.h>
37 #include <glib.h>
39 #ifdef HAVE_PTHREAD_H
40 #include <pthread.h>
41 #endif
43 #ifdef HAVE_UCONTEXT_H
44 #include <ucontext.h>
45 #endif
47 #ifdef HOST_WIN32
48 #ifdef _MSC_VER
49 #include <winsock2.h>
50 #include <process.h>
51 #endif
52 #include <ws2tcpip.h>
53 #ifdef __GNUC__
54 /* cygwin's headers do not seem to define these */
55 void WSAAPI freeaddrinfo (struct addrinfo*);
56 int WSAAPI getaddrinfo (const char*,const char*,const struct addrinfo*,
57 struct addrinfo**);
58 int WSAAPI getnameinfo(const struct sockaddr*,socklen_t,char*,DWORD,
59 char*,DWORD,int);
60 #endif
61 #endif
63 #ifdef PLATFORM_ANDROID
64 #include <linux/in.h>
65 #include <linux/tcp.h>
66 #include <sys/endian.h>
67 #endif
69 #include <mono/metadata/mono-debug.h>
70 #include <mono/metadata/mono-debug-debugger.h>
71 #include <mono/metadata/debug-mono-symfile.h>
72 #include <mono/metadata/gc-internal.h>
73 #include <mono/metadata/environment.h>
74 #include <mono/metadata/threads-types.h>
75 #include <mono/metadata/socket-io.h>
76 #include <mono/metadata/assembly.h>
77 #include <mono/metadata/runtime.h>
78 #include <mono/metadata/threadpool.h>
79 #include <mono/metadata/verify-internals.h>
80 #include <mono/utils/mono-semaphore.h>
81 #include <mono/utils/mono-error-internals.h>
82 #include <mono/utils/mono-stack-unwinding.h>
83 #include <mono/utils/mono-time.h>
84 #include <mono/utils/mono-threads.h>
85 #include "debugger-agent.h"
86 #include "mini.h"
89 On iOS we can't use System.Environment.Exit () as it will do the wrong
90 shutdown sequence.
92 #if !defined (TARGET_IOS)
93 #define TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
94 #endif
97 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
98 #define DISABLE_DEBUGGER_AGENT 1
99 #endif
101 #ifdef DISABLE_SOFT_DEBUG
102 #define DISABLE_DEBUGGER_AGENT 1
103 #endif
105 #ifndef DISABLE_DEBUGGER_AGENT
107 #include <mono/utils/mono-mutex.h>
109 /* Definitions to make backporting to 2.6 easier */
110 //#define MonoInternalThread MonoThread
111 //#define mono_thread_internal_current mono_thread_current
112 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
114 typedef struct {
115 gboolean enabled;
116 char *transport;
117 char *address;
118 int log_level;
119 char *log_file;
120 gboolean suspend;
121 gboolean server;
122 gboolean onuncaught;
123 GSList *onthrow;
124 int timeout;
125 char *launch;
126 gboolean embedding;
127 gboolean defer;
128 int keepalive;
129 gboolean setpgid;
130 } AgentConfig;
132 typedef struct
134 int id;
135 guint32 il_offset, native_offset;
136 MonoDomain *domain;
137 MonoMethod *method;
139 * If method is gshared, this is the actual instance, otherwise this is equal to
140 * method.
142 MonoMethod *actual_method;
144 * This is the method which is visible to debugger clients. Same as method,
145 * except for native-to-managed wrappers.
147 MonoMethod *api_method;
148 MonoContext ctx;
149 MonoDebugMethodJitInfo *jit;
150 MonoJitInfo *ji;
151 int flags;
152 mgreg_t *reg_locations [MONO_MAX_IREGS];
154 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
155 * the frame can become invalid.
157 gboolean has_ctx;
158 } StackFrame;
160 typedef struct _InvokeData InvokeData;
162 struct _InvokeData
164 int id;
165 int flags;
166 guint8 *p;
167 guint8 *endp;
168 /* This is the context which needs to be restored after the invoke */
169 MonoContext ctx;
170 gboolean has_ctx;
172 * If this is set, invoke this method with the arguments given by ARGS.
174 MonoMethod *method;
175 gpointer *args;
176 guint32 suspend_count;
177 int nmethods;
179 InvokeData *last_invoke;
182 typedef struct {
183 MonoThreadUnwindState context;
185 /* This is computed on demand when it is requested using the wire protocol */
186 /* It is freed up when the thread is resumed */
187 int frame_count;
188 StackFrame **frames;
190 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
191 * re-compute it.
193 gboolean frames_up_to_date;
195 * Points to data about a pending invoke which needs to be executed after the thread
196 * resumes.
198 InvokeData *pending_invoke;
200 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
201 * native code.
203 gboolean suspended;
205 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
206 * within a finite amount of time.
208 gboolean suspending;
210 * Set to TRUE if this thread is suspended in suspend_current ().
212 gboolean really_suspended;
213 /* Used to pass the context to the breakpoint/single step handler */
214 MonoContext handler_ctx;
215 /* Whenever thread_stop () was called for this thread */
216 gboolean terminated;
218 /* Number of thread interruptions not yet processed */
219 gint32 interrupt_count;
221 /* Whenever to disable breakpoints (used during invokes) */
222 gboolean disable_breakpoints;
225 * Number of times this thread has been resumed using resume_thread ().
227 guint32 resume_count;
229 MonoInternalThread *thread;
232 * Information about the frame which transitioned to native code for running
233 * threads.
235 StackFrameInfo async_last_frame;
238 * The context where the stack walk can be started for running threads.
240 MonoThreadUnwindState async_state;
243 * The context used for filter clauses
245 MonoThreadUnwindState filter_state;
248 * The callee address of the last mono_runtime_invoke call
250 gpointer invoke_addr;
252 gboolean abort_requested;
255 * The current mono_runtime_invoke invocation.
257 InvokeData *invoke;
260 * The context where single stepping should resume while the thread is suspended because
261 * of an EXCEPTION event.
263 MonoThreadUnwindState catch_state;
266 * The context which needs to be restored after handling a single step/breakpoint
267 * event. This is the same as the ctx at step/breakpoint site, but includes changes
268 * to caller saved registers done by set_var ().
270 MonoContext restore_ctx;
272 /* The currently unloading appdomain */
273 MonoDomain *domain_unloading;
274 } DebuggerTlsData;
276 typedef struct {
277 const char *name;
278 void (*connect) (const char *address);
279 void (*close1) (void);
280 void (*close2) (void);
281 gboolean (*send) (void *buf, int len);
282 int (*recv) (void *buf, int len);
283 } DebuggerTransport;
286 * Wire Protocol definitions
289 #define HEADER_LENGTH 11
291 #define MAJOR_VERSION 2
292 #define MINOR_VERSION 34
294 typedef enum {
295 CMD_SET_VM = 1,
296 CMD_SET_OBJECT_REF = 9,
297 CMD_SET_STRING_REF = 10,
298 CMD_SET_THREAD = 11,
299 CMD_SET_ARRAY_REF = 13,
300 CMD_SET_EVENT_REQUEST = 15,
301 CMD_SET_STACK_FRAME = 16,
302 CMD_SET_APPDOMAIN = 20,
303 CMD_SET_ASSEMBLY = 21,
304 CMD_SET_METHOD = 22,
305 CMD_SET_TYPE = 23,
306 CMD_SET_MODULE = 24,
307 CMD_SET_FIELD = 25,
308 CMD_SET_EVENT = 64
309 } CommandSet;
311 typedef enum {
312 EVENT_KIND_VM_START = 0,
313 EVENT_KIND_VM_DEATH = 1,
314 EVENT_KIND_THREAD_START = 2,
315 EVENT_KIND_THREAD_DEATH = 3,
316 EVENT_KIND_APPDOMAIN_CREATE = 4,
317 EVENT_KIND_APPDOMAIN_UNLOAD = 5,
318 EVENT_KIND_METHOD_ENTRY = 6,
319 EVENT_KIND_METHOD_EXIT = 7,
320 EVENT_KIND_ASSEMBLY_LOAD = 8,
321 EVENT_KIND_ASSEMBLY_UNLOAD = 9,
322 EVENT_KIND_BREAKPOINT = 10,
323 EVENT_KIND_STEP = 11,
324 EVENT_KIND_TYPE_LOAD = 12,
325 EVENT_KIND_EXCEPTION = 13,
326 EVENT_KIND_KEEPALIVE = 14,
327 EVENT_KIND_USER_BREAK = 15,
328 EVENT_KIND_USER_LOG = 16
329 } EventKind;
331 typedef enum {
332 SUSPEND_POLICY_NONE = 0,
333 SUSPEND_POLICY_EVENT_THREAD = 1,
334 SUSPEND_POLICY_ALL = 2
335 } SuspendPolicy;
337 typedef enum {
338 ERR_NONE = 0,
339 ERR_INVALID_OBJECT = 20,
340 ERR_INVALID_FIELDID = 25,
341 ERR_INVALID_FRAMEID = 30,
342 ERR_NOT_IMPLEMENTED = 100,
343 ERR_NOT_SUSPENDED = 101,
344 ERR_INVALID_ARGUMENT = 102,
345 ERR_UNLOADED = 103,
346 ERR_NO_INVOCATION = 104,
347 ERR_ABSENT_INFORMATION = 105,
348 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
349 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
350 } ErrorCode;
352 typedef enum {
353 MOD_KIND_COUNT = 1,
354 MOD_KIND_THREAD_ONLY = 3,
355 MOD_KIND_LOCATION_ONLY = 7,
356 MOD_KIND_EXCEPTION_ONLY = 8,
357 MOD_KIND_STEP = 10,
358 MOD_KIND_ASSEMBLY_ONLY = 11,
359 MOD_KIND_SOURCE_FILE_ONLY = 12,
360 MOD_KIND_TYPE_NAME_ONLY = 13,
361 MOD_KIND_NONE = 14
362 } ModifierKind;
364 typedef enum {
365 STEP_DEPTH_INTO = 0,
366 STEP_DEPTH_OVER = 1,
367 STEP_DEPTH_OUT = 2
368 } StepDepth;
370 typedef enum {
371 STEP_SIZE_MIN = 0,
372 STEP_SIZE_LINE = 1
373 } StepSize;
375 typedef enum {
376 STEP_FILTER_NONE = 0,
377 STEP_FILTER_STATIC_CTOR = 1,
378 STEP_FILTER_DEBUGGER_HIDDEN = 2,
379 STEP_FILTER_DEBUGGER_STEP_THROUGH = 4,
380 STEP_FILTER_DEBUGGER_NON_USER_CODE = 8
381 } StepFilter;
383 typedef enum {
384 TOKEN_TYPE_STRING = 0,
385 TOKEN_TYPE_TYPE = 1,
386 TOKEN_TYPE_FIELD = 2,
387 TOKEN_TYPE_METHOD = 3,
388 TOKEN_TYPE_UNKNOWN = 4
389 } DebuggerTokenType;
391 typedef enum {
392 VALUE_TYPE_ID_NULL = 0xf0,
393 VALUE_TYPE_ID_TYPE = 0xf1,
394 VALUE_TYPE_ID_PARENT_VTYPE = 0xf2
395 } ValueTypeId;
397 typedef enum {
398 FRAME_FLAG_DEBUGGER_INVOKE = 1,
399 FRAME_FLAG_NATIVE_TRANSITION = 2
400 } StackFrameFlags;
402 typedef enum {
403 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
404 INVOKE_FLAG_SINGLE_THREADED = 2
405 } InvokeFlags;
407 typedef enum {
408 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
409 } BindingFlagsExtensions;
411 typedef enum {
412 CMD_VM_VERSION = 1,
413 CMD_VM_ALL_THREADS = 2,
414 CMD_VM_SUSPEND = 3,
415 CMD_VM_RESUME = 4,
416 CMD_VM_EXIT = 5,
417 CMD_VM_DISPOSE = 6,
418 CMD_VM_INVOKE_METHOD = 7,
419 CMD_VM_SET_PROTOCOL_VERSION = 8,
420 CMD_VM_ABORT_INVOKE = 9,
421 CMD_VM_SET_KEEPALIVE = 10,
422 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
423 CMD_VM_GET_TYPES = 12,
424 CMD_VM_INVOKE_METHODS = 13,
425 CMD_VM_START_BUFFERING = 14,
426 CMD_VM_STOP_BUFFERING = 15
427 } CmdVM;
429 typedef enum {
430 CMD_THREAD_GET_FRAME_INFO = 1,
431 CMD_THREAD_GET_NAME = 2,
432 CMD_THREAD_GET_STATE = 3,
433 CMD_THREAD_GET_INFO = 4,
434 CMD_THREAD_GET_ID = 5,
435 CMD_THREAD_GET_TID = 6,
436 CMD_THREAD_SET_IP = 7
437 } CmdThread;
439 typedef enum {
440 CMD_EVENT_REQUEST_SET = 1,
441 CMD_EVENT_REQUEST_CLEAR = 2,
442 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
443 } CmdEvent;
445 typedef enum {
446 CMD_COMPOSITE = 100
447 } CmdComposite;
449 typedef enum {
450 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
451 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
452 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
453 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
454 CMD_APPDOMAIN_CREATE_STRING = 5,
455 CMD_APPDOMAIN_GET_CORLIB = 6,
456 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7
457 } CmdAppDomain;
459 typedef enum {
460 CMD_ASSEMBLY_GET_LOCATION = 1,
461 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
462 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
463 CMD_ASSEMBLY_GET_OBJECT = 4,
464 CMD_ASSEMBLY_GET_TYPE = 5,
465 CMD_ASSEMBLY_GET_NAME = 6
466 } CmdAssembly;
468 typedef enum {
469 CMD_MODULE_GET_INFO = 1,
470 } CmdModule;
472 typedef enum {
473 CMD_FIELD_GET_INFO = 1,
474 } CmdField;
476 typedef enum {
477 CMD_METHOD_GET_NAME = 1,
478 CMD_METHOD_GET_DECLARING_TYPE = 2,
479 CMD_METHOD_GET_DEBUG_INFO = 3,
480 CMD_METHOD_GET_PARAM_INFO = 4,
481 CMD_METHOD_GET_LOCALS_INFO = 5,
482 CMD_METHOD_GET_INFO = 6,
483 CMD_METHOD_GET_BODY = 7,
484 CMD_METHOD_RESOLVE_TOKEN = 8,
485 CMD_METHOD_GET_CATTRS = 9,
486 CMD_METHOD_MAKE_GENERIC_METHOD = 10
487 } CmdMethod;
489 typedef enum {
490 CMD_TYPE_GET_INFO = 1,
491 CMD_TYPE_GET_METHODS = 2,
492 CMD_TYPE_GET_FIELDS = 3,
493 CMD_TYPE_GET_VALUES = 4,
494 CMD_TYPE_GET_OBJECT = 5,
495 CMD_TYPE_GET_SOURCE_FILES = 6,
496 CMD_TYPE_SET_VALUES = 7,
497 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
498 CMD_TYPE_GET_PROPERTIES = 9,
499 CMD_TYPE_GET_CATTRS = 10,
500 CMD_TYPE_GET_FIELD_CATTRS = 11,
501 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
502 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
503 CMD_TYPE_GET_VALUES_2 = 14,
504 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
505 CMD_TYPE_GET_INTERFACES = 16,
506 CMD_TYPE_GET_INTERFACE_MAP = 17,
507 CMD_TYPE_IS_INITIALIZED = 18,
508 CMD_TYPE_CREATE_INSTANCE = 19
509 } CmdType;
511 typedef enum {
512 CMD_STACK_FRAME_GET_VALUES = 1,
513 CMD_STACK_FRAME_GET_THIS = 2,
514 CMD_STACK_FRAME_SET_VALUES = 3
515 } CmdStackFrame;
517 typedef enum {
518 CMD_ARRAY_REF_GET_LENGTH = 1,
519 CMD_ARRAY_REF_GET_VALUES = 2,
520 CMD_ARRAY_REF_SET_VALUES = 3,
521 } CmdArray;
523 typedef enum {
524 CMD_STRING_REF_GET_VALUE = 1,
525 CMD_STRING_REF_GET_LENGTH = 2,
526 CMD_STRING_REF_GET_CHARS = 3
527 } CmdString;
529 typedef enum {
530 CMD_OBJECT_REF_GET_TYPE = 1,
531 CMD_OBJECT_REF_GET_VALUES = 2,
532 CMD_OBJECT_REF_IS_COLLECTED = 3,
533 CMD_OBJECT_REF_GET_ADDRESS = 4,
534 CMD_OBJECT_REF_GET_DOMAIN = 5,
535 CMD_OBJECT_REF_SET_VALUES = 6,
536 CMD_OBJECT_REF_GET_INFO = 7,
537 } CmdObject;
539 typedef struct {
540 ModifierKind kind;
541 union {
542 int count; /* For kind == MOD_KIND_COUNT */
543 MonoInternalThread *thread; /* For kind == MOD_KIND_THREAD_ONLY */
544 MonoClass *exc_class; /* For kind == MONO_KIND_EXCEPTION_ONLY */
545 MonoAssembly **assemblies; /* For kind == MONO_KIND_ASSEMBLY_ONLY */
546 GHashTable *source_files; /* For kind == MONO_KIND_SOURCE_FILE_ONLY */
547 GHashTable *type_names; /* For kind == MONO_KIND_TYPE_NAME_ONLY */
548 StepFilter filter; /* For kind == MOD_KIND_STEP */
549 } data;
550 gboolean caught, uncaught, subclasses; /* For kind == MOD_KIND_EXCEPTION_ONLY */
551 } Modifier;
553 typedef struct{
554 int id;
555 int event_kind;
556 int suspend_policy;
557 int nmodifiers;
558 gpointer info;
559 Modifier modifiers [MONO_ZERO_LEN_ARRAY];
560 } EventRequest;
563 * Describes a single step request.
565 typedef struct {
566 EventRequest *req;
567 MonoInternalThread *thread;
568 StepDepth depth;
569 StepSize size;
570 StepFilter filter;
571 gpointer last_sp;
572 gpointer start_sp;
573 MonoMethod *last_method;
574 int last_line;
575 /* Whenever single stepping is performed using start/stop_single_stepping () */
576 gboolean global;
577 /* The list of breakpoints used to implement step-over */
578 GSList *bps;
579 /* The number of frames at the start of a step-over */
580 int nframes;
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 HOST_WIN32
616 #define get_last_sock_error() WSAGetLastError()
617 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
618 #define MONO_EINTR WSAEINTR
619 #else
620 #define get_last_sock_error() errno
621 #define MONO_EWOULDBLOCK EWOULDBLOCK
622 #define MONO_EINTR EINTR
623 #endif
625 #define CHECK_PROTOCOL_VERSION(major,minor) \
626 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
629 * Globals
632 static AgentConfig agent_config;
635 * Whenever the agent is fully initialized.
636 * When using the onuncaught or onthrow options, only some parts of the agent are
637 * initialized on startup, and the full initialization which includes connection
638 * establishment and the startup of the agent thread is only done in response to
639 * an event.
641 static gint32 inited;
643 #ifndef DISABLE_SOCKET_TRANSPORT
644 static int conn_fd;
645 static int listen_fd;
646 #endif
648 static int packet_id = 0;
650 static int objref_id = 0;
652 static int event_request_id = 0;
654 static int frame_id = 0;
656 static GPtrArray *event_requests;
658 static MonoNativeTlsKey debugger_tls_id;
660 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
662 /* Maps MonoInternalThread -> DebuggerTlsData */
663 static MonoGHashTable *thread_to_tls;
665 /* Maps tid -> MonoInternalThread */
666 static MonoGHashTable *tid_to_thread;
668 /* Maps tid -> MonoThread (not MonoInternalThread) */
669 static MonoGHashTable *tid_to_thread_obj;
671 static gsize debugger_thread_id;
673 static HANDLE debugger_thread_handle;
675 static int log_level;
677 static gboolean embedding;
679 static FILE *log_file;
681 /* Assemblies whose assembly load event has no been sent yet */
682 /* Protected by the dbg lock */
683 static GPtrArray *pending_assembly_loads;
685 /* Whenever the debugger thread has exited */
686 static gboolean debugger_thread_exited;
688 /* Cond variable used to wait for debugger_thread_exited becoming true */
689 static mono_cond_t debugger_thread_exited_cond;
691 /* Mutex for the cond var above */
692 static mono_mutex_t debugger_thread_exited_mutex;
694 static DebuggerProfiler debugger_profiler;
696 /* The single step request instance */
697 static SingleStepReq *ss_req = NULL;
698 static gpointer ss_invoke_addr = NULL;
700 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
701 /* Number of single stepping operations in progress */
702 static int ss_count;
703 #endif
705 /* The protocol version of the client */
706 static int major_version, minor_version;
708 /* Whenever the variables above are set by the client */
709 static gboolean protocol_version_set;
711 /* A hash table containing all active domains */
712 static GHashTable *domains;
714 /* The number of times the runtime is suspended */
715 static gint32 suspend_count;
717 /* Whenever to buffer reply messages and send them together */
718 static gboolean buffer_replies;
720 /* Buffered reply packets */
721 static ReplyPacket reply_packets [128];
722 int nreply_packets;
724 #define dbg_lock() EnterCriticalSection (&debug_mutex)
725 #define dbg_unlock() LeaveCriticalSection (&debug_mutex)
726 static CRITICAL_SECTION debug_mutex;
728 static void transport_init (void);
729 static void transport_connect (const char *address);
730 static gboolean transport_handshake (void);
731 static void register_transport (DebuggerTransport *trans);
733 static guint32 WINAPI debugger_thread (void *arg);
735 static void runtime_initialized (MonoProfiler *prof);
737 static void runtime_shutdown (MonoProfiler *prof);
739 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
741 static void thread_end (MonoProfiler *prof, uintptr_t tid);
743 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result);
745 static void appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain);
747 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
749 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
751 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
753 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
755 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result);
757 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
759 static void emit_assembly_load (gpointer assembly, gpointer user_data);
761 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
763 static void start_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
765 static void end_runtime_invoke (MonoProfiler *prof, MonoMethod *method);
767 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result);
769 static void add_pending_breakpoints (MonoMethod *method, MonoJitInfo *jinfo);
771 static void start_single_stepping (void);
773 static void stop_single_stepping (void);
775 static void suspend_current (void);
777 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
779 static void clear_types_for_assembly (MonoAssembly *assembly);
781 static void clear_breakpoints_for_domain (MonoDomain *domain);
783 static void process_profiler_event (EventKind event, gpointer arg);
785 /* Submodule init/cleanup */
786 static void breakpoints_init (void);
787 static void breakpoints_cleanup (void);
789 static void objrefs_init (void);
790 static void objrefs_cleanup (void);
792 static void ids_init (void);
793 static void ids_cleanup (void);
795 static void suspend_init (void);
797 static void ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch);
798 static ErrorCode ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req);
799 static void ss_destroy (SingleStepReq *req);
801 static void start_debugger_thread (void);
802 static void stop_debugger_thread (void);
804 static void finish_agent_init (gboolean on_startup);
806 static void process_profiler_event (EventKind event, gpointer arg);
808 static void invalidate_frames (DebuggerTlsData *tls);
810 #ifndef DISABLE_SOCKET_TRANSPORT
811 static void
812 register_socket_transport (void);
813 #endif
815 static int
816 parse_address (char *address, char **host, int *port)
818 char *pos = strchr (address, ':');
820 if (pos == NULL || pos == address)
821 return 1;
823 *host = g_malloc (pos - address + 1);
824 strncpy (*host, address, pos - address);
825 (*host) [pos - address] = '\0';
827 *port = atoi (pos + 1);
829 return 0;
832 static void
833 print_usage (void)
835 fprintf (stderr, "Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
836 fprintf (stderr, "Available options:\n");
837 fprintf (stderr, " transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
838 fprintf (stderr, " address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
839 fprintf (stderr, " loglevel=<n>\t\t\tLog level (defaults to 0)\n");
840 fprintf (stderr, " logfile=<file>\t\tFile to log to (defaults to stdout)\n");
841 fprintf (stderr, " suspend=y/n\t\t\tWhether to suspend after startup.\n");
842 fprintf (stderr, " timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
843 fprintf (stderr, " server=y/n\t\t\tWhether to listen for a client connection.\n");
844 fprintf (stderr, " keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
845 fprintf (stderr, " setpgid=y/n\t\t\tWhether to call setpid(0, 0) after startup.\n");
846 fprintf (stderr, " help\t\t\t\tPrint this help.\n");
849 static gboolean
850 parse_flag (const char *option, char *flag)
852 if (!strcmp (flag, "y"))
853 return TRUE;
854 else if (!strcmp (flag, "n"))
855 return FALSE;
856 else {
857 fprintf (stderr, "debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
858 exit (1);
859 return FALSE;
863 void
864 mono_debugger_agent_parse_options (char *options)
866 char **args, **ptr;
867 char *host;
868 int port;
869 const char *extra;
871 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
872 fprintf (stderr, "--debugger-agent is not supported on this platform.\n");
873 exit (1);
874 #endif
876 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
877 if (extra)
878 options = g_strdup_printf ("%s,%s", options, extra);
880 agent_config.enabled = TRUE;
881 agent_config.suspend = TRUE;
882 agent_config.server = FALSE;
883 agent_config.defer = FALSE;
884 agent_config.address = NULL;
886 //agent_config.log_level = 10;
888 args = g_strsplit (options, ",", -1);
889 for (ptr = args; ptr && *ptr; ptr ++) {
890 char *arg = *ptr;
892 if (strncmp (arg, "transport=", 10) == 0) {
893 agent_config.transport = g_strdup (arg + 10);
894 } else if (strncmp (arg, "address=", 8) == 0) {
895 agent_config.address = g_strdup (arg + 8);
896 } else if (strncmp (arg, "loglevel=", 9) == 0) {
897 agent_config.log_level = atoi (arg + 9);
898 } else if (strncmp (arg, "logfile=", 8) == 0) {
899 agent_config.log_file = g_strdup (arg + 8);
900 } else if (strncmp (arg, "suspend=", 8) == 0) {
901 agent_config.suspend = parse_flag ("suspend", arg + 8);
902 } else if (strncmp (arg, "server=", 7) == 0) {
903 agent_config.server = parse_flag ("server", arg + 7);
904 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
905 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
906 } else if (strncmp (arg, "onthrow=", 8) == 0) {
907 /* We support multiple onthrow= options */
908 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
909 } else if (strncmp (arg, "onthrow", 7) == 0) {
910 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
911 } else if (strncmp (arg, "help", 4) == 0) {
912 print_usage ();
913 exit (0);
914 } else if (strncmp (arg, "timeout=", 8) == 0) {
915 agent_config.timeout = atoi (arg + 8);
916 } else if (strncmp (arg, "launch=", 7) == 0) {
917 agent_config.launch = g_strdup (arg + 7);
918 } else if (strncmp (arg, "embedding=", 10) == 0) {
919 agent_config.embedding = atoi (arg + 10) == 1;
920 } else if (strncmp (arg, "keepalive=", 10) == 0) {
921 agent_config.keepalive = atoi (arg + 10);
922 } else if (strncmp (arg, "setpgid=", 8) == 0) {
923 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
924 } else {
925 print_usage ();
926 exit (1);
930 if (agent_config.server && !agent_config.suspend) {
931 /* Waiting for deferred attachment */
932 agent_config.defer = TRUE;
933 if (agent_config.address == NULL) {
934 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (getpid () % 1000));
938 //agent_config.log_level = 0;
940 if (agent_config.transport == NULL) {
941 fprintf (stderr, "debugger-agent: The 'transport' option is mandatory.\n");
942 exit (1);
945 if (agent_config.address == NULL && !agent_config.server) {
946 fprintf (stderr, "debugger-agent: The 'address' option is mandatory.\n");
947 exit (1);
950 // FIXME:
951 if (!strcmp (agent_config.transport, "dt_socket")) {
952 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
953 fprintf (stderr, "debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
954 exit (1);
959 void
960 mono_debugger_agent_init (void)
962 InitializeCriticalSection (&debug_mutex);
964 if (!agent_config.enabled)
965 return;
967 transport_init ();
969 /* Need to know whenever a thread has acquired the loader mutex */
970 mono_loader_lock_track_ownership (TRUE);
972 event_requests = g_ptr_array_new ();
974 mono_mutex_init (&debugger_thread_exited_mutex);
975 mono_cond_init (&debugger_thread_exited_cond, NULL);
977 mono_profiler_install ((MonoProfiler*)&debugger_profiler, runtime_shutdown);
978 mono_profiler_set_events (MONO_PROFILE_APPDOMAIN_EVENTS | MONO_PROFILE_THREADS | MONO_PROFILE_ASSEMBLY_EVENTS | MONO_PROFILE_JIT_COMPILATION | MONO_PROFILE_METHOD_EVENTS);
979 mono_profiler_install_runtime_initialized (runtime_initialized);
980 mono_profiler_install_appdomain (NULL, appdomain_load, appdomain_start_unload, appdomain_unload);
981 mono_profiler_install_thread (thread_startup, thread_end);
982 mono_profiler_install_assembly (NULL, assembly_load, assembly_unload, NULL);
983 mono_profiler_install_jit_end (jit_end);
984 mono_profiler_install_method_invoke (start_runtime_invoke, end_runtime_invoke);
986 mono_native_tls_alloc (&debugger_tls_id, NULL);
988 thread_to_tls = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
989 MONO_GC_REGISTER_ROOT_FIXED (thread_to_tls);
991 tid_to_thread = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
992 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread);
994 tid_to_thread_obj = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_VALUE_GC);
995 MONO_GC_REGISTER_ROOT_FIXED (tid_to_thread_obj);
997 pending_assembly_loads = g_ptr_array_new ();
998 domains = g_hash_table_new (mono_aligned_addr_hash, NULL);
1000 log_level = agent_config.log_level;
1002 embedding = agent_config.embedding;
1003 disconnected = TRUE;
1005 if (agent_config.log_file) {
1006 log_file = fopen (agent_config.log_file, "w+");
1007 if (!log_file) {
1008 fprintf (stderr, "Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
1009 exit (1);
1011 } else {
1012 log_file = stdout;
1015 ids_init ();
1016 objrefs_init ();
1017 breakpoints_init ();
1018 suspend_init ();
1020 mini_get_debug_options ()->gen_seq_points = TRUE;
1022 * This is needed because currently we don't handle liveness info.
1024 mini_get_debug_options ()->mdb_optimizations = TRUE;
1026 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
1027 /* This is needed because we can't set local variables in registers yet */
1028 mono_disable_optimizations (MONO_OPT_LINEARS);
1029 #endif
1032 * The stack walk done from thread_interrupt () needs to be signal safe, but it
1033 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
1034 * safe (#3411). So load AOT info eagerly when the debugger is running as a
1035 * workaround.
1037 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
1039 #ifdef HAVE_SETPGID
1040 if (agent_config.setpgid)
1041 setpgid (0, 0);
1042 #endif
1044 if (!agent_config.onuncaught && !agent_config.onthrow)
1045 finish_agent_init (TRUE);
1049 * finish_agent_init:
1051 * Finish the initialization of the agent. This involves connecting the transport
1052 * and starting the agent thread. This is either done at startup, or
1053 * in response to some event like an unhandled exception.
1055 static void
1056 finish_agent_init (gboolean on_startup)
1058 int res;
1060 if (InterlockedCompareExchange (&inited, 1, 0) == 1)
1061 return;
1063 if (agent_config.launch) {
1064 char *argv [16];
1066 // FIXME: Generated address
1067 // FIXME: Races with transport_connect ()
1069 argv [0] = agent_config.launch;
1070 argv [1] = agent_config.transport;
1071 argv [2] = agent_config.address;
1072 argv [3] = NULL;
1074 res = g_spawn_async_with_pipes (NULL, argv, NULL, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1075 if (!res) {
1076 fprintf (stderr, "Failed to execute '%s'.\n", agent_config.launch);
1077 exit (1);
1081 transport_connect (agent_config.address);
1083 if (!on_startup) {
1084 /* Do some which is usually done after sending the VMStart () event */
1085 vm_start_event_sent = TRUE;
1086 start_debugger_thread ();
1090 static void
1091 mono_debugger_agent_cleanup (void)
1093 if (!inited)
1094 return;
1096 stop_debugger_thread ();
1098 breakpoints_cleanup ();
1099 objrefs_cleanup ();
1100 ids_cleanup ();
1102 mono_mutex_destroy (&debugger_thread_exited_mutex);
1103 mono_cond_destroy (&debugger_thread_exited_cond);
1107 * SOCKET TRANSPORT
1110 #ifndef DISABLE_SOCKET_TRANSPORT
1113 * recv_length:
1115 * recv() + handle incomplete reads and EINTR
1117 static int
1118 socket_transport_recv (void *buf, int len)
1120 int res;
1121 int total = 0;
1122 int fd = conn_fd;
1123 int flags = 0;
1124 static gint32 last_keepalive;
1125 gint32 msecs;
1127 do {
1128 again:
1129 res = recv (fd, (char *) buf + total, len - total, flags);
1130 if (res > 0)
1131 total += res;
1132 if (agent_config.keepalive) {
1133 gboolean need_keepalive = FALSE;
1134 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1135 need_keepalive = TRUE;
1136 } else if (res == -1) {
1137 /* This could happen if recv () is interrupted repeatedly */
1138 msecs = mono_msec_ticks ();
1139 if (msecs - last_keepalive >= agent_config.keepalive) {
1140 need_keepalive = TRUE;
1141 last_keepalive = msecs;
1144 if (need_keepalive) {
1145 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1146 goto again;
1149 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1150 return total;
1153 #ifndef TARGET_PS3
1154 #define HAVE_GETADDRINFO 1
1155 #endif
1157 static void
1158 set_keepalive (void)
1160 struct timeval tv;
1161 int result;
1163 if (!agent_config.keepalive || !conn_fd)
1164 return;
1166 tv.tv_sec = agent_config.keepalive / 1000;
1167 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1169 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1170 g_assert (result >= 0);
1173 static int
1174 socket_transport_accept (int socket_fd)
1176 conn_fd = accept (socket_fd, NULL, NULL);
1177 if (conn_fd == -1) {
1178 fprintf (stderr, "debugger-agent: Unable to listen on %d\n", socket_fd);
1179 } else {
1180 DEBUG (1, fprintf (log_file, "Accepted connection from client, connection fd=%d.\n", conn_fd));
1183 return conn_fd;
1186 static gboolean
1187 socket_transport_send (void *data, int len)
1189 int res;
1191 do {
1192 res = send (conn_fd, data, len, 0);
1193 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1194 if (res != len)
1195 return FALSE;
1196 else
1197 return TRUE;
1201 * socket_transport_connect:
1203 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1205 static void
1206 socket_transport_connect (const char *address)
1208 #ifdef HAVE_GETADDRINFO
1209 struct addrinfo hints;
1210 struct addrinfo *result, *rp;
1211 #else
1212 struct hostent *result;
1213 #endif
1214 int sfd = -1, s, res;
1215 char port_string [128];
1216 char *host;
1217 int port;
1219 if (agent_config.address) {
1220 res = parse_address (agent_config.address, &host, &port);
1221 g_assert (res == 0);
1222 } else {
1223 host = NULL;
1224 port = 0;
1227 conn_fd = -1;
1228 listen_fd = -1;
1230 if (host) {
1231 sprintf (port_string, "%d", port);
1233 mono_network_init ();
1235 /* Obtain address(es) matching host/port */
1236 #ifdef HAVE_GETADDRINFO
1237 memset (&hints, 0, sizeof (struct addrinfo));
1238 hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
1239 hints.ai_socktype = SOCK_STREAM; /* Datagram socket */
1240 hints.ai_flags = 0;
1241 hints.ai_protocol = 0; /* Any protocol */
1243 s = getaddrinfo (host, port_string, &hints, &result);
1244 if (s != 0) {
1245 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %s\n", host, port, gai_strerror (s));
1246 exit (1);
1248 #else
1249 /* The PS3 doesn't even have _r or hstrerror () */
1250 result = gethostbyname (host);
1251 if (!result) {
1252 fprintf (stderr, "debugger-agent: Unable to resolve %s:%d: %d\n", host, port, h_errno);
1254 #endif
1257 if (agent_config.server) {
1258 #ifdef HAVE_GETADDRINFO
1259 /* Wait for a connection */
1260 if (!host) {
1261 struct sockaddr_in addr;
1262 socklen_t addrlen;
1264 /* No address, generate one */
1265 sfd = socket (AF_INET, SOCK_STREAM, 0);
1266 g_assert (sfd);
1268 /* This will bind the socket to a random port */
1269 res = listen (sfd, 16);
1270 if (res == -1) {
1271 fprintf (stderr, "debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1272 exit (1);
1274 listen_fd = sfd;
1276 addrlen = sizeof (addr);
1277 memset (&addr, 0, sizeof (addr));
1278 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1279 g_assert (res == 0);
1281 host = (char*)"127.0.0.1";
1282 port = ntohs (addr.sin_port);
1284 /* Emit the address to stdout */
1285 /* FIXME: Should print another interface, not localhost */
1286 printf ("%s:%d\n", host, port);
1287 } else {
1288 /* Listen on the provided address */
1289 for (rp = result; rp != NULL; rp = rp->ai_next) {
1290 int n = 1;
1292 sfd = socket (rp->ai_family, rp->ai_socktype,
1293 rp->ai_protocol);
1294 if (sfd == -1)
1295 continue;
1297 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(n)) == -1)
1298 continue;
1300 res = bind (sfd, rp->ai_addr, rp->ai_addrlen);
1301 if (res == -1)
1302 continue;
1304 res = listen (sfd, 16);
1305 if (res == -1)
1306 continue;
1307 listen_fd = sfd;
1308 break;
1311 #ifndef HOST_WIN32
1313 * this function is not present on win2000 which we still support, and the
1314 * workaround described here:
1315 * http://msdn.microsoft.com/en-us/library/ms737931(VS.85).aspx
1316 * only works with MSVC.
1318 #ifdef HAVE_GETADDRINFO
1319 freeaddrinfo (result);
1320 #endif
1321 #endif
1324 if (agent_config.defer)
1325 return;
1327 DEBUG (1, fprintf (log_file, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout));
1329 if (agent_config.timeout) {
1330 fd_set readfds;
1331 struct timeval tv;
1333 tv.tv_sec = 0;
1334 tv.tv_usec = agent_config.timeout * 1000;
1335 FD_ZERO (&readfds);
1336 FD_SET (sfd, &readfds);
1337 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1338 if (res == 0) {
1339 fprintf (stderr, "debugger-agent: Timed out waiting to connect.\n");
1340 exit (1);
1344 conn_fd = socket_transport_accept (sfd);
1345 if (conn_fd == -1)
1346 exit (1);
1348 DEBUG (1, fprintf (log_file, "Accepted connection from client, socket fd=%d.\n", conn_fd));
1349 #else
1350 NOT_IMPLEMENTED;
1351 #endif /* HAVE_GETADDRINFO */
1352 } else {
1353 /* Connect to the specified address */
1354 #ifdef HAVE_GETADDRINFO
1355 /* FIXME: Respect the timeout */
1356 for (rp = result; rp != NULL; rp = rp->ai_next) {
1357 sfd = socket (rp->ai_family, rp->ai_socktype,
1358 rp->ai_protocol);
1359 if (sfd == -1)
1360 continue;
1362 if (connect (sfd, rp->ai_addr, rp->ai_addrlen) != -1)
1363 break; /* Success */
1365 close (sfd);
1368 if (rp == 0) {
1369 fprintf (stderr, "debugger-agent: Unable to connect to %s:%d\n", host, port);
1370 exit (1);
1372 #else
1373 sfd = socket (result->h_addrtype, SOCK_STREAM, 0);
1374 if (sfd == -1)
1375 g_assert_not_reached ();
1376 res = connect (sfd, (void*)result->h_addr_list [0], result->h_length);
1377 if (res == -1)
1378 g_assert_not_reached ();
1379 #endif
1381 conn_fd = sfd;
1383 #ifndef HOST_WIN32
1384 /* See the comment above */
1385 #ifdef HAVE_GETADDRINFO
1386 freeaddrinfo (result);
1387 #endif
1388 #endif
1391 if (!transport_handshake ())
1392 exit (1);
1395 static void
1396 socket_transport_close1 (void)
1398 /* This will interrupt the agent thread */
1399 /* Close the read part only so it can still send back replies */
1400 /* Also shut down the connection listener so that we can exit normally */
1401 #ifdef HOST_WIN32
1402 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1403 shutdown (conn_fd, SD_BOTH);
1404 shutdown (listen_fd, SD_BOTH);
1405 closesocket (listen_fd);
1406 #else
1407 shutdown (conn_fd, SHUT_RD);
1408 shutdown (listen_fd, SHUT_RDWR);
1409 close (listen_fd);
1410 #endif
1413 static void
1414 socket_transport_close2 (void)
1416 #ifdef HOST_WIN32
1417 shutdown (conn_fd, SD_BOTH);
1418 #else
1419 shutdown (conn_fd, SHUT_RDWR);
1420 #endif
1423 static void
1424 register_socket_transport (void)
1426 DebuggerTransport trans;
1428 trans.name = "dt_socket";
1429 trans.connect = socket_transport_connect;
1430 trans.close1 = socket_transport_close1;
1431 trans.close2 = socket_transport_close2;
1432 trans.send = socket_transport_send;
1433 trans.recv = socket_transport_recv;
1435 register_transport (&trans);
1438 #endif /* DISABLE_SOCKET_TRANSPORT */
1441 * TRANSPORT CODE
1444 #define MAX_TRANSPORTS 16
1446 static DebuggerTransport *transport;
1448 static DebuggerTransport transports [MAX_TRANSPORTS];
1449 static int ntransports;
1451 void
1452 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1454 void
1455 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1457 register_transport (trans);
1460 static void
1461 register_transport (DebuggerTransport *trans)
1463 g_assert (ntransports < MAX_TRANSPORTS);
1465 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1466 ntransports ++;
1469 static void
1470 transport_init (void)
1472 int i;
1474 #ifndef DISABLE_SOCKET_TRANSPORT
1475 register_socket_transport ();
1476 #endif
1478 for (i = 0; i < ntransports; ++i) {
1479 if (!strcmp (agent_config.transport, transports [i].name))
1480 break;
1482 if (i == ntransports) {
1483 fprintf (stderr, "debugger-agent: The supported values for the 'transport' option are: ");
1484 for (i = 0; i < ntransports; ++i)
1485 fprintf (stderr, "%s'%s'", i > 0 ? ", " : "", transports [i].name);
1486 fprintf (stderr, "\n");
1487 exit (1);
1489 transport = &transports [i];
1492 void
1493 transport_connect (const char *address)
1495 transport->connect (address);
1498 static void
1499 transport_close1 (void)
1501 transport->close1 ();
1504 static void
1505 transport_close2 (void)
1507 transport->close2 ();
1510 static int
1511 transport_send (void *buf, int len)
1513 return transport->send (buf, len);
1516 static int
1517 transport_recv (void *buf, int len)
1519 return transport->recv (buf, len);
1522 gboolean
1523 mono_debugger_agent_transport_handshake (void)
1525 return transport_handshake ();
1528 static gboolean
1529 transport_handshake (void)
1531 char handshake_msg [128];
1532 guint8 buf [128];
1533 int res;
1535 disconnected = TRUE;
1537 /* Write handshake message */
1538 sprintf (handshake_msg, "DWP-Handshake");
1539 do {
1540 res = transport_send (handshake_msg, strlen (handshake_msg));
1541 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1542 g_assert (res != -1);
1544 /* Read answer */
1545 res = transport_recv (buf, strlen (handshake_msg));
1546 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg) != 0))) {
1547 fprintf (stderr, "debugger-agent: DWP handshake failed.\n");
1548 return FALSE;
1552 * To support older clients, the client sends its protocol version after connecting
1553 * using a command. Until that is received, default to our protocol version.
1555 major_version = MAJOR_VERSION;
1556 minor_version = MINOR_VERSION;
1557 protocol_version_set = FALSE;
1559 #ifndef DISABLE_SOCKET_TRANSPORT
1560 // FIXME: Move this somewhere else
1562 * Set TCP_NODELAY on the socket so the client receives events/command
1563 * results immediately.
1565 if (conn_fd) {
1566 int flag = 1;
1567 int result = setsockopt (conn_fd,
1568 IPPROTO_TCP,
1569 TCP_NODELAY,
1570 (char *) &flag,
1571 sizeof(int));
1572 g_assert (result >= 0);
1575 set_keepalive ();
1576 #endif
1578 disconnected = FALSE;
1579 return TRUE;
1582 static void
1583 stop_debugger_thread (void)
1585 if (!inited)
1586 return;
1588 transport_close1 ();
1591 * Wait for the thread to exit.
1593 * If we continue with the shutdown without waiting for it, then the client might
1594 * not receive an answer to its last command like a resume.
1595 * The WaitForSingleObject infrastructure doesn't seem to work during shutdown, so
1596 * use pthreads.
1598 //WaitForSingleObject (debugger_thread_handle, INFINITE);
1599 if (GetCurrentThreadId () != debugger_thread_id) {
1600 do {
1601 mono_mutex_lock (&debugger_thread_exited_mutex);
1602 if (!debugger_thread_exited) {
1603 #ifdef HOST_WIN32
1604 if (WAIT_TIMEOUT == WaitForSingleObject(debugger_thread_exited_cond, 0)) {
1605 mono_mutex_unlock (&debugger_thread_exited_mutex);
1606 Sleep(1);
1607 mono_mutex_lock (&debugger_thread_exited_mutex);
1609 #else
1610 mono_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1611 #endif
1613 mono_mutex_unlock (&debugger_thread_exited_mutex);
1614 } while (!debugger_thread_exited);
1617 transport_close2 ();
1620 static void
1621 start_debugger_thread (void)
1623 debugger_thread_handle = mono_threads_create_thread (debugger_thread, NULL, 0, 0, NULL);
1624 g_assert (debugger_thread_handle);
1628 * Functions to decode protocol data
1631 static inline int
1632 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1634 *endbuf = buf + 1;
1635 g_assert (*endbuf <= limit);
1636 return buf [0];
1639 static inline int
1640 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1642 *endbuf = buf + 4;
1643 g_assert (*endbuf <= limit);
1645 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1648 static inline gint64
1649 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1651 guint32 high = decode_int (buf, &buf, limit);
1652 guint32 low = decode_int (buf, &buf, limit);
1654 *endbuf = buf;
1656 return ((((guint64)high) << 32) | ((guint64)low));
1659 static inline int
1660 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1662 return decode_int (buf, endbuf, limit);
1665 static inline char*
1666 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1668 int len = decode_int (buf, &buf, limit);
1669 char *s;
1671 if (len < 0) {
1672 *endbuf = buf;
1673 return NULL;
1676 s = g_malloc (len + 1);
1677 g_assert (s);
1679 memcpy (s, buf, len);
1680 s [len] = '\0';
1681 buf += len;
1682 *endbuf = buf;
1684 return s;
1688 * Functions to encode protocol data
1691 static inline void
1692 buffer_init (Buffer *buf, int size)
1694 buf->buf = g_malloc (size);
1695 buf->p = buf->buf;
1696 buf->end = buf->buf + size;
1699 static inline int
1700 buffer_len (Buffer *buf)
1702 return buf->p - buf->buf;
1705 static inline void
1706 buffer_make_room (Buffer *buf, int size)
1708 if (buf->end - buf->p < size) {
1709 int new_size = buf->end - buf->buf + size + 32;
1710 guint8 *p = g_realloc (buf->buf, new_size);
1711 size = buf->p - buf->buf;
1712 buf->buf = p;
1713 buf->p = p + size;
1714 buf->end = buf->buf + new_size;
1718 static inline void
1719 buffer_add_byte (Buffer *buf, guint8 val)
1721 buffer_make_room (buf, 1);
1722 buf->p [0] = val;
1723 buf->p++;
1726 static inline void
1727 buffer_add_short (Buffer *buf, guint32 val)
1729 buffer_make_room (buf, 2);
1730 buf->p [0] = (val >> 8) & 0xff;
1731 buf->p [1] = (val >> 0) & 0xff;
1732 buf->p += 2;
1735 static inline void
1736 buffer_add_int (Buffer *buf, guint32 val)
1738 buffer_make_room (buf, 4);
1739 buf->p [0] = (val >> 24) & 0xff;
1740 buf->p [1] = (val >> 16) & 0xff;
1741 buf->p [2] = (val >> 8) & 0xff;
1742 buf->p [3] = (val >> 0) & 0xff;
1743 buf->p += 4;
1746 static inline void
1747 buffer_add_long (Buffer *buf, guint64 l)
1749 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1750 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1753 static inline void
1754 buffer_add_id (Buffer *buf, int id)
1756 buffer_add_int (buf, (guint64)id);
1759 static inline void
1760 buffer_add_data (Buffer *buf, guint8 *data, int len)
1762 buffer_make_room (buf, len);
1763 memcpy (buf->p, data, len);
1764 buf->p += len;
1767 static inline void
1768 buffer_add_string (Buffer *buf, const char *str)
1770 int len;
1772 if (str == NULL) {
1773 buffer_add_int (buf, 0);
1774 } else {
1775 len = strlen (str);
1776 buffer_add_int (buf, len);
1777 buffer_add_data (buf, (guint8*)str, len);
1781 static inline void
1782 buffer_add_buffer (Buffer *buf, Buffer *data)
1784 buffer_add_data (buf, data->buf, buffer_len (data));
1787 static inline void
1788 buffer_free (Buffer *buf)
1790 g_free (buf->buf);
1793 static gboolean
1794 send_packet (int command_set, int command, Buffer *data)
1796 Buffer buf;
1797 int len, id;
1798 gboolean res;
1800 id = InterlockedIncrement (&packet_id);
1802 len = data->p - data->buf + 11;
1803 buffer_init (&buf, len);
1804 buffer_add_int (&buf, len);
1805 buffer_add_int (&buf, id);
1806 buffer_add_byte (&buf, 0); /* flags */
1807 buffer_add_byte (&buf, command_set);
1808 buffer_add_byte (&buf, command);
1809 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1811 res = transport_send (buf.buf, len);
1813 buffer_free (&buf);
1815 return res;
1818 static gboolean
1819 send_reply_packets (int npackets, ReplyPacket *packets)
1821 Buffer buf;
1822 int i, len;
1823 gboolean res;
1825 len = 0;
1826 for (i = 0; i < npackets; ++i)
1827 len += buffer_len (packets [i].data) + 11;
1828 buffer_init (&buf, len);
1829 for (i = 0; i < npackets; ++i) {
1830 buffer_add_int (&buf, buffer_len (packets [i].data) + 11);
1831 buffer_add_int (&buf, packets [i].id);
1832 buffer_add_byte (&buf, 0x80); /* flags */
1833 buffer_add_byte (&buf, (packets [i].error >> 8) & 0xff);
1834 buffer_add_byte (&buf, packets [i].error);
1835 buffer_add_buffer (&buf, packets [i].data);
1837 res = transport_send (buf.buf, len);
1839 buffer_free (&buf);
1841 return res;
1844 static gboolean
1845 send_reply_packet (int id, int error, Buffer *data)
1847 ReplyPacket packet;
1849 memset (&packet, 0, sizeof (ReplyPacket));
1850 packet.id = id;
1851 packet.error = error;
1852 packet.data = data;
1854 return send_reply_packets (1, &packet);
1857 static void
1858 send_buffered_reply_packets (void)
1860 int i;
1862 send_reply_packets (nreply_packets, reply_packets);
1863 for (i = 0; i < nreply_packets; ++i)
1864 buffer_free (reply_packets [i].data);
1865 DEBUG (1, fprintf (log_file, "[dbg] Sent %d buffered reply packets [at=%lx].\n", nreply_packets, (long)mono_100ns_ticks () / 10000));
1866 nreply_packets = 0;
1869 static void
1870 buffer_reply_packet (int id, int error, Buffer *data)
1872 ReplyPacket *p;
1874 if (nreply_packets == 128)
1875 send_buffered_reply_packets ();
1877 p = &reply_packets [nreply_packets];
1878 p->id = id;
1879 p->error = error;
1880 p->data = g_new0 (Buffer, 1);
1881 buffer_init (p->data, buffer_len (data));
1882 buffer_add_buffer (p->data, data);
1883 nreply_packets ++;
1887 * OBJECT IDS
1891 * Represents an object accessible by the debugger client.
1893 typedef struct {
1894 /* Unique id used in the wire protocol to refer to objects */
1895 int id;
1897 * A weakref gc handle pointing to the object. The gc handle is used to
1898 * detect if the object was garbage collected.
1900 guint32 handle;
1901 } ObjRef;
1903 /* Maps objid -> ObjRef */
1904 static GHashTable *objrefs;
1905 static GHashTable *obj_to_objref;
1906 /* Protected by the dbg lock */
1907 static MonoGHashTable *suspended_objs;
1909 static void
1910 free_objref (gpointer value)
1912 ObjRef *o = value;
1914 mono_gchandle_free (o->handle);
1916 g_free (o);
1919 static void
1920 objrefs_init (void)
1922 objrefs = g_hash_table_new_full (NULL, NULL, NULL, free_objref);
1923 obj_to_objref = g_hash_table_new (NULL, NULL);
1924 suspended_objs = mono_g_hash_table_new_type (NULL, NULL, MONO_HASH_KEY_GC);
1925 MONO_GC_REGISTER_ROOT_FIXED (suspended_objs);
1928 static void
1929 objrefs_cleanup (void)
1931 g_hash_table_destroy (objrefs);
1932 objrefs = NULL;
1936 * Return an ObjRef for OBJ.
1938 static ObjRef*
1939 get_objref (MonoObject *obj)
1941 ObjRef *ref;
1942 GSList *reflist = NULL, *l;
1943 int hash = 0;
1945 if (obj == NULL)
1946 return 0;
1948 if (suspend_count) {
1950 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1952 dbg_lock ();
1953 mono_g_hash_table_insert (suspended_objs, obj, NULL);
1954 dbg_unlock ();
1957 mono_loader_lock ();
1959 /* FIXME: The tables can grow indefinitely */
1961 if (mono_gc_is_moving ()) {
1963 * Objects can move, so use a hash table mapping hash codes to lists of
1964 * ObjRef structures.
1966 hash = mono_object_hash (obj);
1968 reflist = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1969 for (l = reflist; l; l = l->next) {
1970 ref = l->data;
1971 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1972 mono_loader_unlock ();
1973 return ref;
1976 } else {
1977 /* Use a hash table with masked pointers to internalize object references */
1978 ref = g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
1979 /* ref might refer to a different object with the same addr which was GCd */
1980 if (ref && mono_gchandle_get_target (ref->handle) == obj) {
1981 mono_loader_unlock ();
1982 return ref;
1986 ref = g_new0 (ObjRef, 1);
1987 ref->id = InterlockedIncrement (&objref_id);
1988 ref->handle = mono_gchandle_new_weakref (obj, FALSE);
1990 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
1992 if (mono_gc_is_moving ()) {
1993 reflist = g_slist_append (reflist, ref);
1994 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
1995 } else {
1996 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
1999 mono_loader_unlock ();
2001 return ref;
2004 static gboolean
2005 true_pred (gpointer key, gpointer value, gpointer user_data)
2007 return TRUE;
2010 static void
2011 clear_suspended_objs (void)
2013 dbg_lock ();
2014 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
2015 dbg_unlock ();
2018 static inline int
2019 get_objid (MonoObject *obj)
2021 return get_objref (obj)->id;
2025 * Set OBJ to the object identified by OBJID.
2026 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
2027 * collected.
2029 static ErrorCode
2030 get_object_allow_null (int objid, MonoObject **obj)
2032 ObjRef *ref;
2034 if (objid == 0) {
2035 *obj = NULL;
2036 return 0;
2039 if (!objrefs)
2040 return ERR_INVALID_OBJECT;
2042 mono_loader_lock ();
2044 ref = g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
2046 if (ref) {
2047 *obj = mono_gchandle_get_target (ref->handle);
2048 mono_loader_unlock ();
2049 if (!(*obj))
2050 return ERR_INVALID_OBJECT;
2051 return 0;
2052 } else {
2053 mono_loader_unlock ();
2054 return ERR_INVALID_OBJECT;
2058 static ErrorCode
2059 get_object (int objid, MonoObject **obj)
2061 int err = get_object_allow_null (objid, obj);
2063 if (err)
2064 return err;
2065 if (!(*obj))
2066 return ERR_INVALID_OBJECT;
2067 return 0;
2070 static inline int
2071 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
2073 return decode_id (buf, endbuf, limit);
2076 static inline void
2077 buffer_add_objid (Buffer *buf, MonoObject *o)
2079 buffer_add_id (buf, get_objid (o));
2083 * IDS
2086 typedef enum {
2087 ID_ASSEMBLY = 0,
2088 ID_MODULE = 1,
2089 ID_TYPE = 2,
2090 ID_METHOD = 3,
2091 ID_FIELD = 4,
2092 ID_DOMAIN = 5,
2093 ID_PROPERTY = 6,
2094 ID_NUM
2095 } IdType;
2098 * Represents a runtime structure accessible to the debugger client
2100 typedef struct {
2101 /* Unique id used in the wire protocol */
2102 int id;
2103 /* Domain of the runtime structure, NULL if the domain was unloaded */
2104 MonoDomain *domain;
2105 union {
2106 gpointer val;
2107 MonoClass *klass;
2108 MonoMethod *method;
2109 MonoImage *image;
2110 MonoAssembly *assembly;
2111 MonoClassField *field;
2112 MonoDomain *domain;
2113 MonoProperty *property;
2114 } data;
2115 } Id;
2117 typedef struct {
2118 /* Maps runtime structure -> Id */
2119 GHashTable *val_to_id [ID_NUM];
2120 /* Classes whose class load event has been sent */
2121 GHashTable *loaded_classes;
2122 /* Maps MonoClass->GPtrArray of file names */
2123 GHashTable *source_files;
2124 /* Maps source file basename -> GSList of classes */
2125 GHashTable *source_file_to_class;
2126 /* Same with ignore-case */
2127 GHashTable *source_file_to_class_ignorecase;
2128 } AgentDomainInfo;
2130 /* Maps id -> Id */
2131 /* Protected by the dbg lock */
2132 static GPtrArray *ids [ID_NUM];
2134 static void
2135 ids_init (void)
2137 int i;
2139 for (i = 0; i < ID_NUM; ++i)
2140 ids [i] = g_ptr_array_new ();
2143 static void
2144 ids_cleanup (void)
2146 int i, j;
2148 for (i = 0; i < ID_NUM; ++i) {
2149 if (ids [i]) {
2150 for (j = 0; j < ids [i]->len; ++j)
2151 g_free (g_ptr_array_index (ids [i], j));
2152 g_ptr_array_free (ids [i], TRUE);
2154 ids [i] = NULL;
2158 void
2159 mono_debugger_agent_free_domain_info (MonoDomain *domain)
2161 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
2162 int i, j;
2163 GHashTableIter iter;
2164 GPtrArray *file_names;
2165 char *basename;
2166 GSList *l;
2168 if (info) {
2169 for (i = 0; i < ID_NUM; ++i)
2170 if (info->val_to_id [i])
2171 g_hash_table_destroy (info->val_to_id [i]);
2172 g_hash_table_destroy (info->loaded_classes);
2174 g_hash_table_iter_init (&iter, info->source_files);
2175 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2176 for (i = 0; i < file_names->len; ++i)
2177 g_free (g_ptr_array_index (file_names, i));
2178 g_ptr_array_free (file_names, TRUE);
2181 g_hash_table_iter_init (&iter, info->source_file_to_class);
2182 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2183 g_free (basename);
2184 g_slist_free (l);
2187 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2188 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2189 g_free (basename);
2190 g_slist_free (l);
2193 g_free (info);
2196 domain_jit_info (domain)->agent_info = NULL;
2198 /* Clear ids referencing structures in the domain */
2199 dbg_lock ();
2200 for (i = 0; i < ID_NUM; ++i) {
2201 if (ids [i]) {
2202 for (j = 0; j < ids [i]->len; ++j) {
2203 Id *id = g_ptr_array_index (ids [i], j);
2204 if (id->domain == domain)
2205 id->domain = NULL;
2209 dbg_unlock ();
2211 mono_loader_lock ();
2212 g_hash_table_remove (domains, domain);
2213 mono_loader_unlock ();
2216 static AgentDomainInfo*
2217 get_agent_domain_info (MonoDomain *domain)
2219 AgentDomainInfo *info = NULL;
2221 mono_domain_lock (domain);
2223 info = domain_jit_info (domain)->agent_info;
2224 if (!info) {
2225 info = domain_jit_info (domain)->agent_info = g_new0 (AgentDomainInfo, 1);
2226 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2227 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2228 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2229 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2232 mono_domain_unlock (domain);
2234 return info;
2237 static int
2238 get_id (MonoDomain *domain, IdType type, gpointer val)
2240 Id *id;
2241 AgentDomainInfo *info;
2243 if (val == NULL)
2244 return 0;
2246 mono_loader_lock ();
2248 mono_domain_lock (domain);
2250 info = get_agent_domain_info (domain);
2252 if (info->val_to_id [type] == NULL)
2253 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2255 id = g_hash_table_lookup (info->val_to_id [type], val);
2256 if (id) {
2257 mono_domain_unlock (domain);
2258 mono_loader_unlock ();
2259 return id->id;
2262 dbg_lock ();
2264 id = g_new0 (Id, 1);
2265 /* Reserve id 0 */
2266 id->id = ids [type]->len + 1;
2267 id->domain = domain;
2268 id->data.val = val;
2270 g_hash_table_insert (info->val_to_id [type], val, id);
2271 g_ptr_array_add (ids [type], id);
2273 dbg_unlock ();
2275 mono_domain_unlock (domain);
2277 mono_loader_unlock ();
2279 return id->id;
2282 static inline gpointer
2283 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, int *err)
2285 Id *res;
2287 int id = decode_id (buf, endbuf, limit);
2289 *err = 0;
2290 if (domain)
2291 *domain = NULL;
2293 if (id == 0)
2294 return NULL;
2296 // FIXME: error handling
2297 dbg_lock ();
2298 g_assert (id > 0 && id <= ids [type]->len);
2300 res = g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2301 dbg_unlock ();
2303 if (res->domain == NULL) {
2304 DEBUG (0, fprintf (log_file, "ERR_UNLOADED, id=%d, type=%d.\n", id, type));
2305 *err = ERR_UNLOADED;
2306 return NULL;
2309 if (domain)
2310 *domain = res->domain;
2312 return res->data.val;
2315 static inline int
2316 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2318 int id = get_id (domain, type, val);
2320 buffer_add_id (buf, id);
2321 return id;
2324 static inline MonoClass*
2325 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2327 MonoClass *klass;
2329 klass = decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2330 if (G_UNLIKELY (log_level >= 2) && klass) {
2331 char *s;
2333 s = mono_type_full_name (&klass->byval_arg);
2334 DEBUG(2, fprintf (log_file, "[dbg] recv class [%s]\n", s));
2335 g_free (s);
2337 return klass;
2340 static inline MonoAssembly*
2341 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2343 return decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2346 static inline MonoImage*
2347 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2349 return decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2352 static inline MonoMethod*
2353 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2355 MonoMethod *m;
2357 m = decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2358 if (G_UNLIKELY (log_level >= 2) && m) {
2359 char *s;
2361 s = mono_method_full_name (m, TRUE);
2362 DEBUG(2, fprintf (log_file, "[dbg] recv method [%s]\n", s));
2363 g_free (s);
2365 return m;
2368 static inline MonoClassField*
2369 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2371 return decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2374 static inline MonoDomain*
2375 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2377 return decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2380 static inline MonoProperty*
2381 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, int *err)
2383 return decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2386 static inline void
2387 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2389 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2390 if (G_UNLIKELY (log_level >= 2) && klass) {
2391 char *s;
2393 s = mono_type_full_name (&klass->byval_arg);
2394 if (GetCurrentThreadId () == debugger_thread_id)
2395 DEBUG(2, fprintf (log_file, "[dbg] send class [%s]\n", s));
2396 else
2397 DEBUG(2, fprintf (log_file, "[%p] send class [%s]\n", (gpointer)GetCurrentThreadId (), s));
2398 g_free (s);
2402 static inline void
2403 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2405 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2406 if (G_UNLIKELY (log_level >= 2) && method) {
2407 char *s;
2409 s = mono_method_full_name (method, 1);
2410 DEBUG(2, fprintf (log_file, "[dbg] send method [%s]\n", s));
2411 g_free (s);
2415 static inline void
2416 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2418 int id;
2420 id = buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2421 if (G_UNLIKELY (log_level >= 2) && assembly)
2422 DEBUG(2, fprintf (log_file, "[dbg] send assembly [%s][%s][%d]\n", assembly->aname.name, domain->friendly_name, id));
2425 static inline void
2426 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2428 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2431 static inline void
2432 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2434 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2437 static inline void
2438 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2440 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2443 static inline void
2444 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2446 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2449 static void invoke_method (void);
2452 * SUSPEND/RESUME
2456 * save_thread_context:
2458 * Set CTX as the current threads context which is used for computing stack traces.
2459 * This function is signal-safe.
2461 static void
2462 save_thread_context (MonoContext *ctx)
2464 DebuggerTlsData *tls;
2466 tls = mono_native_tls_get_value (debugger_tls_id);
2467 g_assert (tls);
2469 if (ctx)
2470 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2471 else
2472 mono_thread_state_init_from_current (&tls->context);
2475 /* Number of threads suspended */
2477 * If this is equal to the size of thread_to_tls, the runtime is considered
2478 * suspended.
2480 static gint32 threads_suspend_count;
2482 static mono_mutex_t suspend_mutex;
2484 /* Cond variable used to wait for suspend_count becoming 0 */
2485 static mono_cond_t suspend_cond;
2487 /* Semaphore used to wait for a thread becoming suspended */
2488 static MonoSemType suspend_sem;
2490 static void
2491 suspend_init (void)
2493 mono_mutex_init (&suspend_mutex);
2494 mono_cond_init (&suspend_cond, NULL);
2495 MONO_SEM_INIT (&suspend_sem, 0);
2498 typedef struct
2500 StackFrameInfo last_frame;
2501 gboolean last_frame_set;
2502 MonoContext ctx;
2503 gpointer lmf;
2504 } GetLastFrameUserData;
2506 static gboolean
2507 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2509 GetLastFrameUserData *data = user_data;
2511 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE)
2512 return FALSE;
2514 if (!data->last_frame_set) {
2515 /* Store the last frame */
2516 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2517 data->last_frame_set = TRUE;
2518 return FALSE;
2519 } else {
2520 /* Store the context/lmf for the frame above the last frame */
2521 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2522 data->lmf = info->lmf;
2523 return TRUE;
2528 * thread_interrupt:
2530 * Process interruption of a thread. If SIGCTX is set, process the current thread. If
2531 * INFO is set, process the thread described by INFO.
2532 * This should be signal safe.
2534 static gboolean
2535 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, void *sigctx, MonoJitInfo *ji)
2537 gboolean res;
2538 gpointer ip;
2539 MonoNativeThreadId tid;
2542 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2543 * guarantee the signal handler will be called that many times. Instead of tracking
2544 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2545 * has been requested that hasn't been handled yet, otherwise we can have threads
2546 * refuse to die when VM_EXIT is called
2548 #if defined(__APPLE__)
2549 if (InterlockedCompareExchange (&tls->interrupt_count, 0, 1) == 0)
2550 return FALSE;
2551 #else
2553 * We use interrupt_count to determine whenever this interrupt should be processed
2554 * by us or the normal interrupt processing code in the signal handler.
2555 * There is no race here with notify_thread (), since the signal is sent after
2556 * incrementing interrupt_count.
2558 if (tls->interrupt_count == 0)
2559 return FALSE;
2561 InterlockedDecrement (&tls->interrupt_count);
2562 #endif
2564 if (sigctx)
2565 ip = mono_arch_ip_from_context (sigctx);
2566 else if (info)
2567 ip = MONO_CONTEXT_GET_IP (&info->suspend_state.ctx);
2568 else
2569 ip = NULL;
2571 if (info)
2572 tid = mono_thread_info_get_tid (info);
2573 else
2574 tid = (MonoNativeThreadId)GetCurrentThreadId ();
2576 // FIXME: Races when the thread leaves managed code before hitting a single step
2577 // event.
2579 if (ji) {
2580 /* Running managed code, will be suspended by the single step code */
2581 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip));
2582 return TRUE;
2583 } else {
2585 * Running native code, will be suspended when it returns to/enters
2586 * managed code. Treat it as already suspended.
2587 * This might interrupt the code in process_single_step_inner (), we use the
2588 * tls->suspending flag to avoid races when that happens.
2590 if (!tls->suspended && !tls->suspending) {
2591 MonoContext ctx;
2592 GetLastFrameUserData data;
2594 // FIXME: printf is not signal safe, but this is only used during
2595 // debugger debugging
2596 if (ip)
2597 DEBUG (1, fprintf (log_file, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip));
2598 //save_thread_context (&ctx);
2600 if (!tls->thread)
2601 /* Already terminated */
2602 return TRUE;
2605 * We are in a difficult position: we want to be able to provide stack
2606 * traces for this thread, but we can't use the current ctx+lmf, since
2607 * the thread is still running, so it might return to managed code,
2608 * making these invalid.
2609 * So we start a stack walk and save the first frame, along with the
2610 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2611 * suspended when it returns to managed code, so the parent's ctx should
2612 * remain valid.
2614 data.last_frame_set = FALSE;
2615 if (sigctx) {
2616 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
2618 * Don't pass MONO_UNWIND_ACTUAL_METHOD, its not signal safe, and
2619 * get_last_frame () doesn't need it, the last frame cannot be a ginst
2620 * since we are not in a JITted method.
2622 mono_walk_stack_with_ctx (get_last_frame, &ctx, MONO_UNWIND_NONE, &data);
2623 } else if (info) {
2624 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, &info->suspend_state, MONO_UNWIND_SIGNAL_SAFE, &data);
2626 if (data.last_frame_set) {
2627 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2628 res = mono_thread_state_init_from_monoctx (&tls->async_state, &ctx);
2629 g_assert (res);
2630 mono_thread_state_init_from_monoctx (&tls->context, &ctx);
2631 g_assert (res);
2633 memcpy (&tls->async_state.ctx, &data.ctx, sizeof (MonoContext));
2634 tls->async_state.unwind_data [MONO_UNWIND_DATA_LMF] = data.lmf;
2635 tls->async_state.unwind_data [MONO_UNWIND_DATA_JIT_TLS] = tls->thread->jit_data;
2636 } else {
2637 tls->async_state.valid = FALSE;
2640 mono_memory_barrier ();
2642 tls->suspended = TRUE;
2643 MONO_SEM_POST (&suspend_sem);
2645 return TRUE;
2650 * mono_debugger_agent_thread_interrupt:
2652 * Called by the abort signal handler.
2653 * Should be signal safe.
2655 gboolean
2656 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
2658 DebuggerTlsData *tls;
2660 if (!inited)
2661 return FALSE;
2663 tls = mono_native_tls_get_value (debugger_tls_id);
2664 if (!tls) {
2665 DEBUG (1, fprintf (log_file, "[%p] Received interrupt with no TLS, continuing.\n", (gpointer)GetCurrentThreadId ()));
2666 return FALSE;
2669 return thread_interrupt (tls, NULL, sigctx, ji);
2672 #ifdef HOST_WIN32
2673 static void CALLBACK notify_thread_apc (ULONG_PTR param)
2675 //DebugBreak ();
2676 mono_debugger_agent_thread_interrupt (NULL, NULL);
2678 #endif /* HOST_WIN32 */
2681 * reset_native_thread_suspend_state:
2683 * Reset the suspended flag and state on native threads
2685 static void
2686 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2688 DebuggerTlsData *tls = value;
2690 if (!tls->really_suspended && tls->suspended) {
2691 tls->suspended = FALSE;
2693 * The thread might still be running if it was executing native code, so the state won't be invalided by
2694 * suspend_current ().
2696 tls->context.valid = FALSE;
2697 tls->async_state.valid = FALSE;
2698 invalidate_frames (tls);
2703 * notify_thread:
2705 * Notify a thread that it needs to suspend.
2707 static void
2708 notify_thread (gpointer key, gpointer value, gpointer user_data)
2710 MonoInternalThread *thread = key;
2711 DebuggerTlsData *tls = value;
2712 gsize tid = thread->tid;
2713 #ifndef HOST_WIN32
2714 int res;
2715 #endif
2717 if (GetCurrentThreadId () == tid || tls->terminated)
2718 return;
2720 DEBUG(1, fprintf (log_file, "[%p] Interrupting %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2723 * OSX can (and will) coalesce signals, so sending multiple pthread_kills does not
2724 * guarantee the signal handler will be called that many times. Instead of tracking
2725 * interrupt_count on osx, we use this as a boolean flag to determine if a interrupt
2726 * has been requested that hasn't been handled yet, otherwise we can have threads
2727 * refuse to die when VM_EXIT is called
2729 #if defined(__APPLE__)
2730 if (InterlockedCompareExchange (&tls->interrupt_count, 1, 0) == 1)
2731 return;
2732 #else
2734 * Maybe we could use the normal interrupt infrastructure, but that does a lot
2735 * of things like breaking waits etc. which we don't want.
2737 InterlockedIncrement (&tls->interrupt_count);
2738 #endif
2740 /* This is _not_ equivalent to ves_icall_System_Threading_Thread_Abort () */
2741 #ifdef HOST_WIN32
2742 QueueUserAPC (notify_thread_apc, thread->handle, (ULONG_PTR)NULL);
2743 #else
2744 if (mono_thread_info_new_interrupt_enabled ()) {
2745 MonoThreadInfo *info;
2746 MonoJitInfo *ji;
2748 info = mono_thread_info_safe_suspend_sync ((MonoNativeThreadId)(gpointer)(gsize)thread->tid, FALSE);
2749 if (!info) {
2750 DEBUG(1, fprintf (log_file, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid));
2752 * Attached thread which died without detaching.
2754 tls->terminated = TRUE;
2755 } else {
2756 ji = mono_jit_info_table_find (info->suspend_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], MONO_CONTEXT_GET_IP (&info->suspend_state.ctx));
2758 thread_interrupt (tls, info, NULL, ji);
2760 mono_thread_info_finish_suspend_and_resume (info);
2762 } else {
2763 res = mono_thread_kill (thread, mono_thread_get_abort_signal ());
2764 if (res) {
2765 DEBUG(1, fprintf (log_file, "[%p] mono_thread_kill () failed for %p: %d...\n", (gpointer)GetCurrentThreadId (), (gpointer)tid, res));
2767 * Attached thread which died without detaching.
2769 tls->terminated = TRUE;
2772 #endif
2775 static void
2776 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2778 guint8 *ip = MONO_CONTEXT_GET_IP (ctx);
2779 MonoJitInfo *ji;
2780 MonoMethod *method;
2782 if (mono_loader_lock_is_owned_by_self ()) {
2784 * Shortcut for the check in suspend_current (). This speeds up processing
2785 * when executing long running code inside the loader lock, i.e. assembly load
2786 * hooks.
2788 return;
2791 if (debugger_thread_id == GetCurrentThreadId ())
2792 return;
2794 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2795 if (suspend_count - tls->resume_count > 0)
2796 tls->suspending = TRUE;
2798 DEBUG(1, fprintf (log_file, "[%p] Received single step event for suspending.\n", (gpointer)GetCurrentThreadId ()));
2800 if (suspend_count - tls->resume_count == 0) {
2802 * We are executing a single threaded invoke but the single step for
2803 * suspending is still active.
2804 * FIXME: This slows down single threaded invokes.
2806 DEBUG(1, fprintf (log_file, "[%p] Ignored during single threaded invoke.\n", (gpointer)GetCurrentThreadId ()));
2807 return;
2810 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
2812 /* Can't suspend in these methods */
2813 method = jinfo_get_method (ji);
2814 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2815 return;
2817 save_thread_context (ctx);
2819 suspend_current ();
2823 * suspend_vm:
2825 * Increase the suspend count of the VM. While the suspend count is greater
2826 * than 0, runtime threads are suspended at certain points during execution.
2828 static void
2829 suspend_vm (void)
2831 mono_loader_lock ();
2833 mono_mutex_lock (&suspend_mutex);
2835 suspend_count ++;
2837 DEBUG(1, fprintf (log_file, "[%p] Suspending vm...\n", (gpointer)GetCurrentThreadId ()));
2839 if (suspend_count == 1) {
2840 // FIXME: Is it safe to call this inside the lock ?
2841 start_single_stepping ();
2842 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2845 mono_mutex_unlock (&suspend_mutex);
2847 if (suspend_count == 1)
2849 * Suspend creation of new threadpool threads, since they cannot run
2851 mono_thread_pool_suspend ();
2853 mono_loader_unlock ();
2857 * resume_vm:
2859 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2860 * are resumed.
2862 static void
2863 resume_vm (void)
2865 int err;
2867 g_assert (debugger_thread_id == GetCurrentThreadId ());
2869 mono_loader_lock ();
2871 mono_mutex_lock (&suspend_mutex);
2873 g_assert (suspend_count > 0);
2874 suspend_count --;
2876 DEBUG(1, fprintf (log_file, "[%p] Resuming vm, suspend count=%d...\n", (gpointer)GetCurrentThreadId (), suspend_count));
2878 if (suspend_count == 0) {
2879 // FIXME: Is it safe to call this inside the lock ?
2880 stop_single_stepping ();
2881 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2884 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2885 err = mono_cond_broadcast (&suspend_cond);
2886 g_assert (err == 0);
2888 mono_mutex_unlock (&suspend_mutex);
2889 //g_assert (err == 0);
2891 if (suspend_count == 0)
2892 mono_thread_pool_resume ();
2894 mono_loader_unlock ();
2898 * resume_thread:
2900 * Resume just one thread.
2902 static void
2903 resume_thread (MonoInternalThread *thread)
2905 int err;
2906 DebuggerTlsData *tls;
2908 g_assert (debugger_thread_id == GetCurrentThreadId ());
2910 mono_loader_lock ();
2912 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
2913 g_assert (tls);
2915 mono_mutex_lock (&suspend_mutex);
2917 g_assert (suspend_count > 0);
2919 DEBUG(1, fprintf (log_file, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid));
2921 tls->resume_count += suspend_count;
2924 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2925 * but only the one whose resume_count field is > 0 will be resumed.
2927 err = mono_cond_broadcast (&suspend_cond);
2928 g_assert (err == 0);
2930 mono_mutex_unlock (&suspend_mutex);
2931 //g_assert (err == 0);
2933 mono_loader_unlock ();
2936 static void
2937 invalidate_frames (DebuggerTlsData *tls)
2939 int i;
2941 if (!tls)
2942 tls = mono_native_tls_get_value (debugger_tls_id);
2943 g_assert (tls);
2945 for (i = 0; i < tls->frame_count; ++i) {
2946 if (tls->frames [i]->jit)
2947 mono_debug_free_method_jit_info (tls->frames [i]->jit);
2948 g_free (tls->frames [i]);
2950 g_free (tls->frames);
2951 tls->frame_count = 0;
2952 tls->frames = NULL;
2956 * suspend_current:
2958 * Suspend the current thread until the runtime is resumed. If the thread has a
2959 * pending invoke, then the invoke is executed before this function returns.
2961 static void
2962 suspend_current (void)
2964 #ifndef HOST_WIN32
2965 int err;
2966 #endif
2967 DebuggerTlsData *tls;
2969 g_assert (debugger_thread_id != GetCurrentThreadId ());
2971 if (mono_loader_lock_is_owned_by_self ()) {
2973 * If we own the loader mutex, can't suspend until we release it, since the
2974 * whole runtime can deadlock otherwise.
2976 return;
2979 tls = mono_native_tls_get_value (debugger_tls_id);
2980 g_assert (tls);
2982 mono_mutex_lock (&suspend_mutex);
2984 tls->suspending = FALSE;
2985 tls->really_suspended = TRUE;
2987 if (!tls->suspended) {
2988 tls->suspended = TRUE;
2989 MONO_SEM_POST (&suspend_sem);
2992 DEBUG(1, fprintf (log_file, "[%p] Suspended.\n", (gpointer)GetCurrentThreadId ()));
2994 while (suspend_count - tls->resume_count > 0) {
2995 #ifdef HOST_WIN32
2996 if (WAIT_TIMEOUT == WaitForSingleObject(suspend_cond, 0))
2998 mono_mutex_unlock (&suspend_mutex);
2999 Sleep(1);
3000 mono_mutex_lock (&suspend_mutex);
3002 else
3005 #else
3006 err = mono_cond_wait (&suspend_cond, &suspend_mutex);
3007 g_assert (err == 0);
3008 #endif
3011 tls->suspended = FALSE;
3012 tls->really_suspended = FALSE;
3014 threads_suspend_count --;
3016 mono_mutex_unlock (&suspend_mutex);
3018 DEBUG(1, fprintf (log_file, "[%p] Resumed.\n", (gpointer)GetCurrentThreadId ()));
3020 if (tls->pending_invoke) {
3021 /* Save the original context */
3022 tls->pending_invoke->has_ctx = TRUE;
3023 tls->pending_invoke->ctx = tls->context.ctx;
3025 invoke_method ();
3028 /* The frame info becomes invalid after a resume */
3029 tls->context.valid = FALSE;
3030 tls->async_state.valid = FALSE;
3031 invalidate_frames (tls);
3034 static void
3035 count_thread (gpointer key, gpointer value, gpointer user_data)
3037 DebuggerTlsData *tls = value;
3039 if (!tls->suspended && !tls->terminated)
3040 *(int*)user_data = *(int*)user_data + 1;
3043 static int
3044 count_threads_to_wait_for (void)
3046 int count = 0;
3048 mono_loader_lock ();
3049 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
3050 mono_loader_unlock ();
3052 return count;
3056 * wait_for_suspend:
3058 * Wait until the runtime is completely suspended.
3060 static void
3061 wait_for_suspend (void)
3063 int nthreads, nwait, err;
3064 gboolean waited = FALSE;
3066 // FIXME: Threads starting/stopping ?
3067 mono_loader_lock ();
3068 nthreads = mono_g_hash_table_size (thread_to_tls);
3069 mono_loader_unlock ();
3071 while (TRUE) {
3072 nwait = count_threads_to_wait_for ();
3073 if (nwait) {
3074 DEBUG(1, fprintf (log_file, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads));
3075 err = MONO_SEM_WAIT (&suspend_sem);
3076 g_assert (err == 0);
3077 waited = TRUE;
3078 } else {
3079 break;
3083 if (waited)
3084 DEBUG(1, fprintf (log_file, "%d threads suspended.\n", nthreads));
3088 * is_suspended:
3090 * Return whenever the runtime is suspended.
3092 static gboolean
3093 is_suspended (void)
3095 return count_threads_to_wait_for () == 0;
3098 static MonoSeqPointInfo*
3099 get_seq_points (MonoDomain *domain, MonoMethod *method)
3101 MonoSeqPointInfo *seq_points;
3103 mono_domain_lock (domain);
3104 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, method);
3105 if (!seq_points && method->is_inflated) {
3106 /* generic sharing + aot */
3107 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (method));
3108 if (!seq_points)
3109 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mini_get_shared_method (method));
3111 mono_domain_unlock (domain);
3113 return seq_points;
3116 static void
3117 no_seq_points_found (MonoMethod *method)
3120 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3122 printf ("Unable to find seq points for method '%s'.\n", mono_method_full_name (method, TRUE));
3126 * find_next_seq_point_for_native_offset:
3128 * Find the first sequence point after NATIVE_OFFSET.
3130 static SeqPoint*
3131 find_next_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
3133 MonoSeqPointInfo *seq_points;
3134 int i;
3136 seq_points = get_seq_points (domain, method);
3137 if (!seq_points) {
3138 if (info)
3139 *info = NULL;
3140 return NULL;
3142 g_assert (seq_points);
3143 if (info)
3144 *info = seq_points;
3146 for (i = 0; i < seq_points->len; ++i) {
3147 if (seq_points->seq_points [i].native_offset >= native_offset)
3148 return &seq_points->seq_points [i];
3151 return NULL;
3155 * find_prev_seq_point_for_native_offset:
3157 * Find the first sequence point before NATIVE_OFFSET.
3159 static SeqPoint*
3160 find_prev_seq_point_for_native_offset (MonoDomain *domain, MonoMethod *method, gint32 native_offset, MonoSeqPointInfo **info)
3162 MonoSeqPointInfo *seq_points;
3163 int i;
3165 seq_points = get_seq_points (domain, method);
3166 if (info)
3167 *info = seq_points;
3168 if (!seq_points)
3169 return NULL;
3171 for (i = seq_points->len - 1; i >= 0; --i) {
3172 if (seq_points->seq_points [i].native_offset <= native_offset)
3173 return &seq_points->seq_points [i];
3176 return NULL;
3180 * find_seq_point:
3182 * Find the sequence point corresponding to the IL offset IL_OFFSET, which
3183 * should be the location of a sequence point.
3185 static G_GNUC_UNUSED SeqPoint*
3186 find_seq_point (MonoDomain *domain, MonoMethod *method, gint32 il_offset, MonoSeqPointInfo **info)
3188 MonoSeqPointInfo *seq_points;
3189 int i;
3191 *info = NULL;
3193 seq_points = get_seq_points (domain, method);
3194 if (!seq_points)
3195 return NULL;
3196 *info = seq_points;
3198 for (i = 0; i < seq_points->len; ++i) {
3199 if (seq_points->seq_points [i].il_offset == il_offset)
3200 return &seq_points->seq_points [i];
3203 return NULL;
3206 typedef struct {
3207 DebuggerTlsData *tls;
3208 GSList *frames;
3209 } ComputeFramesUserData;
3211 static gboolean
3212 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3214 ComputeFramesUserData *ud = user_data;
3215 StackFrame *frame;
3216 MonoMethod *method, *actual_method, *api_method;
3217 SeqPoint *sp;
3218 int flags = 0;
3220 if (info->type != FRAME_TYPE_MANAGED) {
3221 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3222 /* Mark the last frame as an invoke frame */
3223 if (ud->frames)
3224 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3226 return FALSE;
3229 if (info->ji)
3230 method = jinfo_get_method (info->ji);
3231 else
3232 method = info->method;
3233 actual_method = info->actual_method;
3234 api_method = method;
3236 if (!method)
3237 return FALSE;
3239 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE))
3240 return FALSE;
3242 if (info->il_offset == -1) {
3243 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3244 if (ud->frames == NULL) {
3245 sp = find_prev_seq_point_for_native_offset (info->domain, method, info->native_offset, NULL);
3246 if (sp)
3247 info->il_offset = sp->il_offset;
3249 if (info->il_offset == -1)
3250 info->il_offset = mono_debug_il_offset_from_address (method, info->domain, info->native_offset);
3253 DEBUG (1, fprintf (log_file, "\tFrame: %s:%x(%x) %d\n", mono_method_full_name (method, TRUE), info->il_offset, info->native_offset, info->managed));
3255 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3256 if (!CHECK_PROTOCOL_VERSION (2, 17))
3257 /* Older clients can't handle this flag */
3258 return FALSE;
3259 api_method = mono_marshal_method_from_wrapper (method);
3260 if (!api_method)
3261 return FALSE;
3262 actual_method = api_method;
3263 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3266 frame = g_new0 (StackFrame, 1);
3267 frame->method = method;
3268 frame->actual_method = actual_method;
3269 frame->api_method = api_method;
3270 frame->il_offset = info->il_offset;
3271 frame->native_offset = info->native_offset;
3272 frame->flags = flags;
3273 frame->ji = info->ji;
3274 if (info->reg_locations)
3275 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (mgreg_t*));
3276 if (ctx) {
3277 frame->ctx = *ctx;
3278 frame->has_ctx = TRUE;
3280 frame->domain = info->domain;
3282 ud->frames = g_slist_append (ud->frames, frame);
3284 return FALSE;
3287 static gboolean
3288 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3290 ComputeFramesUserData *ud = user_data;
3293 * 'tls->filter_ctx' is the location of the throw site.
3295 * mono_walk_stack() will never actually hit the throw site, but unwind
3296 * directly from the filter to the call site; we abort stack unwinding here
3297 * once this happens and resume from the throw site.
3300 if (MONO_CONTEXT_GET_SP (ctx) >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3301 return TRUE;
3303 return process_frame (info, ctx, user_data);
3306 static void
3307 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls)
3309 ComputeFramesUserData user_data;
3310 GSList *tmp;
3311 int i, findex, new_frame_count;
3312 StackFrame **new_frames, *f;
3313 MonoUnwindOptions opts = MONO_UNWIND_DEFAULT|MONO_UNWIND_REG_LOCATIONS;
3315 // FIXME: Locking on tls
3316 if (tls->frames && tls->frames_up_to_date)
3317 return;
3319 DEBUG(1, fprintf (log_file, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid));
3321 user_data.tls = tls;
3322 user_data.frames = NULL;
3323 if (tls->terminated) {
3324 tls->frame_count = 0;
3325 return;
3326 } if (!tls->really_suspended && tls->async_state.valid) {
3327 /* Have to use the state saved by the signal handler */
3328 process_frame (&tls->async_last_frame, NULL, &user_data);
3329 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3330 } else if (tls->filter_state.valid) {
3332 * We are inside an exception filter.
3334 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3336 if (tls->context.valid)
3337 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3339 * After that, we resume unwinding from the location where the exception has been thrown.
3341 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3342 } else if (tls->context.valid) {
3343 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3344 } else {
3345 // FIXME:
3346 tls->frame_count = 0;
3347 return;
3350 new_frame_count = g_slist_length (user_data.frames);
3351 new_frames = g_new0 (StackFrame*, new_frame_count);
3352 findex = 0;
3353 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3354 f = tmp->data;
3357 * Reuse the id for already existing stack frames, so invokes don't invalidate
3358 * the still valid stack frames.
3360 for (i = 0; i < tls->frame_count; ++i) {
3361 if (MONO_CONTEXT_GET_SP (&tls->frames [i]->ctx) == MONO_CONTEXT_GET_SP (&f->ctx)) {
3362 f->id = tls->frames [i]->id;
3363 break;
3367 if (i >= tls->frame_count)
3368 f->id = InterlockedIncrement (&frame_id);
3370 new_frames [findex ++] = f;
3373 g_slist_free (user_data.frames);
3375 invalidate_frames (tls);
3377 tls->frames = new_frames;
3378 tls->frame_count = new_frame_count;
3379 tls->frames_up_to_date = TRUE;
3383 * GHFunc to emit an appdomain creation event
3384 * @param key Don't care
3385 * @param value A loaded appdomain
3386 * @param user_data Don't care
3388 static void
3389 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3391 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3392 g_hash_table_foreach (get_agent_domain_info (value)->loaded_classes, emit_type_load, NULL);
3396 * GHFunc to emit a thread start event
3397 * @param key A thread id
3398 * @param value A thread object
3399 * @param user_data Don't care
3401 static void
3402 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3404 if (GPOINTER_TO_INT (key) != debugger_thread_id)
3405 process_profiler_event (EVENT_KIND_THREAD_START, value);
3409 * GFunc to emit an assembly load event
3410 * @param value A loaded assembly
3411 * @param user_data Don't care
3413 static void
3414 emit_assembly_load (gpointer value, gpointer user_data)
3416 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3420 * GFunc to emit a type load event
3421 * @param value A loaded type
3422 * @param user_data Don't care
3424 static void
3425 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3427 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3430 static char*
3431 strdup_tolower (char *s)
3433 char *s2, *p;
3435 s2 = g_strdup (s);
3436 for (p = s2; *p; ++p)
3437 *p = tolower (*p);
3438 return s2;
3442 * EVENT HANDLING
3446 * create_event_list:
3448 * Return a list of event request ids matching EVENT, starting from REQS, which
3449 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3450 * policy.
3451 * We return request ids, instead of requests, to simplify threading, since
3452 * requests could be deleted anytime when the loader lock is not held.
3453 * LOCKING: Assumes the loader lock is held.
3455 static GSList*
3456 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3458 int i, j;
3459 GSList *events = NULL;
3461 *suspend_policy = SUSPEND_POLICY_NONE;
3463 if (!reqs)
3464 reqs = event_requests;
3466 if (!reqs)
3467 return NULL;
3469 for (i = 0; i < reqs->len; ++i) {
3470 EventRequest *req = g_ptr_array_index (reqs, i);
3471 if (req->event_kind == event) {
3472 gboolean filtered = FALSE;
3474 /* Apply filters */
3475 for (j = 0; j < req->nmodifiers; ++j) {
3476 Modifier *mod = &req->modifiers [j];
3478 if (mod->kind == MOD_KIND_COUNT) {
3479 filtered = TRUE;
3480 if (mod->data.count > 0) {
3481 if (mod->data.count > 0) {
3482 mod->data.count --;
3483 if (mod->data.count == 0)
3484 filtered = FALSE;
3487 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3488 if (mod->data.thread != mono_thread_internal_current ())
3489 filtered = TRUE;
3490 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && ei) {
3491 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from (mod->data.exc_class, ei->exc->vtable->klass))
3492 filtered = TRUE;
3493 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3494 filtered = TRUE;
3495 if (ei->caught && !mod->caught)
3496 filtered = TRUE;
3497 if (!ei->caught && !mod->uncaught)
3498 filtered = TRUE;
3499 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3500 int k;
3501 gboolean found = FALSE;
3502 MonoAssembly **assemblies = mod->data.assemblies;
3504 if (assemblies) {
3505 for (k = 0; assemblies [k]; ++k)
3506 if (assemblies [k] == jinfo_get_method (ji)->klass->image->assembly)
3507 found = TRUE;
3509 if (!found)
3510 filtered = TRUE;
3511 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3512 gpointer iter = NULL;
3513 MonoMethod *method;
3514 MonoDebugSourceInfo *sinfo;
3515 char *source_file, *s;
3516 gboolean found = FALSE;
3517 int i;
3518 GPtrArray *source_file_list;
3520 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3521 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3523 if (minfo) {
3524 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
3525 for (i = 0; i < source_file_list->len; ++i) {
3526 sinfo = g_ptr_array_index (source_file_list, i);
3528 * Do a case-insesitive match by converting the file name to
3529 * lowercase.
3531 s = strdup_tolower (sinfo->source_file);
3532 if (g_hash_table_lookup (mod->data.source_files, s))
3533 found = TRUE;
3534 else {
3535 char *s2 = g_path_get_basename (sinfo->source_file);
3536 char *s3 = strdup_tolower (s2);
3538 if (g_hash_table_lookup (mod->data.source_files, s3))
3539 found = TRUE;
3540 g_free (s2);
3541 g_free (s3);
3543 g_free (s);
3545 g_ptr_array_free (source_file_list, TRUE);
3548 if (!found)
3549 filtered = TRUE;
3550 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3551 char *s;
3553 s = mono_type_full_name (&ei->klass->byval_arg);
3554 if (!g_hash_table_lookup (mod->data.type_names, s))
3555 filtered = TRUE;
3556 g_free (s);
3557 } else if (mod->kind == MOD_KIND_STEP) {
3558 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3559 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3560 !strcmp (jinfo_get_method (ji)->name, ".cctor"))
3561 filtered = TRUE;
3562 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3563 MonoCustomAttrInfo *ainfo;
3564 static MonoClass *klass;
3566 if (!klass) {
3567 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3568 g_assert (klass);
3570 if (!ji->dbg_hidden_inited) {
3571 ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji));
3572 if (ainfo) {
3573 if (mono_custom_attrs_has_attr (ainfo, klass))
3574 ji->dbg_hidden = TRUE;
3575 mono_custom_attrs_free (ainfo);
3577 ji->dbg_hidden_inited = TRUE;
3579 if (ji->dbg_hidden)
3580 filtered = TRUE;
3582 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3583 MonoCustomAttrInfo *ainfo;
3584 static MonoClass *klass;
3586 if (!klass) {
3587 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3588 g_assert (klass);
3590 if (!ji->dbg_step_through_inited) {
3591 ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji));
3592 if (ainfo) {
3593 if (mono_custom_attrs_has_attr (ainfo, klass))
3594 ji->dbg_step_through = TRUE;
3595 mono_custom_attrs_free (ainfo);
3597 ainfo = mono_custom_attrs_from_class (jinfo_get_method (ji)->klass);
3598 if (ainfo) {
3599 if (mono_custom_attrs_has_attr (ainfo, klass))
3600 ji->dbg_step_through = TRUE;
3601 mono_custom_attrs_free (ainfo);
3603 ji->dbg_step_through_inited = TRUE;
3605 if (ji->dbg_step_through)
3606 filtered = TRUE;
3608 if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3609 MonoCustomAttrInfo *ainfo;
3610 static MonoClass *klass;
3612 if (!klass) {
3613 klass = mono_class_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute");
3614 g_assert (klass);
3616 if (!ji->dbg_non_user_code_inited) {
3617 ainfo = mono_custom_attrs_from_method (jinfo_get_method (ji));
3618 if (ainfo) {
3619 if (mono_custom_attrs_has_attr (ainfo, klass))
3620 ji->dbg_non_user_code = TRUE;
3621 mono_custom_attrs_free (ainfo);
3623 ainfo = mono_custom_attrs_from_class (jinfo_get_method (ji)->klass);
3624 if (ainfo) {
3625 if (mono_custom_attrs_has_attr (ainfo, klass))
3626 ji->dbg_non_user_code = TRUE;
3627 mono_custom_attrs_free (ainfo);
3629 ji->dbg_non_user_code_inited = TRUE;
3631 if (ji->dbg_non_user_code)
3632 filtered = TRUE;
3637 if (!filtered) {
3638 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3639 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3644 /* Send a VM START/DEATH event by default */
3645 if (event == EVENT_KIND_VM_START)
3646 events = g_slist_append (events, GINT_TO_POINTER (0));
3647 if (event == EVENT_KIND_VM_DEATH)
3648 events = g_slist_append (events, GINT_TO_POINTER (0));
3650 return events;
3653 static G_GNUC_UNUSED const char*
3654 event_to_string (EventKind event)
3656 switch (event) {
3657 case EVENT_KIND_VM_START: return "VM_START";
3658 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3659 case EVENT_KIND_THREAD_START: return "THREAD_START";
3660 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3661 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3662 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3663 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3664 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3665 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3666 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3667 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3668 case EVENT_KIND_STEP: return "STEP";
3669 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3670 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3671 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3672 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3673 case EVENT_KIND_USER_LOG: return "USER_LOG";
3674 default:
3675 g_assert_not_reached ();
3676 return "";
3681 * process_event:
3683 * Send an event to the client, suspending the vm if needed.
3684 * LOCKING: Since this can suspend the calling thread, no locks should be held
3685 * by the caller.
3686 * The EVENTS list is freed by this function.
3688 static void
3689 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3691 Buffer buf;
3692 GSList *l;
3693 MonoDomain *domain = mono_domain_get ();
3694 MonoThread *thread = NULL;
3695 MonoObject *keepalive_obj = NULL;
3696 gboolean send_success = FALSE;
3697 static int ecount;
3698 int nevents;
3700 if (!inited) {
3701 DEBUG (2, fprintf (log_file, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event)));
3702 return;
3705 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3706 // FIXME: We miss those events
3707 DEBUG (2, fprintf (log_file, "VM start event not sent yet: dropping %s\n", event_to_string (event)));
3708 return;
3711 if (vm_death_event_sent) {
3712 DEBUG (2, fprintf (log_file, "VM death event has been sent: dropping %s\n", event_to_string (event)));
3713 return;
3716 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3717 DEBUG (2, fprintf (log_file, "Mono runtime is shutting down: dropping %s\n", event_to_string (event)));
3718 return;
3721 if (disconnected) {
3722 DEBUG (2, fprintf (log_file, "Debugger client is not connected: dropping %s\n", event_to_string (event)));
3723 return;
3726 if (event == EVENT_KIND_KEEPALIVE)
3727 suspend_policy = SUSPEND_POLICY_NONE;
3728 else {
3729 if (events == NULL)
3730 return;
3732 if (agent_config.defer) {
3733 /* Make sure the thread id is always set when doing deferred debugging */
3734 if (debugger_thread_id == GetCurrentThreadId ()) {
3735 /* Don't suspend on events from the debugger thread */
3736 suspend_policy = SUSPEND_POLICY_NONE;
3737 thread = mono_thread_get_main ();
3739 else thread = mono_thread_current ();
3740 } else {
3741 if (debugger_thread_id == GetCurrentThreadId () && event != EVENT_KIND_VM_DEATH)
3742 // FIXME: Send these with a NULL thread, don't suspend the current thread
3743 return;
3747 nevents = g_slist_length (events);
3748 buffer_init (&buf, 128);
3749 buffer_add_byte (&buf, suspend_policy);
3750 buffer_add_int (&buf, nevents);
3752 for (l = events; l; l = l->next) {
3753 buffer_add_byte (&buf, event); // event kind
3754 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3756 ecount ++;
3758 if (!thread)
3759 thread = mono_thread_current ();
3761 if (event == EVENT_KIND_VM_START && arg != NULL)
3762 thread = arg;
3764 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3766 switch (event) {
3767 case EVENT_KIND_THREAD_START:
3768 case EVENT_KIND_THREAD_DEATH:
3769 break;
3770 case EVENT_KIND_APPDOMAIN_CREATE:
3771 case EVENT_KIND_APPDOMAIN_UNLOAD:
3772 buffer_add_domainid (&buf, arg);
3773 break;
3774 case EVENT_KIND_METHOD_ENTRY:
3775 case EVENT_KIND_METHOD_EXIT:
3776 buffer_add_methodid (&buf, domain, arg);
3777 break;
3778 case EVENT_KIND_ASSEMBLY_LOAD:
3779 buffer_add_assemblyid (&buf, domain, arg);
3780 break;
3781 case EVENT_KIND_ASSEMBLY_UNLOAD: {
3782 DebuggerTlsData *tls;
3784 /* The domain the assembly belonged to is not equal to the current domain */
3785 tls = mono_native_tls_get_value (debugger_tls_id);
3786 g_assert (tls);
3787 g_assert (tls->domain_unloading);
3789 buffer_add_assemblyid (&buf, tls->domain_unloading, arg);
3790 break;
3792 case EVENT_KIND_TYPE_LOAD:
3793 buffer_add_typeid (&buf, domain, arg);
3794 break;
3795 case EVENT_KIND_BREAKPOINT:
3796 case EVENT_KIND_STEP:
3797 buffer_add_methodid (&buf, domain, arg);
3798 buffer_add_long (&buf, il_offset);
3799 break;
3800 case EVENT_KIND_VM_START:
3801 buffer_add_domainid (&buf, mono_get_root_domain ());
3802 break;
3803 case EVENT_KIND_VM_DEATH:
3804 if (CHECK_PROTOCOL_VERSION (2, 27))
3805 buffer_add_int (&buf, mono_environment_exitcode_get ());
3806 break;
3807 case EVENT_KIND_EXCEPTION: {
3808 EventInfo *ei = arg;
3809 buffer_add_objid (&buf, ei->exc);
3811 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3812 * later after the suspension. (#12494).
3814 keepalive_obj = ei->exc;
3815 break;
3817 case EVENT_KIND_USER_BREAK:
3818 break;
3819 case EVENT_KIND_USER_LOG: {
3820 EventInfo *ei = arg;
3821 buffer_add_int (&buf, ei->level);
3822 buffer_add_string (&buf, ei->category ? ei->category : "");
3823 buffer_add_string (&buf, ei->message ? ei->message : "");
3824 break;
3826 case EVENT_KIND_KEEPALIVE:
3827 suspend_policy = SUSPEND_POLICY_NONE;
3828 break;
3829 default:
3830 g_assert_not_reached ();
3834 if (event == EVENT_KIND_VM_START) {
3835 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3836 if (!agent_config.defer)
3837 start_debugger_thread ();
3840 if (event == EVENT_KIND_VM_DEATH) {
3841 vm_death_event_sent = TRUE;
3842 suspend_policy = SUSPEND_POLICY_NONE;
3845 if (mono_runtime_is_shutting_down ())
3846 suspend_policy = SUSPEND_POLICY_NONE;
3848 if (suspend_policy != SUSPEND_POLICY_NONE) {
3850 * Save the thread context and start suspending before sending the packet,
3851 * since we could be receiving the resume request before send_packet ()
3852 * returns.
3854 save_thread_context (ctx);
3855 suspend_vm ();
3857 if (keepalive_obj)
3858 /* This will keep this object alive */
3859 get_objref (keepalive_obj);
3862 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
3864 buffer_free (&buf);
3866 g_slist_free (events);
3867 events = NULL;
3869 if (!send_success) {
3870 DEBUG (2, fprintf (log_file, "Sending command %s failed.\n", event_to_string (event)));
3871 return;
3874 if (event == EVENT_KIND_VM_START) {
3875 vm_start_event_sent = TRUE;
3878 DEBUG (1, fprintf (log_file, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer)GetCurrentThreadId (), nevents, event_to_string (event), ecount, suspend_policy));
3880 switch (suspend_policy) {
3881 case SUSPEND_POLICY_NONE:
3882 break;
3883 case SUSPEND_POLICY_ALL:
3884 suspend_current ();
3885 break;
3886 case SUSPEND_POLICY_EVENT_THREAD:
3887 NOT_IMPLEMENTED;
3888 break;
3889 default:
3890 g_assert_not_reached ();
3894 static void
3895 process_profiler_event (EventKind event, gpointer arg)
3897 int suspend_policy;
3898 GSList *events;
3899 EventInfo ei, *ei_arg = NULL;
3901 if (event == EVENT_KIND_TYPE_LOAD) {
3902 ei.klass = arg;
3903 ei_arg = &ei;
3906 mono_loader_lock ();
3907 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
3908 mono_loader_unlock ();
3910 process_event (event, arg, 0, NULL, events, suspend_policy);
3913 static void
3914 runtime_initialized (MonoProfiler *prof)
3916 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
3917 if (agent_config.defer)
3918 start_debugger_thread ();
3921 static void
3922 runtime_shutdown (MonoProfiler *prof)
3924 process_profiler_event (EVENT_KIND_VM_DEATH, mono_thread_current ());
3926 mono_debugger_agent_cleanup ();
3929 static void
3930 thread_startup (MonoProfiler *prof, uintptr_t tid)
3932 MonoInternalThread *thread = mono_thread_internal_current ();
3933 MonoInternalThread *old_thread;
3934 DebuggerTlsData *tls;
3936 if (tid == debugger_thread_id)
3937 return;
3939 g_assert (thread->tid == tid);
3941 mono_loader_lock ();
3942 old_thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3943 mono_loader_unlock ();
3944 if (old_thread) {
3945 if (thread == old_thread) {
3947 * For some reason, thread_startup () might be called for the same thread
3948 * multiple times (attach ?).
3950 DEBUG (1, fprintf (log_file, "[%p] thread_start () called multiple times for %p, ignored.\n", (gpointer)tid, (gpointer)tid));
3951 return;
3952 } else {
3954 * thread_end () might not be called for some threads, and the tid could
3955 * get reused.
3957 DEBUG (1, fprintf (log_file, "[%p] Removing stale data for tid %p.\n", (gpointer)tid, (gpointer)tid));
3958 mono_loader_lock ();
3959 mono_g_hash_table_remove (thread_to_tls, old_thread);
3960 mono_g_hash_table_remove (tid_to_thread, (gpointer)tid);
3961 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
3962 mono_loader_unlock ();
3966 tls = mono_native_tls_get_value (debugger_tls_id);
3967 g_assert (!tls);
3968 // FIXME: Free this somewhere
3969 tls = g_new0 (DebuggerTlsData, 1);
3970 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread);
3971 tls->thread = thread;
3972 mono_native_tls_set_value (debugger_tls_id, tls);
3974 DEBUG (1, fprintf (log_file, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
3976 mono_loader_lock ();
3977 mono_g_hash_table_insert (thread_to_tls, thread, tls);
3978 mono_g_hash_table_insert (tid_to_thread, (gpointer)tid, thread);
3979 mono_g_hash_table_insert (tid_to_thread_obj, (gpointer)tid, mono_thread_current ());
3980 mono_loader_unlock ();
3982 process_profiler_event (EVENT_KIND_THREAD_START, thread);
3985 * suspend_vm () could have missed this thread, so wait for a resume.
3987 suspend_current ();
3990 static void
3991 thread_end (MonoProfiler *prof, uintptr_t tid)
3993 MonoInternalThread *thread;
3994 DebuggerTlsData *tls = NULL;
3996 mono_loader_lock ();
3997 thread = mono_g_hash_table_lookup (tid_to_thread, (gpointer)tid);
3998 if (thread) {
3999 mono_g_hash_table_remove (tid_to_thread_obj, (gpointer)tid);
4000 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4001 if (tls) {
4002 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
4003 tls->terminated = TRUE;
4004 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
4005 MONO_GC_UNREGISTER_ROOT (tls->thread);
4006 tls->thread = NULL;
4009 mono_loader_unlock ();
4011 /* We might be called for threads started before we registered the start callback */
4012 if (thread) {
4013 DEBUG (1, fprintf (log_file, "[%p] Thread terminated, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls));
4014 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
4018 static void
4019 appdomain_load (MonoProfiler *prof, MonoDomain *domain, int result)
4021 mono_loader_lock ();
4022 g_hash_table_insert (domains, domain, domain);
4023 mono_loader_unlock ();
4025 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
4028 static void
4029 appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain)
4031 DebuggerTlsData *tls;
4034 * Remember the currently unloading appdomain as it is needed to generate
4035 * proper ids for unloading assemblies.
4037 tls = mono_native_tls_get_value (debugger_tls_id);
4038 g_assert (tls);
4039 tls->domain_unloading = domain;
4042 static void
4043 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
4045 DebuggerTlsData *tls;
4047 tls = mono_native_tls_get_value (debugger_tls_id);
4048 g_assert (tls);
4049 tls->domain_unloading = NULL;
4051 clear_breakpoints_for_domain (domain);
4053 mono_loader_lock ();
4054 /* Invalidate each thread's frame stack */
4055 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
4056 mono_loader_unlock ();
4058 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
4062 * invalidate_each_thread:
4064 * A GHFunc to invalidate frames.
4065 * value must be a DebuggerTlsData*
4067 static void
4068 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
4070 invalidate_frames (value);
4073 static void
4074 assembly_load (MonoProfiler *prof, MonoAssembly *assembly, int result)
4076 /* Sent later in jit_end () */
4077 dbg_lock ();
4078 g_ptr_array_add (pending_assembly_loads, assembly);
4079 dbg_unlock ();
4082 static void
4083 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
4085 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
4087 clear_event_requests_for_assembly (assembly);
4088 clear_types_for_assembly (assembly);
4091 static void
4092 start_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
4094 #if defined(HOST_WIN32) && !defined(__GNUC__)
4095 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
4096 #else
4097 gpointer stackptr = __builtin_frame_address (1);
4098 #endif
4099 MonoInternalThread *thread = mono_thread_internal_current ();
4100 DebuggerTlsData *tls;
4102 mono_loader_lock ();
4104 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
4105 /* Could be the debugger thread with assembly/type load hooks */
4106 if (tls)
4107 tls->invoke_addr = stackptr;
4109 mono_loader_unlock ();
4112 static void
4113 end_runtime_invoke (MonoProfiler *prof, MonoMethod *method)
4115 int i;
4116 #if defined(HOST_WIN32) && !defined(__GNUC__)
4117 gpointer stackptr = ((guint64)_AddressOfReturnAddress () - sizeof (void*));
4118 #else
4119 gpointer stackptr = __builtin_frame_address (1);
4120 #endif
4122 if (!embedding || ss_req == NULL || stackptr != ss_invoke_addr || ss_req->thread != mono_thread_internal_current ())
4123 return;
4126 * We need to stop single stepping when exiting a runtime invoke, since if it is
4127 * a step out, it may return to native code, and thus never end.
4129 mono_loader_lock ();
4130 ss_invoke_addr = NULL;
4132 for (i = 0; i < event_requests->len; ++i) {
4133 EventRequest *req = g_ptr_array_index (event_requests, i);
4135 if (req->event_kind == EVENT_KIND_STEP) {
4136 ss_destroy (req->info);
4137 g_ptr_array_remove_index_fast (event_requests, i);
4138 g_free (req);
4139 break;
4142 mono_loader_unlock ();
4145 static void
4146 send_type_load (MonoClass *klass)
4148 gboolean type_load = FALSE;
4149 MonoDomain *domain = mono_domain_get ();
4150 AgentDomainInfo *info = NULL;
4152 mono_loader_lock ();
4153 mono_domain_lock (domain);
4155 info = get_agent_domain_info (domain);
4157 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
4158 type_load = TRUE;
4159 g_hash_table_insert (info->loaded_classes, klass, klass);
4162 mono_domain_unlock (domain);
4163 mono_loader_unlock ();
4164 if (type_load)
4165 emit_type_load (klass, klass, NULL);
4169 * Emit load events for all types currently loaded in the domain.
4170 * Takes the loader and domain locks.
4171 * user_data is unused.
4173 static void
4174 send_types_for_domain (MonoDomain *domain, void *user_data)
4176 AgentDomainInfo *info = NULL;
4178 mono_loader_lock ();
4179 mono_domain_lock (domain);
4180 info = get_agent_domain_info (domain);
4181 g_assert (info);
4182 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4183 mono_domain_unlock (domain);
4184 mono_loader_unlock ();
4187 static void
4188 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo, int result)
4191 * We emit type load events when the first method of the type is JITted,
4192 * since the class load profiler callbacks might be called with the
4193 * loader lock held. They could also occur in the debugger thread.
4194 * Same for assembly load events.
4196 while (TRUE) {
4197 MonoAssembly *assembly = NULL;
4199 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4200 dbg_lock ();
4201 if (pending_assembly_loads->len > 0) {
4202 assembly = g_ptr_array_index (pending_assembly_loads, 0);
4203 g_ptr_array_remove_index (pending_assembly_loads, 0);
4205 dbg_unlock ();
4207 if (assembly) {
4208 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4209 } else {
4210 break;
4214 send_type_load (method->klass);
4216 if (!result)
4217 add_pending_breakpoints (method, jinfo);
4221 * BREAKPOINTS/SINGLE STEPPING
4225 * Contains information about an inserted breakpoint.
4227 typedef struct {
4228 long il_offset, native_offset;
4229 guint8 *ip;
4230 MonoJitInfo *ji;
4231 MonoDomain *domain;
4232 SeqPoint *sp;
4233 } BreakpointInstance;
4236 * Contains generic information about a breakpoint.
4238 typedef struct {
4240 * The method where the breakpoint is placed. Can be NULL in which case it
4241 * is inserted into every method. This is used to implement method entry/
4242 * exit events. Can be a generic method definition, in which case the
4243 * breakpoint is inserted into every instance.
4245 MonoMethod *method;
4246 long il_offset;
4247 EventRequest *req;
4249 * A list of BreakpointInstance structures describing where the breakpoint
4250 * was inserted. There could be more than one because of
4251 * generics/appdomains/method entry/exit.
4253 GPtrArray *children;
4254 } MonoBreakpoint;
4256 /* List of breakpoints */
4257 static GPtrArray *breakpoints;
4258 /* Maps breakpoint locations to the number of breakpoints at that location */
4259 static GHashTable *bp_locs;
4261 static void
4262 breakpoints_init (void)
4264 breakpoints = g_ptr_array_new ();
4265 bp_locs = g_hash_table_new (NULL, NULL);
4269 * insert_breakpoint:
4271 * Insert the breakpoint described by BP into the method described by
4272 * JI.
4274 static void
4275 insert_breakpoint (MonoSeqPointInfo *seq_points, MonoDomain *domain, MonoJitInfo *ji, MonoBreakpoint *bp, MonoError *error)
4277 int i, count;
4278 BreakpointInstance *inst;
4279 SeqPoint *sp = NULL;
4281 if (error)
4282 mono_error_init (error);
4284 for (i = 0; i < seq_points->len; ++i) {
4285 sp = &seq_points->seq_points [i];
4287 if (sp->il_offset == bp->il_offset)
4288 break;
4291 if (i == seq_points->len) {
4293 * The set of IL offsets with seq points doesn't completely match the
4294 * info returned by CMD_METHOD_GET_DEBUG_INFO (#407).
4296 for (i = 0; i < seq_points->len; ++i) {
4297 sp = &seq_points->seq_points [i];
4299 if (sp->il_offset != METHOD_ENTRY_IL_OFFSET && sp->il_offset != METHOD_EXIT_IL_OFFSET && sp->il_offset + 1 == bp->il_offset)
4300 break;
4304 if (i == seq_points->len) {
4305 char *s = g_strdup_printf ("Unable to insert breakpoint at %s:%d, seq_points=%d\n", mono_method_full_name (jinfo_get_method (ji), TRUE), bp->il_offset, seq_points->len);
4307 for (i = 0; i < seq_points->len; ++i)
4308 DEBUG (1, fprintf (log_file, "%d\n", seq_points->seq_points [i].il_offset));
4310 if (error) {
4311 mono_error_set_error (error, MONO_ERROR_GENERIC, "%s", s);
4312 g_warning ("%s", s);
4313 g_free (s);
4314 return;
4315 } else {
4316 g_warning ("%s", s);
4317 g_free (s);
4318 return;
4322 inst = g_new0 (BreakpointInstance, 1);
4323 inst->sp = sp;
4324 inst->native_offset = sp->native_offset;
4325 inst->ip = (guint8*)ji->code_start + sp->native_offset;
4326 inst->ji = ji;
4327 inst->domain = domain;
4329 mono_loader_lock ();
4331 g_ptr_array_add (bp->children, inst);
4333 mono_loader_unlock ();
4335 dbg_lock ();
4336 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, inst->ip));
4337 g_hash_table_insert (bp_locs, inst->ip, GINT_TO_POINTER (count + 1));
4338 dbg_unlock ();
4340 if (sp->native_offset == SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4341 DEBUG (1, fprintf (log_file, "[dbg] Attempting to insert seq point at dead IL offset %d, ignoring.\n", (int)bp->il_offset));
4342 } else if (count == 0) {
4343 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4344 mono_arch_set_breakpoint (ji, inst->ip);
4345 #else
4346 NOT_IMPLEMENTED;
4347 #endif
4350 DEBUG(1, fprintf (log_file, "[dbg] Inserted breakpoint at %s:0x%x [%p](%d).\n", mono_method_full_name (jinfo_get_method (ji), TRUE), (int)sp->il_offset, inst->ip, count));
4353 static void
4354 remove_breakpoint (BreakpointInstance *inst)
4356 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
4357 int count;
4358 MonoJitInfo *ji = inst->ji;
4359 guint8 *ip = inst->ip;
4361 dbg_lock ();
4362 count = GPOINTER_TO_INT (g_hash_table_lookup (bp_locs, ip));
4363 g_hash_table_insert (bp_locs, ip, GINT_TO_POINTER (count - 1));
4364 dbg_unlock ();
4366 g_assert (count > 0);
4368 if (count == 1 && inst->native_offset != SEQ_POINT_NATIVE_OFFSET_DEAD_CODE) {
4369 mono_arch_clear_breakpoint (ji, ip);
4370 DEBUG(1, fprintf (log_file, "[dbg] Clear breakpoint at %s [%p].\n", mono_method_full_name (jinfo_get_method (ji), TRUE), ip));
4372 #else
4373 NOT_IMPLEMENTED;
4374 #endif
4377 static inline gboolean
4378 bp_matches_method (MonoBreakpoint *bp, MonoMethod *method)
4380 int i;
4382 if (!bp->method)
4383 return TRUE;
4384 if (method == bp->method)
4385 return TRUE;
4386 if (method->is_inflated && ((MonoMethodInflated*)method)->declaring == bp->method)
4387 return TRUE;
4389 if (bp->method->is_inflated && method->is_inflated) {
4390 MonoMethodInflated *bpimethod = (MonoMethodInflated*)bp->method;
4391 MonoMethodInflated *imethod = (MonoMethodInflated*)method;
4393 /* Open generic methods should match closed generic methods of the same class */
4394 if (bpimethod->declaring == imethod->declaring && bpimethod->context.class_inst == imethod->context.class_inst && bpimethod->context.method_inst && bpimethod->context.method_inst->is_open) {
4395 for (i = 0; i < bpimethod->context.method_inst->type_argc; ++i) {
4396 MonoType *t1 = bpimethod->context.method_inst->type_argv [i];
4398 /* FIXME: Handle !mvar */
4399 if (t1->type != MONO_TYPE_MVAR)
4400 return FALSE;
4402 return TRUE;
4406 return FALSE;
4410 * add_pending_breakpoints:
4412 * Insert pending breakpoints into the newly JITted method METHOD.
4414 static void
4415 add_pending_breakpoints (MonoMethod *method, MonoJitInfo *ji)
4417 int i, j;
4418 MonoSeqPointInfo *seq_points;
4419 MonoDomain *domain;
4420 MonoMethod *jmethod;
4422 if (!breakpoints)
4423 return;
4425 domain = mono_domain_get ();
4427 mono_loader_lock ();
4429 for (i = 0; i < breakpoints->len; ++i) {
4430 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4431 gboolean found = FALSE;
4433 if (!bp_matches_method (bp, method))
4434 continue;
4436 for (j = 0; j < bp->children->len; ++j) {
4437 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4439 if (inst->ji == ji)
4440 found = TRUE;
4443 if (!found) {
4444 jmethod = jinfo_get_method (ji);
4445 mono_domain_lock (domain);
4446 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, jmethod);
4447 if (!seq_points && jmethod->is_inflated)
4448 seq_points = g_hash_table_lookup (domain_jit_info (domain)->seq_points, mono_method_get_declaring_generic_method (jmethod));
4449 mono_domain_unlock (domain);
4450 if (!seq_points)
4451 /* Could be AOT code */
4452 continue;
4453 g_assert (seq_points);
4455 insert_breakpoint (seq_points, domain, ji, bp, NULL);
4459 mono_loader_unlock ();
4462 static void
4463 set_bp_in_method (MonoDomain *domain, MonoMethod *method, MonoSeqPointInfo *seq_points, MonoBreakpoint *bp, MonoError *error)
4465 gpointer code;
4466 MonoJitInfo *ji;
4468 if (error)
4469 mono_error_init (error);
4471 code = mono_jit_find_compiled_method_with_jit_info (domain, method, &ji);
4472 if (!code) {
4473 /* Might be AOTed code */
4474 code = mono_aot_get_method (domain, method);
4475 g_assert (code);
4476 ji = mono_jit_info_table_find (domain, code);
4477 g_assert (ji);
4479 g_assert (code);
4481 insert_breakpoint (seq_points, domain, ji, bp, error);
4484 static void
4485 clear_breakpoint (MonoBreakpoint *bp);
4488 * set_breakpoint:
4490 * Set a breakpoint at IL_OFFSET in METHOD.
4491 * METHOD can be NULL, in which case a breakpoint is placed in all methods.
4492 * METHOD can also be a generic method definition, in which case a breakpoint
4493 * is placed in all instances of the method.
4494 * If ERROR is non-NULL, then it is set and NULL is returnd if some breakpoints couldn't be
4495 * inserted.
4497 static MonoBreakpoint*
4498 set_breakpoint (MonoMethod *method, long il_offset, EventRequest *req, MonoError *error)
4500 MonoBreakpoint *bp;
4501 GHashTableIter iter, iter2;
4502 MonoDomain *domain;
4503 MonoMethod *m;
4504 MonoSeqPointInfo *seq_points;
4506 if (error)
4507 mono_error_init (error);
4509 // FIXME:
4510 // - suspend/resume the vm to prevent code patching problems
4511 // - multiple breakpoints on the same location
4512 // - dynamic methods
4513 // - races
4515 bp = g_new0 (MonoBreakpoint, 1);
4516 bp->method = method;
4517 bp->il_offset = il_offset;
4518 bp->req = req;
4519 bp->children = g_ptr_array_new ();
4521 DEBUG(1, fprintf (log_file, "[dbg] Setting %sbreakpoint at %s:0x%x.\n", (req->event_kind == EVENT_KIND_STEP) ? "single step " : "", method ? mono_method_full_name (method, TRUE) : "<all>", (int)il_offset));
4523 mono_loader_lock ();
4525 g_hash_table_iter_init (&iter, domains);
4526 while (g_hash_table_iter_next (&iter, (void**)&domain, NULL)) {
4527 mono_domain_lock (domain);
4529 g_hash_table_iter_init (&iter2, domain_jit_info (domain)->seq_points);
4530 while (g_hash_table_iter_next (&iter2, (void**)&m, (void**)&seq_points)) {
4531 if (bp_matches_method (bp, m))
4532 set_bp_in_method (domain, m, seq_points, bp, error);
4535 mono_domain_unlock (domain);
4538 mono_loader_unlock ();
4540 mono_loader_lock ();
4541 g_ptr_array_add (breakpoints, bp);
4542 mono_loader_unlock ();
4544 if (error && !mono_error_ok (error)) {
4545 clear_breakpoint (bp);
4546 return NULL;
4549 return bp;
4552 static void
4553 clear_breakpoint (MonoBreakpoint *bp)
4555 int i;
4557 // FIXME: locking, races
4558 for (i = 0; i < bp->children->len; ++i) {
4559 BreakpointInstance *inst = g_ptr_array_index (bp->children, i);
4561 remove_breakpoint (inst);
4563 g_free (inst);
4566 mono_loader_lock ();
4567 g_ptr_array_remove (breakpoints, bp);
4568 mono_loader_unlock ();
4570 g_ptr_array_free (bp->children, TRUE);
4571 g_free (bp);
4574 static void
4575 breakpoints_cleanup (void)
4577 int i;
4579 mono_loader_lock ();
4580 i = 0;
4581 while (i < event_requests->len) {
4582 EventRequest *req = g_ptr_array_index (event_requests, i);
4584 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4585 clear_breakpoint (req->info);
4586 g_ptr_array_remove_index_fast (event_requests, i);
4587 g_free (req);
4588 } else {
4589 i ++;
4593 for (i = 0; i < breakpoints->len; ++i)
4594 g_free (g_ptr_array_index (breakpoints, i));
4596 g_ptr_array_free (breakpoints, TRUE);
4597 g_hash_table_destroy (bp_locs);
4599 breakpoints = NULL;
4600 bp_locs = NULL;
4602 mono_loader_unlock ();
4606 * clear_breakpoints_for_domain:
4608 * Clear breakpoint instances which reference DOMAIN.
4610 static void
4611 clear_breakpoints_for_domain (MonoDomain *domain)
4613 int i, j;
4615 /* This could be called after shutdown */
4616 if (!breakpoints)
4617 return;
4619 mono_loader_lock ();
4620 for (i = 0; i < breakpoints->len; ++i) {
4621 MonoBreakpoint *bp = g_ptr_array_index (breakpoints, i);
4623 j = 0;
4624 while (j < bp->children->len) {
4625 BreakpointInstance *inst = g_ptr_array_index (bp->children, j);
4627 if (inst->domain == domain) {
4628 remove_breakpoint (inst);
4630 g_free (inst);
4632 g_ptr_array_remove_index_fast (bp->children, j);
4633 } else {
4634 j ++;
4638 mono_loader_unlock ();
4642 * ss_update:
4644 * Return FALSE if single stepping needs to continue.
4646 static gboolean
4647 ss_update (SingleStepReq *req, MonoJitInfo *ji, SeqPoint *sp, DebuggerTlsData *tls, MonoContext *ctx)
4649 MonoDebugMethodInfo *minfo;
4650 MonoDebugSourceLocation *loc = NULL;
4651 gboolean hit = TRUE;
4652 MonoMethod *method;
4654 if (req->depth == STEP_DEPTH_OVER && (sp->flags & MONO_SEQ_POINT_FLAG_NONEMPTY_STACK)) {
4656 * These seq points are inserted by the JIT after calls, step over needs to skip them.
4658 DEBUG (1, fprintf (log_file, "[%p] Seq point at nonempty stack %x while stepping over, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset));
4659 return FALSE;
4662 if (req->depth == STEP_DEPTH_OVER && hit) {
4663 if (!tls->context.valid)
4664 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4665 compute_frame_info (tls->thread, tls);
4666 if (req->nframes && tls->frame_count && tls->frame_count > req->nframes) {
4667 /* Hit the breakpoint in a recursive call */
4668 DEBUG (1, fprintf (log_file, "[%p] Breakpoint at lower frame while stepping over, continuing single stepping.\n", (gpointer)GetCurrentThreadId ()));
4669 return FALSE;
4673 if (req->size != STEP_SIZE_LINE)
4674 return TRUE;
4676 /* Have to check whenever a different source line was reached */
4677 method = jinfo_get_method (ji);
4678 minfo = mono_debug_lookup_method (method);
4680 if (minfo)
4681 loc = mono_debug_symfile_lookup_location (minfo, sp->il_offset);
4683 if (!loc || (loc && method == ss_req->last_method && loc->row == ss_req->last_line)) {
4684 /* Have to continue single stepping */
4685 if (!loc)
4686 DEBUG(1, fprintf (log_file, "[%p] No line number info for il offset %x, continuing single stepping.\n", (gpointer)GetCurrentThreadId (), sp->il_offset));
4687 else
4688 DEBUG(1, fprintf (log_file, "[%p] Same source line (%d), continuing single stepping.\n", (gpointer)GetCurrentThreadId (), loc->row));
4689 hit = FALSE;
4692 if (loc) {
4693 ss_req->last_method = method;
4694 ss_req->last_line = loc->row;
4695 mono_debug_free_source_location (loc);
4698 return hit;
4701 static gboolean
4702 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4704 return bp->method && bp->method->klass->image->assembly == assembly;
4707 static void
4708 process_breakpoint_inner (DebuggerTlsData *tls)
4710 MonoJitInfo *ji;
4711 guint8 *ip;
4712 int i, j, suspend_policy;
4713 guint32 native_offset;
4714 MonoBreakpoint *bp;
4715 BreakpointInstance *inst;
4716 GPtrArray *bp_reqs, *ss_reqs_orig, *ss_reqs;
4717 GSList *bp_events = NULL, *ss_events = NULL, *enter_leave_events = NULL;
4718 EventKind kind = EVENT_KIND_BREAKPOINT;
4719 MonoContext *ctx = &tls->restore_ctx;
4720 MonoMethod *method;
4721 MonoSeqPointInfo *info;
4722 SeqPoint *sp;
4724 // FIXME: Speed this up
4726 ip = MONO_CONTEXT_GET_IP (ctx);
4727 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, NULL);
4728 g_assert (ji);
4729 method = jinfo_get_method (ji);
4731 /* Compute the native offset of the breakpoint from the ip */
4732 native_offset = ip - (guint8*)ji->code_start;
4735 * Skip the instruction causing the breakpoint signal.
4737 mono_arch_skip_breakpoint (ctx, ji);
4739 if (method->wrapper_type || tls->disable_breakpoints)
4740 return;
4742 bp_reqs = g_ptr_array_new ();
4743 ss_reqs = g_ptr_array_new ();
4744 ss_reqs_orig = g_ptr_array_new ();
4746 mono_loader_lock ();
4749 * The ip points to the instruction causing the breakpoint event, which is after
4750 * the offset recorded in the seq point map, so find the prev seq point before ip.
4752 sp = find_prev_seq_point_for_native_offset (mono_domain_get (), method, native_offset, &info);
4753 if (!sp)
4754 no_seq_points_found (method);
4755 g_assert (sp);
4757 DEBUG(1, fprintf (log_file, "[%p] Breakpoint hit, method=%s, ip=%p, offset=0x%x, sp il offset=0x%x.\n", (gpointer)GetCurrentThreadId (), method->name, ip, native_offset, sp ? sp->il_offset : -1));
4759 bp = NULL;
4760 for (i = 0; i < breakpoints->len; ++i) {
4761 bp = g_ptr_array_index (breakpoints, i);
4763 if (!bp->method)
4764 continue;
4766 for (j = 0; j < bp->children->len; ++j) {
4767 inst = g_ptr_array_index (bp->children, j);
4768 if (inst->ji == ji && inst->sp == sp) {
4769 if (bp->req->event_kind == EVENT_KIND_STEP) {
4770 g_ptr_array_add (ss_reqs_orig, bp->req);
4771 } else {
4772 g_ptr_array_add (bp_reqs, bp->req);
4777 if (bp_reqs->len == 0 && ss_reqs_orig->len == 0) {
4778 /* Maybe a method entry/exit event */
4779 if (sp->il_offset == METHOD_ENTRY_IL_OFFSET)
4780 kind = EVENT_KIND_METHOD_ENTRY;
4781 else if (sp->il_offset == METHOD_EXIT_IL_OFFSET)
4782 kind = EVENT_KIND_METHOD_EXIT;
4785 /* Process single step requests */
4786 for (i = 0; i < ss_reqs_orig->len; ++i) {
4787 EventRequest *req = g_ptr_array_index (ss_reqs_orig, i);
4788 SingleStepReq *ss_req = req->info;
4789 gboolean hit;
4791 if (mono_thread_internal_current () != ss_req->thread)
4792 continue;
4794 hit = ss_update (ss_req, ji, sp, tls, ctx);
4795 if (hit)
4796 g_ptr_array_add (ss_reqs, req);
4798 /* Start single stepping again from the current sequence point */
4799 ss_start (ss_req, method, sp, info, ctx, tls, FALSE);
4802 if (ss_reqs->len > 0)
4803 ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4804 if (bp_reqs->len > 0)
4805 bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4806 if (kind != EVENT_KIND_BREAKPOINT)
4807 enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4809 mono_loader_unlock ();
4811 g_ptr_array_free (bp_reqs, TRUE);
4812 g_ptr_array_free (ss_reqs, TRUE);
4815 * FIXME: The first event will suspend, so the second will only be sent after the
4816 * resume.
4818 if (ss_events)
4819 process_event (EVENT_KIND_STEP, method, 0, ctx, ss_events, suspend_policy);
4820 if (bp_events)
4821 process_event (kind, method, 0, ctx, bp_events, suspend_policy);
4822 if (enter_leave_events)
4823 process_event (kind, method, 0, ctx, enter_leave_events, suspend_policy);
4826 /* Process a breakpoint/single step event after resuming from a signal handler */
4827 static void
4828 process_signal_event (void (*func) (DebuggerTlsData*))
4830 DebuggerTlsData *tls;
4831 MonoContext orig_restore_ctx, ctx;
4833 tls = mono_native_tls_get_value (debugger_tls_id);
4834 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4835 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
4836 memcpy (&tls->restore_ctx, &tls->handler_ctx, sizeof (MonoContext));
4838 func (tls);
4840 /* This is called when resuming from a signal handler, so it shouldn't return */
4841 memcpy (&ctx, &tls->restore_ctx, sizeof (MonoContext));
4842 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
4843 mono_restore_context (&ctx);
4844 g_assert_not_reached ();
4847 static void
4848 process_breakpoint (void)
4850 process_signal_event (process_breakpoint_inner);
4853 static void
4854 resume_from_signal_handler (void *sigctx, void *func)
4856 DebuggerTlsData *tls;
4857 MonoContext ctx;
4859 /* Save the original context in TLS */
4860 // FIXME: This might not work on an altstack ?
4861 tls = mono_native_tls_get_value (debugger_tls_id);
4862 if (!tls)
4863 fprintf (stderr, "Thread %p is not attached to the JIT.\n", (gpointer)GetCurrentThreadId ());
4864 g_assert (tls);
4866 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4867 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4868 // clob:c could be added to op_seq_point.
4870 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
4871 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4872 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4873 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4874 #else
4875 MONO_CONTEXT_SET_IP (&ctx, func);
4876 #endif
4877 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
4879 #ifdef PPC_USES_FUNCTION_DESCRIPTOR
4880 mono_ppc_set_func_into_sigctx (sigctx, func);
4881 #endif
4884 void
4885 mono_debugger_agent_breakpoint_hit (void *sigctx)
4888 * We are called from a signal handler, and running code there causes all kinds of
4889 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4890 * So set up the signal context to return to the real breakpoint handler function.
4892 resume_from_signal_handler (sigctx, process_breakpoint);
4895 static gboolean
4896 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer data)
4898 if (frame->managed) {
4899 *(MonoContext*)data = *ctx;
4901 return TRUE;
4902 } else {
4903 return FALSE;
4908 * Called by System.Diagnostics.Debugger:Break ().
4910 void
4911 mono_debugger_agent_user_break (void)
4913 if (agent_config.enabled) {
4914 MonoContext ctx;
4915 int suspend_policy;
4916 GSList *events;
4918 /* Obtain a context */
4919 MONO_CONTEXT_SET_IP (&ctx, NULL);
4920 mono_walk_stack_with_ctx (user_break_cb, NULL, 0, &ctx);
4921 g_assert (MONO_CONTEXT_GET_IP (&ctx) != NULL);
4923 mono_loader_lock ();
4924 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4925 mono_loader_unlock ();
4927 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4928 } else {
4929 G_BREAKPOINT ();
4933 static const char*
4934 ss_depth_to_string (StepDepth depth)
4936 switch (depth) {
4937 case STEP_DEPTH_OVER:
4938 return "over";
4939 case STEP_DEPTH_OUT:
4940 return "out";
4941 case STEP_DEPTH_INTO:
4942 return "into";
4943 default:
4944 g_assert_not_reached ();
4945 return NULL;
4949 static void
4950 process_single_step_inner (DebuggerTlsData *tls)
4952 MonoJitInfo *ji;
4953 guint8 *ip;
4954 GPtrArray *reqs;
4955 int il_offset, suspend_policy;
4956 MonoDomain *domain;
4957 GSList *events;
4958 MonoContext *ctx = &tls->restore_ctx;
4959 MonoMethod *method;
4960 SeqPoint *sp;
4961 MonoSeqPointInfo *info;
4963 ip = MONO_CONTEXT_GET_IP (ctx);
4965 /* Skip the instruction causing the single step */
4966 mono_arch_skip_single_step (ctx);
4968 if (suspend_count > 0) {
4969 process_suspend (tls, ctx);
4970 return;
4973 if (!ss_req)
4974 // FIXME: A suspend race
4975 return;
4977 if (mono_thread_internal_current () != ss_req->thread)
4978 return;
4980 if (log_level > 0) {
4981 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4983 DEBUG (1, fprintf (log_file, "[%p] Single step event (depth=%s) at %s (%p), sp %p, last sp %p\n", (gpointer)GetCurrentThreadId (), ss_depth_to_string (ss_req->depth), mono_method_full_name (jinfo_get_method (ji), TRUE), MONO_CONTEXT_GET_IP (ctx), MONO_CONTEXT_GET_SP (ctx), ss_req->last_sp));
4986 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, &domain);
4987 g_assert (ji);
4988 method = jinfo_get_method (ji);
4989 g_assert (method);
4991 if (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD)
4992 return;
4995 * FIXME:
4996 * Stopping in memset makes half-initialized vtypes visible.
4997 * Stopping in memcpy makes half-copied vtypes visible.
4999 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
5000 return;
5003 * The ip points to the instruction causing the single step event, which is before
5004 * the offset recorded in the seq point map, so find the next seq point after ip.
5006 sp = find_next_seq_point_for_native_offset (domain, method, (guint8*)ip - (guint8*)ji->code_start, &info);
5007 if (!sp)
5008 return;
5009 il_offset = sp->il_offset;
5011 if (!ss_update (ss_req, ji, sp, tls, ctx))
5012 return;
5014 /* Start single stepping again from the current sequence point */
5015 ss_start (ss_req, method, sp, info, ctx, tls, FALSE);
5017 if ((ss_req->filter & STEP_FILTER_STATIC_CTOR) &&
5018 (method->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
5019 !strcmp (method->name, ".cctor"))
5020 return;
5022 // FIXME: Has to lock earlier
5024 reqs = g_ptr_array_new ();
5026 mono_loader_lock ();
5028 g_ptr_array_add (reqs, ss_req->req);
5030 events = create_event_list (EVENT_KIND_STEP, reqs, ji, NULL, &suspend_policy);
5032 g_ptr_array_free (reqs, TRUE);
5034 mono_loader_unlock ();
5036 process_event (EVENT_KIND_STEP, jinfo_get_method (ji), il_offset, ctx, events, suspend_policy);
5039 static void
5040 process_single_step (void)
5042 process_signal_event (process_single_step_inner);
5046 * mono_debugger_agent_single_step_event:
5048 * Called from a signal handler to handle a single step event.
5050 void
5051 mono_debugger_agent_single_step_event (void *sigctx)
5053 /* Resume to process_single_step through the signal context */
5055 // FIXME: Since step out/over is implemented using step in, the step in case should
5056 // be as fast as possible. Move the relevant code from process_single_step_inner ()
5057 // here
5059 if (GetCurrentThreadId () == debugger_thread_id) {
5061 * This could happen despite our best effors when the runtime calls
5062 * assembly/type resolve hooks.
5063 * FIXME: Breakpoints too.
5065 MonoContext ctx;
5067 mono_arch_sigctx_to_monoctx (sigctx, &ctx);
5068 mono_arch_skip_single_step (&ctx);
5069 mono_arch_monoctx_to_sigctx (&ctx, sigctx);
5070 return;
5073 resume_from_signal_handler (sigctx, process_single_step);
5076 void
5077 debugger_agent_single_step_from_context (MonoContext *ctx)
5079 DebuggerTlsData *tls;
5080 MonoContext orig_restore_ctx;
5082 tls = mono_native_tls_get_value (debugger_tls_id);
5083 g_assert (tls);
5085 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
5086 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
5087 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
5089 process_single_step_inner (tls);
5091 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
5092 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
5095 void
5096 debugger_agent_breakpoint_from_context (MonoContext *ctx)
5098 DebuggerTlsData *tls;
5099 MonoContext orig_restore_ctx;
5101 tls = mono_native_tls_get_value (debugger_tls_id);
5102 g_assert (tls);
5103 memcpy (&orig_restore_ctx, &tls->restore_ctx, sizeof (MonoContext));
5104 memcpy (&tls->restore_ctx, ctx, sizeof (MonoContext));
5106 process_breakpoint_inner (tls);
5108 memcpy (ctx, &tls->restore_ctx, sizeof (MonoContext));
5109 memcpy (&tls->restore_ctx, &orig_restore_ctx, sizeof (MonoContext));
5113 * start_single_stepping:
5115 * Turn on single stepping. Can be called multiple times, for example,
5116 * by a single step event request + a suspend.
5118 static void
5119 start_single_stepping (void)
5121 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5122 int val = InterlockedIncrement (&ss_count);
5124 if (val == 1)
5125 mono_arch_start_single_stepping ();
5127 if (ss_req != NULL && ss_invoke_addr == NULL) {
5128 DebuggerTlsData *tls;
5130 mono_loader_lock ();
5132 tls = mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
5133 ss_invoke_addr = tls->invoke_addr;
5135 mono_loader_unlock ();
5137 #else
5138 g_assert_not_reached ();
5139 #endif
5142 static void
5143 stop_single_stepping (void)
5145 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
5146 int val = InterlockedDecrement (&ss_count);
5148 if (val == 0)
5149 mono_arch_stop_single_stepping ();
5150 if (ss_req != NULL)
5151 ss_invoke_addr = NULL;
5152 #else
5153 g_assert_not_reached ();
5154 #endif
5158 * ss_stop:
5160 * Stop the single stepping operation given by SS_REQ.
5162 static void
5163 ss_stop (SingleStepReq *ss_req)
5165 if (ss_req->bps) {
5166 GSList *l;
5168 for (l = ss_req->bps; l; l = l->next) {
5169 clear_breakpoint (l->data);
5171 g_slist_free (ss_req->bps);
5172 ss_req->bps = NULL;
5175 if (ss_req->global) {
5176 stop_single_stepping ();
5177 ss_req->global = FALSE;
5182 * ss_start:
5184 * Start the single stepping operation given by SS_REQ from the sequence point SP.
5185 * If CTX is not set, then this can target any thread. If CTX is set, then TLS should
5186 * belong to the same thread as CTX.
5188 static void
5189 ss_start (SingleStepReq *ss_req, MonoMethod *method, SeqPoint *sp, MonoSeqPointInfo *info, MonoContext *ctx, DebuggerTlsData *tls, gboolean step_to_catch)
5191 int i, j, frame_index;
5192 SeqPoint *next_sp;
5193 MonoBreakpoint *bp;
5194 gboolean enable_global = FALSE;
5196 /* Stop the previous operation */
5197 ss_stop (ss_req);
5200 * Implement single stepping using breakpoints if possible.
5202 if (step_to_catch) {
5203 bp = set_breakpoint (method, sp->il_offset, ss_req->req, NULL);
5204 ss_req->bps = g_slist_append (ss_req->bps, bp);
5205 } else {
5206 frame_index = 1;
5208 if ((!sp || sp->next_len == 0 || ss_req->depth == STEP_DEPTH_OUT || ss_req->depth == STEP_DEPTH_OVER) && ctx) {
5209 /* Need parent frames */
5210 if (!tls->context.valid)
5211 mono_thread_state_init_from_monoctx (&tls->context, ctx);
5212 compute_frame_info (tls->thread, tls);
5216 * Find the first sequence point in the current or in a previous frame which
5217 * is not the last in its method.
5219 if (ss_req->depth == STEP_DEPTH_OUT) {
5220 /* Ignore seq points in current method */
5221 while (frame_index < tls->frame_count) {
5222 StackFrame *frame = tls->frames [frame_index];
5224 method = frame->method;
5225 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5226 frame_index ++;
5227 if (sp && sp->next_len != 0)
5228 break;
5230 // There could be method calls before the next seq point in the caller when using nested calls
5231 //enable_global = TRUE;
5232 } else {
5233 if (sp && sp->next_len == 0) {
5234 sp = NULL;
5235 while (frame_index < tls->frame_count) {
5236 StackFrame *frame = tls->frames [frame_index];
5238 method = frame->method;
5239 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5240 if (sp && sp->next_len != 0)
5241 break;
5242 sp = NULL;
5243 frame_index ++;
5248 if (sp && sp->next_len > 0) {
5249 for (i = 0; i < sp->next_len; ++i) {
5250 next_sp = &info->seq_points [sp->next [i]];
5252 bp = set_breakpoint (method, next_sp->il_offset, ss_req->req, NULL);
5253 ss_req->bps = g_slist_append (ss_req->bps, bp);
5257 if (ss_req->depth == STEP_DEPTH_OVER) {
5258 if (ss_req->nframes == 0)
5259 ss_req->nframes = tls->frame_count;
5260 /* Need to stop in catch clauses as well */
5261 for (i = 0; i < tls->frame_count; ++i) {
5262 StackFrame *frame = tls->frames [i];
5264 if (frame->ji) {
5265 MonoJitInfo *jinfo = frame->ji;
5266 for (j = 0; j < jinfo->num_clauses; ++j) {
5267 MonoJitExceptionInfo *ei = &jinfo->clauses [j];
5269 sp = find_next_seq_point_for_native_offset (frame->domain, frame->method, (char*)ei->handler_start - (char*)jinfo->code_start, NULL);
5270 if (sp) {
5271 bp = set_breakpoint (frame->method, sp->il_offset, ss_req->req, NULL);
5272 ss_req->bps = g_slist_append (ss_req->bps, bp);
5280 if (ss_req->depth == STEP_DEPTH_INTO) {
5281 /* Enable global stepping so we stop at method entry too */
5282 enable_global = TRUE;
5286 * The ctx/frame info computed above will become invalid when we continue.
5288 tls->context.valid = FALSE;
5289 tls->async_state.valid = FALSE;
5290 invalidate_frames (tls);
5293 if (enable_global) {
5294 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
5295 ss_req->global = TRUE;
5296 start_single_stepping ();
5297 } else if (!ss_req->bps) {
5298 DEBUG (1, fprintf (log_file, "[dbg] Turning on global single stepping.\n"));
5299 ss_req->global = TRUE;
5300 start_single_stepping ();
5301 } else {
5302 ss_req->global = FALSE;
5307 * Start single stepping of thread THREAD
5309 static ErrorCode
5310 ss_create (MonoInternalThread *thread, StepSize size, StepDepth depth, EventRequest *req)
5312 DebuggerTlsData *tls;
5313 MonoSeqPointInfo *info = NULL;
5314 SeqPoint *sp = NULL;
5315 MonoMethod *method = NULL;
5316 MonoDebugMethodInfo *minfo;
5317 gboolean step_to_catch = FALSE;
5319 if (suspend_count == 0)
5320 return ERR_NOT_SUSPENDED;
5322 wait_for_suspend ();
5324 // FIXME: Multiple requests
5325 if (ss_req) {
5326 DEBUG (0, fprintf (log_file, "Received a single step request while the previous one was still active.\n"));
5327 return ERR_NOT_IMPLEMENTED;
5330 DEBUG (1, fprintf (log_file, "[dbg] Starting single step of thread %p (depth=%s).\n", thread, ss_depth_to_string (depth)));
5332 ss_req = g_new0 (SingleStepReq, 1);
5333 ss_req->req = req;
5334 ss_req->thread = thread;
5335 ss_req->size = size;
5336 ss_req->depth = depth;
5337 req->info = ss_req;
5339 mono_loader_lock ();
5340 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5341 mono_loader_unlock ();
5342 g_assert (tls);
5343 g_assert (tls->context.valid);
5344 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5346 if (tls->catch_state.valid) {
5347 gboolean res;
5348 StackFrameInfo frame;
5349 MonoContext new_ctx;
5350 MonoLMF *lmf = NULL;
5353 * We are stopped at a throw site. Stepping should go to the catch site.
5356 /* Find the the jit info for the catch context */
5357 res = mono_find_jit_info_ext (tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN], thread->jit_data, NULL, &tls->catch_state.ctx, &new_ctx, NULL, &lmf, NULL, &frame);
5358 g_assert (res);
5359 g_assert (frame.type == FRAME_TYPE_MANAGED);
5362 * Find the seq point corresponding to the landing site ip, which is the first seq
5363 * point after ip.
5365 sp = find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info);
5366 if (!sp)
5367 no_seq_points_found (frame.method);
5368 g_assert (sp);
5370 method = frame.method;
5372 step_to_catch = TRUE;
5373 /* This make sure the seq point is not skipped by process_single_step () */
5374 ss_req->last_sp = NULL;
5377 if (!step_to_catch && ss_req->size == STEP_SIZE_LINE) {
5378 StackFrame *frame;
5380 /* Compute the initial line info */
5381 compute_frame_info (thread, tls);
5383 if (tls->frame_count) {
5384 frame = tls->frames [0];
5386 ss_req->last_method = frame->method;
5387 ss_req->last_line = -1;
5389 minfo = mono_debug_lookup_method (frame->method);
5390 if (minfo && frame->il_offset != -1) {
5391 MonoDebugSourceLocation *loc = mono_debug_symfile_lookup_location (minfo, frame->il_offset);
5393 if (loc) {
5394 ss_req->last_line = loc->row;
5395 g_free (loc);
5401 if (!step_to_catch) {
5402 StackFrame *frame;
5404 compute_frame_info (thread, tls);
5406 if (tls->frame_count) {
5407 frame = tls->frames [0];
5409 if (!method && frame->il_offset != -1) {
5410 /* FIXME: Sort the table and use a binary search */
5411 sp = find_prev_seq_point_for_native_offset (frame->domain, frame->method, frame->native_offset, &info);
5412 if (!sp)
5413 no_seq_points_found (frame->method);
5414 g_assert (sp);
5415 method = frame->method;
5420 ss_start (ss_req, method, sp, info, &tls->context.ctx, tls, step_to_catch);
5422 return 0;
5425 static void
5426 ss_destroy (SingleStepReq *req)
5428 // FIXME: Locking
5429 g_assert (ss_req == req);
5431 ss_stop (ss_req);
5433 g_free (ss_req);
5434 ss_req = NULL;
5437 static void
5438 ss_clear_for_assembly (SingleStepReq *req, MonoAssembly *assembly)
5440 GSList *l;
5441 gboolean found = TRUE;
5443 while (found) {
5444 found = FALSE;
5445 for (l = ss_req->bps; l; l = l->next) {
5446 if (breakpoint_matches_assembly (l->data, assembly)) {
5447 clear_breakpoint (l->data);
5448 ss_req->bps = g_slist_delete_link (ss_req->bps, l);
5449 found = TRUE;
5450 break;
5457 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5459 void
5460 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5462 int suspend_policy;
5463 GSList *events;
5464 EventInfo ei;
5466 if (!agent_config.enabled)
5467 return;
5469 mono_loader_lock ();
5470 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5471 mono_loader_unlock ();
5473 ei.level = level;
5474 ei.category = category ? mono_string_to_utf8 (category) : NULL;
5475 ei.message = message ? mono_string_to_utf8 (message) : NULL;
5477 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5479 g_free (ei.category);
5480 g_free (ei.message);
5483 gboolean
5484 mono_debugger_agent_debug_log_is_enabled (void)
5486 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5487 return agent_config.enabled;
5490 #if defined(PLATFORM_ANDROID) || defined(TARGET_ANDROID)
5491 void
5492 mono_debugger_agent_unhandled_exception (MonoException *exc)
5494 int suspend_policy;
5495 GSList *events;
5496 EventInfo ei;
5498 if (!inited)
5499 return;
5501 memset (&ei, 0, sizeof (EventInfo));
5502 ei.exc = (MonoObject*)exc;
5504 mono_loader_lock ();
5505 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5506 mono_loader_unlock ();
5508 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5510 #endif
5512 void
5513 mono_debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5514 MonoContext *catch_ctx)
5516 int i, j, suspend_policy;
5517 GSList *events;
5518 MonoJitInfo *ji, *catch_ji;
5519 EventInfo ei;
5520 DebuggerTlsData *tls = NULL;
5522 if (thread_to_tls != NULL) {
5523 MonoInternalThread *thread = mono_thread_internal_current ();
5525 mono_loader_lock ();
5526 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
5527 mono_loader_unlock ();
5529 if (tls && tls->abort_requested)
5530 return;
5531 if (tls && tls->disable_breakpoints)
5532 return;
5535 memset (&ei, 0, sizeof (EventInfo));
5537 /* Just-In-Time debugging */
5538 if (!catch_ctx) {
5539 if (agent_config.onuncaught && !inited) {
5540 finish_agent_init (FALSE);
5543 * Send an unsolicited EXCEPTION event with a dummy request id.
5545 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5546 ei.exc = (MonoObject*)exc;
5547 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5548 return;
5550 } else if (agent_config.onthrow && !inited) {
5551 GSList *l;
5552 gboolean found = FALSE;
5554 for (l = agent_config.onthrow; l; l = l->next) {
5555 char *ex_type = l->data;
5556 char *f = mono_type_full_name (&exc->object.vtable->klass->byval_arg);
5558 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5559 found = TRUE;
5561 g_free (f);
5564 if (found) {
5565 finish_agent_init (FALSE);
5568 * Send an unsolicited EXCEPTION event with a dummy request id.
5570 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5571 ei.exc = (MonoObject*)exc;
5572 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5573 return;
5577 if (!inited)
5578 return;
5580 ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5581 if (catch_ctx)
5582 catch_ji = mini_jit_info_table_find (mono_domain_get (), MONO_CONTEXT_GET_IP (catch_ctx), NULL);
5583 else
5584 catch_ji = NULL;
5586 ei.exc = (MonoObject*)exc;
5587 ei.caught = catch_ctx != NULL;
5589 mono_loader_lock ();
5591 /* Treat exceptions which are caught in non-user code as unhandled */
5592 for (i = 0; i < event_requests->len; ++i) {
5593 EventRequest *req = g_ptr_array_index (event_requests, i);
5594 if (req->event_kind != EVENT_KIND_EXCEPTION)
5595 continue;
5597 for (j = 0; j < req->nmodifiers; ++j) {
5598 Modifier *mod = &req->modifiers [j];
5600 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5601 int k;
5602 gboolean found = FALSE;
5603 MonoAssembly **assemblies = mod->data.assemblies;
5605 if (assemblies) {
5606 for (k = 0; assemblies [k]; ++k)
5607 if (assemblies [k] == jinfo_get_method (catch_ji)->klass->image->assembly)
5608 found = TRUE;
5610 if (!found)
5611 ei.caught = FALSE;
5616 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5617 mono_loader_unlock ();
5619 if (tls && ei.caught && catch_ctx) {
5620 memset (&tls->catch_state, 0, sizeof (tls->catch_state));
5621 tls->catch_state.ctx = *catch_ctx;
5622 tls->catch_state.unwind_data [MONO_UNWIND_DATA_DOMAIN] = mono_domain_get ();
5623 tls->catch_state.valid = TRUE;
5626 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5628 if (tls)
5629 tls->catch_state.valid = FALSE;
5632 void
5633 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5635 DebuggerTlsData *tls;
5637 if (!inited)
5638 return;
5640 tls = mono_native_tls_get_value (debugger_tls_id);
5641 if (!tls)
5642 return;
5645 * We're about to invoke an exception filter during the first pass of exception handling.
5647 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5648 * 'orig_ctx' is the context where the exception has been thrown.
5651 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5653 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5654 * the call site (line 37) and then continue to Main(), but it would never
5655 * include the throw site (line 32).
5657 * Since exception filters are invoked during the first pass of exception handling,
5658 * the stack frames of the throw site are still intact, so we should include them
5659 * in a stack trace.
5661 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5663 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5664 * but report the location of the 'throw' to the user.
5668 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5671 void
5672 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5674 DebuggerTlsData *tls;
5676 if (!inited)
5677 return;
5679 tls = mono_native_tls_get_value (debugger_tls_id);
5680 if (!tls)
5681 return;
5683 tls->filter_state.valid = FALSE;
5687 * buffer_add_value_full:
5689 * Add the encoding of the value at ADDR described by T to the buffer.
5690 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5691 * vtypes.
5693 static void
5694 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5695 gboolean as_vtype, GHashTable *parent_vtypes)
5697 MonoObject *obj;
5698 gboolean boxed_vtype = FALSE;
5700 if (t->byref) {
5701 if (!(*(void**)addr)) {
5702 /* This can happen with compiler generated locals */
5703 //printf ("%s\n", mono_type_full_name (t));
5704 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5705 return;
5707 g_assert (*(void**)addr);
5708 addr = *(void**)addr;
5711 if (as_vtype) {
5712 switch (t->type) {
5713 case MONO_TYPE_BOOLEAN:
5714 case MONO_TYPE_I1:
5715 case MONO_TYPE_U1:
5716 case MONO_TYPE_CHAR:
5717 case MONO_TYPE_I2:
5718 case MONO_TYPE_U2:
5719 case MONO_TYPE_I4:
5720 case MONO_TYPE_U4:
5721 case MONO_TYPE_R4:
5722 case MONO_TYPE_I8:
5723 case MONO_TYPE_U8:
5724 case MONO_TYPE_R8:
5725 case MONO_TYPE_I:
5726 case MONO_TYPE_U:
5727 case MONO_TYPE_PTR:
5728 goto handle_vtype;
5729 break;
5730 default:
5731 break;
5735 switch (t->type) {
5736 case MONO_TYPE_VOID:
5737 buffer_add_byte (buf, t->type);
5738 break;
5739 case MONO_TYPE_BOOLEAN:
5740 case MONO_TYPE_I1:
5741 case MONO_TYPE_U1:
5742 buffer_add_byte (buf, t->type);
5743 buffer_add_int (buf, *(gint8*)addr);
5744 break;
5745 case MONO_TYPE_CHAR:
5746 case MONO_TYPE_I2:
5747 case MONO_TYPE_U2:
5748 buffer_add_byte (buf, t->type);
5749 buffer_add_int (buf, *(gint16*)addr);
5750 break;
5751 case MONO_TYPE_I4:
5752 case MONO_TYPE_U4:
5753 case MONO_TYPE_R4:
5754 buffer_add_byte (buf, t->type);
5755 buffer_add_int (buf, *(gint32*)addr);
5756 break;
5757 case MONO_TYPE_I8:
5758 case MONO_TYPE_U8:
5759 case MONO_TYPE_R8:
5760 buffer_add_byte (buf, t->type);
5761 buffer_add_long (buf, *(gint64*)addr);
5762 break;
5763 case MONO_TYPE_I:
5764 case MONO_TYPE_U:
5765 /* Treat it as a vtype */
5766 goto handle_vtype;
5767 case MONO_TYPE_PTR: {
5768 gssize val = *(gssize*)addr;
5770 buffer_add_byte (buf, t->type);
5771 buffer_add_long (buf, val);
5772 break;
5774 handle_ref:
5775 case MONO_TYPE_STRING:
5776 case MONO_TYPE_SZARRAY:
5777 case MONO_TYPE_OBJECT:
5778 case MONO_TYPE_CLASS:
5779 case MONO_TYPE_ARRAY:
5780 obj = *(MonoObject**)addr;
5782 if (!obj) {
5783 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5784 } else {
5785 if (obj->vtable->klass->valuetype) {
5786 t = &obj->vtable->klass->byval_arg;
5787 addr = mono_object_unbox (obj);
5788 boxed_vtype = TRUE;
5789 goto handle_vtype;
5790 } else if (obj->vtable->klass->rank) {
5791 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5792 } else if (obj->vtable->klass->byval_arg.type == MONO_TYPE_GENERICINST) {
5793 buffer_add_byte (buf, MONO_TYPE_CLASS);
5794 } else {
5795 buffer_add_byte (buf, obj->vtable->klass->byval_arg.type);
5797 buffer_add_objid (buf, obj);
5799 break;
5800 handle_vtype:
5801 case MONO_TYPE_VALUETYPE: {
5802 int nfields;
5803 gpointer iter;
5804 MonoClassField *f;
5805 MonoClass *klass = mono_class_from_mono_type (t);
5806 int vtype_index;
5808 if (boxed_vtype) {
5810 * Handle boxed vtypes recursively referencing themselves using fields.
5812 if (!parent_vtypes)
5813 parent_vtypes = g_hash_table_new (NULL, NULL);
5814 vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
5815 if (vtype_index) {
5816 if (CHECK_PROTOCOL_VERSION (2, 33)) {
5817 buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
5818 buffer_add_int (buf, vtype_index - 1);
5819 } else {
5820 /* The client can't handle PARENT_VTYPE */
5821 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5823 break;
5824 } else {
5825 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
5829 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5830 buffer_add_byte (buf, klass->enumtype);
5831 buffer_add_typeid (buf, domain, klass);
5833 nfields = 0;
5834 iter = NULL;
5835 while ((f = mono_class_get_fields (klass, &iter))) {
5836 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5837 continue;
5838 if (mono_field_is_deleted (f))
5839 continue;
5840 nfields ++;
5842 buffer_add_int (buf, nfields);
5844 iter = NULL;
5845 while ((f = mono_class_get_fields (klass, &iter))) {
5846 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5847 continue;
5848 if (mono_field_is_deleted (f))
5849 continue;
5850 buffer_add_value_full (buf, f->type, (guint8*)addr + f->offset - sizeof (MonoObject), domain, FALSE, parent_vtypes);
5853 if (boxed_vtype) {
5854 g_hash_table_remove (parent_vtypes, addr);
5855 if (g_hash_table_size (parent_vtypes) == 0) {
5856 g_hash_table_destroy (parent_vtypes);
5857 parent_vtypes = NULL;
5860 break;
5862 case MONO_TYPE_GENERICINST:
5863 if (mono_type_generic_inst_is_valuetype (t)) {
5864 goto handle_vtype;
5865 } else {
5866 goto handle_ref;
5868 break;
5869 default:
5870 NOT_IMPLEMENTED;
5874 static void
5875 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5877 buffer_add_value_full (buf, t, addr, domain, FALSE, NULL);
5880 static gboolean
5881 obj_is_of_type (MonoObject *obj, MonoType *t)
5883 MonoClass *klass = obj->vtable->klass;
5884 if (!mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5885 if (mono_class_is_transparent_proxy (klass)) {
5886 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5887 if (mono_class_is_assignable_from (mono_class_from_mono_type (t), klass)) {
5888 return TRUE;
5891 return FALSE;
5893 return TRUE;
5896 static ErrorCode
5897 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit);
5899 static ErrorCode
5900 decode_vtype (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5902 gboolean is_enum;
5903 MonoClass *klass;
5904 MonoClassField *f;
5905 int nfields;
5906 gpointer iter = NULL;
5907 MonoDomain *d;
5908 int err;
5910 is_enum = decode_byte (buf, &buf, limit);
5911 /* Enums are sent as a normal vtype */
5912 if (is_enum)
5913 return ERR_NOT_IMPLEMENTED;
5914 klass = decode_typeid (buf, &buf, limit, &d, &err);
5915 if (err)
5916 return err;
5918 if (t && klass != mono_class_from_mono_type (t)) {
5919 char *name = mono_type_full_name (t);
5920 char *name2 = mono_type_full_name (&klass->byval_arg);
5921 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got %s.\n", (gpointer)GetCurrentThreadId (), name, name2));
5922 g_free (name);
5923 g_free (name2);
5924 return ERR_INVALID_ARGUMENT;
5927 nfields = decode_int (buf, &buf, limit);
5928 while ((f = mono_class_get_fields (klass, &iter))) {
5929 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5930 continue;
5931 if (mono_field_is_deleted (f))
5932 continue;
5933 err = decode_value (f->type, domain, (guint8*)addr + f->offset - sizeof (MonoObject), buf, &buf, limit);
5934 if (err)
5935 return err;
5936 nfields --;
5938 g_assert (nfields == 0);
5940 *endbuf = buf;
5942 return 0;
5945 static ErrorCode
5946 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
5948 int err;
5950 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5951 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5952 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5953 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5954 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE)) {
5955 char *name = mono_type_full_name (t);
5956 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
5957 g_free (name);
5958 return ERR_INVALID_ARGUMENT;
5961 switch (t->type) {
5962 case MONO_TYPE_BOOLEAN:
5963 *(guint8*)addr = decode_int (buf, &buf, limit);
5964 break;
5965 case MONO_TYPE_CHAR:
5966 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5967 break;
5968 case MONO_TYPE_I1:
5969 *(gint8*)addr = decode_int (buf, &buf, limit);
5970 break;
5971 case MONO_TYPE_U1:
5972 *(guint8*)addr = decode_int (buf, &buf, limit);
5973 break;
5974 case MONO_TYPE_I2:
5975 *(gint16*)addr = decode_int (buf, &buf, limit);
5976 break;
5977 case MONO_TYPE_U2:
5978 *(guint16*)addr = decode_int (buf, &buf, limit);
5979 break;
5980 case MONO_TYPE_I4:
5981 *(gint32*)addr = decode_int (buf, &buf, limit);
5982 break;
5983 case MONO_TYPE_U4:
5984 *(guint32*)addr = decode_int (buf, &buf, limit);
5985 break;
5986 case MONO_TYPE_I8:
5987 *(gint64*)addr = decode_long (buf, &buf, limit);
5988 break;
5989 case MONO_TYPE_U8:
5990 *(guint64*)addr = decode_long (buf, &buf, limit);
5991 break;
5992 case MONO_TYPE_R4:
5993 *(guint32*)addr = decode_int (buf, &buf, limit);
5994 break;
5995 case MONO_TYPE_R8:
5996 *(guint64*)addr = decode_long (buf, &buf, limit);
5997 break;
5998 case MONO_TYPE_PTR:
5999 /* We send these as I8, so we get them back as such */
6000 g_assert (type == MONO_TYPE_I8);
6001 *(gssize*)addr = decode_long (buf, &buf, limit);
6002 break;
6003 case MONO_TYPE_GENERICINST:
6004 if (MONO_TYPE_ISSTRUCT (t)) {
6005 /* The client sends these as a valuetype */
6006 goto handle_vtype;
6007 } else {
6008 goto handle_ref;
6010 break;
6011 case MONO_TYPE_I:
6012 case MONO_TYPE_U:
6013 /* We send these as vtypes, so we get them back as such */
6014 g_assert (type == MONO_TYPE_VALUETYPE);
6015 /* Fall through */
6016 handle_vtype:
6017 case MONO_TYPE_VALUETYPE:
6018 err = decode_vtype (t, domain, addr,buf, &buf, limit);
6019 if (err)
6020 return err;
6021 break;
6022 handle_ref:
6023 default:
6024 if (MONO_TYPE_IS_REFERENCE (t)) {
6025 if (type == MONO_TYPE_OBJECT) {
6026 int objid = decode_objid (buf, &buf, limit);
6027 int err;
6028 MonoObject *obj;
6030 err = get_object (objid, (MonoObject**)&obj);
6031 if (err)
6032 return err;
6034 if (obj) {
6035 if (!obj_is_of_type (obj, t)) {
6036 DEBUG (1, fprintf (log_file, "Expected type '%s', got '%s'\n", mono_type_full_name (t), obj->vtable->klass->name));
6037 return ERR_INVALID_ARGUMENT;
6040 if (obj && obj->vtable->domain != domain)
6041 return ERR_INVALID_ARGUMENT;
6043 mono_gc_wbarrier_generic_store (addr, obj);
6044 } else if (type == VALUE_TYPE_ID_NULL) {
6045 *(MonoObject**)addr = NULL;
6046 } else if (type == MONO_TYPE_VALUETYPE) {
6047 guint8 *buf2;
6048 gboolean is_enum;
6049 MonoClass *klass;
6050 MonoDomain *d;
6051 guint8 *vtype_buf;
6052 int vtype_buf_size;
6054 /* This can happen when round-tripping boxed vtypes */
6056 * Obtain vtype class.
6057 * Same as the beginning of the handle_vtype case above.
6059 buf2 = buf;
6060 is_enum = decode_byte (buf, &buf, limit);
6061 if (is_enum)
6062 return ERR_NOT_IMPLEMENTED;
6063 klass = decode_typeid (buf, &buf, limit, &d, &err);
6064 if (err)
6065 return err;
6067 /* Decode the vtype into a temporary buffer, then box it. */
6068 vtype_buf_size = mono_class_value_size (klass, NULL);
6069 vtype_buf = g_malloc0 (vtype_buf_size);
6070 g_assert (vtype_buf);
6072 buf = buf2;
6073 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit);
6074 if (err) {
6075 g_free (vtype_buf);
6076 return err;
6078 *(MonoObject**)addr = mono_value_box (d, klass, vtype_buf);
6079 g_free (vtype_buf);
6080 } else {
6081 char *name = mono_type_full_name (t);
6082 DEBUG(1, fprintf (log_file, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer)GetCurrentThreadId (), name, type));
6083 g_free (name);
6084 return ERR_INVALID_ARGUMENT;
6086 } else {
6087 NOT_IMPLEMENTED;
6089 break;
6092 *endbuf = buf;
6094 return 0;
6097 static ErrorCode
6098 decode_value (MonoType *t, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit)
6100 int err;
6101 int type = decode_byte (buf, &buf, limit);
6103 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type (t))) {
6104 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
6105 guint8 *nullable_buf;
6108 * First try decoding it as a Nullable`1
6110 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6111 if (!err)
6112 return err;
6115 * Then try decoding as a primitive value or null.
6117 if (targ->type == type) {
6118 nullable_buf = g_malloc (mono_class_instance_size (mono_class_from_mono_type (targ)));
6119 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit);
6120 if (err) {
6121 g_free (nullable_buf);
6122 return err;
6124 mono_nullable_init (addr, mono_value_box (domain, mono_class_from_mono_type (targ), nullable_buf), mono_class_from_mono_type (t));
6125 g_free (nullable_buf);
6126 *endbuf = buf;
6127 return ERR_NONE;
6128 } else if (type == VALUE_TYPE_ID_NULL) {
6129 mono_nullable_init (addr, NULL, mono_class_from_mono_type (t));
6130 *endbuf = buf;
6131 return ERR_NONE;
6135 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit);
6138 static void
6139 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
6141 guint32 flags;
6142 int reg;
6143 guint8 *addr, *gaddr;
6144 mgreg_t reg_val;
6146 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6147 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6149 switch (flags) {
6150 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
6151 reg_val = mono_arch_context_get_int_reg (ctx, reg);
6153 buffer_add_value_full (buf, t, &reg_val, domain, as_vtype, NULL);
6154 break;
6155 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6156 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6157 addr += (gint32)var->offset;
6159 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6161 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6162 break;
6163 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6164 NOT_IMPLEMENTED;
6165 break;
6166 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6167 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
6168 /* Same as regoffset, but with an indirection */
6169 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6170 addr += (gint32)var->offset;
6172 gaddr = *(gpointer*)addr;
6173 g_assert (gaddr);
6174 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL);
6175 break;
6176 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
6177 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
6178 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
6179 MonoGSharedVtMethodRuntimeInfo *info;
6180 guint8 *locals;
6181 int idx;
6183 idx = reg;
6185 g_assert (info_var);
6186 g_assert (locals_var);
6188 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6189 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6190 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6191 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6192 addr += (gint32)info_var->offset;
6193 info = *(gpointer*)addr;
6194 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6195 info = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6196 } else {
6197 g_assert_not_reached ();
6199 g_assert (info);
6201 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6202 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6203 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6204 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6205 addr += (gint32)locals_var->offset;
6206 locals = *(gpointer*)addr;
6207 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6208 locals = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6209 } else {
6210 g_assert_not_reached ();
6212 g_assert (locals);
6214 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6216 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL);
6217 break;
6220 default:
6221 g_assert_not_reached ();
6225 static void
6226 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, mgreg_t **reg_locations, MonoContext *restore_ctx)
6228 guint32 flags;
6229 int reg, size;
6230 guint8 *addr, *gaddr;
6232 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6233 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6235 if (MONO_TYPE_IS_REFERENCE (t))
6236 size = sizeof (gpointer);
6237 else
6238 size = mono_class_value_size (mono_class_from_mono_type (t), NULL);
6240 switch (flags) {
6241 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6242 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6243 mgreg_t v;
6244 gboolean is_signed = FALSE;
6246 if (t->byref) {
6247 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6249 if (addr) {
6250 // FIXME: Write barriers
6251 mono_gc_memmove_atomic (addr, val, size);
6253 break;
6256 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6257 is_signed = TRUE;
6259 switch (size) {
6260 case 1:
6261 v = is_signed ? *(gint8*)val : *(guint8*)val;
6262 break;
6263 case 2:
6264 v = is_signed ? *(gint16*)val : *(guint16*)val;
6265 break;
6266 case 4:
6267 v = is_signed ? *(gint32*)val : *(guint32*)val;
6268 break;
6269 case 8:
6270 v = is_signed ? *(gint64*)val : *(guint64*)val;
6271 break;
6272 default:
6273 g_assert_not_reached ();
6276 /* Set value on the stack or in the return ctx */
6277 if (reg_locations [reg]) {
6278 /* Saved on the stack */
6279 DEBUG (1, fprintf (log_file, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v));
6280 *(reg_locations [reg]) = v;
6281 } else {
6282 /* Not saved yet */
6283 DEBUG (1, fprintf (log_file, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v));
6284 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6287 // FIXME: Move these to mono-context.h/c.
6288 mono_arch_context_set_int_reg (ctx, reg, v);
6289 #else
6290 // FIXME: Can't set registers, so we disable linears
6291 NOT_IMPLEMENTED;
6292 #endif
6293 break;
6295 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6296 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6297 addr += (gint32)var->offset;
6299 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6301 if (t->byref) {
6302 addr = *(guint8**)addr;
6304 if (!addr)
6305 break;
6308 // FIXME: Write barriers
6309 mono_gc_memmove_atomic (addr, val, size);
6310 break;
6311 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6312 /* Same as regoffset, but with an indirection */
6313 addr = (gpointer)mono_arch_context_get_int_reg (ctx, reg);
6314 addr += (gint32)var->offset;
6316 gaddr = *(gpointer*)addr;
6317 g_assert (gaddr);
6318 // FIXME: Write barriers
6319 mono_gc_memmove_atomic (gaddr, val, size);
6320 break;
6321 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6322 NOT_IMPLEMENTED;
6323 break;
6324 default:
6325 g_assert_not_reached ();
6329 static void
6330 clear_event_request (int req_id, int etype)
6332 int i;
6334 mono_loader_lock ();
6335 for (i = 0; i < event_requests->len; ++i) {
6336 EventRequest *req = g_ptr_array_index (event_requests, i);
6338 if (req->id == req_id && req->event_kind == etype) {
6339 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6340 clear_breakpoint (req->info);
6341 if (req->event_kind == EVENT_KIND_STEP)
6342 ss_destroy (req->info);
6343 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6344 clear_breakpoint (req->info);
6345 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6346 clear_breakpoint (req->info);
6347 g_ptr_array_remove_index_fast (event_requests, i);
6348 g_free (req);
6349 break;
6352 mono_loader_unlock ();
6355 static void
6356 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
6358 int i;
6360 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m->data.exc_class->image->assembly == assembly)
6361 m->kind = MOD_KIND_NONE;
6362 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6363 int count = 0, match_count = 0, pos;
6364 MonoAssembly **newassemblies;
6366 for (i = 0; m->data.assemblies [i]; ++i) {
6367 count ++;
6368 if (m->data.assemblies [i] == assembly)
6369 match_count ++;
6372 if (match_count) {
6373 newassemblies = g_new0 (MonoAssembly*, count - match_count);
6375 pos = 0;
6376 for (i = 0; i < count; ++i)
6377 if (m->data.assemblies [i] != assembly)
6378 newassemblies [pos ++] = m->data.assemblies [i];
6379 g_assert (pos == count - match_count);
6380 g_free (m->data.assemblies);
6381 m->data.assemblies = newassemblies;
6386 static void
6387 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
6389 int i;
6391 for (i = 0; i < req->nmodifiers; ++i) {
6392 Modifier *m = &req->modifiers [i];
6394 clear_assembly_from_modifier (req, m, assembly);
6399 * clear_event_requests_for_assembly:
6401 * Clear all events requests which reference ASSEMBLY.
6403 static void
6404 clear_event_requests_for_assembly (MonoAssembly *assembly)
6406 int i;
6407 gboolean found;
6409 mono_loader_lock ();
6410 found = TRUE;
6411 while (found) {
6412 found = FALSE;
6413 for (i = 0; i < event_requests->len; ++i) {
6414 EventRequest *req = g_ptr_array_index (event_requests, i);
6416 clear_assembly_from_modifiers (req, assembly);
6418 if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly (req->info, assembly)) {
6419 clear_event_request (req->id, req->event_kind);
6420 found = TRUE;
6421 break;
6424 if (req->event_kind == EVENT_KIND_STEP)
6425 ss_clear_for_assembly (req->info, assembly);
6428 mono_loader_unlock ();
6432 * type_comes_from_assembly:
6434 * GHRFunc that returns TRUE if klass comes from assembly
6436 static gboolean
6437 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6439 return (mono_class_get_image ((MonoClass*)klass) == mono_assembly_get_image ((MonoAssembly*)assembly));
6443 * clear_types_for_assembly:
6445 * Clears types from loaded_classes for a given assembly
6447 static void
6448 clear_types_for_assembly (MonoAssembly *assembly)
6450 MonoDomain *domain = mono_domain_get ();
6451 AgentDomainInfo *info = NULL;
6453 mono_loader_lock ();
6454 info = get_agent_domain_info (domain);
6455 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6456 mono_loader_unlock ();
6459 static void
6460 add_thread (gpointer key, gpointer value, gpointer user_data)
6462 MonoInternalThread *thread = value;
6463 Buffer *buf = user_data;
6465 buffer_add_objid (buf, (MonoObject*)thread);
6468 static ErrorCode
6469 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6471 guint8 *end = invoke->endp;
6472 MonoMethod *m;
6473 int i, err, nargs;
6474 MonoMethodSignature *sig;
6475 guint8 **arg_buf;
6476 void **args;
6477 MonoObject *this, *res, *exc;
6478 MonoDomain *domain;
6479 guint8 *this_buf;
6480 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6481 MonoLMFExt ext;
6482 #endif
6483 MonoStopwatch watch;
6485 if (invoke->method) {
6487 * Invoke this method directly, currently only Environment.Exit () is supported.
6489 this = NULL;
6490 DEBUG (1, fprintf (log_file, "[%p] Invoking method '%s' on receiver '%s'.\n", (gpointer)GetCurrentThreadId (), mono_method_full_name (invoke->method, TRUE), this ? this->vtable->klass->name : "<null>"));
6491 mono_runtime_invoke (invoke->method, NULL, invoke->args, &exc);
6492 g_assert_not_reached ();
6495 m = decode_methodid (p, &p, end, &domain, &err);
6496 if (err)
6497 return err;
6498 sig = mono_method_signature (m);
6500 if (m->klass->valuetype)
6501 this_buf = g_alloca (mono_class_instance_size (m->klass));
6502 else
6503 this_buf = g_alloca (sizeof (MonoObject*));
6504 if (m->klass->valuetype && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6505 /* Should be null */
6506 int type = decode_byte (p, &p, end);
6507 if (type != VALUE_TYPE_ID_NULL) {
6508 DEBUG (1, fprintf (log_file, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer)GetCurrentThreadId ()));
6509 return ERR_INVALID_ARGUMENT;
6511 memset (this_buf, 0, mono_class_instance_size (m->klass));
6512 } else {
6513 err = decode_value (&m->klass->byval_arg, domain, this_buf, p, &p, end);
6514 if (err)
6515 return err;
6518 if (!m->klass->valuetype)
6519 this = *(MonoObject**)this_buf;
6520 else
6521 this = NULL;
6523 if (MONO_CLASS_IS_INTERFACE (m->klass)) {
6524 if (!this) {
6525 DEBUG (1, fprintf (log_file, "[%p] Error: Interface method invoked without this argument.\n", (gpointer)GetCurrentThreadId ()));
6526 return ERR_INVALID_ARGUMENT;
6528 m = mono_object_get_virtual_method (this, m);
6531 DEBUG (1, fprintf (log_file, "[%p] Invoking method '%s' on receiver '%s'.\n", (gpointer)GetCurrentThreadId (), mono_method_full_name (m, TRUE), this ? this->vtable->klass->name : "<null>"));
6533 if (this && this->vtable->domain != domain)
6534 NOT_IMPLEMENTED;
6536 if (!m->klass->valuetype && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this) {
6537 if (!strcmp (m->name, ".ctor")) {
6538 if (m->klass->flags & TYPE_ATTRIBUTE_ABSTRACT)
6539 return ERR_INVALID_ARGUMENT;
6540 else
6541 this = mono_object_new (domain, m->klass);
6542 } else {
6543 return ERR_INVALID_ARGUMENT;
6547 if (this && !obj_is_of_type (this, &m->klass->byval_arg))
6548 return ERR_INVALID_ARGUMENT;
6550 nargs = decode_int (p, &p, end);
6551 if (nargs != sig->param_count)
6552 return ERR_INVALID_ARGUMENT;
6553 /* Use alloca to get gc tracking */
6554 arg_buf = g_alloca (nargs * sizeof (gpointer));
6555 memset (arg_buf, 0, nargs * sizeof (gpointer));
6556 args = g_alloca (nargs * sizeof (gpointer));
6557 for (i = 0; i < nargs; ++i) {
6558 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6559 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end);
6560 if (err)
6561 break;
6563 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6564 NOT_IMPLEMENTED;
6565 } else {
6566 arg_buf [i] = g_alloca (mono_class_instance_size (mono_class_from_mono_type (sig->params [i])));
6567 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end);
6568 if (err)
6569 break;
6570 args [i] = arg_buf [i];
6574 if (i < nargs)
6575 return err;
6577 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6578 tls->disable_breakpoints = TRUE;
6579 else
6580 tls->disable_breakpoints = FALSE;
6583 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6585 /* FIXME: Move this to arch specific code */
6586 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6587 if (invoke->has_ctx) {
6588 MonoLMF **lmf_addr;
6590 lmf_addr = mono_get_lmf_addr ();
6592 /* Setup our lmf */
6593 memset (&ext, 0, sizeof (ext));
6594 mono_arch_init_lmf_ext (&ext, *lmf_addr);
6596 ext.debugger_invoke = TRUE;
6597 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6599 mono_set_lmf ((MonoLMF*)&ext);
6601 #endif
6603 mono_stopwatch_start (&watch);
6604 if (m->klass->valuetype)
6605 res = mono_runtime_invoke (m, this_buf, args, &exc);
6606 else
6607 res = mono_runtime_invoke (m, this, args, &exc);
6608 mono_stopwatch_stop (&watch);
6609 DEBUG (1, fprintf (log_file, "[%p] Invoke result: %p, exc: %s, time: %ld ms.\n", (gpointer)GetCurrentThreadId (), res, exc ? exc->vtable->klass->name : NULL, (long)mono_stopwatch_elapsed_ms (&watch)));
6610 if (exc) {
6611 buffer_add_byte (buf, 0);
6612 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &exc, domain);
6613 } else {
6614 buffer_add_byte (buf, 1);
6615 if (sig->ret->type == MONO_TYPE_VOID) {
6616 if (!strcmp (m->name, ".ctor") && !m->klass->valuetype) {
6617 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &this, domain);
6619 else
6620 buffer_add_value (buf, &mono_defaults.void_class->byval_arg, NULL, domain);
6621 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6622 buffer_add_value (buf, sig->ret, &res, domain);
6623 } else if (mono_class_from_mono_type (sig->ret)->valuetype || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6624 if (mono_class_is_nullable (mono_class_from_mono_type (sig->ret))) {
6625 MonoClass *k = mono_class_from_mono_type (sig->ret);
6626 guint8 *nullable_buf = g_alloca (mono_class_value_size (k, NULL));
6628 g_assert (nullable_buf);
6629 mono_nullable_init (nullable_buf, res, k);
6630 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6631 } else {
6632 g_assert (res);
6633 buffer_add_value (buf, sig->ret, mono_object_unbox (res), domain);
6635 } else {
6636 NOT_IMPLEMENTED;
6640 tls->disable_breakpoints = FALSE;
6642 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6643 if (invoke->has_ctx)
6644 mono_set_lmf ((gpointer)(((gssize)ext.lmf.previous_lmf) & ~3));
6645 #endif
6647 *endp = p;
6648 // FIXME: byref arguments
6649 // FIXME: varargs
6650 return ERR_NONE;
6654 * invoke_method:
6656 * Invoke the method given by tls->pending_invoke in the current thread.
6658 static void
6659 invoke_method (void)
6661 DebuggerTlsData *tls;
6662 InvokeData *invoke;
6663 int id;
6664 int i, err, mindex;
6665 Buffer buf;
6666 MonoContext restore_ctx;
6667 guint8 *p;
6669 tls = mono_native_tls_get_value (debugger_tls_id);
6670 g_assert (tls);
6673 * Store the `InvokeData *' in `tls->invoke' until we're done with
6674 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6677 mono_loader_lock ();
6679 invoke = tls->pending_invoke;
6680 g_assert (invoke);
6681 tls->pending_invoke = NULL;
6683 invoke->last_invoke = tls->invoke;
6684 tls->invoke = invoke;
6686 mono_loader_unlock ();
6688 tls->frames_up_to_date = FALSE;
6690 id = invoke->id;
6692 p = invoke->p;
6693 err = 0;
6694 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6695 buffer_init (&buf, 128);
6697 if (err) {
6698 /* Fail the other invokes as well */
6699 } else {
6700 err = do_invoke_method (tls, &buf, invoke, p, &p);
6703 /* Start suspending before sending the reply */
6704 if (mindex == invoke->nmethods - 1) {
6705 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6706 for (i = 0; i < invoke->suspend_count; ++i)
6707 suspend_vm ();
6711 send_reply_packet (id, err, &buf);
6713 buffer_free (&buf);
6716 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6718 if (invoke->has_ctx)
6719 save_thread_context (&restore_ctx);
6721 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6722 g_assert (tls->resume_count);
6723 tls->resume_count -= invoke->suspend_count;
6726 DEBUG (1, fprintf (log_file, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer)GetCurrentThreadId (), err, tls->resume_count));
6729 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6731 * It is possible that ves_icall_System_Threading_Thread_Abort () was called
6732 * after the mono_runtime_invoke() already returned, but it doesn't matter
6733 * because we reset the abort here.
6736 mono_loader_lock ();
6738 if (tls->abort_requested)
6739 mono_thread_internal_reset_abort (tls->thread);
6741 tls->invoke = tls->invoke->last_invoke;
6742 tls->abort_requested = FALSE;
6744 mono_loader_unlock ();
6746 g_free (invoke->p);
6747 g_free (invoke);
6749 suspend_current ();
6752 static gboolean
6753 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6755 MonoThread *thread = value;
6756 DebuggerTlsData *tls;
6757 gboolean res;
6759 mono_loader_lock ();
6760 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6761 g_assert (tls);
6762 res = tls->really_suspended;
6763 mono_loader_unlock ();
6765 return res;
6768 static GPtrArray*
6769 get_source_files_for_type (MonoClass *klass)
6771 gpointer iter = NULL;
6772 MonoMethod *method;
6773 MonoDebugSourceInfo *sinfo;
6774 GPtrArray *files;
6775 int i, j;
6777 files = g_ptr_array_new ();
6779 while ((method = mono_class_get_methods (klass, &iter))) {
6780 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6781 GPtrArray *source_file_list;
6783 if (minfo) {
6784 mono_debug_symfile_get_line_numbers_full (minfo, NULL, &source_file_list, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
6785 for (j = 0; j < source_file_list->len; ++j) {
6786 sinfo = g_ptr_array_index (source_file_list, j);
6787 for (i = 0; i < files->len; ++i)
6788 if (!strcmp (g_ptr_array_index (files, i), sinfo->source_file))
6789 break;
6790 if (i == files->len)
6791 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6793 g_ptr_array_free (source_file_list, TRUE);
6797 return files;
6800 static ErrorCode
6801 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6803 switch (command) {
6804 case CMD_VM_VERSION: {
6805 char *build_info, *version;
6807 build_info = mono_get_runtime_build_info ();
6808 version = g_strdup_printf ("mono %s", build_info);
6810 buffer_add_string (buf, version); /* vm version */
6811 buffer_add_int (buf, MAJOR_VERSION);
6812 buffer_add_int (buf, MINOR_VERSION);
6813 g_free (build_info);
6814 g_free (version);
6815 break;
6817 case CMD_VM_SET_PROTOCOL_VERSION: {
6818 major_version = decode_int (p, &p, end);
6819 minor_version = decode_int (p, &p, end);
6820 protocol_version_set = TRUE;
6821 DEBUG(1, fprintf (log_file, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version));
6822 break;
6824 case CMD_VM_ALL_THREADS: {
6825 // FIXME: Domains
6826 mono_loader_lock ();
6827 buffer_add_int (buf, mono_g_hash_table_size (tid_to_thread_obj));
6828 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
6829 mono_loader_unlock ();
6830 break;
6832 case CMD_VM_SUSPEND:
6833 suspend_vm ();
6834 wait_for_suspend ();
6835 break;
6836 case CMD_VM_RESUME:
6837 if (suspend_count == 0)
6838 return ERR_NOT_SUSPENDED;
6839 resume_vm ();
6840 clear_suspended_objs ();
6841 break;
6842 case CMD_VM_DISPOSE:
6843 /* Clear all event requests */
6844 mono_loader_lock ();
6845 while (event_requests->len > 0) {
6846 EventRequest *req = g_ptr_array_index (event_requests, 0);
6848 clear_event_request (req->id, req->event_kind);
6850 mono_loader_unlock ();
6852 while (suspend_count > 0)
6853 resume_vm ();
6854 disconnected = TRUE;
6855 vm_start_event_sent = FALSE;
6856 break;
6857 case CMD_VM_EXIT: {
6858 MonoInternalThread *thread;
6859 DebuggerTlsData *tls;
6860 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6861 MonoClass *env_class;
6862 #endif
6863 MonoMethod *exit_method = NULL;
6864 gpointer *args;
6865 int exit_code;
6867 exit_code = decode_int (p, &p, end);
6869 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
6871 /* Have to send a reply before exiting */
6872 send_reply_packet (id, 0, buf);
6874 /* Clear all event requests */
6875 mono_loader_lock ();
6876 while (event_requests->len > 0) {
6877 EventRequest *req = g_ptr_array_index (event_requests, 0);
6879 clear_event_request (req->id, req->event_kind);
6881 mono_loader_unlock ();
6884 * The JDWP documentation says that the shutdown is not orderly. It doesn't
6885 * specify whenever a VM_DEATH event is sent. We currently do an orderly
6886 * shutdown by hijacking a thread to execute Environment.Exit (). This is
6887 * better than doing the shutdown ourselves, since it avoids various races.
6890 suspend_vm ();
6891 wait_for_suspend ();
6893 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
6894 env_class = mono_class_from_name (mono_defaults.corlib, "System", "Environment");
6895 if (env_class)
6896 exit_method = mono_class_get_method_from_name (env_class, "Exit", 1);
6897 #endif
6899 mono_loader_lock ();
6900 thread = mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
6901 mono_loader_unlock ();
6903 if (thread && exit_method) {
6904 mono_loader_lock ();
6905 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
6906 mono_loader_unlock ();
6908 args = g_new0 (gpointer, 1);
6909 args [0] = g_malloc (sizeof (int));
6910 *(int*)(args [0]) = exit_code;
6912 tls->pending_invoke = g_new0 (InvokeData, 1);
6913 tls->pending_invoke->method = exit_method;
6914 tls->pending_invoke->args = args;
6915 tls->pending_invoke->nmethods = 1;
6917 while (suspend_count > 0)
6918 resume_vm ();
6919 } else {
6921 * No thread found, do it ourselves.
6922 * FIXME: This can race with normal shutdown etc.
6924 while (suspend_count > 0)
6925 resume_vm ();
6927 if (!mono_runtime_try_shutdown ())
6928 break;
6930 mono_environment_exitcode_set (exit_code);
6932 /* Suspend all managed threads since the runtime is going away */
6933 DEBUG(1, fprintf (log_file, "Suspending all threads...\n"));
6934 mono_thread_suspend_all_other_threads ();
6935 DEBUG(1, fprintf (log_file, "Shutting down the runtime...\n"));
6936 mono_runtime_quit ();
6937 transport_close2 ();
6938 DEBUG(1, fprintf (log_file, "Exiting...\n"));
6940 exit (exit_code);
6942 break;
6944 case CMD_VM_INVOKE_METHOD:
6945 case CMD_VM_INVOKE_METHODS: {
6946 int objid = decode_objid (p, &p, end);
6947 MonoThread *thread;
6948 DebuggerTlsData *tls;
6949 int i, count, err, flags, nmethods;
6951 err = get_object (objid, (MonoObject**)&thread);
6952 if (err)
6953 return err;
6955 flags = decode_int (p, &p, end);
6957 if (command == CMD_VM_INVOKE_METHODS)
6958 nmethods = decode_int (p, &p, end);
6959 else
6960 nmethods = 1;
6962 // Wait for suspending if it already started
6963 if (suspend_count)
6964 wait_for_suspend ();
6965 if (!is_suspended ())
6966 return ERR_NOT_SUSPENDED;
6968 mono_loader_lock ();
6969 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
6970 mono_loader_unlock ();
6971 g_assert (tls);
6973 if (!tls->really_suspended)
6974 /* The thread is still running native code, can't do invokes */
6975 return ERR_NOT_SUSPENDED;
6978 * Store the invoke data into tls, the thread will execute it after it is
6979 * resumed.
6981 if (tls->pending_invoke)
6982 return ERR_NOT_SUSPENDED;
6983 tls->pending_invoke = g_new0 (InvokeData, 1);
6984 tls->pending_invoke->id = id;
6985 tls->pending_invoke->flags = flags;
6986 tls->pending_invoke->p = g_malloc (end - p);
6987 memcpy (tls->pending_invoke->p, p, end - p);
6988 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
6989 tls->pending_invoke->suspend_count = suspend_count;
6990 tls->pending_invoke->nmethods = nmethods;
6992 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
6993 resume_thread (THREAD_TO_INTERNAL (thread));
6995 else {
6996 count = suspend_count;
6997 for (i = 0; i < count; ++i)
6998 resume_vm ();
7000 break;
7002 case CMD_VM_ABORT_INVOKE: {
7003 int objid = decode_objid (p, &p, end);
7004 MonoThread *thread;
7005 DebuggerTlsData *tls;
7006 int invoke_id, err;
7008 err = get_object (objid, (MonoObject**)&thread);
7009 if (err)
7010 return err;
7012 invoke_id = decode_int (p, &p, end);
7014 mono_loader_lock ();
7015 tls = mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7016 g_assert (tls);
7018 if (tls->abort_requested) {
7019 mono_loader_unlock ();
7020 break;
7024 * Check whether we're still inside the mono_runtime_invoke() and that it's
7025 * actually the correct invocation.
7027 * Careful, we do not stop the thread that's doing the invocation, so we can't
7028 * inspect its stack. However, invoke_method() also acquires the loader lock
7029 * when it's done, so we're safe here.
7033 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
7034 mono_loader_unlock ();
7035 return ERR_NO_INVOCATION;
7038 tls->abort_requested = TRUE;
7040 ves_icall_System_Threading_Thread_Abort (THREAD_TO_INTERNAL (thread), NULL);
7041 mono_loader_unlock ();
7042 break;
7045 case CMD_VM_SET_KEEPALIVE: {
7046 int timeout = decode_int (p, &p, end);
7047 agent_config.keepalive = timeout;
7048 // FIXME:
7049 #ifndef DISABLE_SOCKET_TRANSPORT
7050 set_keepalive ();
7051 #else
7052 NOT_IMPLEMENTED;
7053 #endif
7054 break;
7056 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
7057 GHashTableIter iter, kiter;
7058 MonoDomain *domain;
7059 MonoClass *klass;
7060 GPtrArray *files;
7061 int i;
7062 char *fname, *basename;
7063 gboolean ignore_case;
7064 GSList *class_list, *l;
7065 GPtrArray *res_classes, *res_domains;
7067 fname = decode_string (p, &p, end);
7068 ignore_case = decode_byte (p, &p, end);
7070 basename = g_path_get_basename (fname);
7072 res_classes = g_ptr_array_new ();
7073 res_domains = g_ptr_array_new ();
7075 mono_loader_lock ();
7076 g_hash_table_iter_init (&iter, domains);
7077 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7078 AgentDomainInfo *info = domain_jit_info (domain)->agent_info;
7080 /* Update 'source_file_to_class' cache */
7081 g_hash_table_iter_init (&kiter, info->loaded_classes);
7082 while (g_hash_table_iter_next (&kiter, NULL, (void**)&klass)) {
7083 if (!g_hash_table_lookup (info->source_files, klass)) {
7084 files = get_source_files_for_type (klass);
7085 g_hash_table_insert (info->source_files, klass, files);
7087 for (i = 0; i < files->len; ++i) {
7088 char *s = g_ptr_array_index (files, i);
7089 char *s2 = g_path_get_basename (s);
7090 char *s3;
7092 class_list = g_hash_table_lookup (info->source_file_to_class, s2);
7093 if (!class_list) {
7094 class_list = g_slist_prepend (class_list, klass);
7095 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
7096 } else {
7097 class_list = g_slist_prepend (class_list, klass);
7098 g_hash_table_insert (info->source_file_to_class, s2, class_list);
7101 /* The _ignorecase hash contains the lowercase path */
7102 s3 = strdup_tolower (s2);
7103 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
7104 if (!class_list) {
7105 class_list = g_slist_prepend (class_list, klass);
7106 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
7107 } else {
7108 class_list = g_slist_prepend (class_list, klass);
7109 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
7112 g_free (s2);
7113 g_free (s3);
7118 if (ignore_case) {
7119 char *s;
7121 s = strdup_tolower (basename);
7122 class_list = g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
7123 g_free (s);
7124 } else {
7125 class_list = g_hash_table_lookup (info->source_file_to_class, basename);
7128 for (l = class_list; l; l = l->next) {
7129 klass = l->data;
7131 g_ptr_array_add (res_classes, klass);
7132 g_ptr_array_add (res_domains, domain);
7135 mono_loader_unlock ();
7137 g_free (fname);
7138 g_free (basename);
7140 buffer_add_int (buf, res_classes->len);
7141 for (i = 0; i < res_classes->len; ++i)
7142 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
7143 g_ptr_array_free (res_classes, TRUE);
7144 g_ptr_array_free (res_domains, TRUE);
7145 break;
7147 case CMD_VM_GET_TYPES: {
7148 GHashTableIter iter;
7149 MonoDomain *domain;
7150 int i;
7151 char *name;
7152 gboolean ignore_case;
7153 GPtrArray *res_classes, *res_domains;
7154 MonoTypeNameParse info;
7156 name = decode_string (p, &p, end);
7157 ignore_case = decode_byte (p, &p, end);
7159 if (!mono_reflection_parse_type (name, &info)) {
7160 g_free (name);
7161 mono_reflection_free_type_info (&info);
7162 return ERR_INVALID_ARGUMENT;
7165 res_classes = g_ptr_array_new ();
7166 res_domains = g_ptr_array_new ();
7168 mono_loader_lock ();
7169 g_hash_table_iter_init (&iter, domains);
7170 while (g_hash_table_iter_next (&iter, NULL, (void**)&domain)) {
7171 MonoAssembly *ass;
7172 gboolean type_resolve;
7173 MonoType *t;
7174 GSList *tmp;
7176 mono_domain_assemblies_lock (domain);
7177 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7178 ass = tmp->data;
7180 if (ass->image) {
7181 type_resolve = TRUE;
7182 t = mono_reflection_get_type (ass->image, &info, ignore_case, &type_resolve);
7183 if (t) {
7184 g_ptr_array_add (res_classes, mono_type_get_class (t));
7185 g_ptr_array_add (res_domains, domain);
7189 mono_domain_assemblies_unlock (domain);
7191 mono_loader_unlock ();
7193 g_free (name);
7194 mono_reflection_free_type_info (&info);
7196 buffer_add_int (buf, res_classes->len);
7197 for (i = 0; i < res_classes->len; ++i)
7198 buffer_add_typeid (buf, g_ptr_array_index (res_domains, i), g_ptr_array_index (res_classes, i));
7199 g_ptr_array_free (res_classes, TRUE);
7200 g_ptr_array_free (res_domains, TRUE);
7201 break;
7203 case CMD_VM_START_BUFFERING:
7204 case CMD_VM_STOP_BUFFERING:
7205 /* Handled in the main loop */
7206 break;
7207 default:
7208 return ERR_NOT_IMPLEMENTED;
7211 return ERR_NONE;
7214 static ErrorCode
7215 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7217 int err;
7218 MonoError error;
7220 switch (command) {
7221 case CMD_EVENT_REQUEST_SET: {
7222 EventRequest *req;
7223 int i, event_kind, suspend_policy, nmodifiers, mod;
7224 MonoMethod *method;
7225 long location = 0;
7226 MonoThread *step_thread;
7227 int size = 0, depth = 0, filter = 0, step_thread_id = 0;
7228 MonoDomain *domain;
7229 Modifier *modifier;
7231 event_kind = decode_byte (p, &p, end);
7232 suspend_policy = decode_byte (p, &p, end);
7233 nmodifiers = decode_byte (p, &p, end);
7235 req = g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7236 req->id = InterlockedIncrement (&event_request_id);
7237 req->event_kind = event_kind;
7238 req->suspend_policy = suspend_policy;
7239 req->nmodifiers = nmodifiers;
7241 method = NULL;
7242 for (i = 0; i < nmodifiers; ++i) {
7243 mod = decode_byte (p, &p, end);
7245 req->modifiers [i].kind = mod;
7246 if (mod == MOD_KIND_COUNT) {
7247 req->modifiers [i].data.count = decode_int (p, &p, end);
7248 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7249 method = decode_methodid (p, &p, end, &domain, &err);
7250 if (err)
7251 return err;
7252 location = decode_long (p, &p, end);
7253 } else if (mod == MOD_KIND_STEP) {
7254 step_thread_id = decode_id (p, &p, end);
7255 size = decode_int (p, &p, end);
7256 depth = decode_int (p, &p, end);
7257 if (CHECK_PROTOCOL_VERSION (2, 16))
7258 filter = decode_int (p, &p, end);
7259 req->modifiers [i].data.filter = filter;
7260 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7261 /* Treat STEP_THOUGH the same as HIDDEN */
7262 req->modifiers [i].data.filter |= STEP_FILTER_DEBUGGER_STEP_THROUGH;
7263 } else if (mod == MOD_KIND_THREAD_ONLY) {
7264 int id = decode_id (p, &p, end);
7266 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7267 if (err) {
7268 g_free (req);
7269 return err;
7271 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7272 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7274 if (err)
7275 return err;
7276 req->modifiers [i].caught = decode_byte (p, &p, end);
7277 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7278 if (CHECK_PROTOCOL_VERSION (2, 25))
7279 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7280 else
7281 req->modifiers [i].subclasses = TRUE;
7282 DEBUG(1, fprintf (log_file, "[dbg] \tEXCEPTION_ONLY filter (%s%s%s%s).\n", exc_class ? exc_class->name : "all", req->modifiers [i].caught ? ", caught" : "", req->modifiers [i].uncaught ? ", uncaught" : "", req->modifiers [i].subclasses ? ", include-subclasses" : ""));
7283 if (exc_class) {
7284 req->modifiers [i].data.exc_class = exc_class;
7286 if (!mono_class_is_assignable_from (mono_defaults.exception_class, exc_class)) {
7287 g_free (req);
7288 return ERR_INVALID_ARGUMENT;
7291 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7292 int n = decode_int (p, &p, end);
7293 int j;
7295 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n);
7296 for (j = 0; j < n; ++j) {
7297 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7298 if (err) {
7299 g_free (req->modifiers [i].data.assemblies);
7300 return err;
7303 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7304 int n = decode_int (p, &p, end);
7305 int j;
7307 modifier = &req->modifiers [i];
7308 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7309 for (j = 0; j < n; ++j) {
7310 char *s = decode_string (p, &p, end);
7311 char *s2;
7313 if (s) {
7314 s2 = strdup_tolower (s);
7315 g_hash_table_insert (modifier->data.source_files, s2, s2);
7316 g_free (s);
7319 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7320 int n = decode_int (p, &p, end);
7321 int j;
7323 modifier = &req->modifiers [i];
7324 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7325 for (j = 0; j < n; ++j) {
7326 char *s = decode_string (p, &p, end);
7328 if (s)
7329 g_hash_table_insert (modifier->data.type_names, s, s);
7331 } else {
7332 g_free (req);
7333 return ERR_NOT_IMPLEMENTED;
7337 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7338 g_assert (method);
7340 req->info = set_breakpoint (method, location, req, &error);
7341 if (!mono_error_ok (&error)) {
7342 g_free (req);
7343 DEBUG(1, fprintf (log_file, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (&error)));
7344 mono_error_cleanup (&error);
7345 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7347 } else if (req->event_kind == EVENT_KIND_STEP) {
7348 g_assert (step_thread_id);
7350 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7351 if (err) {
7352 g_free (req);
7353 return err;
7356 err = ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, req);
7357 if (err) {
7358 g_free (req);
7359 return err;
7361 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7362 req->info = set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7363 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7364 req->info = set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7365 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7366 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7367 } else {
7368 if (req->nmodifiers) {
7369 g_free (req);
7370 return ERR_NOT_IMPLEMENTED;
7374 mono_loader_lock ();
7375 g_ptr_array_add (event_requests, req);
7377 if (agent_config.defer) {
7378 /* Transmit cached data to the client on receipt of the event request */
7379 switch (req->event_kind) {
7380 case EVENT_KIND_APPDOMAIN_CREATE:
7381 /* Emit load events for currently loaded domains */
7382 g_hash_table_foreach (domains, emit_appdomain_load, NULL);
7383 break;
7384 case EVENT_KIND_ASSEMBLY_LOAD:
7385 /* Emit load events for currently loaded assemblies */
7386 mono_assembly_foreach (emit_assembly_load, NULL);
7387 break;
7388 case EVENT_KIND_THREAD_START:
7389 /* Emit start events for currently started threads */
7390 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7391 break;
7392 case EVENT_KIND_TYPE_LOAD:
7393 /* Emit type load events for currently loaded types */
7394 mono_domain_foreach (send_types_for_domain, NULL);
7395 break;
7396 default:
7397 break;
7400 mono_loader_unlock ();
7402 buffer_add_int (buf, req->id);
7403 break;
7405 case CMD_EVENT_REQUEST_CLEAR: {
7406 int etype = decode_byte (p, &p, end);
7407 int req_id = decode_int (p, &p, end);
7409 // FIXME: Make a faster mapping from req_id to request
7410 mono_loader_lock ();
7411 clear_event_request (req_id, etype);
7412 mono_loader_unlock ();
7413 break;
7415 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7416 int i;
7418 mono_loader_lock ();
7419 i = 0;
7420 while (i < event_requests->len) {
7421 EventRequest *req = g_ptr_array_index (event_requests, i);
7423 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7424 clear_breakpoint (req->info);
7426 g_ptr_array_remove_index_fast (event_requests, i);
7427 g_free (req);
7428 } else {
7429 i ++;
7432 mono_loader_unlock ();
7433 break;
7435 default:
7436 return ERR_NOT_IMPLEMENTED;
7439 return ERR_NONE;
7442 static ErrorCode
7443 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7445 int err;
7446 MonoDomain *domain;
7448 switch (command) {
7449 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7450 buffer_add_domainid (buf, mono_get_root_domain ());
7451 break;
7453 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7454 domain = decode_domainid (p, &p, end, NULL, &err);
7455 if (err)
7456 return err;
7457 buffer_add_string (buf, domain->friendly_name);
7458 break;
7460 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7461 GSList *tmp;
7462 MonoAssembly *ass;
7463 int count;
7465 domain = decode_domainid (p, &p, end, NULL, &err);
7466 if (err)
7467 return err;
7468 mono_loader_lock ();
7469 count = 0;
7470 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7471 count ++;
7473 buffer_add_int (buf, count);
7474 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7475 ass = tmp->data;
7476 buffer_add_assemblyid (buf, domain, ass);
7478 mono_loader_unlock ();
7479 break;
7481 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7482 domain = decode_domainid (p, &p, end, NULL, &err);
7483 if (err)
7484 return err;
7486 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7487 break;
7489 case CMD_APPDOMAIN_GET_CORLIB: {
7490 domain = decode_domainid (p, &p, end, NULL, &err);
7491 if (err)
7492 return err;
7494 buffer_add_assemblyid (buf, domain, domain->domain->mbr.obj.vtable->klass->image->assembly);
7495 break;
7497 case CMD_APPDOMAIN_CREATE_STRING: {
7498 char *s;
7499 MonoString *o;
7501 domain = decode_domainid (p, &p, end, NULL, &err);
7502 if (err)
7503 return err;
7504 s = decode_string (p, &p, end);
7506 o = mono_string_new (domain, s);
7507 buffer_add_objid (buf, (MonoObject*)o);
7508 break;
7510 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7511 MonoClass *klass;
7512 MonoDomain *domain2;
7513 MonoObject *o;
7515 domain = decode_domainid (p, &p, end, NULL, &err);
7516 if (err)
7517 return err;
7518 klass = decode_typeid (p, &p, end, &domain2, &err);
7519 if (err)
7520 return err;
7522 // FIXME:
7523 g_assert (domain == domain2);
7525 o = mono_object_new (domain, klass);
7527 err = decode_value (&klass->byval_arg, domain, mono_object_unbox (o), p, &p, end);
7528 if (err)
7529 return err;
7531 buffer_add_objid (buf, o);
7532 break;
7534 default:
7535 return ERR_NOT_IMPLEMENTED;
7538 return ERR_NONE;
7541 static ErrorCode
7542 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7544 int err;
7545 MonoAssembly *ass;
7546 MonoDomain *domain;
7548 ass = decode_assemblyid (p, &p, end, &domain, &err);
7549 if (err)
7550 return err;
7552 switch (command) {
7553 case CMD_ASSEMBLY_GET_LOCATION: {
7554 buffer_add_string (buf, mono_image_get_filename (ass->image));
7555 break;
7557 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7558 guint32 token;
7559 MonoMethod *m;
7561 if (ass->image->dynamic) {
7562 buffer_add_id (buf, 0);
7563 } else {
7564 token = mono_image_get_entry_point (ass->image);
7565 if (token == 0) {
7566 buffer_add_id (buf, 0);
7567 } else {
7568 m = mono_get_method (ass->image, token, NULL);
7569 buffer_add_methodid (buf, domain, m);
7572 break;
7574 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7575 buffer_add_moduleid (buf, domain, ass->image);
7576 break;
7578 case CMD_ASSEMBLY_GET_OBJECT: {
7579 MonoObject *o = (MonoObject*)mono_assembly_get_object (domain, ass);
7580 buffer_add_objid (buf, o);
7581 break;
7583 case CMD_ASSEMBLY_GET_TYPE: {
7584 char *s = decode_string (p, &p, end);
7585 gboolean ignorecase = decode_byte (p, &p, end);
7586 MonoTypeNameParse info;
7587 MonoType *t;
7588 gboolean type_resolve, res;
7589 MonoDomain *d = mono_domain_get ();
7591 /* This is needed to be able to find referenced assemblies */
7592 res = mono_domain_set (domain, FALSE);
7593 g_assert (res);
7595 if (!mono_reflection_parse_type (s, &info)) {
7596 t = NULL;
7597 } else {
7598 if (info.assembly.name)
7599 NOT_IMPLEMENTED;
7600 t = mono_reflection_get_type (ass->image, &info, ignorecase, &type_resolve);
7602 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type (t) : NULL);
7603 mono_reflection_free_type_info (&info);
7604 g_free (s);
7606 mono_domain_set (d, TRUE);
7608 break;
7610 case CMD_ASSEMBLY_GET_NAME: {
7611 gchar *name;
7612 MonoAssembly *mass = ass;
7614 name = g_strdup_printf (
7615 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7616 mass->aname.name,
7617 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7618 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7619 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7620 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7622 buffer_add_string (buf, name);
7623 g_free (name);
7624 break;
7626 default:
7627 return ERR_NOT_IMPLEMENTED;
7630 return ERR_NONE;
7633 static ErrorCode
7634 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7636 int err;
7637 MonoDomain *domain;
7639 switch (command) {
7640 case CMD_MODULE_GET_INFO: {
7641 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7642 char *basename;
7644 basename = g_path_get_basename (image->name);
7645 buffer_add_string (buf, basename); // name
7646 buffer_add_string (buf, image->module_name); // scopename
7647 buffer_add_string (buf, image->name); // fqname
7648 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7649 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7650 g_free (basename);
7651 break;
7653 default:
7654 return ERR_NOT_IMPLEMENTED;
7657 return ERR_NONE;
7660 static ErrorCode
7661 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7663 int err;
7664 MonoDomain *domain;
7666 switch (command) {
7667 case CMD_FIELD_GET_INFO: {
7668 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
7670 buffer_add_string (buf, f->name);
7671 buffer_add_typeid (buf, domain, f->parent);
7672 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7673 buffer_add_int (buf, f->type->attrs);
7674 break;
7676 default:
7677 return ERR_NOT_IMPLEMENTED;
7680 return ERR_NONE;
7683 static void
7684 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7686 if (val && val->vtable->klass == mono_defaults.monotype_class) {
7687 /* Special case these so the client doesn't have to handle Type objects */
7689 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7690 buffer_add_typeid (buf, domain, mono_class_from_mono_type (((MonoReflectionType*)val)->type));
7691 } else if (MONO_TYPE_IS_REFERENCE (t))
7692 buffer_add_value (buf, t, &val, domain);
7693 else
7694 buffer_add_value (buf, t, mono_object_unbox (val), domain);
7697 static void
7698 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7700 int i, j;
7701 int nattrs = 0;
7703 if (!cinfo) {
7704 buffer_add_int (buf, 0);
7705 return;
7708 for (i = 0; i < cinfo->num_attrs; ++i) {
7709 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7710 nattrs ++;
7712 buffer_add_int (buf, nattrs);
7714 for (i = 0; i < cinfo->num_attrs; ++i) {
7715 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7716 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7717 MonoArray *typed_args, *named_args;
7718 MonoType *t;
7719 CattrNamedArg *arginfo = NULL;
7720 MonoError error;
7722 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, &typed_args, &named_args, &arginfo, &error);
7723 g_assert (mono_error_ok (&error));
7725 buffer_add_methodid (buf, domain, attr->ctor);
7727 /* Ctor args */
7728 if (typed_args) {
7729 buffer_add_int (buf, mono_array_length (typed_args));
7730 for (j = 0; j < mono_array_length (typed_args); ++j) {
7731 MonoObject *val = mono_array_get (typed_args, MonoObject*, j);
7733 t = mono_method_signature (attr->ctor)->params [j];
7735 buffer_add_cattr_arg (buf, t, domain, val);
7737 } else {
7738 buffer_add_int (buf, 0);
7741 /* Named args */
7742 if (named_args) {
7743 buffer_add_int (buf, mono_array_length (named_args));
7745 for (j = 0; j < mono_array_length (named_args); ++j) {
7746 MonoObject *val = mono_array_get (named_args, MonoObject*, j);
7748 if (arginfo [j].prop) {
7749 buffer_add_byte (buf, 0x54);
7750 buffer_add_propertyid (buf, domain, arginfo [j].prop);
7751 } else if (arginfo [j].field) {
7752 buffer_add_byte (buf, 0x53);
7753 buffer_add_fieldid (buf, domain, arginfo [j].field);
7754 } else {
7755 g_assert_not_reached ();
7758 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
7760 } else {
7761 buffer_add_int (buf, 0);
7763 g_free (arginfo);
7768 /* FIXME: Code duplication with icall.c */
7769 static void
7770 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7772 int i;
7773 MonoClass *ic;
7775 mono_class_setup_interfaces (klass, error);
7776 if (!mono_error_ok (error))
7777 return;
7779 for (i = 0; i < klass->interface_count; i++) {
7780 ic = klass->interfaces [i];
7781 g_hash_table_insert (ifaces, ic, ic);
7783 collect_interfaces (ic, ifaces, error);
7784 if (!mono_error_ok (error))
7785 return;
7789 static ErrorCode
7790 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
7792 MonoClass *nested;
7793 MonoType *type;
7794 gpointer iter;
7795 guint8 b;
7796 int err, nnested;
7797 char *name;
7799 switch (command) {
7800 case CMD_TYPE_GET_INFO: {
7801 buffer_add_string (buf, klass->name_space);
7802 buffer_add_string (buf, klass->name);
7803 // FIXME: byref
7804 name = mono_type_get_name_full (&klass->byval_arg, MONO_TYPE_NAME_FORMAT_FULL_NAME);
7805 buffer_add_string (buf, name);
7806 g_free (name);
7807 buffer_add_assemblyid (buf, domain, klass->image->assembly);
7808 buffer_add_moduleid (buf, domain, klass->image);
7809 buffer_add_typeid (buf, domain, klass->parent);
7810 if (klass->rank || klass->byval_arg.type == MONO_TYPE_PTR)
7811 buffer_add_typeid (buf, domain, klass->element_class);
7812 else
7813 buffer_add_id (buf, 0);
7814 buffer_add_int (buf, klass->type_token);
7815 buffer_add_byte (buf, klass->rank);
7816 buffer_add_int (buf, klass->flags);
7817 b = 0;
7818 type = &klass->byval_arg;
7819 // FIXME: Can't decide whenever a class represents a byref type
7820 if (FALSE)
7821 b |= (1 << 0);
7822 if (type->type == MONO_TYPE_PTR)
7823 b |= (1 << 1);
7824 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
7825 b |= (1 << 2);
7826 if (type->type == MONO_TYPE_VALUETYPE)
7827 b |= (1 << 3);
7828 if (klass->enumtype)
7829 b |= (1 << 4);
7830 if (klass->generic_container)
7831 b |= (1 << 5);
7832 if (klass->generic_container || klass->generic_class)
7833 b |= (1 << 6);
7834 buffer_add_byte (buf, b);
7835 nnested = 0;
7836 iter = NULL;
7837 while ((nested = mono_class_get_nested_types (klass, &iter)))
7838 nnested ++;
7839 buffer_add_int (buf, nnested);
7840 iter = NULL;
7841 while ((nested = mono_class_get_nested_types (klass, &iter)))
7842 buffer_add_typeid (buf, domain, nested);
7843 if (CHECK_PROTOCOL_VERSION (2, 12)) {
7844 if (klass->generic_container)
7845 buffer_add_typeid (buf, domain, klass);
7846 else if (klass->generic_class)
7847 buffer_add_typeid (buf, domain, klass->generic_class->container_class);
7848 else
7849 buffer_add_id (buf, 0);
7851 if (CHECK_PROTOCOL_VERSION (2, 15)) {
7852 int count, i;
7854 if (klass->generic_class) {
7855 MonoGenericInst *inst = klass->generic_class->context.class_inst;
7857 count = inst->type_argc;
7858 buffer_add_int (buf, count);
7859 for (i = 0; i < count; i++)
7860 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
7861 } else if (klass->generic_container) {
7862 MonoGenericContainer *container = klass->generic_container;
7863 MonoClass *pklass;
7865 count = container->type_argc;
7866 buffer_add_int (buf, count);
7867 for (i = 0; i < count; i++) {
7868 pklass = mono_class_from_generic_parameter (mono_generic_container_get_param (container, i), klass->image, FALSE);
7869 buffer_add_typeid (buf, domain, pklass);
7871 } else {
7872 buffer_add_int (buf, 0);
7875 break;
7877 case CMD_TYPE_GET_METHODS: {
7878 int nmethods;
7879 int i = 0;
7880 gpointer iter = NULL;
7881 MonoMethod *m;
7883 mono_class_setup_methods (klass);
7885 nmethods = mono_class_num_methods (klass);
7887 buffer_add_int (buf, nmethods);
7889 while ((m = mono_class_get_methods (klass, &iter))) {
7890 buffer_add_methodid (buf, domain, m);
7891 i ++;
7893 g_assert (i == nmethods);
7894 break;
7896 case CMD_TYPE_GET_FIELDS: {
7897 int nfields;
7898 int i = 0;
7899 gpointer iter = NULL;
7900 MonoClassField *f;
7902 nfields = mono_class_num_fields (klass);
7904 buffer_add_int (buf, nfields);
7906 while ((f = mono_class_get_fields (klass, &iter))) {
7907 buffer_add_fieldid (buf, domain, f);
7908 buffer_add_string (buf, f->name);
7909 buffer_add_typeid (buf, domain, mono_class_from_mono_type (f->type));
7910 buffer_add_int (buf, f->type->attrs);
7911 i ++;
7913 g_assert (i == nfields);
7914 break;
7916 case CMD_TYPE_GET_PROPERTIES: {
7917 int nprops;
7918 int i = 0;
7919 gpointer iter = NULL;
7920 MonoProperty *p;
7922 nprops = mono_class_num_properties (klass);
7924 buffer_add_int (buf, nprops);
7926 while ((p = mono_class_get_properties (klass, &iter))) {
7927 buffer_add_propertyid (buf, domain, p);
7928 buffer_add_string (buf, p->name);
7929 buffer_add_methodid (buf, domain, p->get);
7930 buffer_add_methodid (buf, domain, p->set);
7931 buffer_add_int (buf, p->attrs);
7932 i ++;
7934 g_assert (i == nprops);
7935 break;
7937 case CMD_TYPE_GET_CATTRS: {
7938 MonoClass *attr_klass;
7939 MonoCustomAttrInfo *cinfo;
7941 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7942 /* attr_klass can be NULL */
7943 if (err)
7944 return err;
7946 cinfo = mono_custom_attrs_from_class (klass);
7948 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7949 break;
7951 case CMD_TYPE_GET_FIELD_CATTRS: {
7952 MonoClass *attr_klass;
7953 MonoCustomAttrInfo *cinfo;
7954 MonoClassField *field;
7956 field = decode_fieldid (p, &p, end, NULL, &err);
7957 if (err)
7958 return err;
7959 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7960 if (err)
7961 return err;
7963 cinfo = mono_custom_attrs_from_field (klass, field);
7965 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7966 break;
7968 case CMD_TYPE_GET_PROPERTY_CATTRS: {
7969 MonoClass *attr_klass;
7970 MonoCustomAttrInfo *cinfo;
7971 MonoProperty *prop;
7973 prop = decode_propertyid (p, &p, end, NULL, &err);
7974 if (err)
7975 return err;
7976 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7977 if (err)
7978 return err;
7980 cinfo = mono_custom_attrs_from_property (klass, prop);
7982 buffer_add_cattrs (buf, domain, klass->image, attr_klass, cinfo);
7983 break;
7985 case CMD_TYPE_GET_VALUES:
7986 case CMD_TYPE_GET_VALUES_2: {
7987 guint8 *val;
7988 MonoClassField *f;
7989 MonoVTable *vtable;
7990 MonoClass *k;
7991 int len, i;
7992 gboolean found;
7993 MonoThread *thread_obj;
7994 MonoInternalThread *thread = NULL;
7995 guint32 special_static_type;
7997 if (command == CMD_TYPE_GET_VALUES_2) {
7998 int objid = decode_objid (p, &p, end);
7999 int err;
8001 err = get_object (objid, (MonoObject**)&thread_obj);
8002 if (err)
8003 return err;
8005 thread = THREAD_TO_INTERNAL (thread_obj);
8008 len = decode_int (p, &p, end);
8009 for (i = 0; i < len; ++i) {
8010 f = decode_fieldid (p, &p, end, NULL, &err);
8011 if (err)
8012 return err;
8014 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8015 return ERR_INVALID_FIELDID;
8016 special_static_type = mono_class_field_get_special_static_type (f);
8017 if (special_static_type != SPECIAL_STATIC_NONE) {
8018 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
8019 return ERR_INVALID_FIELDID;
8022 /* Check that the field belongs to the object */
8023 found = FALSE;
8024 for (k = klass; k; k = k->parent) {
8025 if (k == f->parent) {
8026 found = TRUE;
8027 break;
8030 if (!found)
8031 return ERR_INVALID_FIELDID;
8033 vtable = mono_class_vtable (domain, f->parent);
8034 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8035 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val);
8036 buffer_add_value (buf, f->type, val, domain);
8037 g_free (val);
8039 break;
8041 case CMD_TYPE_SET_VALUES: {
8042 guint8 *val;
8043 MonoClassField *f;
8044 MonoVTable *vtable;
8045 MonoClass *k;
8046 int len, i;
8047 gboolean found;
8049 len = decode_int (p, &p, end);
8050 for (i = 0; i < len; ++i) {
8051 f = decode_fieldid (p, &p, end, NULL, &err);
8052 if (err)
8053 return err;
8055 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8056 return ERR_INVALID_FIELDID;
8057 if (mono_class_field_is_special_static (f))
8058 return ERR_INVALID_FIELDID;
8060 /* Check that the field belongs to the object */
8061 found = FALSE;
8062 for (k = klass; k; k = k->parent) {
8063 if (k == f->parent) {
8064 found = TRUE;
8065 break;
8068 if (!found)
8069 return ERR_INVALID_FIELDID;
8071 // FIXME: Check for literal/const
8073 vtable = mono_class_vtable (domain, f->parent);
8074 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
8075 err = decode_value (f->type, domain, val, p, &p, end);
8076 if (err) {
8077 g_free (val);
8078 return err;
8080 if (MONO_TYPE_IS_REFERENCE (f->type))
8081 mono_field_static_set_value (vtable, f, *(gpointer*)val);
8082 else
8083 mono_field_static_set_value (vtable, f, val);
8084 g_free (val);
8086 break;
8088 case CMD_TYPE_GET_OBJECT: {
8089 MonoObject *o = (MonoObject*)mono_type_get_object (domain, &klass->byval_arg);
8090 buffer_add_objid (buf, o);
8091 break;
8093 case CMD_TYPE_GET_SOURCE_FILES:
8094 case CMD_TYPE_GET_SOURCE_FILES_2: {
8095 char *source_file, *base;
8096 GPtrArray *files;
8097 int i;
8099 files = get_source_files_for_type (klass);
8101 buffer_add_int (buf, files->len);
8102 for (i = 0; i < files->len; ++i) {
8103 source_file = g_ptr_array_index (files, i);
8104 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8105 buffer_add_string (buf, source_file);
8106 } else {
8107 base = g_path_get_basename (source_file);
8108 buffer_add_string (buf, base);
8109 g_free (base);
8111 g_free (source_file);
8113 g_ptr_array_free (files, TRUE);
8114 break;
8116 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8117 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8119 if (err)
8120 return err;
8121 if (mono_class_is_assignable_from (klass, oklass))
8122 buffer_add_byte (buf, 1);
8123 else
8124 buffer_add_byte (buf, 0);
8125 break;
8127 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8128 char *name = decode_string (p, &p, end);
8129 int i, flags = decode_int (p, &p, end);
8130 MonoException *ex = NULL;
8131 GPtrArray *array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, (flags & BINDING_FLAGS_IGNORE_CASE) != 0, TRUE, &ex);
8133 if (!array)
8134 return ERR_LOADER_ERROR;
8135 buffer_add_int (buf, array->len);
8136 for (i = 0; i < array->len; ++i) {
8137 MonoMethod *method = g_ptr_array_index (array, i);
8138 buffer_add_methodid (buf, domain, method);
8141 g_ptr_array_free (array, TRUE);
8142 g_free (name);
8143 break;
8145 case CMD_TYPE_GET_INTERFACES: {
8146 MonoClass *parent;
8147 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8148 MonoError error;
8149 MonoClass *tclass, *iface;
8150 GHashTableIter iter;
8152 tclass = klass;
8154 for (parent = tclass; parent; parent = parent->parent) {
8155 mono_class_setup_interfaces (parent, &error);
8156 if (!mono_error_ok (&error))
8157 return ERR_LOADER_ERROR;
8158 collect_interfaces (parent, iface_hash, &error);
8159 if (!mono_error_ok (&error))
8160 return ERR_LOADER_ERROR;
8163 buffer_add_int (buf, g_hash_table_size (iface_hash));
8165 g_hash_table_iter_init (&iter, iface_hash);
8166 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8167 buffer_add_typeid (buf, domain, iface);
8168 g_hash_table_destroy (iface_hash);
8169 break;
8171 case CMD_TYPE_GET_INTERFACE_MAP: {
8172 int tindex, ioffset;
8173 gboolean variance_used;
8174 MonoClass *iclass;
8175 int len, nmethods, i;
8176 gpointer iter;
8177 MonoMethod *method;
8179 len = decode_int (p, &p, end);
8180 mono_class_setup_vtable (klass);
8182 for (tindex = 0; tindex < len; ++tindex) {
8183 iclass = decode_typeid (p, &p, end, NULL, &err);
8184 if (err)
8185 return err;
8187 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8188 if (ioffset == -1)
8189 return ERR_INVALID_ARGUMENT;
8191 nmethods = mono_class_num_methods (iclass);
8192 buffer_add_int (buf, nmethods);
8194 iter = NULL;
8195 while ((method = mono_class_get_methods (iclass, &iter))) {
8196 buffer_add_methodid (buf, domain, method);
8198 for (i = 0; i < nmethods; ++i)
8199 buffer_add_methodid (buf, domain, klass->vtable [i + ioffset]);
8201 break;
8203 case CMD_TYPE_IS_INITIALIZED: {
8204 MonoVTable *vtable = mono_class_vtable (domain, klass);
8206 if (vtable)
8207 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8208 else
8209 buffer_add_int (buf, 0);
8210 break;
8212 case CMD_TYPE_CREATE_INSTANCE: {
8213 MonoObject *obj;
8215 obj = mono_object_new (domain, klass);
8216 buffer_add_objid (buf, obj);
8217 break;
8219 default:
8220 return ERR_NOT_IMPLEMENTED;
8223 return ERR_NONE;
8226 static ErrorCode
8227 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8229 MonoClass *klass;
8230 MonoDomain *old_domain;
8231 MonoDomain *domain;
8232 int err;
8234 klass = decode_typeid (p, &p, end, &domain, &err);
8235 if (err)
8236 return err;
8238 old_domain = mono_domain_get ();
8240 mono_domain_set (domain, TRUE);
8242 err = type_commands_internal (command, klass, domain, p, end, buf);
8244 mono_domain_set (old_domain, TRUE);
8246 return err;
8249 static ErrorCode
8250 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8252 MonoMethodHeader *header;
8253 int err;
8255 switch (command) {
8256 case CMD_METHOD_GET_NAME: {
8257 buffer_add_string (buf, method->name);
8258 break;
8260 case CMD_METHOD_GET_DECLARING_TYPE: {
8261 buffer_add_typeid (buf, domain, method->klass);
8262 break;
8264 case CMD_METHOD_GET_DEBUG_INFO: {
8265 MonoDebugMethodInfo *minfo;
8266 char *source_file;
8267 int i, j, n_il_offsets;
8268 int *il_offsets;
8269 int *line_numbers;
8270 int *column_numbers;
8271 int *end_line_numbers;
8272 int *end_column_numbers;
8273 int *source_files;
8274 GPtrArray *source_file_list;
8276 header = mono_method_get_header (method);
8277 if (!header) {
8278 buffer_add_int (buf, 0);
8279 buffer_add_string (buf, "");
8280 buffer_add_int (buf, 0);
8281 break;
8284 minfo = mono_debug_lookup_method (method);
8285 if (!minfo) {
8286 buffer_add_int (buf, header->code_size);
8287 buffer_add_string (buf, "");
8288 buffer_add_int (buf, 0);
8289 mono_metadata_free_mh (header);
8290 break;
8293 mono_debug_symfile_get_line_numbers_full (minfo, &source_file, &source_file_list, &n_il_offsets, &il_offsets, &line_numbers, &column_numbers, &source_files, &end_line_numbers, &end_column_numbers);
8294 buffer_add_int (buf, header->code_size);
8295 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8296 buffer_add_int (buf, source_file_list->len);
8297 for (i = 0; i < source_file_list->len; ++i) {
8298 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, i);
8299 buffer_add_string (buf, sinfo->source_file);
8300 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8301 for (j = 0; j < 16; ++j)
8302 buffer_add_byte (buf, sinfo->hash [j]);
8305 } else {
8306 buffer_add_string (buf, source_file);
8308 buffer_add_int (buf, n_il_offsets);
8309 DEBUG (10, fprintf (log_file, "Line number table for method %s:\n", mono_method_full_name (method, TRUE)));
8310 for (i = 0; i < n_il_offsets; ++i) {
8311 const char *srcfile = "";
8313 if (source_files [i] != -1) {
8314 MonoDebugSourceInfo *sinfo = g_ptr_array_index (source_file_list, source_files [i]);
8315 srcfile = sinfo->source_file;
8317 DEBUG (10, fprintf (log_file, "IL%x -> %s:%d %d\n", il_offsets [i], srcfile, line_numbers [i], column_numbers ? column_numbers [i] : -1));
8318 buffer_add_int (buf, il_offsets [i]);
8319 buffer_add_int (buf, line_numbers [i]);
8320 if (CHECK_PROTOCOL_VERSION (2, 13))
8321 buffer_add_int (buf, source_files [i]);
8322 if (CHECK_PROTOCOL_VERSION (2, 19))
8323 buffer_add_int (buf, column_numbers ? column_numbers [i] : -1);
8324 if (CHECK_PROTOCOL_VERSION (2, 32)) {
8325 buffer_add_int (buf, end_line_numbers ? end_line_numbers [i] : -1);
8326 buffer_add_int (buf, end_column_numbers ? end_column_numbers [i] : -1);
8329 g_free (source_file);
8330 g_free (il_offsets);
8331 g_free (line_numbers);
8332 g_free (column_numbers);
8333 g_free (end_line_numbers);
8334 g_free (end_column_numbers);
8335 g_free (source_files);
8336 g_ptr_array_free (source_file_list, TRUE);
8337 mono_metadata_free_mh (header);
8338 break;
8340 case CMD_METHOD_GET_PARAM_INFO: {
8341 MonoMethodSignature *sig = mono_method_signature (method);
8342 guint32 i;
8343 char **names;
8345 /* FIXME: mono_class_from_mono_type () and byrefs */
8347 /* FIXME: Use a smaller encoding */
8348 buffer_add_int (buf, sig->call_convention);
8349 buffer_add_int (buf, sig->param_count);
8350 buffer_add_int (buf, sig->generic_param_count);
8351 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->ret));
8352 for (i = 0; i < sig->param_count; ++i) {
8353 /* FIXME: vararg */
8354 buffer_add_typeid (buf, domain, mono_class_from_mono_type (sig->params [i]));
8357 /* Emit parameter names */
8358 names = g_new (char *, sig->param_count);
8359 mono_method_get_param_names (method, (const char **) names);
8360 for (i = 0; i < sig->param_count; ++i)
8361 buffer_add_string (buf, names [i]);
8362 g_free (names);
8364 break;
8366 case CMD_METHOD_GET_LOCALS_INFO: {
8367 int i, j, num_locals;
8368 MonoDebugLocalsInfo *locals;
8370 header = mono_method_get_header (method);
8371 if (!header)
8372 return ERR_INVALID_ARGUMENT;
8374 buffer_add_int (buf, header->num_locals);
8376 /* Types */
8377 for (i = 0; i < header->num_locals; ++i)
8378 buffer_add_typeid (buf, domain, mono_class_from_mono_type (header->locals [i]));
8380 /* Names */
8381 locals = mono_debug_lookup_locals (method);
8382 if (locals)
8383 num_locals = locals->num_locals;
8384 else
8385 num_locals = 0;
8386 for (i = 0; i < header->num_locals; ++i) {
8387 for (j = 0; j < num_locals; ++j)
8388 if (locals->locals [j].index == i)
8389 break;
8390 if (j < num_locals)
8391 buffer_add_string (buf, locals->locals [j].name);
8392 else
8393 buffer_add_string (buf, "");
8396 /* Scopes */
8397 for (i = 0; i < header->num_locals; ++i) {
8398 for (j = 0; j < num_locals; ++j)
8399 if (locals->locals [j].index == i)
8400 break;
8401 if (j < num_locals && locals->locals [j].block) {
8402 buffer_add_int (buf, locals->locals [j].block->start_offset);
8403 buffer_add_int (buf, locals->locals [j].block->end_offset);
8404 } else {
8405 buffer_add_int (buf, 0);
8406 buffer_add_int (buf, header->code_size);
8409 mono_metadata_free_mh (header);
8411 if (locals)
8412 mono_debug_symfile_free_locals (locals);
8414 break;
8416 case CMD_METHOD_GET_INFO:
8417 buffer_add_int (buf, method->flags);
8418 buffer_add_int (buf, method->iflags);
8419 buffer_add_int (buf, method->token);
8420 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8421 guint8 attrs = 0;
8422 if (method->is_generic)
8423 attrs |= (1 << 0);
8424 if (mono_method_signature (method)->generic_param_count)
8425 attrs |= (1 << 1);
8426 buffer_add_byte (buf, attrs);
8427 if (method->is_generic || method->is_inflated) {
8428 MonoMethod *result;
8430 if (method->is_generic) {
8431 result = method;
8432 } else {
8433 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8435 result = imethod->declaring;
8436 if (imethod->context.class_inst) {
8437 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8438 /*Generic methods gets the context of the GTD.*/
8439 if (mono_class_get_context (klass))
8440 result = mono_class_inflate_generic_method_full (result, klass, mono_class_get_context (klass));
8444 buffer_add_methodid (buf, domain, result);
8445 } else {
8446 buffer_add_id (buf, 0);
8448 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8449 if (mono_method_signature (method)->generic_param_count) {
8450 int count, i;
8452 if (method->is_inflated) {
8453 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
8454 if (inst) {
8455 count = inst->type_argc;
8456 buffer_add_int (buf, count);
8458 for (i = 0; i < count; i++)
8459 buffer_add_typeid (buf, domain, mono_class_from_mono_type (inst->type_argv [i]));
8460 } else {
8461 buffer_add_int (buf, 0);
8463 } else if (method->is_generic) {
8464 MonoGenericContainer *container = mono_method_get_generic_container (method);
8466 count = mono_method_signature (method)->generic_param_count;
8467 buffer_add_int (buf, count);
8468 for (i = 0; i < count; i++) {
8469 MonoGenericParam *param = mono_generic_container_get_param (container, i);
8470 MonoClass *pklass = mono_class_from_generic_parameter (param, method->klass->image, TRUE);
8471 buffer_add_typeid (buf, domain, pklass);
8473 } else {
8474 buffer_add_int (buf, 0);
8476 } else {
8477 buffer_add_int (buf, 0);
8481 break;
8482 case CMD_METHOD_GET_BODY: {
8483 int i;
8485 header = mono_method_get_header (method);
8486 if (!header) {
8487 buffer_add_int (buf, 0);
8489 if (CHECK_PROTOCOL_VERSION (2, 18))
8490 buffer_add_int (buf, 0);
8491 } else {
8492 buffer_add_int (buf, header->code_size);
8493 for (i = 0; i < header->code_size; ++i)
8494 buffer_add_byte (buf, header->code [i]);
8496 if (CHECK_PROTOCOL_VERSION (2, 18)) {
8497 buffer_add_int (buf, header->num_clauses);
8498 for (i = 0; i < header->num_clauses; ++i) {
8499 MonoExceptionClause *clause = &header->clauses [i];
8501 buffer_add_int (buf, clause->flags);
8502 buffer_add_int (buf, clause->try_offset);
8503 buffer_add_int (buf, clause->try_len);
8504 buffer_add_int (buf, clause->handler_offset);
8505 buffer_add_int (buf, clause->handler_len);
8506 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
8507 buffer_add_typeid (buf, domain, clause->data.catch_class);
8508 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8509 buffer_add_int (buf, clause->data.filter_offset);
8513 mono_metadata_free_mh (header);
8516 break;
8518 case CMD_METHOD_RESOLVE_TOKEN: {
8519 guint32 token = decode_int (p, &p, end);
8521 // FIXME: Generics
8522 switch (mono_metadata_token_code (token)) {
8523 case MONO_TOKEN_STRING: {
8524 MonoString *s;
8525 char *s2;
8527 s = mono_ldstr (domain, method->klass->image, mono_metadata_token_index (token));
8528 g_assert (s);
8530 s2 = mono_string_to_utf8 (s);
8532 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8533 buffer_add_string (buf, s2);
8534 g_free (s2);
8535 break;
8537 default: {
8538 gpointer val;
8539 MonoClass *handle_class;
8541 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8542 val = mono_method_get_wrapper_data (method, token);
8543 handle_class = mono_method_get_wrapper_data (method, token + 1);
8545 if (handle_class == NULL) {
8546 // Can't figure out the token type
8547 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8548 break;
8550 } else {
8551 val = mono_ldtoken (method->klass->image, token, &handle_class, NULL);
8552 g_assert (val);
8555 if (handle_class == mono_defaults.typehandle_class) {
8556 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8557 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8558 buffer_add_typeid (buf, domain, (MonoClass *) val);
8559 else
8560 buffer_add_typeid (buf, domain, mono_class_from_mono_type ((MonoType*)val));
8561 } else if (handle_class == mono_defaults.fieldhandle_class) {
8562 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8563 buffer_add_fieldid (buf, domain, val);
8564 } else if (handle_class == mono_defaults.methodhandle_class) {
8565 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8566 buffer_add_methodid (buf, domain, val);
8567 } else if (handle_class == mono_defaults.string_class) {
8568 char *s;
8570 s = mono_string_to_utf8 (val);
8571 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8572 buffer_add_string (buf, s);
8573 g_free (s);
8574 } else {
8575 g_assert_not_reached ();
8577 break;
8580 break;
8582 case CMD_METHOD_GET_CATTRS: {
8583 MonoClass *attr_klass;
8584 MonoCustomAttrInfo *cinfo;
8586 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8587 /* attr_klass can be NULL */
8588 if (err)
8589 return err;
8591 cinfo = mono_custom_attrs_from_method (method);
8593 buffer_add_cattrs (buf, domain, method->klass->image, attr_klass, cinfo);
8594 break;
8596 case CMD_METHOD_MAKE_GENERIC_METHOD: {
8597 MonoType **type_argv;
8598 int i, type_argc;
8599 MonoDomain *d;
8600 MonoClass *klass;
8601 MonoGenericInst *ginst;
8602 MonoGenericContext tmp_context;
8603 MonoMethod *inflated;
8605 type_argc = decode_int (p, &p, end);
8606 type_argv = g_new0 (MonoType*, type_argc);
8607 for (i = 0; i < type_argc; ++i) {
8608 klass = decode_typeid (p, &p, end, &d, &err);
8609 if (err) {
8610 g_free (type_argv);
8611 return err;
8613 if (domain != d) {
8614 g_free (type_argv);
8615 return ERR_INVALID_ARGUMENT;
8617 type_argv [i] = &klass->byval_arg;
8619 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
8620 g_free (type_argv);
8621 tmp_context.class_inst = method->klass->generic_class ? method->klass->generic_class->context.class_inst : NULL;
8622 tmp_context.method_inst = ginst;
8624 inflated = mono_class_inflate_generic_method (method, &tmp_context);
8625 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
8626 return ERR_INVALID_ARGUMENT;
8627 buffer_add_methodid (buf, domain, inflated);
8628 break;
8630 default:
8631 return ERR_NOT_IMPLEMENTED;
8634 return ERR_NONE;
8637 static ErrorCode
8638 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8640 int err;
8641 MonoDomain *old_domain;
8642 MonoDomain *domain;
8643 MonoMethod *method;
8645 method = decode_methodid (p, &p, end, &domain, &err);
8646 if (err)
8647 return err;
8649 old_domain = mono_domain_get ();
8651 mono_domain_set (domain, TRUE);
8653 err = method_commands_internal (command, method, domain, p, end, buf);
8655 mono_domain_set (old_domain, TRUE);
8657 return err;
8660 static ErrorCode
8661 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8663 int objid = decode_objid (p, &p, end);
8664 int err;
8665 MonoThread *thread_obj;
8666 MonoInternalThread *thread;
8668 err = get_object (objid, (MonoObject**)&thread_obj);
8669 if (err)
8670 return err;
8672 thread = THREAD_TO_INTERNAL (thread_obj);
8674 switch (command) {
8675 case CMD_THREAD_GET_NAME: {
8676 guint32 name_len;
8677 gunichar2 *s = mono_thread_get_name (thread, &name_len);
8679 if (!s) {
8680 buffer_add_int (buf, 0);
8681 } else {
8682 char *name;
8683 glong len;
8685 name = g_utf16_to_utf8 (s, name_len, NULL, &len, NULL);
8686 g_assert (name);
8687 buffer_add_int (buf, len);
8688 buffer_add_data (buf, (guint8*)name, len);
8689 g_free (s);
8691 break;
8693 case CMD_THREAD_GET_FRAME_INFO: {
8694 DebuggerTlsData *tls;
8695 int i, start_frame, length;
8697 // Wait for suspending if it already started
8698 // FIXME: Races with suspend_count
8699 while (!is_suspended ()) {
8700 if (suspend_count)
8701 wait_for_suspend ();
8704 if (suspend_count)
8705 wait_for_suspend ();
8706 if (!is_suspended ())
8707 return ERR_NOT_SUSPENDED;
8710 start_frame = decode_int (p, &p, end);
8711 length = decode_int (p, &p, end);
8713 if (start_frame != 0 || length != -1)
8714 return ERR_NOT_IMPLEMENTED;
8716 mono_loader_lock ();
8717 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8718 mono_loader_unlock ();
8719 g_assert (tls);
8721 compute_frame_info (thread, tls);
8723 buffer_add_int (buf, tls->frame_count);
8724 for (i = 0; i < tls->frame_count; ++i) {
8725 buffer_add_int (buf, tls->frames [i]->id);
8726 buffer_add_methodid (buf, tls->frames [i]->domain, tls->frames [i]->actual_method);
8727 buffer_add_int (buf, tls->frames [i]->il_offset);
8729 * Instead of passing the frame type directly to the client, we associate
8730 * it with the previous frame using a set of flags. This avoids lots of
8731 * conditional code in the client, since a frame whose type isn't
8732 * FRAME_TYPE_MANAGED has no method, location, etc.
8734 buffer_add_byte (buf, tls->frames [i]->flags);
8737 break;
8739 case CMD_THREAD_GET_STATE:
8740 buffer_add_int (buf, thread->state);
8741 break;
8742 case CMD_THREAD_GET_INFO:
8743 buffer_add_byte (buf, thread->threadpool_thread);
8744 break;
8745 case CMD_THREAD_GET_ID:
8746 buffer_add_long (buf, (guint64)(gsize)thread);
8747 break;
8748 case CMD_THREAD_GET_TID:
8749 buffer_add_long (buf, (guint64)thread->tid);
8750 break;
8751 case CMD_THREAD_SET_IP: {
8752 DebuggerTlsData *tls;
8753 MonoMethod *method;
8754 MonoDomain *domain;
8755 MonoSeqPointInfo *seq_points;
8756 SeqPoint *sp = NULL;
8757 gint64 il_offset;
8758 int i;
8760 method = decode_methodid (p, &p, end, &domain, &err);
8761 if (err)
8762 return err;
8763 il_offset = decode_long (p, &p, end);
8765 while (!is_suspended ()) {
8766 if (suspend_count)
8767 wait_for_suspend ();
8770 mono_loader_lock ();
8771 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8772 mono_loader_unlock ();
8773 g_assert (tls);
8775 compute_frame_info (thread, tls);
8776 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
8777 return ERR_INVALID_ARGUMENT;
8779 seq_points = get_seq_points (domain, method);
8780 g_assert (seq_points);
8782 for (i = 0; i < seq_points->len; ++i) {
8783 sp = &seq_points->seq_points [i];
8785 if (sp->il_offset == il_offset)
8786 break;
8788 if (i == seq_points->len)
8789 return ERR_INVALID_ARGUMENT;
8791 // FIXME: Check that the ip change is safe
8793 DEBUG (1, fprintf (log_file, "[dbg] Setting IP to %s:0x%0x(0x%0x)\n", tls->frames [0]->actual_method->name, (int)sp->il_offset, (int)sp->native_offset));
8794 MONO_CONTEXT_SET_IP (&tls->restore_ctx, (guint8*)tls->frames [0]->ji->code_start + sp->native_offset);
8795 break;
8797 default:
8798 return ERR_NOT_IMPLEMENTED;
8801 return ERR_NONE;
8804 static ErrorCode
8805 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8807 int objid;
8808 int err;
8809 MonoThread *thread_obj;
8810 MonoInternalThread *thread;
8811 int pos, i, len, frame_idx;
8812 DebuggerTlsData *tls;
8813 StackFrame *frame;
8814 MonoDebugMethodJitInfo *jit;
8815 MonoDebugVarInfo *var;
8816 MonoMethodSignature *sig;
8817 gssize id;
8818 MonoMethodHeader *header;
8820 objid = decode_objid (p, &p, end);
8821 err = get_object (objid, (MonoObject**)&thread_obj);
8822 if (err)
8823 return err;
8825 thread = THREAD_TO_INTERNAL (thread_obj);
8827 id = decode_id (p, &p, end);
8829 mono_loader_lock ();
8830 tls = mono_g_hash_table_lookup (thread_to_tls, thread);
8831 mono_loader_unlock ();
8832 g_assert (tls);
8834 for (i = 0; i < tls->frame_count; ++i) {
8835 if (tls->frames [i]->id == id)
8836 break;
8838 if (i == tls->frame_count)
8839 return ERR_INVALID_FRAMEID;
8841 frame_idx = i;
8842 frame = tls->frames [frame_idx];
8844 if (!frame->has_ctx)
8845 return ERR_ABSENT_INFORMATION;
8847 if (!frame->jit) {
8848 frame->jit = mono_debug_find_method (frame->api_method, frame->domain);
8849 if (!frame->jit && frame->api_method->is_inflated)
8850 frame->jit = mono_debug_find_method (mono_method_get_declaring_generic_method (frame->api_method), frame->domain);
8851 if (!frame->jit) {
8852 char *s;
8854 /* This could happen for aot images with no jit debug info */
8855 s = mono_method_full_name (frame->api_method, TRUE);
8856 DEBUG (1, fprintf (log_file, "[dbg] No debug information found for '%s'.\n", s));
8857 g_free (s);
8858 return ERR_ABSENT_INFORMATION;
8861 jit = frame->jit;
8863 sig = mono_method_signature (frame->actual_method);
8865 if (!get_seq_points (frame->domain, frame->actual_method))
8867 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
8869 return ERR_ABSENT_INFORMATION;
8871 switch (command) {
8872 case CMD_STACK_FRAME_GET_VALUES: {
8873 len = decode_int (p, &p, end);
8874 header = mono_method_get_header (frame->actual_method);
8876 for (i = 0; i < len; ++i) {
8877 pos = decode_int (p, &p, end);
8879 if (pos < 0) {
8880 pos = - pos - 1;
8882 g_assert (pos >= 0 && pos < jit->num_params);
8884 var = &jit->params [pos];
8886 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->domain, FALSE);
8887 } else {
8888 g_assert (pos >= 0 && pos < jit->num_locals);
8890 var = &jit->locals [pos];
8892 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->domain, FALSE);
8895 mono_metadata_free_mh (header);
8896 break;
8898 case CMD_STACK_FRAME_GET_THIS: {
8899 if (frame->api_method->klass->valuetype) {
8900 if (!sig->hasthis) {
8901 MonoObject *p = NULL;
8902 buffer_add_value (buf, &mono_defaults.object_class->byval_arg, &p, frame->domain);
8903 } else {
8904 add_var (buf, jit, &frame->actual_method->klass->this_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8906 } else {
8907 if (!sig->hasthis) {
8908 MonoObject *p = NULL;
8909 buffer_add_value (buf, &frame->actual_method->klass->byval_arg, &p, frame->domain);
8910 } else {
8911 add_var (buf, jit, &frame->api_method->klass->byval_arg, jit->this_var, &frame->ctx, frame->domain, TRUE);
8914 break;
8916 case CMD_STACK_FRAME_SET_VALUES: {
8917 guint8 *val_buf;
8918 MonoType *t;
8919 MonoDebugVarInfo *var;
8921 len = decode_int (p, &p, end);
8922 header = mono_method_get_header (frame->actual_method);
8924 for (i = 0; i < len; ++i) {
8925 pos = decode_int (p, &p, end);
8927 if (pos < 0) {
8928 pos = - pos - 1;
8930 g_assert (pos >= 0 && pos < jit->num_params);
8932 t = sig->params [pos];
8933 var = &jit->params [pos];
8934 } else {
8935 g_assert (pos >= 0 && pos < jit->num_locals);
8937 t = header->locals [pos];
8938 var = &jit->locals [pos];
8941 if (MONO_TYPE_IS_REFERENCE (t))
8942 val_buf = g_alloca (sizeof (MonoObject*));
8943 else
8944 val_buf = g_alloca (mono_class_instance_size (mono_class_from_mono_type (t)));
8945 err = decode_value (t, frame->domain, val_buf, p, &p, end);
8946 if (err)
8947 return err;
8949 set_var (t, var, &frame->ctx, frame->domain, val_buf, frame->reg_locations, &tls->restore_ctx);
8951 mono_metadata_free_mh (header);
8952 break;
8954 default:
8955 return ERR_NOT_IMPLEMENTED;
8958 return ERR_NONE;
8961 static ErrorCode
8962 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8964 MonoArray *arr;
8965 int objid, err, index, len, i, esize;
8966 gpointer elem;
8968 objid = decode_objid (p, &p, end);
8969 err = get_object (objid, (MonoObject**)&arr);
8970 if (err)
8971 return err;
8973 switch (command) {
8974 case CMD_ARRAY_REF_GET_LENGTH:
8975 buffer_add_int (buf, arr->obj.vtable->klass->rank);
8976 if (!arr->bounds) {
8977 buffer_add_int (buf, arr->max_length);
8978 buffer_add_int (buf, 0);
8979 } else {
8980 for (i = 0; i < arr->obj.vtable->klass->rank; ++i) {
8981 buffer_add_int (buf, arr->bounds [i].length);
8982 buffer_add_int (buf, arr->bounds [i].lower_bound);
8985 break;
8986 case CMD_ARRAY_REF_GET_VALUES:
8987 index = decode_int (p, &p, end);
8988 len = decode_int (p, &p, end);
8990 g_assert (index >= 0 && len >= 0);
8991 // Reordered to avoid integer overflow
8992 g_assert (!(index > arr->max_length - len));
8994 esize = mono_array_element_size (arr->obj.vtable->klass);
8995 for (i = index; i < index + len; ++i) {
8996 elem = (gpointer*)((char*)arr->vector + (i * esize));
8997 buffer_add_value (buf, &arr->obj.vtable->klass->element_class->byval_arg, elem, arr->obj.vtable->domain);
8999 break;
9000 case CMD_ARRAY_REF_SET_VALUES:
9001 index = decode_int (p, &p, end);
9002 len = decode_int (p, &p, end);
9004 g_assert (index >= 0 && len >= 0);
9005 // Reordered to avoid integer overflow
9006 g_assert (!(index > arr->max_length - len));
9008 esize = mono_array_element_size (arr->obj.vtable->klass);
9009 for (i = index; i < index + len; ++i) {
9010 elem = (gpointer*)((char*)arr->vector + (i * esize));
9012 decode_value (&arr->obj.vtable->klass->element_class->byval_arg, arr->obj.vtable->domain, elem, p, &p, end);
9014 break;
9015 default:
9016 return ERR_NOT_IMPLEMENTED;
9019 return ERR_NONE;
9022 static ErrorCode
9023 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9025 int objid, err;
9026 MonoString *str;
9027 char *s;
9028 int i, index, length;
9029 gunichar2 *c;
9031 objid = decode_objid (p, &p, end);
9032 err = get_object (objid, (MonoObject**)&str);
9033 if (err)
9034 return err;
9036 switch (command) {
9037 case CMD_STRING_REF_GET_VALUE:
9038 s = mono_string_to_utf8 (str);
9039 buffer_add_string (buf, s);
9040 g_free (s);
9041 break;
9042 case CMD_STRING_REF_GET_LENGTH:
9043 buffer_add_long (buf, mono_string_length (str));
9044 break;
9045 case CMD_STRING_REF_GET_CHARS:
9046 index = decode_long (p, &p, end);
9047 length = decode_long (p, &p, end);
9048 if (index > mono_string_length (str) - length)
9049 return ERR_INVALID_ARGUMENT;
9050 c = mono_string_chars (str) + index;
9051 for (i = 0; i < length; ++i)
9052 buffer_add_short (buf, c [i]);
9053 break;
9054 default:
9055 return ERR_NOT_IMPLEMENTED;
9058 return ERR_NONE;
9061 static ErrorCode
9062 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9064 int objid, err;
9065 MonoObject *obj;
9066 int len, i;
9067 MonoClassField *f;
9068 MonoClass *k;
9069 gboolean found;
9071 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9072 objid = decode_objid (p, &p, end);
9073 err = get_object (objid, &obj);
9074 if (err)
9075 buffer_add_int (buf, 1);
9076 else
9077 buffer_add_int (buf, 0);
9078 return 0;
9081 objid = decode_objid (p, &p, end);
9082 err = get_object (objid, &obj);
9083 if (err)
9084 return err;
9086 switch (command) {
9087 case CMD_OBJECT_REF_GET_TYPE:
9088 /* This handles transparent proxies too */
9089 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9090 break;
9091 case CMD_OBJECT_REF_GET_VALUES:
9092 len = decode_int (p, &p, end);
9094 for (i = 0; i < len; ++i) {
9095 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9096 if (err)
9097 return err;
9099 /* Check that the field belongs to the object */
9100 found = FALSE;
9101 for (k = obj->vtable->klass; k; k = k->parent) {
9102 if (k == f->parent) {
9103 found = TRUE;
9104 break;
9107 if (!found)
9108 return ERR_INVALID_FIELDID;
9110 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9111 guint8 *val;
9112 MonoVTable *vtable;
9114 if (mono_class_field_is_special_static (f))
9115 return ERR_INVALID_FIELDID;
9117 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9118 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9119 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9120 mono_field_static_get_value (vtable, f, val);
9121 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9122 g_free (val);
9123 } else {
9124 buffer_add_value (buf, f->type, (guint8*)obj + f->offset, obj->vtable->domain);
9127 break;
9128 case CMD_OBJECT_REF_SET_VALUES:
9129 len = decode_int (p, &p, end);
9131 for (i = 0; i < len; ++i) {
9132 f = decode_fieldid (p, &p, end, NULL, &err);
9133 if (err)
9134 return err;
9136 /* Check that the field belongs to the object */
9137 found = FALSE;
9138 for (k = obj->vtable->klass; k; k = k->parent) {
9139 if (k == f->parent) {
9140 found = TRUE;
9141 break;
9144 if (!found)
9145 return ERR_INVALID_FIELDID;
9147 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9148 guint8 *val;
9149 MonoVTable *vtable;
9151 if (mono_class_field_is_special_static (f))
9152 return ERR_INVALID_FIELDID;
9154 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9155 vtable = mono_class_vtable (obj->vtable->domain, f->parent);
9157 val = g_malloc (mono_class_instance_size (mono_class_from_mono_type (f->type)));
9158 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end);
9159 if (err) {
9160 g_free (val);
9161 return err;
9163 mono_field_static_set_value (vtable, f, val);
9164 g_free (val);
9165 } else {
9166 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end);
9167 if (err)
9168 return err;
9171 break;
9172 case CMD_OBJECT_REF_GET_ADDRESS:
9173 buffer_add_long (buf, (gssize)obj);
9174 break;
9175 case CMD_OBJECT_REF_GET_DOMAIN:
9176 buffer_add_domainid (buf, obj->vtable->domain);
9177 break;
9178 case CMD_OBJECT_REF_GET_INFO:
9179 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type (((MonoReflectionType*)obj->vtable->type)->type));
9180 buffer_add_domainid (buf, obj->vtable->domain);
9181 break;
9182 default:
9183 return ERR_NOT_IMPLEMENTED;
9186 return ERR_NONE;
9189 static const char*
9190 command_set_to_string (CommandSet command_set)
9192 switch (command_set) {
9193 case CMD_SET_VM:
9194 return "VM";
9195 case CMD_SET_OBJECT_REF:
9196 return "OBJECT_REF";
9197 case CMD_SET_STRING_REF:
9198 return "STRING_REF";
9199 case CMD_SET_THREAD:
9200 return "THREAD";
9201 case CMD_SET_ARRAY_REF:
9202 return "ARRAY_REF";
9203 case CMD_SET_EVENT_REQUEST:
9204 return "EVENT_REQUEST";
9205 case CMD_SET_STACK_FRAME:
9206 return "STACK_FRAME";
9207 case CMD_SET_APPDOMAIN:
9208 return "APPDOMAIN";
9209 case CMD_SET_ASSEMBLY:
9210 return "ASSEMBLY";
9211 case CMD_SET_METHOD:
9212 return "METHOD";
9213 case CMD_SET_TYPE:
9214 return "TYPE";
9215 case CMD_SET_MODULE:
9216 return "MODULE";
9217 case CMD_SET_FIELD:
9218 return "FIELD";
9219 case CMD_SET_EVENT:
9220 return "EVENT";
9221 default:
9222 return "";
9226 static const char* vm_cmds_str [] = {
9227 "VERSION",
9228 "ALL_THREADS",
9229 "SUSPEND",
9230 "RESUME",
9231 "EXIT",
9232 "DISPOSE",
9233 "INVOKE_METHOD",
9234 "SET_PROTOCOL_VERSION",
9235 "ABORT_INVOKE",
9236 "SET_KEEPALIVE"
9237 "GET_TYPES_FOR_SOURCE_FILE",
9238 "GET_TYPES",
9239 "INVOKE_METHODS"
9242 static const char* thread_cmds_str[] = {
9243 "GET_FRAME_INFO",
9244 "GET_NAME",
9245 "GET_STATE",
9246 "GET_INFO",
9247 "GET_ID",
9248 "GET_TID",
9249 "SET_IP"
9252 static const char* event_cmds_str[] = {
9253 "REQUEST_SET",
9254 "REQUEST_CLEAR",
9255 "REQUEST_CLEAR_ALL_BREAKPOINTS"
9258 static const char* appdomain_cmds_str[] = {
9259 "GET_ROOT_DOMAIN",
9260 "GET_FRIENDLY_NAME",
9261 "GET_ASSEMBLIES",
9262 "GET_ENTRY_ASSEMBLY",
9263 "CREATE_STRING",
9264 "GET_CORLIB",
9265 "CREATE_BOXED_VALUE"
9268 static const char* assembly_cmds_str[] = {
9269 "GET_LOCATION",
9270 "GET_ENTRY_POINT",
9271 "GET_MANIFEST_MODULE",
9272 "GET_OBJECT",
9273 "GET_TYPE",
9274 "GET_NAME"
9277 static const char* module_cmds_str[] = {
9278 "GET_INFO",
9281 static const char* field_cmds_str[] = {
9282 "GET_INFO",
9285 static const char* method_cmds_str[] = {
9286 "GET_NAME",
9287 "GET_DECLARING_TYPE",
9288 "GET_DEBUG_INFO",
9289 "GET_PARAM_INFO",
9290 "GET_LOCALS_INFO",
9291 "GET_INFO",
9292 "GET_BODY",
9293 "RESOLVE_TOKEN",
9294 "GET_CATTRS ",
9295 "MAKE_GENERIC_METHOD"
9298 static const char* type_cmds_str[] = {
9299 "GET_INFO",
9300 "GET_METHODS",
9301 "GET_FIELDS",
9302 "GET_VALUES",
9303 "GET_OBJECT",
9304 "GET_SOURCE_FILES",
9305 "SET_VALUES",
9306 "IS_ASSIGNABLE_FROM",
9307 "GET_PROPERTIES ",
9308 "GET_CATTRS",
9309 "GET_FIELD_CATTRS",
9310 "GET_PROPERTY_CATTRS",
9311 "GET_SOURCE_FILES_2",
9312 "GET_VALUES_2",
9313 "GET_METHODS_BY_NAME_FLAGS",
9314 "GET_INTERFACES",
9315 "GET_INTERFACE_MAP",
9316 "IS_INITIALIZED"
9319 static const char* stack_frame_cmds_str[] = {
9320 "GET_VALUES",
9321 "GET_THIS",
9322 "SET_VALUES"
9325 static const char* array_cmds_str[] = {
9326 "GET_LENGTH",
9327 "GET_VALUES",
9328 "SET_VALUES",
9331 static const char* string_cmds_str[] = {
9332 "GET_VALUE",
9333 "GET_LENGTH",
9334 "GET_CHARS"
9337 static const char* object_cmds_str[] = {
9338 "GET_TYPE",
9339 "GET_VALUES",
9340 "IS_COLLECTED",
9341 "GET_ADDRESS",
9342 "GET_DOMAIN",
9343 "SET_VALUES",
9344 "GET_INFO",
9347 static const char*
9348 cmd_to_string (CommandSet set, int command)
9350 const char **cmds;
9351 int cmds_len = 0;
9353 switch (set) {
9354 case CMD_SET_VM:
9355 cmds = vm_cmds_str;
9356 cmds_len = G_N_ELEMENTS (vm_cmds_str);
9357 break;
9358 case CMD_SET_OBJECT_REF:
9359 cmds = object_cmds_str;
9360 cmds_len = G_N_ELEMENTS (object_cmds_str);
9361 break;
9362 case CMD_SET_STRING_REF:
9363 cmds = string_cmds_str;
9364 cmds_len = G_N_ELEMENTS (string_cmds_str);
9365 break;
9366 case CMD_SET_THREAD:
9367 cmds = thread_cmds_str;
9368 cmds_len = G_N_ELEMENTS (thread_cmds_str);
9369 break;
9370 case CMD_SET_ARRAY_REF:
9371 cmds = array_cmds_str;
9372 cmds_len = G_N_ELEMENTS (array_cmds_str);
9373 break;
9374 case CMD_SET_EVENT_REQUEST:
9375 cmds = event_cmds_str;
9376 cmds_len = G_N_ELEMENTS (event_cmds_str);
9377 break;
9378 case CMD_SET_STACK_FRAME:
9379 cmds = stack_frame_cmds_str;
9380 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
9381 break;
9382 case CMD_SET_APPDOMAIN:
9383 cmds = appdomain_cmds_str;
9384 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
9385 break;
9386 case CMD_SET_ASSEMBLY:
9387 cmds = assembly_cmds_str;
9388 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
9389 break;
9390 case CMD_SET_METHOD:
9391 cmds = method_cmds_str;
9392 cmds_len = G_N_ELEMENTS (method_cmds_str);
9393 break;
9394 case CMD_SET_TYPE:
9395 cmds = type_cmds_str;
9396 cmds_len = G_N_ELEMENTS (type_cmds_str);
9397 break;
9398 case CMD_SET_MODULE:
9399 cmds = module_cmds_str;
9400 cmds_len = G_N_ELEMENTS (module_cmds_str);
9401 break;
9402 case CMD_SET_FIELD:
9403 cmds = field_cmds_str;
9404 cmds_len = G_N_ELEMENTS (field_cmds_str);
9405 break;
9406 case CMD_SET_EVENT:
9407 cmds = event_cmds_str;
9408 cmds_len = G_N_ELEMENTS (event_cmds_str);
9409 break;
9410 default:
9411 return NULL;
9413 if (command > 0 && command <= cmds_len)
9414 return cmds [command - 1];
9415 else
9416 return NULL;
9419 static gboolean
9420 wait_for_attach (void)
9422 #ifndef DISABLE_SOCKET_TRANSPORT
9423 if (listen_fd == -1) {
9424 DEBUG (1, fprintf (log_file, "[dbg] Invalid listening socket\n"));
9425 return FALSE;
9428 /* Block and wait for client connection */
9429 conn_fd = socket_transport_accept (listen_fd);
9430 DEBUG (1, fprintf (log_file, "Accepted connection on %d\n", conn_fd));
9431 if (conn_fd == -1) {
9432 DEBUG (1, fprintf (log_file, "[dbg] Bad client connection\n"));
9433 return FALSE;
9435 #else
9436 g_assert_not_reached ();
9437 #endif
9439 /* Handshake */
9440 disconnected = !transport_handshake ();
9441 if (disconnected) {
9442 DEBUG (1, fprintf (log_file, "Transport handshake failed!\n"));
9443 return FALSE;
9446 return TRUE;
9450 * debugger_thread:
9452 * This thread handles communication with the debugger client using a JDWP
9453 * like protocol.
9455 static guint32 WINAPI
9456 debugger_thread (void *arg)
9458 int res, len, id, flags, command_set = 0, command = 0;
9459 guint8 header [HEADER_LENGTH];
9460 guint8 *data, *p, *end;
9461 Buffer buf;
9462 ErrorCode err;
9463 gboolean no_reply;
9464 gboolean attach_failed = FALSE;
9466 DEBUG (1, fprintf (log_file, "[dbg] Agent thread started, pid=%p\n", (gpointer)GetCurrentThreadId ()));
9468 debugger_thread_id = GetCurrentThreadId ();
9470 mono_jit_thread_attach (mono_get_root_domain ());
9472 mono_thread_internal_current ()->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
9474 mono_set_is_debugger_attached (TRUE);
9476 if (agent_config.defer) {
9477 if (!wait_for_attach ()) {
9478 DEBUG (1, fprintf (log_file, "[dbg] Can't attach, aborting debugger thread.\n"));
9479 attach_failed = TRUE; // Don't abort process when we can't listen
9480 } else {
9481 /* Send start event to client */
9482 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
9486 while (!attach_failed) {
9487 res = transport_recv (header, HEADER_LENGTH);
9489 /* This will break if the socket is closed during shutdown too */
9490 if (res != HEADER_LENGTH) {
9491 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH));
9492 break;
9495 p = header;
9496 end = header + HEADER_LENGTH;
9498 len = decode_int (p, &p, end);
9499 id = decode_int (p, &p, end);
9500 flags = decode_byte (p, &p, end);
9501 command_set = decode_byte (p, &p, end);
9502 command = decode_byte (p, &p, end);
9504 g_assert (flags == 0);
9506 if (log_level) {
9507 const char *cmd_str;
9508 char cmd_num [256];
9510 cmd_str = cmd_to_string (command_set, command);
9511 if (!cmd_str) {
9512 sprintf (cmd_num, "%d", command);
9513 cmd_str = cmd_num;
9516 DEBUG (1, fprintf (log_file, "[dbg] Command %s(%s) [%d][at=%lx].\n", command_set_to_string (command_set), cmd_str, id, (long)mono_100ns_ticks () / 10000));
9519 data = g_malloc (len - HEADER_LENGTH);
9520 if (len - HEADER_LENGTH > 0)
9522 res = transport_recv (data, len - HEADER_LENGTH);
9523 if (res != len - HEADER_LENGTH) {
9524 DEBUG (1, fprintf (log_file, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH));
9525 break;
9529 p = data;
9530 end = data + (len - HEADER_LENGTH);
9532 buffer_init (&buf, 128);
9534 err = ERR_NONE;
9535 no_reply = FALSE;
9537 /* Process the request */
9538 switch (command_set) {
9539 case CMD_SET_VM:
9540 err = vm_commands (command, id, p, end, &buf);
9541 if (!err && command == CMD_VM_INVOKE_METHOD)
9542 /* Sent after the invoke is complete */
9543 no_reply = TRUE;
9544 break;
9545 case CMD_SET_EVENT_REQUEST:
9546 err = event_commands (command, p, end, &buf);
9547 break;
9548 case CMD_SET_APPDOMAIN:
9549 err = domain_commands (command, p, end, &buf);
9550 break;
9551 case CMD_SET_ASSEMBLY:
9552 err = assembly_commands (command, p, end, &buf);
9553 break;
9554 case CMD_SET_MODULE:
9555 err = module_commands (command, p, end, &buf);
9556 break;
9557 case CMD_SET_FIELD:
9558 err = field_commands (command, p, end, &buf);
9559 break;
9560 case CMD_SET_TYPE:
9561 err = type_commands (command, p, end, &buf);
9562 break;
9563 case CMD_SET_METHOD:
9564 err = method_commands (command, p, end, &buf);
9565 break;
9566 case CMD_SET_THREAD:
9567 err = thread_commands (command, p, end, &buf);
9568 break;
9569 case CMD_SET_STACK_FRAME:
9570 err = frame_commands (command, p, end, &buf);
9571 break;
9572 case CMD_SET_ARRAY_REF:
9573 err = array_commands (command, p, end, &buf);
9574 break;
9575 case CMD_SET_STRING_REF:
9576 err = string_commands (command, p, end, &buf);
9577 break;
9578 case CMD_SET_OBJECT_REF:
9579 err = object_commands (command, p, end, &buf);
9580 break;
9581 default:
9582 err = ERR_NOT_IMPLEMENTED;
9585 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
9586 buffer_replies = TRUE;
9589 if (!no_reply) {
9590 if (buffer_replies) {
9591 buffer_reply_packet (id, err, &buf);
9592 } else {
9593 send_reply_packet (id, err, &buf);
9594 //DEBUG (1, fprintf (log_file, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000));
9598 if (!err && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
9599 send_buffered_reply_packets ();
9600 buffer_replies = FALSE;
9603 g_free (data);
9604 buffer_free (&buf);
9606 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
9607 break;
9610 mono_set_is_debugger_attached (FALSE);
9612 mono_mutex_lock (&debugger_thread_exited_mutex);
9613 debugger_thread_exited = TRUE;
9614 mono_cond_signal (&debugger_thread_exited_cond);
9615 mono_mutex_unlock (&debugger_thread_exited_mutex);
9617 DEBUG (1, fprintf (log_file, "[dbg] Debugger thread exited.\n"));
9619 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
9620 DEBUG (2, fprintf (log_file, "[dbg] Detached - restarting clean debugger thread.\n"));
9621 start_debugger_thread ();
9624 return 0;
9627 #else /* DISABLE_DEBUGGER_AGENT */
9629 void
9630 mono_debugger_agent_parse_options (char *options)
9632 g_error ("This runtime is configured with the debugger agent disabled.");
9635 void
9636 mono_debugger_agent_init (void)
9640 void
9641 mono_debugger_agent_breakpoint_hit (void *sigctx)
9645 void
9646 mono_debugger_agent_single_step_event (void *sigctx)
9650 void
9651 mono_debugger_agent_free_domain_info (MonoDomain *domain)
9655 gboolean
9656 mono_debugger_agent_thread_interrupt (void *sigctx, MonoJitInfo *ji)
9658 return FALSE;
9661 void
9662 mono_debugger_agent_handle_exception (MonoException *ext, MonoContext *throw_ctx,
9663 MonoContext *catch_ctx)
9667 void
9668 mono_debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9672 void
9673 mono_debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
9677 void
9678 mono_debugger_agent_user_break (void)
9680 G_BREAKPOINT ();
9683 void
9684 mono_debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
9688 gboolean
9689 mono_debugger_agent_debug_log_is_enabled (void)
9691 return FALSE;
9694 #endif