Revert "[mono][debugger] First PR to implement iCorDebug on mono (#20757)"
[mono-project.git] / mono / mini / debugger-agent.c
blob09cac6ac5e7daa777c5d1403009c290dac262643
1 /**
2 * \file
3 * Soft Debugger back-end module
5 * Author:
6 * Zoltan Varga (vargaz@gmail.com)
8 * Copyright 2009-2010 Novell, Inc.
9 * Copyright 2011 Xamarin Inc.
10 * Licensed under the MIT license. See LICENSE file in the project root for full license information.
13 #include <config.h>
14 #include <stdio.h>
15 #include <stdlib.h>
16 #include <string.h>
17 #ifdef HAVE_SYS_TYPES_H
18 #include <sys/types.h>
19 #endif
20 #ifdef HAVE_SYS_SELECT_H
21 #include <sys/select.h>
22 #endif
23 #ifdef HAVE_SYS_SOCKET_H
24 #include <sys/socket.h>
25 #endif
26 #ifdef HAVE_NETINET_TCP_H
27 #include <netinet/tcp.h>
28 #endif
29 #ifdef HAVE_NETINET_IN_H
30 #include <netinet/in.h>
31 #endif
32 #ifdef HAVE_UNISTD_H
33 #include <unistd.h>
34 #endif
35 #include <errno.h>
36 #include <glib.h>
38 #ifdef HAVE_PTHREAD_H
39 #include <pthread.h>
40 #endif
42 #ifdef HOST_WIN32
43 #ifdef _MSC_VER
44 #include <winsock2.h>
45 #include <process.h>
46 #endif
47 #include <ws2tcpip.h>
48 #include <windows.h>
49 #endif
51 #ifdef HOST_ANDROID
52 #include <linux/in.h>
53 #include <linux/tcp.h>
54 #include <sys/endian.h>
55 #endif
57 #include <mono/metadata/mono-debug.h>
58 #include <mono/metadata/debug-internals.h>
59 #include <mono/metadata/domain-internals.h>
60 #include <mono/metadata/gc-internals.h>
61 #include <mono/metadata/environment.h>
62 #include <mono/metadata/mono-hash-internals.h>
63 #include <mono/metadata/threads-types.h>
64 #include <mono/metadata/threadpool.h>
65 #include <mono/metadata/assembly.h>
66 #include <mono/metadata/assembly-internals.h>
67 #include <mono/metadata/runtime.h>
68 #include <mono/metadata/verify-internals.h>
69 #include <mono/metadata/reflection-internals.h>
70 #include <mono/metadata/w32socket.h>
71 #include <mono/utils/mono-coop-mutex.h>
72 #include <mono/utils/mono-coop-semaphore.h>
73 #include <mono/utils/mono-error-internals.h>
74 #include <mono/utils/mono-stack-unwinding.h>
75 #include <mono/utils/mono-time.h>
76 #include <mono/utils/mono-threads.h>
77 #include <mono/utils/networking.h>
78 #include <mono/utils/mono-proclib.h>
79 #include <mono/utils/w32api.h>
80 #include <mono/utils/mono-logger-internals.h>
81 #include "debugger-state-machine.h"
82 #include "debugger-agent.h"
83 #include "mini.h"
84 #include "seq-points.h"
85 #include "aot-runtime.h"
86 #include "mini-runtime.h"
87 #include "interp/interp.h"
88 #include "debugger-engine.h"
89 #include "mono/metadata/debug-mono-ppdb.h"
90 #include "mono/metadata/custom-attrs-internals.h"
93 * On iOS we can't use System.Environment.Exit () as it will do the wrong
94 * shutdown sequence.
96 #if !defined (TARGET_IOS)
97 #define TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
98 #endif
100 #if DISABLE_SOCKETS
101 #define DISABLE_SOCKET_TRANSPORT
102 #endif
104 #ifndef DISABLE_SDB
106 #include <mono/utils/mono-os-mutex.h>
108 #include <fcntl.h>
109 #include <sys/stat.h>
111 #ifndef S_IWUSR
112 #define S_IWUSR S_IWRITE
113 #endif
115 #define THREAD_TO_INTERNAL(thread) (thread)->internal_thread
117 #if _MSC_VER
118 #pragma warning(disable:4312) // FIXME pointer cast to different size
119 #endif
121 typedef struct {
122 gboolean enabled;
123 char *transport;
124 char *address;
125 int log_level;
126 char *log_file;
127 gboolean suspend;
128 gboolean server;
129 gboolean onuncaught;
130 GSList *onthrow;
131 int timeout;
132 char *launch;
133 gboolean embedding;
134 gboolean defer;
135 int keepalive;
136 gboolean setpgid;
137 } AgentConfig;
139 typedef struct _InvokeData InvokeData;
141 struct _InvokeData
143 int id;
144 int flags;
145 guint8 *p;
146 guint8 *endp;
147 /* This is the context which needs to be restored after the invoke */
148 MonoContext ctx;
149 gboolean has_ctx;
151 * If this is set, invoke this method with the arguments given by ARGS.
153 MonoMethod *method;
154 gpointer *args;
155 guint32 suspend_count;
156 int nmethods;
158 InvokeData *last_invoke;
161 struct _DebuggerTlsData {
162 MonoThreadUnwindState context;
164 /* This is computed on demand when it is requested using the wire protocol */
165 /* It is freed up when the thread is resumed */
166 int frame_count;
167 StackFrame **frames;
169 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
170 * re-compute it.
172 gboolean frames_up_to_date;
174 * Points to data about a pending invoke which needs to be executed after the thread
175 * resumes.
177 InvokeData *pending_invoke;
179 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
180 * native code.
182 gboolean suspended;
184 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
185 * within a finite amount of time.
187 gboolean suspending;
189 * Set to TRUE if this thread is suspended in suspend_current ().
191 gboolean really_suspended;
192 /* Used to pass the context to the breakpoint/single step handler */
193 MonoContext handler_ctx;
194 /* Whenever thread_stop () was called for this thread */
195 gboolean terminated;
197 /* Whenever to disable breakpoints (used during invokes) */
198 gboolean disable_breakpoints;
201 * Number of times this thread has been resumed using resume_thread ().
203 guint32 resume_count;
204 guint32 resume_count_internal;
205 guint32 suspend_count;
207 MonoInternalThread *thread;
208 intptr_t thread_id;
211 * Information about the frame which transitioned to native code for running
212 * threads.
214 StackFrameInfo async_last_frame;
217 * The context where the stack walk can be started for running threads.
219 MonoThreadUnwindState async_state;
222 * The context used for filter clauses
224 MonoThreadUnwindState filter_state;
226 gboolean abort_requested;
229 * The current mono_runtime_invoke_checked invocation.
231 InvokeData *invoke;
233 StackFrameInfo catch_frame;
234 gboolean has_catch_frame;
237 * The context which needs to be restored after handling a single step/breakpoint
238 * event. This is the same as the ctx at step/breakpoint site, but includes changes
239 * to caller saved registers done by set_var ().
241 MonoThreadUnwindState restore_state;
242 /* Frames computed from restore_state */
243 int restore_frame_count;
244 StackFrame **restore_frames;
246 /* The currently unloading appdomain */
247 MonoDomain *domain_unloading;
249 // The state that the debugger expects the thread to be in
250 MonoDebuggerThreadState thread_state;
251 MonoStopwatch step_time;
253 gboolean gc_finalizing;
256 typedef struct {
257 const char *name;
258 void (*connect) (const char *address);
259 void (*close1) (void);
260 void (*close2) (void);
261 gboolean (*send) (void *buf, int len);
262 int (*recv) (void *buf, int len);
263 } DebuggerTransport;
266 * Wire Protocol definitions
269 #define HEADER_LENGTH 11
271 #define MAJOR_VERSION 2
272 #define MINOR_VERSION 58
274 typedef enum {
275 CMD_SET_VM = 1,
276 CMD_SET_OBJECT_REF = 9,
277 CMD_SET_STRING_REF = 10,
278 CMD_SET_THREAD = 11,
279 CMD_SET_ARRAY_REF = 13,
280 CMD_SET_EVENT_REQUEST = 15,
281 CMD_SET_STACK_FRAME = 16,
282 CMD_SET_APPDOMAIN = 20,
283 CMD_SET_ASSEMBLY = 21,
284 CMD_SET_METHOD = 22,
285 CMD_SET_TYPE = 23,
286 CMD_SET_MODULE = 24,
287 CMD_SET_FIELD = 25,
288 CMD_SET_EVENT = 64,
289 CMD_SET_POINTER = 65
290 } CommandSet;
292 typedef enum {
293 SUSPEND_POLICY_NONE = 0,
294 SUSPEND_POLICY_EVENT_THREAD = 1,
295 SUSPEND_POLICY_ALL = 2
296 } SuspendPolicy;
298 typedef enum {
299 ERR_NONE = 0,
300 ERR_INVALID_OBJECT = 20,
301 ERR_INVALID_FIELDID = 25,
302 ERR_INVALID_FRAMEID = 30,
303 ERR_NOT_IMPLEMENTED = 100,
304 ERR_NOT_SUSPENDED = 101,
305 ERR_INVALID_ARGUMENT = 102,
306 ERR_UNLOADED = 103,
307 ERR_NO_INVOCATION = 104,
308 ERR_ABSENT_INFORMATION = 105,
309 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
310 ERR_INVOKE_ABORTED = 107,
311 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
312 } ErrorCode;
314 typedef enum {
315 TOKEN_TYPE_STRING = 0,
316 TOKEN_TYPE_TYPE = 1,
317 TOKEN_TYPE_FIELD = 2,
318 TOKEN_TYPE_METHOD = 3,
319 TOKEN_TYPE_UNKNOWN = 4
320 } DebuggerTokenType;
322 typedef enum {
323 VALUE_TYPE_ID_NULL = 0xf0,
324 VALUE_TYPE_ID_TYPE = 0xf1,
325 VALUE_TYPE_ID_PARENT_VTYPE = 0xf2,
326 VALUE_TYPE_ID_FIXED_ARRAY = 0xf3
327 } ValueTypeId;
329 typedef enum {
330 FRAME_FLAG_DEBUGGER_INVOKE = 1,
331 FRAME_FLAG_NATIVE_TRANSITION = 2
332 } StackFrameFlags;
334 typedef enum {
335 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
336 INVOKE_FLAG_SINGLE_THREADED = 2,
337 INVOKE_FLAG_RETURN_OUT_THIS = 4,
338 INVOKE_FLAG_RETURN_OUT_ARGS = 8,
339 INVOKE_FLAG_VIRTUAL = 16
340 } InvokeFlags;
342 typedef enum {
343 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
344 } BindingFlagsExtensions;
346 typedef enum {
347 CMD_VM_VERSION = 1,
348 CMD_VM_ALL_THREADS = 2,
349 CMD_VM_SUSPEND = 3,
350 CMD_VM_RESUME = 4,
351 CMD_VM_EXIT = 5,
352 CMD_VM_DISPOSE = 6,
353 CMD_VM_INVOKE_METHOD = 7,
354 CMD_VM_SET_PROTOCOL_VERSION = 8,
355 CMD_VM_ABORT_INVOKE = 9,
356 CMD_VM_SET_KEEPALIVE = 10,
357 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
358 CMD_VM_GET_TYPES = 12,
359 CMD_VM_INVOKE_METHODS = 13,
360 CMD_VM_START_BUFFERING = 14,
361 CMD_VM_STOP_BUFFERING = 15
362 } CmdVM;
364 typedef enum {
365 CMD_THREAD_GET_FRAME_INFO = 1,
366 CMD_THREAD_GET_NAME = 2,
367 CMD_THREAD_GET_STATE = 3,
368 CMD_THREAD_GET_INFO = 4,
369 CMD_THREAD_GET_ID = 5,
370 CMD_THREAD_GET_TID = 6,
371 CMD_THREAD_SET_IP = 7,
372 CMD_THREAD_ELAPSED_TIME = 8
373 } CmdThread;
375 typedef enum {
376 CMD_EVENT_REQUEST_SET = 1,
377 CMD_EVENT_REQUEST_CLEAR = 2,
378 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
379 } CmdEvent;
381 typedef enum {
382 CMD_COMPOSITE = 100
383 } CmdComposite;
385 typedef enum {
386 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
387 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
388 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
389 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
390 CMD_APPDOMAIN_CREATE_STRING = 5,
391 CMD_APPDOMAIN_GET_CORLIB = 6,
392 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7,
393 CMD_APPDOMAIN_CREATE_BYTE_ARRAY = 8,
394 } CmdAppDomain;
396 typedef enum {
397 CMD_ASSEMBLY_GET_LOCATION = 1,
398 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
399 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
400 CMD_ASSEMBLY_GET_OBJECT = 4,
401 CMD_ASSEMBLY_GET_TYPE = 5,
402 CMD_ASSEMBLY_GET_NAME = 6,
403 CMD_ASSEMBLY_GET_DOMAIN = 7,
404 CMD_ASSEMBLY_GET_METADATA_BLOB = 8,
405 CMD_ASSEMBLY_GET_IS_DYNAMIC = 9,
406 CMD_ASSEMBLY_GET_PDB_BLOB = 10,
407 CMD_ASSEMBLY_GET_TYPE_FROM_TOKEN = 11,
408 CMD_ASSEMBLY_GET_METHOD_FROM_TOKEN = 12,
409 CMD_ASSEMBLY_HAS_DEBUG_INFO = 13,
410 CMD_ASSEMBLY_GET_CATTRS = 14,
411 } CmdAssembly;
413 typedef enum {
414 CMD_MODULE_GET_INFO = 1,
415 } CmdModule;
417 typedef enum {
418 CMD_FIELD_GET_INFO = 1,
419 } CmdField;
421 typedef enum {
422 CMD_METHOD_GET_NAME = 1,
423 CMD_METHOD_GET_DECLARING_TYPE = 2,
424 CMD_METHOD_GET_DEBUG_INFO = 3,
425 CMD_METHOD_GET_PARAM_INFO = 4,
426 CMD_METHOD_GET_LOCALS_INFO = 5,
427 CMD_METHOD_GET_INFO = 6,
428 CMD_METHOD_GET_BODY = 7,
429 CMD_METHOD_RESOLVE_TOKEN = 8,
430 CMD_METHOD_GET_CATTRS = 9,
431 CMD_METHOD_MAKE_GENERIC_METHOD = 10
432 } CmdMethod;
434 typedef enum {
435 CMD_TYPE_GET_INFO = 1,
436 CMD_TYPE_GET_METHODS = 2,
437 CMD_TYPE_GET_FIELDS = 3,
438 CMD_TYPE_GET_VALUES = 4,
439 CMD_TYPE_GET_OBJECT = 5,
440 CMD_TYPE_GET_SOURCE_FILES = 6,
441 CMD_TYPE_SET_VALUES = 7,
442 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
443 CMD_TYPE_GET_PROPERTIES = 9,
444 CMD_TYPE_GET_CATTRS = 10,
445 CMD_TYPE_GET_FIELD_CATTRS = 11,
446 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
447 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
448 CMD_TYPE_GET_VALUES_2 = 14,
449 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
450 CMD_TYPE_GET_INTERFACES = 16,
451 CMD_TYPE_GET_INTERFACE_MAP = 17,
452 CMD_TYPE_IS_INITIALIZED = 18,
453 CMD_TYPE_CREATE_INSTANCE = 19,
454 CMD_TYPE_GET_VALUE_SIZE = 20
455 } CmdType;
457 typedef enum {
458 CMD_STACK_FRAME_GET_VALUES = 1,
459 CMD_STACK_FRAME_GET_THIS = 2,
460 CMD_STACK_FRAME_SET_VALUES = 3,
461 CMD_STACK_FRAME_GET_DOMAIN = 4,
462 CMD_STACK_FRAME_SET_THIS = 5,
463 } CmdStackFrame;
465 typedef enum {
466 CMD_ARRAY_REF_GET_LENGTH = 1,
467 CMD_ARRAY_REF_GET_VALUES = 2,
468 CMD_ARRAY_REF_SET_VALUES = 3,
469 } CmdArray;
471 typedef enum {
472 CMD_STRING_REF_GET_VALUE = 1,
473 CMD_STRING_REF_GET_LENGTH = 2,
474 CMD_STRING_REF_GET_CHARS = 3
475 } CmdString;
477 typedef enum {
478 CMD_POINTER_GET_VALUE = 1
479 } CmdPointer;
481 typedef enum {
482 CMD_OBJECT_REF_GET_TYPE = 1,
483 CMD_OBJECT_REF_GET_VALUES = 2,
484 CMD_OBJECT_REF_IS_COLLECTED = 3,
485 CMD_OBJECT_REF_GET_ADDRESS = 4,
486 CMD_OBJECT_REF_GET_DOMAIN = 5,
487 CMD_OBJECT_REF_SET_VALUES = 6,
488 CMD_OBJECT_REF_GET_INFO = 7,
489 } CmdObject;
492 * Contains additional information for an event
494 typedef struct {
495 /* For EVENT_KIND_EXCEPTION */
496 MonoObject *exc;
497 MonoContext catch_ctx;
498 gboolean caught;
499 /* For EVENT_KIND_USER_LOG */
500 int level;
501 char *category, *message;
502 /* For EVENT_KIND_TYPE_LOAD */
503 MonoClass *klass;
504 /* For EVENT_KIND_CRASH */
505 char *dump;
506 MonoStackHash *hashes;
507 } EventInfo;
509 typedef struct {
510 guint8 *buf, *p, *end;
511 } Buffer;
513 typedef struct ReplyPacket {
514 int id;
515 int error;
516 Buffer *data;
517 } ReplyPacket;
519 #ifdef HOST_WIN32
520 #define get_last_sock_error() WSAGetLastError()
521 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
522 #define MONO_EINTR WSAEINTR
523 #else
524 #define get_last_sock_error() errno
525 #define MONO_EWOULDBLOCK EWOULDBLOCK
526 #define MONO_EINTR EINTR
527 #endif
529 #define CHECK_PROTOCOL_VERSION(major,minor) \
530 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
533 * Globals
536 static AgentConfig agent_config;
539 * Whenever the agent is fully initialized.
540 * When using the onuncaught or onthrow options, only some parts of the agent are
541 * initialized on startup, and the full initialization which includes connection
542 * establishment and the startup of the agent thread is only done in response to
543 * an event.
545 static gint32 agent_inited;
547 #ifndef DISABLE_SOCKET_TRANSPORT
548 static int conn_fd;
549 static int listen_fd;
550 #endif
552 static int packet_id = 0;
554 static int objref_id = 0;
556 static int event_request_id = 0;
558 static int frame_id = 0;
560 static GPtrArray *event_requests;
562 static MonoNativeTlsKey debugger_tls_id;
564 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
566 /* Maps MonoInternalThread -> DebuggerTlsData */
567 /* Protected by the loader lock */
568 static MonoGHashTable *thread_to_tls;
570 /* Maps tid -> MonoInternalThread */
571 /* Protected by the loader lock */
572 static MonoGHashTable *tid_to_thread;
574 /* Maps tid -> MonoThread (not MonoInternalThread) */
575 /* Protected by the loader lock */
576 static MonoGHashTable *tid_to_thread_obj;
578 static MonoNativeThreadId debugger_thread_id;
580 static MonoThreadHandle *debugger_thread_handle;
582 static int log_level;
584 static int file_check_valid_memory = -1;
586 static char* filename_check_valid_memory;
588 static gboolean embedding;
590 static FILE *log_file;
592 /* Assemblies whose assembly load event has no been sent yet */
593 /* Protected by the dbg lock */
594 static GPtrArray *pending_assembly_loads;
596 /* Whenever the debugger thread has exited */
597 static gboolean debugger_thread_exited;
599 /* Cond variable used to wait for debugger_thread_exited becoming true */
600 static MonoCoopCond debugger_thread_exited_cond;
602 /* Mutex for the cond var above */
603 static MonoCoopMutex debugger_thread_exited_mutex;
605 /* The protocol version of the client */
606 static int major_version, minor_version;
608 /* Whenever the variables above are set by the client */
609 static gboolean protocol_version_set;
611 /* The number of times the runtime is suspended */
612 static gint32 suspend_count;
614 /* Whenever to buffer reply messages and send them together */
615 static gboolean buffer_replies;
617 /* Buffered reply packets */
618 static ReplyPacket reply_packets [128];
619 static int nreply_packets;
621 #define dbg_lock mono_de_lock
622 #define dbg_unlock mono_de_unlock
624 static void transport_init (void);
625 static void transport_connect (const char *address);
626 static gboolean transport_handshake (void);
627 static void register_transport (DebuggerTransport *trans);
629 static gsize WINAPI debugger_thread (void *arg);
631 static void runtime_initialized (MonoProfiler *prof);
633 static void runtime_shutdown (MonoProfiler *prof);
635 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
637 static void thread_end (MonoProfiler *prof, uintptr_t tid);
639 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain);
641 static void appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain);
643 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
645 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
647 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
649 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
651 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly);
653 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
655 static void gc_finalizing (MonoProfiler *prof);
657 static void gc_finalized (MonoProfiler *prof);
659 static void emit_assembly_load (gpointer assembly, gpointer user_data);
661 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
663 static void jit_done (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo);
665 static void jit_failed (MonoProfiler *prof, MonoMethod *method);
667 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo);
669 static void suspend_current (void);
671 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
673 static void clear_types_for_assembly (MonoAssembly *assembly);
675 static void process_profiler_event (EventKind event, gpointer arg);
677 /* Submodule init/cleanup */
678 static void event_requests_cleanup (void);
680 static void objrefs_init (void);
681 static void objrefs_cleanup (void);
683 static void ids_init (void);
684 static void ids_cleanup (void);
686 static void suspend_init (void);
688 static void start_debugger_thread (MonoError *error);
689 static void stop_debugger_thread (void);
691 static void finish_agent_init (gboolean on_startup);
693 static void process_profiler_event (EventKind event, gpointer arg);
695 static void invalidate_frames (DebuggerTlsData *tls);
697 /* Callbacks used by debugger-engine */
698 static MonoContext* tls_get_restore_state (void *the_tls);
699 static gboolean try_process_suspend (void *tls, MonoContext *ctx, gboolean from_breakpoint);
700 static gboolean begin_breakpoint_processing (void *tls, MonoContext *ctx, MonoJitInfo *ji, gboolean from_signal);
701 static void begin_single_step_processing (MonoContext *ctx, gboolean from_signal);
702 static void ss_discard_frame_context (void *the_tls);
703 static void ss_calculate_framecount (void *tls, MonoContext *ctx, gboolean force_use_ctx, DbgEngineStackFrame ***frames, int *nframes);
704 static gboolean ensure_jit (DbgEngineStackFrame* the_frame);
705 static int ensure_runtime_is_suspended (void);
706 static int get_this_async_id (DbgEngineStackFrame *frame);
707 static void* create_breakpoint_events (GPtrArray *ss_reqs, GPtrArray *bp_reqs, MonoJitInfo *ji, EventKind kind);
708 static void process_breakpoint_events (void *_evts, MonoMethod *method, MonoContext *ctx, int il_offset);
709 static int ss_create_init_args (SingleStepReq *ss_req, SingleStepArgs *args);
710 static void ss_args_destroy (SingleStepArgs *ss_args);
711 static int handle_multiple_ss_requests (void);
713 static GENERATE_TRY_GET_CLASS_WITH_CACHE (fixed_buffer, "System.Runtime.CompilerServices", "FixedBufferAttribute")
715 #ifndef DISABLE_SOCKET_TRANSPORT
716 static void
717 register_socket_transport (void);
718 #endif
720 static gboolean
721 is_debugger_thread (void)
723 MonoInternalThread *internal;
725 internal = mono_thread_internal_current ();
726 if (!internal)
727 return FALSE;
729 return internal->debugger_thread;
732 static int
733 parse_address (char *address, char **host, int *port)
735 char *pos = strchr (address, ':');
737 if (pos == NULL || pos == address)
738 return 1;
740 size_t len = pos - address;
741 *host = (char *)g_malloc (len + 1);
742 memcpy (*host, address, len);
743 (*host) [len] = '\0';
745 *port = atoi (pos + 1);
747 return 0;
750 static void
751 print_usage (void)
753 PRINT_ERROR_MSG ("Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
754 PRINT_ERROR_MSG ("Available options:\n");
755 PRINT_ERROR_MSG (" transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
756 PRINT_ERROR_MSG (" address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
757 PRINT_ERROR_MSG (" loglevel=<n>\t\t\tLog level (defaults to 0)\n");
758 PRINT_ERROR_MSG (" logfile=<file>\t\tFile to log to (defaults to stdout)\n");
759 PRINT_ERROR_MSG (" suspend=y/n\t\t\tWhether to suspend after startup.\n");
760 PRINT_ERROR_MSG (" timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
761 PRINT_ERROR_MSG (" server=y/n\t\t\tWhether to listen for a client connection.\n");
762 PRINT_ERROR_MSG (" keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
763 PRINT_ERROR_MSG (" setpgid=y/n\t\t\tWhether to call setpid(0, 0) after startup.\n");
764 PRINT_ERROR_MSG (" help\t\t\t\tPrint this help.\n");
767 static gboolean
768 parse_flag (const char *option, char *flag)
770 if (!strcmp (flag, "y"))
771 return TRUE;
772 else if (!strcmp (flag, "n"))
773 return FALSE;
774 else {
775 PRINT_ERROR_MSG ("debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
776 exit (1);
777 return FALSE;
781 static void
782 debugger_agent_parse_options (char *options)
784 char **args, **ptr;
785 char *host;
786 int port;
787 char *extra;
789 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
790 PRINT_ERROR_MSG ("--debugger-agent is not supported on this platform.\n");
791 exit (1);
792 #endif
794 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
795 if (extra) {
796 options = g_strdup_printf ("%s,%s", options, extra);
797 g_free (extra);
800 agent_config.enabled = TRUE;
801 agent_config.suspend = TRUE;
802 agent_config.server = FALSE;
803 agent_config.defer = FALSE;
804 agent_config.address = NULL;
806 //agent_config.log_level = 10;
808 args = g_strsplit (options, ",", -1);
809 for (ptr = args; ptr && *ptr; ptr ++) {
810 char *arg = *ptr;
812 if (strncmp (arg, "transport=", 10) == 0) {
813 agent_config.transport = g_strdup (arg + 10);
814 } else if (strncmp (arg, "address=", 8) == 0) {
815 agent_config.address = g_strdup (arg + 8);
816 } else if (strncmp (arg, "loglevel=", 9) == 0) {
817 agent_config.log_level = atoi (arg + 9);
818 } else if (strncmp (arg, "logfile=", 8) == 0) {
819 agent_config.log_file = g_strdup (arg + 8);
820 } else if (strncmp (arg, "suspend=", 8) == 0) {
821 agent_config.suspend = parse_flag ("suspend", arg + 8);
822 } else if (strncmp (arg, "server=", 7) == 0) {
823 agent_config.server = parse_flag ("server", arg + 7);
824 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
825 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
826 } else if (strncmp (arg, "onthrow=", 8) == 0) {
827 /* We support multiple onthrow= options */
828 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
829 } else if (strncmp (arg, "onthrow", 7) == 0) {
830 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
831 } else if (strncmp (arg, "help", 4) == 0) {
832 print_usage ();
833 exit (0);
834 } else if (strncmp (arg, "timeout=", 8) == 0) {
835 agent_config.timeout = atoi (arg + 8);
836 } else if (strncmp (arg, "launch=", 7) == 0) {
837 agent_config.launch = g_strdup (arg + 7);
838 } else if (strncmp (arg, "embedding=", 10) == 0) {
839 agent_config.embedding = atoi (arg + 10) == 1;
840 } else if (strncmp (arg, "keepalive=", 10) == 0) {
841 agent_config.keepalive = atoi (arg + 10);
842 } else if (strncmp (arg, "setpgid=", 8) == 0) {
843 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
844 } else {
845 print_usage ();
846 exit (1);
850 if (agent_config.server && !agent_config.suspend) {
851 /* Waiting for deferred attachment */
852 agent_config.defer = TRUE;
853 if (agent_config.address == NULL) {
854 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (mono_process_current_pid () % 1000));
858 //agent_config.log_level = 0;
860 if (agent_config.transport == NULL) {
861 PRINT_ERROR_MSG ("debugger-agent: The 'transport' option is mandatory.\n");
862 exit (1);
865 if (agent_config.address == NULL && !agent_config.server) {
866 PRINT_ERROR_MSG ("debugger-agent: The 'address' option is mandatory.\n");
867 exit (1);
870 // FIXME:
871 if (!strcmp (agent_config.transport, "dt_socket")) {
872 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
873 PRINT_ERROR_MSG ("debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
874 exit (1);
879 void
880 mono_debugger_set_thread_state (DebuggerTlsData *tls, MonoDebuggerThreadState expected, MonoDebuggerThreadState set)
882 g_assertf (tls, "Cannot get state of null thread", NULL);
884 g_assert (tls->thread_state == expected);
886 tls->thread_state = set;
889 MonoDebuggerThreadState
890 mono_debugger_get_thread_state (DebuggerTlsData *tls)
892 g_assertf (tls, "Cannot get state of null thread", NULL);
894 return tls->thread_state;
897 gsize
898 mono_debugger_tls_thread_id (DebuggerTlsData *tls)
900 if (!tls)
901 return 0;
903 return tls->thread_id;
906 // Only call this function with the loader lock held
907 MonoGHashTable *
908 mono_debugger_get_thread_states (void)
910 return thread_to_tls;
913 gboolean
914 mono_debugger_is_disconnected (void)
916 return disconnected;
919 static void
920 debugger_agent_init (void)
922 if (!agent_config.enabled)
923 return;
925 DebuggerEngineCallbacks cbs;
926 memset (&cbs, 0, sizeof (cbs));
927 cbs.tls_get_restore_state = tls_get_restore_state;
928 cbs.try_process_suspend = try_process_suspend;
929 cbs.begin_breakpoint_processing = begin_breakpoint_processing;
930 cbs.begin_single_step_processing = begin_single_step_processing;
931 cbs.ss_discard_frame_context = ss_discard_frame_context;
932 cbs.ss_calculate_framecount = ss_calculate_framecount;
933 cbs.ensure_jit = ensure_jit;
934 cbs.ensure_runtime_is_suspended = ensure_runtime_is_suspended;
935 cbs.get_this_async_id = get_this_async_id;
936 cbs.set_set_notification_for_wait_completion_flag = set_set_notification_for_wait_completion_flag;
937 cbs.get_notify_debugger_of_wait_completion_method = get_notify_debugger_of_wait_completion_method;
938 cbs.create_breakpoint_events = create_breakpoint_events;
939 cbs.process_breakpoint_events = process_breakpoint_events;
940 cbs.ss_create_init_args = ss_create_init_args;
941 cbs.ss_args_destroy = ss_args_destroy;
942 cbs.handle_multiple_ss_requests = handle_multiple_ss_requests;
944 mono_de_init (&cbs);
946 transport_init ();
948 /* Need to know whenever a thread has acquired the loader mutex */
949 mono_loader_lock_track_ownership (TRUE);
951 event_requests = g_ptr_array_new ();
953 mono_coop_mutex_init (&debugger_thread_exited_mutex);
954 mono_coop_cond_init (&debugger_thread_exited_cond);
956 MonoProfilerHandle prof = mono_profiler_create (NULL);
957 mono_profiler_set_runtime_shutdown_end_callback (prof, runtime_shutdown);
958 mono_profiler_set_runtime_initialized_callback (prof, runtime_initialized);
959 mono_profiler_set_domain_loaded_callback (prof, appdomain_load);
960 mono_profiler_set_domain_unloading_callback (prof, appdomain_start_unload);
961 mono_profiler_set_domain_unloaded_callback (prof, appdomain_unload);
962 mono_profiler_set_thread_started_callback (prof, thread_startup);
963 mono_profiler_set_thread_stopped_callback (prof, thread_end);
964 mono_profiler_set_assembly_loaded_callback (prof, assembly_load);
965 mono_profiler_set_assembly_unloading_callback (prof, assembly_unload);
966 mono_profiler_set_jit_done_callback (prof, jit_done);
967 mono_profiler_set_jit_failed_callback (prof, jit_failed);
968 mono_profiler_set_gc_finalizing_callback (prof, gc_finalizing);
969 mono_profiler_set_gc_finalized_callback (prof, gc_finalized);
971 mono_native_tls_alloc (&debugger_tls_id, NULL);
973 /* Needed by the hash_table_new_type () call below */
974 mono_gc_base_init ();
976 thread_to_tls = mono_g_hash_table_new_type_internal ((GHashFunc)mono_object_hash_internal, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_DEBUGGER, NULL, "Debugger TLS Table");
978 tid_to_thread = mono_g_hash_table_new_type_internal (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DEBUGGER, NULL, "Debugger Thread Table");
980 tid_to_thread_obj = mono_g_hash_table_new_type_internal (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DEBUGGER, NULL, "Debugger Thread Object Table");
982 pending_assembly_loads = g_ptr_array_new ();
984 log_level = agent_config.log_level;
986 embedding = agent_config.embedding;
987 disconnected = TRUE;
989 if (agent_config.log_file) {
990 log_file = fopen (agent_config.log_file, "w+");
991 if (!log_file) {
992 PRINT_ERROR_MSG ("Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
993 exit (1);
995 } else {
996 log_file = stdout;
998 mono_de_set_log_level (log_level, log_file);
1000 ids_init ();
1001 objrefs_init ();
1002 suspend_init ();
1004 mini_get_debug_options ()->gen_sdb_seq_points = TRUE;
1006 * This is needed because currently we don't handle liveness info.
1008 mini_get_debug_options ()->mdb_optimizations = TRUE;
1010 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
1011 /* This is needed because we can't set local variables in registers yet */
1012 mono_disable_optimizations (MONO_OPT_LINEARS);
1013 #endif
1016 * The stack walk done from thread_interrupt () needs to be signal safe, but it
1017 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
1018 * safe (#3411). So load AOT info eagerly when the debugger is running as a
1019 * workaround.
1021 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
1023 #ifdef HAVE_SETPGID
1024 if (agent_config.setpgid)
1025 setpgid (0, 0);
1026 #endif
1028 if (!agent_config.onuncaught && !agent_config.onthrow)
1029 finish_agent_init (TRUE);
1033 * finish_agent_init:
1035 * Finish the initialization of the agent. This involves connecting the transport
1036 * and starting the agent thread. This is either done at startup, or
1037 * in response to some event like an unhandled exception.
1039 static void
1040 finish_agent_init (gboolean on_startup)
1042 if (mono_atomic_cas_i32 (&agent_inited, 1, 0) == 1)
1043 return;
1045 if (agent_config.launch) {
1047 // FIXME: Generated address
1048 // FIXME: Races with transport_connect ()
1050 #ifdef G_OS_WIN32
1051 // Nothing. FIXME? g_spawn_async_with_pipes is easy enough to provide for Windows if needed.
1052 #elif !HAVE_G_SPAWN
1053 PRINT_ERROR_MSG ("g_spawn_async_with_pipes not supported on this platform\n");
1054 exit (1);
1055 #else
1056 char *argv [ ] = {
1057 agent_config.launch,
1058 agent_config.transport,
1059 agent_config.address,
1060 NULL
1062 int res = g_spawn_async_with_pipes (NULL, argv, NULL, (GSpawnFlags)0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1063 if (!res) {
1064 PRINT_ERROR_MSG ("Failed to execute '%s'.\n", agent_config.launch);
1065 exit (1);
1067 #endif
1070 transport_connect (agent_config.address);
1072 if (!on_startup) {
1073 /* Do some which is usually done after sending the VMStart () event */
1074 vm_start_event_sent = TRUE;
1075 ERROR_DECL (error);
1076 start_debugger_thread (error);
1077 mono_error_assert_ok (error);
1081 static void
1082 mono_debugger_agent_cleanup (void)
1084 if (!agent_inited)
1085 return;
1087 stop_debugger_thread ();
1089 event_requests_cleanup ();
1090 objrefs_cleanup ();
1091 ids_cleanup ();
1093 mono_de_cleanup ();
1095 if (file_check_valid_memory != -1) {
1096 remove (filename_check_valid_memory);
1097 g_free (filename_check_valid_memory);
1098 close (file_check_valid_memory);
1103 * SOCKET TRANSPORT
1106 #ifndef DISABLE_SOCKET_TRANSPORT
1109 * recv_length:
1111 * recv() + handle incomplete reads and EINTR
1113 static int
1114 socket_transport_recv (void *buf, int len)
1116 int res;
1117 int total = 0;
1118 int fd = conn_fd;
1119 int flags = 0;
1120 static gint64 last_keepalive;
1121 gint64 msecs;
1123 MONO_ENTER_GC_SAFE;
1125 do {
1126 again:
1127 res = recv (fd, (char *) buf + total, len - total, flags);
1128 if (res > 0)
1129 total += res;
1130 if (agent_config.keepalive) {
1131 gboolean need_keepalive = FALSE;
1132 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1133 need_keepalive = TRUE;
1134 } else if (res == -1) {
1135 /* This could happen if recv () is interrupted repeatedly */
1136 msecs = mono_msec_ticks ();
1137 if (msecs - last_keepalive >= agent_config.keepalive) {
1138 need_keepalive = TRUE;
1139 last_keepalive = msecs;
1142 if (need_keepalive) {
1143 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1144 goto again;
1147 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1149 MONO_EXIT_GC_SAFE;
1151 return total;
1154 static void
1155 set_keepalive (void)
1157 struct timeval tv;
1158 int result;
1160 if (!agent_config.keepalive || !conn_fd)
1161 return;
1163 tv.tv_sec = agent_config.keepalive / 1000;
1164 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1166 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1167 g_assert (result >= 0);
1170 static int
1171 socket_transport_accept (int socket_fd)
1173 MONO_ENTER_GC_SAFE;
1174 conn_fd = accept (socket_fd, NULL, NULL);
1175 MONO_EXIT_GC_SAFE;
1177 if (conn_fd == -1) {
1178 PRINT_ERROR_MSG ("debugger-agent: Unable to listen on %d\n", socket_fd);
1179 } else {
1180 PRINT_DEBUG_MSG (1, "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 MONO_ENTER_GC_SAFE;
1193 do {
1194 res = send (conn_fd, (const char*)data, len, 0);
1195 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1197 MONO_EXIT_GC_SAFE;
1199 if (res != len)
1200 return FALSE;
1201 else
1202 return TRUE;
1206 * socket_transport_connect:
1208 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1210 static void
1211 socket_transport_connect (const char *address)
1213 MonoAddressInfo *result;
1214 MonoAddressEntry *rp;
1215 int sfd = -1, s, res;
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 int hints[] = {
1232 MONO_HINT_IPV4 | MONO_HINT_NUMERIC_HOST,
1233 MONO_HINT_IPV6 | MONO_HINT_NUMERIC_HOST,
1234 MONO_HINT_UNSPECIFIED
1237 mono_network_init ();
1239 for (int i = 0; i < sizeof(hints) / sizeof(int); i++) {
1240 /* Obtain address(es) matching host/port */
1241 s = mono_get_address_info (host, port, hints[i], &result);
1242 if (s == 0)
1243 break;
1245 if (s != 0) {
1246 PRINT_ERROR_MSG ("debugger-agent: Unable to resolve %s:%d: %d\n", host, port, s); // FIXME add portable error conversion functions
1247 exit (1);
1251 if (agent_config.server) {
1252 /* Wait for a connection */
1253 if (!host) {
1254 struct sockaddr_in addr;
1255 socklen_t addrlen;
1257 /* No address, generate one */
1258 sfd = socket (AF_INET, SOCK_STREAM, 0);
1259 if (sfd == -1) {
1260 PRINT_ERROR_MSG ("debugger-agent: Unable to create a socket: %s\n", strerror (get_last_sock_error ()));
1261 exit (1);
1264 /* This will bind the socket to a random port */
1265 res = listen (sfd, 16);
1266 if (res == -1) {
1267 PRINT_ERROR_MSG ("debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1268 exit (1);
1270 listen_fd = sfd;
1272 addrlen = sizeof (addr);
1273 memset (&addr, 0, sizeof (addr));
1274 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1275 g_assert (res == 0);
1277 host = (char*)"127.0.0.1";
1278 port = ntohs (addr.sin_port);
1280 /* Emit the address to stdout */
1281 /* FIXME: Should print another interface, not localhost */
1282 PRINT_MSG ("%s:%d\n", host, port);
1283 } else {
1284 /* Listen on the provided address */
1285 for (rp = result->entries; rp != NULL; rp = rp->next) {
1286 MonoSocketAddress sockaddr;
1287 socklen_t sock_len;
1288 int n = 1;
1290 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1292 sfd = socket (rp->family, rp->socktype,
1293 rp->protocol);
1294 if (sfd == -1)
1295 continue;
1297 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&n, sizeof(n)) == -1)
1298 continue;
1300 res = bind (sfd, &sockaddr.addr, sock_len);
1301 if (res == -1)
1302 continue;
1304 res = listen (sfd, 16);
1305 if (res == -1)
1306 continue;
1307 listen_fd = sfd;
1308 break;
1311 mono_free_address_info (result);
1314 if (agent_config.defer)
1315 return;
1317 PRINT_DEBUG_MSG (1, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout);
1319 if (agent_config.timeout) {
1320 fd_set readfds;
1321 struct timeval tv;
1323 tv.tv_sec = 0;
1324 tv.tv_usec = agent_config.timeout * 1000;
1325 FD_ZERO (&readfds);
1326 FD_SET (sfd, &readfds);
1328 MONO_ENTER_GC_SAFE;
1329 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1330 MONO_EXIT_GC_SAFE;
1332 if (res == 0) {
1333 PRINT_ERROR_MSG ("debugger-agent: Timed out waiting to connect.\n");
1334 exit (1);
1338 conn_fd = socket_transport_accept (sfd);
1339 if (conn_fd == -1)
1340 exit (1);
1342 PRINT_DEBUG_MSG (1, "Accepted connection from client, socket fd=%d.\n", conn_fd);
1343 } else {
1344 /* Connect to the specified address */
1345 /* FIXME: Respect the timeout */
1346 for (rp = result->entries; rp != NULL; rp = rp->next) {
1347 MonoSocketAddress sockaddr;
1348 socklen_t sock_len;
1350 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1352 sfd = socket (rp->family, rp->socktype,
1353 rp->protocol);
1354 if (sfd == -1)
1355 continue;
1357 MONO_ENTER_GC_SAFE;
1358 res = connect (sfd, &sockaddr.addr, sock_len);
1359 MONO_EXIT_GC_SAFE;
1361 if (res != -1)
1362 break; /* Success */
1364 MONO_ENTER_GC_SAFE;
1365 #ifdef HOST_WIN32
1366 closesocket (sfd);
1367 #else
1368 close (sfd);
1369 #endif
1370 MONO_EXIT_GC_SAFE;
1373 if (rp == 0) {
1374 PRINT_ERROR_MSG ("debugger-agent: Unable to connect to %s:%d\n", host, port);
1375 exit (1);
1378 conn_fd = sfd;
1380 mono_free_address_info (result);
1383 if (!transport_handshake ())
1384 exit (1);
1387 static void
1388 socket_transport_close1 (void)
1390 /* This will interrupt the agent thread */
1391 /* Close the read part only so it can still send back replies */
1392 /* Also shut down the connection listener so that we can exit normally */
1393 #ifdef HOST_WIN32
1394 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1395 shutdown (conn_fd, SD_BOTH);
1396 shutdown (listen_fd, SD_BOTH);
1397 closesocket (listen_fd);
1398 #else
1399 shutdown (conn_fd, SHUT_RD);
1400 shutdown (listen_fd, SHUT_RDWR);
1401 MONO_ENTER_GC_SAFE;
1402 close (listen_fd);
1403 MONO_EXIT_GC_SAFE;
1404 #endif
1407 static void
1408 socket_transport_close2 (void)
1410 #ifdef HOST_WIN32
1411 shutdown (conn_fd, SD_BOTH);
1412 #else
1413 shutdown (conn_fd, SHUT_RDWR);
1414 #endif
1417 static void
1418 register_socket_transport (void)
1420 DebuggerTransport trans;
1422 trans.name = "dt_socket";
1423 trans.connect = socket_transport_connect;
1424 trans.close1 = socket_transport_close1;
1425 trans.close2 = socket_transport_close2;
1426 trans.send = socket_transport_send;
1427 trans.recv = socket_transport_recv;
1429 register_transport (&trans);
1433 * socket_fd_transport_connect:
1436 static void
1437 socket_fd_transport_connect (const char *address)
1439 int res;
1441 res = sscanf (address, "%d", &conn_fd);
1442 if (res != 1) {
1443 PRINT_ERROR_MSG ("debugger-agent: socket-fd transport address is invalid: '%s'\n", address);
1444 exit (1);
1447 if (!transport_handshake ())
1448 exit (1);
1451 static void
1452 register_socket_fd_transport (void)
1454 DebuggerTransport trans;
1456 /* This is the same as the 'dt_socket' transport, but receives an already connected socket fd */
1457 trans.name = "socket-fd";
1458 trans.connect = socket_fd_transport_connect;
1459 trans.close1 = socket_transport_close1;
1460 trans.close2 = socket_transport_close2;
1461 trans.send = socket_transport_send;
1462 trans.recv = socket_transport_recv;
1464 register_transport (&trans);
1467 #endif /* DISABLE_SOCKET_TRANSPORT */
1470 * TRANSPORT CODE
1473 #define MAX_TRANSPORTS 16
1475 static DebuggerTransport *transport;
1477 static DebuggerTransport transports [MAX_TRANSPORTS];
1478 static int ntransports;
1480 MONO_API void
1481 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1483 void
1484 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1486 register_transport (trans);
1489 static void
1490 register_transport (DebuggerTransport *trans)
1492 g_assert (ntransports < MAX_TRANSPORTS);
1494 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1495 ntransports ++;
1498 static void
1499 transport_init (void)
1501 int i;
1503 #ifndef DISABLE_SOCKET_TRANSPORT
1504 register_socket_transport ();
1505 register_socket_fd_transport ();
1506 #endif
1508 for (i = 0; i < ntransports; ++i) {
1509 if (!strcmp (agent_config.transport, transports [i].name))
1510 break;
1512 if (i == ntransports) {
1513 PRINT_ERROR_MSG ("debugger-agent: The supported values for the 'transport' option are: ");
1514 for (i = 0; i < ntransports; ++i)
1515 PRINT_ERROR_MSG ("%s'%s'", i > 0 ? ", " : "", transports [i].name);
1516 PRINT_ERROR_MSG ("\n");
1517 exit (1);
1519 transport = &transports [i];
1522 void
1523 transport_connect (const char *address)
1525 transport->connect (address);
1528 static void
1529 transport_close1 (void)
1531 transport->close1 ();
1534 static void
1535 transport_close2 (void)
1537 transport->close2 ();
1540 static int
1541 transport_send (void *buf, int len)
1543 return transport->send (buf, len);
1546 static int
1547 transport_recv (void *buf, int len)
1549 return transport->recv (buf, len);
1552 gboolean
1553 mono_debugger_agent_transport_handshake (void)
1555 return transport_handshake ();
1558 static gboolean
1559 transport_handshake (void)
1561 char handshake_msg [128];
1562 guint8 buf [128];
1563 int res;
1565 disconnected = TRUE;
1567 /* Write handshake message */
1568 sprintf (handshake_msg, "DWP-Handshake");
1570 do {
1571 res = transport_send (handshake_msg, strlen (handshake_msg));
1572 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1574 g_assert (res != -1);
1576 /* Read answer */
1577 res = transport_recv (buf, strlen (handshake_msg));
1578 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg)) != 0)) {
1579 PRINT_ERROR_MSG ("debugger-agent: DWP handshake failed.\n");
1580 return FALSE;
1584 * To support older clients, the client sends its protocol version after connecting
1585 * using a command. Until that is received, default to our protocol version.
1587 major_version = MAJOR_VERSION;
1588 minor_version = MINOR_VERSION;
1589 protocol_version_set = FALSE;
1591 #ifndef DISABLE_SOCKET_TRANSPORT
1592 // FIXME: Move this somewhere else
1594 * Set TCP_NODELAY on the socket so the client receives events/command
1595 * results immediately.
1597 if (conn_fd) {
1598 int flag = 1;
1599 int result = setsockopt (conn_fd,
1600 IPPROTO_TCP,
1601 TCP_NODELAY,
1602 (char *) &flag,
1603 sizeof(int));
1604 g_assert (result >= 0);
1607 set_keepalive ();
1608 #endif
1610 disconnected = FALSE;
1611 return TRUE;
1614 static void
1615 stop_debugger_thread (void)
1617 if (!agent_inited)
1618 return;
1620 transport_close1 ();
1623 * Wait for the thread to exit.
1625 * If we continue with the shutdown without waiting for it, then the client might
1626 * not receive an answer to its last command like a resume.
1628 if (!is_debugger_thread ()) {
1629 do {
1630 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
1631 if (!debugger_thread_exited)
1632 mono_coop_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1633 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
1634 } while (!debugger_thread_exited);
1636 if (debugger_thread_handle)
1637 mono_thread_info_wait_one_handle (debugger_thread_handle, MONO_INFINITE_WAIT, TRUE);
1640 transport_close2 ();
1643 static void
1644 start_debugger_thread (MonoError *error)
1646 MonoInternalThread *thread;
1648 thread = mono_thread_create_internal (mono_get_root_domain (), (gpointer)debugger_thread, NULL, MONO_THREAD_CREATE_FLAGS_DEBUGGER, error);
1649 return_if_nok (error);
1651 /* Is it possible for the thread to be dead alreay ? */
1652 debugger_thread_handle = mono_threads_open_thread_handle (thread->handle);
1653 g_assert (debugger_thread_handle);
1658 * Functions to decode protocol data
1661 static int
1662 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1664 *endbuf = buf + 1;
1665 g_assert (*endbuf <= limit);
1666 return buf [0];
1669 static int
1670 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1672 *endbuf = buf + 4;
1673 g_assert (*endbuf <= limit);
1675 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1678 static gint64
1679 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1681 guint32 high = decode_int (buf, &buf, limit);
1682 guint32 low = decode_int (buf, &buf, limit);
1684 *endbuf = buf;
1686 return ((((guint64)high) << 32) | ((guint64)low));
1689 static int
1690 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1692 return decode_int (buf, endbuf, limit);
1695 static char*
1696 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1698 int len = decode_int (buf, &buf, limit);
1699 char *s;
1701 if (len < 0) {
1702 *endbuf = buf;
1703 return NULL;
1706 s = (char *)g_malloc (len + 1);
1707 g_assert (s);
1709 memcpy (s, buf, len);
1710 s [len] = '\0';
1711 buf += len;
1712 *endbuf = buf;
1714 return s;
1718 * Functions to encode protocol data
1721 static void
1722 buffer_init (Buffer *buf, int size)
1724 buf->buf = (guint8 *)g_malloc (size);
1725 buf->p = buf->buf;
1726 buf->end = buf->buf + size;
1729 static int
1730 buffer_len (Buffer *buf)
1732 return buf->p - buf->buf;
1735 static void
1736 buffer_make_room (Buffer *buf, int size)
1738 if (buf->end - buf->p < size) {
1739 int new_size = buf->end - buf->buf + size + 32;
1740 guint8 *p = (guint8 *)g_realloc (buf->buf, new_size);
1741 size = buf->p - buf->buf;
1742 buf->buf = p;
1743 buf->p = p + size;
1744 buf->end = buf->buf + new_size;
1748 static void
1749 buffer_add_byte (Buffer *buf, guint8 val)
1751 buffer_make_room (buf, 1);
1752 buf->p [0] = val;
1753 buf->p++;
1756 static void
1757 buffer_add_short (Buffer *buf, guint32 val)
1759 buffer_make_room (buf, 2);
1760 buf->p [0] = (val >> 8) & 0xff;
1761 buf->p [1] = (val >> 0) & 0xff;
1762 buf->p += 2;
1765 static void
1766 buffer_add_int (Buffer *buf, guint32 val)
1768 buffer_make_room (buf, 4);
1769 buf->p [0] = (val >> 24) & 0xff;
1770 buf->p [1] = (val >> 16) & 0xff;
1771 buf->p [2] = (val >> 8) & 0xff;
1772 buf->p [3] = (val >> 0) & 0xff;
1773 buf->p += 4;
1776 static void
1777 buffer_add_long (Buffer *buf, guint64 l)
1779 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1780 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1783 static void
1784 buffer_add_id (Buffer *buf, int id)
1786 buffer_add_int (buf, (guint64)id);
1789 static void
1790 buffer_add_data (Buffer *buf, guint8 *data, int len)
1792 buffer_make_room (buf, len);
1793 memcpy (buf->p, data, len);
1794 buf->p += len;
1797 static void
1798 buffer_add_utf16 (Buffer *buf, guint8 *data, int len)
1800 #if G_BYTE_ORDER == G_LITTLE_ENDIAN
1801 buffer_make_room (buf, len);
1802 memcpy (buf->p, data, len);
1803 #else
1804 for (int i=0; i<len; i +=2) {
1805 buf->p[i] = data[i+1];
1806 buf->p[i+1] = data[i];
1808 #endif
1809 buf->p += len;
1812 static void
1813 buffer_add_string (Buffer *buf, const char *str)
1815 int len;
1817 if (str == NULL) {
1818 buffer_add_int (buf, 0);
1819 } else {
1820 len = strlen (str);
1821 buffer_add_int (buf, len);
1822 buffer_add_data (buf, (guint8*)str, len);
1826 static void
1827 buffer_add_byte_array (Buffer *buf, guint8 *bytes, guint32 arr_len)
1829 buffer_add_int (buf, arr_len);
1830 buffer_add_data (buf, bytes, arr_len);
1833 static void
1834 buffer_add_buffer (Buffer *buf, Buffer *data)
1836 buffer_add_data (buf, data->buf, buffer_len (data));
1839 static void
1840 buffer_free (Buffer *buf)
1842 g_free (buf->buf);
1845 static gboolean
1846 send_packet (int command_set, int command, Buffer *data)
1848 Buffer buf;
1849 int len, id;
1850 gboolean res;
1852 id = mono_atomic_inc_i32 (&packet_id);
1854 len = data->p - data->buf + 11;
1855 buffer_init (&buf, len);
1856 buffer_add_int (&buf, len);
1857 buffer_add_int (&buf, id);
1858 buffer_add_byte (&buf, 0); /* flags */
1859 buffer_add_byte (&buf, command_set);
1860 buffer_add_byte (&buf, command);
1861 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1863 res = transport_send (buf.buf, len);
1865 buffer_free (&buf);
1867 return res;
1870 static gboolean
1871 send_reply_packets (int npackets, ReplyPacket *packets)
1873 Buffer buf;
1874 int i, len;
1875 gboolean res;
1877 len = 0;
1878 for (i = 0; i < npackets; ++i)
1879 len += buffer_len (packets [i].data) + 11;
1880 buffer_init (&buf, len);
1881 for (i = 0; i < npackets; ++i) {
1882 buffer_add_int (&buf, buffer_len (packets [i].data) + 11);
1883 buffer_add_int (&buf, packets [i].id);
1884 buffer_add_byte (&buf, 0x80); /* flags */
1885 buffer_add_byte (&buf, (packets [i].error >> 8) & 0xff);
1886 buffer_add_byte (&buf, packets [i].error);
1887 buffer_add_buffer (&buf, packets [i].data);
1890 res = transport_send (buf.buf, len);
1892 buffer_free (&buf);
1894 return res;
1897 static gboolean
1898 send_reply_packet (int id, int error, Buffer *data)
1900 ReplyPacket packet;
1902 memset (&packet, 0, sizeof (packet));
1903 packet.id = id;
1904 packet.error = error;
1905 packet.data = data;
1907 return send_reply_packets (1, &packet);
1910 static void
1911 send_buffered_reply_packets (void)
1913 int i;
1915 send_reply_packets (nreply_packets, reply_packets);
1916 for (i = 0; i < nreply_packets; ++i)
1917 buffer_free (reply_packets [i].data);
1918 PRINT_DEBUG_MSG (1, "[dbg] Sent %d buffered reply packets [at=%lx].\n", nreply_packets, (long)mono_100ns_ticks () / 10000);
1919 nreply_packets = 0;
1922 static void
1923 buffer_reply_packet (int id, int error, Buffer *data)
1925 ReplyPacket *p;
1927 if (nreply_packets == 128)
1928 send_buffered_reply_packets ();
1930 p = &reply_packets [nreply_packets];
1931 p->id = id;
1932 p->error = error;
1933 p->data = g_new0 (Buffer, 1);
1934 buffer_init (p->data, buffer_len (data));
1935 buffer_add_buffer (p->data, data);
1936 nreply_packets ++;
1940 /* Maps objid -> ObjRef */
1941 /* Protected by the loader lock */
1942 static GHashTable *objrefs;
1943 /* Protected by the loader lock */
1944 static GHashTable *obj_to_objref;
1945 /* Protected by the dbg lock */
1946 static MonoGHashTable *suspended_objs;
1950 static void
1951 objrefs_init (void)
1953 objrefs = g_hash_table_new_full (NULL, NULL, NULL, mono_debugger_free_objref);
1954 obj_to_objref = g_hash_table_new (NULL, NULL);
1955 suspended_objs = mono_g_hash_table_new_type_internal ((GHashFunc)mono_object_hash_internal, NULL, MONO_HASH_KEY_GC, MONO_ROOT_SOURCE_DEBUGGER, NULL, "Debugger Suspended Object Table");
1958 static void
1959 objrefs_cleanup (void)
1961 g_hash_table_destroy (objrefs);
1962 objrefs = NULL;
1966 * Return an ObjRef for OBJ.
1968 static ObjRef*
1969 get_objref (MonoObject *obj)
1971 ObjRef *ref;
1972 GSList *reflist = NULL, *l;
1973 int hash = 0;
1975 if (obj == NULL)
1976 return NULL;
1978 if (suspend_count) {
1980 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1982 dbg_lock ();
1983 mono_g_hash_table_insert_internal (suspended_objs, obj, NULL);
1984 dbg_unlock ();
1987 mono_loader_lock ();
1989 /* FIXME: The tables can grow indefinitely */
1991 if (mono_gc_is_moving ()) {
1993 * Objects can move, so use a hash table mapping hash codes to lists of
1994 * ObjRef structures.
1996 hash = mono_object_hash_internal (obj);
1998 reflist = (GSList *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
1999 for (l = reflist; l; l = l->next) {
2000 ref = (ObjRef *)l->data;
2001 if (ref && mono_gchandle_get_target_internal (ref->handle) == obj) {
2002 mono_loader_unlock ();
2003 return ref;
2006 } else {
2007 /* Use a hash table with masked pointers to internalize object references */
2008 ref = (ObjRef *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
2009 /* ref might refer to a different object with the same addr which was GCd */
2010 if (ref && mono_gchandle_get_target_internal (ref->handle) == obj) {
2011 mono_loader_unlock ();
2012 return ref;
2016 ref = g_new0 (ObjRef, 1);
2017 ref->id = mono_atomic_inc_i32 (&objref_id);
2018 ref->handle = mono_gchandle_new_weakref_internal (obj, FALSE);
2020 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
2022 if (mono_gc_is_moving ()) {
2023 reflist = g_slist_append (reflist, ref);
2024 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
2025 } else {
2026 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
2029 mono_loader_unlock ();
2031 return ref;
2034 static gboolean
2035 true_pred (gpointer key, gpointer value, gpointer user_data)
2037 return TRUE;
2040 static void
2041 clear_suspended_objs (void)
2043 dbg_lock ();
2044 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
2045 dbg_unlock ();
2048 static int
2049 get_objid (MonoObject *obj)
2051 if (!obj)
2052 return 0;
2053 else
2054 return get_objref (obj)->id;
2058 * Set OBJ to the object identified by OBJID.
2059 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
2060 * collected.
2062 static ErrorCode
2063 get_object_allow_null (int objid, MonoObject **obj)
2065 ObjRef *ref;
2067 if (objid == 0) {
2068 *obj = NULL;
2069 return ERR_NONE;
2072 if (!objrefs)
2073 return ERR_INVALID_OBJECT;
2075 mono_loader_lock ();
2077 ref = (ObjRef *)g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
2079 if (ref) {
2080 *obj = mono_gchandle_get_target_internal (ref->handle);
2081 mono_loader_unlock ();
2082 if (!(*obj))
2083 return ERR_INVALID_OBJECT;
2084 return ERR_NONE;
2085 } else {
2086 mono_loader_unlock ();
2087 return ERR_INVALID_OBJECT;
2091 static ErrorCode
2092 get_object (int objid, MonoObject **obj)
2094 ErrorCode err = get_object_allow_null (objid, obj);
2096 if (err != ERR_NONE)
2097 return err;
2098 if (!(*obj))
2099 return ERR_INVALID_OBJECT;
2100 return ERR_NONE;
2103 static int
2104 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
2106 return decode_id (buf, endbuf, limit);
2109 static void
2110 buffer_add_objid (Buffer *buf, MonoObject *o)
2112 buffer_add_id (buf, get_objid (o));
2116 * IDS
2119 typedef enum {
2120 ID_ASSEMBLY = 0,
2121 ID_MODULE = 1,
2122 ID_TYPE = 2,
2123 ID_METHOD = 3,
2124 ID_FIELD = 4,
2125 ID_DOMAIN = 5,
2126 ID_PROPERTY = 6,
2127 ID_NUM
2128 } IdType;
2131 * Represents a runtime structure accessible to the debugger client
2133 typedef struct {
2134 /* Unique id used in the wire protocol */
2135 int id;
2136 /* Domain of the runtime structure, NULL if the domain was unloaded */
2137 MonoDomain *domain;
2138 union {
2139 gpointer val;
2140 MonoClass *klass;
2141 MonoMethod *method;
2142 MonoImage *image;
2143 MonoAssembly *assembly;
2144 MonoClassField *field;
2145 MonoDomain *domain;
2146 MonoProperty *property;
2147 } data;
2148 } Id;
2150 typedef struct {
2151 /* Maps runtime structure -> Id */
2152 /* Protected by the dbg lock */
2153 GHashTable *val_to_id [ID_NUM];
2154 /* Classes whose class load event has been sent */
2155 /* Protected by the loader lock */
2156 GHashTable *loaded_classes;
2157 /* Maps MonoClass->GPtrArray of file names */
2158 GHashTable *source_files;
2159 /* Maps source file basename -> GSList of classes */
2160 GHashTable *source_file_to_class;
2161 /* Same with ignore-case */
2162 GHashTable *source_file_to_class_ignorecase;
2163 } AgentDomainInfo;
2165 /* Maps id -> Id */
2166 /* Protected by the dbg lock */
2167 static GPtrArray *ids [ID_NUM];
2169 static void
2170 ids_init (void)
2172 int i;
2174 for (i = 0; i < ID_NUM; ++i)
2175 ids [i] = g_ptr_array_new ();
2178 static void
2179 ids_cleanup (void)
2181 int i, j;
2183 for (i = 0; i < ID_NUM; ++i) {
2184 if (ids [i]) {
2185 for (j = 0; j < ids [i]->len; ++j)
2186 g_free (g_ptr_array_index (ids [i], j));
2187 g_ptr_array_free (ids [i], TRUE);
2189 ids [i] = NULL;
2193 static void
2194 debugger_agent_free_domain_info (MonoDomain *domain)
2196 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2197 int i, j;
2198 GHashTableIter iter;
2199 GPtrArray *file_names;
2200 char *basename;
2201 GSList *l;
2203 if (info) {
2204 for (i = 0; i < ID_NUM; ++i)
2205 g_hash_table_destroy (info->val_to_id [i]);
2206 g_hash_table_destroy (info->loaded_classes);
2208 g_hash_table_iter_init (&iter, info->source_files);
2209 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2210 for (i = 0; i < file_names->len; ++i)
2211 g_free (g_ptr_array_index (file_names, i));
2212 g_ptr_array_free (file_names, TRUE);
2215 g_hash_table_iter_init (&iter, info->source_file_to_class);
2216 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2217 g_free (basename);
2218 g_slist_free (l);
2221 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2222 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2223 g_free (basename);
2224 g_slist_free (l);
2227 g_free (info);
2230 domain_jit_info (domain)->agent_info = NULL;
2232 /* Clear ids referencing structures in the domain */
2233 dbg_lock ();
2234 for (i = 0; i < ID_NUM; ++i) {
2235 if (ids [i]) {
2236 for (j = 0; j < ids [i]->len; ++j) {
2237 Id *id = (Id *)g_ptr_array_index (ids [i], j);
2238 if (id->domain == domain)
2239 id->domain = NULL;
2243 dbg_unlock ();
2245 mono_de_domain_remove (domain);
2248 static AgentDomainInfo*
2249 get_agent_domain_info (MonoDomain *domain)
2251 AgentDomainInfo *info = NULL;
2252 MonoJitDomainInfo *jit_info = domain_jit_info (domain);
2254 info = (AgentDomainInfo *)jit_info->agent_info;
2256 if (info) {
2257 mono_memory_read_barrier ();
2258 return info;
2261 info = g_new0 (AgentDomainInfo, 1);
2262 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2263 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2264 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2265 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2267 mono_memory_write_barrier ();
2269 gpointer other_info = mono_atomic_cas_ptr (&jit_info->agent_info, info, NULL);
2271 if (other_info != NULL) {
2272 g_hash_table_destroy (info->loaded_classes);
2273 g_hash_table_destroy (info->source_files);
2274 g_hash_table_destroy (info->source_file_to_class);
2275 g_hash_table_destroy (info->source_file_to_class_ignorecase);
2276 g_free (info);
2279 return (AgentDomainInfo *)jit_info->agent_info;
2282 static int
2283 get_id (MonoDomain *domain, IdType type, gpointer val)
2285 Id *id;
2286 AgentDomainInfo *info;
2288 if (val == NULL)
2289 return 0;
2291 info = get_agent_domain_info (domain);
2293 dbg_lock ();
2295 if (info->val_to_id [type] == NULL)
2296 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2298 id = (Id *)g_hash_table_lookup (info->val_to_id [type], val);
2299 if (id) {
2300 dbg_unlock ();
2301 return id->id;
2304 id = g_new0 (Id, 1);
2305 /* Reserve id 0 */
2306 id->id = ids [type]->len + 1;
2307 id->domain = domain;
2308 id->data.val = val;
2310 g_hash_table_insert (info->val_to_id [type], val, id);
2311 g_ptr_array_add (ids [type], id);
2313 dbg_unlock ();
2315 return id->id;
2318 static gpointer
2319 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, ErrorCode *err)
2321 Id *res;
2323 int id = decode_id (buf, endbuf, limit);
2325 *err = ERR_NONE;
2326 if (domain)
2327 *domain = NULL;
2329 if (id == 0)
2330 return NULL;
2332 // FIXME: error handling
2333 dbg_lock ();
2334 g_assert (id > 0 && id <= ids [type]->len);
2336 res = (Id *)g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2337 dbg_unlock ();
2339 if (res->domain == NULL || res->domain->state == MONO_APPDOMAIN_UNLOADED) {
2340 PRINT_DEBUG_MSG (1, "ERR_UNLOADED, id=%d, type=%d.\n", id, type);
2341 *err = ERR_UNLOADED;
2342 return NULL;
2345 if (domain)
2346 *domain = res->domain;
2348 return res->data.val;
2351 static int
2352 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2354 int id = get_id (domain, type, val);
2356 buffer_add_id (buf, id);
2357 return id;
2360 static MonoClass*
2361 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2363 MonoClass *klass;
2365 klass = (MonoClass *)decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2366 if (G_UNLIKELY (log_level >= 2) && klass) {
2367 char *s;
2369 s = mono_type_full_name (m_class_get_byval_arg (klass));
2370 PRINT_DEBUG_MSG (2, "[dbg] recv class [%s]\n", s);
2371 g_free (s);
2373 return klass;
2376 static MonoAssembly*
2377 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2379 return (MonoAssembly *)decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2382 static MonoImage*
2383 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2385 return (MonoImage *)decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2388 static MonoMethod*
2389 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2391 MonoMethod *m;
2393 m = (MonoMethod *)decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2394 if (G_UNLIKELY (log_level >= 2) && m) {
2395 char *s;
2397 s = mono_method_full_name (m, TRUE);
2398 PRINT_DEBUG_MSG (2, "[dbg] recv method [%s]\n", s);
2399 g_free (s);
2401 return m;
2404 static MonoClassField*
2405 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2407 return (MonoClassField *)decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2410 static MonoDomain*
2411 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2413 return (MonoDomain *)decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2416 static MonoProperty*
2417 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2419 return (MonoProperty *)decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2422 static void
2423 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2425 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2426 if (G_UNLIKELY (log_level >= 2) && klass) {
2427 char *s;
2429 s = mono_type_full_name (m_class_get_byval_arg (klass));
2430 if (is_debugger_thread ())
2431 PRINT_DEBUG_MSG (2, "[dbg] send class [%s]\n", s);
2432 else
2433 PRINT_DEBUG_MSG (2, "[%p] send class [%s]\n", (gpointer) (gsize) mono_native_thread_id_get (), s);
2434 g_free (s);
2438 static void
2439 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2441 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2442 if (G_UNLIKELY (log_level >= 2) && method) {
2443 char *s;
2445 s = mono_method_full_name (method, 1);
2446 if (is_debugger_thread ())
2447 PRINT_DEBUG_MSG (2, "[dbg] send method [%s]\n", s);
2448 else
2449 PRINT_DEBUG_MSG (2, "[%p] send method [%s]\n", (gpointer) (gsize) mono_native_thread_id_get (), s);
2450 g_free (s);
2454 static void
2455 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2457 int id;
2459 id = buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2460 if (G_UNLIKELY (log_level >= 2) && assembly)
2461 PRINT_DEBUG_MSG (2, "[dbg] send assembly [%s][%s][%d]\n", assembly->aname.name, domain->friendly_name, id);
2464 static void
2465 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2467 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2470 static void
2471 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2473 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2476 static void
2477 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2479 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2482 static void
2483 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2485 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2488 static void invoke_method (void);
2491 * SUSPEND/RESUME
2494 static MonoJitInfo*
2495 get_top_method_ji (gpointer ip, MonoDomain **domain, gpointer *out_ip)
2497 MonoJitInfo *ji;
2499 if (out_ip)
2500 *out_ip = ip;
2502 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, domain);
2503 if (!ji) {
2504 /* Could be an interpreter method */
2506 MonoLMF *lmf = mono_get_lmf ();
2507 MonoInterpFrameHandle *frame;
2509 g_assert (((gsize)lmf->previous_lmf) & 2);
2510 MonoLMFExt *ext = (MonoLMFExt*)lmf;
2512 g_assert (ext->kind == MONO_LMFEXT_INTERP_EXIT || ext->kind == MONO_LMFEXT_INTERP_EXIT_WITH_CTX);
2513 frame = (MonoInterpFrameHandle*)ext->interp_exit_data;
2514 ji = mini_get_interp_callbacks ()->frame_get_jit_info (frame);
2515 if (domain)
2516 *domain = mono_domain_get ();
2517 if (out_ip)
2518 *out_ip = mini_get_interp_callbacks ()->frame_get_ip (frame);
2520 return ji;
2524 * save_thread_context:
2526 * Set CTX as the current threads context which is used for computing stack traces.
2527 * This function is signal-safe.
2529 static void
2530 save_thread_context (MonoContext *ctx)
2532 DebuggerTlsData *tls;
2534 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2535 g_assert (tls);
2537 if (ctx)
2538 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2539 else
2540 mono_thread_state_init_from_current (&tls->context);
2543 static MonoCoopMutex suspend_mutex;
2545 /* Cond variable used to wait for suspend_count becoming 0 */
2546 static MonoCoopCond suspend_cond;
2548 /* Semaphore used to wait for a thread becoming suspended */
2549 static MonoCoopSem suspend_sem;
2551 static void
2552 suspend_init (void)
2554 mono_coop_mutex_init (&suspend_mutex);
2555 mono_coop_cond_init (&suspend_cond);
2556 mono_coop_sem_init (&suspend_sem, 0);
2559 typedef struct
2561 StackFrameInfo last_frame;
2562 gboolean last_frame_set;
2563 MonoContext ctx;
2564 gpointer lmf;
2565 MonoDomain *domain;
2566 } GetLastFrameUserData;
2568 static gboolean
2569 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2571 GetLastFrameUserData *data = (GetLastFrameUserData *)user_data;
2573 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE || info->type == FRAME_TYPE_TRAMPOLINE)
2574 return FALSE;
2576 if (!data->last_frame_set) {
2577 /* Store the last frame */
2578 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2579 data->last_frame_set = TRUE;
2580 return FALSE;
2581 } else {
2582 /* Store the context/lmf for the frame above the last frame */
2583 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2584 data->lmf = info->lmf;
2585 data->domain = info->domain;
2586 return TRUE;
2590 static void
2591 copy_unwind_state_from_frame_data (MonoThreadUnwindState *to, GetLastFrameUserData *data, gpointer jit_tls)
2593 memcpy (&to->ctx, &data->ctx, sizeof (MonoContext));
2595 to->unwind_data [MONO_UNWIND_DATA_DOMAIN] = data->domain;
2596 to->unwind_data [MONO_UNWIND_DATA_LMF] = data->lmf;
2597 to->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = jit_tls;
2598 to->valid = TRUE;
2602 * thread_interrupt:
2604 * Process interruption of a thread. This should be signal safe.
2606 * This always runs in the debugger thread.
2608 static void
2609 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, MonoJitInfo *ji)
2611 gpointer ip;
2612 MonoNativeThreadId tid;
2614 g_assert (info);
2616 ip = MINI_FTNPTR_TO_ADDR (MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx));
2617 tid = mono_thread_info_get_tid (info);
2619 // FIXME: Races when the thread leaves managed code before hitting a single step
2620 // event.
2622 if (ji && !ji->is_trampoline) {
2623 /* Running managed code, will be suspended by the single step code */
2624 PRINT_DEBUG_MSG (1, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip);
2625 } else {
2627 * Running native code, will be suspended when it returns to/enters
2628 * managed code. Treat it as already suspended.
2629 * This might interrupt the code in mono_de_process_single_step (), we use the
2630 * tls->suspending flag to avoid races when that happens.
2632 if (!tls->suspended && !tls->suspending) {
2633 GetLastFrameUserData data;
2635 // FIXME: printf is not signal safe, but this is only used during
2636 // debugger debugging
2637 if (ip)
2638 PRINT_DEBUG_MSG (1, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip);
2639 //save_thread_context (&ctx);
2641 if (!tls->thread)
2642 /* Already terminated */
2643 return;
2646 * We are in a difficult position: we want to be able to provide stack
2647 * traces for this thread, but we can't use the current ctx+lmf, since
2648 * the thread is still running, so it might return to managed code,
2649 * making these invalid.
2650 * So we start a stack walk and save the first frame, along with the
2651 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2652 * suspended when it returns to managed code, so the parent's ctx should
2653 * remain valid.
2655 MonoThreadUnwindState *state = mono_thread_info_get_suspend_state (info);
2657 data.last_frame_set = FALSE;
2658 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, state, MONO_UNWIND_SIGNAL_SAFE, &data);
2659 if (data.last_frame_set) {
2660 gpointer jit_tls = tls->thread->thread_info->jit_data;
2662 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2664 if (data.last_frame.type == FRAME_TYPE_INTERP_TO_MANAGED || data.last_frame.type == FRAME_TYPE_INTERP_TO_MANAGED_WITH_CTX) {
2666 * Store the current lmf instead of the parent one, since that
2667 * contains the interp exit data.
2669 data.lmf = state->unwind_data [MONO_UNWIND_DATA_LMF];
2672 copy_unwind_state_from_frame_data (&tls->async_state, &data, jit_tls);
2673 /* Don't set tls->context, it could race with the thread processing a breakpoint etc. */
2674 } else {
2675 tls->async_state.valid = FALSE;
2678 mono_memory_barrier ();
2680 tls->suspended = TRUE;
2681 mono_coop_sem_post (&suspend_sem);
2687 * reset_native_thread_suspend_state:
2689 * Reset the suspended flag and state on native threads
2691 static void
2692 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2694 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2696 if (!tls->really_suspended && tls->suspended) {
2697 tls->suspended = FALSE;
2699 * The thread might still be running if it was executing native code, so the state won't be invalided by
2700 * suspend_current ().
2702 tls->context.valid = FALSE;
2703 tls->async_state.valid = FALSE;
2704 invalidate_frames (tls);
2706 tls->resume_count_internal++;
2710 typedef struct {
2711 DebuggerTlsData *tls;
2712 gboolean valid_info;
2713 } InterruptData;
2715 static SuspendThreadResult
2716 debugger_interrupt_critical (MonoThreadInfo *info, gpointer user_data)
2718 InterruptData *data = (InterruptData *)user_data;
2719 MonoJitInfo *ji;
2721 data->valid_info = TRUE;
2722 MonoDomain *domain = (MonoDomain *) mono_thread_info_get_suspend_state (info)->unwind_data [MONO_UNWIND_DATA_DOMAIN];
2723 if (!domain) {
2724 /* not attached */
2725 ji = NULL;
2726 } else {
2727 ji = mono_jit_info_table_find_internal (domain, MINI_FTNPTR_TO_ADDR (MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx)), TRUE, TRUE);
2730 /* This is signal safe */
2731 thread_interrupt (data->tls, info, ji);
2732 return MonoResumeThread;
2736 * notify_thread:
2738 * Notify a thread that it needs to suspend.
2740 static void
2741 notify_thread (gpointer key, gpointer value, gpointer user_data)
2743 MonoInternalThread *thread = (MonoInternalThread *)key;
2744 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2745 MonoNativeThreadId tid = MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid);
2747 if (mono_thread_internal_is_current (thread) || tls->terminated)
2748 return;
2750 PRINT_DEBUG_MSG (1, "[%p] Interrupting %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)(gsize)tid);
2752 /* This is _not_ equivalent to mono_thread_internal_abort () */
2753 InterruptData interrupt_data = { 0 };
2754 interrupt_data.tls = tls;
2756 mono_thread_info_safe_suspend_and_run ((MonoNativeThreadId)(gsize)thread->tid, FALSE, debugger_interrupt_critical, &interrupt_data);
2757 if (!interrupt_data.valid_info) {
2758 PRINT_DEBUG_MSG (1, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2760 * Attached thread which died without detaching.
2762 tls->terminated = TRUE;
2766 static void
2767 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2769 guint8 *ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
2770 MonoJitInfo *ji;
2771 MonoMethod *method;
2773 if (mono_loader_lock_is_owned_by_self ()) {
2775 * Shortcut for the check in suspend_current (). This speeds up processing
2776 * when executing long running code inside the loader lock, i.e. assembly load
2777 * hooks.
2779 return;
2782 if (is_debugger_thread ())
2783 return;
2785 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2786 if (suspend_count - tls->resume_count > 0)
2787 tls->suspending = TRUE;
2789 PRINT_DEBUG_MSG (1, "[%p] Received single step event for suspending.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2791 if (suspend_count - tls->resume_count == 0) {
2793 * We are executing a single threaded invoke but the single step for
2794 * suspending is still active.
2795 * FIXME: This slows down single threaded invokes.
2797 PRINT_DEBUG_MSG (1, "[%p] Ignored during single threaded invoke.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2798 return;
2801 ji = get_top_method_ji (ip, NULL, NULL);
2802 g_assert (ji);
2803 /* Can't suspend in these methods */
2804 method = jinfo_get_method (ji);
2805 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2806 return;
2808 save_thread_context (ctx);
2810 suspend_current ();
2814 /* Conditionally call process_suspend depending oh the current state */
2815 static gboolean
2816 try_process_suspend (void *the_tls, MonoContext *ctx, gboolean from_breakpoint)
2818 MONO_REQ_GC_UNSAFE_MODE;
2820 DebuggerTlsData *tls = (DebuggerTlsData*)the_tls;
2821 /* if there is a suspend pending that is not executed yes */
2822 if (suspend_count > 0) {
2823 /* Fastpath during invokes, see in process_suspend () */
2824 /* if there is a suspend pending but this thread is already resumed, we shouldn't suspend it again and the breakpoint/ss can run */
2825 if (suspend_count - tls->resume_count == 0)
2826 return FALSE;
2827 /* if there is in a invoke the breakpoint/step should be executed even with the suspend pending */
2828 if (tls->invoke)
2829 return FALSE;
2830 /* with the multithreaded single step check if there is a suspend_count pending in the current thread and not in the vm */
2831 if (from_breakpoint && tls->suspend_count <= tls->resume_count_internal)
2832 return FALSE;
2833 process_suspend (tls, ctx);
2834 return TRUE;
2835 } /* if there isn't any suspend pending, the breakpoint/ss will be executed and will suspend then vm when the event is sent */
2836 return FALSE;
2840 * suspend_vm:
2842 * Increase the suspend count of the VM. While the suspend count is greater
2843 * than 0, runtime threads are suspended at certain points during execution.
2845 static void
2846 suspend_vm (void)
2848 gboolean tp_suspend = FALSE;
2849 mono_loader_lock ();
2851 mono_coop_mutex_lock (&suspend_mutex);
2853 suspend_count ++;
2855 PRINT_DEBUG_MSG (1, "[%p] Suspending vm...\n", (gpointer) (gsize) mono_native_thread_id_get ());
2857 if (suspend_count == 1) {
2858 // FIXME: Is it safe to call this inside the lock ?
2859 mono_de_start_single_stepping ();
2860 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2863 mono_coop_mutex_unlock (&suspend_mutex);
2865 if (suspend_count == 1)
2867 * Suspend creation of new threadpool threads, since they cannot run
2869 tp_suspend = TRUE;
2870 mono_loader_unlock ();
2872 #ifndef ENABLE_NETCORE
2873 if (tp_suspend)
2874 mono_threadpool_suspend ();
2875 #endif
2879 * resume_vm:
2881 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2882 * are resumed.
2884 static void
2885 resume_vm (void)
2887 g_assert (is_debugger_thread ());
2888 gboolean tp_resume = FALSE;
2890 mono_loader_lock ();
2892 mono_coop_mutex_lock (&suspend_mutex);
2894 g_assert (suspend_count > 0);
2895 suspend_count --;
2897 PRINT_DEBUG_MSG (1, "[%p] Resuming vm, suspend count=%d...\n", (gpointer) (gsize) mono_native_thread_id_get (), suspend_count);
2899 if (suspend_count == 0) {
2900 // FIXME: Is it safe to call this inside the lock ?
2901 mono_de_stop_single_stepping ();
2902 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2905 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2906 mono_coop_cond_broadcast (&suspend_cond);
2908 mono_coop_mutex_unlock (&suspend_mutex);
2909 //g_assert (err == 0);
2911 if (suspend_count == 0)
2912 tp_resume = TRUE;
2913 mono_loader_unlock ();
2915 #ifndef ENABLE_NETCORE
2916 if (tp_resume)
2917 mono_threadpool_resume ();
2918 #endif
2922 * resume_thread:
2924 * Resume just one thread.
2926 static void
2927 resume_thread (MonoInternalThread *thread)
2929 DebuggerTlsData *tls;
2931 g_assert (is_debugger_thread ());
2933 mono_loader_lock ();
2935 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
2936 g_assert (tls);
2938 mono_coop_mutex_lock (&suspend_mutex);
2940 g_assert (suspend_count > 0);
2942 PRINT_DEBUG_MSG (1, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid);
2944 tls->resume_count += suspend_count;
2945 tls->resume_count_internal += tls->suspend_count;
2946 tls->suspend_count = 0;
2949 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2950 * but only the one whose resume_count field is > 0 will be resumed.
2952 mono_coop_cond_broadcast (&suspend_cond);
2954 mono_coop_mutex_unlock (&suspend_mutex);
2955 //g_assert (err == 0);
2957 mono_loader_unlock ();
2960 static void
2961 free_frames (StackFrame **frames, int nframes)
2963 int i;
2965 for (i = 0; i < nframes; ++i) {
2966 if (frames [i]->jit)
2967 mono_debug_free_method_jit_info (frames [i]->jit);
2968 g_free (frames [i]);
2970 g_free (frames);
2973 static void
2974 invalidate_frames (DebuggerTlsData *tls)
2976 mono_loader_lock ();
2978 if (!tls)
2979 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2980 g_assert (tls);
2982 free_frames (tls->frames, tls->frame_count);
2983 tls->frame_count = 0;
2984 tls->frames = NULL;
2986 free_frames (tls->restore_frames, tls->restore_frame_count);
2987 tls->restore_frame_count = 0;
2988 tls->restore_frames = NULL;
2990 mono_loader_unlock ();
2994 * suspend_current:
2996 * Suspend the current thread until the runtime is resumed. If the thread has a
2997 * pending invoke, then the invoke is executed before this function returns.
2999 static void
3000 suspend_current (void)
3002 DebuggerTlsData *tls;
3004 g_assert (!is_debugger_thread ());
3006 if (mono_loader_lock_is_owned_by_self ()) {
3008 * If we own the loader mutex, can't suspend until we release it, since the
3009 * whole runtime can deadlock otherwise.
3011 return;
3014 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3015 g_assert (tls);
3017 gboolean do_resume = FALSE;
3018 while (!do_resume) {
3019 mono_coop_mutex_lock (&suspend_mutex);
3021 tls->suspending = FALSE;
3022 tls->really_suspended = TRUE;
3024 if (!tls->suspended) {
3025 tls->suspended = TRUE;
3026 mono_coop_sem_post (&suspend_sem);
3029 mono_debugger_log_suspend (tls);
3030 PRINT_DEBUG_MSG (1, "[%p] Suspended.\n", (gpointer) (gsize) mono_native_thread_id_get ());
3032 while (suspend_count - tls->resume_count > 0) {
3033 mono_coop_cond_wait (&suspend_cond, &suspend_mutex);
3036 tls->suspended = FALSE;
3037 tls->really_suspended = FALSE;
3039 mono_coop_mutex_unlock (&suspend_mutex);
3041 mono_debugger_log_resume (tls);
3042 PRINT_DEBUG_MSG (1, "[%p] Resumed.\n", (gpointer) (gsize) mono_native_thread_id_get ());
3044 if (tls->pending_invoke) {
3045 /* Save the original context */
3046 tls->pending_invoke->has_ctx = TRUE;
3047 tls->pending_invoke->ctx = tls->context.ctx;
3049 invoke_method ();
3051 /* Have to suspend again */
3052 } else {
3053 do_resume = TRUE;
3057 /* The frame info becomes invalid after a resume */
3058 tls->context.valid = FALSE;
3059 tls->async_state.valid = FALSE;
3060 invalidate_frames (tls);
3061 mono_stopwatch_start (&tls->step_time);
3064 static void
3065 count_thread (gpointer key, gpointer value, gpointer user_data)
3067 DebuggerTlsData *tls = (DebuggerTlsData *)value;
3069 if (!tls->suspended && !tls->terminated && !mono_thread_internal_is_current (tls->thread))
3070 *(int*)user_data = *(int*)user_data + 1;
3073 static int
3074 count_threads_to_wait_for (void)
3076 int count = 0;
3078 mono_loader_lock ();
3079 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
3080 mono_loader_unlock ();
3082 return count;
3086 * wait_for_suspend:
3088 * Wait until the runtime is completely suspended.
3090 static void
3091 wait_for_suspend (void)
3093 int nthreads, nwait, err;
3094 gboolean waited = FALSE;
3096 // FIXME: Threads starting/stopping ?
3097 mono_loader_lock ();
3098 nthreads = mono_g_hash_table_size (thread_to_tls);
3099 mono_loader_unlock ();
3101 while (TRUE) {
3102 nwait = count_threads_to_wait_for ();
3103 if (nwait) {
3104 PRINT_DEBUG_MSG (1, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads);
3105 err = mono_coop_sem_wait (&suspend_sem, MONO_SEM_FLAGS_NONE);
3106 g_assert (err == 0);
3107 waited = TRUE;
3108 } else {
3109 break;
3113 if (waited)
3114 PRINT_DEBUG_MSG (1, "%d threads suspended.\n", nthreads);
3118 * is_suspended:
3120 * Return whenever the runtime is suspended.
3122 static gboolean
3123 is_suspended (void)
3125 return count_threads_to_wait_for () == 0;
3128 static void
3129 no_seq_points_found (MonoMethod *method, int offset)
3132 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3134 PRINT_MSG ("Unable to find seq points for method '%s', offset 0x%x.\n", mono_method_full_name (method, TRUE), offset);
3137 static int
3138 calc_il_offset (MonoDomain *domain, MonoMethod *method, int native_offset, gboolean is_top_frame)
3140 int ret = -1;
3141 if (is_top_frame) {
3142 SeqPoint sp;
3143 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3144 if (mono_find_prev_seq_point_for_native_offset (domain, method, native_offset, NULL, &sp))
3145 ret = sp.il_offset;
3147 if (ret == -1)
3148 ret = mono_debug_il_offset_from_address (method, domain, native_offset);
3149 return ret;
3152 typedef struct {
3153 DebuggerTlsData *tls;
3154 GSList *frames;
3155 gboolean set_debugger_flag;
3156 } ComputeFramesUserData;
3158 static gboolean
3159 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3161 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3162 StackFrame *frame;
3163 MonoMethod *method, *actual_method, *api_method;
3164 int flags = 0;
3166 mono_loader_lock ();
3167 if (info->type != FRAME_TYPE_MANAGED && info->type != FRAME_TYPE_INTERP && info->type != FRAME_TYPE_MANAGED_TO_NATIVE) {
3168 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3169 /* Mark the last frame as an invoke frame */
3170 if (ud->frames)
3171 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3172 else
3173 ud->set_debugger_flag = TRUE;
3175 mono_loader_unlock ();
3176 return FALSE;
3179 if (info->ji)
3180 method = jinfo_get_method (info->ji);
3181 else
3182 method = info->method;
3183 actual_method = info->actual_method;
3184 api_method = method;
3186 if (!method) {
3187 mono_loader_unlock ();
3188 return FALSE;
3191 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE)) {
3192 mono_loader_unlock ();
3193 return FALSE;
3196 if (info->il_offset == -1) {
3197 info->il_offset = calc_il_offset (info->domain, method, info->native_offset, ud->frames == NULL);
3200 PRINT_DEBUG_MSG (1, "\tFrame: %s:[il=0x%x, native=0x%x] %d\n", mono_method_full_name (method, TRUE), info->il_offset, info->native_offset, info->managed);
3202 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3203 if (!CHECK_PROTOCOL_VERSION (2, 17)) {
3204 /* Older clients can't handle this flag */
3205 mono_loader_unlock ();
3206 return FALSE;
3208 api_method = mono_marshal_method_from_wrapper (method);
3209 if (!api_method) {
3210 mono_loader_unlock ();
3211 return FALSE;
3213 actual_method = api_method;
3214 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3217 if (ud->set_debugger_flag) {
3218 g_assert (g_slist_length (ud->frames) == 0);
3219 flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3220 ud->set_debugger_flag = FALSE;
3223 frame = g_new0 (StackFrame, 1);
3224 frame->de.ji = info->ji;
3225 frame->de.domain = info->domain;
3226 frame->de.method = method;
3227 frame->de.native_offset = info->native_offset;
3229 frame->actual_method = actual_method;
3230 frame->api_method = api_method;
3231 frame->il_offset = info->il_offset;
3232 frame->flags = flags;
3233 frame->interp_frame = info->interp_frame;
3234 frame->frame_addr = info->frame_addr;
3235 if (info->reg_locations)
3236 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (host_mgreg_t*));
3237 if (ctx) {
3238 frame->ctx = *ctx;
3239 frame->has_ctx = TRUE;
3242 ud->frames = g_slist_append (ud->frames, frame);
3244 mono_loader_unlock ();
3245 return FALSE;
3248 static gint32 isFixedSizeArray (MonoClassField *f)
3250 ERROR_DECL (error);
3251 if (!CHECK_PROTOCOL_VERSION (2, 53) || f->type->type != MONO_TYPE_VALUETYPE) {
3252 return 1;
3254 MonoCustomAttrInfo *cinfo;
3255 MonoCustomAttrEntry *attr;
3256 int aindex;
3257 gint32 ret = 1;
3258 cinfo = mono_custom_attrs_from_field_checked (f->parent, f, error);
3259 goto_if_nok (error, leave);
3260 attr = NULL;
3261 if (cinfo) {
3262 for (aindex = 0; aindex < cinfo->num_attrs; ++aindex) {
3263 MonoClass *ctor_class = cinfo->attrs [aindex].ctor->klass;
3264 MonoClass *fixed_size_class = mono_class_try_get_fixed_buffer_class ();
3265 if (fixed_size_class != NULL && mono_class_has_parent (ctor_class, fixed_size_class)) {
3266 attr = &cinfo->attrs [aindex];
3267 gpointer *typed_args, *named_args;
3268 CattrNamedArg *arginfo;
3269 int num_named_args;
3271 mono_reflection_create_custom_attr_data_args_noalloc (mono_defaults.corlib, attr->ctor, attr->data, attr->data_size,
3272 &typed_args, &named_args, &num_named_args, &arginfo, error);
3273 if (!is_ok (error)) {
3274 ret = 0;
3275 goto leave;
3277 ret = *(gint32*)typed_args [1];
3278 g_free (typed_args [1]);
3279 g_free (typed_args);
3280 g_free (named_args);
3281 g_free (arginfo);
3282 return ret;
3286 leave:
3287 mono_error_cleanup (error);
3288 return ret;
3291 static gboolean
3292 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3294 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3297 * 'tls->filter_ctx' is the location of the throw site.
3299 * mono_walk_stack() will never actually hit the throw site, but unwind
3300 * directly from the filter to the call site; we abort stack unwinding here
3301 * once this happens and resume from the throw site.
3303 if (info->frame_addr >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3304 return TRUE;
3306 return process_frame (info, ctx, user_data);
3310 * Return a malloc-ed list of StackFrame structures.
3312 static StackFrame**
3313 compute_frame_info_from (MonoInternalThread *thread, DebuggerTlsData *tls, MonoThreadUnwindState *state, int *out_nframes)
3315 ComputeFramesUserData user_data;
3316 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3317 StackFrame **res;
3318 int i, nframes;
3319 GSList *l;
3321 user_data.tls = tls;
3322 user_data.frames = NULL;
3324 mono_walk_stack_with_state (process_frame, state, opts, &user_data);
3326 nframes = g_slist_length (user_data.frames);
3327 res = g_new0 (StackFrame*, nframes);
3328 l = user_data.frames;
3329 for (i = 0; i < nframes; ++i) {
3330 res [i] = (StackFrame *)l->data;
3331 l = l->next;
3333 *out_nframes = nframes;
3335 return res;
3338 static void
3339 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls, gboolean force_update)
3341 ComputeFramesUserData user_data;
3342 GSList *tmp;
3343 int i, findex, new_frame_count;
3344 StackFrame **new_frames, *f;
3345 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3347 // FIXME: Locking on tls
3348 if (tls->frames && tls->frames_up_to_date && !force_update)
3349 return;
3351 PRINT_DEBUG_MSG (1, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid);
3353 if (CHECK_PROTOCOL_VERSION (2, 52)) {
3354 if (tls->restore_state.valid && MONO_CONTEXT_GET_IP (&tls->context.ctx) != MONO_CONTEXT_GET_IP (&tls->restore_state.ctx)) {
3355 new_frames = compute_frame_info_from (thread, tls, &tls->restore_state, &new_frame_count);
3356 invalidate_frames (tls);
3358 tls->frames = new_frames;
3359 tls->frame_count = new_frame_count;
3360 tls->frames_up_to_date = TRUE;
3361 return;
3365 user_data.tls = tls;
3366 user_data.frames = NULL;
3367 if (tls->terminated) {
3368 tls->frame_count = 0;
3369 return;
3370 } if (!tls->really_suspended && tls->async_state.valid) {
3371 /* Have to use the state saved by the signal handler */
3372 process_frame (&tls->async_last_frame, NULL, &user_data);
3373 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3374 } else if (tls->filter_state.valid) {
3376 * We are inside an exception filter.
3378 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3380 if (tls->context.valid) {
3381 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3382 PRINT_DEBUG_MSG (1, "\tFrame: <call filter>\n");
3385 * After that, we resume unwinding from the location where the exception has been thrown.
3387 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3388 } else if (tls->context.valid) {
3389 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3390 } else {
3391 // FIXME:
3392 tls->frame_count = 0;
3393 return;
3396 new_frame_count = g_slist_length (user_data.frames);
3397 new_frames = g_new0 (StackFrame*, new_frame_count);
3398 findex = 0;
3399 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3400 f = (StackFrame *)tmp->data;
3403 * Reuse the id for already existing stack frames, so invokes don't invalidate
3404 * the still valid stack frames.
3406 for (i = 0; i < tls->frame_count; ++i) {
3407 if (tls->frames [i]->frame_addr == f->frame_addr) {
3408 f->id = tls->frames [i]->id;
3409 break;
3413 if (i >= tls->frame_count)
3414 f->id = mono_atomic_inc_i32 (&frame_id);
3416 new_frames [findex ++] = f;
3419 g_slist_free (user_data.frames);
3421 invalidate_frames (tls);
3423 tls->frames = new_frames;
3424 tls->frame_count = new_frame_count;
3425 tls->frames_up_to_date = TRUE;
3427 if (CHECK_PROTOCOL_VERSION (2, 52)) {
3428 MonoJitTlsData *jit_data = thread->thread_info->jit_data;
3429 gboolean has_interp_resume_state = FALSE;
3430 MonoInterpFrameHandle interp_resume_frame = NULL;
3431 gpointer interp_resume_ip = 0;
3432 mini_get_interp_callbacks ()->get_resume_state (jit_data, &has_interp_resume_state, &interp_resume_frame, &interp_resume_ip);
3433 if (has_interp_resume_state && tls->frame_count > 0) {
3434 StackFrame *top_frame = tls->frames [0];
3435 if (interp_resume_frame == top_frame->interp_frame) {
3436 int native_offset = (int) ((uintptr_t) interp_resume_ip - (uintptr_t) top_frame->de.ji->code_start);
3437 top_frame->il_offset = calc_il_offset (top_frame->de.domain, top_frame->de.method, native_offset, TRUE);
3444 * GHFunc to emit an appdomain creation event
3445 * @param key Don't care
3446 * @param value A loaded appdomain
3447 * @param user_data Don't care
3449 static void
3450 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3452 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3453 g_hash_table_foreach (get_agent_domain_info ((MonoDomain *)value)->loaded_classes, emit_type_load, NULL);
3457 * GHFunc to emit a thread start event
3458 * @param key A thread id
3459 * @param value A thread object
3460 * @param user_data Don't care
3462 static void
3463 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3465 g_assert (!mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (GPOINTER_TO_UINT (key)), debugger_thread_id));
3466 process_profiler_event (EVENT_KIND_THREAD_START, value);
3470 * GFunc to emit an assembly load event
3471 * @param value A loaded assembly
3472 * @param user_data Don't care
3474 static void
3475 emit_assembly_load (gpointer value, gpointer user_data)
3477 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3481 * GFunc to emit a type load event
3482 * @param value A loaded type
3483 * @param user_data Don't care
3485 static void
3486 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3488 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3492 static void gc_finalizing (MonoProfiler *prof)
3494 DebuggerTlsData *tls;
3496 if (is_debugger_thread ())
3497 return;
3499 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3500 g_assert (tls);
3501 tls->gc_finalizing = TRUE;
3504 static void gc_finalized (MonoProfiler *prof)
3506 DebuggerTlsData *tls;
3508 if (is_debugger_thread ())
3509 return;
3511 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3512 g_assert (tls);
3513 tls->gc_finalizing = FALSE;
3517 static char*
3518 strdup_tolower (char *s)
3520 char *s2, *p;
3522 s2 = g_strdup (s);
3523 for (p = s2; *p; ++p)
3524 *p = tolower (*p);
3525 return s2;
3529 * Same as g_path_get_basename () but handles windows paths as well,
3530 * which can occur in .mdb files created by pdb2mdb.
3532 static char*
3533 dbg_path_get_basename (const char *filename)
3535 char *r;
3537 if (!filename || strchr (filename, '/') || !strchr (filename, '\\'))
3538 return g_path_get_basename (filename);
3540 /* From gpath.c */
3542 /* No separator -> filename */
3543 r = (char*)strrchr (filename, '\\');
3544 if (r == NULL)
3545 return g_strdup (filename);
3547 /* Trailing slash, remove component */
3548 if (r [1] == 0){
3549 char *copy = g_strdup (filename);
3550 copy [r-filename] = 0;
3551 r = strrchr (copy, '\\');
3553 if (r == NULL){
3554 g_free (copy);
3555 return g_strdup ("/");
3557 r = g_strdup (&r[1]);
3558 g_free (copy);
3559 return r;
3562 return g_strdup (&r[1]);
3565 static GENERATE_TRY_GET_CLASS_WITH_CACHE(hidden_klass, "System.Diagnostics", "DebuggerHiddenAttribute")
3566 static GENERATE_TRY_GET_CLASS_WITH_CACHE(step_through_klass, "System.Diagnostics", "DebuggerStepThroughAttribute")
3567 static GENERATE_TRY_GET_CLASS_WITH_CACHE(non_user_klass, "System.Diagnostics", "DebuggerNonUserCodeAttribute")
3569 static void
3570 init_jit_info_dbg_attrs (MonoJitInfo *ji)
3572 ERROR_DECL (error);
3573 MonoCustomAttrInfo *ainfo;
3575 if (ji->dbg_attrs_inited)
3576 return;
3578 // NOTE: The following Debugger attributes may not exist if they are trimmed away by the ILLinker
3579 MonoClass *hidden_klass = mono_class_try_get_hidden_klass_class ();
3580 MonoClass *step_through_klass = mono_class_try_get_step_through_klass_class ();
3581 MonoClass *non_user_klass = mono_class_try_get_non_user_klass_class ();
3583 ainfo = mono_custom_attrs_from_method_checked (jinfo_get_method (ji), error);
3584 mono_error_cleanup (error); /* FIXME don't swallow the error? */
3585 if (ainfo) {
3586 if (hidden_klass && mono_custom_attrs_has_attr (ainfo, hidden_klass))
3587 ji->dbg_hidden = TRUE;
3588 if (step_through_klass && mono_custom_attrs_has_attr (ainfo, step_through_klass))
3589 ji->dbg_step_through = TRUE;
3590 if (non_user_klass && mono_custom_attrs_has_attr (ainfo, non_user_klass))
3591 ji->dbg_non_user_code = TRUE;
3592 mono_custom_attrs_free (ainfo);
3595 ainfo = mono_custom_attrs_from_class_checked (jinfo_get_method (ji)->klass, error);
3596 mono_error_cleanup (error); /* FIXME don't swallow the error? */
3597 if (ainfo) {
3598 if (step_through_klass && mono_custom_attrs_has_attr (ainfo, step_through_klass))
3599 ji->dbg_step_through = TRUE;
3600 if (non_user_klass && mono_custom_attrs_has_attr (ainfo, non_user_klass))
3601 ji->dbg_non_user_code = TRUE;
3602 mono_custom_attrs_free (ainfo);
3605 mono_memory_barrier ();
3606 ji->dbg_attrs_inited = TRUE;
3610 * EVENT HANDLING
3614 * create_event_list:
3616 * Return a list of event request ids matching EVENT, starting from REQS, which
3617 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3618 * policy.
3619 * We return request ids, instead of requests, to simplify threading, since
3620 * requests could be deleted anytime when the loader lock is not held.
3621 * LOCKING: Assumes the loader lock is held.
3623 static GSList*
3624 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3626 int i, j;
3627 GSList *events = NULL;
3629 *suspend_policy = SUSPEND_POLICY_NONE;
3631 if (!reqs)
3632 reqs = event_requests;
3634 if (!reqs)
3635 return NULL;
3636 gboolean has_everything_else = FALSE;
3637 gboolean is_new_filtered_exception = FALSE;
3638 gboolean filteredException = TRUE;
3639 gint filtered_suspend_policy = 0;
3640 gint filtered_req_id = 0;
3641 gint everything_else_suspend_policy = 0;
3642 gint everything_else_req_id = 0;
3643 gboolean is_already_filtered = FALSE;
3644 for (i = 0; i < reqs->len; ++i) {
3645 EventRequest *req = (EventRequest *)g_ptr_array_index (reqs, i);
3646 if (req->event_kind == event) {
3647 gboolean filtered = FALSE;
3649 /* Apply filters */
3650 for (j = 0; j < req->nmodifiers; ++j) {
3651 Modifier *mod = &req->modifiers [j];
3653 if (mod->kind == MOD_KIND_COUNT) {
3654 filtered = TRUE;
3655 if (mod->data.count > 0) {
3656 if (mod->data.count > 0) {
3657 mod->data.count --;
3658 if (mod->data.count == 0)
3659 filtered = FALSE;
3662 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3663 if (mod->data.thread != mono_thread_internal_current ())
3664 filtered = TRUE;
3665 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && !mod->not_filtered_feature && ei) {
3666 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from_internal (mod->data.exc_class, ei->exc->vtable->klass))
3667 filtered = TRUE;
3668 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3669 filtered = TRUE;
3670 if (ei->caught && !mod->caught)
3671 filtered = TRUE;
3672 if (!ei->caught && !mod->uncaught)
3673 filtered = TRUE;
3674 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && mod->not_filtered_feature && ei) {
3675 is_new_filtered_exception = TRUE;
3676 if ((mod->data.exc_class && mod->subclasses && mono_class_is_assignable_from_internal (mod->data.exc_class, ei->exc->vtable->klass)) ||
3677 (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)) {
3678 is_already_filtered = TRUE;
3679 if ((ei->caught && mod->caught) || (!ei->caught && mod->uncaught)) {
3680 filteredException = FALSE;
3681 filtered_suspend_policy = req->suspend_policy;
3682 filtered_req_id = req->id;
3685 if (!mod->data.exc_class && mod->everything_else) {
3686 if ((ei->caught && mod->caught) || (!ei->caught && mod->uncaught)) {
3687 has_everything_else = TRUE;
3688 everything_else_req_id = req->id;
3689 everything_else_suspend_policy = req->suspend_policy;
3692 if (!mod->data.exc_class && !mod->everything_else) {
3693 if ((ei->caught && mod->caught) || (!ei->caught && mod->uncaught)) {
3694 filteredException = FALSE;
3695 filtered_suspend_policy = req->suspend_policy;
3696 filtered_req_id = req->id;
3699 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3700 int k;
3701 gboolean found = FALSE;
3702 MonoAssembly **assemblies = mod->data.assemblies;
3704 if (assemblies) {
3705 for (k = 0; assemblies [k]; ++k)
3706 if (assemblies [k] == m_class_get_image (jinfo_get_method (ji)->klass)->assembly)
3707 found = TRUE;
3709 if (!found)
3710 filtered = TRUE;
3711 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3712 gpointer iter = NULL;
3713 MonoMethod *method;
3714 MonoDebugSourceInfo *sinfo;
3715 char *s;
3716 gboolean found = FALSE;
3717 int i;
3718 GPtrArray *source_file_list;
3720 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3721 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3723 if (minfo) {
3724 mono_debug_get_seq_points (minfo, NULL, &source_file_list, NULL, NULL, NULL);
3725 for (i = 0; i < source_file_list->len; ++i) {
3726 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
3728 * Do a case-insesitive match by converting the file name to
3729 * lowercase.
3731 s = strdup_tolower (sinfo->source_file);
3732 if (g_hash_table_lookup (mod->data.source_files, s))
3733 found = TRUE;
3734 else {
3735 char *s2 = dbg_path_get_basename (sinfo->source_file);
3736 char *s3 = strdup_tolower (s2);
3738 if (g_hash_table_lookup (mod->data.source_files, s3))
3739 found = TRUE;
3740 g_free (s2);
3741 g_free (s3);
3743 g_free (s);
3745 g_ptr_array_free (source_file_list, TRUE);
3748 if (!found)
3749 filtered = TRUE;
3750 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3751 char *s;
3753 s = mono_type_full_name (m_class_get_byval_arg (ei->klass));
3754 if (!g_hash_table_lookup (mod->data.type_names, s))
3755 filtered = TRUE;
3756 g_free (s);
3757 } else if (mod->kind == MOD_KIND_STEP) {
3758 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3759 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3760 !strcmp (jinfo_get_method (ji)->name, ".cctor") &&
3761 (jinfo_get_method (ji) != ((SingleStepReq*)req->info)->start_method))
3762 filtered = TRUE;
3763 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3764 init_jit_info_dbg_attrs (ji);
3765 if (ji->dbg_hidden)
3766 filtered = TRUE;
3768 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3769 init_jit_info_dbg_attrs (ji);
3770 if (ji->dbg_step_through)
3771 filtered = TRUE;
3773 if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3774 init_jit_info_dbg_attrs (ji);
3775 if (ji->dbg_non_user_code)
3776 filtered = TRUE;
3781 if (!filtered && !is_new_filtered_exception) {
3782 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3783 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3788 if (has_everything_else && !is_already_filtered) {
3789 filteredException = FALSE;
3790 filtered_suspend_policy = everything_else_suspend_policy;
3791 filtered_req_id = everything_else_req_id;
3794 if (!filteredException) {
3795 *suspend_policy = MAX (*suspend_policy, filtered_suspend_policy);
3796 events = g_slist_append (events, GINT_TO_POINTER (filtered_req_id));
3799 /* Send a VM START/DEATH event by default */
3800 if (event == EVENT_KIND_VM_START)
3801 events = g_slist_append (events, GINT_TO_POINTER (0));
3802 if (event == EVENT_KIND_VM_DEATH)
3803 events = g_slist_append (events, GINT_TO_POINTER (0));
3805 return events;
3808 static G_GNUC_UNUSED const char*
3809 event_to_string (EventKind event)
3811 switch (event) {
3812 case EVENT_KIND_VM_START: return "VM_START";
3813 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3814 case EVENT_KIND_THREAD_START: return "THREAD_START";
3815 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3816 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3817 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3818 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3819 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3820 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3821 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3822 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3823 case EVENT_KIND_STEP: return "STEP";
3824 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3825 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3826 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3827 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3828 case EVENT_KIND_USER_LOG: return "USER_LOG";
3829 case EVENT_KIND_CRASH: return "CRASH";
3830 default:
3831 g_assert_not_reached ();
3832 return "";
3837 * process_event:
3839 * Send an event to the client, suspending the vm if needed.
3840 * LOCKING: Since this can suspend the calling thread, no locks should be held
3841 * by the caller.
3842 * The EVENTS list is freed by this function.
3844 static void
3845 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3847 Buffer buf;
3848 GSList *l;
3849 MonoDomain *domain = mono_domain_get ();
3850 MonoThread *thread = NULL;
3851 MonoObject *keepalive_obj = NULL;
3852 gboolean send_success = FALSE;
3853 static int ecount;
3854 int nevents;
3856 if (!agent_inited) {
3857 PRINT_DEBUG_MSG (2, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event));
3858 return;
3861 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3862 // FIXME: We miss those events
3863 PRINT_DEBUG_MSG (2, "VM start event not sent yet: dropping %s\n", event_to_string (event));
3864 return;
3867 if (vm_death_event_sent) {
3868 PRINT_DEBUG_MSG (2, "VM death event has been sent: dropping %s\n", event_to_string (event));
3869 return;
3872 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3873 PRINT_DEBUG_MSG (2, "Mono runtime is shutting down: dropping %s\n", event_to_string (event));
3874 return;
3877 if (disconnected) {
3878 PRINT_DEBUG_MSG (2, "Debugger client is not connected: dropping %s\n", event_to_string (event));
3879 return;
3882 if (event == EVENT_KIND_KEEPALIVE)
3883 suspend_policy = SUSPEND_POLICY_NONE;
3884 else {
3885 if (events == NULL)
3886 return;
3888 if (agent_config.defer) {
3889 if (is_debugger_thread ()) {
3890 /* Don't suspend on events from the debugger thread */
3891 suspend_policy = SUSPEND_POLICY_NONE;
3893 } else {
3894 if (is_debugger_thread () && event != EVENT_KIND_VM_DEATH)
3895 // FIXME: Send these with a NULL thread, don't suspend the current thread
3896 return;
3900 if (event == EVENT_KIND_VM_START)
3901 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3903 nevents = g_slist_length (events);
3904 buffer_init (&buf, 128);
3905 buffer_add_byte (&buf, suspend_policy);
3906 buffer_add_int (&buf, nevents);
3908 for (l = events; l; l = l->next) {
3909 buffer_add_byte (&buf, event); // event kind
3910 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3912 ecount ++;
3914 if (event == EVENT_KIND_VM_DEATH) {
3915 thread = NULL;
3916 } else {
3917 if (!thread)
3918 thread = is_debugger_thread () ? mono_thread_get_main () : mono_thread_current ();
3920 if (event == EVENT_KIND_VM_START && arg != NULL)
3921 thread = (MonoThread *)arg;
3924 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3926 switch (event) {
3927 case EVENT_KIND_THREAD_START:
3928 case EVENT_KIND_THREAD_DEATH:
3929 break;
3930 case EVENT_KIND_APPDOMAIN_CREATE:
3931 case EVENT_KIND_APPDOMAIN_UNLOAD:
3932 buffer_add_domainid (&buf, (MonoDomain *)arg);
3933 break;
3934 case EVENT_KIND_METHOD_ENTRY:
3935 case EVENT_KIND_METHOD_EXIT:
3936 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3937 break;
3938 case EVENT_KIND_ASSEMBLY_LOAD:
3939 buffer_add_assemblyid (&buf, domain, (MonoAssembly *)arg);
3940 break;
3941 case EVENT_KIND_ASSEMBLY_UNLOAD: {
3942 DebuggerTlsData *tls;
3944 /* The domain the assembly belonged to is not equal to the current domain */
3945 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3946 g_assert (tls);
3947 g_assert (tls->domain_unloading);
3949 buffer_add_assemblyid (&buf, tls->domain_unloading, (MonoAssembly *)arg);
3950 break;
3952 case EVENT_KIND_TYPE_LOAD:
3953 buffer_add_typeid (&buf, domain, (MonoClass *)arg);
3954 break;
3955 case EVENT_KIND_BREAKPOINT:
3956 case EVENT_KIND_STEP: {
3957 DebuggerTlsData *tls;
3958 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3959 g_assert (tls);
3960 mono_stopwatch_stop (&tls->step_time);
3961 MonoMethod *method = (MonoMethod *)arg;
3963 buffer_add_methodid (&buf, domain, method);
3964 buffer_add_long (&buf, il_offset);
3965 break;
3967 case EVENT_KIND_VM_START:
3968 buffer_add_domainid (&buf, mono_get_root_domain ());
3969 break;
3970 case EVENT_KIND_VM_DEATH:
3971 if (CHECK_PROTOCOL_VERSION (2, 27))
3972 buffer_add_int (&buf, mono_environment_exitcode_get ());
3973 break;
3974 case EVENT_KIND_CRASH: {
3975 EventInfo *ei = (EventInfo *)arg;
3976 buffer_add_long (&buf, ei->hashes->offset_free_hash);
3977 buffer_add_string (&buf, ei->dump);
3978 break;
3980 case EVENT_KIND_EXCEPTION: {
3981 EventInfo *ei = (EventInfo *)arg;
3982 buffer_add_objid (&buf, ei->exc);
3984 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
3985 * later after the suspension. (#12494).
3987 keepalive_obj = ei->exc;
3988 break;
3990 case EVENT_KIND_USER_BREAK: {
3991 DebuggerTlsData *tls;
3992 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3993 g_assert (tls);
3994 // We are already processing a breakpoint event
3995 if (tls->disable_breakpoints)
3996 return;
3997 mono_stopwatch_stop (&tls->step_time);
3998 break;
4000 case EVENT_KIND_USER_LOG: {
4001 EventInfo *ei = (EventInfo *)arg;
4002 buffer_add_int (&buf, ei->level);
4003 buffer_add_string (&buf, ei->category ? ei->category : "");
4004 buffer_add_string (&buf, ei->message ? ei->message : "");
4005 break;
4007 case EVENT_KIND_KEEPALIVE:
4008 suspend_policy = SUSPEND_POLICY_NONE;
4009 break;
4010 default:
4011 g_assert_not_reached ();
4015 if (event == EVENT_KIND_VM_START) {
4016 if (!agent_config.defer) {
4017 ERROR_DECL (error);
4018 start_debugger_thread (error);
4019 mono_error_assert_ok (error);
4023 if (event == EVENT_KIND_VM_DEATH) {
4024 vm_death_event_sent = TRUE;
4025 suspend_policy = SUSPEND_POLICY_NONE;
4028 if (mono_runtime_is_shutting_down ())
4029 suspend_policy = SUSPEND_POLICY_NONE;
4031 if (suspend_policy != SUSPEND_POLICY_NONE) {
4033 * Save the thread context and start suspending before sending the packet,
4034 * since we could be receiving the resume request before send_packet ()
4035 * returns.
4037 save_thread_context (ctx);
4038 DebuggerTlsData *tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, mono_thread_internal_current ());
4039 tls->suspend_count++;
4040 suspend_vm ();
4042 if (keepalive_obj)
4043 /* This will keep this object alive */
4044 get_objref (keepalive_obj);
4047 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
4049 if (send_success) {
4050 DebuggerTlsData *tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4051 mono_debugger_log_event (tls, event_to_string (event), buf.buf, buffer_len (&buf));
4054 buffer_free (&buf);
4056 g_slist_free (events);
4057 events = NULL;
4059 if (!send_success) {
4060 PRINT_DEBUG_MSG (2, "Sending command %s failed.\n", event_to_string (event));
4061 return;
4064 if (event == EVENT_KIND_VM_START) {
4065 vm_start_event_sent = TRUE;
4068 PRINT_DEBUG_MSG (1, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer) (gsize) mono_native_thread_id_get (), nevents, event_to_string (event), ecount, suspend_policy);
4070 switch (suspend_policy) {
4071 case SUSPEND_POLICY_NONE:
4072 break;
4073 case SUSPEND_POLICY_ALL:
4074 suspend_current ();
4075 break;
4076 case SUSPEND_POLICY_EVENT_THREAD:
4077 NOT_IMPLEMENTED;
4078 break;
4079 default:
4080 g_assert_not_reached ();
4084 static void
4085 process_profiler_event (EventKind event, gpointer arg)
4087 int suspend_policy;
4088 GSList *events;
4089 EventInfo ei, *ei_arg = NULL;
4091 if (event == EVENT_KIND_TYPE_LOAD) {
4092 ei.klass = (MonoClass *)arg;
4093 ei_arg = &ei;
4096 mono_loader_lock ();
4097 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
4098 mono_loader_unlock ();
4100 process_event (event, arg, 0, NULL, events, suspend_policy);
4103 static void
4104 runtime_initialized (MonoProfiler *prof)
4106 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
4107 if (agent_config.defer) {
4108 ERROR_DECL (error);
4109 start_debugger_thread (error);
4110 mono_error_assert_ok (error);
4114 static void
4115 runtime_shutdown (MonoProfiler *prof)
4117 process_profiler_event (EVENT_KIND_VM_DEATH, NULL);
4119 mono_debugger_agent_cleanup ();
4122 static void
4123 thread_startup (MonoProfiler *prof, uintptr_t tid)
4125 MonoInternalThread *thread = mono_thread_internal_current ();
4126 MonoInternalThread *old_thread;
4127 DebuggerTlsData *tls;
4129 if (is_debugger_thread ())
4130 return;
4132 g_assert (mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (tid), MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid)));
4134 mono_loader_lock ();
4135 old_thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
4136 mono_loader_unlock ();
4137 if (old_thread) {
4138 if (thread == old_thread) {
4140 * For some reason, thread_startup () might be called for the same thread
4141 * multiple times (attach ?).
4143 PRINT_DEBUG_MSG (1, "[%p] thread_start () called multiple times for %p, ignored.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
4144 return;
4145 } else {
4147 * thread_end () might not be called for some threads, and the tid could
4148 * get reused.
4150 PRINT_DEBUG_MSG (1, "[%p] Removing stale data for tid %p.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
4151 mono_loader_lock ();
4152 mono_g_hash_table_remove (thread_to_tls, old_thread);
4153 mono_g_hash_table_remove (tid_to_thread, GUINT_TO_POINTER (tid));
4154 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
4155 mono_loader_unlock ();
4159 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4160 g_assert (!tls);
4161 // FIXME: Free this somewhere
4162 tls = g_new0 (DebuggerTlsData, 1);
4163 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread, MONO_ROOT_SOURCE_DEBUGGER, NULL, "Debugger Thread Reference");
4164 tls->thread = thread;
4165 // Do so we have thread id even after termination
4166 tls->thread_id = (intptr_t) thread->tid;
4167 mono_native_tls_set_value (debugger_tls_id, tls);
4169 PRINT_DEBUG_MSG (1, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
4171 mono_loader_lock ();
4172 mono_g_hash_table_insert_internal (thread_to_tls, thread, tls);
4173 mono_g_hash_table_insert_internal (tid_to_thread, (gpointer)tid, thread);
4174 mono_g_hash_table_insert_internal (tid_to_thread_obj, GUINT_TO_POINTER (tid), mono_thread_current ());
4175 mono_loader_unlock ();
4177 process_profiler_event (EVENT_KIND_THREAD_START, thread);
4180 * suspend_vm () could have missed this thread, so wait for a resume.
4183 suspend_current ();
4186 static void
4187 thread_end (MonoProfiler *prof, uintptr_t tid)
4189 MonoInternalThread *thread;
4190 DebuggerTlsData *tls = NULL;
4192 mono_loader_lock ();
4193 thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
4194 if (thread) {
4195 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
4196 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
4197 if (tls) {
4198 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
4199 tls->terminated = TRUE;
4200 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
4201 MONO_GC_UNREGISTER_ROOT (tls->thread);
4202 tls->thread = NULL;
4205 mono_loader_unlock ();
4207 /* We might be called for threads started before we registered the start callback */
4208 if (thread) {
4209 PRINT_DEBUG_MSG (1, "[%p] Thread terminated, obj=%p, tls=%p (domain=%p).\n", (gpointer)tid, thread, tls, (gpointer)mono_domain_get ());
4211 if (mono_thread_internal_is_current (thread) &&
4212 (!mono_native_tls_get_value (debugger_tls_id) ||
4213 !mono_domain_get ())
4216 * This can happen on darwin and android since we
4217 * deregister threads using pthread dtors.
4218 * process_profiler_event () and the code it calls
4219 * cannot handle a null TLS value.
4221 return;
4224 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
4228 static void
4229 appdomain_load (MonoProfiler *prof, MonoDomain *domain)
4231 mono_de_domain_add (domain);
4233 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
4236 static void
4237 appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain)
4239 DebuggerTlsData *tls;
4241 /* This might be called during shutdown on the debugger thread from the CMD_VM_EXIT code */
4242 if (is_debugger_thread ())
4243 return;
4246 * Remember the currently unloading appdomain as it is needed to generate
4247 * proper ids for unloading assemblies.
4249 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4250 g_assert (tls);
4251 tls->domain_unloading = domain;
4254 static void
4255 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
4257 DebuggerTlsData *tls;
4259 if (is_debugger_thread ())
4260 return;
4262 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4263 g_assert (tls);
4264 tls->domain_unloading = NULL;
4266 mono_de_clear_breakpoints_for_domain (domain);
4268 mono_loader_lock ();
4269 /* Invalidate each thread's frame stack */
4270 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
4271 mono_loader_unlock ();
4273 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
4277 * invalidate_each_thread:
4279 * A GHFunc to invalidate frames.
4280 * value must be a DebuggerTlsData*
4282 static void
4283 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
4285 invalidate_frames ((DebuggerTlsData *)value);
4288 static void
4289 assembly_load (MonoProfiler *prof, MonoAssembly *assembly)
4291 /* Sent later in jit_end () */
4292 dbg_lock ();
4293 g_ptr_array_add (pending_assembly_loads, assembly);
4294 dbg_unlock ();
4297 static void
4298 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
4300 if (is_debugger_thread ())
4301 return;
4303 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
4305 clear_event_requests_for_assembly (assembly);
4306 clear_types_for_assembly (assembly);
4309 static void
4310 send_type_load (MonoClass *klass)
4312 gboolean type_load = FALSE;
4313 MonoDomain *domain = mono_domain_get ();
4314 AgentDomainInfo *info = NULL;
4316 info = get_agent_domain_info (domain);
4318 mono_loader_lock ();
4320 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
4321 type_load = TRUE;
4322 g_hash_table_insert (info->loaded_classes, klass, klass);
4325 mono_loader_unlock ();
4327 if (type_load)
4328 emit_type_load (klass, klass, NULL);
4332 * Emit load events for all types currently loaded in the domain.
4333 * Takes the loader and domain locks.
4334 * user_data is unused.
4336 static void
4337 send_types_for_domain (MonoDomain *domain, void *user_data)
4339 MonoDomain* old_domain;
4340 AgentDomainInfo *info = NULL;
4342 if (mono_domain_is_unloading (domain))
4343 return;
4345 info = get_agent_domain_info (domain);
4346 g_assert (info);
4348 old_domain = mono_domain_get ();
4350 mono_domain_set_fast (domain, TRUE);
4352 mono_loader_lock ();
4353 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4354 mono_loader_unlock ();
4356 mono_domain_set_fast (old_domain, TRUE);
4359 static void
4360 send_assemblies_for_domain (MonoDomain *domain, void *user_data)
4362 GSList *tmp;
4363 MonoDomain* old_domain;
4365 if (mono_domain_is_unloading (domain))
4366 return;
4368 old_domain = mono_domain_get ();
4370 mono_domain_set_fast (domain, TRUE);
4372 mono_domain_assemblies_lock (domain);
4373 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
4374 MonoAssembly* ass = (MonoAssembly *)tmp->data;
4375 emit_assembly_load (ass, NULL);
4377 mono_domain_assemblies_unlock (domain);
4379 mono_domain_set_fast (old_domain, TRUE);
4382 static void
4383 jit_done (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo)
4385 jit_end (prof, method, jinfo);
4388 static void
4389 jit_failed (MonoProfiler *prof, MonoMethod *method)
4391 jit_end (prof, method, NULL);
4394 static void
4395 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo)
4398 * We emit type load events when the first method of the type is JITted,
4399 * since the class load profiler callbacks might be called with the
4400 * loader lock held. They could also occur in the debugger thread.
4401 * Same for assembly load events.
4403 while (TRUE) {
4404 MonoAssembly *assembly = NULL;
4406 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4407 dbg_lock ();
4408 if (pending_assembly_loads->len > 0) {
4409 assembly = (MonoAssembly *)g_ptr_array_index (pending_assembly_loads, 0);
4410 g_ptr_array_remove_index (pending_assembly_loads, 0);
4412 dbg_unlock ();
4414 if (assembly) {
4415 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4416 } else {
4417 break;
4421 send_type_load (method->klass);
4423 if (jinfo)
4424 mono_de_add_pending_breakpoints (method, jinfo);
4428 * SINGLE STEPPING
4431 static void
4432 event_requests_cleanup (void)
4434 mono_loader_lock ();
4435 int i = 0;
4436 while (i < event_requests->len) {
4437 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
4439 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4440 mono_de_clear_breakpoint ((MonoBreakpoint *)req->info);
4441 g_ptr_array_remove_index_fast (event_requests, i);
4442 g_free (req);
4443 } else {
4444 i ++;
4447 mono_loader_unlock ();
4451 * ss_calculate_framecount:
4453 * Ensure DebuggerTlsData fields are filled out.
4455 static void
4456 ss_calculate_framecount (void *the_tls, MonoContext *ctx, gboolean force_use_ctx, DbgEngineStackFrame ***frames, int *nframes)
4458 DebuggerTlsData *tls = (DebuggerTlsData*)the_tls;
4460 if (force_use_ctx || !tls->context.valid)
4461 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4462 compute_frame_info (tls->thread, tls, FALSE);
4463 if (frames)
4464 *frames = (DbgEngineStackFrame**)tls->frames;
4465 if (nframes)
4466 *nframes = tls->frame_count;
4470 * ss_discard_frame_data:
4472 * Discard frame data and invalidate any context
4474 static void
4475 ss_discard_frame_context (void *the_tls)
4477 DebuggerTlsData *tls = (DebuggerTlsData*)the_tls;
4478 tls->context.valid = FALSE;
4479 tls->async_state.valid = FALSE;
4480 invalidate_frames (tls);
4483 static MonoContext*
4484 tls_get_restore_state (void *the_tls)
4486 DebuggerTlsData *tls = (DebuggerTlsData*)the_tls;
4488 return &tls->restore_state.ctx;
4491 static gboolean
4492 ensure_jit (DbgEngineStackFrame* the_frame)
4494 StackFrame *frame = (StackFrame*)the_frame;
4495 if (!frame->jit) {
4496 frame->jit = mono_debug_find_method (frame->api_method, frame->de.domain);
4497 if (!frame->jit && frame->api_method->is_inflated)
4498 frame->jit = mono_debug_find_method(mono_method_get_declaring_generic_method (frame->api_method), frame->de.domain);
4499 if (!frame->jit) {
4500 char *s;
4502 /* This could happen for aot images with no jit debug info */
4503 s = mono_method_full_name (frame->api_method, TRUE);
4504 PRINT_DEBUG_MSG(1, "[dbg] No debug information found for '%s'.\n", s);
4505 g_free (s);
4506 return FALSE;
4509 return TRUE;
4512 static gboolean
4513 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4515 return bp->method && m_class_get_image (bp->method->klass)->assembly == assembly;
4518 //This ID is used to figure out if breakpoint hit on resumeOffset belongs to us or not
4519 //since thread probably changed...
4520 static int
4521 get_this_async_id (DbgEngineStackFrame *frame)
4523 MonoClassField *builder_field;
4524 gpointer builder;
4525 MonoMethod *method;
4526 MonoObject *ex;
4527 ERROR_DECL (error);
4528 MonoObject *obj;
4529 gboolean old_disable_breakpoints = FALSE;
4530 DebuggerTlsData *tls;
4533 * FRAME points to a method in a state machine class/struct.
4534 * Call the ObjectIdForDebugger method of the associated method builder type.
4536 builder = get_async_method_builder (frame);
4537 if (!builder)
4538 return 0;
4540 builder_field = mono_class_get_field_from_name_full (get_class_to_get_builder_field(frame), "<>t__builder", NULL);
4541 if (!builder_field)
4542 return 0;
4544 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4545 if (tls) {
4546 old_disable_breakpoints = tls->disable_breakpoints;
4547 tls->disable_breakpoints = TRUE;
4550 method = get_object_id_for_debugger_method (mono_class_from_mono_type_internal (builder_field->type));
4551 if (!method) {
4552 if (tls)
4553 tls->disable_breakpoints = old_disable_breakpoints;
4554 return 0;
4556 obj = mono_runtime_try_invoke (method, builder, NULL, &ex, error);
4557 mono_error_assert_ok (error);
4559 if (tls)
4560 tls->disable_breakpoints = old_disable_breakpoints;
4562 return get_objid (obj);
4565 static gboolean
4566 begin_breakpoint_processing (void *the_tls, MonoContext *ctx, MonoJitInfo *ji, gboolean from_signal)
4568 DebuggerTlsData *tls = (DebuggerTlsData*)the_tls;
4571 * Skip the instruction causing the breakpoint signal.
4573 if (from_signal)
4574 mono_arch_skip_breakpoint (ctx, ji);
4576 if (tls->disable_breakpoints)
4577 return FALSE;
4578 return TRUE;
4581 typedef struct {
4582 GSList *bp_events, *ss_events, *enter_leave_events;
4583 EventKind kind;
4584 int suspend_policy;
4585 } BreakPointEvents;
4587 static void*
4588 create_breakpoint_events (GPtrArray *ss_reqs, GPtrArray *bp_reqs, MonoJitInfo *ji, EventKind kind)
4590 int suspend_policy = 0;
4591 BreakPointEvents *evts = g_new0 (BreakPointEvents, 1);
4592 if (ss_reqs && ss_reqs->len > 0)
4593 evts->ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4594 else if (bp_reqs && bp_reqs->len > 0)
4595 evts->bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4596 else if (kind != EVENT_KIND_BREAKPOINT)
4597 evts->enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4599 evts->kind = kind;
4600 evts->suspend_policy = suspend_policy;
4601 return evts;
4604 static void
4605 process_breakpoint_events (void *_evts, MonoMethod *method, MonoContext *ctx, int il_offset)
4607 BreakPointEvents *evts = (BreakPointEvents*)_evts;
4609 * FIXME: The first event will suspend, so the second will only be sent after the
4610 * resume.
4612 if (evts->ss_events)
4613 process_event (EVENT_KIND_STEP, method, il_offset, ctx, evts->ss_events, evts->suspend_policy);
4614 if (evts->bp_events)
4615 process_event (evts->kind, method, il_offset, ctx, evts->bp_events, evts->suspend_policy);
4616 if (evts->enter_leave_events)
4617 process_event (evts->kind, method, il_offset, ctx, evts->enter_leave_events, evts->suspend_policy);
4619 g_free (evts);
4622 /* Process a breakpoint/single step event after resuming from a signal handler */
4623 static void
4624 process_signal_event (void (*func) (void*, gboolean))
4626 DebuggerTlsData *tls;
4627 MonoThreadUnwindState orig_restore_state;
4628 MonoContext ctx;
4630 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4631 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4632 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4633 mono_thread_state_init_from_monoctx (&tls->restore_state, &tls->handler_ctx);
4635 func (tls, TRUE);
4637 /* This is called when resuming from a signal handler, so it shouldn't return */
4638 memcpy (&ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4639 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4640 mono_restore_context (&ctx);
4641 g_assert_not_reached ();
4644 static void
4645 process_breakpoint_from_signal (void)
4647 process_signal_event (mono_de_process_breakpoint);
4650 static void
4651 resume_from_signal_handler (void *sigctx, void *func)
4653 DebuggerTlsData *tls;
4654 MonoContext ctx;
4656 /* Save the original context in TLS */
4657 // FIXME: This might not work on an altstack ?
4658 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4659 if (!tls)
4660 PRINT_ERROR_MSG ("Thread %p is not attached to the JIT.\n", (gpointer) (gsize) mono_native_thread_id_get ());
4661 g_assert (tls);
4663 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4664 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4665 // clob:c could be added to op_seq_point.
4667 mono_sigctx_to_monoctx (sigctx, &ctx);
4668 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4669 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4670 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4671 #else
4672 MONO_CONTEXT_SET_IP (&ctx, func);
4673 #endif
4674 mono_monoctx_to_sigctx (&ctx, sigctx);
4677 static void
4678 debugger_agent_breakpoint_hit (void *sigctx)
4681 * We are called from a signal handler, and running code there causes all kinds of
4682 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4683 * So set up the signal context to return to the real breakpoint handler function.
4685 resume_from_signal_handler (sigctx, (gpointer)process_breakpoint_from_signal);
4688 typedef struct {
4689 gboolean found;
4690 MonoContext *ctx;
4691 } UserBreakCbData;
4693 static gboolean
4694 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer user_data)
4696 UserBreakCbData *data = (UserBreakCbData*)user_data;
4698 if (frame->type == FRAME_TYPE_INTERP_TO_MANAGED || frame->type == FRAME_TYPE_INTERP_TO_MANAGED_WITH_CTX) {
4699 data->found = TRUE;
4700 return TRUE;
4702 if (frame->managed) {
4703 data->found = TRUE;
4704 *data->ctx = *ctx;
4706 return TRUE;
4708 return FALSE;
4712 * Called by System.Diagnostics.Debugger:Break ().
4714 static void
4715 debugger_agent_user_break (void)
4717 if (agent_config.enabled) {
4718 MonoContext ctx;
4719 int suspend_policy;
4720 GSList *events;
4721 UserBreakCbData data;
4723 memset (&data, 0, sizeof (data));
4724 data.ctx = &ctx;
4726 /* Obtain a context */
4727 MONO_CONTEXT_SET_IP (&ctx, NULL);
4728 mono_walk_stack_with_ctx (user_break_cb, NULL, (MonoUnwindOptions)0, &data);
4729 g_assert (data.found);
4731 mono_loader_lock ();
4732 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4733 mono_loader_unlock ();
4735 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4736 } else if (mini_debug_options.native_debugger_break) {
4737 G_BREAKPOINT ();
4741 static void
4742 begin_single_step_processing (MonoContext *ctx, gboolean from_signal)
4744 if (from_signal)
4745 mono_arch_skip_single_step (ctx);
4748 static void
4749 process_single_step (void)
4751 process_signal_event (mono_de_process_single_step);
4755 * debugger_agent_single_step_event:
4757 * Called from a signal handler to handle a single step event.
4759 static void
4760 debugger_agent_single_step_event (void *sigctx)
4762 /* Resume to process_single_step through the signal context */
4764 // FIXME: Since step out/over is implemented using step in, the step in case should
4765 // be as fast as possible. Move the relevant code from mono_de_process_single_step ()
4766 // here
4768 if (is_debugger_thread ()) {
4770 * This could happen despite our best effors when the runtime calls
4771 * assembly/type resolve hooks.
4772 * FIXME: Breakpoints too.
4774 MonoContext ctx;
4776 mono_sigctx_to_monoctx (sigctx, &ctx);
4777 mono_arch_skip_single_step (&ctx);
4778 mono_monoctx_to_sigctx (&ctx, sigctx);
4779 return;
4782 resume_from_signal_handler (sigctx, (gpointer)process_single_step);
4785 static void
4786 debugger_agent_single_step_from_context (MonoContext *ctx)
4788 DebuggerTlsData *tls;
4789 MonoThreadUnwindState orig_restore_state;
4791 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4792 /* Fastpath during invokes, see in process_suspend () */
4793 if (tls && suspend_count && suspend_count - tls->resume_count == 0)
4794 return;
4796 if (is_debugger_thread ())
4797 return;
4799 g_assert (tls);
4801 tls->terminated = FALSE;
4803 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4804 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4805 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
4806 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
4808 /* We might be called while the thread is already running some native
4809 * code after an native-to-managed transition, so the thread might be
4810 * in GC Safe mode.
4812 MONO_ENTER_GC_UNSAFE;
4813 mono_de_process_single_step (tls, FALSE);
4814 MONO_EXIT_GC_UNSAFE;
4816 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4817 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4820 static void
4821 debugger_agent_breakpoint_from_context (MonoContext *ctx)
4823 DebuggerTlsData *tls;
4824 MonoThreadUnwindState orig_restore_state;
4825 guint8 *orig_ip;
4827 if (is_debugger_thread ())
4828 return;
4830 orig_ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
4831 MONO_CONTEXT_SET_IP (ctx, orig_ip - 1);
4833 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4834 g_assert (tls);
4836 //if a thread was suspended and doesn't have any managed stack, it was considered as terminated,
4837 //but it wasn't really terminated because it can execute managed code again, and stop in a breakpoint so here we set terminated as FALSE
4838 tls->terminated = FALSE;
4840 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4841 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
4842 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
4844 /* We might be called while the thread is already running some native
4845 * code after an native-to-managed transition, so the thread might be
4846 * in GC Safe mode.
4848 MONO_ENTER_GC_UNSAFE;
4849 mono_de_process_breakpoint (tls, FALSE);
4850 MONO_EXIT_GC_UNSAFE;
4852 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4853 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4854 if (MONO_CONTEXT_GET_IP (ctx) == orig_ip - 1)
4855 MONO_CONTEXT_SET_IP (ctx, orig_ip);
4857 static void
4858 ss_args_destroy (SingleStepArgs *ss_args)
4860 if (ss_args->frames)
4861 free_frames ((StackFrame**)ss_args->frames, ss_args->nframes);
4864 static int
4865 handle_multiple_ss_requests (void)
4867 if (!CHECK_PROTOCOL_VERSION (2, 57))
4868 return DE_ERR_NOT_IMPLEMENTED;
4869 return 1;
4872 static int
4873 ensure_runtime_is_suspended (void)
4875 if (suspend_count == 0)
4876 return ERR_NOT_SUSPENDED;
4878 wait_for_suspend ();
4880 return ERR_NONE;
4883 static int
4884 ss_create_init_args (SingleStepReq *ss_req, SingleStepArgs *args)
4886 MonoSeqPointInfo *info = NULL;
4887 gboolean found_sp;
4888 MonoMethod *method = NULL;
4889 MonoDebugMethodInfo *minfo;
4890 gboolean step_to_catch = FALSE;
4891 gboolean set_ip = FALSE;
4892 StackFrame **frames = NULL;
4893 int nframes = 0;
4895 mono_loader_lock ();
4896 DebuggerTlsData *tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
4897 mono_loader_unlock ();
4898 g_assert (tls);
4899 if (!tls->context.valid) {
4900 PRINT_DEBUG_MSG (1, "Received a single step request on a thread with no managed frames.\n");
4901 return ERR_INVALID_ARGUMENT;
4904 if (tls->restore_state.valid && MONO_CONTEXT_GET_IP (&tls->context.ctx) != MONO_CONTEXT_GET_IP (&tls->restore_state.ctx)) {
4906 * Need to start single stepping from restore_state and not from the current state
4908 set_ip = TRUE;
4909 frames = compute_frame_info_from (ss_req->thread, tls, &tls->restore_state, &nframes);
4912 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
4914 if (tls->has_catch_frame) {
4915 StackFrameInfo frame;
4918 * We are stopped at a throw site. Stepping should go to the catch site.
4920 frame = tls->catch_frame;
4921 if (frame.type != FRAME_TYPE_MANAGED && frame.type != FRAME_TYPE_INTERP) {
4922 PRINT_DEBUG_MSG (1, "Current frame is not managed nor interpreter.\n");
4923 return ERR_INVALID_ARGUMENT;
4927 * Find the seq point corresponding to the landing site ip, which is the first seq
4928 * point after ip.
4930 found_sp = mono_find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info, &args->sp);
4931 if (!found_sp)
4932 no_seq_points_found (frame.method, frame.native_offset);
4933 if (!found_sp) {
4934 PRINT_DEBUG_MSG (1, "Could not find next sequence point.\n");
4935 return ERR_INVALID_ARGUMENT;
4938 method = frame.method;
4940 step_to_catch = TRUE;
4941 /* This make sure the seq point is not skipped by process_single_step () */
4942 ss_req->last_sp = NULL;
4945 if (!step_to_catch) {
4946 StackFrame *frame = NULL;
4948 if (set_ip) {
4949 if (frames && nframes)
4950 frame = frames [0];
4951 } else {
4952 compute_frame_info (ss_req->thread, tls, FALSE);
4954 if (tls->frame_count)
4955 frame = tls->frames [0];
4958 if (ss_req->size == STEP_SIZE_LINE) {
4959 if (frame) {
4960 ss_req->last_method = frame->de.method;
4961 ss_req->last_line = -1;
4963 minfo = mono_debug_lookup_method (frame->de.method);
4964 if (minfo && frame->il_offset != -1) {
4965 MonoDebugSourceLocation *loc = mono_debug_method_lookup_location (minfo, frame->il_offset);
4967 if (loc) {
4968 ss_req->last_line = loc->row;
4969 g_free (loc);
4975 if (frame) {
4976 if (!method && frame->il_offset != -1) {
4977 /* FIXME: Sort the table and use a binary search */
4978 found_sp = mono_find_prev_seq_point_for_native_offset (frame->de.domain, frame->de.method, frame->de.native_offset, &info, &args->sp);
4979 if (!found_sp)
4980 no_seq_points_found (frame->de.method, frame->de.native_offset);
4981 if (!found_sp) {
4982 PRINT_DEBUG_MSG (1, "Could not find next sequence point.\n");
4983 return ERR_INVALID_ARGUMENT;
4985 method = frame->de.method;
4990 ss_req->start_method = method;
4992 args->method = method;
4993 args->ctx = set_ip ? &tls->restore_state.ctx : &tls->context.ctx;
4994 args->tls = tls;
4995 args->step_to_catch = step_to_catch;
4996 args->info = info;
4997 args->frames = (DbgEngineStackFrame**)frames;
4998 args->nframes = nframes;
5000 return ERR_NONE;
5003 static void
5004 ss_clear_for_assembly (SingleStepReq *req, MonoAssembly *assembly)
5006 GSList *l;
5007 gboolean found = TRUE;
5009 while (found) {
5010 found = FALSE;
5011 for (l = req->bps; l; l = l->next) {
5012 if (breakpoint_matches_assembly ((MonoBreakpoint *)l->data, assembly)) {
5013 mono_de_clear_breakpoint ((MonoBreakpoint *)l->data);
5014 req->bps = g_slist_delete_link (req->bps, l);
5015 found = TRUE;
5016 break;
5023 * This takes a lot of locks and stuff. Do this at the end, after
5024 * other things have dumped us, so that getting stuck here won't
5025 * prevent seeing other crash information
5027 static void
5028 mono_debugger_agent_send_crash (char *json_dump, MonoStackHash *hashes, int pause)
5030 MONO_ENTER_GC_UNSAFE;
5031 #ifndef DISABLE_CRASH_REPORTING
5032 int suspend_policy;
5033 GSList *events;
5034 EventInfo ei;
5036 if (!agent_config.enabled)
5037 return;
5039 // Don't send the event if the client doesn't expect it
5040 if (!CHECK_PROTOCOL_VERSION (2, 49))
5041 return;
5043 // It doesn't make sense to wait for lldb/gdb to finish if we're not
5044 // actually enabled. Therefore we do the wait here.
5045 sleep (pause);
5047 // Don't heap allocate when we can avoid it
5048 EventRequest request;
5049 memset (&request, 0, sizeof (request));
5050 request.event_kind = EVENT_KIND_CRASH;
5052 gpointer pdata [1];
5053 pdata [0] = &request;
5054 GPtrArray array;
5055 memset (&array, 0, sizeof (array));
5056 array.pdata = pdata;
5057 array.len = 1;
5059 mono_loader_lock ();
5060 events = create_event_list (EVENT_KIND_CRASH, &array, NULL, NULL, &suspend_policy);
5061 mono_loader_unlock ();
5063 ei.dump = json_dump;
5064 ei.hashes = hashes;
5066 g_assert (events != NULL);
5068 process_event (EVENT_KIND_CRASH, &ei, 0, NULL, events, suspend_policy);
5070 // Don't die before it is sent.
5071 sleep (4);
5072 #endif
5073 MONO_EXIT_GC_UNSAFE;
5077 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5079 static void
5080 debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5082 ERROR_DECL (error);
5083 int suspend_policy;
5084 GSList *events;
5085 EventInfo ei;
5087 if (!agent_config.enabled)
5088 return;
5090 memset (&ei, 0, sizeof (ei));
5092 mono_loader_lock ();
5093 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5094 mono_loader_unlock ();
5096 ei.level = level;
5097 if (category) {
5098 ei.category = mono_string_to_utf8_checked_internal (category, error);
5099 mono_error_cleanup (error);
5100 error_init (error);
5102 if (message) {
5103 ei.message = mono_string_to_utf8_checked_internal (message, error);
5104 mono_error_cleanup (error);
5107 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5109 g_free (ei.category);
5110 g_free (ei.message);
5113 static gboolean
5114 debugger_agent_debug_log_is_enabled (void)
5116 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5117 return agent_config.enabled;
5120 static void
5121 debugger_agent_unhandled_exception (MonoException *exc)
5123 int suspend_policy;
5124 GSList *events;
5125 EventInfo ei;
5127 if (!agent_inited)
5128 return;
5130 memset (&ei, 0, sizeof (ei));
5131 ei.exc = (MonoObject*)exc;
5133 mono_loader_lock ();
5134 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5135 mono_loader_unlock ();
5137 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5140 static void
5141 debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5142 MonoContext *catch_ctx, StackFrameInfo *catch_frame)
5144 if (catch_ctx == NULL && catch_frame == NULL && mini_debug_options.suspend_on_unhandled && mono_object_class (exc) != mono_defaults.threadabortexception_class) {
5145 mono_runtime_printf_err ("Unhandled exception, suspending...");
5146 while (1)
5150 int i, j, suspend_policy;
5151 GSList *events;
5152 MonoJitInfo *ji, *catch_ji;
5153 EventInfo ei;
5154 DebuggerTlsData *tls = NULL;
5156 if (thread_to_tls != NULL) {
5157 MonoInternalThread *thread = mono_thread_internal_current ();
5159 mono_loader_lock ();
5160 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5161 mono_loader_unlock ();
5163 if (tls && tls->abort_requested)
5164 return;
5165 if (tls && tls->disable_breakpoints)
5166 return;
5169 memset (&ei, 0, sizeof (ei));
5171 /* Just-In-Time debugging */
5172 if (!catch_ctx) {
5173 if (agent_config.onuncaught && !agent_inited) {
5174 finish_agent_init (FALSE);
5177 * Send an unsolicited EXCEPTION event with a dummy request id.
5179 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5180 ei.exc = (MonoObject*)exc;
5181 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5182 return;
5184 } else if (agent_config.onthrow && !agent_inited) {
5185 GSList *l;
5186 gboolean found = FALSE;
5188 for (l = agent_config.onthrow; l; l = l->next) {
5189 char *ex_type = (char *)l->data;
5190 char *f = mono_type_full_name (m_class_get_byval_arg (exc->object.vtable->klass));
5192 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5193 found = TRUE;
5195 g_free (f);
5198 if (found) {
5199 finish_agent_init (FALSE);
5202 * Send an unsolicited EXCEPTION event with a dummy request id.
5204 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5205 ei.exc = (MonoObject*)exc;
5206 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5207 return;
5211 if (!agent_inited)
5212 return;
5214 ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5215 if (catch_frame)
5216 catch_ji = catch_frame->ji;
5217 else
5218 catch_ji = NULL;
5220 ei.exc = (MonoObject*)exc;
5221 ei.caught = catch_ctx != NULL;
5223 mono_loader_lock ();
5225 /* Treat exceptions which are caught in non-user code as unhandled */
5226 for (i = 0; i < event_requests->len; ++i) {
5227 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
5228 if (req->event_kind != EVENT_KIND_EXCEPTION)
5229 continue;
5231 for (j = 0; j < req->nmodifiers; ++j) {
5232 Modifier *mod = &req->modifiers [j];
5234 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5235 int k;
5236 gboolean found = FALSE;
5237 MonoAssembly **assemblies = mod->data.assemblies;
5239 if (assemblies) {
5240 for (k = 0; assemblies [k]; ++k)
5241 if (assemblies [k] == m_class_get_image (jinfo_get_method (catch_ji)->klass)->assembly)
5242 found = TRUE;
5244 if (!found)
5245 ei.caught = FALSE;
5250 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5251 mono_loader_unlock ();
5253 if (tls && ei.caught && catch_ctx) {
5254 if (catch_frame) {
5255 tls->has_catch_frame = TRUE;
5256 tls->catch_frame = *catch_frame;
5257 } else {
5258 memset (&tls->catch_frame, 0, sizeof (tls->catch_frame));
5262 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5264 if (tls)
5265 tls->has_catch_frame = FALSE;
5268 static void
5269 debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5271 DebuggerTlsData *tls;
5273 if (!agent_inited)
5274 return;
5276 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5277 if (!tls)
5278 return;
5281 * We're about to invoke an exception filter during the first pass of exception handling.
5283 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5284 * 'orig_ctx' is the context where the exception has been thrown.
5287 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5289 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5290 * the call site (line 37) and then continue to Main(), but it would never
5291 * include the throw site (line 32).
5293 * Since exception filters are invoked during the first pass of exception handling,
5294 * the stack frames of the throw site are still intact, so we should include them
5295 * in a stack trace.
5297 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5299 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5300 * but report the location of the 'throw' to the user.
5304 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5307 static void
5308 debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5310 DebuggerTlsData *tls;
5312 if (!agent_inited)
5313 return;
5315 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5316 if (!tls)
5317 return;
5319 tls->filter_state.valid = FALSE;
5322 static void
5323 buffer_add_fixed_array (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5324 gboolean as_vtype, GHashTable *parent_vtypes, gint32 len_fixed_array)
5326 buffer_add_byte (buf, VALUE_TYPE_ID_FIXED_ARRAY);
5327 buffer_add_byte (buf, t->type);
5328 buffer_add_int (buf, len_fixed_array );
5329 for (int i = 0; i < len_fixed_array; i++) {
5330 switch (t->type) {
5331 case MONO_TYPE_BOOLEAN:
5332 case MONO_TYPE_I1:
5333 case MONO_TYPE_U1:
5334 buffer_add_int (buf, ((gint8*)addr)[i]);
5335 break;
5336 case MONO_TYPE_CHAR:
5337 case MONO_TYPE_I2:
5338 case MONO_TYPE_U2:
5339 buffer_add_int (buf, ((gint16*)addr)[i]);
5340 break;
5341 case MONO_TYPE_I4:
5342 case MONO_TYPE_U4:
5343 case MONO_TYPE_R4:
5344 buffer_add_int (buf, ((gint32*)addr)[i]);
5345 break;
5346 case MONO_TYPE_I8:
5347 case MONO_TYPE_U8:
5348 case MONO_TYPE_R8:
5349 buffer_add_long (buf, ((gint64*)addr)[i]);
5350 break;
5351 case MONO_TYPE_PTR: {
5352 gssize val = *(gssize*)addr;
5354 buffer_add_byte (buf, t->type);
5355 buffer_add_long (buf, val);
5356 if (CHECK_PROTOCOL_VERSION(2, 46))
5357 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (t));
5358 break;
5364 * buffer_add_value_full:
5366 * Add the encoding of the value at ADDR described by T to the buffer.
5367 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5368 * vtypes.
5370 static void
5371 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5372 gboolean as_vtype, GHashTable *parent_vtypes, gint32 len_fixed_array)
5374 MonoObject *obj;
5375 gboolean boxed_vtype = FALSE;
5377 if (t->byref) {
5378 if (!(*(void**)addr)) {
5379 /* This can happen with compiler generated locals */
5380 //PRINT_MSG ("%s\n", mono_type_full_name (t));
5381 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5382 return;
5384 g_assert (*(void**)addr);
5385 addr = *(void**)addr;
5388 if (as_vtype) {
5389 switch (t->type) {
5390 case MONO_TYPE_BOOLEAN:
5391 case MONO_TYPE_I1:
5392 case MONO_TYPE_U1:
5393 case MONO_TYPE_CHAR:
5394 case MONO_TYPE_I2:
5395 case MONO_TYPE_U2:
5396 case MONO_TYPE_I4:
5397 case MONO_TYPE_U4:
5398 case MONO_TYPE_R4:
5399 case MONO_TYPE_I8:
5400 case MONO_TYPE_U8:
5401 case MONO_TYPE_R8:
5402 case MONO_TYPE_I:
5403 case MONO_TYPE_U:
5404 case MONO_TYPE_PTR:
5405 goto handle_vtype;
5406 break;
5407 default:
5408 break;
5412 if (len_fixed_array > 1 && t->type != MONO_TYPE_VALUETYPE && CHECK_PROTOCOL_VERSION (2, 53))
5414 buffer_add_fixed_array(buf, t, addr, domain, as_vtype, parent_vtypes, len_fixed_array);
5415 return;
5417 switch (t->type) {
5418 case MONO_TYPE_VOID:
5419 buffer_add_byte (buf, t->type);
5420 break;
5421 case MONO_TYPE_BOOLEAN:
5422 case MONO_TYPE_I1:
5423 case MONO_TYPE_U1:
5424 buffer_add_byte (buf, t->type);
5425 buffer_add_int (buf, *(gint8*)addr);
5426 break;
5427 case MONO_TYPE_CHAR:
5428 case MONO_TYPE_I2:
5429 case MONO_TYPE_U2:
5430 buffer_add_byte (buf, t->type);
5431 buffer_add_int (buf, *(gint16*)addr);
5432 break;
5433 case MONO_TYPE_I4:
5434 case MONO_TYPE_U4:
5435 case MONO_TYPE_R4:
5436 buffer_add_byte (buf, t->type);
5437 buffer_add_int (buf, *(gint32*)addr);
5438 break;
5439 case MONO_TYPE_I8:
5440 case MONO_TYPE_U8:
5441 case MONO_TYPE_R8:
5442 buffer_add_byte (buf, t->type);
5443 buffer_add_long (buf, *(gint64*)addr);
5444 break;
5445 case MONO_TYPE_I:
5446 case MONO_TYPE_U:
5447 /* Treat it as a vtype */
5448 goto handle_vtype;
5449 case MONO_TYPE_PTR:
5450 case MONO_TYPE_FNPTR: {
5451 gssize val = *(gssize*)addr;
5453 buffer_add_byte (buf, t->type);
5454 buffer_add_long (buf, val);
5455 if (CHECK_PROTOCOL_VERSION(2, 46))
5456 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (t));
5457 break;
5459 handle_ref:
5460 case MONO_TYPE_STRING:
5461 case MONO_TYPE_SZARRAY:
5462 case MONO_TYPE_OBJECT:
5463 case MONO_TYPE_CLASS:
5464 case MONO_TYPE_ARRAY:
5465 obj = *(MonoObject**)addr;
5467 if (!obj) {
5468 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5469 } else {
5470 if (m_class_is_valuetype (obj->vtable->klass)) {
5471 t = m_class_get_byval_arg (obj->vtable->klass);
5472 addr = mono_object_unbox_internal (obj);
5473 boxed_vtype = TRUE;
5474 goto handle_vtype;
5475 } else if (m_class_get_rank (obj->vtable->klass)) {
5476 buffer_add_byte (buf, m_class_get_byval_arg (obj->vtable->klass)->type);
5477 } else if (m_class_get_byval_arg (obj->vtable->klass)->type == MONO_TYPE_GENERICINST) {
5478 buffer_add_byte (buf, MONO_TYPE_CLASS);
5479 } else {
5480 buffer_add_byte (buf, m_class_get_byval_arg (obj->vtable->klass)->type);
5482 buffer_add_objid (buf, obj);
5484 break;
5485 handle_vtype:
5486 case MONO_TYPE_VALUETYPE:
5487 case MONO_TYPE_TYPEDBYREF: {
5488 int nfields;
5489 gpointer iter;
5490 MonoClassField *f;
5491 MonoClass *klass = mono_class_from_mono_type_internal (t);
5492 int vtype_index;
5494 if (boxed_vtype) {
5496 * Handle boxed vtypes recursively referencing themselves using fields.
5498 if (!parent_vtypes)
5499 parent_vtypes = g_hash_table_new (NULL, NULL);
5500 vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
5501 if (vtype_index) {
5502 if (CHECK_PROTOCOL_VERSION (2, 33)) {
5503 buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
5504 buffer_add_int (buf, vtype_index - 1);
5505 } else {
5506 /* The client can't handle PARENT_VTYPE */
5507 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5509 break;
5510 } else {
5511 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
5515 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5516 buffer_add_byte (buf, m_class_is_enumtype (klass));
5517 buffer_add_typeid (buf, domain, klass);
5519 nfields = 0;
5520 iter = NULL;
5521 while ((f = mono_class_get_fields_internal (klass, &iter))) {
5522 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5523 continue;
5524 if (mono_field_is_deleted (f))
5525 continue;
5526 nfields ++;
5528 buffer_add_int (buf, nfields);
5530 iter = NULL;
5531 while ((f = mono_class_get_fields_internal (klass, &iter))) {
5532 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5533 continue;
5534 if (mono_field_is_deleted (f))
5535 continue;
5536 buffer_add_value_full (buf, f->type, mono_vtype_get_field_addr (addr, f), domain, FALSE, parent_vtypes, len_fixed_array != 1 ? len_fixed_array : isFixedSizeArray(f));
5539 if (boxed_vtype) {
5540 g_hash_table_remove (parent_vtypes, addr);
5541 if (g_hash_table_size (parent_vtypes) == 0) {
5542 g_hash_table_destroy (parent_vtypes);
5543 parent_vtypes = NULL;
5546 break;
5548 case MONO_TYPE_GENERICINST:
5549 if (mono_type_generic_inst_is_valuetype (t)) {
5550 goto handle_vtype;
5551 } else {
5552 goto handle_ref;
5554 break;
5555 default:
5556 NOT_IMPLEMENTED;
5560 static void
5561 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5563 buffer_add_value_full (buf, t, addr, domain, FALSE, NULL, 1);
5566 static gboolean
5567 obj_is_of_type (MonoObject *obj, MonoType *t)
5569 MonoClass *klass = obj->vtable->klass;
5570 if (!mono_class_is_assignable_from_internal (mono_class_from_mono_type_internal (t), klass)) {
5571 if (mono_class_is_transparent_proxy (klass)) {
5572 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5573 if (mono_class_is_assignable_from_internal (mono_class_from_mono_type_internal (t), klass)) {
5574 return TRUE;
5577 return FALSE;
5579 return TRUE;
5582 static ErrorCode
5583 decode_value (MonoType *t, MonoDomain *domain, gpointer void_addr, gpointer void_buf, guint8 **endbuf, guint8 *limit, gboolean check_field_datatype);
5585 static ErrorCode
5586 decode_vtype (MonoType *t, MonoDomain *domain, gpointer void_addr, gpointer void_buf, guint8 **endbuf, guint8 *limit, gboolean check_field_datatype)
5588 guint8 *addr = (guint8*)void_addr;
5589 guint8 *buf = (guint8*)void_buf;
5590 gboolean is_enum;
5591 MonoClass *klass;
5592 MonoClassField *f;
5593 int nfields;
5594 gpointer iter = NULL;
5595 MonoDomain *d;
5596 ErrorCode err;
5598 is_enum = decode_byte (buf, &buf, limit);
5599 /* Enums are sent as a normal vtype */
5600 if (is_enum)
5601 return ERR_NOT_IMPLEMENTED;
5602 klass = decode_typeid (buf, &buf, limit, &d, &err);
5603 if (err != ERR_NONE)
5604 return err;
5606 if (t && klass != mono_class_from_mono_type_internal (t)) {
5607 char *name = mono_type_full_name (t);
5608 char *name2 = mono_type_full_name (m_class_get_byval_arg (klass));
5609 PRINT_DEBUG_MSG (1, "[%p] Expected value of type %s, got %s.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, name2);
5610 g_free (name);
5611 g_free (name2);
5612 return ERR_INVALID_ARGUMENT;
5615 nfields = decode_int (buf, &buf, limit);
5616 while ((f = mono_class_get_fields_internal (klass, &iter))) {
5617 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5618 continue;
5619 if (mono_field_is_deleted (f))
5620 continue;
5621 err = decode_value (f->type, domain, mono_vtype_get_field_addr (addr, f), buf, &buf, limit, check_field_datatype);
5622 if (err != ERR_NONE)
5623 return err;
5624 nfields --;
5626 g_assert (nfields == 0);
5628 *endbuf = buf;
5630 return ERR_NONE;
5632 static ErrorCode decode_fixed_size_array_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit, gboolean check_field_datatype)
5634 ErrorCode err = ERR_NONE;
5635 int fixedSizeLen = 1;
5636 int newType = MONO_TYPE_END;
5637 if (CHECK_PROTOCOL_VERSION (2, 53)) {
5638 newType = decode_byte (buf, &buf, limit);
5639 fixedSizeLen = decode_int (buf, &buf, limit);
5640 //t->type = newType;
5642 for (int i = 0 ; i < fixedSizeLen; i++) {
5643 switch (newType) {
5644 case MONO_TYPE_BOOLEAN:
5645 ((guint8*)addr)[i] = decode_int (buf, &buf, limit);
5646 break;
5647 case MONO_TYPE_CHAR:
5648 ((gunichar2*)addr)[i] = decode_int (buf, &buf, limit);
5649 break;
5650 case MONO_TYPE_I1:
5651 ((gint8*)addr)[i] = decode_int (buf, &buf, limit);
5652 break;
5653 case MONO_TYPE_U1:
5654 ((guint8*)addr)[i] = decode_int (buf, &buf, limit);
5655 break;
5656 case MONO_TYPE_I2:
5657 ((gint16*)addr)[i] = decode_int (buf, &buf, limit);
5658 break;
5659 case MONO_TYPE_U2:
5660 ((guint16*)addr)[i] = decode_int (buf, &buf, limit);
5661 break;
5662 case MONO_TYPE_I4:
5663 ((gint32*)addr)[i] = decode_int (buf, &buf, limit);
5664 break;
5665 case MONO_TYPE_U4:
5666 ((guint32*)addr)[i] = decode_int (buf, &buf, limit);
5667 break;
5668 case MONO_TYPE_I8:
5669 ((gint64*)addr)[i] = decode_long (buf, &buf, limit);
5670 break;
5671 case MONO_TYPE_U8:
5672 ((guint64*)addr)[i] = decode_long (buf, &buf, limit);
5673 break;
5674 case MONO_TYPE_R4:
5675 ((guint32*)addr)[i] = decode_int (buf, &buf, limit);
5676 break;
5677 case MONO_TYPE_R8:
5678 ((guint64*)addr)[i] = decode_long (buf, &buf, limit);
5679 break;
5682 *endbuf = buf;
5683 return err;
5685 static ErrorCode
5686 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit, gboolean check_field_datatype)
5688 ErrorCode err;
5689 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5690 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5691 !(type == VALUE_TYPE_ID_FIXED_ARRAY) &&
5692 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5693 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5694 !(t->type == MONO_TYPE_FNPTR && type == MONO_TYPE_I8) &&
5695 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE) &&
5696 !(t->type == MONO_TYPE_VALUETYPE && type == MONO_TYPE_OBJECT)) {
5697 char *name = mono_type_full_name (t);
5698 PRINT_DEBUG_MSG (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
5699 g_free (name);
5700 return ERR_INVALID_ARGUMENT;
5702 if (type == VALUE_TYPE_ID_FIXED_ARRAY && t->type != MONO_TYPE_VALUETYPE) {
5703 decode_fixed_size_array_internal (t, type, domain, addr, buf, endbuf, limit, check_field_datatype);
5704 return ERR_NONE;
5707 switch (t->type) {
5708 case MONO_TYPE_BOOLEAN:
5709 *(guint8*)addr = decode_int (buf, &buf, limit);
5710 break;
5711 case MONO_TYPE_CHAR:
5712 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5713 break;
5714 case MONO_TYPE_I1:
5715 *(gint8*)addr = decode_int (buf, &buf, limit);
5716 break;
5717 case MONO_TYPE_U1:
5718 *(guint8*)addr = decode_int (buf, &buf, limit);
5719 break;
5720 case MONO_TYPE_I2:
5721 *(gint16*)addr = decode_int (buf, &buf, limit);
5722 break;
5723 case MONO_TYPE_U2:
5724 *(guint16*)addr = decode_int (buf, &buf, limit);
5725 break;
5726 case MONO_TYPE_I4:
5727 *(gint32*)addr = decode_int (buf, &buf, limit);
5728 break;
5729 case MONO_TYPE_U4:
5730 *(guint32*)addr = decode_int (buf, &buf, limit);
5731 break;
5732 case MONO_TYPE_I8:
5733 *(gint64*)addr = decode_long (buf, &buf, limit);
5734 break;
5735 case MONO_TYPE_U8:
5736 *(guint64*)addr = decode_long (buf, &buf, limit);
5737 break;
5738 case MONO_TYPE_R4:
5739 *(guint32*)addr = decode_int (buf, &buf, limit);
5740 break;
5741 case MONO_TYPE_R8:
5742 *(guint64*)addr = decode_long (buf, &buf, limit);
5743 break;
5744 case MONO_TYPE_PTR:
5745 case MONO_TYPE_FNPTR:
5746 /* We send these as I8, so we get them back as such */
5747 g_assert (type == MONO_TYPE_I8);
5748 *(gssize*)addr = decode_long (buf, &buf, limit);
5749 break;
5750 case MONO_TYPE_GENERICINST:
5751 if (MONO_TYPE_ISSTRUCT (t)) {
5752 /* The client sends these as a valuetype */
5753 goto handle_vtype;
5754 } else {
5755 goto handle_ref;
5757 break;
5758 case MONO_TYPE_I:
5759 case MONO_TYPE_U:
5760 /* We send these as vtypes, so we get them back as such */
5761 g_assert (type == MONO_TYPE_VALUETYPE);
5762 /* Fall through */
5763 handle_vtype:
5764 case MONO_TYPE_VALUETYPE:
5765 if (type == MONO_TYPE_OBJECT) {
5766 /* Boxed vtype */
5767 int objid = decode_objid (buf, &buf, limit);
5768 ErrorCode err;
5769 MonoObject *obj;
5771 err = get_object (objid, (MonoObject**)&obj);
5772 if (err != ERR_NONE)
5773 return err;
5774 if (!obj)
5775 return ERR_INVALID_ARGUMENT;
5776 if (obj->vtable->klass != mono_class_from_mono_type_internal (t)) {
5777 PRINT_DEBUG_MSG (1, "Expected type '%s', got object '%s'\n", mono_type_full_name (t), m_class_get_name (obj->vtable->klass));
5778 return ERR_INVALID_ARGUMENT;
5780 memcpy (addr, mono_object_unbox_internal (obj), mono_class_value_size (obj->vtable->klass, NULL));
5781 } else {
5782 err = decode_vtype (t, domain, addr, buf, &buf, limit, check_field_datatype);
5783 if (err != ERR_NONE)
5784 return err;
5786 break;
5787 handle_ref:
5788 default:
5789 if (MONO_TYPE_IS_REFERENCE (t)) {
5790 if (type == MONO_TYPE_OBJECT) {
5791 int objid = decode_objid (buf, &buf, limit);
5792 ErrorCode err;
5793 MonoObject *obj;
5795 err = get_object (objid, (MonoObject**)&obj);
5796 if (err != ERR_NONE)
5797 return err;
5799 if (obj) {
5800 if (!obj_is_of_type (obj, t)) {
5801 if (check_field_datatype) { //if it's not executing a invoke method check the datatypes.
5802 PRINT_DEBUG_MSG (1, "Expected type '%s', got '%s'\n", mono_type_full_name (t), m_class_get_name (obj->vtable->klass));
5803 return ERR_INVALID_ARGUMENT;
5807 if (obj && obj->vtable->domain != domain)
5808 return ERR_INVALID_ARGUMENT;
5810 mono_gc_wbarrier_generic_store_internal (addr, obj);
5811 } else if (type == VALUE_TYPE_ID_NULL) {
5812 *(MonoObject**)addr = NULL;
5813 } else if (type == MONO_TYPE_VALUETYPE) {
5814 ERROR_DECL (error);
5815 guint8 *buf2;
5816 gboolean is_enum;
5817 MonoClass *klass;
5818 MonoDomain *d;
5819 guint8 *vtype_buf;
5820 int vtype_buf_size;
5822 /* This can happen when round-tripping boxed vtypes */
5824 * Obtain vtype class.
5825 * Same as the beginning of the handle_vtype case above.
5827 buf2 = buf;
5828 is_enum = decode_byte (buf, &buf, limit);
5829 if (is_enum)
5830 return ERR_NOT_IMPLEMENTED;
5831 klass = decode_typeid (buf, &buf, limit, &d, &err);
5832 if (err != ERR_NONE)
5833 return err;
5835 /* Decode the vtype into a temporary buffer, then box it. */
5836 vtype_buf_size = mono_class_value_size (klass, NULL);
5837 vtype_buf = (guint8 *)g_malloc0 (vtype_buf_size);
5838 g_assert (vtype_buf);
5840 buf = buf2;
5841 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit, check_field_datatype);
5842 if (err != ERR_NONE) {
5843 g_free (vtype_buf);
5844 return err;
5846 *(MonoObject**)addr = mono_value_box_checked (d, klass, vtype_buf, error);
5847 mono_error_cleanup (error);
5848 g_free (vtype_buf);
5849 } else {
5850 char *name = mono_type_full_name (t);
5851 PRINT_DEBUG_MSG (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
5852 g_free (name);
5853 return ERR_INVALID_ARGUMENT;
5855 } else if ((t->type == MONO_TYPE_GENERICINST) &&
5856 mono_metadata_generic_class_is_valuetype (t->data.generic_class) &&
5857 m_class_is_enumtype (t->data.generic_class->container_class)){
5858 err = decode_vtype (t, domain, addr, buf, &buf, limit, check_field_datatype);
5859 if (err != ERR_NONE)
5860 return err;
5861 } else {
5862 NOT_IMPLEMENTED;
5864 break;
5868 *endbuf = buf;
5870 return ERR_NONE;
5873 static ErrorCode
5874 decode_value (MonoType *t, MonoDomain *domain, gpointer void_addr, gpointer void_buf, guint8 **endbuf, guint8 *limit, gboolean check_field_datatype)
5876 guint8 *addr = (guint8*)void_addr;
5877 guint8 *buf = (guint8*)void_buf;
5879 ERROR_DECL (error);
5880 ErrorCode err;
5881 int type = decode_byte (buf, &buf, limit);
5883 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type_internal (t))) {
5884 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
5885 guint8 *nullable_buf;
5888 * First try decoding it as a Nullable`1
5890 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit, check_field_datatype);
5891 if (err == ERR_NONE)
5892 return err;
5895 * Then try decoding as a primitive value or null.
5897 if (targ->type == type) {
5898 nullable_buf = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type_internal (targ)));
5899 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit, check_field_datatype);
5900 if (err != ERR_NONE) {
5901 g_free (nullable_buf);
5902 return err;
5904 MonoObject *boxed = mono_value_box_checked (domain, mono_class_from_mono_type_internal (targ), nullable_buf, error);
5905 if (!is_ok (error)) {
5906 mono_error_cleanup (error);
5907 return ERR_INVALID_OBJECT;
5909 mono_nullable_init (addr, boxed, mono_class_from_mono_type_internal (t));
5910 g_free (nullable_buf);
5911 *endbuf = buf;
5912 return ERR_NONE;
5913 } else if (type == VALUE_TYPE_ID_NULL) {
5914 mono_nullable_init (addr, NULL, mono_class_from_mono_type_internal (t));
5915 *endbuf = buf;
5916 return ERR_NONE;
5920 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit, check_field_datatype);
5923 static void
5924 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
5926 guint32 flags;
5927 int reg;
5928 guint8 *addr, *gaddr;
5929 host_mgreg_t reg_val;
5931 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5932 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5934 switch (flags) {
5935 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
5936 reg_val = mono_arch_context_get_int_reg (ctx, reg);
5938 buffer_add_value_full (buf, t, &reg_val, domain, as_vtype, NULL, 1);
5939 break;
5940 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5941 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
5942 addr += (gint32)var->offset;
5944 //PRINT_MSG ("[R%d+%d] = %p\n", reg, var->offset, addr);
5946 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL, 1);
5947 break;
5948 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5949 NOT_IMPLEMENTED;
5950 break;
5951 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
5952 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
5953 /* Same as regoffset, but with an indirection */
5954 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
5955 addr += (gint32)var->offset;
5957 gaddr = (guint8 *)*(gpointer*)addr;
5958 g_assert (gaddr);
5959 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL, 1);
5960 break;
5961 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
5962 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
5963 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
5964 MonoGSharedVtMethodRuntimeInfo *info;
5965 guint8 *locals;
5966 int idx;
5968 idx = reg;
5970 g_assert (info_var);
5971 g_assert (locals_var);
5973 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5974 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5975 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
5976 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
5977 addr += (gint32)info_var->offset;
5978 info = (MonoGSharedVtMethodRuntimeInfo *)*(gpointer*)addr;
5979 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
5980 info = (MonoGSharedVtMethodRuntimeInfo *)mono_arch_context_get_int_reg (ctx, reg);
5981 } else {
5982 g_assert_not_reached ();
5984 g_assert (info);
5986 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5987 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5988 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
5989 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
5990 addr += (gint32)locals_var->offset;
5991 locals = (guint8 *)*(gpointer*)addr;
5992 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
5993 locals = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
5994 } else {
5995 g_assert_not_reached ();
5997 g_assert (locals);
5999 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6001 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL, 1);
6002 break;
6005 default:
6006 g_assert_not_reached ();
6010 static void
6011 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, host_mgreg_t **reg_locations, MonoContext *restore_ctx)
6013 guint32 flags;
6014 int reg, size;
6015 guint8 *addr, *gaddr;
6017 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6018 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6020 if (MONO_TYPE_IS_REFERENCE (t))
6021 size = sizeof (gpointer);
6022 else
6023 size = mono_class_value_size (mono_class_from_mono_type_internal (t), NULL);
6025 switch (flags) {
6026 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6027 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6028 host_mgreg_t v;
6029 gboolean is_signed = FALSE;
6031 if (t->byref) {
6032 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6034 if (addr) {
6035 // FIXME: Write barriers
6036 mono_gc_memmove_atomic (addr, val, size);
6038 break;
6041 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6042 is_signed = TRUE;
6044 switch (size) {
6045 case 1:
6046 v = is_signed ? *(gint8*)val : *(guint8*)val;
6047 break;
6048 case 2:
6049 v = is_signed ? *(gint16*)val : *(guint16*)val;
6050 break;
6051 case 4:
6052 v = is_signed ? *(gint32*)val : *(guint32*)val;
6053 break;
6054 case 8:
6055 v = is_signed ? *(gint64*)val : *(guint64*)val;
6056 break;
6057 default:
6058 g_assert_not_reached ();
6061 /* Set value on the stack or in the return ctx */
6062 if (reg_locations [reg]) {
6063 /* Saved on the stack */
6064 PRINT_DEBUG_MSG (1, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v);
6065 *(reg_locations [reg]) = v;
6066 } else {
6067 /* Not saved yet */
6068 PRINT_DEBUG_MSG (1, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v);
6069 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6072 // FIXME: Move these to mono-context.h/c.
6073 mono_arch_context_set_int_reg (ctx, reg, v);
6074 #else
6075 // FIXME: Can't set registers, so we disable linears
6076 NOT_IMPLEMENTED;
6077 #endif
6078 break;
6080 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6081 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6082 addr += (gint32)var->offset;
6084 //PRINT_MSG ("[R%d+%d] = %p\n", reg, var->offset, addr);
6086 if (t->byref) {
6087 addr = *(guint8**)addr;
6089 if (!addr)
6090 break;
6093 // FIXME: Write barriers
6094 mono_gc_memmove_atomic (addr, val, size);
6095 break;
6096 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6097 /* Same as regoffset, but with an indirection */
6098 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6099 addr += (gint32)var->offset;
6101 gaddr = (guint8 *)*(gpointer*)addr;
6102 g_assert (gaddr);
6103 // FIXME: Write barriers
6104 mono_gc_memmove_atomic (gaddr, val, size);
6105 break;
6106 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6107 NOT_IMPLEMENTED;
6108 break;
6109 default:
6110 g_assert_not_reached ();
6114 static void
6115 set_interp_var (MonoType *t, gpointer addr, guint8 *val_buf)
6117 int size;
6119 if (t->byref) {
6120 addr = *(gpointer*)addr;
6121 g_assert (addr);
6124 if (MONO_TYPE_IS_REFERENCE (t))
6125 size = sizeof (gpointer);
6126 else
6127 size = mono_class_value_size (mono_class_from_mono_type_internal (t), NULL);
6129 memcpy (addr, val_buf, size);
6132 static void
6133 clear_event_request (int req_id, int etype)
6135 int i;
6137 mono_loader_lock ();
6138 for (i = 0; i < event_requests->len; ++i) {
6139 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6141 if (req->id == req_id && req->event_kind == etype) {
6142 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6143 mono_de_clear_breakpoint ((MonoBreakpoint *)req->info);
6144 if (req->event_kind == EVENT_KIND_STEP) {
6145 mono_de_cancel_ss ((SingleStepReq *)req->info);
6147 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6148 mono_de_clear_breakpoint ((MonoBreakpoint *)req->info);
6149 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6150 mono_de_clear_breakpoint ((MonoBreakpoint *)req->info);
6151 g_ptr_array_remove_index_fast (event_requests, i);
6152 g_free (req);
6153 break;
6156 mono_loader_unlock ();
6159 static void
6160 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
6162 int i;
6164 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m_class_get_image (m->data.exc_class)->assembly == assembly)
6165 m->kind = MOD_KIND_NONE;
6166 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6167 int count = 0, match_count = 0, pos;
6168 MonoAssembly **newassemblies;
6170 for (i = 0; m->data.assemblies [i]; ++i) {
6171 count ++;
6172 if (m->data.assemblies [i] == assembly)
6173 match_count ++;
6176 if (match_count) {
6177 // +1 because we don't know length and we use last element to check for end
6178 newassemblies = g_new0 (MonoAssembly*, count - match_count + 1);
6180 pos = 0;
6181 for (i = 0; i < count; ++i)
6182 if (m->data.assemblies [i] != assembly)
6183 newassemblies [pos ++] = m->data.assemblies [i];
6184 g_assert (pos == count - match_count);
6185 g_free (m->data.assemblies);
6186 m->data.assemblies = newassemblies;
6191 static void
6192 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
6194 int i;
6196 for (i = 0; i < req->nmodifiers; ++i) {
6197 Modifier *m = &req->modifiers [i];
6199 clear_assembly_from_modifier (req, m, assembly);
6204 * clear_event_requests_for_assembly:
6206 * Clear all events requests which reference ASSEMBLY.
6208 static void
6209 clear_event_requests_for_assembly (MonoAssembly *assembly)
6211 int i;
6212 gboolean found;
6214 mono_loader_lock ();
6215 found = TRUE;
6216 while (found) {
6217 found = FALSE;
6218 for (i = 0; i < event_requests->len; ++i) {
6219 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6221 clear_assembly_from_modifiers (req, assembly);
6223 if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly ((MonoBreakpoint *)req->info, assembly)) {
6224 clear_event_request (req->id, req->event_kind);
6225 found = TRUE;
6226 break;
6229 if (req->event_kind == EVENT_KIND_STEP)
6230 ss_clear_for_assembly ((SingleStepReq *)req->info, assembly);
6233 mono_loader_unlock ();
6237 * type_comes_from_assembly:
6239 * GHRFunc that returns TRUE if klass comes from assembly
6241 static gboolean
6242 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6244 return mono_type_in_image (m_class_get_byval_arg ((MonoClass*)klass), mono_assembly_get_image_internal ((MonoAssembly*)assembly));
6248 * clear_types_for_assembly:
6250 * Clears types from loaded_classes for a given assembly
6252 static void
6253 clear_types_for_assembly (MonoAssembly *assembly)
6255 MonoDomain *domain = mono_domain_get ();
6256 AgentDomainInfo *info = NULL;
6258 if (!domain || !domain_jit_info (domain))
6259 /* Can happen during shutdown */
6260 return;
6262 info = get_agent_domain_info (domain);
6264 mono_loader_lock ();
6265 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6266 mono_loader_unlock ();
6269 static void
6270 dispose_vm (void)
6272 /* Clear all event requests */
6273 mono_loader_lock ();
6274 while (event_requests->len > 0) {
6275 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
6277 clear_event_request (req->id, req->event_kind);
6279 mono_loader_unlock ();
6281 while (suspend_count > 0)
6282 resume_vm ();
6283 disconnected = TRUE;
6284 vm_start_event_sent = FALSE;
6287 static void
6288 count_thread_check_gc_finalizer (gpointer key, gpointer value, gpointer user_data)
6290 MonoThread *thread = (MonoThread *)value;
6291 gboolean *ret = (gboolean *)user_data;
6292 if (mono_gc_is_finalizer_internal_thread(thread->internal_thread)) {
6293 DebuggerTlsData *tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread->internal_thread);
6294 if (!tls->gc_finalizing) { //GC Finalizer is not running some finalizer code, so ignore it
6295 *ret = TRUE;
6296 return;
6301 static void
6302 add_thread (gpointer key, gpointer value, gpointer user_data)
6304 MonoThread *thread = (MonoThread *)value;
6305 Buffer *buf = (Buffer *)user_data;
6306 if (mono_gc_is_finalizer_internal_thread(thread->internal_thread)) {
6307 DebuggerTlsData *tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread->internal_thread);
6308 if (!tls->gc_finalizing) //GC Finalizer is not running some finalizer code, so ignore it
6309 return;
6311 buffer_add_objid (buf, (MonoObject*)thread);
6315 static ErrorCode
6316 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6318 ERROR_DECL (error);
6319 guint8 *end = invoke->endp;
6320 MonoMethod *m;
6321 int i, nargs;
6322 ErrorCode err;
6323 MonoMethodSignature *sig;
6324 guint8 **arg_buf;
6325 void **args;
6326 MonoObject *this_arg, *res, *exc = NULL;
6327 MonoDomain *domain;
6328 guint8 *this_buf;
6329 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6330 MonoLMFExt ext;
6331 #endif
6332 MonoStopwatch watch;
6334 if (invoke->method) {
6336 * Invoke this method directly, currently only Environment.Exit () is supported.
6338 this_arg = NULL;
6339 PRINT_DEBUG_MSG (1, "[%p] Invoking method '%s' on receiver '%s'.\n", (gpointer) (gsize) mono_native_thread_id_get (), mono_method_full_name (invoke->method, TRUE), this_arg ? m_class_get_name (this_arg->vtable->klass) : "<null>");
6341 mono_runtime_try_invoke (invoke->method, NULL, invoke->args, &exc, error);
6342 mono_error_assert_ok (error);
6343 g_assert_not_reached ();
6346 m = decode_methodid (p, &p, end, &domain, &err);
6347 if (err != ERR_NONE)
6348 return err;
6349 sig = mono_method_signature_internal (m);
6351 if (m_class_is_valuetype (m->klass))
6352 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6353 else
6354 this_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
6356 if (m->is_generic) {
6357 PRINT_DEBUG_MSG (1, "[%p] Error: Attempting to invoke uninflated generic method %s.\n", (gpointer)(gsize)mono_native_thread_id_get (), mono_method_full_name (m, TRUE));
6358 return ERR_INVALID_ARGUMENT;
6359 } else if (m_class_is_valuetype (m->klass) && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6360 /* Should be null */
6361 int type = decode_byte (p, &p, end);
6362 if (type != VALUE_TYPE_ID_NULL) {
6363 PRINT_DEBUG_MSG (1, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6364 return ERR_INVALID_ARGUMENT;
6366 memset (this_buf, 0, mono_class_instance_size (m->klass));
6367 } else if (m_class_is_valuetype (m->klass) && !strcmp (m->name, ".ctor")) {
6368 /* Could be null */
6369 guint8 *tmp_p;
6371 int type = decode_byte (p, &tmp_p, end);
6372 if (type == VALUE_TYPE_ID_NULL) {
6373 memset (this_buf, 0, mono_class_instance_size (m->klass));
6374 p = tmp_p;
6375 } else {
6376 err = decode_value (m_class_get_byval_arg (m->klass), domain, this_buf, p, &p, end, FALSE);
6377 if (err != ERR_NONE)
6378 return err;
6380 } else {
6381 err = decode_value (m_class_get_byval_arg (m->klass), domain, this_buf, p, &p, end, FALSE);
6382 if (err != ERR_NONE)
6383 return err;
6386 if (!m_class_is_valuetype (m->klass))
6387 this_arg = *(MonoObject**)this_buf;
6388 else
6389 this_arg = NULL;
6391 if (MONO_CLASS_IS_INTERFACE_INTERNAL (m->klass)) {
6392 if (!this_arg) {
6393 PRINT_DEBUG_MSG (1, "[%p] Error: Interface method invoked without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6394 return ERR_INVALID_ARGUMENT;
6396 m = mono_object_get_virtual_method_internal (this_arg, m);
6397 /* Transform this to the format the rest of the code expects it to be */
6398 if (m_class_is_valuetype (m->klass)) {
6399 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6400 memcpy (this_buf, mono_object_unbox_internal (this_arg), mono_class_instance_size (m->klass));
6402 } else if ((m->flags & METHOD_ATTRIBUTE_VIRTUAL) && !m_class_is_valuetype (m->klass) && invoke->flags & INVOKE_FLAG_VIRTUAL) {
6403 if (!this_arg) {
6404 PRINT_DEBUG_MSG (1, "[%p] Error: invoke with INVOKE_FLAG_VIRTUAL flag set without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6405 return ERR_INVALID_ARGUMENT;
6407 m = mono_object_get_virtual_method_internal (this_arg, m);
6408 if (m_class_is_valuetype (m->klass)) {
6409 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6410 memcpy (this_buf, mono_object_unbox_internal (this_arg), mono_class_instance_size (m->klass));
6414 PRINT_DEBUG_MSG (1, "[%p] Invoking method '%s' on receiver '%s'.\n", (gpointer) (gsize) mono_native_thread_id_get (), mono_method_full_name (m, TRUE), this_arg ? m_class_get_name (this_arg->vtable->klass) : "<null>");
6416 if (this_arg && this_arg->vtable->domain != domain)
6417 NOT_IMPLEMENTED;
6419 if (!m_class_is_valuetype (m->klass) && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this_arg) {
6420 if (!strcmp (m->name, ".ctor")) {
6421 if (mono_class_is_abstract (m->klass))
6422 return ERR_INVALID_ARGUMENT;
6423 else {
6424 ERROR_DECL (error);
6425 this_arg = mono_object_new_checked (domain, m->klass, error);
6426 if (!is_ok (error)) {
6427 mono_error_cleanup (error);
6428 return ERR_INVALID_ARGUMENT;
6431 } else {
6432 return ERR_INVALID_ARGUMENT;
6436 if (this_arg && !obj_is_of_type (this_arg, m_class_get_byval_arg (m->klass)))
6437 return ERR_INVALID_ARGUMENT;
6439 nargs = decode_int (p, &p, end);
6440 if (nargs != sig->param_count)
6441 return ERR_INVALID_ARGUMENT;
6442 /* Use alloca to get gc tracking */
6443 arg_buf = (guint8 **)g_alloca (nargs * sizeof (gpointer));
6444 memset (arg_buf, 0, nargs * sizeof (gpointer));
6445 args = (gpointer *)g_alloca (nargs * sizeof (gpointer));
6446 for (i = 0; i < nargs; ++i) {
6447 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6448 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end, TRUE);
6449 if (err != ERR_NONE)
6450 break;
6451 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6452 NOT_IMPLEMENTED;
6454 if (sig->params [i]->byref) {
6455 arg_buf [i] = g_newa (guint8, sizeof (gpointer));
6456 *(gpointer*)arg_buf [i] = args [i];
6457 args [i] = arg_buf [i];
6459 } else {
6460 MonoClass *arg_class = mono_class_from_mono_type_internal (sig->params [i]);
6461 arg_buf [i] = (guint8 *)g_alloca (mono_class_instance_size (arg_class));
6462 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end, TRUE);
6463 if (err != ERR_NONE)
6464 break;
6465 if (mono_class_is_nullable (arg_class)) {
6466 args [i] = mono_nullable_box (arg_buf [i], arg_class, error);
6467 mono_error_assert_ok (error);
6468 } else {
6469 args [i] = arg_buf [i];
6474 if (i < nargs)
6475 return err;
6477 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6478 tls->disable_breakpoints = TRUE;
6479 else
6480 tls->disable_breakpoints = FALSE;
6483 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6485 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6486 if (invoke->has_ctx) {
6487 /* Setup our lmf */
6488 memset (&ext, 0, sizeof (ext));
6489 ext.kind = MONO_LMFEXT_DEBUGGER_INVOKE;
6490 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6492 mono_push_lmf (&ext);
6494 #endif
6496 mono_stopwatch_start (&watch);
6497 res = mono_runtime_try_invoke (m, m_class_is_valuetype (m->klass) ? (gpointer) this_buf : (gpointer) this_arg, args, &exc, error);
6498 if (!is_ok (error) && exc == NULL) {
6499 exc = (MonoObject*) mono_error_convert_to_exception (error);
6500 } else {
6501 mono_error_cleanup (error); /* FIXME report error */
6503 mono_stopwatch_stop (&watch);
6504 PRINT_DEBUG_MSG (1, "[%p] Invoke result: %p, exc: %s, time: %ld ms.\n", (gpointer) (gsize) mono_native_thread_id_get (), res, exc ? m_class_get_name (exc->vtable->klass) : NULL, (long)mono_stopwatch_elapsed_ms (&watch));
6505 if (exc) {
6506 buffer_add_byte (buf, 0);
6507 buffer_add_value (buf, mono_get_object_type (), &exc, domain);
6508 } else {
6509 gboolean out_this = FALSE;
6510 gboolean out_args = FALSE;
6512 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_THIS) && CHECK_PROTOCOL_VERSION (2, 35))
6513 out_this = TRUE;
6514 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_ARGS) && CHECK_PROTOCOL_VERSION (2, 35))
6515 out_args = TRUE;
6516 buffer_add_byte (buf, 1 + (out_this ? 2 : 0) + (out_args ? 4 : 0));
6517 if (m->string_ctor) {
6518 buffer_add_value (buf, m_class_get_byval_arg (mono_get_string_class ()), &res, domain);
6519 } else if (sig->ret->type == MONO_TYPE_VOID && !m->string_ctor) {
6520 if (!strcmp (m->name, ".ctor")) {
6521 if (!m_class_is_valuetype (m->klass))
6522 buffer_add_value (buf, mono_get_object_type (), &this_arg, domain);
6523 else
6524 buffer_add_value (buf, m_class_get_byval_arg (m->klass), this_buf, domain);
6525 } else {
6526 buffer_add_value (buf, mono_get_void_type (), NULL, domain);
6528 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6529 if (sig->ret->byref) {
6530 MonoType* ret_byval = m_class_get_byval_arg (mono_class_from_mono_type_internal (sig->ret));
6531 buffer_add_value (buf, ret_byval, &res, domain);
6532 } else {
6533 buffer_add_value (buf, sig->ret, &res, domain);
6535 } else if (m_class_is_valuetype (mono_class_from_mono_type_internal (sig->ret)) || sig->ret->type == MONO_TYPE_PTR || sig->ret->type == MONO_TYPE_FNPTR) {
6536 if (mono_class_is_nullable (mono_class_from_mono_type_internal (sig->ret))) {
6537 MonoClass *k = mono_class_from_mono_type_internal (sig->ret);
6538 guint8 *nullable_buf = (guint8 *)g_alloca (mono_class_value_size (k, NULL));
6540 g_assert (nullable_buf);
6541 mono_nullable_init (nullable_buf, res, k);
6542 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6543 } else {
6544 g_assert (res);
6546 if (sig->ret->byref) {
6547 MonoType* ret_byval = m_class_get_byval_arg (mono_class_from_mono_type_internal (sig->ret));
6548 buffer_add_value (buf, ret_byval, mono_object_unbox_internal (res), domain);
6549 } else {
6550 buffer_add_value (buf, sig->ret, mono_object_unbox_internal (res), domain);
6553 } else {
6554 NOT_IMPLEMENTED;
6556 if (out_this)
6557 /* Return the new value of the receiver after the call */
6558 buffer_add_value (buf, m_class_get_byval_arg (m->klass), this_buf, domain);
6559 if (out_args) {
6560 buffer_add_int (buf, nargs);
6561 for (i = 0; i < nargs; ++i) {
6562 if (MONO_TYPE_IS_REFERENCE (sig->params [i]))
6563 buffer_add_value (buf, sig->params [i], &args [i], domain);
6564 else if (sig->params [i]->byref)
6565 /* add_value () does an indirection */
6566 buffer_add_value (buf, sig->params [i], &arg_buf [i], domain);
6567 else
6568 buffer_add_value (buf, sig->params [i], arg_buf [i], domain);
6573 tls->disable_breakpoints = FALSE;
6575 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6576 if (invoke->has_ctx)
6577 mono_pop_lmf ((MonoLMF*)&ext);
6578 #endif
6580 *endp = p;
6581 // FIXME: byref arguments
6582 // FIXME: varargs
6583 return ERR_NONE;
6587 * invoke_method:
6589 * Invoke the method given by tls->pending_invoke in the current thread.
6591 static void
6592 invoke_method (void)
6594 DebuggerTlsData *tls;
6595 InvokeData *invoke;
6596 int id;
6597 int i, mindex;
6598 ErrorCode err;
6599 Buffer buf;
6600 MonoContext restore_ctx;
6601 guint8 *p;
6603 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
6604 g_assert (tls);
6607 * Store the `InvokeData *' in `tls->invoke' until we're done with
6608 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6611 mono_loader_lock ();
6613 invoke = tls->pending_invoke;
6614 g_assert (invoke);
6615 tls->pending_invoke = NULL;
6617 invoke->last_invoke = tls->invoke;
6618 tls->invoke = invoke;
6620 mono_loader_unlock ();
6622 tls->frames_up_to_date = FALSE;
6624 id = invoke->id;
6626 p = invoke->p;
6627 err = ERR_NONE;
6628 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6629 buffer_init (&buf, 128);
6631 if (err) {
6632 /* Fail the other invokes as well */
6633 } else {
6634 err = do_invoke_method (tls, &buf, invoke, p, &p);
6637 if (tls->abort_requested) {
6638 if (CHECK_PROTOCOL_VERSION (2, 42))
6639 err = ERR_INVOKE_ABORTED;
6642 /* Start suspending before sending the reply */
6643 if (mindex == invoke->nmethods - 1) {
6644 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6645 for (i = 0; i < invoke->suspend_count; ++i)
6646 suspend_vm ();
6650 send_reply_packet (id, err, &buf);
6652 buffer_free (&buf);
6655 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6657 if (invoke->has_ctx)
6658 save_thread_context (&restore_ctx);
6660 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6661 g_assert (tls->resume_count);
6662 tls->resume_count -= invoke->suspend_count;
6665 PRINT_DEBUG_MSG (1, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer) (gsize) mono_native_thread_id_get (), err, tls->resume_count);
6668 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6670 * It is possible that mono_thread_internal_abort () was called
6671 * after the mono_runtime_invoke_checked() already returned, but it doesn't matter
6672 * because we reset the abort here.
6675 mono_loader_lock ();
6677 if (tls->abort_requested)
6678 mono_thread_internal_reset_abort (tls->thread);
6680 tls->invoke = tls->invoke->last_invoke;
6681 tls->abort_requested = FALSE;
6683 mono_loader_unlock ();
6685 g_free (invoke->p);
6686 g_free (invoke);
6689 static gboolean
6690 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6692 MonoThread *thread = (MonoThread *)value;
6693 DebuggerTlsData *tls;
6694 gboolean res;
6696 mono_loader_lock ();
6697 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
6698 g_assert (tls);
6699 res = tls->really_suspended;
6700 mono_loader_unlock ();
6702 return res;
6705 static GPtrArray*
6706 get_source_files_for_type (MonoClass *klass)
6708 gpointer iter = NULL;
6709 MonoMethod *method;
6710 MonoDebugSourceInfo *sinfo;
6711 GPtrArray *files;
6712 int i, j;
6714 files = g_ptr_array_new ();
6716 while ((method = mono_class_get_methods (klass, &iter))) {
6717 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6718 GPtrArray *source_file_list;
6720 if (minfo) {
6721 mono_debug_get_seq_points (minfo, NULL, &source_file_list, NULL, NULL, NULL);
6722 for (j = 0; j < source_file_list->len; ++j) {
6723 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, j);
6724 for (i = 0; i < files->len; ++i)
6725 if (!strcmp ((const char*)g_ptr_array_index (files, i), (const char*)sinfo->source_file))
6726 break;
6727 if (i == files->len)
6728 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6730 g_ptr_array_free (source_file_list, TRUE);
6734 return files;
6738 typedef struct {
6739 MonoTypeNameParse *info;
6740 gboolean ignore_case;
6741 GPtrArray *res_classes;
6742 GPtrArray *res_domains;
6743 } GetTypesArgs;
6745 static void
6746 get_types (gpointer key, gpointer value, gpointer user_data)
6748 MonoAssembly *ass;
6749 gboolean type_resolve;
6750 MonoType *t;
6751 GSList *tmp;
6752 MonoDomain *domain = (MonoDomain*)key;
6754 if (mono_domain_is_unloading (domain))
6755 return;
6757 MonoAssemblyLoadContext *alc = mono_domain_default_alc (domain);
6758 GetTypesArgs *ud = (GetTypesArgs*)user_data;
6760 mono_domain_assemblies_lock (domain);
6761 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6762 ass = (MonoAssembly *)tmp->data;
6764 if (ass->image) {
6765 ERROR_DECL (probe_type_error);
6766 /* FIXME really okay to call while holding locks? */
6767 t = mono_reflection_get_type_checked (alc, ass->image, ass->image, ud->info, ud->ignore_case, TRUE, &type_resolve, probe_type_error);
6768 mono_error_cleanup (probe_type_error);
6769 if (t) {
6770 g_ptr_array_add (ud->res_classes, mono_type_get_class_internal (t));
6771 g_ptr_array_add (ud->res_domains, domain);
6775 mono_domain_assemblies_unlock (domain);
6778 typedef struct {
6779 gboolean ignore_case;
6780 char *basename;
6781 GPtrArray *res_classes;
6782 GPtrArray *res_domains;
6783 } GetTypesForSourceFileArgs;
6785 static void
6786 get_types_for_source_file (gpointer key, gpointer value, gpointer user_data)
6788 GHashTableIter iter;
6789 GSList *class_list = NULL;
6790 MonoClass *klass = NULL;
6791 GPtrArray *files = NULL;
6793 GetTypesForSourceFileArgs *ud = (GetTypesForSourceFileArgs*)user_data;
6794 MonoDomain *domain = (MonoDomain*)key;
6796 if (mono_domain_is_unloading (domain))
6797 return;
6799 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
6801 /* Update 'source_file_to_class' cache */
6802 g_hash_table_iter_init (&iter, info->loaded_classes);
6803 while (g_hash_table_iter_next (&iter, NULL, (void**)&klass)) {
6804 if (!g_hash_table_lookup (info->source_files, klass)) {
6805 files = get_source_files_for_type (klass);
6806 g_hash_table_insert (info->source_files, klass, files);
6808 for (int i = 0; i < files->len; ++i) {
6809 char *s = (char *)g_ptr_array_index (files, i);
6810 char *s2 = dbg_path_get_basename (s);
6811 char *s3;
6813 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, s2);
6814 if (!class_list) {
6815 class_list = g_slist_prepend (class_list, klass);
6816 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
6817 } else {
6818 class_list = g_slist_prepend (class_list, klass);
6819 g_hash_table_insert (info->source_file_to_class, s2, class_list);
6822 /* The _ignorecase hash contains the lowercase path */
6823 s3 = strdup_tolower (s2);
6824 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
6825 if (!class_list) {
6826 class_list = g_slist_prepend (class_list, klass);
6827 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
6828 } else {
6829 class_list = g_slist_prepend (class_list, klass);
6830 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
6833 g_free (s2);
6834 g_free (s3);
6839 if (ud->ignore_case) {
6840 char *s;
6842 s = strdup_tolower (ud->basename);
6843 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
6844 g_free (s);
6845 } else {
6846 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, ud->basename);
6849 for (GSList *l = class_list; l; l = l->next) {
6850 klass = (MonoClass *)l->data;
6852 g_ptr_array_add (ud->res_classes, klass);
6853 g_ptr_array_add (ud->res_domains, domain);
6857 static void
6858 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
6860 if (val && val->vtable->klass == mono_defaults.runtimetype_class) {
6861 /* Special case these so the client doesn't have to handle Type objects */
6863 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
6864 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (((MonoReflectionType*)val)->type));
6865 } else if (MONO_TYPE_IS_REFERENCE (t))
6866 buffer_add_value (buf, t, &val, domain);
6867 else
6868 buffer_add_value (buf, t, mono_object_unbox_internal (val), domain);
6871 static ErrorCode
6872 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
6874 int i, j;
6875 int nattrs = 0;
6877 if (!cinfo) {
6878 buffer_add_int (buf, 0);
6879 return ERR_NONE;
6882 SETUP_ICALL_FUNCTION;
6884 for (i = 0; i < cinfo->num_attrs; ++i) {
6885 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
6886 nattrs ++;
6888 buffer_add_int (buf, nattrs);
6890 for (i = 0; i < cinfo->num_attrs; ++i) {
6891 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
6892 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
6893 MonoArray *typed_args, *named_args;
6894 MonoArrayHandleOut typed_args_h, named_args_h;
6895 MonoObjectHandle val_h;
6896 MonoType *t;
6897 CattrNamedArg *arginfo = NULL;
6898 ERROR_DECL (error);
6900 SETUP_ICALL_FRAME;
6901 typed_args_h = MONO_HANDLE_NEW (MonoArray, NULL);
6902 named_args_h = MONO_HANDLE_NEW (MonoArray, NULL);
6903 val_h = MONO_HANDLE_NEW (MonoObject, NULL);
6905 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, typed_args_h, named_args_h, &arginfo, error);
6906 if (!is_ok (error)) {
6907 PRINT_DEBUG_MSG (2, "[dbg] mono_reflection_create_custom_attr_data_args () failed with: '%s'\n", mono_error_get_message (error));
6908 mono_error_cleanup (error);
6909 CLEAR_ICALL_FRAME;
6910 return ERR_LOADER_ERROR;
6912 typed_args = MONO_HANDLE_RAW (typed_args_h);
6913 named_args = MONO_HANDLE_RAW (named_args_h);
6915 buffer_add_methodid (buf, domain, attr->ctor);
6917 /* Ctor args */
6918 if (typed_args) {
6919 buffer_add_int (buf, mono_array_length_internal (typed_args));
6920 for (j = 0; j < mono_array_length_internal (typed_args); ++j) {
6921 MonoObject *val = mono_array_get_internal (typed_args, MonoObject*, j);
6922 MONO_HANDLE_ASSIGN_RAW (val_h, val);
6924 t = mono_method_signature_internal (attr->ctor)->params [j];
6926 buffer_add_cattr_arg (buf, t, domain, val);
6928 } else {
6929 buffer_add_int (buf, 0);
6932 /* Named args */
6933 if (named_args) {
6934 buffer_add_int (buf, mono_array_length_internal (named_args));
6936 for (j = 0; j < mono_array_length_internal (named_args); ++j) {
6937 MonoObject *val = mono_array_get_internal (named_args, MonoObject*, j);
6938 MONO_HANDLE_ASSIGN_RAW (val_h, val);
6940 if (arginfo [j].prop) {
6941 buffer_add_byte (buf, 0x54);
6942 buffer_add_propertyid (buf, domain, arginfo [j].prop);
6943 } else if (arginfo [j].field) {
6944 buffer_add_byte (buf, 0x53);
6945 buffer_add_fieldid (buf, domain, arginfo [j].field);
6946 } else {
6947 g_assert_not_reached ();
6950 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
6952 } else {
6953 buffer_add_int (buf, 0);
6955 g_free (arginfo);
6957 CLEAR_ICALL_FRAME;
6961 return ERR_NONE;
6964 static void add_error_string (Buffer *buf, const char *str)
6966 if (CHECK_PROTOCOL_VERSION (2, 56))
6967 buffer_add_string (buf, str);
6970 static ErrorCode
6971 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6973 switch (command) {
6974 case CMD_VM_VERSION: {
6975 char *build_info, *version;
6977 build_info = mono_get_runtime_build_info ();
6978 version = g_strdup_printf ("mono %s", build_info);
6980 buffer_add_string (buf, version); /* vm version */
6981 buffer_add_int (buf, MAJOR_VERSION);
6982 buffer_add_int (buf, MINOR_VERSION);
6983 g_free (build_info);
6984 g_free (version);
6985 break;
6987 case CMD_VM_SET_PROTOCOL_VERSION: {
6988 major_version = decode_int (p, &p, end);
6989 minor_version = decode_int (p, &p, end);
6990 protocol_version_set = TRUE;
6991 PRINT_DEBUG_MSG (1, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version);
6992 break;
6994 case CMD_VM_ALL_THREADS: {
6995 // FIXME: Domains
6996 gboolean remove_gc_finalizing = FALSE;
6997 mono_loader_lock ();
6998 int count = mono_g_hash_table_size (tid_to_thread_obj);
6999 mono_g_hash_table_foreach (tid_to_thread_obj, count_thread_check_gc_finalizer, &remove_gc_finalizing);
7000 if (remove_gc_finalizing)
7001 count--;
7002 buffer_add_int (buf, count);
7003 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
7005 mono_loader_unlock ();
7006 break;
7008 case CMD_VM_SUSPEND:
7009 suspend_vm ();
7010 wait_for_suspend ();
7011 break;
7012 case CMD_VM_RESUME:
7013 if (suspend_count == 0) {
7014 if (agent_config.defer && !agent_config.suspend)
7015 // Workaround for issue in debugger-libs when running in defer attach mode.
7016 break;
7017 else
7018 return ERR_NOT_SUSPENDED;
7020 resume_vm ();
7021 clear_suspended_objs ();
7022 break;
7023 case CMD_VM_DISPOSE:
7024 dispose_vm ();
7025 break;
7026 case CMD_VM_EXIT: {
7027 MonoInternalThread *thread;
7028 DebuggerTlsData *tls;
7029 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7030 MonoClass *env_class;
7031 #endif
7032 MonoMethod *exit_method = NULL;
7033 gpointer *args;
7034 int exit_code;
7036 exit_code = decode_int (p, &p, end);
7038 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
7040 /* Have to send a reply before exiting */
7041 send_reply_packet (id, 0, buf);
7043 /* Clear all event requests */
7044 mono_loader_lock ();
7045 while (event_requests->len > 0) {
7046 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
7048 clear_event_request (req->id, req->event_kind);
7050 mono_loader_unlock ();
7053 * The JDWP documentation says that the shutdown is not orderly. It doesn't
7054 * specify whenever a VM_DEATH event is sent. We currently do an orderly
7055 * shutdown by hijacking a thread to execute Environment.Exit (). This is
7056 * better than doing the shutdown ourselves, since it avoids various races.
7059 suspend_vm ();
7060 wait_for_suspend ();
7062 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7063 env_class = mono_class_try_load_from_name (mono_defaults.corlib, "System", "Environment");
7064 if (env_class) {
7065 ERROR_DECL (error);
7066 exit_method = mono_class_get_method_from_name_checked (env_class, "Exit", 1, 0, error);
7067 mono_error_assert_ok (error);
7069 #endif
7071 mono_loader_lock ();
7072 thread = (MonoInternalThread *)mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
7073 mono_loader_unlock ();
7075 if (thread && exit_method) {
7076 mono_loader_lock ();
7077 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
7078 mono_loader_unlock ();
7080 args = g_new0 (gpointer, 1);
7081 args [0] = g_malloc (sizeof (int));
7082 *(int*)(args [0]) = exit_code;
7084 tls->pending_invoke = g_new0 (InvokeData, 1);
7085 tls->pending_invoke->method = exit_method;
7086 tls->pending_invoke->args = args;
7087 tls->pending_invoke->nmethods = 1;
7089 while (suspend_count > 0)
7090 resume_vm ();
7091 } else {
7093 * No thread found, do it ourselves.
7094 * FIXME: This can race with normal shutdown etc.
7096 while (suspend_count > 0)
7097 resume_vm ();
7099 if (!mono_runtime_try_shutdown ())
7100 break;
7102 mono_environment_exitcode_set (exit_code);
7104 /* Suspend all managed threads since the runtime is going away */
7105 #ifndef ENABLE_NETCORE
7106 PRINT_DEBUG_MSG (1, "Suspending all threads...\n");
7107 mono_thread_suspend_all_other_threads ();
7108 #endif
7109 PRINT_DEBUG_MSG (1, "Shutting down the runtime...\n");
7110 mono_runtime_quit_internal ();
7111 transport_close2 ();
7112 PRINT_DEBUG_MSG (1, "Exiting...\n");
7114 exit (exit_code);
7116 break;
7118 case CMD_VM_INVOKE_METHOD:
7119 case CMD_VM_INVOKE_METHODS: {
7120 int objid = decode_objid (p, &p, end);
7121 MonoThread *thread;
7122 DebuggerTlsData *tls;
7123 int i, count, flags, nmethods;
7124 ErrorCode err;
7126 err = get_object (objid, (MonoObject**)&thread);
7127 if (err != ERR_NONE)
7128 return err;
7130 flags = decode_int (p, &p, end);
7132 if (command == CMD_VM_INVOKE_METHODS)
7133 nmethods = decode_int (p, &p, end);
7134 else
7135 nmethods = 1;
7137 // Wait for suspending if it already started
7138 if (suspend_count)
7139 wait_for_suspend ();
7140 if (!is_suspended ())
7141 return ERR_NOT_SUSPENDED;
7143 mono_loader_lock ();
7144 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7145 mono_loader_unlock ();
7146 g_assert (tls);
7148 if (!tls->really_suspended)
7149 /* The thread is still running native code, can't do invokes */
7150 return ERR_NOT_SUSPENDED;
7153 * Store the invoke data into tls, the thread will execute it after it is
7154 * resumed.
7156 if (tls->pending_invoke)
7157 return ERR_NOT_SUSPENDED;
7158 tls->pending_invoke = g_new0 (InvokeData, 1);
7159 tls->pending_invoke->id = id;
7160 tls->pending_invoke->flags = flags;
7161 tls->pending_invoke->p = (guint8 *)g_malloc (end - p);
7162 memcpy (tls->pending_invoke->p, p, end - p);
7163 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
7164 tls->pending_invoke->suspend_count = suspend_count;
7165 tls->pending_invoke->nmethods = nmethods;
7167 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
7168 resume_thread (THREAD_TO_INTERNAL (thread));
7170 else {
7171 count = suspend_count;
7172 for (i = 0; i < count; ++i)
7173 resume_vm ();
7175 break;
7177 case CMD_VM_ABORT_INVOKE: {
7178 int objid = decode_objid (p, &p, end);
7179 MonoThread *thread;
7180 DebuggerTlsData *tls;
7181 int invoke_id;
7182 ErrorCode err;
7184 err = get_object (objid, (MonoObject**)&thread);
7185 if (err != ERR_NONE)
7186 return err;
7188 invoke_id = decode_int (p, &p, end);
7190 mono_loader_lock ();
7191 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7192 g_assert (tls);
7194 if (tls->abort_requested) {
7195 PRINT_DEBUG_MSG (1, "Abort already requested.\n");
7196 mono_loader_unlock ();
7197 break;
7201 * Check whether we're still inside the mono_runtime_invoke_checked() and that it's
7202 * actually the correct invocation.
7204 * Careful, we do not stop the thread that's doing the invocation, so we can't
7205 * inspect its stack. However, invoke_method() also acquires the loader lock
7206 * when it's done, so we're safe here.
7210 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
7211 mono_loader_unlock ();
7212 return ERR_NO_INVOCATION;
7215 tls->abort_requested = TRUE;
7217 mono_thread_internal_abort (THREAD_TO_INTERNAL (thread), FALSE);
7218 mono_loader_unlock ();
7219 break;
7222 case CMD_VM_SET_KEEPALIVE: {
7223 int timeout = decode_int (p, &p, end);
7224 agent_config.keepalive = timeout;
7225 // FIXME:
7226 #ifndef DISABLE_SOCKET_TRANSPORT
7227 set_keepalive ();
7228 #else
7229 NOT_IMPLEMENTED;
7230 #endif
7231 break;
7233 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
7234 int i;
7235 char *fname, *basename;
7236 gboolean ignore_case;
7237 GPtrArray *res_classes, *res_domains;
7239 fname = decode_string (p, &p, end);
7240 ignore_case = decode_byte (p, &p, end);
7242 basename = dbg_path_get_basename (fname);
7244 res_classes = g_ptr_array_new ();
7245 res_domains = g_ptr_array_new ();
7247 mono_loader_lock ();
7248 GetTypesForSourceFileArgs args;
7249 memset (&args, 0, sizeof (args));
7250 args.ignore_case = ignore_case;
7251 args.basename = basename;
7252 args.res_classes = res_classes;
7253 args.res_domains = res_domains;
7254 mono_de_foreach_domain (get_types_for_source_file, &args);
7255 mono_loader_unlock ();
7257 g_free (fname);
7258 g_free (basename);
7260 buffer_add_int (buf, res_classes->len);
7261 for (i = 0; i < res_classes->len; ++i)
7262 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7263 g_ptr_array_free (res_classes, TRUE);
7264 g_ptr_array_free (res_domains, TRUE);
7265 break;
7267 case CMD_VM_GET_TYPES: {
7268 ERROR_DECL (error);
7269 int i;
7270 char *name;
7271 gboolean ignore_case;
7272 GPtrArray *res_classes, *res_domains;
7273 MonoTypeNameParse info;
7275 name = decode_string (p, &p, end);
7276 ignore_case = decode_byte (p, &p, end);
7278 if (!mono_reflection_parse_type_checked (name, &info, error)) {
7279 add_error_string (buf, mono_error_get_message (error));
7280 mono_error_cleanup (error);
7281 g_free (name);
7282 mono_reflection_free_type_info (&info);
7283 return ERR_INVALID_ARGUMENT;
7286 res_classes = g_ptr_array_new ();
7287 res_domains = g_ptr_array_new ();
7289 mono_loader_lock ();
7291 GetTypesArgs args;
7292 memset (&args, 0, sizeof (args));
7293 args.info = &info;
7294 args.ignore_case = ignore_case;
7295 args.res_classes = res_classes;
7296 args.res_domains = res_domains;
7298 mono_de_foreach_domain (get_types, &args);
7300 mono_loader_unlock ();
7302 g_free (name);
7303 mono_reflection_free_type_info (&info);
7305 buffer_add_int (buf, res_classes->len);
7306 for (i = 0; i < res_classes->len; ++i)
7307 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7308 g_ptr_array_free (res_classes, TRUE);
7309 g_ptr_array_free (res_domains, TRUE);
7310 break;
7312 case CMD_VM_START_BUFFERING:
7313 case CMD_VM_STOP_BUFFERING:
7314 /* Handled in the main loop */
7315 break;
7316 default:
7317 return ERR_NOT_IMPLEMENTED;
7320 return ERR_NONE;
7323 static ErrorCode
7324 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7326 ErrorCode err;
7327 ERROR_DECL (error);
7329 switch (command) {
7330 case CMD_EVENT_REQUEST_SET: {
7331 EventRequest *req;
7332 int i, event_kind, suspend_policy, nmodifiers;
7333 ModifierKind mod;
7334 MonoMethod *method;
7335 long location = 0;
7336 MonoThread *step_thread;
7337 int step_thread_id = 0;
7338 StepDepth depth = STEP_DEPTH_INTO;
7339 StepSize size = STEP_SIZE_MIN;
7340 StepFilter filter = STEP_FILTER_NONE;
7341 MonoDomain *domain;
7342 Modifier *modifier;
7344 event_kind = decode_byte (p, &p, end);
7345 suspend_policy = decode_byte (p, &p, end);
7346 nmodifiers = decode_byte (p, &p, end);
7348 req = (EventRequest *)g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7349 req->id = mono_atomic_inc_i32 (&event_request_id);
7350 req->event_kind = event_kind;
7351 req->suspend_policy = suspend_policy;
7352 req->nmodifiers = nmodifiers;
7354 method = NULL;
7355 for (i = 0; i < nmodifiers; ++i) {
7356 mod = (ModifierKind)decode_byte (p, &p, end);
7358 req->modifiers [i].kind = mod;
7359 if (mod == MOD_KIND_COUNT) {
7360 req->modifiers [i].data.count = decode_int (p, &p, end);
7361 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7362 method = decode_methodid (p, &p, end, &domain, &err);
7363 if (err != ERR_NONE)
7364 return err;
7365 location = decode_long (p, &p, end);
7366 } else if (mod == MOD_KIND_STEP) {
7367 step_thread_id = decode_id (p, &p, end);
7368 size = (StepSize)decode_int (p, &p, end);
7369 depth = (StepDepth)decode_int (p, &p, end);
7370 if (CHECK_PROTOCOL_VERSION (2, 16))
7371 filter = (StepFilter)decode_int (p, &p, end);
7372 req->modifiers [i].data.filter = filter;
7373 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7374 /* Treat STEP_THOUGH the same as HIDDEN */
7375 req->modifiers [i].data.filter = (StepFilter)(req->modifiers [i].data.filter | STEP_FILTER_DEBUGGER_STEP_THROUGH);
7376 } else if (mod == MOD_KIND_THREAD_ONLY) {
7377 int id = decode_id (p, &p, end);
7379 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7380 if (err != ERR_NONE) {
7381 g_free (req);
7382 return err;
7384 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7385 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7387 if (err != ERR_NONE)
7388 return err;
7389 req->modifiers [i].caught = decode_byte (p, &p, end);
7390 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7391 if (CHECK_PROTOCOL_VERSION (2, 25))
7392 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7393 else
7394 req->modifiers [i].subclasses = TRUE;
7395 if (exc_class) {
7396 req->modifiers [i].data.exc_class = exc_class;
7398 if (!mono_class_is_assignable_from_internal (mono_defaults.exception_class, exc_class)) {
7399 g_free (req);
7400 return ERR_INVALID_ARGUMENT;
7403 if (CHECK_PROTOCOL_VERSION (2, 54)) {
7404 req->modifiers [i].not_filtered_feature = decode_byte (p, &p, end);
7405 req->modifiers [i].everything_else = decode_byte (p, &p, end);
7406 PRINT_DEBUG_MSG (1, "[dbg] \tEXCEPTION_ONLY 2 filter (%s%s%s%s).\n", exc_class ? m_class_get_name (exc_class) : (req->modifiers [i].everything_else ? "everything else" : "all"), req->modifiers [i].caught ? ", caught" : "", req->modifiers [i].uncaught ? ", uncaught" : "", req->modifiers [i].subclasses ? ", include-subclasses" : "");
7407 } else {
7408 req->modifiers [i].not_filtered_feature = FALSE;
7409 req->modifiers [i].everything_else = FALSE;
7410 PRINT_DEBUG_MSG (1, "[dbg] \tEXCEPTION_ONLY filter (%s%s%s%s).\n", exc_class ? m_class_get_name (exc_class) : "all", req->modifiers [i].caught ? ", caught" : "", req->modifiers [i].uncaught ? ", uncaught" : "", req->modifiers [i].subclasses ? ", include-subclasses" : "");
7413 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7414 int n = decode_int (p, &p, end);
7415 int j;
7417 // +1 because we don't know length and we use last element to check for end
7418 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n + 1);
7419 for (j = 0; j < n; ++j) {
7420 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7421 if (err != ERR_NONE) {
7422 g_free (req->modifiers [i].data.assemblies);
7423 return err;
7426 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7427 int n = decode_int (p, &p, end);
7428 int j;
7430 modifier = &req->modifiers [i];
7431 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7432 for (j = 0; j < n; ++j) {
7433 char *s = decode_string (p, &p, end);
7434 char *s2;
7436 if (s) {
7437 s2 = strdup_tolower (s);
7438 g_hash_table_insert (modifier->data.source_files, s2, s2);
7439 g_free (s);
7442 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7443 int n = decode_int (p, &p, end);
7444 int j;
7446 modifier = &req->modifiers [i];
7447 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7448 for (j = 0; j < n; ++j) {
7449 char *s = decode_string (p, &p, end);
7451 if (s)
7452 g_hash_table_insert (modifier->data.type_names, s, s);
7454 } else {
7455 g_free (req);
7456 return ERR_NOT_IMPLEMENTED;
7460 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7461 g_assert (method);
7463 req->info = mono_de_set_breakpoint (method, location, req, error);
7464 if (!is_ok (error)) {
7465 g_free (req);
7466 PRINT_DEBUG_MSG (1, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (error));
7467 mono_error_cleanup (error);
7468 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7470 } else if (req->event_kind == EVENT_KIND_STEP) {
7471 g_assert (step_thread_id);
7473 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7474 if (err != ERR_NONE) {
7475 g_free (req);
7476 return err;
7479 mono_loader_lock ();
7480 DebuggerTlsData *tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL(step_thread));
7481 mono_loader_unlock ();
7482 g_assert (tls);
7484 if (tls->terminated) {
7485 /* if the thread is already terminated ignore the single step */
7486 buffer_add_int (buf, req->id);
7487 return ERR_NONE;
7490 err = (ErrorCode)mono_de_ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, filter, req);
7491 if (err != ERR_NONE) {
7492 g_free (req);
7493 return err;
7495 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7496 req->info = mono_de_set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7497 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7498 req->info = mono_de_set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7499 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7500 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7501 } else {
7502 if (req->nmodifiers) {
7503 g_free (req);
7504 return ERR_NOT_IMPLEMENTED;
7508 mono_loader_lock ();
7509 g_ptr_array_add (event_requests, req);
7511 if (agent_config.defer) {
7512 /* Transmit cached data to the client on receipt of the event request */
7513 switch (req->event_kind) {
7514 case EVENT_KIND_APPDOMAIN_CREATE:
7515 /* Emit load events for currently loaded domains */
7516 mono_de_foreach_domain (emit_appdomain_load, NULL);
7517 break;
7518 case EVENT_KIND_ASSEMBLY_LOAD:
7519 /* Emit load events for currently loaded assemblies */
7520 mono_domain_foreach (send_assemblies_for_domain, NULL);
7521 break;
7522 case EVENT_KIND_THREAD_START:
7523 /* Emit start events for currently started threads */
7524 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7525 break;
7526 case EVENT_KIND_TYPE_LOAD:
7527 /* Emit type load events for currently loaded types */
7528 mono_domain_foreach (send_types_for_domain, NULL);
7529 break;
7530 default:
7531 break;
7534 mono_loader_unlock ();
7536 buffer_add_int (buf, req->id);
7537 break;
7539 case CMD_EVENT_REQUEST_CLEAR: {
7540 int etype = decode_byte (p, &p, end);
7541 int req_id = decode_int (p, &p, end);
7543 // FIXME: Make a faster mapping from req_id to request
7544 mono_loader_lock ();
7545 clear_event_request (req_id, etype);
7546 mono_loader_unlock ();
7547 break;
7549 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7550 int i;
7552 mono_loader_lock ();
7553 i = 0;
7554 while (i < event_requests->len) {
7555 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
7557 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7558 mono_de_clear_breakpoint ((MonoBreakpoint *)req->info);
7560 g_ptr_array_remove_index_fast (event_requests, i);
7561 g_free (req);
7562 } else {
7563 i ++;
7566 mono_loader_unlock ();
7567 break;
7569 default:
7570 return ERR_NOT_IMPLEMENTED;
7573 return ERR_NONE;
7576 static ErrorCode
7577 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7579 ErrorCode err;
7580 MonoDomain *domain;
7582 switch (command) {
7583 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7584 buffer_add_domainid (buf, mono_get_root_domain ());
7585 break;
7587 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7588 domain = decode_domainid (p, &p, end, NULL, &err);
7589 if (err != ERR_NONE)
7590 return err;
7591 buffer_add_string (buf, domain->friendly_name);
7592 break;
7594 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7595 GSList *tmp;
7596 MonoAssembly *ass;
7597 int count;
7599 domain = decode_domainid (p, &p, end, NULL, &err);
7600 if (err != ERR_NONE)
7601 return err;
7602 mono_domain_assemblies_lock (domain);
7603 count = 0;
7604 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7605 count ++;
7607 buffer_add_int (buf, count);
7608 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7609 ass = (MonoAssembly *)tmp->data;
7610 buffer_add_assemblyid (buf, domain, ass);
7612 mono_domain_assemblies_unlock (domain);
7613 break;
7615 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7616 domain = decode_domainid (p, &p, end, NULL, &err);
7617 if (err != ERR_NONE)
7618 return err;
7620 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7621 break;
7623 case CMD_APPDOMAIN_GET_CORLIB: {
7624 domain = decode_domainid (p, &p, end, NULL, &err);
7625 if (err != ERR_NONE)
7626 return err;
7628 buffer_add_assemblyid (buf, domain, m_class_get_image (domain->domain->mbr.obj.vtable->klass)->assembly);
7629 break;
7631 case CMD_APPDOMAIN_CREATE_STRING: {
7632 char *s;
7633 MonoString *o;
7634 ERROR_DECL (error);
7636 domain = decode_domainid (p, &p, end, NULL, &err);
7637 if (err != ERR_NONE)
7638 return err;
7639 s = decode_string (p, &p, end);
7641 o = mono_string_new_checked (domain, s, error);
7642 if (!is_ok (error)) {
7643 PRINT_DEBUG_MSG (1, "[dbg] Failed to allocate String object '%s': %s\n", s, mono_error_get_message (error));
7644 mono_error_cleanup (error);
7645 return ERR_INVALID_OBJECT;
7647 buffer_add_objid (buf, (MonoObject*)o);
7648 break;
7650 case CMD_APPDOMAIN_CREATE_BYTE_ARRAY: {
7651 ERROR_DECL (error);
7652 MonoArray *arr;
7653 gpointer elem;
7654 domain = decode_domainid (p, &p, end, NULL, &err);
7655 uintptr_t size = 0;
7656 int len = decode_int (p, &p, end);
7657 size = len;
7658 arr = mono_array_new_full_checked (mono_domain_get (), mono_class_create_array (mono_get_byte_class(), 1), &size, NULL, error);
7659 elem = mono_array_addr_internal (arr, guint8, 0);
7660 memcpy (elem, p, len);
7661 p += len;
7662 buffer_add_objid (buf, (MonoObject*) arr);
7663 break;
7665 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7666 ERROR_DECL (error);
7667 MonoClass *klass;
7668 MonoDomain *domain2;
7669 MonoObject *o;
7671 domain = decode_domainid (p, &p, end, NULL, &err);
7672 if (err != ERR_NONE)
7673 return err;
7674 klass = decode_typeid (p, &p, end, &domain2, &err);
7675 if (err != ERR_NONE)
7676 return err;
7678 // FIXME:
7679 g_assert (domain == domain2);
7681 o = mono_object_new_checked (domain, klass, error);
7682 mono_error_assert_ok (error);
7684 err = decode_value (m_class_get_byval_arg (klass), domain, (guint8 *)mono_object_unbox_internal (o), p, &p, end, TRUE);
7685 if (err != ERR_NONE)
7686 return err;
7688 buffer_add_objid (buf, o);
7689 break;
7691 default:
7692 return ERR_NOT_IMPLEMENTED;
7695 return ERR_NONE;
7698 static ErrorCode
7699 get_assembly_object_command (MonoDomain *domain, MonoAssembly *ass, Buffer *buf, MonoError *error)
7701 HANDLE_FUNCTION_ENTER();
7702 ErrorCode err = ERR_NONE;
7703 error_init (error);
7704 MonoReflectionAssemblyHandle o = mono_assembly_get_object_handle (domain, ass, error);
7705 if (MONO_HANDLE_IS_NULL (o)) {
7706 err = ERR_INVALID_OBJECT;
7707 goto leave;
7709 buffer_add_objid (buf, MONO_HANDLE_RAW (MONO_HANDLE_CAST (MonoObject, o)));
7710 leave:
7711 HANDLE_FUNCTION_RETURN_VAL (err);
7715 static ErrorCode
7716 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7718 ErrorCode err;
7719 MonoAssembly *ass;
7720 MonoDomain *domain;
7722 ass = decode_assemblyid (p, &p, end, &domain, &err);
7723 if (err != ERR_NONE)
7724 return err;
7726 switch (command) {
7727 case CMD_ASSEMBLY_GET_LOCATION: {
7728 buffer_add_string (buf, mono_image_get_filename (ass->image));
7729 break;
7731 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7732 guint32 token;
7733 MonoMethod *m;
7735 if (ass->image->dynamic) {
7736 buffer_add_id (buf, 0);
7737 } else {
7738 token = mono_image_get_entry_point (ass->image);
7739 if (token == 0) {
7740 buffer_add_id (buf, 0);
7741 } else {
7742 ERROR_DECL (error);
7743 m = mono_get_method_checked (ass->image, token, NULL, NULL, error);
7744 if (!m)
7745 mono_error_cleanup (error); /* FIXME don't swallow the error */
7746 buffer_add_methodid (buf, domain, m);
7749 break;
7751 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7752 buffer_add_moduleid (buf, domain, ass->image);
7753 break;
7755 case CMD_ASSEMBLY_GET_OBJECT: {
7756 ERROR_DECL (error);
7757 err = get_assembly_object_command (domain, ass, buf, error);
7758 mono_error_cleanup (error);
7759 return err;
7761 case CMD_ASSEMBLY_GET_DOMAIN: {
7762 buffer_add_domainid (buf, domain);
7763 break;
7765 case CMD_ASSEMBLY_GET_TYPE: {
7766 ERROR_DECL (error);
7767 char *s = decode_string (p, &p, end);
7768 char* original_s = g_strdup_printf ("\"%s\"", s);
7770 gboolean ignorecase = decode_byte (p, &p, end);
7771 MonoTypeNameParse info;
7772 MonoType *t;
7773 gboolean type_resolve, res;
7774 MonoDomain *d = mono_domain_get ();
7775 MonoAssemblyLoadContext *alc = mono_domain_default_alc (d);
7777 /* This is needed to be able to find referenced assemblies */
7778 res = mono_domain_set_fast (domain, FALSE);
7779 g_assert (res);
7781 if (!mono_reflection_parse_type_checked (s, &info, error)) {
7782 mono_error_cleanup (error);
7783 t = NULL;
7784 } else {
7785 if (info.assembly.name) {
7786 mono_reflection_free_type_info (&info);
7787 g_free (s);
7788 mono_domain_set_fast (d, TRUE);
7789 char* error_msg = g_strdup_printf ("Unexpected assembly-qualified type %s was provided", original_s);
7790 add_error_string (buf, error_msg);
7791 g_free (error_msg);
7792 g_free (original_s);
7793 return ERR_INVALID_ARGUMENT;
7795 t = mono_reflection_get_type_checked (alc, ass->image, ass->image, &info, ignorecase, TRUE, &type_resolve, error);
7796 if (!is_ok (error)) {
7797 mono_error_cleanup (error); /* FIXME don't swallow the error */
7798 mono_reflection_free_type_info (&info);
7799 g_free (s);
7800 mono_domain_set_fast (d, TRUE);
7801 char* error_msg = g_strdup_printf ("Invalid type name %s", original_s);
7802 add_error_string (buf, error_msg);
7803 g_free (error_msg);
7804 g_free (original_s);
7805 return ERR_INVALID_ARGUMENT;
7808 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type_internal (t) : NULL);
7809 mono_reflection_free_type_info (&info);
7810 g_free (s);
7811 g_free (original_s);
7812 mono_domain_set_fast (d, TRUE);
7814 break;
7816 case CMD_ASSEMBLY_GET_NAME: {
7817 gchar *name;
7818 MonoAssembly *mass = ass;
7820 name = g_strdup_printf (
7821 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7822 mass->aname.name,
7823 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7824 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7825 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7826 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7828 buffer_add_string (buf, name);
7829 g_free (name);
7830 break;
7832 case CMD_ASSEMBLY_GET_METADATA_BLOB: {
7833 MonoImage* image = ass->image;
7834 if (ass->dynamic) {
7835 return ERR_NOT_IMPLEMENTED;
7837 buffer_add_byte_array (buf, (guint8*)image->raw_data, image->raw_data_len);
7838 break;
7840 case CMD_ASSEMBLY_GET_IS_DYNAMIC: {
7841 buffer_add_byte (buf, ass->dynamic);
7842 break;
7844 case CMD_ASSEMBLY_GET_PDB_BLOB: {
7845 MonoImage* image = ass->image;
7846 MonoDebugHandle* handle = mono_debug_get_handle (image);
7847 if (!handle) {
7848 return ERR_INVALID_ARGUMENT;
7850 MonoPPDBFile* ppdb = handle->ppdb;
7851 if (ppdb) {
7852 image = mono_ppdb_get_image (ppdb);
7853 buffer_add_byte_array (buf, (guint8*)image->raw_data, image->raw_data_len);
7854 } else {
7855 buffer_add_byte_array (buf, NULL, 0);
7857 break;
7859 case CMD_ASSEMBLY_GET_TYPE_FROM_TOKEN: {
7860 if (ass->dynamic) {
7861 return ERR_NOT_IMPLEMENTED;
7863 guint32 token = decode_int (p, &p, end);
7864 ERROR_DECL (error);
7865 error_init (error);
7866 MonoClass* mono_class = mono_class_get_checked (ass->image, token, error);
7867 if (!is_ok (error)) {
7868 add_error_string (buf, mono_error_get_message (error));
7869 mono_error_cleanup (error);
7870 return ERR_INVALID_ARGUMENT;
7872 buffer_add_typeid (buf, domain, mono_class);
7873 mono_error_cleanup (error);
7874 break;
7876 case CMD_ASSEMBLY_GET_METHOD_FROM_TOKEN: {
7877 if (ass->dynamic) {
7878 return ERR_NOT_IMPLEMENTED;
7880 guint32 token = decode_int (p, &p, end);
7881 ERROR_DECL (error);
7882 error_init (error);
7883 MonoMethod* mono_method = mono_get_method_checked (ass->image, token, NULL, NULL, error);
7884 if (!is_ok (error)) {
7885 add_error_string (buf, mono_error_get_message (error));
7886 mono_error_cleanup (error);
7887 return ERR_INVALID_ARGUMENT;
7889 buffer_add_methodid (buf, domain, mono_method);
7890 mono_error_cleanup (error);
7891 break;
7893 case CMD_ASSEMBLY_HAS_DEBUG_INFO: {
7894 buffer_add_byte (buf, !ass->dynamic && mono_debug_image_has_debug_info (ass->image));
7895 break;
7897 case CMD_ASSEMBLY_GET_CATTRS: {
7898 ERROR_DECL (error);
7899 MonoClass *attr_klass;
7900 MonoCustomAttrInfo *cinfo;
7902 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7903 /* attr_klass can be NULL */
7904 if (err != ERR_NONE)
7905 return err;
7907 cinfo = mono_custom_attrs_from_assembly_checked (ass, FALSE, error);
7908 if (!is_ok (error)) {
7909 mono_error_cleanup (error); /* FIXME don't swallow the error message */
7910 return ERR_LOADER_ERROR;
7913 err = buffer_add_cattrs (buf, domain, mono_assembly_get_image_internal (ass), attr_klass, cinfo);
7914 if (err != ERR_NONE)
7915 return err;
7916 break;
7918 default:
7919 return ERR_NOT_IMPLEMENTED;
7922 return ERR_NONE;
7925 static ErrorCode
7926 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7928 ErrorCode err;
7929 MonoDomain *domain;
7931 switch (command) {
7932 case CMD_MODULE_GET_INFO: {
7933 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7934 char *basename, *sourcelink = NULL;
7936 if (CHECK_PROTOCOL_VERSION (2, 48))
7937 sourcelink = mono_debug_image_get_sourcelink (image);
7939 basename = g_path_get_basename (image->name);
7940 buffer_add_string (buf, basename); // name
7941 buffer_add_string (buf, image->module_name); // scopename
7942 buffer_add_string (buf, image->name); // fqname
7943 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7944 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7945 if (CHECK_PROTOCOL_VERSION (2, 48))
7946 buffer_add_string (buf, sourcelink);
7947 g_free (basename);
7948 g_free (sourcelink);
7949 break;
7951 default:
7952 return ERR_NOT_IMPLEMENTED;
7955 return ERR_NONE;
7958 static ErrorCode
7959 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7961 ErrorCode err;
7962 MonoDomain *domain;
7964 switch (command) {
7965 case CMD_FIELD_GET_INFO: {
7966 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
7968 buffer_add_string (buf, f->name);
7969 buffer_add_typeid (buf, domain, f->parent);
7970 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (f->type));
7971 buffer_add_int (buf, f->type->attrs);
7972 break;
7974 default:
7975 return ERR_NOT_IMPLEMENTED;
7978 return ERR_NONE;
7981 /* FIXME: Code duplication with icall.c */
7982 static void
7983 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
7985 int i;
7986 MonoClass *ic;
7988 mono_class_setup_interfaces (klass, error);
7989 if (!is_ok (error))
7990 return;
7992 int klass_interface_count = m_class_get_interface_count (klass);
7993 MonoClass **klass_interfaces = m_class_get_interfaces (klass);
7994 for (i = 0; i < klass_interface_count; i++) {
7995 ic = klass_interfaces [i];
7996 g_hash_table_insert (ifaces, ic, ic);
7998 collect_interfaces (ic, ifaces, error);
7999 if (!is_ok (error))
8000 return;
8004 static ErrorCode
8005 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8007 HANDLE_FUNCTION_ENTER ();
8009 ERROR_DECL (error);
8010 MonoClass *nested;
8011 MonoType *type;
8012 gpointer iter;
8013 guint8 b;
8014 int nnested;
8015 ErrorCode err;
8016 char *name;
8017 MonoStringHandle string_handle = MONO_HANDLE_NEW (MonoString, NULL); // FIXME? Not always needed.
8019 switch (command) {
8020 case CMD_TYPE_GET_INFO: {
8021 buffer_add_string (buf, m_class_get_name_space (klass));
8022 buffer_add_string (buf, m_class_get_name (klass));
8023 // FIXME: byref
8024 name = mono_type_get_name_full (m_class_get_byval_arg (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
8025 buffer_add_string (buf, name);
8026 g_free (name);
8027 buffer_add_assemblyid (buf, domain, m_class_get_image (klass)->assembly);
8028 buffer_add_moduleid (buf, domain, m_class_get_image (klass));
8029 buffer_add_typeid (buf, domain, m_class_get_parent (klass));
8030 if (m_class_get_rank (klass) || m_class_get_byval_arg (klass)->type == MONO_TYPE_PTR)
8031 buffer_add_typeid (buf, domain, m_class_get_element_class (klass));
8032 else
8033 buffer_add_id (buf, 0);
8034 buffer_add_int (buf, m_class_get_type_token (klass));
8035 buffer_add_byte (buf, m_class_get_rank (klass));
8036 buffer_add_int (buf, mono_class_get_flags (klass));
8037 b = 0;
8038 type = m_class_get_byval_arg (klass);
8039 // FIXME: Can't decide whenever a class represents a byref type
8040 if (FALSE)
8041 b |= (1 << 0);
8042 if (type->type == MONO_TYPE_PTR || type->type == MONO_TYPE_FNPTR)
8043 b |= (1 << 1);
8044 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
8045 b |= (1 << 2);
8046 if (type->type == MONO_TYPE_VALUETYPE)
8047 b |= (1 << 3);
8048 if (m_class_is_enumtype (klass))
8049 b |= (1 << 4);
8050 if (mono_class_is_gtd (klass))
8051 b |= (1 << 5);
8052 if (mono_class_is_gtd (klass) || mono_class_is_ginst (klass))
8053 b |= (1 << 6);
8054 buffer_add_byte (buf, b);
8055 nnested = 0;
8056 iter = NULL;
8057 while ((nested = mono_class_get_nested_types (klass, &iter)))
8058 nnested ++;
8059 buffer_add_int (buf, nnested);
8060 iter = NULL;
8061 while ((nested = mono_class_get_nested_types (klass, &iter)))
8062 buffer_add_typeid (buf, domain, nested);
8063 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8064 if (mono_class_is_gtd (klass))
8065 buffer_add_typeid (buf, domain, klass);
8066 else if (mono_class_is_ginst (klass))
8067 buffer_add_typeid (buf, domain, mono_class_get_generic_class (klass)->container_class);
8068 else
8069 buffer_add_id (buf, 0);
8071 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8072 int count, i;
8074 if (mono_class_is_ginst (klass)) {
8075 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
8077 count = inst->type_argc;
8078 buffer_add_int (buf, count);
8079 for (i = 0; i < count; i++)
8080 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (inst->type_argv [i]));
8081 } else if (mono_class_is_gtd (klass)) {
8082 MonoGenericContainer *container = mono_class_get_generic_container (klass);
8083 MonoClass *pklass;
8085 count = container->type_argc;
8086 buffer_add_int (buf, count);
8087 for (i = 0; i < count; i++) {
8088 pklass = mono_class_create_generic_parameter (mono_generic_container_get_param (container, i));
8089 buffer_add_typeid (buf, domain, pklass);
8091 } else {
8092 buffer_add_int (buf, 0);
8095 break;
8097 case CMD_TYPE_GET_METHODS: {
8098 int nmethods;
8099 int i = 0;
8100 gpointer iter = NULL;
8101 MonoMethod *m;
8103 mono_class_setup_methods (klass);
8105 nmethods = mono_class_num_methods (klass);
8107 buffer_add_int (buf, nmethods);
8109 while ((m = mono_class_get_methods (klass, &iter))) {
8110 buffer_add_methodid (buf, domain, m);
8111 i ++;
8113 g_assert (i == nmethods);
8114 break;
8116 case CMD_TYPE_GET_FIELDS: {
8117 int nfields;
8118 int i = 0;
8119 gpointer iter = NULL;
8120 MonoClassField *f;
8122 nfields = mono_class_num_fields (klass);
8124 buffer_add_int (buf, nfields);
8126 while ((f = mono_class_get_fields_internal (klass, &iter))) {
8127 buffer_add_fieldid (buf, domain, f);
8128 buffer_add_string (buf, f->name);
8129 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (f->type));
8130 buffer_add_int (buf, f->type->attrs);
8131 i ++;
8133 g_assert (i == nfields);
8134 break;
8136 case CMD_TYPE_GET_PROPERTIES: {
8137 int nprops;
8138 int i = 0;
8139 gpointer iter = NULL;
8140 MonoProperty *p;
8142 nprops = mono_class_num_properties (klass);
8144 buffer_add_int (buf, nprops);
8146 while ((p = mono_class_get_properties (klass, &iter))) {
8147 buffer_add_propertyid (buf, domain, p);
8148 buffer_add_string (buf, p->name);
8149 buffer_add_methodid (buf, domain, p->get);
8150 buffer_add_methodid (buf, domain, p->set);
8151 buffer_add_int (buf, p->attrs);
8152 i ++;
8154 g_assert (i == nprops);
8155 break;
8157 case CMD_TYPE_GET_CATTRS: {
8158 MonoClass *attr_klass;
8159 MonoCustomAttrInfo *cinfo;
8161 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8162 /* attr_klass can be NULL */
8163 if (err != ERR_NONE)
8164 goto exit;
8166 cinfo = mono_custom_attrs_from_class_checked (klass, error);
8167 if (!is_ok (error)) {
8168 mono_error_cleanup (error); /* FIXME don't swallow the error message */
8169 goto loader_error;
8172 err = buffer_add_cattrs (buf, domain, m_class_get_image (klass), attr_klass, cinfo);
8173 if (err != ERR_NONE)
8174 goto exit;
8175 break;
8177 case CMD_TYPE_GET_FIELD_CATTRS: {
8178 MonoClass *attr_klass;
8179 MonoCustomAttrInfo *cinfo;
8180 MonoClassField *field;
8182 field = decode_fieldid (p, &p, end, NULL, &err);
8183 if (err != ERR_NONE)
8184 goto exit;
8185 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8186 if (err != ERR_NONE)
8187 goto exit;
8189 cinfo = mono_custom_attrs_from_field_checked (klass, field, error);
8190 if (!is_ok (error)) {
8191 mono_error_cleanup (error); /* FIXME don't swallow the error message */
8192 goto loader_error;
8195 err = buffer_add_cattrs (buf, domain, m_class_get_image (klass), attr_klass, cinfo);
8196 if (err != ERR_NONE)
8197 goto exit;
8198 break;
8200 case CMD_TYPE_GET_PROPERTY_CATTRS: {
8201 MonoClass *attr_klass;
8202 MonoCustomAttrInfo *cinfo;
8203 MonoProperty *prop;
8205 prop = decode_propertyid (p, &p, end, NULL, &err);
8206 if (err != ERR_NONE)
8207 goto exit;
8208 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8209 if (err != ERR_NONE)
8210 goto exit;
8212 cinfo = mono_custom_attrs_from_property_checked (klass, prop, error);
8213 if (!is_ok (error)) {
8214 mono_error_cleanup (error); /* FIXME don't swallow the error message */
8215 goto loader_error;
8218 err = buffer_add_cattrs (buf, domain, m_class_get_image (klass), attr_klass, cinfo);
8219 if (err != ERR_NONE)
8220 goto exit;
8221 break;
8223 case CMD_TYPE_GET_VALUES:
8224 case CMD_TYPE_GET_VALUES_2: {
8225 guint8 *val;
8226 MonoClassField *f;
8227 MonoVTable *vtable;
8228 MonoClass *k;
8229 int len, i;
8230 gboolean found;
8231 MonoThread *thread_obj;
8232 MonoInternalThread *thread = NULL;
8233 guint32 special_static_type;
8235 if (command == CMD_TYPE_GET_VALUES_2) {
8236 int objid = decode_objid (p, &p, end);
8238 err = get_object (objid, (MonoObject**)&thread_obj);
8239 if (err != ERR_NONE)
8240 goto exit;
8242 thread = THREAD_TO_INTERNAL (thread_obj);
8245 len = decode_int (p, &p, end);
8246 for (i = 0; i < len; ++i) {
8247 f = decode_fieldid (p, &p, end, NULL, &err);
8248 if (err != ERR_NONE)
8249 goto exit;
8251 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8252 goto invalid_fieldid;
8254 special_static_type = mono_class_field_get_special_static_type (f);
8255 if (special_static_type != SPECIAL_STATIC_NONE) {
8256 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
8257 goto invalid_fieldid;
8260 /* Check that the field belongs to the object */
8261 found = FALSE;
8262 for (k = klass; k; k = m_class_get_parent (k)) {
8263 if (k == f->parent) {
8264 found = TRUE;
8265 break;
8268 if (!found)
8269 goto invalid_fieldid;
8271 vtable = mono_class_vtable_checked (domain, f->parent, error);
8272 goto_if_nok (error, invalid_fieldid);
8274 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type_internal (f->type)));
8275 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val, string_handle, error);
8276 goto_if_nok (error, invalid_fieldid);
8278 buffer_add_value (buf, f->type, val, domain);
8279 g_free (val);
8281 break;
8283 case CMD_TYPE_SET_VALUES: {
8284 guint8 *val;
8285 MonoClassField *f;
8286 MonoVTable *vtable;
8287 MonoClass *k;
8288 int len, i;
8289 gboolean found;
8291 len = decode_int (p, &p, end);
8292 for (i = 0; i < len; ++i) {
8293 f = decode_fieldid (p, &p, end, NULL, &err);
8294 if (err != ERR_NONE)
8295 goto exit;
8297 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8298 goto invalid_fieldid;
8300 if (mono_class_field_is_special_static (f))
8301 goto invalid_fieldid;
8303 /* Check that the field belongs to the object */
8304 found = FALSE;
8305 for (k = klass; k; k = m_class_get_parent (k)) {
8306 if (k == f->parent) {
8307 found = TRUE;
8308 break;
8311 if (!found)
8312 goto invalid_fieldid;
8314 // FIXME: Check for literal/const
8316 vtable = mono_class_vtable_checked (domain, f->parent, error);
8317 goto_if_nok (error, invalid_fieldid);
8319 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type_internal (f->type)));
8320 err = decode_value (f->type, domain, val, p, &p, end, TRUE);
8321 if (err != ERR_NONE) {
8322 g_free (val);
8323 goto exit;
8325 if (MONO_TYPE_IS_REFERENCE (f->type))
8326 mono_field_static_set_value_internal (vtable, f, *(gpointer*)val);
8327 else
8328 mono_field_static_set_value_internal (vtable, f, val);
8329 g_free (val);
8331 break;
8333 case CMD_TYPE_GET_OBJECT: {
8334 MonoObject *o = (MonoObject*)mono_type_get_object_checked (domain, m_class_get_byval_arg (klass), error);
8335 if (!is_ok (error)) {
8336 mono_error_cleanup (error);
8337 goto invalid_object;
8339 buffer_add_objid (buf, o);
8340 break;
8342 case CMD_TYPE_GET_SOURCE_FILES:
8343 case CMD_TYPE_GET_SOURCE_FILES_2: {
8344 char *source_file, *base;
8345 GPtrArray *files;
8346 int i;
8348 files = get_source_files_for_type (klass);
8350 buffer_add_int (buf, files->len);
8351 for (i = 0; i < files->len; ++i) {
8352 source_file = (char *)g_ptr_array_index (files, i);
8353 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8354 buffer_add_string (buf, source_file);
8355 } else {
8356 base = dbg_path_get_basename (source_file);
8357 buffer_add_string (buf, base);
8358 g_free (base);
8360 g_free (source_file);
8362 g_ptr_array_free (files, TRUE);
8363 break;
8365 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8366 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8368 if (err != ERR_NONE)
8369 goto exit;
8370 if (mono_class_is_assignable_from_internal (klass, oklass))
8371 buffer_add_byte (buf, 1);
8372 else
8373 buffer_add_byte (buf, 0);
8374 break;
8376 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8377 char *name = decode_string (p, &p, end);
8378 int i, flags = decode_int (p, &p, end);
8379 int mlisttype;
8380 if (CHECK_PROTOCOL_VERSION (2, 48))
8381 mlisttype = decode_int (p, &p, end);
8382 else
8383 mlisttype = 0; // MLISTTYPE_All
8384 ERROR_DECL (error);
8385 GPtrArray *array;
8387 error_init (error);
8388 array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, mlisttype, TRUE, error);
8389 if (!is_ok (error)) {
8390 mono_error_cleanup (error);
8391 goto loader_error;
8393 buffer_add_int (buf, array->len);
8394 for (i = 0; i < array->len; ++i) {
8395 MonoMethod *method = (MonoMethod *)g_ptr_array_index (array, i);
8396 buffer_add_methodid (buf, domain, method);
8399 g_ptr_array_free (array, TRUE);
8400 g_free (name);
8401 break;
8403 case CMD_TYPE_GET_INTERFACES: {
8404 MonoClass *parent;
8405 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8406 MonoClass *tclass, *iface;
8407 GHashTableIter iter;
8409 tclass = klass;
8411 for (parent = tclass; parent; parent = m_class_get_parent (parent)) {
8412 mono_class_setup_interfaces (parent, error);
8413 goto_if_nok (error, loader_error);
8415 collect_interfaces (parent, iface_hash, error);
8416 goto_if_nok (error, loader_error);
8419 buffer_add_int (buf, g_hash_table_size (iface_hash));
8421 g_hash_table_iter_init (&iter, iface_hash);
8422 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8423 buffer_add_typeid (buf, domain, iface);
8424 g_hash_table_destroy (iface_hash);
8425 break;
8427 case CMD_TYPE_GET_INTERFACE_MAP: {
8428 int tindex, ioffset;
8429 gboolean variance_used;
8430 MonoClass *iclass;
8431 int len, nmethods, i;
8432 gpointer iter;
8433 MonoMethod *method;
8435 len = decode_int (p, &p, end);
8436 mono_class_setup_vtable (klass);
8438 for (tindex = 0; tindex < len; ++tindex) {
8439 iclass = decode_typeid (p, &p, end, NULL, &err);
8440 if (err != ERR_NONE)
8441 goto exit;
8443 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8444 if (ioffset == -1)
8445 goto invalid_argument;
8447 nmethods = mono_class_num_methods (iclass);
8448 buffer_add_int (buf, nmethods);
8450 iter = NULL;
8451 while ((method = mono_class_get_methods (iclass, &iter))) {
8452 buffer_add_methodid (buf, domain, method);
8454 MonoMethod **klass_vtable = m_class_get_vtable (klass);
8455 for (i = 0; i < nmethods; ++i)
8456 buffer_add_methodid (buf, domain, klass_vtable [i + ioffset]);
8458 break;
8460 case CMD_TYPE_IS_INITIALIZED: {
8461 MonoVTable *vtable = mono_class_vtable_checked (domain, klass, error);
8462 goto_if_nok (error, loader_error);
8464 if (vtable)
8465 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8466 else
8467 buffer_add_int (buf, 0);
8468 break;
8470 case CMD_TYPE_CREATE_INSTANCE: {
8471 ERROR_DECL (error);
8472 MonoObject *obj;
8474 obj = mono_object_new_checked (domain, klass, error);
8475 mono_error_assert_ok (error);
8476 buffer_add_objid (buf, obj);
8477 break;
8479 case CMD_TYPE_GET_VALUE_SIZE: {
8480 int32_t value_size;
8482 value_size = mono_class_value_size (klass, NULL);
8483 buffer_add_int (buf, value_size);
8484 break;
8486 default:
8487 err = ERR_NOT_IMPLEMENTED;
8488 goto exit;
8491 err = ERR_NONE;
8492 goto exit;
8493 invalid_argument:
8494 err = ERR_INVALID_ARGUMENT;
8495 goto exit;
8496 invalid_fieldid:
8497 err = ERR_INVALID_FIELDID;
8498 goto exit;
8499 invalid_object:
8500 err = ERR_INVALID_OBJECT;
8501 goto exit;
8502 loader_error:
8503 err = ERR_LOADER_ERROR;
8504 goto exit;
8505 exit:
8506 HANDLE_FUNCTION_RETURN_VAL (err);
8509 static ErrorCode
8510 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8512 MonoClass *klass;
8513 MonoDomain *old_domain;
8514 MonoDomain *domain;
8515 ErrorCode err;
8517 klass = decode_typeid (p, &p, end, &domain, &err);
8518 if (err != ERR_NONE)
8519 return err;
8521 old_domain = mono_domain_get ();
8523 mono_domain_set_fast (domain, TRUE);
8525 err = type_commands_internal (command, klass, domain, p, end, buf);
8527 mono_domain_set_fast (old_domain, TRUE);
8529 return err;
8532 static ErrorCode
8533 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8535 MonoMethodHeader *header;
8536 ErrorCode err;
8538 switch (command) {
8539 case CMD_METHOD_GET_NAME: {
8540 buffer_add_string (buf, method->name);
8541 break;
8543 case CMD_METHOD_GET_DECLARING_TYPE: {
8544 buffer_add_typeid (buf, domain, method->klass);
8545 break;
8547 case CMD_METHOD_GET_DEBUG_INFO: {
8548 ERROR_DECL (error);
8549 MonoDebugMethodInfo *minfo;
8550 char *source_file;
8551 int i, j, n_il_offsets;
8552 int *source_files;
8553 GPtrArray *source_file_list;
8554 MonoSymSeqPoint *sym_seq_points;
8556 header = mono_method_get_header_checked (method, error);
8557 if (!header) {
8558 mono_error_cleanup (error); /* FIXME don't swallow the error */
8559 buffer_add_int (buf, 0);
8560 buffer_add_string (buf, "");
8561 buffer_add_int (buf, 0);
8562 break;
8565 minfo = mono_debug_lookup_method (method);
8566 if (!minfo) {
8567 buffer_add_int (buf, header->code_size);
8568 buffer_add_string (buf, "");
8569 buffer_add_int (buf, 0);
8570 mono_metadata_free_mh (header);
8571 break;
8574 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, &source_files, &sym_seq_points, &n_il_offsets);
8575 buffer_add_int (buf, header->code_size);
8576 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8577 buffer_add_int (buf, source_file_list->len);
8578 for (i = 0; i < source_file_list->len; ++i) {
8579 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
8580 buffer_add_string (buf, sinfo->source_file);
8581 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8582 for (j = 0; j < 16; ++j)
8583 buffer_add_byte (buf, sinfo->hash [j]);
8586 } else {
8587 buffer_add_string (buf, source_file);
8589 buffer_add_int (buf, n_il_offsets);
8590 PRINT_DEBUG_MSG (10, "Line number table for method %s:\n", mono_method_full_name (method, TRUE));
8591 for (i = 0; i < n_il_offsets; ++i) {
8592 MonoSymSeqPoint *sp = &sym_seq_points [i];
8593 const char *srcfile = "";
8595 if (source_files [i] != -1) {
8596 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, source_files [i]);
8597 srcfile = sinfo->source_file;
8599 PRINT_DEBUG_MSG (10, "IL%x -> %s:%d %d %d %d\n", sp->il_offset, srcfile, sp->line, sp->column, sp->end_line, sp->end_column);
8600 buffer_add_int (buf, sp->il_offset);
8601 buffer_add_int (buf, sp->line);
8602 if (CHECK_PROTOCOL_VERSION (2, 13))
8603 buffer_add_int (buf, source_files [i]);
8604 if (CHECK_PROTOCOL_VERSION (2, 19))
8605 buffer_add_int (buf, sp->column);
8606 if (CHECK_PROTOCOL_VERSION (2, 32)) {
8607 buffer_add_int (buf, sp->end_line);
8608 buffer_add_int (buf, sp->end_column);
8611 g_free (source_file);
8612 g_free (source_files);
8613 g_free (sym_seq_points);
8614 g_ptr_array_free (source_file_list, TRUE);
8615 mono_metadata_free_mh (header);
8616 break;
8618 case CMD_METHOD_GET_PARAM_INFO: {
8619 MonoMethodSignature *sig = mono_method_signature_internal (method);
8620 guint32 i;
8621 char **names;
8623 /* FIXME: mono_class_from_mono_type_internal () and byrefs */
8625 /* FIXME: Use a smaller encoding */
8626 buffer_add_int (buf, sig->call_convention);
8627 buffer_add_int (buf, sig->param_count);
8628 buffer_add_int (buf, sig->generic_param_count);
8629 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (sig->ret));
8630 for (i = 0; i < sig->param_count; ++i) {
8631 /* FIXME: vararg */
8632 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (sig->params [i]));
8635 /* Emit parameter names */
8636 names = g_new (char *, sig->param_count);
8637 mono_method_get_param_names (method, (const char **) names);
8638 for (i = 0; i < sig->param_count; ++i)
8639 buffer_add_string (buf, names [i]);
8640 g_free (names);
8642 break;
8644 case CMD_METHOD_GET_LOCALS_INFO: {
8645 ERROR_DECL (error);
8646 int i, num_locals;
8647 MonoDebugLocalsInfo *locals;
8648 int *locals_map = NULL;
8650 header = mono_method_get_header_checked (method, error);
8651 if (!header) {
8652 add_error_string (buf, mono_error_get_message (error));
8653 mono_error_cleanup (error); /* FIXME don't swallow the error */
8654 return ERR_INVALID_ARGUMENT;
8657 locals = mono_debug_lookup_locals (method);
8658 if (!locals) {
8659 if (CHECK_PROTOCOL_VERSION (2, 43)) {
8660 /* Scopes */
8661 buffer_add_int (buf, 1);
8662 buffer_add_int (buf, 0);
8663 buffer_add_int (buf, header->code_size);
8665 buffer_add_int (buf, header->num_locals);
8666 /* Types */
8667 for (i = 0; i < header->num_locals; ++i) {
8668 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (header->locals [i]));
8670 /* Names */
8671 for (i = 0; i < header->num_locals; ++i) {
8672 char lname [128];
8673 sprintf (lname, "V_%d", i);
8674 buffer_add_string (buf, lname);
8676 /* Scopes */
8677 for (i = 0; i < header->num_locals; ++i) {
8678 buffer_add_int (buf, 0);
8679 buffer_add_int (buf, header->code_size);
8681 } else {
8682 if (CHECK_PROTOCOL_VERSION (2, 43)) {
8683 /* Scopes */
8684 buffer_add_int (buf, locals->num_blocks);
8685 int last_start = 0;
8686 for (i = 0; i < locals->num_blocks; ++i) {
8687 buffer_add_int (buf, locals->code_blocks [i].start_offset - last_start);
8688 buffer_add_int (buf, locals->code_blocks [i].end_offset - locals->code_blocks [i].start_offset);
8689 last_start = locals->code_blocks [i].start_offset;
8693 num_locals = locals->num_locals;
8694 buffer_add_int (buf, num_locals);
8696 /* Types */
8697 for (i = 0; i < num_locals; ++i) {
8698 g_assert (locals->locals [i].index < header->num_locals);
8699 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (header->locals [locals->locals [i].index]));
8701 /* Names */
8702 for (i = 0; i < num_locals; ++i)
8703 buffer_add_string (buf, locals->locals [i].name);
8704 /* Scopes */
8705 for (i = 0; i < num_locals; ++i) {
8706 if (locals->locals [i].block) {
8707 buffer_add_int (buf, locals->locals [i].block->start_offset);
8708 buffer_add_int (buf, locals->locals [i].block->end_offset);
8709 } else {
8710 buffer_add_int (buf, 0);
8711 buffer_add_int (buf, header->code_size);
8715 mono_metadata_free_mh (header);
8717 if (locals)
8718 mono_debug_free_locals (locals);
8719 g_free (locals_map);
8721 break;
8723 case CMD_METHOD_GET_INFO:
8724 buffer_add_int (buf, method->flags);
8725 buffer_add_int (buf, method->iflags);
8726 buffer_add_int (buf, method->token);
8727 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8728 guint8 attrs = 0;
8729 if (method->is_generic)
8730 attrs |= (1 << 0);
8731 if (mono_method_signature_internal (method)->generic_param_count)
8732 attrs |= (1 << 1);
8733 buffer_add_byte (buf, attrs);
8734 if (method->is_generic || method->is_inflated) {
8735 MonoMethod *result;
8737 if (method->is_generic) {
8738 result = method;
8739 } else {
8740 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8742 result = imethod->declaring;
8743 if (imethod->context.class_inst) {
8744 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8745 /*Generic methods gets the context of the GTD.*/
8746 if (mono_class_get_context (klass)) {
8747 ERROR_DECL (error);
8748 result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), error);
8749 if (!is_ok (error)) {
8750 add_error_string (buf, mono_error_get_message (error));
8751 mono_error_cleanup (error);
8752 return ERR_INVALID_ARGUMENT;
8758 buffer_add_methodid (buf, domain, result);
8759 } else {
8760 buffer_add_id (buf, 0);
8762 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8763 if (mono_method_signature_internal (method)->generic_param_count) {
8764 int count, i;
8766 if (method->is_inflated) {
8767 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
8768 if (inst) {
8769 count = inst->type_argc;
8770 buffer_add_int (buf, count);
8772 for (i = 0; i < count; i++)
8773 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (inst->type_argv [i]));
8774 } else {
8775 buffer_add_int (buf, 0);
8777 } else if (method->is_generic) {
8778 MonoGenericContainer *container = mono_method_get_generic_container (method);
8780 count = mono_method_signature_internal (method)->generic_param_count;
8781 buffer_add_int (buf, count);
8782 for (i = 0; i < count; i++) {
8783 MonoGenericParam *param = mono_generic_container_get_param (container, i);
8784 MonoClass *pklass = mono_class_create_generic_parameter (param);
8785 buffer_add_typeid (buf, domain, pklass);
8787 } else {
8788 buffer_add_int (buf, 0);
8790 } else {
8791 buffer_add_int (buf, 0);
8795 break;
8796 case CMD_METHOD_GET_BODY: {
8797 ERROR_DECL (error);
8798 int i;
8800 header = mono_method_get_header_checked (method, error);
8801 if (!header) {
8802 mono_error_cleanup (error); /* FIXME don't swallow the error */
8803 buffer_add_int (buf, 0);
8805 if (CHECK_PROTOCOL_VERSION (2, 18))
8806 buffer_add_int (buf, 0);
8807 } else {
8808 buffer_add_int (buf, header->code_size);
8809 for (i = 0; i < header->code_size; ++i)
8810 buffer_add_byte (buf, header->code [i]);
8812 if (CHECK_PROTOCOL_VERSION (2, 18)) {
8813 buffer_add_int (buf, header->num_clauses);
8814 for (i = 0; i < header->num_clauses; ++i) {
8815 MonoExceptionClause *clause = &header->clauses [i];
8817 buffer_add_int (buf, clause->flags);
8818 buffer_add_int (buf, clause->try_offset);
8819 buffer_add_int (buf, clause->try_len);
8820 buffer_add_int (buf, clause->handler_offset);
8821 buffer_add_int (buf, clause->handler_len);
8822 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
8823 buffer_add_typeid (buf, domain, clause->data.catch_class);
8824 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8825 buffer_add_int (buf, clause->data.filter_offset);
8829 mono_metadata_free_mh (header);
8832 break;
8834 case CMD_METHOD_RESOLVE_TOKEN: {
8835 guint32 token = decode_int (p, &p, end);
8837 // FIXME: Generics
8838 switch (mono_metadata_token_code (token)) {
8839 case MONO_TOKEN_STRING: {
8840 ERROR_DECL (error);
8841 MonoString *s;
8842 char *s2;
8844 s = mono_ldstr_checked (domain, m_class_get_image (method->klass), mono_metadata_token_index (token), error);
8845 mono_error_assert_ok (error); /* FIXME don't swallow the error */
8847 s2 = mono_string_to_utf8_checked_internal (s, error);
8848 mono_error_assert_ok (error);
8850 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8851 buffer_add_string (buf, s2);
8852 g_free (s2);
8853 break;
8855 default: {
8856 ERROR_DECL (error);
8857 gpointer val;
8858 MonoClass *handle_class;
8860 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8861 val = mono_method_get_wrapper_data (method, token);
8862 handle_class = (MonoClass *)mono_method_get_wrapper_data (method, token + 1);
8864 if (handle_class == NULL) {
8865 // Can't figure out the token type
8866 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8867 break;
8869 } else {
8870 val = mono_ldtoken_checked (m_class_get_image (method->klass), token, &handle_class, NULL, error);
8871 if (!val)
8872 g_error ("Could not load token due to %s", mono_error_get_message (error));
8875 if (handle_class == mono_defaults.typehandle_class) {
8876 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8877 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8878 buffer_add_typeid (buf, domain, (MonoClass *) val);
8879 else
8880 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal ((MonoType*)val));
8881 } else if (handle_class == mono_defaults.fieldhandle_class) {
8882 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8883 buffer_add_fieldid (buf, domain, (MonoClassField *)val);
8884 } else if (handle_class == mono_defaults.methodhandle_class) {
8885 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8886 buffer_add_methodid (buf, domain, (MonoMethod *)val);
8887 } else if (handle_class == mono_defaults.string_class) {
8888 char *s;
8890 s = mono_string_to_utf8_checked_internal ((MonoString *)val, error);
8891 if (!is_ok (error)) {
8892 add_error_string (buf, mono_error_get_message (error));
8893 mono_error_cleanup (error);
8894 g_free (s);
8895 return ERR_INVALID_ARGUMENT;
8897 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8898 buffer_add_string (buf, s);
8899 g_free (s);
8900 } else {
8901 g_assert_not_reached ();
8903 break;
8906 break;
8908 case CMD_METHOD_GET_CATTRS: {
8909 ERROR_DECL (error);
8910 MonoClass *attr_klass;
8911 MonoCustomAttrInfo *cinfo;
8913 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8914 /* attr_klass can be NULL */
8915 if (err != ERR_NONE)
8916 return err;
8918 cinfo = mono_custom_attrs_from_method_checked (method, error);
8919 if (!is_ok (error)) {
8920 mono_error_cleanup (error); /* FIXME don't swallow the error message */
8921 return ERR_LOADER_ERROR;
8924 err = buffer_add_cattrs (buf, domain, m_class_get_image (method->klass), attr_klass, cinfo);
8925 if (err != ERR_NONE)
8926 return err;
8927 break;
8929 case CMD_METHOD_MAKE_GENERIC_METHOD: {
8930 ERROR_DECL (error);
8931 MonoType **type_argv;
8932 int i, type_argc;
8933 MonoDomain *d;
8934 MonoClass *klass;
8935 MonoGenericInst *ginst;
8936 MonoGenericContext tmp_context;
8937 MonoMethod *inflated;
8939 type_argc = decode_int (p, &p, end);
8940 type_argv = g_new0 (MonoType*, type_argc);
8941 for (i = 0; i < type_argc; ++i) {
8942 klass = decode_typeid (p, &p, end, &d, &err);
8943 if (err != ERR_NONE) {
8944 g_free (type_argv);
8945 return err;
8947 if (domain != d) {
8948 g_free (type_argv);
8949 return ERR_INVALID_ARGUMENT;
8951 type_argv [i] = m_class_get_byval_arg (klass);
8953 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
8954 g_free (type_argv);
8955 tmp_context.class_inst = mono_class_is_ginst (method->klass) ? mono_class_get_generic_class (method->klass)->context.class_inst : NULL;
8956 tmp_context.method_inst = ginst;
8958 inflated = mono_class_inflate_generic_method_checked (method, &tmp_context, error);
8959 if (!is_ok (error)) {
8960 add_error_string (buf, mono_error_get_message (error));
8961 mono_error_cleanup (error);
8962 return ERR_INVALID_ARGUMENT;
8964 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
8965 return ERR_INVALID_ARGUMENT;
8966 buffer_add_methodid (buf, domain, inflated);
8967 break;
8969 default:
8970 return ERR_NOT_IMPLEMENTED;
8973 return ERR_NONE;
8976 static ErrorCode
8977 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8979 ErrorCode err;
8980 MonoDomain *old_domain;
8981 MonoDomain *domain;
8982 MonoMethod *method;
8984 method = decode_methodid (p, &p, end, &domain, &err);
8985 if (err != ERR_NONE)
8986 return err;
8988 old_domain = mono_domain_get ();
8990 mono_domain_set_fast (domain, TRUE);
8992 err = method_commands_internal (command, method, domain, p, end, buf);
8994 mono_domain_set_fast (old_domain, TRUE);
8996 return err;
8999 static ErrorCode
9000 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9002 int objid = decode_objid (p, &p, end);
9003 ErrorCode err;
9004 MonoThread *thread_obj;
9005 MonoInternalThread *thread;
9007 err = get_object (objid, (MonoObject**)&thread_obj);
9008 if (err != ERR_NONE)
9009 return err;
9011 thread = THREAD_TO_INTERNAL (thread_obj);
9013 switch (command) {
9014 case CMD_THREAD_GET_NAME: {
9015 char *s = mono_thread_get_name_utf8 (thread_obj);
9017 if (!s) {
9018 buffer_add_int (buf, 0);
9019 } else {
9020 const size_t len = strlen (s);
9021 buffer_add_int (buf, len);
9022 buffer_add_data (buf, (guint8*)s, len);
9023 g_free (s);
9025 break;
9027 case CMD_THREAD_GET_FRAME_INFO: {
9028 DebuggerTlsData *tls;
9029 int i, start_frame, length;
9031 // Wait for suspending if it already started
9032 // FIXME: Races with suspend_count
9033 while (!is_suspended ()) {
9034 if (suspend_count)
9035 wait_for_suspend ();
9038 if (suspend_count)
9039 wait_for_suspend ();
9040 if (!is_suspended ())
9041 return ERR_NOT_SUSPENDED;
9044 start_frame = decode_int (p, &p, end);
9045 length = decode_int (p, &p, end);
9047 if (start_frame != 0 || length != -1)
9048 return ERR_NOT_IMPLEMENTED;
9050 mono_loader_lock ();
9051 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9052 mono_loader_unlock ();
9053 if (tls == NULL)
9054 return ERR_UNLOADED;
9056 compute_frame_info (thread, tls, TRUE); //the last parameter is TRUE to force that the frame info that will be send is synchronised with the debugged thread
9058 buffer_add_int (buf, tls->frame_count);
9059 for (i = 0; i < tls->frame_count; ++i) {
9060 buffer_add_int (buf, tls->frames [i]->id);
9061 buffer_add_methodid (buf, tls->frames [i]->de.domain, tls->frames [i]->actual_method);
9062 buffer_add_int (buf, tls->frames [i]->il_offset);
9064 * Instead of passing the frame type directly to the client, we associate
9065 * it with the previous frame using a set of flags. This avoids lots of
9066 * conditional code in the client, since a frame whose type isn't
9067 * FRAME_TYPE_MANAGED has no method, location, etc.
9069 buffer_add_byte (buf, tls->frames [i]->flags);
9072 break;
9074 case CMD_THREAD_GET_STATE:
9075 buffer_add_int (buf, thread->state);
9076 break;
9077 case CMD_THREAD_GET_INFO:
9078 buffer_add_byte (buf, thread->threadpool_thread);
9079 break;
9080 case CMD_THREAD_GET_ID:
9081 buffer_add_long (buf, (guint64)(gsize)thread);
9082 break;
9083 case CMD_THREAD_GET_TID:
9084 buffer_add_long (buf, (guint64)thread->tid);
9085 break;
9086 case CMD_THREAD_SET_IP: {
9087 DebuggerTlsData *tls;
9088 MonoMethod *method;
9089 MonoDomain *domain;
9090 MonoSeqPointInfo *seq_points;
9091 SeqPoint sp;
9092 gboolean found_sp;
9093 gint64 il_offset;
9095 method = decode_methodid (p, &p, end, &domain, &err);
9096 if (err != ERR_NONE)
9097 return err;
9098 il_offset = decode_long (p, &p, end);
9100 while (!is_suspended ()) {
9101 if (suspend_count)
9102 wait_for_suspend ();
9105 mono_loader_lock ();
9106 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9107 mono_loader_unlock ();
9108 g_assert (tls);
9110 compute_frame_info (thread, tls, FALSE);
9111 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
9112 return ERR_INVALID_ARGUMENT;
9114 found_sp = mono_find_seq_point (domain, method, il_offset, &seq_points, &sp);
9116 g_assert (seq_points);
9118 if (!found_sp)
9119 return ERR_INVALID_ARGUMENT;
9121 // FIXME: Check that the ip change is safe
9123 PRINT_DEBUG_MSG (1, "[dbg] Setting IP to %s:0x%0x(0x%0x)\n", tls->frames [0]->actual_method->name, (int)sp.il_offset, (int)sp.native_offset);
9125 if (tls->frames [0]->de.ji->is_interp) {
9126 MonoJitTlsData *jit_data = thread->thread_info->jit_data;
9127 mini_get_interp_callbacks ()->set_resume_state (jit_data, NULL, NULL, tls->frames [0]->interp_frame, (guint8*)tls->frames [0]->de.ji->code_start + sp.native_offset);
9128 } else {
9129 MONO_CONTEXT_SET_IP (&tls->restore_state.ctx, (guint8*)tls->frames [0]->de.ji->code_start + sp.native_offset);
9131 break;
9133 case CMD_THREAD_ELAPSED_TIME: {
9134 DebuggerTlsData *tls;
9135 mono_loader_lock ();
9136 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9137 mono_loader_unlock ();
9138 g_assert (tls);
9139 buffer_add_long (buf, (long)mono_stopwatch_elapsed_ms (&tls->step_time));
9140 break;
9142 default:
9143 return ERR_NOT_IMPLEMENTED;
9146 return ERR_NONE;
9149 static ErrorCode
9150 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9152 int objid;
9153 ErrorCode err;
9154 MonoThread *thread_obj;
9155 MonoInternalThread *thread;
9156 int pos, i, len, frame_idx;
9157 DebuggerTlsData *tls;
9158 StackFrame *frame;
9159 MonoDebugMethodJitInfo *jit;
9160 MonoMethodSignature *sig;
9161 gssize id;
9162 MonoMethodHeader *header;
9164 objid = decode_objid (p, &p, end);
9165 err = get_object (objid, (MonoObject**)&thread_obj);
9166 if (err != ERR_NONE)
9167 return err;
9169 thread = THREAD_TO_INTERNAL (thread_obj);
9171 id = decode_id (p, &p, end);
9173 mono_loader_lock ();
9174 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9175 mono_loader_unlock ();
9176 g_assert (tls);
9178 for (i = 0; i < tls->frame_count; ++i) {
9179 if (tls->frames [i]->id == id)
9180 break;
9182 if (i == tls->frame_count)
9183 return ERR_INVALID_FRAMEID;
9185 /* The thread is still running native code, can't get frame variables info */
9186 if (!tls->really_suspended && !tls->async_state.valid)
9187 return ERR_NOT_SUSPENDED;
9188 frame_idx = i;
9189 frame = tls->frames [frame_idx];
9191 /* This is supported for frames without has_ctx etc. set */
9192 if (command == CMD_STACK_FRAME_GET_DOMAIN) {
9193 if (CHECK_PROTOCOL_VERSION (2, 38))
9194 buffer_add_domainid (buf, frame->de.domain);
9195 return ERR_NONE;
9198 if (!frame->has_ctx)
9199 return ERR_ABSENT_INFORMATION;
9201 if (!ensure_jit ((DbgEngineStackFrame*)frame))
9202 return ERR_ABSENT_INFORMATION;
9204 jit = frame->jit;
9206 sig = mono_method_signature_internal (frame->actual_method);
9208 if (!(jit->has_var_info || frame->de.ji->is_interp) || !mono_get_seq_points (frame->de.domain, frame->actual_method))
9210 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
9212 return ERR_ABSENT_INFORMATION;
9214 switch (command) {
9215 case CMD_STACK_FRAME_GET_VALUES: {
9216 ERROR_DECL (error);
9217 len = decode_int (p, &p, end);
9218 header = mono_method_get_header_checked (frame->actual_method, error);
9219 mono_error_assert_ok (error); /* FIXME report error */
9221 for (i = 0; i < len; ++i) {
9222 pos = decode_int (p, &p, end);
9224 if (pos < 0) {
9225 pos = - pos - 1;
9227 PRINT_DEBUG_MSG (4, "[dbg] send arg %d.\n", pos);
9229 if (frame->de.ji->is_interp) {
9230 guint8 *addr;
9232 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_arg (frame->interp_frame, pos);
9234 buffer_add_value_full (buf, sig->params [pos], addr, frame->de.domain, FALSE, NULL, 1);
9235 } else {
9236 g_assert (pos >= 0 && pos < jit->num_params);
9238 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->de.domain, FALSE);
9240 } else {
9241 MonoDebugLocalsInfo *locals;
9243 locals = mono_debug_lookup_locals (frame->de.method);
9244 if (locals) {
9245 g_assert (pos < locals->num_locals);
9246 pos = locals->locals [pos].index;
9247 mono_debug_free_locals (locals);
9250 PRINT_DEBUG_MSG (4, "[dbg] send local %d.\n", pos);
9252 if (frame->de.ji->is_interp) {
9253 guint8 *addr;
9255 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_local (frame->interp_frame, pos);
9257 buffer_add_value_full (buf, header->locals [pos], addr, frame->de.domain, FALSE, NULL, 1);
9258 } else {
9259 g_assert (pos >= 0 && pos < jit->num_locals);
9261 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->de.domain, FALSE);
9265 mono_metadata_free_mh (header);
9266 break;
9268 case CMD_STACK_FRAME_GET_THIS: {
9269 if (frame->de.method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE)
9270 return ERR_ABSENT_INFORMATION;
9271 if (m_class_is_valuetype (frame->api_method->klass)) {
9272 if (!sig->hasthis) {
9273 MonoObject *p = NULL;
9274 buffer_add_value (buf, mono_get_object_type (), &p, frame->de.domain);
9275 } else {
9276 if (frame->de.ji->is_interp) {
9277 guint8 *addr;
9279 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_this (frame->interp_frame);
9281 buffer_add_value_full (buf, m_class_get_this_arg (frame->actual_method->klass), addr, frame->de.domain, FALSE, NULL, 1);
9282 } else {
9283 add_var (buf, jit, m_class_get_this_arg (frame->actual_method->klass), jit->this_var, &frame->ctx, frame->de.domain, TRUE);
9286 } else {
9287 if (!sig->hasthis) {
9288 MonoObject *p = NULL;
9289 buffer_add_value (buf, m_class_get_byval_arg (frame->actual_method->klass), &p, frame->de.domain);
9290 } else {
9291 if (frame->de.ji->is_interp) {
9292 guint8 *addr;
9294 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_this (frame->interp_frame);
9296 buffer_add_value_full (buf, m_class_get_byval_arg (frame->api_method->klass), addr, frame->de.domain, FALSE, NULL, 1);
9297 } else {
9298 add_var (buf, jit, m_class_get_byval_arg (frame->api_method->klass), jit->this_var, &frame->ctx, frame->de.domain, TRUE);
9302 break;
9304 case CMD_STACK_FRAME_SET_VALUES: {
9305 ERROR_DECL (error);
9306 guint8 *val_buf;
9307 MonoType *t;
9308 MonoDebugVarInfo *var = NULL;
9309 gboolean is_arg = FALSE;
9311 len = decode_int (p, &p, end);
9312 header = mono_method_get_header_checked (frame->actual_method, error);
9313 mono_error_assert_ok (error); /* FIXME report error */
9315 for (i = 0; i < len; ++i) {
9316 pos = decode_int (p, &p, end);
9318 if (pos < 0) {
9319 pos = - pos - 1;
9321 g_assert (pos >= 0 && pos < jit->num_params);
9323 t = sig->params [pos];
9324 var = &jit->params [pos];
9325 is_arg = TRUE;
9326 } else {
9327 MonoDebugLocalsInfo *locals;
9329 locals = mono_debug_lookup_locals (frame->de.method);
9330 if (locals) {
9331 g_assert (pos < locals->num_locals);
9332 pos = locals->locals [pos].index;
9333 mono_debug_free_locals (locals);
9335 g_assert (pos >= 0 && pos < jit->num_locals);
9337 t = header->locals [pos];
9338 var = &jit->locals [pos];
9341 if (MONO_TYPE_IS_REFERENCE (t))
9342 val_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
9343 else
9344 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type_internal (t)));
9345 err = decode_value (t, frame->de.domain, val_buf, p, &p, end, TRUE);
9346 if (err != ERR_NONE)
9347 return err;
9349 if (frame->de.ji->is_interp) {
9350 guint8 *addr;
9352 if (is_arg)
9353 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_arg (frame->interp_frame, pos);
9354 else
9355 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_local (frame->interp_frame, pos);
9356 set_interp_var (t, addr, val_buf);
9357 } else {
9358 set_var (t, var, &frame->ctx, frame->de.domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9361 mono_metadata_free_mh (header);
9362 break;
9364 case CMD_STACK_FRAME_GET_DOMAIN: {
9365 if (CHECK_PROTOCOL_VERSION (2, 38))
9366 buffer_add_domainid (buf, frame->de.domain);
9367 break;
9369 case CMD_STACK_FRAME_SET_THIS: {
9370 guint8 *val_buf;
9371 MonoType *t;
9372 MonoDebugVarInfo *var;
9374 t = m_class_get_byval_arg (frame->actual_method->klass);
9375 /* Checked by the sender */
9376 g_assert (MONO_TYPE_ISSTRUCT (t));
9378 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type_internal (t)));
9379 err = decode_value (t, frame->de.domain, val_buf, p, &p, end, TRUE);
9380 if (err != ERR_NONE)
9381 return err;
9383 if (frame->de.ji->is_interp) {
9384 guint8 *addr;
9386 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_this (frame->interp_frame);
9387 set_interp_var (m_class_get_this_arg (frame->actual_method->klass), addr, val_buf);
9388 } else {
9389 var = jit->this_var;
9390 if (!var) {
9391 add_error_string (buf, "Invalid this object");
9392 return ERR_INVALID_ARGUMENT;
9395 set_var (m_class_get_this_arg (frame->actual_method->klass), var, &frame->ctx, frame->de.domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9397 break;
9399 default:
9400 return ERR_NOT_IMPLEMENTED;
9403 return ERR_NONE;
9406 static ErrorCode
9407 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9409 MonoArray *arr;
9410 int objid, index, len, i, esize;
9411 ErrorCode err;
9412 gpointer elem;
9414 objid = decode_objid (p, &p, end);
9415 err = get_object (objid, (MonoObject**)&arr);
9416 if (err != ERR_NONE)
9417 return err;
9419 switch (command) {
9420 case CMD_ARRAY_REF_GET_LENGTH:
9421 buffer_add_int (buf, m_class_get_rank (arr->obj.vtable->klass));
9422 if (!arr->bounds) {
9423 buffer_add_int (buf, arr->max_length);
9424 buffer_add_int (buf, 0);
9425 } else {
9426 for (i = 0; i < m_class_get_rank (arr->obj.vtable->klass); ++i) {
9427 buffer_add_int (buf, arr->bounds [i].length);
9428 buffer_add_int (buf, arr->bounds [i].lower_bound);
9431 break;
9432 case CMD_ARRAY_REF_GET_VALUES:
9433 index = decode_int (p, &p, end);
9434 len = decode_int (p, &p, end);
9436 if (index < 0 || len < 0)
9437 return ERR_INVALID_ARGUMENT;
9438 // Reordered to avoid integer overflow
9439 if (index > arr->max_length - len)
9440 return ERR_INVALID_ARGUMENT;
9442 esize = mono_array_element_size (arr->obj.vtable->klass);
9443 for (i = index; i < index + len; ++i) {
9444 elem = (gpointer*)((char*)arr->vector + (i * esize));
9445 buffer_add_value (buf, m_class_get_byval_arg (m_class_get_element_class (arr->obj.vtable->klass)), elem, arr->obj.vtable->domain);
9447 break;
9448 case CMD_ARRAY_REF_SET_VALUES:
9449 index = decode_int (p, &p, end);
9450 len = decode_int (p, &p, end);
9452 if (index < 0 || len < 0)
9453 return ERR_INVALID_ARGUMENT;
9454 // Reordered to avoid integer overflow
9455 if (index > arr->max_length - len)
9456 return ERR_INVALID_ARGUMENT;
9458 esize = mono_array_element_size (arr->obj.vtable->klass);
9459 for (i = index; i < index + len; ++i) {
9460 elem = (gpointer*)((char*)arr->vector + (i * esize));
9462 decode_value (m_class_get_byval_arg (m_class_get_element_class (arr->obj.vtable->klass)), arr->obj.vtable->domain, (guint8 *)elem, p, &p, end, TRUE);
9464 break;
9465 default:
9466 return ERR_NOT_IMPLEMENTED;
9469 return ERR_NONE;
9472 static ErrorCode
9473 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9475 int objid;
9476 ErrorCode err;
9477 MonoString *str;
9478 char *s;
9479 int i, index, length;
9480 gunichar2 *c;
9481 gboolean use_utf16 = FALSE;
9483 objid = decode_objid (p, &p, end);
9484 err = get_object (objid, (MonoObject**)&str);
9485 if (err != ERR_NONE)
9486 return err;
9488 switch (command) {
9489 case CMD_STRING_REF_GET_VALUE:
9490 if (CHECK_PROTOCOL_VERSION (2, 41)) {
9491 for (i = 0; i < mono_string_length_internal (str); ++i)
9492 if (mono_string_chars_internal (str)[i] == 0)
9493 use_utf16 = TRUE;
9494 buffer_add_byte (buf, use_utf16 ? 1 : 0);
9496 if (use_utf16) {
9497 buffer_add_int (buf, mono_string_length_internal (str) * 2);
9498 buffer_add_utf16 (buf, (guint8*)mono_string_chars_internal (str), mono_string_length_internal (str) * 2);
9499 } else {
9500 ERROR_DECL (error);
9501 s = mono_string_to_utf8_checked_internal (str, error);
9502 if (!is_ok (error)) {
9503 if (s)
9504 g_free (s);
9505 add_error_string (buf, mono_error_get_message (error));
9506 return ERR_INVALID_ARGUMENT;
9508 buffer_add_string (buf, s);
9509 g_free (s);
9511 break;
9512 case CMD_STRING_REF_GET_LENGTH:
9513 buffer_add_long (buf, mono_string_length_internal (str));
9514 break;
9515 case CMD_STRING_REF_GET_CHARS:
9516 index = decode_long (p, &p, end);
9517 length = decode_long (p, &p, end);
9518 if (index > mono_string_length_internal (str) - length)
9519 return ERR_INVALID_ARGUMENT;
9520 c = mono_string_chars_internal (str) + index;
9521 for (i = 0; i < length; ++i)
9522 buffer_add_short (buf, c [i]);
9523 break;
9524 default:
9525 return ERR_NOT_IMPLEMENTED;
9528 return ERR_NONE;
9531 static void
9532 create_file_to_check_memory_address (void)
9534 if (file_check_valid_memory != -1)
9535 return;
9536 char *file_name = g_strdup_printf ("debugger_check_valid_memory.%d", getpid());
9537 filename_check_valid_memory = g_build_filename (g_get_tmp_dir (), file_name, (const char*)NULL);
9538 file_check_valid_memory = open(filename_check_valid_memory, O_CREAT | O_WRONLY | O_APPEND, S_IWUSR);
9539 g_free (file_name);
9542 static gboolean
9543 valid_memory_address (gpointer addr, gint size)
9545 #ifndef _MSC_VER
9546 gboolean ret = TRUE;
9547 create_file_to_check_memory_address ();
9548 if(file_check_valid_memory < 0) {
9549 return TRUE;
9551 write (file_check_valid_memory, (gpointer)addr, 1);
9552 if (errno == EFAULT) {
9553 ret = FALSE;
9555 #else
9556 int i = 0;
9557 gboolean ret = FALSE;
9558 __try {
9559 for (i = 0; i < size; i++)
9560 *((volatile char*)addr+i);
9561 ret = TRUE;
9562 } __except(1) {
9563 return ret;
9565 #endif
9566 return ret;
9569 static ErrorCode
9570 pointer_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9572 ErrorCode err;
9573 gint64 addr;
9574 MonoClass* klass;
9575 MonoDomain* domain = NULL;
9576 MonoType *type = NULL;
9577 int align;
9578 int size = 0;
9580 switch (command) {
9581 case CMD_POINTER_GET_VALUE:
9582 addr = decode_long (p, &p, end);
9583 klass = decode_typeid (p, &p, end, &domain, &err);
9584 if (err != ERR_NONE)
9585 return err;
9587 if (m_class_get_byval_arg (klass)->type != MONO_TYPE_PTR)
9588 return ERR_INVALID_ARGUMENT;
9590 type = m_class_get_byval_arg (m_class_get_element_class (klass));
9591 size = mono_type_size (type, &align);
9593 if (!valid_memory_address((gpointer)addr, size))
9594 return ERR_INVALID_ARGUMENT;
9596 buffer_add_value (buf, type, (gpointer)addr, domain);
9598 break;
9599 default:
9600 return ERR_NOT_IMPLEMENTED;
9603 return ERR_NONE;
9606 static ErrorCode
9607 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9609 HANDLE_FUNCTION_ENTER ();
9611 ERROR_DECL (error);
9612 int objid;
9613 ErrorCode err;
9614 MonoObject *obj;
9615 int len, i;
9616 MonoClassField *f;
9617 MonoClass *k;
9618 gboolean found;
9619 gboolean remote_obj = FALSE;
9620 MonoStringHandle string_handle = MONO_HANDLE_NEW (MonoString, NULL); // FIXME? Not always needed.
9622 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9623 objid = decode_objid (p, &p, end);
9624 err = get_object (objid, &obj);
9625 if (err != ERR_NONE)
9626 buffer_add_int (buf, 1);
9627 else
9628 buffer_add_int (buf, 0);
9629 err = ERR_NONE;
9630 goto exit;
9633 objid = decode_objid (p, &p, end);
9634 err = get_object (objid, &obj);
9635 if (err != ERR_NONE)
9636 goto exit;
9638 MonoClass *obj_type;
9640 obj_type = obj->vtable->klass;
9641 if (mono_class_is_transparent_proxy (obj_type)) {
9642 obj_type = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
9643 remote_obj = TRUE;
9646 g_assert (obj_type);
9648 switch (command) {
9649 case CMD_OBJECT_REF_GET_TYPE:
9650 /* This handles transparent proxies too */
9651 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type_internal (((MonoReflectionType*)obj->vtable->type)->type));
9652 break;
9653 case CMD_OBJECT_REF_GET_VALUES:
9654 len = decode_int (p, &p, end);
9656 for (i = 0; i < len; ++i) {
9657 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9658 if (err != ERR_NONE)
9659 goto exit;
9661 /* Check that the field belongs to the object */
9662 found = FALSE;
9663 for (k = obj_type; k; k = m_class_get_parent (k)) {
9664 if (k == f->parent) {
9665 found = TRUE;
9666 break;
9669 if (!found)
9670 goto invalid_fieldid;
9672 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9673 guint8 *val;
9674 MonoVTable *vtable;
9676 if (mono_class_field_is_special_static (f))
9677 goto invalid_fieldid;
9679 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9680 vtable = mono_class_vtable_checked (obj->vtable->domain, f->parent, error);
9681 if (!is_ok (error)) {
9682 mono_error_cleanup (error);
9683 goto invalid_object;
9685 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type_internal (f->type)));
9686 mono_field_static_get_value_checked (vtable, f, val, string_handle, error);
9687 if (!is_ok (error)) {
9688 mono_error_cleanup (error); /* FIXME report the error */
9689 goto invalid_object;
9691 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9692 g_free (val);
9693 } else {
9694 void *field_value = NULL;
9695 #ifndef DISABLE_REMOTING
9696 void *field_storage = NULL;
9697 #endif
9698 if (remote_obj) {
9699 #ifndef DISABLE_REMOTING
9700 field_value = mono_load_remote_field_checked(obj, obj_type, f, &field_storage, error);
9701 if (!is_ok (error)) {
9702 mono_error_cleanup (error); /* FIXME report the error */
9703 goto invalid_object;
9705 #else
9706 g_assert_not_reached ();
9707 #endif
9708 } else
9709 field_value = (guint8*)obj + f->offset;
9711 buffer_add_value (buf, f->type, field_value, obj->vtable->domain);
9714 break;
9715 case CMD_OBJECT_REF_SET_VALUES:
9716 len = decode_int (p, &p, end);
9718 for (i = 0; i < len; ++i) {
9719 f = decode_fieldid (p, &p, end, NULL, &err);
9720 if (err != ERR_NONE)
9721 goto exit;
9723 /* Check that the field belongs to the object */
9724 found = FALSE;
9725 for (k = obj_type; k; k = m_class_get_parent (k)) {
9726 if (k == f->parent) {
9727 found = TRUE;
9728 break;
9731 if (!found)
9732 goto invalid_fieldid;
9734 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9735 guint8 *val;
9736 MonoVTable *vtable;
9738 if (mono_class_field_is_special_static (f))
9739 goto invalid_fieldid;
9741 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9742 vtable = mono_class_vtable_checked (obj->vtable->domain, f->parent, error);
9743 if (!is_ok (error)) {
9744 mono_error_cleanup (error);
9745 goto invalid_fieldid;
9748 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type_internal (f->type)));
9749 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end, TRUE);
9750 if (err != ERR_NONE) {
9751 g_free (val);
9752 goto exit;
9754 mono_field_static_set_value_internal (vtable, f, val);
9755 g_free (val);
9756 } else {
9757 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end, TRUE);
9758 if (err != ERR_NONE)
9759 goto exit;
9762 break;
9763 case CMD_OBJECT_REF_GET_ADDRESS:
9764 buffer_add_long (buf, (gssize)obj);
9765 break;
9766 case CMD_OBJECT_REF_GET_DOMAIN:
9767 buffer_add_domainid (buf, obj->vtable->domain);
9768 break;
9769 case CMD_OBJECT_REF_GET_INFO:
9770 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type_internal (((MonoReflectionType*)obj->vtable->type)->type));
9771 buffer_add_domainid (buf, obj->vtable->domain);
9772 break;
9773 default:
9774 err = ERR_NOT_IMPLEMENTED;
9775 goto exit;
9778 err = ERR_NONE;
9779 goto exit;
9780 invalid_fieldid:
9781 err = ERR_INVALID_FIELDID;
9782 goto exit;
9783 invalid_object:
9784 err = ERR_INVALID_OBJECT;
9785 goto exit;
9786 exit:
9787 HANDLE_FUNCTION_RETURN_VAL (err);
9790 static const char*
9791 command_set_to_string (CommandSet command_set)
9793 switch (command_set) {
9794 case CMD_SET_VM:
9795 return "VM";
9796 case CMD_SET_OBJECT_REF:
9797 return "OBJECT_REF";
9798 case CMD_SET_STRING_REF:
9799 return "STRING_REF";
9800 case CMD_SET_THREAD:
9801 return "THREAD";
9802 case CMD_SET_ARRAY_REF:
9803 return "ARRAY_REF";
9804 case CMD_SET_EVENT_REQUEST:
9805 return "EVENT_REQUEST";
9806 case CMD_SET_STACK_FRAME:
9807 return "STACK_FRAME";
9808 case CMD_SET_APPDOMAIN:
9809 return "APPDOMAIN";
9810 case CMD_SET_ASSEMBLY:
9811 return "ASSEMBLY";
9812 case CMD_SET_METHOD:
9813 return "METHOD";
9814 case CMD_SET_TYPE:
9815 return "TYPE";
9816 case CMD_SET_MODULE:
9817 return "MODULE";
9818 case CMD_SET_FIELD:
9819 return "FIELD";
9820 case CMD_SET_EVENT:
9821 return "EVENT";
9822 case CMD_SET_POINTER:
9823 return "POINTER";
9824 default:
9825 return "";
9829 static const char* vm_cmds_str [] = {
9830 "VERSION",
9831 "ALL_THREADS",
9832 "SUSPEND",
9833 "RESUME",
9834 "EXIT",
9835 "DISPOSE",
9836 "INVOKE_METHOD",
9837 "SET_PROTOCOL_VERSION",
9838 "ABORT_INVOKE",
9839 "SET_KEEPALIVE"
9840 "GET_TYPES_FOR_SOURCE_FILE",
9841 "GET_TYPES",
9842 "INVOKE_METHODS"
9845 static const char* thread_cmds_str[] = {
9846 "GET_FRAME_INFO",
9847 "GET_NAME",
9848 "GET_STATE",
9849 "GET_INFO",
9850 "GET_ID",
9851 "GET_TID",
9852 "SET_IP"
9855 static const char* event_cmds_str[] = {
9856 "REQUEST_SET",
9857 "REQUEST_CLEAR",
9858 "REQUEST_CLEAR_ALL_BREAKPOINTS"
9861 static const char* appdomain_cmds_str[] = {
9862 "GET_ROOT_DOMAIN",
9863 "GET_FRIENDLY_NAME",
9864 "GET_ASSEMBLIES",
9865 "GET_ENTRY_ASSEMBLY",
9866 "CREATE_STRING",
9867 "GET_CORLIB",
9868 "CREATE_BOXED_VALUE",
9869 "CREATE_BYTE_ARRAY",
9872 static const char* assembly_cmds_str[] = {
9873 "GET_LOCATION",
9874 "GET_ENTRY_POINT",
9875 "GET_MANIFEST_MODULE",
9876 "GET_OBJECT",
9877 "GET_TYPE",
9878 "GET_NAME",
9879 "GET_DOMAIN",
9880 "HAS_DEBUG_INFO"
9883 static const char* module_cmds_str[] = {
9884 "GET_INFO",
9887 static const char* field_cmds_str[] = {
9888 "GET_INFO",
9891 static const char* method_cmds_str[] = {
9892 "GET_NAME",
9893 "GET_DECLARING_TYPE",
9894 "GET_DEBUG_INFO",
9895 "GET_PARAM_INFO",
9896 "GET_LOCALS_INFO",
9897 "GET_INFO",
9898 "GET_BODY",
9899 "RESOLVE_TOKEN",
9900 "GET_CATTRS ",
9901 "MAKE_GENERIC_METHOD"
9904 static const char* type_cmds_str[] = {
9905 "GET_INFO",
9906 "GET_METHODS",
9907 "GET_FIELDS",
9908 "GET_VALUES",
9909 "GET_OBJECT",
9910 "GET_SOURCE_FILES",
9911 "SET_VALUES",
9912 "IS_ASSIGNABLE_FROM",
9913 "GET_PROPERTIES ",
9914 "GET_CATTRS",
9915 "GET_FIELD_CATTRS",
9916 "GET_PROPERTY_CATTRS",
9917 "GET_SOURCE_FILES_2",
9918 "GET_VALUES_2",
9919 "GET_METHODS_BY_NAME_FLAGS",
9920 "GET_INTERFACES",
9921 "GET_INTERFACE_MAP",
9922 "IS_INITIALIZED",
9923 "CREATE_INSTANCE",
9924 "GET_VALUE_SIZE"
9927 static const char* stack_frame_cmds_str[] = {
9928 "GET_VALUES",
9929 "GET_THIS",
9930 "SET_VALUES",
9931 "GET_DOMAIN",
9932 "SET_THIS"
9935 static const char* array_cmds_str[] = {
9936 "GET_LENGTH",
9937 "GET_VALUES",
9938 "SET_VALUES",
9941 static const char* string_cmds_str[] = {
9942 "GET_VALUE",
9943 "GET_LENGTH",
9944 "GET_CHARS"
9947 static const char* pointer_cmds_str[] = {
9948 "GET_VALUE"
9951 static const char* object_cmds_str[] = {
9952 "GET_TYPE",
9953 "GET_VALUES",
9954 "IS_COLLECTED",
9955 "GET_ADDRESS",
9956 "GET_DOMAIN",
9957 "SET_VALUES",
9958 "GET_INFO",
9961 static const char*
9962 cmd_to_string (CommandSet set, int command)
9964 const char **cmds;
9965 int cmds_len = 0;
9967 switch (set) {
9968 case CMD_SET_VM:
9969 cmds = vm_cmds_str;
9970 cmds_len = G_N_ELEMENTS (vm_cmds_str);
9971 break;
9972 case CMD_SET_OBJECT_REF:
9973 cmds = object_cmds_str;
9974 cmds_len = G_N_ELEMENTS (object_cmds_str);
9975 break;
9976 case CMD_SET_STRING_REF:
9977 cmds = string_cmds_str;
9978 cmds_len = G_N_ELEMENTS (string_cmds_str);
9979 break;
9980 case CMD_SET_THREAD:
9981 cmds = thread_cmds_str;
9982 cmds_len = G_N_ELEMENTS (thread_cmds_str);
9983 break;
9984 case CMD_SET_ARRAY_REF:
9985 cmds = array_cmds_str;
9986 cmds_len = G_N_ELEMENTS (array_cmds_str);
9987 break;
9988 case CMD_SET_EVENT_REQUEST:
9989 cmds = event_cmds_str;
9990 cmds_len = G_N_ELEMENTS (event_cmds_str);
9991 break;
9992 case CMD_SET_STACK_FRAME:
9993 cmds = stack_frame_cmds_str;
9994 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
9995 break;
9996 case CMD_SET_APPDOMAIN:
9997 cmds = appdomain_cmds_str;
9998 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
9999 break;
10000 case CMD_SET_ASSEMBLY:
10001 cmds = assembly_cmds_str;
10002 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
10003 break;
10004 case CMD_SET_METHOD:
10005 cmds = method_cmds_str;
10006 cmds_len = G_N_ELEMENTS (method_cmds_str);
10007 break;
10008 case CMD_SET_TYPE:
10009 cmds = type_cmds_str;
10010 cmds_len = G_N_ELEMENTS (type_cmds_str);
10011 break;
10012 case CMD_SET_MODULE:
10013 cmds = module_cmds_str;
10014 cmds_len = G_N_ELEMENTS (module_cmds_str);
10015 break;
10016 case CMD_SET_FIELD:
10017 cmds = field_cmds_str;
10018 cmds_len = G_N_ELEMENTS (field_cmds_str);
10019 break;
10020 case CMD_SET_EVENT:
10021 cmds = event_cmds_str;
10022 cmds_len = G_N_ELEMENTS (event_cmds_str);
10023 break;
10024 case CMD_SET_POINTER:
10025 cmds = pointer_cmds_str;
10026 cmds_len = G_N_ELEMENTS (pointer_cmds_str);
10027 break;
10028 default:
10029 return NULL;
10031 if (command > 0 && command <= cmds_len)
10032 return cmds [command - 1];
10033 else
10034 return NULL;
10037 static gboolean
10038 wait_for_attach (void)
10040 #ifndef DISABLE_SOCKET_TRANSPORT
10041 if (listen_fd == -1) {
10042 PRINT_DEBUG_MSG (1, "[dbg] Invalid listening socket\n");
10043 return FALSE;
10046 /* Block and wait for client connection */
10047 conn_fd = socket_transport_accept (listen_fd);
10049 PRINT_DEBUG_MSG (1, "Accepted connection on %d\n", conn_fd);
10050 if (conn_fd == -1) {
10051 PRINT_DEBUG_MSG (1, "[dbg] Bad client connection\n");
10052 return FALSE;
10054 #else
10055 g_assert_not_reached ();
10056 #endif
10058 /* Handshake */
10059 disconnected = !transport_handshake ();
10060 if (disconnected) {
10061 PRINT_DEBUG_MSG (1, "Transport handshake failed!\n");
10062 return FALSE;
10065 return TRUE;
10069 * debugger_thread:
10071 * This thread handles communication with the debugger client using a JDWP
10072 * like protocol.
10074 static gsize WINAPI
10075 debugger_thread (void *arg)
10077 int res, len, id, flags, command = 0;
10078 CommandSet command_set = (CommandSet)0;
10079 guint8 header [HEADER_LENGTH];
10080 guint8 *data, *p, *end;
10081 Buffer buf;
10082 ErrorCode err;
10083 gboolean no_reply;
10084 gboolean attach_failed = FALSE;
10086 PRINT_DEBUG_MSG (1, "[dbg] Agent thread started, pid=%p\n", (gpointer) (gsize) mono_native_thread_id_get ());
10088 gboolean log_each_step = g_hasenv ("MONO_DEBUGGER_LOG_AFTER_COMMAND");
10090 debugger_thread_id = mono_native_thread_id_get ();
10092 MonoInternalThread *internal = mono_thread_internal_current ();
10093 mono_thread_set_name_constant_ignore_error (internal, "Debugger agent", MonoSetThreadNameFlag_Permanent);
10095 internal->state |= ThreadState_Background;
10096 internal->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
10098 if (agent_config.defer) {
10099 if (!wait_for_attach ()) {
10100 PRINT_DEBUG_MSG (1, "[dbg] Can't attach, aborting debugger thread.\n");
10101 attach_failed = TRUE; // Don't abort process when we can't listen
10102 } else {
10103 mono_set_is_debugger_attached (TRUE);
10104 /* Send start event to client */
10105 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
10107 } else {
10108 mono_set_is_debugger_attached (TRUE);
10111 while (!attach_failed) {
10112 res = transport_recv (header, HEADER_LENGTH);
10114 /* This will break if the socket is closed during shutdown too */
10115 if (res != HEADER_LENGTH) {
10116 PRINT_DEBUG_MSG (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH);
10117 command_set = (CommandSet)0;
10118 command = 0;
10119 dispose_vm ();
10120 break;
10121 } else {
10122 p = header;
10123 end = header + HEADER_LENGTH;
10125 len = decode_int (p, &p, end);
10126 id = decode_int (p, &p, end);
10127 flags = decode_byte (p, &p, end);
10128 command_set = (CommandSet)decode_byte (p, &p, end);
10129 command = decode_byte (p, &p, end);
10132 g_assert (flags == 0);
10133 const char *cmd_str;
10134 char cmd_num [256];
10136 cmd_str = cmd_to_string (command_set, command);
10137 if (!cmd_str) {
10138 sprintf (cmd_num, "%d", command);
10139 cmd_str = cmd_num;
10142 if (log_level) {
10143 PRINT_DEBUG_MSG (1, "[dbg] Command %s(%s) [%d][at=%lx].\n", command_set_to_string (command_set), cmd_str, id, (long)mono_100ns_ticks () / 10000);
10146 data = (guint8 *)g_malloc (len - HEADER_LENGTH);
10147 if (len - HEADER_LENGTH > 0)
10149 res = transport_recv (data, len - HEADER_LENGTH);
10150 if (res != len - HEADER_LENGTH) {
10151 PRINT_DEBUG_MSG (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH);
10152 break;
10156 p = data;
10157 end = data + (len - HEADER_LENGTH);
10159 buffer_init (&buf, 128);
10161 err = ERR_NONE;
10162 no_reply = FALSE;
10164 /* Process the request */
10165 switch (command_set) {
10166 case CMD_SET_VM:
10167 err = vm_commands (command, id, p, end, &buf);
10168 if (err == ERR_NONE && command == CMD_VM_INVOKE_METHOD)
10169 /* Sent after the invoke is complete */
10170 no_reply = TRUE;
10171 break;
10172 case CMD_SET_EVENT_REQUEST:
10173 err = event_commands (command, p, end, &buf);
10174 break;
10175 case CMD_SET_APPDOMAIN:
10176 err = domain_commands (command, p, end, &buf);
10177 break;
10178 case CMD_SET_ASSEMBLY:
10179 err = assembly_commands (command, p, end, &buf);
10180 break;
10181 case CMD_SET_MODULE:
10182 err = module_commands (command, p, end, &buf);
10183 break;
10184 case CMD_SET_FIELD:
10185 err = field_commands (command, p, end, &buf);
10186 break;
10187 case CMD_SET_TYPE:
10188 err = type_commands (command, p, end, &buf);
10189 break;
10190 case CMD_SET_METHOD:
10191 err = method_commands (command, p, end, &buf);
10192 break;
10193 case CMD_SET_THREAD:
10194 err = thread_commands (command, p, end, &buf);
10195 break;
10196 case CMD_SET_STACK_FRAME:
10197 err = frame_commands (command, p, end, &buf);
10198 break;
10199 case CMD_SET_ARRAY_REF:
10200 err = array_commands (command, p, end, &buf);
10201 break;
10202 case CMD_SET_STRING_REF:
10203 err = string_commands (command, p, end, &buf);
10204 break;
10205 case CMD_SET_POINTER:
10206 err = pointer_commands (command, p, end, &buf);
10207 break;
10208 case CMD_SET_OBJECT_REF:
10209 err = object_commands (command, p, end, &buf);
10210 break;
10211 default:
10212 err = ERR_NOT_IMPLEMENTED;
10215 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
10216 buffer_replies = TRUE;
10219 if (!no_reply) {
10220 if (buffer_replies) {
10221 buffer_reply_packet (id, err, &buf);
10222 } else {
10223 send_reply_packet (id, err, &buf);
10224 //PRINT_DEBUG_MSG (1, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000);
10228 mono_debugger_log_command (command_set_to_string (command_set), cmd_str, buf.buf, buffer_len (&buf));
10230 if (err == ERR_NONE && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
10231 send_buffered_reply_packets ();
10232 buffer_replies = FALSE;
10235 g_free (data);
10236 buffer_free (&buf);
10238 if (log_each_step) {
10239 char *debugger_log = mono_debugger_state_str ();
10240 if (debugger_log) {
10241 PRINT_ERROR_MSG ("Debugger state: %s\n", debugger_log);
10242 g_free (debugger_log);
10246 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
10247 break;
10250 mono_set_is_debugger_attached (FALSE);
10252 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
10253 debugger_thread_exited = TRUE;
10254 mono_coop_cond_signal (&debugger_thread_exited_cond);
10255 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
10257 PRINT_DEBUG_MSG (1, "[dbg] Debugger thread exited.\n");
10259 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
10260 PRINT_DEBUG_MSG (2, "[dbg] Detached - restarting clean debugger thread.\n");
10261 ERROR_DECL (error);
10262 start_debugger_thread (error);
10263 mono_error_cleanup (error);
10266 return 0;
10269 void
10270 mono_debugger_agent_init (void)
10272 MonoDebuggerCallbacks cbs;
10274 memset (&cbs, 0, sizeof (cbs));
10275 cbs.version = MONO_DBG_CALLBACKS_VERSION;
10276 cbs.parse_options = debugger_agent_parse_options;
10277 cbs.init = debugger_agent_init;
10278 cbs.breakpoint_hit = debugger_agent_breakpoint_hit;
10279 cbs.single_step_event = debugger_agent_single_step_event;
10280 cbs.single_step_from_context = debugger_agent_single_step_from_context;
10281 cbs.breakpoint_from_context = debugger_agent_breakpoint_from_context;
10282 cbs.free_domain_info = debugger_agent_free_domain_info;
10283 cbs.unhandled_exception = debugger_agent_unhandled_exception;
10284 cbs.handle_exception = debugger_agent_handle_exception;
10285 cbs.begin_exception_filter = debugger_agent_begin_exception_filter;
10286 cbs.end_exception_filter = debugger_agent_end_exception_filter;
10287 cbs.user_break = debugger_agent_user_break;
10288 cbs.debug_log = debugger_agent_debug_log;
10289 cbs.debug_log_is_enabled = debugger_agent_debug_log_is_enabled;
10290 cbs.send_crash = mono_debugger_agent_send_crash;
10292 mini_install_dbg_callbacks (&cbs);
10295 void
10296 mono_debugger_agent_parse_options (char *options)
10298 sdb_options = options;
10301 #endif /* DISABLE_SDB */