[LoongArch64] Part-5:add loongarch support in some files for LoongArch64. (#21769)
[mono-project.git] / mono / mini / debugger-agent.c
bloba9a24e6e472676dfa4d161ff74af1c0118d5780b
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 63
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 CMD_GET_ENC_CAPABILITIES = 21
363 } CmdVM;
365 typedef enum {
366 CMD_THREAD_GET_FRAME_INFO = 1,
367 CMD_THREAD_GET_NAME = 2,
368 CMD_THREAD_GET_STATE = 3,
369 CMD_THREAD_GET_INFO = 4,
370 CMD_THREAD_GET_ID = 5,
371 CMD_THREAD_GET_TID = 6,
372 CMD_THREAD_SET_IP = 7,
373 CMD_THREAD_ELAPSED_TIME = 8
374 } CmdThread;
376 typedef enum {
377 CMD_EVENT_REQUEST_SET = 1,
378 CMD_EVENT_REQUEST_CLEAR = 2,
379 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
380 } CmdEvent;
382 typedef enum {
383 CMD_COMPOSITE = 100
384 } CmdComposite;
386 typedef enum {
387 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
388 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
389 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
390 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
391 CMD_APPDOMAIN_CREATE_STRING = 5,
392 CMD_APPDOMAIN_GET_CORLIB = 6,
393 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7,
394 CMD_APPDOMAIN_CREATE_BYTE_ARRAY = 8,
395 } CmdAppDomain;
397 typedef enum {
398 CMD_ASSEMBLY_GET_LOCATION = 1,
399 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
400 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
401 CMD_ASSEMBLY_GET_OBJECT = 4,
402 CMD_ASSEMBLY_GET_TYPE = 5,
403 CMD_ASSEMBLY_GET_NAME = 6,
404 CMD_ASSEMBLY_GET_DOMAIN = 7,
405 CMD_ASSEMBLY_GET_METADATA_BLOB = 8,
406 CMD_ASSEMBLY_GET_IS_DYNAMIC = 9,
407 CMD_ASSEMBLY_GET_PDB_BLOB = 10,
408 CMD_ASSEMBLY_GET_TYPE_FROM_TOKEN = 11,
409 CMD_ASSEMBLY_GET_METHOD_FROM_TOKEN = 12,
410 CMD_ASSEMBLY_HAS_DEBUG_INFO = 13,
411 CMD_ASSEMBLY_GET_CATTRS = 14,
412 CMD_ASSEMBLY_GET_DEBUG_INFORMATION = 17,
413 CMD_ASSEMBLY_HAS_DEBUG_INFO_LOADED = 18
414 } CmdAssembly;
416 typedef enum {
417 CMD_MODULE_GET_INFO = 1,
418 CMD_MODULE_APPLY_CHANGES = 2, /* unused, reserved */
419 } CmdModule;
421 typedef enum {
422 CMD_FIELD_GET_INFO = 1,
423 } CmdField;
425 typedef enum {
426 CMD_METHOD_GET_NAME = 1,
427 CMD_METHOD_GET_DECLARING_TYPE = 2,
428 CMD_METHOD_GET_DEBUG_INFO = 3,
429 CMD_METHOD_GET_PARAM_INFO = 4,
430 CMD_METHOD_GET_LOCALS_INFO = 5,
431 CMD_METHOD_GET_INFO = 6,
432 CMD_METHOD_GET_BODY = 7,
433 CMD_METHOD_RESOLVE_TOKEN = 8,
434 CMD_METHOD_GET_CATTRS = 9,
435 CMD_METHOD_MAKE_GENERIC_METHOD = 10
436 } CmdMethod;
438 typedef enum {
439 CMD_TYPE_GET_INFO = 1,
440 CMD_TYPE_GET_METHODS = 2,
441 CMD_TYPE_GET_FIELDS = 3,
442 CMD_TYPE_GET_VALUES = 4,
443 CMD_TYPE_GET_OBJECT = 5,
444 CMD_TYPE_GET_SOURCE_FILES = 6,
445 CMD_TYPE_SET_VALUES = 7,
446 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
447 CMD_TYPE_GET_PROPERTIES = 9,
448 CMD_TYPE_GET_CATTRS = 10,
449 CMD_TYPE_GET_FIELD_CATTRS = 11,
450 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
451 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
452 CMD_TYPE_GET_VALUES_2 = 14,
453 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
454 CMD_TYPE_GET_INTERFACES = 16,
455 CMD_TYPE_GET_INTERFACE_MAP = 17,
456 CMD_TYPE_IS_INITIALIZED = 18,
457 CMD_TYPE_CREATE_INSTANCE = 19,
458 CMD_TYPE_GET_VALUE_SIZE = 20
459 } CmdType;
461 typedef enum {
462 CMD_STACK_FRAME_GET_VALUES = 1,
463 CMD_STACK_FRAME_GET_THIS = 2,
464 CMD_STACK_FRAME_SET_VALUES = 3,
465 CMD_STACK_FRAME_GET_DOMAIN = 4,
466 CMD_STACK_FRAME_SET_THIS = 5,
467 } CmdStackFrame;
469 typedef enum {
470 CMD_ARRAY_REF_GET_LENGTH = 1,
471 CMD_ARRAY_REF_GET_VALUES = 2,
472 CMD_ARRAY_REF_SET_VALUES = 3,
473 } CmdArray;
475 typedef enum {
476 CMD_STRING_REF_GET_VALUE = 1,
477 CMD_STRING_REF_GET_LENGTH = 2,
478 CMD_STRING_REF_GET_CHARS = 3
479 } CmdString;
481 typedef enum {
482 CMD_POINTER_GET_VALUE = 1
483 } CmdPointer;
485 typedef enum {
486 CMD_OBJECT_REF_GET_TYPE = 1,
487 CMD_OBJECT_REF_GET_VALUES = 2,
488 CMD_OBJECT_REF_IS_COLLECTED = 3,
489 CMD_OBJECT_REF_GET_ADDRESS = 4,
490 CMD_OBJECT_REF_GET_DOMAIN = 5,
491 CMD_OBJECT_REF_SET_VALUES = 6,
492 CMD_OBJECT_REF_GET_INFO = 7,
493 } CmdObject;
496 * Contains additional information for an event
498 typedef struct {
499 /* For EVENT_KIND_EXCEPTION */
500 MonoObject *exc;
501 MonoContext catch_ctx;
502 gboolean caught;
503 /* For EVENT_KIND_USER_LOG */
504 int level;
505 char *category, *message;
506 /* For EVENT_KIND_TYPE_LOAD */
507 MonoClass *klass;
508 /* For EVENT_KIND_CRASH */
509 char *dump;
510 MonoStackHash *hashes;
511 } EventInfo;
513 typedef struct {
514 guint8 *buf, *p, *end;
515 } Buffer;
517 typedef struct ReplyPacket {
518 int id;
519 int error;
520 Buffer *data;
521 } ReplyPacket;
523 #ifdef HOST_WIN32
524 #define get_last_sock_error() WSAGetLastError()
525 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
526 #define MONO_EINTR WSAEINTR
527 #else
528 #define get_last_sock_error() errno
529 #define MONO_EWOULDBLOCK EWOULDBLOCK
530 #define MONO_EINTR EINTR
531 #endif
533 #define CHECK_PROTOCOL_VERSION(major,minor) \
534 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
537 * Globals
540 static AgentConfig agent_config;
543 * Whenever the agent is fully initialized.
544 * When using the onuncaught or onthrow options, only some parts of the agent are
545 * initialized on startup, and the full initialization which includes connection
546 * establishment and the startup of the agent thread is only done in response to
547 * an event.
549 static gint32 agent_inited;
551 #ifndef DISABLE_SOCKET_TRANSPORT
552 static int conn_fd;
553 static int listen_fd;
554 #endif
556 static int packet_id = 0;
558 static int objref_id = 0;
560 static int event_request_id = 0;
562 static int frame_id = 0;
564 static GPtrArray *event_requests;
566 static MonoNativeTlsKey debugger_tls_id;
568 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
570 /* Maps MonoInternalThread -> DebuggerTlsData */
571 /* Protected by the loader lock */
572 static MonoGHashTable *thread_to_tls;
574 /* Maps tid -> MonoInternalThread */
575 /* Protected by the loader lock */
576 static MonoGHashTable *tid_to_thread;
578 /* Maps tid -> MonoThread (not MonoInternalThread) */
579 /* Protected by the loader lock */
580 static MonoGHashTable *tid_to_thread_obj;
582 static MonoNativeThreadId debugger_thread_id;
584 static MonoThreadHandle *debugger_thread_handle;
586 static int log_level;
588 static int file_check_valid_memory = -1;
590 static char* filename_check_valid_memory;
592 static gboolean embedding;
594 static FILE *log_file;
596 /* Assemblies whose assembly load event has no been sent yet */
597 /* Protected by the dbg lock */
598 static GPtrArray *pending_assembly_loads;
600 /* Whenever the debugger thread has exited */
601 static gboolean debugger_thread_exited;
603 /* Cond variable used to wait for debugger_thread_exited becoming true */
604 static MonoCoopCond debugger_thread_exited_cond;
606 /* Mutex for the cond var above */
607 static MonoCoopMutex debugger_thread_exited_mutex;
609 /* The protocol version of the client */
610 static int major_version, minor_version;
612 /* Whenever the variables above are set by the client */
613 static gboolean protocol_version_set;
615 /* The number of times the runtime is suspended */
616 static gint32 suspend_count;
618 /* Whenever to buffer reply messages and send them together */
619 static gboolean buffer_replies;
621 /* Buffered reply packets */
622 static ReplyPacket reply_packets [128];
623 static int nreply_packets;
625 #define dbg_lock mono_de_lock
626 #define dbg_unlock mono_de_unlock
628 static void transport_init (void);
629 static void transport_connect (const char *address);
630 static gboolean transport_handshake (void);
631 static void register_transport (DebuggerTransport *trans);
633 static gsize WINAPI debugger_thread (void *arg);
635 static void runtime_initialized (MonoProfiler *prof);
637 static void runtime_shutdown (MonoProfiler *prof);
639 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
641 static void thread_end (MonoProfiler *prof, uintptr_t tid);
643 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain);
645 static void appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain);
647 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
649 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
651 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
653 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
655 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly);
657 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
659 static void gc_finalizing (MonoProfiler *prof);
661 static void gc_finalized (MonoProfiler *prof);
663 static void emit_assembly_load (gpointer assembly, gpointer user_data);
665 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
667 static void jit_done (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo);
669 static void jit_failed (MonoProfiler *prof, MonoMethod *method);
671 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo);
673 static void suspend_current (void);
675 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
677 static void clear_types_for_assembly (MonoAssembly *assembly);
679 static void process_profiler_event (EventKind event, gpointer arg);
681 /* Submodule init/cleanup */
682 static void event_requests_cleanup (void);
684 static void objrefs_init (void);
685 static void objrefs_cleanup (void);
687 static void ids_init (void);
688 static void ids_cleanup (void);
690 static void suspend_init (void);
692 static void start_debugger_thread (MonoError *error);
693 static void stop_debugger_thread (void);
695 static void finish_agent_init (gboolean on_startup);
697 static void process_profiler_event (EventKind event, gpointer arg);
699 static void invalidate_frames (DebuggerTlsData *tls);
701 /* Callbacks used by debugger-engine */
702 static MonoContext* tls_get_restore_state (void *the_tls);
703 static gboolean try_process_suspend (void *tls, MonoContext *ctx, gboolean from_breakpoint);
704 static gboolean begin_breakpoint_processing (void *tls, MonoContext *ctx, MonoJitInfo *ji, gboolean from_signal);
705 static void begin_single_step_processing (MonoContext *ctx, gboolean from_signal);
706 static void ss_discard_frame_context (void *the_tls);
707 static void ss_calculate_framecount (void *tls, MonoContext *ctx, gboolean force_use_ctx, DbgEngineStackFrame ***frames, int *nframes);
708 static gboolean ensure_jit (DbgEngineStackFrame* the_frame);
709 static int ensure_runtime_is_suspended (void);
710 static int get_this_async_id (DbgEngineStackFrame *frame);
711 static void* create_breakpoint_events (GPtrArray *ss_reqs, GPtrArray *bp_reqs, MonoJitInfo *ji, EventKind kind);
712 static void process_breakpoint_events (void *_evts, MonoMethod *method, MonoContext *ctx, int il_offset);
713 static int ss_create_init_args (SingleStepReq *ss_req, SingleStepArgs *args);
714 static void ss_args_destroy (SingleStepArgs *ss_args);
715 static int handle_multiple_ss_requests (void);
717 static GENERATE_TRY_GET_CLASS_WITH_CACHE (fixed_buffer, "System.Runtime.CompilerServices", "FixedBufferAttribute")
719 #ifndef DISABLE_SOCKET_TRANSPORT
720 static void
721 register_socket_transport (void);
722 #endif
724 static gboolean
725 is_debugger_thread (void)
727 MonoInternalThread *internal;
729 internal = mono_thread_internal_current ();
730 if (!internal)
731 return FALSE;
733 return internal->debugger_thread;
736 static int
737 parse_address (char *address, char **host, int *port)
739 char *pos = strchr (address, ':');
741 if (pos == NULL || pos == address)
742 return 1;
744 size_t len = pos - address;
745 *host = (char *)g_malloc (len + 1);
746 memcpy (*host, address, len);
747 (*host) [len] = '\0';
749 *port = atoi (pos + 1);
751 return 0;
754 static void
755 print_usage (void)
757 PRINT_ERROR_MSG ("Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
758 PRINT_ERROR_MSG ("Available options:\n");
759 PRINT_ERROR_MSG (" transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
760 PRINT_ERROR_MSG (" address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
761 PRINT_ERROR_MSG (" loglevel=<n>\t\t\tLog level (defaults to 0)\n");
762 PRINT_ERROR_MSG (" logfile=<file>\t\tFile to log to (defaults to stdout)\n");
763 PRINT_ERROR_MSG (" suspend=y/n\t\t\tWhether to suspend after startup.\n");
764 PRINT_ERROR_MSG (" timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
765 PRINT_ERROR_MSG (" server=y/n\t\t\tWhether to listen for a client connection.\n");
766 PRINT_ERROR_MSG (" keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
767 PRINT_ERROR_MSG (" setpgid=y/n\t\t\tWhether to call setpid(0, 0) after startup.\n");
768 PRINT_ERROR_MSG (" help\t\t\t\tPrint this help.\n");
771 static gboolean
772 parse_flag (const char *option, char *flag)
774 if (!strcmp (flag, "y"))
775 return TRUE;
776 else if (!strcmp (flag, "n"))
777 return FALSE;
778 else {
779 PRINT_ERROR_MSG ("debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
780 exit (1);
781 return FALSE;
785 static void
786 debugger_agent_parse_options (char *options)
788 char **args, **ptr;
789 char *host;
790 int port;
791 char *extra;
793 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
794 PRINT_ERROR_MSG ("--debugger-agent is not supported on this platform.\n");
795 exit (1);
796 #endif
798 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
799 if (extra) {
800 options = g_strdup_printf ("%s,%s", options, extra);
801 g_free (extra);
804 agent_config.enabled = TRUE;
805 agent_config.suspend = TRUE;
806 agent_config.server = FALSE;
807 agent_config.defer = FALSE;
808 agent_config.address = NULL;
810 //agent_config.log_level = 10;
812 args = g_strsplit (options, ",", -1);
813 for (ptr = args; ptr && *ptr; ptr ++) {
814 char *arg = *ptr;
816 if (strncmp (arg, "transport=", 10) == 0) {
817 agent_config.transport = g_strdup (arg + 10);
818 } else if (strncmp (arg, "address=", 8) == 0) {
819 agent_config.address = g_strdup (arg + 8);
820 } else if (strncmp (arg, "loglevel=", 9) == 0) {
821 agent_config.log_level = atoi (arg + 9);
822 } else if (strncmp (arg, "logfile=", 8) == 0) {
823 agent_config.log_file = g_strdup (arg + 8);
824 } else if (strncmp (arg, "suspend=", 8) == 0) {
825 agent_config.suspend = parse_flag ("suspend", arg + 8);
826 } else if (strncmp (arg, "server=", 7) == 0) {
827 agent_config.server = parse_flag ("server", arg + 7);
828 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
829 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
830 } else if (strncmp (arg, "onthrow=", 8) == 0) {
831 /* We support multiple onthrow= options */
832 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
833 } else if (strncmp (arg, "onthrow", 7) == 0) {
834 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
835 } else if (strncmp (arg, "help", 4) == 0) {
836 print_usage ();
837 exit (0);
838 } else if (strncmp (arg, "timeout=", 8) == 0) {
839 agent_config.timeout = atoi (arg + 8);
840 } else if (strncmp (arg, "launch=", 7) == 0) {
841 agent_config.launch = g_strdup (arg + 7);
842 } else if (strncmp (arg, "embedding=", 10) == 0) {
843 agent_config.embedding = atoi (arg + 10) == 1;
844 } else if (strncmp (arg, "keepalive=", 10) == 0) {
845 agent_config.keepalive = atoi (arg + 10);
846 } else if (strncmp (arg, "setpgid=", 8) == 0) {
847 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
848 } else {
849 print_usage ();
850 exit (1);
854 if (agent_config.server && !agent_config.suspend) {
855 /* Waiting for deferred attachment */
856 agent_config.defer = TRUE;
857 if (agent_config.address == NULL) {
858 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (mono_process_current_pid () % 1000));
862 //agent_config.log_level = 0;
864 if (agent_config.transport == NULL) {
865 PRINT_ERROR_MSG ("debugger-agent: The 'transport' option is mandatory.\n");
866 exit (1);
869 if (agent_config.address == NULL && !agent_config.server) {
870 PRINT_ERROR_MSG ("debugger-agent: The 'address' option is mandatory.\n");
871 exit (1);
874 // FIXME:
875 if (!strcmp (agent_config.transport, "dt_socket")) {
876 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
877 PRINT_ERROR_MSG ("debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
878 exit (1);
882 mini_get_debug_options ()->gen_sdb_seq_points = TRUE;
884 * This is needed because currently we don't handle liveness info.
886 mini_get_debug_options ()->mdb_optimizations = TRUE;
888 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
889 /* This is needed because we can't set local variables in registers yet */
890 mono_disable_optimizations (MONO_OPT_LINEARS);
891 #endif
894 * The stack walk done from thread_interrupt () needs to be signal safe, but it
895 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
896 * safe (#3411). So load AOT info eagerly when the debugger is running as a
897 * workaround.
899 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
902 void
903 mono_debugger_set_thread_state (DebuggerTlsData *tls, MonoDebuggerThreadState expected, MonoDebuggerThreadState set)
905 g_assertf (tls, "Cannot get state of null thread", NULL);
907 g_assert (tls->thread_state == expected);
909 tls->thread_state = set;
912 MonoDebuggerThreadState
913 mono_debugger_get_thread_state (DebuggerTlsData *tls)
915 g_assertf (tls, "Cannot get state of null thread", NULL);
917 return tls->thread_state;
920 gsize
921 mono_debugger_tls_thread_id (DebuggerTlsData *tls)
923 if (!tls)
924 return 0;
926 return tls->thread_id;
929 // Only call this function with the loader lock held
930 MonoGHashTable *
931 mono_debugger_get_thread_states (void)
933 return thread_to_tls;
936 gboolean
937 mono_debugger_is_disconnected (void)
939 return disconnected;
942 static void
943 debugger_agent_init (void)
945 if (!agent_config.enabled)
946 return;
948 DebuggerEngineCallbacks cbs;
949 memset (&cbs, 0, sizeof (cbs));
950 cbs.tls_get_restore_state = tls_get_restore_state;
951 cbs.try_process_suspend = try_process_suspend;
952 cbs.begin_breakpoint_processing = begin_breakpoint_processing;
953 cbs.begin_single_step_processing = begin_single_step_processing;
954 cbs.ss_discard_frame_context = ss_discard_frame_context;
955 cbs.ss_calculate_framecount = ss_calculate_framecount;
956 cbs.ensure_jit = ensure_jit;
957 cbs.ensure_runtime_is_suspended = ensure_runtime_is_suspended;
958 cbs.get_this_async_id = get_this_async_id;
959 cbs.set_set_notification_for_wait_completion_flag = set_set_notification_for_wait_completion_flag;
960 cbs.get_notify_debugger_of_wait_completion_method = get_notify_debugger_of_wait_completion_method;
961 cbs.create_breakpoint_events = create_breakpoint_events;
962 cbs.process_breakpoint_events = process_breakpoint_events;
963 cbs.ss_create_init_args = ss_create_init_args;
964 cbs.ss_args_destroy = ss_args_destroy;
965 cbs.handle_multiple_ss_requests = handle_multiple_ss_requests;
967 mono_de_init (&cbs);
969 transport_init ();
971 /* Need to know whenever a thread has acquired the loader mutex */
972 mono_loader_lock_track_ownership (TRUE);
974 event_requests = g_ptr_array_new ();
976 mono_coop_mutex_init (&debugger_thread_exited_mutex);
977 mono_coop_cond_init (&debugger_thread_exited_cond);
979 MonoProfilerHandle prof = mono_profiler_create (NULL);
980 mono_profiler_set_runtime_shutdown_end_callback (prof, runtime_shutdown);
981 mono_profiler_set_runtime_initialized_callback (prof, runtime_initialized);
982 mono_profiler_set_domain_loaded_callback (prof, appdomain_load);
983 mono_profiler_set_domain_unloading_callback (prof, appdomain_start_unload);
984 mono_profiler_set_domain_unloaded_callback (prof, appdomain_unload);
985 mono_profiler_set_thread_started_callback (prof, thread_startup);
986 mono_profiler_set_thread_stopped_callback (prof, thread_end);
987 mono_profiler_set_assembly_loaded_callback (prof, assembly_load);
988 mono_profiler_set_assembly_unloading_callback (prof, assembly_unload);
989 mono_profiler_set_jit_done_callback (prof, jit_done);
990 mono_profiler_set_jit_failed_callback (prof, jit_failed);
991 mono_profiler_set_gc_finalizing_callback (prof, gc_finalizing);
992 mono_profiler_set_gc_finalized_callback (prof, gc_finalized);
994 mono_native_tls_alloc (&debugger_tls_id, NULL);
996 /* Needed by the hash_table_new_type () call below */
997 mono_gc_base_init ();
999 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");
1001 tid_to_thread = mono_g_hash_table_new_type_internal (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DEBUGGER, NULL, "Debugger Thread Table");
1003 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");
1005 pending_assembly_loads = g_ptr_array_new ();
1007 log_level = agent_config.log_level;
1009 embedding = agent_config.embedding;
1010 disconnected = TRUE;
1012 if (agent_config.log_file) {
1013 log_file = fopen (agent_config.log_file, "w+");
1014 if (!log_file) {
1015 PRINT_ERROR_MSG ("Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
1016 exit (1);
1018 } else {
1019 log_file = stdout;
1021 mono_de_set_log_level (log_level, log_file);
1023 ids_init ();
1024 objrefs_init ();
1025 suspend_init ();
1027 #ifdef HAVE_SETPGID
1028 if (agent_config.setpgid)
1029 setpgid (0, 0);
1030 #endif
1032 if (!agent_config.onuncaught && !agent_config.onthrow)
1033 finish_agent_init (TRUE);
1037 * finish_agent_init:
1039 * Finish the initialization of the agent. This involves connecting the transport
1040 * and starting the agent thread. This is either done at startup, or
1041 * in response to some event like an unhandled exception.
1043 static void
1044 finish_agent_init (gboolean on_startup)
1046 if (mono_atomic_cas_i32 (&agent_inited, 1, 0) == 1)
1047 return;
1049 if (agent_config.launch) {
1051 // FIXME: Generated address
1052 // FIXME: Races with transport_connect ()
1054 #ifdef G_OS_WIN32
1055 // Nothing. FIXME? g_spawn_async_with_pipes is easy enough to provide for Windows if needed.
1056 #elif !HAVE_G_SPAWN
1057 PRINT_ERROR_MSG ("g_spawn_async_with_pipes not supported on this platform\n");
1058 exit (1);
1059 #else
1060 char *argv [ ] = {
1061 agent_config.launch,
1062 agent_config.transport,
1063 agent_config.address,
1064 NULL
1066 int res = g_spawn_async_with_pipes (NULL, argv, NULL, (GSpawnFlags)0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1067 if (!res) {
1068 PRINT_ERROR_MSG ("Failed to execute '%s'.\n", agent_config.launch);
1069 exit (1);
1071 #endif
1074 transport_connect (agent_config.address);
1076 if (!on_startup) {
1077 /* Do some which is usually done after sending the VMStart () event */
1078 vm_start_event_sent = TRUE;
1079 ERROR_DECL (error);
1080 start_debugger_thread (error);
1081 mono_error_assert_ok (error);
1085 static void
1086 mono_debugger_agent_cleanup (void)
1088 if (!agent_inited)
1089 return;
1091 stop_debugger_thread ();
1093 event_requests_cleanup ();
1094 objrefs_cleanup ();
1095 ids_cleanup ();
1097 mono_de_cleanup ();
1099 if (file_check_valid_memory != -1) {
1100 remove (filename_check_valid_memory);
1101 g_free (filename_check_valid_memory);
1102 close (file_check_valid_memory);
1107 * SOCKET TRANSPORT
1110 #ifndef DISABLE_SOCKET_TRANSPORT
1113 * recv_length:
1115 * recv() + handle incomplete reads and EINTR
1117 static int
1118 socket_transport_recv (void *buf, int len)
1120 int res;
1121 int total = 0;
1122 int fd = conn_fd;
1123 int flags = 0;
1124 static gint64 last_keepalive;
1125 gint64 msecs;
1127 MONO_ENTER_GC_SAFE;
1129 do {
1130 again:
1131 res = recv (fd, (char *) buf + total, len - total, flags);
1132 if (res > 0)
1133 total += res;
1134 if (agent_config.keepalive) {
1135 gboolean need_keepalive = FALSE;
1136 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1137 need_keepalive = TRUE;
1138 } else if (res == -1) {
1139 /* This could happen if recv () is interrupted repeatedly */
1140 msecs = mono_msec_ticks ();
1141 if (msecs - last_keepalive >= agent_config.keepalive) {
1142 need_keepalive = TRUE;
1143 last_keepalive = msecs;
1146 if (need_keepalive) {
1147 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1148 goto again;
1151 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1153 MONO_EXIT_GC_SAFE;
1155 return total;
1158 static void
1159 set_keepalive (void)
1161 struct timeval tv;
1162 int result;
1164 if (!agent_config.keepalive || !conn_fd)
1165 return;
1167 tv.tv_sec = agent_config.keepalive / 1000;
1168 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1170 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1171 g_assert (result >= 0);
1174 static int
1175 socket_transport_accept (int socket_fd)
1177 MONO_ENTER_GC_SAFE;
1178 conn_fd = accept (socket_fd, NULL, NULL);
1179 MONO_EXIT_GC_SAFE;
1181 if (conn_fd == -1) {
1182 PRINT_ERROR_MSG ("debugger-agent: Unable to listen on %d\n", socket_fd);
1183 } else {
1184 PRINT_DEBUG_MSG (1, "Accepted connection from client, connection fd=%d.\n", conn_fd);
1187 return conn_fd;
1190 static gboolean
1191 socket_transport_send (void *data, int len)
1193 int res;
1195 MONO_ENTER_GC_SAFE;
1197 do {
1198 res = send (conn_fd, (const char*)data, len, 0);
1199 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1201 MONO_EXIT_GC_SAFE;
1203 if (res != len)
1204 return FALSE;
1205 else
1206 return TRUE;
1210 * socket_transport_connect:
1212 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1214 static void
1215 socket_transport_connect (const char *address)
1217 MonoAddressInfo *result;
1218 MonoAddressEntry *rp;
1219 int sfd = -1, s, res;
1220 char *host;
1221 int port;
1223 if (agent_config.address) {
1224 res = parse_address (agent_config.address, &host, &port);
1225 g_assert (res == 0);
1226 } else {
1227 host = NULL;
1228 port = 0;
1231 conn_fd = -1;
1232 listen_fd = -1;
1234 if (host) {
1235 int hints[] = {
1236 MONO_HINT_IPV4 | MONO_HINT_NUMERIC_HOST,
1237 MONO_HINT_IPV6 | MONO_HINT_NUMERIC_HOST,
1238 MONO_HINT_UNSPECIFIED
1241 mono_network_init ();
1243 for (int i = 0; i < sizeof(hints) / sizeof(int); i++) {
1244 /* Obtain address(es) matching host/port */
1245 s = mono_get_address_info (host, port, hints[i], &result);
1246 if (s == 0)
1247 break;
1249 if (s != 0) {
1250 PRINT_ERROR_MSG ("debugger-agent: Unable to resolve %s:%d: %d\n", host, port, s); // FIXME add portable error conversion functions
1251 exit (1);
1255 if (agent_config.server) {
1256 /* Wait for a connection */
1257 if (!host) {
1258 struct sockaddr_in addr;
1259 socklen_t addrlen;
1261 /* No address, generate one */
1262 sfd = socket (AF_INET, SOCK_STREAM, 0);
1263 if (sfd == -1) {
1264 PRINT_ERROR_MSG ("debugger-agent: Unable to create a socket: %s\n", strerror (get_last_sock_error ()));
1265 exit (1);
1268 /* This will bind the socket to a random port */
1269 res = listen (sfd, 16);
1270 if (res == -1) {
1271 PRINT_ERROR_MSG ("debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1272 exit (1);
1274 listen_fd = sfd;
1276 addrlen = sizeof (addr);
1277 memset (&addr, 0, sizeof (addr));
1278 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1279 g_assert (res == 0);
1281 host = (char*)"127.0.0.1";
1282 port = ntohs (addr.sin_port);
1284 /* Emit the address to stdout */
1285 /* FIXME: Should print another interface, not localhost */
1286 PRINT_MSG ("%s:%d\n", host, port);
1287 } else {
1288 /* Listen on the provided address */
1289 for (rp = result->entries; rp != NULL; rp = rp->next) {
1290 MonoSocketAddress sockaddr;
1291 socklen_t sock_len;
1292 int n = 1;
1294 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1296 sfd = socket (rp->family, rp->socktype,
1297 rp->protocol);
1298 if (sfd == -1)
1299 continue;
1301 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&n, sizeof(n)) == -1)
1302 continue;
1304 res = bind (sfd, &sockaddr.addr, sock_len);
1305 if (res == -1)
1306 continue;
1308 res = listen (sfd, 16);
1309 if (res == -1)
1310 continue;
1311 listen_fd = sfd;
1312 break;
1315 mono_free_address_info (result);
1318 if (agent_config.defer)
1319 return;
1321 PRINT_DEBUG_MSG (1, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout);
1323 if (agent_config.timeout) {
1324 fd_set readfds;
1325 struct timeval tv;
1327 tv.tv_sec = 0;
1328 tv.tv_usec = agent_config.timeout * 1000;
1329 FD_ZERO (&readfds);
1330 FD_SET (sfd, &readfds);
1332 MONO_ENTER_GC_SAFE;
1333 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1334 MONO_EXIT_GC_SAFE;
1336 if (res == 0) {
1337 PRINT_ERROR_MSG ("debugger-agent: Timed out waiting to connect.\n");
1338 exit (1);
1342 conn_fd = socket_transport_accept (sfd);
1343 if (conn_fd == -1)
1344 exit (1);
1346 PRINT_DEBUG_MSG (1, "Accepted connection from client, socket fd=%d.\n", conn_fd);
1347 } else {
1348 /* Connect to the specified address */
1349 /* FIXME: Respect the timeout */
1350 for (rp = result->entries; rp != NULL; rp = rp->next) {
1351 MonoSocketAddress sockaddr;
1352 socklen_t sock_len;
1354 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1356 sfd = socket (rp->family, rp->socktype,
1357 rp->protocol);
1358 if (sfd == -1)
1359 continue;
1361 MONO_ENTER_GC_SAFE;
1362 res = connect (sfd, &sockaddr.addr, sock_len);
1363 MONO_EXIT_GC_SAFE;
1365 if (res != -1)
1366 break; /* Success */
1368 MONO_ENTER_GC_SAFE;
1369 #ifdef HOST_WIN32
1370 closesocket (sfd);
1371 #else
1372 close (sfd);
1373 #endif
1374 MONO_EXIT_GC_SAFE;
1377 if (rp == 0) {
1378 PRINT_ERROR_MSG ("debugger-agent: Unable to connect to %s:%d\n", host, port);
1379 exit (1);
1382 conn_fd = sfd;
1384 mono_free_address_info (result);
1387 if (!transport_handshake ())
1388 exit (1);
1391 static void
1392 socket_transport_close1 (void)
1394 /* This will interrupt the agent thread */
1395 /* Close the read part only so it can still send back replies */
1396 /* Also shut down the connection listener so that we can exit normally */
1397 #ifdef HOST_WIN32
1398 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1399 shutdown (conn_fd, SD_BOTH);
1400 shutdown (listen_fd, SD_BOTH);
1401 closesocket (listen_fd);
1402 #else
1403 shutdown (conn_fd, SHUT_RD);
1404 shutdown (listen_fd, SHUT_RDWR);
1405 MONO_ENTER_GC_SAFE;
1406 close (listen_fd);
1407 MONO_EXIT_GC_SAFE;
1408 #endif
1411 static void
1412 socket_transport_close2 (void)
1414 #ifdef HOST_WIN32
1415 shutdown (conn_fd, SD_BOTH);
1416 #else
1417 shutdown (conn_fd, SHUT_RDWR);
1418 #endif
1421 static void
1422 register_socket_transport (void)
1424 DebuggerTransport trans;
1426 trans.name = "dt_socket";
1427 trans.connect = socket_transport_connect;
1428 trans.close1 = socket_transport_close1;
1429 trans.close2 = socket_transport_close2;
1430 trans.send = socket_transport_send;
1431 trans.recv = socket_transport_recv;
1433 register_transport (&trans);
1437 * socket_fd_transport_connect:
1440 static void
1441 socket_fd_transport_connect (const char *address)
1443 int res;
1445 res = sscanf (address, "%d", &conn_fd);
1446 if (res != 1) {
1447 PRINT_ERROR_MSG ("debugger-agent: socket-fd transport address is invalid: '%s'\n", address);
1448 exit (1);
1451 if (!transport_handshake ())
1452 exit (1);
1455 static void
1456 register_socket_fd_transport (void)
1458 DebuggerTransport trans;
1460 /* This is the same as the 'dt_socket' transport, but receives an already connected socket fd */
1461 trans.name = "socket-fd";
1462 trans.connect = socket_fd_transport_connect;
1463 trans.close1 = socket_transport_close1;
1464 trans.close2 = socket_transport_close2;
1465 trans.send = socket_transport_send;
1466 trans.recv = socket_transport_recv;
1468 register_transport (&trans);
1471 #endif /* DISABLE_SOCKET_TRANSPORT */
1474 * TRANSPORT CODE
1477 #define MAX_TRANSPORTS 16
1479 static DebuggerTransport *transport;
1481 static DebuggerTransport transports [MAX_TRANSPORTS];
1482 static int ntransports;
1484 MONO_API void
1485 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1487 void
1488 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1490 register_transport (trans);
1493 static void
1494 register_transport (DebuggerTransport *trans)
1496 g_assert (ntransports < MAX_TRANSPORTS);
1498 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1499 ntransports ++;
1502 static void
1503 transport_init (void)
1505 int i;
1507 #ifndef DISABLE_SOCKET_TRANSPORT
1508 register_socket_transport ();
1509 register_socket_fd_transport ();
1510 #endif
1512 for (i = 0; i < ntransports; ++i) {
1513 if (!strcmp (agent_config.transport, transports [i].name))
1514 break;
1516 if (i == ntransports) {
1517 PRINT_ERROR_MSG ("debugger-agent: The supported values for the 'transport' option are: ");
1518 for (i = 0; i < ntransports; ++i)
1519 PRINT_ERROR_MSG ("%s'%s'", i > 0 ? ", " : "", transports [i].name);
1520 PRINT_ERROR_MSG ("\n");
1521 exit (1);
1523 transport = &transports [i];
1526 void
1527 transport_connect (const char *address)
1529 transport->connect (address);
1532 static void
1533 transport_close1 (void)
1535 transport->close1 ();
1538 static void
1539 transport_close2 (void)
1541 transport->close2 ();
1544 static int
1545 transport_send (void *buf, int len)
1547 return transport->send (buf, len);
1550 static int
1551 transport_recv (void *buf, int len)
1553 return transport->recv (buf, len);
1556 gboolean
1557 mono_debugger_agent_transport_handshake (void)
1559 return transport_handshake ();
1562 static gboolean
1563 transport_handshake (void)
1565 char handshake_msg [128];
1566 guint8 buf [128];
1567 int res;
1569 disconnected = TRUE;
1571 /* Write handshake message */
1572 sprintf (handshake_msg, "DWP-Handshake");
1574 do {
1575 res = transport_send (handshake_msg, strlen (handshake_msg));
1576 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1578 g_assert (res != -1);
1580 /* Read answer */
1581 res = transport_recv (buf, strlen (handshake_msg));
1582 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg)) != 0)) {
1583 PRINT_ERROR_MSG ("debugger-agent: DWP handshake failed.\n");
1584 return FALSE;
1588 * To support older clients, the client sends its protocol version after connecting
1589 * using a command. Until that is received, default to our protocol version.
1591 major_version = MAJOR_VERSION;
1592 minor_version = MINOR_VERSION;
1593 protocol_version_set = FALSE;
1595 #ifndef DISABLE_SOCKET_TRANSPORT
1596 // FIXME: Move this somewhere else
1598 * Set TCP_NODELAY on the socket so the client receives events/command
1599 * results immediately.
1601 if (conn_fd) {
1602 int flag = 1;
1603 int result = setsockopt (conn_fd,
1604 IPPROTO_TCP,
1605 TCP_NODELAY,
1606 (char *) &flag,
1607 sizeof(int));
1608 g_assert (result >= 0);
1611 set_keepalive ();
1612 #endif
1614 disconnected = FALSE;
1615 return TRUE;
1618 static void
1619 stop_debugger_thread (void)
1621 if (!agent_inited)
1622 return;
1624 transport_close1 ();
1627 * Wait for the thread to exit.
1629 * If we continue with the shutdown without waiting for it, then the client might
1630 * not receive an answer to its last command like a resume.
1632 if (!is_debugger_thread ()) {
1633 do {
1634 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
1635 if (!debugger_thread_exited)
1636 mono_coop_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1637 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
1638 } while (!debugger_thread_exited);
1640 if (debugger_thread_handle)
1641 mono_thread_info_wait_one_handle (debugger_thread_handle, MONO_INFINITE_WAIT, TRUE);
1644 transport_close2 ();
1647 static void
1648 start_debugger_thread (MonoError *error)
1650 MonoInternalThread *thread;
1652 thread = mono_thread_create_internal (mono_get_root_domain (), (gpointer)debugger_thread, NULL, MONO_THREAD_CREATE_FLAGS_DEBUGGER, error);
1653 return_if_nok (error);
1655 /* Is it possible for the thread to be dead alreay ? */
1656 debugger_thread_handle = mono_threads_open_thread_handle (thread->handle);
1657 g_assert (debugger_thread_handle);
1662 * Functions to decode protocol data
1665 static int
1666 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1668 *endbuf = buf + 1;
1669 g_assert (*endbuf <= limit);
1670 return buf [0];
1673 static int
1674 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1676 *endbuf = buf + 4;
1677 g_assert (*endbuf <= limit);
1679 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1682 static gint64
1683 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1685 guint32 high = decode_int (buf, &buf, limit);
1686 guint32 low = decode_int (buf, &buf, limit);
1688 *endbuf = buf;
1690 return ((((guint64)high) << 32) | ((guint64)low));
1693 static int
1694 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1696 return decode_int (buf, endbuf, limit);
1699 static char*
1700 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1702 int len = decode_int (buf, &buf, limit);
1703 char *s;
1705 if (len < 0) {
1706 *endbuf = buf;
1707 return NULL;
1710 s = (char *)g_malloc (len + 1);
1711 g_assert (s);
1713 memcpy (s, buf, len);
1714 s [len] = '\0';
1715 buf += len;
1716 *endbuf = buf;
1718 return s;
1722 * Functions to encode protocol data
1725 static void
1726 buffer_init (Buffer *buf, int size)
1728 buf->buf = (guint8 *)g_malloc (size);
1729 buf->p = buf->buf;
1730 buf->end = buf->buf + size;
1733 static int
1734 buffer_len (Buffer *buf)
1736 return buf->p - buf->buf;
1739 static void
1740 buffer_make_room (Buffer *buf, int size)
1742 if (buf->end - buf->p < size) {
1743 int new_size = buf->end - buf->buf + size + 32;
1744 guint8 *p = (guint8 *)g_realloc (buf->buf, new_size);
1745 size = buf->p - buf->buf;
1746 buf->buf = p;
1747 buf->p = p + size;
1748 buf->end = buf->buf + new_size;
1752 static void
1753 buffer_add_byte (Buffer *buf, guint8 val)
1755 buffer_make_room (buf, 1);
1756 buf->p [0] = val;
1757 buf->p++;
1760 static void
1761 buffer_add_short (Buffer *buf, guint32 val)
1763 buffer_make_room (buf, 2);
1764 buf->p [0] = (val >> 8) & 0xff;
1765 buf->p [1] = (val >> 0) & 0xff;
1766 buf->p += 2;
1769 static void
1770 buffer_add_int (Buffer *buf, guint32 val)
1772 buffer_make_room (buf, 4);
1773 buf->p [0] = (val >> 24) & 0xff;
1774 buf->p [1] = (val >> 16) & 0xff;
1775 buf->p [2] = (val >> 8) & 0xff;
1776 buf->p [3] = (val >> 0) & 0xff;
1777 buf->p += 4;
1780 static void
1781 buffer_add_long (Buffer *buf, guint64 l)
1783 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1784 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1787 static void
1788 buffer_add_id (Buffer *buf, int id)
1790 buffer_add_int (buf, (guint64)id);
1793 static void
1794 buffer_add_data (Buffer *buf, guint8 *data, int len)
1796 buffer_make_room (buf, len);
1797 memcpy (buf->p, data, len);
1798 buf->p += len;
1801 static void
1802 buffer_add_utf16 (Buffer *buf, guint8 *data, int len)
1804 #if G_BYTE_ORDER == G_LITTLE_ENDIAN
1805 buffer_make_room (buf, len);
1806 memcpy (buf->p, data, len);
1807 #else
1808 for (int i=0; i<len; i +=2) {
1809 buf->p[i] = data[i+1];
1810 buf->p[i+1] = data[i];
1812 #endif
1813 buf->p += len;
1816 static void
1817 buffer_add_string (Buffer *buf, const char *str)
1819 int len;
1821 if (str == NULL) {
1822 buffer_add_int (buf, 0);
1823 } else {
1824 len = strlen (str);
1825 buffer_add_int (buf, len);
1826 buffer_add_data (buf, (guint8*)str, len);
1830 static void
1831 buffer_add_byte_array (Buffer *buf, guint8 *bytes, guint32 arr_len)
1833 buffer_add_int (buf, arr_len);
1834 buffer_add_data (buf, bytes, arr_len);
1837 static void
1838 buffer_add_buffer (Buffer *buf, Buffer *data)
1840 buffer_add_data (buf, data->buf, buffer_len (data));
1843 static void
1844 buffer_free (Buffer *buf)
1846 g_free (buf->buf);
1849 static gboolean
1850 send_packet (int command_set, int command, Buffer *data)
1852 Buffer buf;
1853 int len, id;
1854 gboolean res;
1856 id = mono_atomic_inc_i32 (&packet_id);
1858 len = data->p - data->buf + 11;
1859 buffer_init (&buf, len);
1860 buffer_add_int (&buf, len);
1861 buffer_add_int (&buf, id);
1862 buffer_add_byte (&buf, 0); /* flags */
1863 buffer_add_byte (&buf, command_set);
1864 buffer_add_byte (&buf, command);
1865 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1867 res = transport_send (buf.buf, len);
1869 buffer_free (&buf);
1871 return res;
1874 static gboolean
1875 send_reply_packets (int npackets, ReplyPacket *packets)
1877 Buffer buf;
1878 int i, len;
1879 gboolean res;
1881 len = 0;
1882 for (i = 0; i < npackets; ++i)
1883 len += buffer_len (packets [i].data) + 11;
1884 buffer_init (&buf, len);
1885 for (i = 0; i < npackets; ++i) {
1886 buffer_add_int (&buf, buffer_len (packets [i].data) + 11);
1887 buffer_add_int (&buf, packets [i].id);
1888 buffer_add_byte (&buf, 0x80); /* flags */
1889 buffer_add_byte (&buf, (packets [i].error >> 8) & 0xff);
1890 buffer_add_byte (&buf, packets [i].error);
1891 buffer_add_buffer (&buf, packets [i].data);
1894 res = transport_send (buf.buf, len);
1896 buffer_free (&buf);
1898 return res;
1901 static gboolean
1902 send_reply_packet (int id, int error, Buffer *data)
1904 ReplyPacket packet;
1906 memset (&packet, 0, sizeof (packet));
1907 packet.id = id;
1908 packet.error = error;
1909 packet.data = data;
1911 return send_reply_packets (1, &packet);
1914 static void
1915 send_buffered_reply_packets (void)
1917 int i;
1919 send_reply_packets (nreply_packets, reply_packets);
1920 for (i = 0; i < nreply_packets; ++i)
1921 buffer_free (reply_packets [i].data);
1922 PRINT_DEBUG_MSG (1, "[dbg] Sent %d buffered reply packets [at=%lx].\n", nreply_packets, (long)mono_100ns_ticks () / 10000);
1923 nreply_packets = 0;
1926 static void
1927 buffer_reply_packet (int id, int error, Buffer *data)
1929 ReplyPacket *p;
1931 if (nreply_packets == 128)
1932 send_buffered_reply_packets ();
1934 p = &reply_packets [nreply_packets];
1935 p->id = id;
1936 p->error = error;
1937 p->data = g_new0 (Buffer, 1);
1938 buffer_init (p->data, buffer_len (data));
1939 buffer_add_buffer (p->data, data);
1940 nreply_packets ++;
1944 /* Maps objid -> ObjRef */
1945 /* Protected by the loader lock */
1946 static GHashTable *objrefs;
1947 /* Protected by the loader lock */
1948 static GHashTable *obj_to_objref;
1949 /* Protected by the dbg lock */
1950 static MonoGHashTable *suspended_objs;
1954 static void
1955 objrefs_init (void)
1957 objrefs = g_hash_table_new_full (NULL, NULL, NULL, mono_debugger_free_objref);
1958 obj_to_objref = g_hash_table_new (NULL, NULL);
1959 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");
1962 static void
1963 objrefs_cleanup (void)
1965 g_hash_table_destroy (objrefs);
1966 objrefs = NULL;
1970 * Return an ObjRef for OBJ.
1972 static ObjRef*
1973 get_objref (MonoObject *obj)
1975 ObjRef *ref;
1976 GSList *reflist = NULL, *l;
1977 int hash = 0;
1979 if (obj == NULL)
1980 return NULL;
1982 if (suspend_count) {
1984 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1986 dbg_lock ();
1987 mono_g_hash_table_insert_internal (suspended_objs, obj, NULL);
1988 dbg_unlock ();
1991 mono_loader_lock ();
1993 /* FIXME: The tables can grow indefinitely */
1995 if (mono_gc_is_moving ()) {
1997 * Objects can move, so use a hash table mapping hash codes to lists of
1998 * ObjRef structures.
2000 hash = mono_object_hash_internal (obj);
2002 reflist = (GSList *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
2003 for (l = reflist; l; l = l->next) {
2004 ref = (ObjRef *)l->data;
2005 if (ref && mono_gchandle_get_target_internal (ref->handle) == obj) {
2006 mono_loader_unlock ();
2007 return ref;
2010 } else {
2011 /* Use a hash table with masked pointers to internalize object references */
2012 ref = (ObjRef *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
2013 /* ref might refer to a different object with the same addr which was GCd */
2014 if (ref && mono_gchandle_get_target_internal (ref->handle) == obj) {
2015 mono_loader_unlock ();
2016 return ref;
2020 ref = g_new0 (ObjRef, 1);
2021 ref->id = mono_atomic_inc_i32 (&objref_id);
2022 ref->handle = mono_gchandle_new_weakref_internal (obj, FALSE);
2024 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
2026 if (mono_gc_is_moving ()) {
2027 reflist = g_slist_append (reflist, ref);
2028 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
2029 } else {
2030 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
2033 mono_loader_unlock ();
2035 return ref;
2038 static gboolean
2039 true_pred (gpointer key, gpointer value, gpointer user_data)
2041 return TRUE;
2044 static void
2045 clear_suspended_objs (void)
2047 dbg_lock ();
2048 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
2049 dbg_unlock ();
2052 static int
2053 get_objid (MonoObject *obj)
2055 if (!obj)
2056 return 0;
2057 else
2058 return get_objref (obj)->id;
2062 * Set OBJ to the object identified by OBJID.
2063 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
2064 * collected.
2066 static ErrorCode
2067 get_object_allow_null (int objid, MonoObject **obj)
2069 ObjRef *ref;
2071 if (objid == 0) {
2072 *obj = NULL;
2073 return ERR_NONE;
2076 if (!objrefs)
2077 return ERR_INVALID_OBJECT;
2079 mono_loader_lock ();
2081 ref = (ObjRef *)g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
2083 if (ref) {
2084 *obj = mono_gchandle_get_target_internal (ref->handle);
2085 mono_loader_unlock ();
2086 if (!(*obj))
2087 return ERR_INVALID_OBJECT;
2088 return ERR_NONE;
2089 } else {
2090 mono_loader_unlock ();
2091 return ERR_INVALID_OBJECT;
2095 static ErrorCode
2096 get_object (int objid, MonoObject **obj)
2098 ErrorCode err = get_object_allow_null (objid, obj);
2100 if (err != ERR_NONE)
2101 return err;
2102 if (!(*obj))
2103 return ERR_INVALID_OBJECT;
2104 return ERR_NONE;
2107 static int
2108 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
2110 return decode_id (buf, endbuf, limit);
2113 static void
2114 buffer_add_objid (Buffer *buf, MonoObject *o)
2116 buffer_add_id (buf, get_objid (o));
2120 * IDS
2123 typedef enum {
2124 ID_ASSEMBLY = 0,
2125 ID_MODULE = 1,
2126 ID_TYPE = 2,
2127 ID_METHOD = 3,
2128 ID_FIELD = 4,
2129 ID_DOMAIN = 5,
2130 ID_PROPERTY = 6,
2131 ID_NUM
2132 } IdType;
2135 * Represents a runtime structure accessible to the debugger client
2137 typedef struct {
2138 /* Unique id used in the wire protocol */
2139 int id;
2140 /* Domain of the runtime structure, NULL if the domain was unloaded */
2141 MonoDomain *domain;
2142 union {
2143 gpointer val;
2144 MonoClass *klass;
2145 MonoMethod *method;
2146 MonoImage *image;
2147 MonoAssembly *assembly;
2148 MonoClassField *field;
2149 MonoDomain *domain;
2150 MonoProperty *property;
2151 } data;
2152 } Id;
2154 typedef struct {
2155 /* Maps runtime structure -> Id */
2156 /* Protected by the dbg lock */
2157 GHashTable *val_to_id [ID_NUM];
2158 /* Classes whose class load event has been sent */
2159 /* Protected by the loader lock */
2160 GHashTable *loaded_classes;
2161 /* Maps MonoClass->GPtrArray of file names */
2162 GHashTable *source_files;
2163 /* Maps source file basename -> GSList of classes */
2164 GHashTable *source_file_to_class;
2165 /* Same with ignore-case */
2166 GHashTable *source_file_to_class_ignorecase;
2167 } AgentDomainInfo;
2169 /* Maps id -> Id */
2170 /* Protected by the dbg lock */
2171 static GPtrArray *ids [ID_NUM];
2173 static void
2174 ids_init (void)
2176 int i;
2178 for (i = 0; i < ID_NUM; ++i)
2179 ids [i] = g_ptr_array_new ();
2182 static void
2183 ids_cleanup (void)
2185 int i, j;
2187 for (i = 0; i < ID_NUM; ++i) {
2188 if (ids [i]) {
2189 for (j = 0; j < ids [i]->len; ++j)
2190 g_free (g_ptr_array_index (ids [i], j));
2191 g_ptr_array_free (ids [i], TRUE);
2193 ids [i] = NULL;
2197 static void
2198 debugger_agent_free_domain_info (MonoDomain *domain)
2200 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2201 int i, j;
2202 GHashTableIter iter;
2203 GPtrArray *file_names;
2204 char *basename;
2205 GSList *l;
2207 if (info) {
2208 for (i = 0; i < ID_NUM; ++i)
2209 g_hash_table_destroy (info->val_to_id [i]);
2210 g_hash_table_destroy (info->loaded_classes);
2212 g_hash_table_iter_init (&iter, info->source_files);
2213 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2214 for (i = 0; i < file_names->len; ++i)
2215 g_free (g_ptr_array_index (file_names, i));
2216 g_ptr_array_free (file_names, TRUE);
2219 g_hash_table_iter_init (&iter, info->source_file_to_class);
2220 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2221 g_free (basename);
2222 g_slist_free (l);
2225 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2226 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2227 g_free (basename);
2228 g_slist_free (l);
2231 g_free (info);
2234 domain_jit_info (domain)->agent_info = NULL;
2236 /* Clear ids referencing structures in the domain */
2237 dbg_lock ();
2238 for (i = 0; i < ID_NUM; ++i) {
2239 if (ids [i]) {
2240 for (j = 0; j < ids [i]->len; ++j) {
2241 Id *id = (Id *)g_ptr_array_index (ids [i], j);
2242 if (id->domain == domain)
2243 id->domain = NULL;
2247 dbg_unlock ();
2249 mono_de_domain_remove (domain);
2252 static AgentDomainInfo*
2253 get_agent_domain_info (MonoDomain *domain)
2255 AgentDomainInfo *info = NULL;
2256 MonoJitDomainInfo *jit_info = domain_jit_info (domain);
2258 info = (AgentDomainInfo *)jit_info->agent_info;
2260 if (info) {
2261 mono_memory_read_barrier ();
2262 return info;
2265 info = g_new0 (AgentDomainInfo, 1);
2266 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2267 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2268 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2269 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2271 mono_memory_write_barrier ();
2273 gpointer other_info = mono_atomic_cas_ptr (&jit_info->agent_info, info, NULL);
2275 if (other_info != NULL) {
2276 g_hash_table_destroy (info->loaded_classes);
2277 g_hash_table_destroy (info->source_files);
2278 g_hash_table_destroy (info->source_file_to_class);
2279 g_hash_table_destroy (info->source_file_to_class_ignorecase);
2280 g_free (info);
2283 return (AgentDomainInfo *)jit_info->agent_info;
2286 static int
2287 get_id (MonoDomain *domain, IdType type, gpointer val)
2289 Id *id;
2290 AgentDomainInfo *info;
2292 if (val == NULL)
2293 return 0;
2295 info = get_agent_domain_info (domain);
2297 dbg_lock ();
2299 if (info->val_to_id [type] == NULL)
2300 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2302 id = (Id *)g_hash_table_lookup (info->val_to_id [type], val);
2303 if (id) {
2304 dbg_unlock ();
2305 return id->id;
2308 id = g_new0 (Id, 1);
2309 /* Reserve id 0 */
2310 id->id = ids [type]->len + 1;
2311 id->domain = domain;
2312 id->data.val = val;
2314 g_hash_table_insert (info->val_to_id [type], val, id);
2315 g_ptr_array_add (ids [type], id);
2317 dbg_unlock ();
2319 return id->id;
2322 static gpointer
2323 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, ErrorCode *err)
2325 Id *res;
2327 int id = decode_id (buf, endbuf, limit);
2329 *err = ERR_NONE;
2330 if (domain)
2331 *domain = NULL;
2333 if (id == 0)
2334 return NULL;
2336 // FIXME: error handling
2337 dbg_lock ();
2338 g_assert (id > 0 && id <= ids [type]->len);
2340 res = (Id *)g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2341 dbg_unlock ();
2343 if (res->domain == NULL || res->domain->state == MONO_APPDOMAIN_UNLOADED) {
2344 PRINT_DEBUG_MSG (1, "ERR_UNLOADED, id=%d, type=%d.\n", id, type);
2345 *err = ERR_UNLOADED;
2346 return NULL;
2349 if (domain)
2350 *domain = res->domain;
2352 return res->data.val;
2355 static int
2356 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2358 int id = get_id (domain, type, val);
2360 buffer_add_id (buf, id);
2361 return id;
2364 static MonoClass*
2365 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2367 MonoClass *klass;
2369 klass = (MonoClass *)decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2370 if (G_UNLIKELY (log_level >= 2) && klass) {
2371 char *s;
2373 s = mono_type_full_name (m_class_get_byval_arg (klass));
2374 PRINT_DEBUG_MSG (2, "[dbg] recv class [%s]\n", s);
2375 g_free (s);
2377 return klass;
2380 static MonoAssembly*
2381 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2383 return (MonoAssembly *)decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2386 static MonoImage*
2387 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2389 return (MonoImage *)decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2392 static MonoMethod*
2393 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2395 MonoMethod *m;
2397 m = (MonoMethod *)decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2398 if (G_UNLIKELY (log_level >= 2) && m) {
2399 char *s;
2401 s = mono_method_full_name (m, TRUE);
2402 PRINT_DEBUG_MSG (2, "[dbg] recv method [%s]\n", s);
2403 g_free (s);
2405 return m;
2408 static MonoClassField*
2409 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2411 return (MonoClassField *)decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2414 static MonoDomain*
2415 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2417 return (MonoDomain *)decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2420 static MonoProperty*
2421 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2423 return (MonoProperty *)decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2426 static void
2427 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2429 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2430 if (G_UNLIKELY (log_level >= 2) && klass) {
2431 char *s;
2433 s = mono_type_full_name (m_class_get_byval_arg (klass));
2434 if (is_debugger_thread ())
2435 PRINT_DEBUG_MSG (2, "[dbg] send class [%s]\n", s);
2436 else
2437 PRINT_DEBUG_MSG (2, "[%p] send class [%s]\n", (gpointer) (gsize) mono_native_thread_id_get (), s);
2438 g_free (s);
2442 static void
2443 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2445 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2446 if (G_UNLIKELY (log_level >= 2) && method) {
2447 char *s;
2449 s = mono_method_full_name (method, 1);
2450 if (is_debugger_thread ())
2451 PRINT_DEBUG_MSG (2, "[dbg] send method [%s]\n", s);
2452 else
2453 PRINT_DEBUG_MSG (2, "[%p] send method [%s]\n", (gpointer) (gsize) mono_native_thread_id_get (), s);
2454 g_free (s);
2458 static void
2459 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2461 int id;
2463 id = buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2464 if (G_UNLIKELY (log_level >= 2) && assembly)
2465 PRINT_DEBUG_MSG (2, "[dbg] send assembly [%s][%s][%d]\n", assembly->aname.name, domain->friendly_name, id);
2468 static void
2469 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2471 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2474 static void
2475 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2477 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2480 static void
2481 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2483 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2486 static void
2487 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2489 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2492 static void invoke_method (void);
2495 * SUSPEND/RESUME
2498 static MonoJitInfo*
2499 get_top_method_ji (gpointer ip, MonoDomain **domain, gpointer *out_ip)
2501 MonoJitInfo *ji;
2503 if (out_ip)
2504 *out_ip = ip;
2506 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, domain);
2507 if (!ji) {
2508 /* Could be an interpreter method */
2510 MonoLMF *lmf = mono_get_lmf ();
2511 MonoInterpFrameHandle *frame;
2513 g_assert (((gsize)lmf->previous_lmf) & 2);
2514 MonoLMFExt *ext = (MonoLMFExt*)lmf;
2516 g_assert (ext->kind == MONO_LMFEXT_INTERP_EXIT || ext->kind == MONO_LMFEXT_INTERP_EXIT_WITH_CTX);
2517 frame = (MonoInterpFrameHandle*)ext->interp_exit_data;
2518 ji = mini_get_interp_callbacks ()->frame_get_jit_info (frame);
2519 if (domain)
2520 *domain = mono_domain_get ();
2521 if (out_ip)
2522 *out_ip = mini_get_interp_callbacks ()->frame_get_ip (frame);
2524 return ji;
2528 * save_thread_context:
2530 * Set CTX as the current threads context which is used for computing stack traces.
2531 * This function is signal-safe.
2533 static void
2534 save_thread_context (MonoContext *ctx)
2536 DebuggerTlsData *tls;
2538 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2539 g_assert (tls);
2541 if (ctx)
2542 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2543 else
2544 mono_thread_state_init_from_current (&tls->context);
2547 static MonoCoopMutex suspend_mutex;
2549 /* Cond variable used to wait for suspend_count becoming 0 */
2550 static MonoCoopCond suspend_cond;
2552 /* Semaphore used to wait for a thread becoming suspended */
2553 static MonoCoopSem suspend_sem;
2555 static void
2556 suspend_init (void)
2558 mono_coop_mutex_init (&suspend_mutex);
2559 mono_coop_cond_init (&suspend_cond);
2560 mono_coop_sem_init (&suspend_sem, 0);
2563 typedef struct
2565 StackFrameInfo last_frame;
2566 gboolean last_frame_set;
2567 MonoContext ctx;
2568 gpointer lmf;
2569 MonoDomain *domain;
2570 } GetLastFrameUserData;
2572 static gboolean
2573 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2575 GetLastFrameUserData *data = (GetLastFrameUserData *)user_data;
2577 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE || info->type == FRAME_TYPE_TRAMPOLINE)
2578 return FALSE;
2580 if (!data->last_frame_set) {
2581 /* Store the last frame */
2582 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2583 data->last_frame_set = TRUE;
2584 return FALSE;
2585 } else {
2586 /* Store the context/lmf for the frame above the last frame */
2587 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2588 data->lmf = info->lmf;
2589 data->domain = info->domain;
2590 return TRUE;
2594 static void
2595 copy_unwind_state_from_frame_data (MonoThreadUnwindState *to, GetLastFrameUserData *data, gpointer jit_tls)
2597 memcpy (&to->ctx, &data->ctx, sizeof (MonoContext));
2599 to->unwind_data [MONO_UNWIND_DATA_DOMAIN] = data->domain;
2600 to->unwind_data [MONO_UNWIND_DATA_LMF] = data->lmf;
2601 to->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = jit_tls;
2602 to->valid = TRUE;
2606 * thread_interrupt:
2608 * Process interruption of a thread. This should be signal safe.
2610 * This always runs in the debugger thread.
2612 static void
2613 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, MonoJitInfo *ji)
2615 gpointer ip;
2616 MonoNativeThreadId tid;
2618 g_assert (info);
2620 ip = MINI_FTNPTR_TO_ADDR (MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx));
2621 tid = mono_thread_info_get_tid (info);
2623 // FIXME: Races when the thread leaves managed code before hitting a single step
2624 // event.
2626 if (ji && !ji->is_trampoline) {
2627 /* Running managed code, will be suspended by the single step code */
2628 PRINT_DEBUG_MSG (1, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip);
2629 } else {
2631 * Running native code, will be suspended when it returns to/enters
2632 * managed code. Treat it as already suspended.
2633 * This might interrupt the code in mono_de_process_single_step (), we use the
2634 * tls->suspending flag to avoid races when that happens.
2636 if (!tls->suspended && !tls->suspending) {
2637 GetLastFrameUserData data;
2639 // FIXME: printf is not signal safe, but this is only used during
2640 // debugger debugging
2641 if (ip)
2642 PRINT_DEBUG_MSG (1, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip);
2643 //save_thread_context (&ctx);
2645 if (!tls->thread)
2646 /* Already terminated */
2647 return;
2650 * We are in a difficult position: we want to be able to provide stack
2651 * traces for this thread, but we can't use the current ctx+lmf, since
2652 * the thread is still running, so it might return to managed code,
2653 * making these invalid.
2654 * So we start a stack walk and save the first frame, along with the
2655 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2656 * suspended when it returns to managed code, so the parent's ctx should
2657 * remain valid.
2659 MonoThreadUnwindState *state = mono_thread_info_get_suspend_state (info);
2661 data.last_frame_set = FALSE;
2662 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, state, MONO_UNWIND_SIGNAL_SAFE, &data);
2663 if (data.last_frame_set) {
2664 gpointer jit_tls = tls->thread->thread_info->jit_data;
2666 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2668 if (data.last_frame.type == FRAME_TYPE_INTERP_TO_MANAGED || data.last_frame.type == FRAME_TYPE_INTERP_TO_MANAGED_WITH_CTX) {
2670 * Store the current lmf instead of the parent one, since that
2671 * contains the interp exit data.
2673 data.lmf = state->unwind_data [MONO_UNWIND_DATA_LMF];
2676 copy_unwind_state_from_frame_data (&tls->async_state, &data, jit_tls);
2677 /* Don't set tls->context, it could race with the thread processing a breakpoint etc. */
2678 } else {
2679 tls->async_state.valid = FALSE;
2682 mono_memory_barrier ();
2684 tls->suspended = TRUE;
2685 mono_coop_sem_post (&suspend_sem);
2691 * reset_native_thread_suspend_state:
2693 * Reset the suspended flag and state on native threads
2695 static void
2696 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2698 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2700 if (!tls->really_suspended && tls->suspended) {
2701 tls->suspended = FALSE;
2703 * The thread might still be running if it was executing native code, so the state won't be invalided by
2704 * suspend_current ().
2706 tls->context.valid = FALSE;
2707 tls->async_state.valid = FALSE;
2708 invalidate_frames (tls);
2710 tls->resume_count_internal++;
2714 typedef struct {
2715 DebuggerTlsData *tls;
2716 gboolean valid_info;
2717 } InterruptData;
2719 static SuspendThreadResult
2720 debugger_interrupt_critical (MonoThreadInfo *info, gpointer user_data)
2722 InterruptData *data = (InterruptData *)user_data;
2723 MonoJitInfo *ji;
2725 data->valid_info = TRUE;
2726 MonoDomain *domain = (MonoDomain *) mono_thread_info_get_suspend_state (info)->unwind_data [MONO_UNWIND_DATA_DOMAIN];
2727 if (!domain) {
2728 /* not attached */
2729 ji = NULL;
2730 } else {
2731 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);
2734 /* This is signal safe */
2735 thread_interrupt (data->tls, info, ji);
2736 return MonoResumeThread;
2740 * notify_thread:
2742 * Notify a thread that it needs to suspend.
2744 static void
2745 notify_thread (gpointer key, gpointer value, gpointer user_data)
2747 MonoInternalThread *thread = (MonoInternalThread *)key;
2748 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2749 MonoNativeThreadId tid = MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid);
2751 if (mono_thread_internal_is_current (thread) || tls->terminated)
2752 return;
2754 PRINT_DEBUG_MSG (1, "[%p] Interrupting %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)(gsize)tid);
2756 /* This is _not_ equivalent to mono_thread_internal_abort () */
2757 InterruptData interrupt_data = { 0 };
2758 interrupt_data.tls = tls;
2760 mono_thread_info_safe_suspend_and_run ((MonoNativeThreadId)(gsize)thread->tid, FALSE, debugger_interrupt_critical, &interrupt_data);
2761 if (!interrupt_data.valid_info) {
2762 PRINT_DEBUG_MSG (1, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2764 * Attached thread which died without detaching.
2766 tls->terminated = TRUE;
2770 static void
2771 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2773 guint8 *ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
2774 MonoJitInfo *ji;
2775 MonoMethod *method;
2777 if (mono_loader_lock_is_owned_by_self ()) {
2779 * Shortcut for the check in suspend_current (). This speeds up processing
2780 * when executing long running code inside the loader lock, i.e. assembly load
2781 * hooks.
2783 return;
2786 if (is_debugger_thread ())
2787 return;
2789 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2790 if (suspend_count - tls->resume_count > 0)
2791 tls->suspending = TRUE;
2793 PRINT_DEBUG_MSG (1, "[%p] Received single step event for suspending.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2795 if (suspend_count - tls->resume_count == 0) {
2797 * We are executing a single threaded invoke but the single step for
2798 * suspending is still active.
2799 * FIXME: This slows down single threaded invokes.
2801 PRINT_DEBUG_MSG (1, "[%p] Ignored during single threaded invoke.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2802 return;
2805 ji = get_top_method_ji (ip, NULL, NULL);
2806 g_assert (ji);
2807 /* Can't suspend in these methods */
2808 method = jinfo_get_method (ji);
2809 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2810 return;
2812 save_thread_context (ctx);
2814 suspend_current ();
2818 /* Conditionally call process_suspend depending oh the current state */
2819 static gboolean
2820 try_process_suspend (void *the_tls, MonoContext *ctx, gboolean from_breakpoint)
2822 MONO_REQ_GC_UNSAFE_MODE;
2824 DebuggerTlsData *tls = (DebuggerTlsData*)the_tls;
2825 /* if there is a suspend pending that is not executed yes */
2826 if (suspend_count > 0) {
2827 /* Fastpath during invokes, see in process_suspend () */
2828 /* if there is a suspend pending but this thread is already resumed, we shouldn't suspend it again and the breakpoint/ss can run */
2829 if (suspend_count - tls->resume_count == 0)
2830 return FALSE;
2831 /* if there is in a invoke the breakpoint/step should be executed even with the suspend pending */
2832 if (tls->invoke)
2833 return FALSE;
2834 /* with the multithreaded single step check if there is a suspend_count pending in the current thread and not in the vm */
2835 if (from_breakpoint && tls->suspend_count <= tls->resume_count_internal)
2836 return FALSE;
2837 process_suspend (tls, ctx);
2838 return TRUE;
2839 } /* if there isn't any suspend pending, the breakpoint/ss will be executed and will suspend then vm when the event is sent */
2840 return FALSE;
2844 * suspend_vm:
2846 * Increase the suspend count of the VM. While the suspend count is greater
2847 * than 0, runtime threads are suspended at certain points during execution.
2849 static void
2850 suspend_vm (void)
2852 gboolean tp_suspend = FALSE;
2853 mono_loader_lock ();
2855 mono_coop_mutex_lock (&suspend_mutex);
2857 suspend_count ++;
2859 PRINT_DEBUG_MSG (1, "[%p] Suspending vm...\n", (gpointer) (gsize) mono_native_thread_id_get ());
2861 if (suspend_count == 1) {
2862 // FIXME: Is it safe to call this inside the lock ?
2863 mono_de_start_single_stepping ();
2864 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2867 mono_coop_mutex_unlock (&suspend_mutex);
2869 if (suspend_count == 1)
2871 * Suspend creation of new threadpool threads, since they cannot run
2873 tp_suspend = TRUE;
2874 mono_loader_unlock ();
2876 if (tp_suspend)
2877 mono_threadpool_suspend ();
2881 * resume_vm:
2883 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2884 * are resumed.
2886 static void
2887 resume_vm (void)
2889 g_assert (is_debugger_thread ());
2890 gboolean tp_resume = FALSE;
2892 mono_loader_lock ();
2894 mono_coop_mutex_lock (&suspend_mutex);
2896 g_assert (suspend_count > 0);
2897 suspend_count --;
2899 PRINT_DEBUG_MSG (1, "[%p] Resuming vm, suspend count=%d...\n", (gpointer) (gsize) mono_native_thread_id_get (), suspend_count);
2901 if (suspend_count == 0) {
2902 // FIXME: Is it safe to call this inside the lock ?
2903 mono_de_stop_single_stepping ();
2904 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2907 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2908 mono_coop_cond_broadcast (&suspend_cond);
2910 mono_coop_mutex_unlock (&suspend_mutex);
2911 //g_assert (err == 0);
2913 if (suspend_count == 0)
2914 tp_resume = TRUE;
2915 mono_loader_unlock ();
2917 if (tp_resume)
2918 mono_threadpool_resume ();
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 /* Did we crash on an unattached thread? Can't do runtime notifications from there */
5031 if (!mono_thread_info_current_unchecked ())
5032 return;
5034 MONO_ENTER_GC_UNSAFE;
5035 #ifndef DISABLE_CRASH_REPORTING
5036 int suspend_policy;
5037 GSList *events;
5038 EventInfo ei;
5040 if (!agent_config.enabled)
5041 return;
5043 // Don't send the event if the client doesn't expect it
5044 if (!CHECK_PROTOCOL_VERSION (2, 49))
5045 return;
5047 // It doesn't make sense to wait for lldb/gdb to finish if we're not
5048 // actually enabled. Therefore we do the wait here.
5049 sleep (pause);
5051 // Don't heap allocate when we can avoid it
5052 EventRequest request;
5053 memset (&request, 0, sizeof (request));
5054 request.event_kind = EVENT_KIND_CRASH;
5056 gpointer pdata [1];
5057 pdata [0] = &request;
5058 GPtrArray array;
5059 memset (&array, 0, sizeof (array));
5060 array.pdata = pdata;
5061 array.len = 1;
5063 mono_loader_lock ();
5064 events = create_event_list (EVENT_KIND_CRASH, &array, NULL, NULL, &suspend_policy);
5065 mono_loader_unlock ();
5067 ei.dump = json_dump;
5068 ei.hashes = hashes;
5070 g_assert (events != NULL);
5072 process_event (EVENT_KIND_CRASH, &ei, 0, NULL, events, suspend_policy);
5074 // Don't die before it is sent.
5075 sleep (4);
5076 #endif
5077 MONO_EXIT_GC_UNSAFE;
5081 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5083 static void
5084 debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5086 ERROR_DECL (error);
5087 int suspend_policy;
5088 GSList *events;
5089 EventInfo ei;
5091 if (!agent_config.enabled)
5092 return;
5094 memset (&ei, 0, sizeof (ei));
5096 mono_loader_lock ();
5097 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5098 mono_loader_unlock ();
5100 ei.level = level;
5101 if (category) {
5102 ei.category = mono_string_to_utf8_checked_internal (category, error);
5103 mono_error_cleanup (error);
5104 error_init (error);
5106 if (message) {
5107 ei.message = mono_string_to_utf8_checked_internal (message, error);
5108 mono_error_cleanup (error);
5111 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5113 g_free (ei.category);
5114 g_free (ei.message);
5117 static gboolean
5118 debugger_agent_debug_log_is_enabled (void)
5120 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5121 return agent_config.enabled;
5124 static void
5125 debugger_agent_unhandled_exception (MonoException *exc)
5127 int suspend_policy;
5128 GSList *events;
5129 EventInfo ei;
5131 if (!agent_inited)
5132 return;
5134 memset (&ei, 0, sizeof (ei));
5135 ei.exc = (MonoObject*)exc;
5137 mono_loader_lock ();
5138 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5139 mono_loader_unlock ();
5141 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5144 static void
5145 debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5146 MonoContext *catch_ctx, StackFrameInfo *catch_frame)
5148 if (catch_ctx == NULL && catch_frame == NULL && mini_debug_options.suspend_on_unhandled && mono_object_class (exc) != mono_defaults.threadabortexception_class) {
5149 mono_runtime_printf_err ("Unhandled exception, suspending...");
5150 while (1)
5154 int i, j, suspend_policy;
5155 GSList *events;
5156 MonoJitInfo *ji, *catch_ji;
5157 EventInfo ei;
5158 DebuggerTlsData *tls = NULL;
5160 if (thread_to_tls != NULL) {
5161 MonoInternalThread *thread = mono_thread_internal_current ();
5163 mono_loader_lock ();
5164 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5165 mono_loader_unlock ();
5167 if (tls && tls->abort_requested)
5168 return;
5169 if (tls && tls->disable_breakpoints)
5170 return;
5173 memset (&ei, 0, sizeof (ei));
5175 /* Just-In-Time debugging */
5176 if (!catch_ctx) {
5177 if (agent_config.onuncaught && !agent_inited) {
5178 finish_agent_init (FALSE);
5181 * Send an unsolicited EXCEPTION event with a dummy request id.
5183 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5184 ei.exc = (MonoObject*)exc;
5185 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5186 return;
5188 } else if (agent_config.onthrow && !agent_inited) {
5189 GSList *l;
5190 gboolean found = FALSE;
5192 for (l = agent_config.onthrow; l; l = l->next) {
5193 char *ex_type = (char *)l->data;
5194 char *f = mono_type_full_name (m_class_get_byval_arg (exc->object.vtable->klass));
5196 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5197 found = TRUE;
5199 g_free (f);
5202 if (found) {
5203 finish_agent_init (FALSE);
5206 * Send an unsolicited EXCEPTION event with a dummy request id.
5208 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5209 ei.exc = (MonoObject*)exc;
5210 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5211 return;
5215 if (!agent_inited)
5216 return;
5218 ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5219 if (catch_frame)
5220 catch_ji = catch_frame->ji;
5221 else
5222 catch_ji = NULL;
5224 ei.exc = (MonoObject*)exc;
5225 ei.caught = catch_ctx != NULL;
5227 mono_loader_lock ();
5229 /* Treat exceptions which are caught in non-user code as unhandled */
5230 for (i = 0; i < event_requests->len; ++i) {
5231 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
5232 if (req->event_kind != EVENT_KIND_EXCEPTION)
5233 continue;
5235 for (j = 0; j < req->nmodifiers; ++j) {
5236 Modifier *mod = &req->modifiers [j];
5238 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5239 int k;
5240 gboolean found = FALSE;
5241 MonoAssembly **assemblies = mod->data.assemblies;
5243 if (assemblies) {
5244 for (k = 0; assemblies [k]; ++k)
5245 if (assemblies [k] == m_class_get_image (jinfo_get_method (catch_ji)->klass)->assembly)
5246 found = TRUE;
5248 if (!found)
5249 ei.caught = FALSE;
5254 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5255 mono_loader_unlock ();
5257 if (tls && ei.caught && catch_ctx) {
5258 if (catch_frame) {
5259 tls->has_catch_frame = TRUE;
5260 tls->catch_frame = *catch_frame;
5261 } else {
5262 memset (&tls->catch_frame, 0, sizeof (tls->catch_frame));
5266 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5268 if (tls)
5269 tls->has_catch_frame = FALSE;
5272 static void
5273 debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5275 DebuggerTlsData *tls;
5277 if (!agent_inited)
5278 return;
5280 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5281 if (!tls)
5282 return;
5285 * We're about to invoke an exception filter during the first pass of exception handling.
5287 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5288 * 'orig_ctx' is the context where the exception has been thrown.
5291 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5293 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5294 * the call site (line 37) and then continue to Main(), but it would never
5295 * include the throw site (line 32).
5297 * Since exception filters are invoked during the first pass of exception handling,
5298 * the stack frames of the throw site are still intact, so we should include them
5299 * in a stack trace.
5301 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5303 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5304 * but report the location of the 'throw' to the user.
5308 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5311 static void
5312 debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5314 DebuggerTlsData *tls;
5316 if (!agent_inited)
5317 return;
5319 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5320 if (!tls)
5321 return;
5323 tls->filter_state.valid = FALSE;
5326 static void
5327 buffer_add_fixed_array (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5328 gboolean as_vtype, GHashTable *parent_vtypes, gint32 len_fixed_array)
5330 buffer_add_byte (buf, VALUE_TYPE_ID_FIXED_ARRAY);
5331 buffer_add_byte (buf, t->type);
5332 buffer_add_int (buf, len_fixed_array );
5333 for (int i = 0; i < len_fixed_array; i++) {
5334 switch (t->type) {
5335 case MONO_TYPE_BOOLEAN:
5336 case MONO_TYPE_I1:
5337 case MONO_TYPE_U1:
5338 buffer_add_int (buf, ((gint8*)addr)[i]);
5339 break;
5340 case MONO_TYPE_CHAR:
5341 case MONO_TYPE_I2:
5342 case MONO_TYPE_U2:
5343 buffer_add_int (buf, ((gint16*)addr)[i]);
5344 break;
5345 case MONO_TYPE_I4:
5346 case MONO_TYPE_U4:
5347 case MONO_TYPE_R4:
5348 buffer_add_int (buf, ((gint32*)addr)[i]);
5349 break;
5350 case MONO_TYPE_I8:
5351 case MONO_TYPE_U8:
5352 case MONO_TYPE_R8:
5353 buffer_add_long (buf, ((gint64*)addr)[i]);
5354 break;
5355 case MONO_TYPE_PTR: {
5356 gssize val = *(gssize*)addr;
5358 buffer_add_byte (buf, t->type);
5359 buffer_add_long (buf, val);
5360 if (CHECK_PROTOCOL_VERSION(2, 46))
5361 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (t));
5362 break;
5368 * buffer_add_value_full:
5370 * Add the encoding of the value at ADDR described by T to the buffer.
5371 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5372 * vtypes.
5374 static void
5375 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5376 gboolean as_vtype, GHashTable *parent_vtypes, gint32 len_fixed_array)
5378 MonoObject *obj;
5379 gboolean boxed_vtype = FALSE;
5381 if (t->byref) {
5382 if (!(*(void**)addr)) {
5383 /* This can happen with compiler generated locals */
5384 //PRINT_MSG ("%s\n", mono_type_full_name (t));
5385 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5386 return;
5388 g_assert (*(void**)addr);
5389 addr = *(void**)addr;
5392 if (as_vtype) {
5393 switch (t->type) {
5394 case MONO_TYPE_BOOLEAN:
5395 case MONO_TYPE_I1:
5396 case MONO_TYPE_U1:
5397 case MONO_TYPE_CHAR:
5398 case MONO_TYPE_I2:
5399 case MONO_TYPE_U2:
5400 case MONO_TYPE_I4:
5401 case MONO_TYPE_U4:
5402 case MONO_TYPE_R4:
5403 case MONO_TYPE_I8:
5404 case MONO_TYPE_U8:
5405 case MONO_TYPE_R8:
5406 case MONO_TYPE_I:
5407 case MONO_TYPE_U:
5408 case MONO_TYPE_PTR:
5409 goto handle_vtype;
5410 break;
5411 default:
5412 break;
5416 if (len_fixed_array > 1 && t->type != MONO_TYPE_VALUETYPE && CHECK_PROTOCOL_VERSION (2, 53))
5418 buffer_add_fixed_array(buf, t, addr, domain, as_vtype, parent_vtypes, len_fixed_array);
5419 return;
5421 switch (t->type) {
5422 case MONO_TYPE_VOID:
5423 buffer_add_byte (buf, t->type);
5424 break;
5425 case MONO_TYPE_BOOLEAN:
5426 case MONO_TYPE_I1:
5427 case MONO_TYPE_U1:
5428 buffer_add_byte (buf, t->type);
5429 buffer_add_int (buf, *(gint8*)addr);
5430 break;
5431 case MONO_TYPE_CHAR:
5432 case MONO_TYPE_I2:
5433 case MONO_TYPE_U2:
5434 buffer_add_byte (buf, t->type);
5435 buffer_add_int (buf, *(gint16*)addr);
5436 break;
5437 case MONO_TYPE_I4:
5438 case MONO_TYPE_U4:
5439 case MONO_TYPE_R4:
5440 buffer_add_byte (buf, t->type);
5441 buffer_add_int (buf, *(gint32*)addr);
5442 break;
5443 case MONO_TYPE_I8:
5444 case MONO_TYPE_U8:
5445 case MONO_TYPE_R8:
5446 buffer_add_byte (buf, t->type);
5447 buffer_add_long (buf, *(gint64*)addr);
5448 break;
5449 case MONO_TYPE_I:
5450 case MONO_TYPE_U:
5451 /* Treat it as a vtype */
5452 goto handle_vtype;
5453 case MONO_TYPE_PTR:
5454 case MONO_TYPE_FNPTR: {
5455 gssize val = *(gssize*)addr;
5457 buffer_add_byte (buf, t->type);
5458 buffer_add_long (buf, val);
5459 if (CHECK_PROTOCOL_VERSION(2, 46))
5460 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (t));
5461 break;
5463 handle_ref:
5464 case MONO_TYPE_STRING:
5465 case MONO_TYPE_SZARRAY:
5466 case MONO_TYPE_OBJECT:
5467 case MONO_TYPE_CLASS:
5468 case MONO_TYPE_ARRAY:
5469 obj = *(MonoObject**)addr;
5471 if (!obj) {
5472 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5473 } else {
5474 if (m_class_is_valuetype (obj->vtable->klass)) {
5475 t = m_class_get_byval_arg (obj->vtable->klass);
5476 addr = mono_object_unbox_internal (obj);
5477 boxed_vtype = TRUE;
5478 goto handle_vtype;
5479 } else if (m_class_get_rank (obj->vtable->klass)) {
5480 buffer_add_byte (buf, m_class_get_byval_arg (obj->vtable->klass)->type);
5481 } else if (m_class_get_byval_arg (obj->vtable->klass)->type == MONO_TYPE_GENERICINST) {
5482 buffer_add_byte (buf, MONO_TYPE_CLASS);
5483 } else {
5484 buffer_add_byte (buf, m_class_get_byval_arg (obj->vtable->klass)->type);
5486 buffer_add_objid (buf, obj);
5488 break;
5489 handle_vtype:
5490 case MONO_TYPE_VALUETYPE:
5491 case MONO_TYPE_TYPEDBYREF: {
5492 int nfields;
5493 gpointer iter;
5494 MonoClassField *f;
5495 MonoClass *klass = mono_class_from_mono_type_internal (t);
5496 int vtype_index;
5498 if (boxed_vtype) {
5500 * Handle boxed vtypes recursively referencing themselves using fields.
5502 if (!parent_vtypes)
5503 parent_vtypes = g_hash_table_new (NULL, NULL);
5504 vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
5505 if (vtype_index) {
5506 if (CHECK_PROTOCOL_VERSION (2, 33)) {
5507 buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
5508 buffer_add_int (buf, vtype_index - 1);
5509 } else {
5510 /* The client can't handle PARENT_VTYPE */
5511 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5513 break;
5514 } else {
5515 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
5519 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5520 buffer_add_byte (buf, m_class_is_enumtype (klass));
5521 buffer_add_typeid (buf, domain, klass);
5523 nfields = 0;
5524 iter = NULL;
5525 while ((f = mono_class_get_fields_internal (klass, &iter))) {
5526 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5527 continue;
5528 if (mono_field_is_deleted (f))
5529 continue;
5530 nfields ++;
5532 buffer_add_int (buf, nfields);
5534 iter = NULL;
5535 while ((f = mono_class_get_fields_internal (klass, &iter))) {
5536 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5537 continue;
5538 if (mono_field_is_deleted (f))
5539 continue;
5540 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));
5543 if (boxed_vtype) {
5544 g_hash_table_remove (parent_vtypes, addr);
5545 if (g_hash_table_size (parent_vtypes) == 0) {
5546 g_hash_table_destroy (parent_vtypes);
5547 parent_vtypes = NULL;
5550 break;
5552 case MONO_TYPE_GENERICINST:
5553 if (mono_type_generic_inst_is_valuetype (t)) {
5554 goto handle_vtype;
5555 } else {
5556 goto handle_ref;
5558 break;
5559 default:
5560 NOT_IMPLEMENTED;
5564 static void
5565 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5567 buffer_add_value_full (buf, t, addr, domain, FALSE, NULL, 1);
5570 static gboolean
5571 obj_is_of_type (MonoObject *obj, MonoType *t)
5573 MonoClass *klass = obj->vtable->klass;
5574 if (!mono_class_is_assignable_from_internal (mono_class_from_mono_type_internal (t), klass)) {
5575 if (mono_class_is_transparent_proxy (klass)) {
5576 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5577 if (mono_class_is_assignable_from_internal (mono_class_from_mono_type_internal (t), klass)) {
5578 return TRUE;
5581 return FALSE;
5583 return TRUE;
5586 static ErrorCode
5587 decode_value (MonoType *t, MonoDomain *domain, gpointer void_addr, gpointer void_buf, guint8 **endbuf, guint8 *limit, gboolean check_field_datatype);
5589 static ErrorCode
5590 decode_vtype (MonoType *t, MonoDomain *domain, gpointer void_addr, gpointer void_buf, guint8 **endbuf, guint8 *limit, gboolean check_field_datatype)
5592 guint8 *addr = (guint8*)void_addr;
5593 guint8 *buf = (guint8*)void_buf;
5594 gboolean is_enum;
5595 MonoClass *klass;
5596 MonoClassField *f;
5597 int nfields;
5598 gpointer iter = NULL;
5599 MonoDomain *d;
5600 ErrorCode err;
5602 is_enum = decode_byte (buf, &buf, limit);
5603 /* Enums are sent as a normal vtype */
5604 if (is_enum)
5605 return ERR_NOT_IMPLEMENTED;
5606 klass = decode_typeid (buf, &buf, limit, &d, &err);
5607 if (err != ERR_NONE)
5608 return err;
5610 if (t && klass != mono_class_from_mono_type_internal (t)) {
5611 char *name = mono_type_full_name (t);
5612 char *name2 = mono_type_full_name (m_class_get_byval_arg (klass));
5613 PRINT_DEBUG_MSG (1, "[%p] Expected value of type %s, got %s.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, name2);
5614 g_free (name);
5615 g_free (name2);
5616 return ERR_INVALID_ARGUMENT;
5619 nfields = decode_int (buf, &buf, limit);
5620 while ((f = mono_class_get_fields_internal (klass, &iter))) {
5621 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5622 continue;
5623 if (mono_field_is_deleted (f))
5624 continue;
5625 err = decode_value (f->type, domain, mono_vtype_get_field_addr (addr, f), buf, &buf, limit, check_field_datatype);
5626 if (err != ERR_NONE)
5627 return err;
5628 nfields --;
5630 g_assert (nfields == 0);
5632 *endbuf = buf;
5634 return ERR_NONE;
5636 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)
5638 ErrorCode err = ERR_NONE;
5639 int fixedSizeLen = 1;
5640 int newType = MONO_TYPE_END;
5641 if (CHECK_PROTOCOL_VERSION (2, 53)) {
5642 newType = decode_byte (buf, &buf, limit);
5643 fixedSizeLen = decode_int (buf, &buf, limit);
5644 //t->type = newType;
5646 for (int i = 0 ; i < fixedSizeLen; i++) {
5647 switch (newType) {
5648 case MONO_TYPE_BOOLEAN:
5649 ((guint8*)addr)[i] = decode_int (buf, &buf, limit);
5650 break;
5651 case MONO_TYPE_CHAR:
5652 ((gunichar2*)addr)[i] = decode_int (buf, &buf, limit);
5653 break;
5654 case MONO_TYPE_I1:
5655 ((gint8*)addr)[i] = decode_int (buf, &buf, limit);
5656 break;
5657 case MONO_TYPE_U1:
5658 ((guint8*)addr)[i] = decode_int (buf, &buf, limit);
5659 break;
5660 case MONO_TYPE_I2:
5661 ((gint16*)addr)[i] = decode_int (buf, &buf, limit);
5662 break;
5663 case MONO_TYPE_U2:
5664 ((guint16*)addr)[i] = decode_int (buf, &buf, limit);
5665 break;
5666 case MONO_TYPE_I4:
5667 ((gint32*)addr)[i] = decode_int (buf, &buf, limit);
5668 break;
5669 case MONO_TYPE_U4:
5670 ((guint32*)addr)[i] = decode_int (buf, &buf, limit);
5671 break;
5672 case MONO_TYPE_I8:
5673 ((gint64*)addr)[i] = decode_long (buf, &buf, limit);
5674 break;
5675 case MONO_TYPE_U8:
5676 ((guint64*)addr)[i] = decode_long (buf, &buf, limit);
5677 break;
5678 case MONO_TYPE_R4:
5679 ((guint32*)addr)[i] = decode_int (buf, &buf, limit);
5680 break;
5681 case MONO_TYPE_R8:
5682 ((guint64*)addr)[i] = decode_long (buf, &buf, limit);
5683 break;
5686 *endbuf = buf;
5687 return err;
5689 static ErrorCode
5690 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit, gboolean check_field_datatype)
5692 ErrorCode err;
5693 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5694 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5695 !(type == VALUE_TYPE_ID_FIXED_ARRAY) &&
5696 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5697 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5698 !(t->type == MONO_TYPE_FNPTR && type == MONO_TYPE_I8) &&
5699 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE) &&
5700 !(t->type == MONO_TYPE_VALUETYPE && type == MONO_TYPE_OBJECT)) {
5701 char *name = mono_type_full_name (t);
5702 PRINT_DEBUG_MSG (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
5703 g_free (name);
5704 return ERR_INVALID_ARGUMENT;
5706 if (type == VALUE_TYPE_ID_FIXED_ARRAY && t->type != MONO_TYPE_VALUETYPE) {
5707 decode_fixed_size_array_internal (t, type, domain, addr, buf, endbuf, limit, check_field_datatype);
5708 return ERR_NONE;
5711 switch (t->type) {
5712 case MONO_TYPE_BOOLEAN:
5713 *(guint8*)addr = decode_int (buf, &buf, limit);
5714 break;
5715 case MONO_TYPE_CHAR:
5716 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5717 break;
5718 case MONO_TYPE_I1:
5719 *(gint8*)addr = decode_int (buf, &buf, limit);
5720 break;
5721 case MONO_TYPE_U1:
5722 *(guint8*)addr = decode_int (buf, &buf, limit);
5723 break;
5724 case MONO_TYPE_I2:
5725 *(gint16*)addr = decode_int (buf, &buf, limit);
5726 break;
5727 case MONO_TYPE_U2:
5728 *(guint16*)addr = decode_int (buf, &buf, limit);
5729 break;
5730 case MONO_TYPE_I4:
5731 *(gint32*)addr = decode_int (buf, &buf, limit);
5732 break;
5733 case MONO_TYPE_U4:
5734 *(guint32*)addr = decode_int (buf, &buf, limit);
5735 break;
5736 case MONO_TYPE_I8:
5737 *(gint64*)addr = decode_long (buf, &buf, limit);
5738 break;
5739 case MONO_TYPE_U8:
5740 *(guint64*)addr = decode_long (buf, &buf, limit);
5741 break;
5742 case MONO_TYPE_R4:
5743 *(guint32*)addr = decode_int (buf, &buf, limit);
5744 break;
5745 case MONO_TYPE_R8:
5746 *(guint64*)addr = decode_long (buf, &buf, limit);
5747 break;
5748 case MONO_TYPE_PTR:
5749 case MONO_TYPE_FNPTR:
5750 /* We send these as I8, so we get them back as such */
5751 g_assert (type == MONO_TYPE_I8);
5752 *(gssize*)addr = decode_long (buf, &buf, limit);
5753 break;
5754 case MONO_TYPE_GENERICINST:
5755 if (MONO_TYPE_ISSTRUCT (t)) {
5756 /* The client sends these as a valuetype */
5757 goto handle_vtype;
5758 } else {
5759 goto handle_ref;
5761 break;
5762 case MONO_TYPE_I:
5763 case MONO_TYPE_U:
5764 /* We send these as vtypes, so we get them back as such */
5765 g_assert (type == MONO_TYPE_VALUETYPE);
5766 /* Fall through */
5767 handle_vtype:
5768 case MONO_TYPE_VALUETYPE:
5769 if (type == MONO_TYPE_OBJECT) {
5770 /* Boxed vtype */
5771 int objid = decode_objid (buf, &buf, limit);
5772 ErrorCode err;
5773 MonoObject *obj;
5775 err = get_object (objid, (MonoObject**)&obj);
5776 if (err != ERR_NONE)
5777 return err;
5778 if (!obj)
5779 return ERR_INVALID_ARGUMENT;
5780 if (obj->vtable->klass != mono_class_from_mono_type_internal (t)) {
5781 PRINT_DEBUG_MSG (1, "Expected type '%s', got object '%s'\n", mono_type_full_name (t), m_class_get_name (obj->vtable->klass));
5782 return ERR_INVALID_ARGUMENT;
5784 memcpy (addr, mono_object_unbox_internal (obj), mono_class_value_size (obj->vtable->klass, NULL));
5785 } else {
5786 err = decode_vtype (t, domain, addr, buf, &buf, limit, check_field_datatype);
5787 if (err != ERR_NONE)
5788 return err;
5790 break;
5791 handle_ref:
5792 default:
5793 if (MONO_TYPE_IS_REFERENCE (t)) {
5794 if (type == MONO_TYPE_OBJECT) {
5795 int objid = decode_objid (buf, &buf, limit);
5796 ErrorCode err;
5797 MonoObject *obj;
5799 err = get_object (objid, (MonoObject**)&obj);
5800 if (err != ERR_NONE)
5801 return err;
5803 if (obj) {
5804 if (!obj_is_of_type (obj, t)) {
5805 if (check_field_datatype) { //if it's not executing a invoke method check the datatypes.
5806 PRINT_DEBUG_MSG (1, "Expected type '%s', got '%s'\n", mono_type_full_name (t), m_class_get_name (obj->vtable->klass));
5807 return ERR_INVALID_ARGUMENT;
5811 if (obj && obj->vtable->domain != domain)
5812 return ERR_INVALID_ARGUMENT;
5814 mono_gc_wbarrier_generic_store_internal (addr, obj);
5815 } else if (type == VALUE_TYPE_ID_NULL) {
5816 *(MonoObject**)addr = NULL;
5817 } else if (type == MONO_TYPE_VALUETYPE) {
5818 ERROR_DECL (error);
5819 guint8 *buf2;
5820 gboolean is_enum;
5821 MonoClass *klass;
5822 MonoDomain *d;
5823 guint8 *vtype_buf;
5824 int vtype_buf_size;
5826 /* This can happen when round-tripping boxed vtypes */
5828 * Obtain vtype class.
5829 * Same as the beginning of the handle_vtype case above.
5831 buf2 = buf;
5832 is_enum = decode_byte (buf, &buf, limit);
5833 if (is_enum)
5834 return ERR_NOT_IMPLEMENTED;
5835 klass = decode_typeid (buf, &buf, limit, &d, &err);
5836 if (err != ERR_NONE)
5837 return err;
5839 /* Decode the vtype into a temporary buffer, then box it. */
5840 vtype_buf_size = mono_class_value_size (klass, NULL);
5841 vtype_buf = (guint8 *)g_malloc0 (vtype_buf_size);
5842 g_assert (vtype_buf);
5844 buf = buf2;
5845 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit, check_field_datatype);
5846 if (err != ERR_NONE) {
5847 g_free (vtype_buf);
5848 return err;
5850 *(MonoObject**)addr = mono_value_box_checked (d, klass, vtype_buf, error);
5851 mono_error_cleanup (error);
5852 g_free (vtype_buf);
5853 } else {
5854 char *name = mono_type_full_name (t);
5855 PRINT_DEBUG_MSG (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
5856 g_free (name);
5857 return ERR_INVALID_ARGUMENT;
5859 } else if ((t->type == MONO_TYPE_GENERICINST) &&
5860 mono_metadata_generic_class_is_valuetype (t->data.generic_class) &&
5861 m_class_is_enumtype (t->data.generic_class->container_class)){
5862 err = decode_vtype (t, domain, addr, buf, &buf, limit, check_field_datatype);
5863 if (err != ERR_NONE)
5864 return err;
5865 } else {
5866 NOT_IMPLEMENTED;
5868 break;
5872 *endbuf = buf;
5874 return ERR_NONE;
5877 static ErrorCode
5878 decode_value (MonoType *t, MonoDomain *domain, gpointer void_addr, gpointer void_buf, guint8 **endbuf, guint8 *limit, gboolean check_field_datatype)
5880 guint8 *addr = (guint8*)void_addr;
5881 guint8 *buf = (guint8*)void_buf;
5883 ERROR_DECL (error);
5884 ErrorCode err;
5885 int type = decode_byte (buf, &buf, limit);
5887 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type_internal (t))) {
5888 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
5889 guint8 *nullable_buf;
5892 * First try decoding it as a Nullable`1
5894 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit, check_field_datatype);
5895 if (err == ERR_NONE)
5896 return err;
5899 * Then try decoding as a primitive value or null.
5901 if (targ->type == type) {
5902 nullable_buf = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type_internal (targ)));
5903 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit, check_field_datatype);
5904 if (err != ERR_NONE) {
5905 g_free (nullable_buf);
5906 return err;
5908 MonoObject *boxed = mono_value_box_checked (domain, mono_class_from_mono_type_internal (targ), nullable_buf, error);
5909 if (!is_ok (error)) {
5910 mono_error_cleanup (error);
5911 return ERR_INVALID_OBJECT;
5913 mono_nullable_init (addr, boxed, mono_class_from_mono_type_internal (t));
5914 g_free (nullable_buf);
5915 *endbuf = buf;
5916 return ERR_NONE;
5917 } else if (type == VALUE_TYPE_ID_NULL) {
5918 mono_nullable_init (addr, NULL, mono_class_from_mono_type_internal (t));
5919 *endbuf = buf;
5920 return ERR_NONE;
5924 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit, check_field_datatype);
5927 static void
5928 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
5930 guint32 flags;
5931 int reg;
5932 guint8 *addr, *gaddr;
5933 host_mgreg_t reg_val;
5935 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5936 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5938 switch (flags) {
5939 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
5940 reg_val = mono_arch_context_get_int_reg (ctx, reg);
5942 buffer_add_value_full (buf, t, &reg_val, domain, as_vtype, NULL, 1);
5943 break;
5944 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
5945 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
5946 addr += (gint32)var->offset;
5948 //PRINT_MSG ("[R%d+%d] = %p\n", reg, var->offset, addr);
5950 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL, 1);
5951 break;
5952 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
5953 NOT_IMPLEMENTED;
5954 break;
5955 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
5956 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
5957 /* Same as regoffset, but with an indirection */
5958 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
5959 addr += (gint32)var->offset;
5961 gaddr = (guint8 *)*(gpointer*)addr;
5962 g_assert (gaddr);
5963 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL, 1);
5964 break;
5965 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
5966 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
5967 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
5968 MonoGSharedVtMethodRuntimeInfo *info;
5969 guint8 *locals;
5970 int idx;
5972 idx = reg;
5974 g_assert (info_var);
5975 g_assert (locals_var);
5977 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5978 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5979 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
5980 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
5981 addr += (gint32)info_var->offset;
5982 info = (MonoGSharedVtMethodRuntimeInfo *)*(gpointer*)addr;
5983 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
5984 info = (MonoGSharedVtMethodRuntimeInfo *)mono_arch_context_get_int_reg (ctx, reg);
5985 } else {
5986 g_assert_not_reached ();
5988 g_assert (info);
5990 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5991 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
5992 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
5993 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
5994 addr += (gint32)locals_var->offset;
5995 locals = (guint8 *)*(gpointer*)addr;
5996 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
5997 locals = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
5998 } else {
5999 g_assert_not_reached ();
6001 g_assert (locals);
6003 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6005 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL, 1);
6006 break;
6009 default:
6010 g_assert_not_reached ();
6014 static void
6015 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, host_mgreg_t **reg_locations, MonoContext *restore_ctx)
6017 guint32 flags;
6018 int reg, size;
6019 guint8 *addr, *gaddr;
6021 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6022 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6024 if (MONO_TYPE_IS_REFERENCE (t))
6025 size = sizeof (gpointer);
6026 else
6027 size = mono_class_value_size (mono_class_from_mono_type_internal (t), NULL);
6029 switch (flags) {
6030 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6031 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6032 host_mgreg_t v;
6033 gboolean is_signed = FALSE;
6035 if (t->byref) {
6036 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6038 if (addr) {
6039 // FIXME: Write barriers
6040 mono_gc_memmove_atomic (addr, val, size);
6042 break;
6045 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6046 is_signed = TRUE;
6048 switch (size) {
6049 case 1:
6050 v = is_signed ? *(gint8*)val : *(guint8*)val;
6051 break;
6052 case 2:
6053 v = is_signed ? *(gint16*)val : *(guint16*)val;
6054 break;
6055 case 4:
6056 v = is_signed ? *(gint32*)val : *(guint32*)val;
6057 break;
6058 case 8:
6059 v = is_signed ? *(gint64*)val : *(guint64*)val;
6060 break;
6061 default:
6062 g_assert_not_reached ();
6065 /* Set value on the stack or in the return ctx */
6066 if (reg_locations [reg]) {
6067 /* Saved on the stack */
6068 PRINT_DEBUG_MSG (1, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v);
6069 *(reg_locations [reg]) = v;
6070 } else {
6071 /* Not saved yet */
6072 PRINT_DEBUG_MSG (1, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v);
6073 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6076 // FIXME: Move these to mono-context.h/c.
6077 mono_arch_context_set_int_reg (ctx, reg, v);
6078 #else
6079 // FIXME: Can't set registers, so we disable linears
6080 NOT_IMPLEMENTED;
6081 #endif
6082 break;
6084 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6085 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6086 addr += (gint32)var->offset;
6088 //PRINT_MSG ("[R%d+%d] = %p\n", reg, var->offset, addr);
6090 if (t->byref) {
6091 addr = *(guint8**)addr;
6093 if (!addr)
6094 break;
6097 // FIXME: Write barriers
6098 mono_gc_memmove_atomic (addr, val, size);
6099 break;
6100 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6101 /* Same as regoffset, but with an indirection */
6102 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6103 addr += (gint32)var->offset;
6105 gaddr = (guint8 *)*(gpointer*)addr;
6106 g_assert (gaddr);
6107 // FIXME: Write barriers
6108 mono_gc_memmove_atomic (gaddr, val, size);
6109 break;
6110 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6111 NOT_IMPLEMENTED;
6112 break;
6113 default:
6114 g_assert_not_reached ();
6118 static void
6119 set_interp_var (MonoType *t, gpointer addr, guint8 *val_buf)
6121 int size;
6123 if (t->byref) {
6124 addr = *(gpointer*)addr;
6125 g_assert (addr);
6128 if (MONO_TYPE_IS_REFERENCE (t))
6129 size = sizeof (gpointer);
6130 else
6131 size = mono_class_value_size (mono_class_from_mono_type_internal (t), NULL);
6133 memcpy (addr, val_buf, size);
6136 static void
6137 clear_event_request (int req_id, int etype)
6139 int i;
6141 mono_loader_lock ();
6142 for (i = 0; i < event_requests->len; ++i) {
6143 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6145 if (req->id == req_id && req->event_kind == etype) {
6146 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6147 mono_de_clear_breakpoint ((MonoBreakpoint *)req->info);
6148 if (req->event_kind == EVENT_KIND_STEP) {
6149 mono_de_cancel_ss ((SingleStepReq *)req->info);
6151 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6152 mono_de_clear_breakpoint ((MonoBreakpoint *)req->info);
6153 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6154 mono_de_clear_breakpoint ((MonoBreakpoint *)req->info);
6155 g_ptr_array_remove_index_fast (event_requests, i);
6156 g_free (req);
6157 break;
6160 mono_loader_unlock ();
6163 static void
6164 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
6166 int i;
6168 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m_class_get_image (m->data.exc_class)->assembly == assembly)
6169 m->kind = MOD_KIND_NONE;
6170 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6171 int count = 0, match_count = 0, pos;
6172 MonoAssembly **newassemblies;
6174 for (i = 0; m->data.assemblies [i]; ++i) {
6175 count ++;
6176 if (m->data.assemblies [i] == assembly)
6177 match_count ++;
6180 if (match_count) {
6181 // +1 because we don't know length and we use last element to check for end
6182 newassemblies = g_new0 (MonoAssembly*, count - match_count + 1);
6184 pos = 0;
6185 for (i = 0; i < count; ++i)
6186 if (m->data.assemblies [i] != assembly)
6187 newassemblies [pos ++] = m->data.assemblies [i];
6188 g_assert (pos == count - match_count);
6189 g_free (m->data.assemblies);
6190 m->data.assemblies = newassemblies;
6195 static void
6196 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
6198 int i;
6200 for (i = 0; i < req->nmodifiers; ++i) {
6201 Modifier *m = &req->modifiers [i];
6203 clear_assembly_from_modifier (req, m, assembly);
6208 * clear_event_requests_for_assembly:
6210 * Clear all events requests which reference ASSEMBLY.
6212 static void
6213 clear_event_requests_for_assembly (MonoAssembly *assembly)
6215 int i;
6216 gboolean found;
6218 mono_loader_lock ();
6219 found = TRUE;
6220 while (found) {
6221 found = FALSE;
6222 for (i = 0; i < event_requests->len; ++i) {
6223 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6225 clear_assembly_from_modifiers (req, assembly);
6227 if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly ((MonoBreakpoint *)req->info, assembly)) {
6228 clear_event_request (req->id, req->event_kind);
6229 found = TRUE;
6230 break;
6233 if (req->event_kind == EVENT_KIND_STEP)
6234 ss_clear_for_assembly ((SingleStepReq *)req->info, assembly);
6237 mono_loader_unlock ();
6241 * type_comes_from_assembly:
6243 * GHRFunc that returns TRUE if klass comes from assembly
6245 static gboolean
6246 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6248 return mono_type_in_image (m_class_get_byval_arg ((MonoClass*)klass), mono_assembly_get_image_internal ((MonoAssembly*)assembly));
6252 * clear_types_for_assembly:
6254 * Clears types from loaded_classes for a given assembly
6256 static void
6257 clear_types_for_assembly (MonoAssembly *assembly)
6259 MonoDomain *domain = mono_domain_get ();
6260 AgentDomainInfo *info = NULL;
6262 if (!domain || !domain_jit_info (domain))
6263 /* Can happen during shutdown */
6264 return;
6266 info = get_agent_domain_info (domain);
6268 mono_loader_lock ();
6269 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6270 mono_loader_unlock ();
6273 static void
6274 dispose_vm (void)
6276 /* Clear all event requests */
6277 mono_loader_lock ();
6278 while (event_requests->len > 0) {
6279 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
6281 clear_event_request (req->id, req->event_kind);
6283 mono_loader_unlock ();
6285 while (suspend_count > 0)
6286 resume_vm ();
6287 disconnected = TRUE;
6288 vm_start_event_sent = FALSE;
6291 static void
6292 count_thread_check_gc_finalizer (gpointer key, gpointer value, gpointer user_data)
6294 MonoThread *thread = (MonoThread *)value;
6295 gboolean *ret = (gboolean *)user_data;
6296 if (mono_gc_is_finalizer_internal_thread(thread->internal_thread)) {
6297 DebuggerTlsData *tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread->internal_thread);
6298 if (!tls->gc_finalizing) { //GC Finalizer is not running some finalizer code, so ignore it
6299 *ret = TRUE;
6300 return;
6305 static void
6306 add_thread (gpointer key, gpointer value, gpointer user_data)
6308 MonoThread *thread = (MonoThread *)value;
6309 Buffer *buf = (Buffer *)user_data;
6310 if (mono_gc_is_finalizer_internal_thread(thread->internal_thread)) {
6311 DebuggerTlsData *tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread->internal_thread);
6312 if (!tls->gc_finalizing) //GC Finalizer is not running some finalizer code, so ignore it
6313 return;
6315 buffer_add_objid (buf, (MonoObject*)thread);
6319 static ErrorCode
6320 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6322 ERROR_DECL (error);
6323 guint8 *end = invoke->endp;
6324 MonoMethod *m;
6325 int i, nargs;
6326 ErrorCode err;
6327 MonoMethodSignature *sig;
6328 guint8 **arg_buf;
6329 void **args;
6330 MonoObject *this_arg, *res, *exc = NULL;
6331 MonoDomain *domain;
6332 guint8 *this_buf;
6333 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6334 MonoLMFExt ext;
6335 #endif
6336 MonoStopwatch watch;
6338 if (invoke->method) {
6340 * Invoke this method directly, currently only Environment.Exit () is supported.
6342 this_arg = NULL;
6343 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>");
6345 mono_runtime_try_invoke (invoke->method, NULL, invoke->args, &exc, error);
6346 mono_error_assert_ok (error);
6347 g_assert_not_reached ();
6350 m = decode_methodid (p, &p, end, &domain, &err);
6351 if (err != ERR_NONE)
6352 return err;
6353 sig = mono_method_signature_internal (m);
6355 if (m_class_is_valuetype (m->klass))
6356 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6357 else
6358 this_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
6360 if (m->is_generic) {
6361 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));
6362 return ERR_INVALID_ARGUMENT;
6363 } else if (m_class_is_valuetype (m->klass) && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6364 /* Should be null */
6365 int type = decode_byte (p, &p, end);
6366 if (type != VALUE_TYPE_ID_NULL) {
6367 PRINT_DEBUG_MSG (1, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6368 return ERR_INVALID_ARGUMENT;
6370 memset (this_buf, 0, mono_class_instance_size (m->klass));
6371 } else if (m_class_is_valuetype (m->klass) && !strcmp (m->name, ".ctor")) {
6372 /* Could be null */
6373 guint8 *tmp_p;
6375 int type = decode_byte (p, &tmp_p, end);
6376 if (type == VALUE_TYPE_ID_NULL) {
6377 memset (this_buf, 0, mono_class_instance_size (m->klass));
6378 p = tmp_p;
6379 } else {
6380 err = decode_value (m_class_get_byval_arg (m->klass), domain, this_buf, p, &p, end, FALSE);
6381 if (err != ERR_NONE)
6382 return err;
6384 } else {
6385 err = decode_value (m_class_get_byval_arg (m->klass), domain, this_buf, p, &p, end, FALSE);
6386 if (err != ERR_NONE)
6387 return err;
6390 if (!m_class_is_valuetype (m->klass))
6391 this_arg = *(MonoObject**)this_buf;
6392 else
6393 this_arg = NULL;
6395 if (MONO_CLASS_IS_INTERFACE_INTERNAL (m->klass)) {
6396 if (!this_arg) {
6397 PRINT_DEBUG_MSG (1, "[%p] Error: Interface method invoked without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6398 return ERR_INVALID_ARGUMENT;
6400 m = mono_object_get_virtual_method_internal (this_arg, m);
6401 /* Transform this to the format the rest of the code expects it to be */
6402 if (m_class_is_valuetype (m->klass)) {
6403 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6404 memcpy (this_buf, mono_object_unbox_internal (this_arg), mono_class_instance_size (m->klass));
6406 } else if ((m->flags & METHOD_ATTRIBUTE_VIRTUAL) && !m_class_is_valuetype (m->klass) && invoke->flags & INVOKE_FLAG_VIRTUAL) {
6407 if (!this_arg) {
6408 PRINT_DEBUG_MSG (1, "[%p] Error: invoke with INVOKE_FLAG_VIRTUAL flag set without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6409 return ERR_INVALID_ARGUMENT;
6411 m = mono_object_get_virtual_method_internal (this_arg, m);
6412 if (m_class_is_valuetype (m->klass)) {
6413 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6414 memcpy (this_buf, mono_object_unbox_internal (this_arg), mono_class_instance_size (m->klass));
6418 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>");
6420 if (this_arg && this_arg->vtable->domain != domain)
6421 NOT_IMPLEMENTED;
6423 if (!m_class_is_valuetype (m->klass) && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this_arg) {
6424 if (!strcmp (m->name, ".ctor")) {
6425 if (mono_class_is_abstract (m->klass))
6426 return ERR_INVALID_ARGUMENT;
6427 else {
6428 ERROR_DECL (error);
6429 this_arg = mono_object_new_checked (domain, m->klass, error);
6430 if (!is_ok (error)) {
6431 mono_error_cleanup (error);
6432 return ERR_INVALID_ARGUMENT;
6435 } else {
6436 return ERR_INVALID_ARGUMENT;
6440 if (this_arg && !obj_is_of_type (this_arg, m_class_get_byval_arg (m->klass)))
6441 return ERR_INVALID_ARGUMENT;
6443 nargs = decode_int (p, &p, end);
6444 if (nargs != sig->param_count)
6445 return ERR_INVALID_ARGUMENT;
6446 /* Use alloca to get gc tracking */
6447 arg_buf = (guint8 **)g_alloca (nargs * sizeof (gpointer));
6448 memset (arg_buf, 0, nargs * sizeof (gpointer));
6449 args = (gpointer *)g_alloca (nargs * sizeof (gpointer));
6450 for (i = 0; i < nargs; ++i) {
6451 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6452 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end, TRUE);
6453 if (err != ERR_NONE)
6454 break;
6455 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6456 NOT_IMPLEMENTED;
6458 if (sig->params [i]->byref) {
6459 arg_buf [i] = g_newa (guint8, sizeof (gpointer));
6460 *(gpointer*)arg_buf [i] = args [i];
6461 args [i] = arg_buf [i];
6463 } else {
6464 MonoClass *arg_class = mono_class_from_mono_type_internal (sig->params [i]);
6465 arg_buf [i] = (guint8 *)g_alloca (mono_class_instance_size (arg_class));
6466 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end, TRUE);
6467 if (err != ERR_NONE)
6468 break;
6469 if (mono_class_is_nullable (arg_class)) {
6470 args [i] = mono_nullable_box (arg_buf [i], arg_class, error);
6471 mono_error_assert_ok (error);
6472 } else {
6473 args [i] = arg_buf [i];
6478 if (i < nargs)
6479 return err;
6481 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6482 tls->disable_breakpoints = TRUE;
6483 else
6484 tls->disable_breakpoints = FALSE;
6487 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6489 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6490 if (invoke->has_ctx) {
6491 /* Setup our lmf */
6492 memset (&ext, 0, sizeof (ext));
6493 ext.kind = MONO_LMFEXT_DEBUGGER_INVOKE;
6494 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6496 mono_push_lmf (&ext);
6498 #endif
6500 mono_stopwatch_start (&watch);
6501 res = mono_runtime_try_invoke (m, m_class_is_valuetype (m->klass) ? (gpointer) this_buf : (gpointer) this_arg, args, &exc, error);
6502 if (!is_ok (error) && exc == NULL) {
6503 exc = (MonoObject*) mono_error_convert_to_exception (error);
6504 } else {
6505 mono_error_cleanup (error); /* FIXME report error */
6507 mono_stopwatch_stop (&watch);
6508 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));
6509 if (exc) {
6510 buffer_add_byte (buf, 0);
6511 buffer_add_value (buf, mono_get_object_type (), &exc, domain);
6512 } else {
6513 gboolean out_this = FALSE;
6514 gboolean out_args = FALSE;
6516 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_THIS) && CHECK_PROTOCOL_VERSION (2, 35))
6517 out_this = TRUE;
6518 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_ARGS) && CHECK_PROTOCOL_VERSION (2, 35))
6519 out_args = TRUE;
6520 buffer_add_byte (buf, 1 + (out_this ? 2 : 0) + (out_args ? 4 : 0));
6521 if (m->string_ctor) {
6522 buffer_add_value (buf, m_class_get_byval_arg (mono_get_string_class ()), &res, domain);
6523 } else if (sig->ret->type == MONO_TYPE_VOID && !m->string_ctor) {
6524 if (!strcmp (m->name, ".ctor")) {
6525 if (!m_class_is_valuetype (m->klass))
6526 buffer_add_value (buf, mono_get_object_type (), &this_arg, domain);
6527 else
6528 buffer_add_value (buf, m_class_get_byval_arg (m->klass), this_buf, domain);
6529 } else {
6530 buffer_add_value (buf, mono_get_void_type (), NULL, domain);
6532 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6533 if (sig->ret->byref) {
6534 MonoType* ret_byval = m_class_get_byval_arg (mono_class_from_mono_type_internal (sig->ret));
6535 buffer_add_value (buf, ret_byval, &res, domain);
6536 } else {
6537 buffer_add_value (buf, sig->ret, &res, domain);
6539 } 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) {
6540 if (mono_class_is_nullable (mono_class_from_mono_type_internal (sig->ret))) {
6541 MonoClass *k = mono_class_from_mono_type_internal (sig->ret);
6542 guint8 *nullable_buf = (guint8 *)g_alloca (mono_class_value_size (k, NULL));
6544 g_assert (nullable_buf);
6545 mono_nullable_init (nullable_buf, res, k);
6546 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6547 } else {
6548 g_assert (res);
6550 if (sig->ret->byref) {
6551 MonoType* ret_byval = m_class_get_byval_arg (mono_class_from_mono_type_internal (sig->ret));
6552 buffer_add_value (buf, ret_byval, mono_object_unbox_internal (res), domain);
6553 } else {
6554 buffer_add_value (buf, sig->ret, mono_object_unbox_internal (res), domain);
6557 } else {
6558 NOT_IMPLEMENTED;
6560 if (out_this)
6561 /* Return the new value of the receiver after the call */
6562 buffer_add_value (buf, m_class_get_byval_arg (m->klass), this_buf, domain);
6563 if (out_args) {
6564 buffer_add_int (buf, nargs);
6565 for (i = 0; i < nargs; ++i) {
6566 if (MONO_TYPE_IS_REFERENCE (sig->params [i]))
6567 buffer_add_value (buf, sig->params [i], &args [i], domain);
6568 else if (sig->params [i]->byref)
6569 /* add_value () does an indirection */
6570 buffer_add_value (buf, sig->params [i], &arg_buf [i], domain);
6571 else
6572 buffer_add_value (buf, sig->params [i], arg_buf [i], domain);
6577 tls->disable_breakpoints = FALSE;
6579 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6580 if (invoke->has_ctx)
6581 mono_pop_lmf ((MonoLMF*)&ext);
6582 #endif
6584 *endp = p;
6585 // FIXME: byref arguments
6586 // FIXME: varargs
6587 return ERR_NONE;
6591 * invoke_method:
6593 * Invoke the method given by tls->pending_invoke in the current thread.
6595 static void
6596 invoke_method (void)
6598 DebuggerTlsData *tls;
6599 InvokeData *invoke;
6600 int id;
6601 int i, mindex;
6602 ErrorCode err;
6603 Buffer buf;
6604 MonoContext restore_ctx;
6605 guint8 *p;
6607 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
6608 g_assert (tls);
6611 * Store the `InvokeData *' in `tls->invoke' until we're done with
6612 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6615 mono_loader_lock ();
6617 invoke = tls->pending_invoke;
6618 g_assert (invoke);
6619 tls->pending_invoke = NULL;
6621 invoke->last_invoke = tls->invoke;
6622 tls->invoke = invoke;
6624 mono_loader_unlock ();
6626 tls->frames_up_to_date = FALSE;
6628 id = invoke->id;
6630 p = invoke->p;
6631 err = ERR_NONE;
6632 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6633 buffer_init (&buf, 128);
6635 if (err) {
6636 /* Fail the other invokes as well */
6637 } else {
6638 err = do_invoke_method (tls, &buf, invoke, p, &p);
6641 if (tls->abort_requested) {
6642 if (CHECK_PROTOCOL_VERSION (2, 42))
6643 err = ERR_INVOKE_ABORTED;
6646 /* Start suspending before sending the reply */
6647 if (mindex == invoke->nmethods - 1) {
6648 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6649 for (i = 0; i < invoke->suspend_count; ++i)
6650 suspend_vm ();
6654 send_reply_packet (id, err, &buf);
6656 buffer_free (&buf);
6659 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6661 if (invoke->has_ctx)
6662 save_thread_context (&restore_ctx);
6664 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6665 g_assert (tls->resume_count);
6666 tls->resume_count -= invoke->suspend_count;
6669 PRINT_DEBUG_MSG (1, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer) (gsize) mono_native_thread_id_get (), err, tls->resume_count);
6672 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6674 * It is possible that mono_thread_internal_abort () was called
6675 * after the mono_runtime_invoke_checked() already returned, but it doesn't matter
6676 * because we reset the abort here.
6679 mono_loader_lock ();
6681 if (tls->abort_requested)
6682 mono_thread_internal_reset_abort (tls->thread);
6684 tls->invoke = tls->invoke->last_invoke;
6685 tls->abort_requested = FALSE;
6687 mono_loader_unlock ();
6689 g_free (invoke->p);
6690 g_free (invoke);
6693 static gboolean
6694 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6696 MonoThread *thread = (MonoThread *)value;
6697 DebuggerTlsData *tls;
6698 gboolean res;
6700 mono_loader_lock ();
6701 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
6702 g_assert (tls);
6703 res = tls->really_suspended;
6704 mono_loader_unlock ();
6706 return res;
6709 static GPtrArray*
6710 get_source_files_for_type (MonoClass *klass)
6712 gpointer iter = NULL;
6713 MonoMethod *method;
6714 MonoDebugSourceInfo *sinfo;
6715 GPtrArray *files;
6716 int i, j;
6718 files = g_ptr_array_new ();
6720 while ((method = mono_class_get_methods (klass, &iter))) {
6721 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6722 GPtrArray *source_file_list;
6724 if (minfo) {
6725 mono_debug_get_seq_points (minfo, NULL, &source_file_list, NULL, NULL, NULL);
6726 for (j = 0; j < source_file_list->len; ++j) {
6727 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, j);
6728 for (i = 0; i < files->len; ++i)
6729 if (!strcmp ((const char*)g_ptr_array_index (files, i), (const char*)sinfo->source_file))
6730 break;
6731 if (i == files->len)
6732 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6734 g_ptr_array_free (source_file_list, TRUE);
6738 return files;
6742 typedef struct {
6743 MonoTypeNameParse *info;
6744 gboolean ignore_case;
6745 GPtrArray *res_classes;
6746 GPtrArray *res_domains;
6747 } GetTypesArgs;
6749 static void
6750 get_types (gpointer key, gpointer value, gpointer user_data)
6752 MonoAssembly *ass;
6753 gboolean type_resolve;
6754 MonoType *t;
6755 GSList *tmp;
6756 MonoDomain *domain = (MonoDomain*)key;
6758 if (mono_domain_is_unloading (domain))
6759 return;
6761 MonoAssemblyLoadContext *alc = mono_domain_default_alc (domain);
6762 GetTypesArgs *ud = (GetTypesArgs*)user_data;
6764 mono_domain_assemblies_lock (domain);
6765 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6766 ass = (MonoAssembly *)tmp->data;
6768 if (ass->image) {
6769 ERROR_DECL (probe_type_error);
6770 /* FIXME really okay to call while holding locks? */
6771 t = mono_reflection_get_type_checked (alc, ass->image, ass->image, ud->info, ud->ignore_case, TRUE, &type_resolve, probe_type_error);
6772 mono_error_cleanup (probe_type_error);
6773 if (t) {
6774 g_ptr_array_add (ud->res_classes, mono_type_get_class_internal (t));
6775 g_ptr_array_add (ud->res_domains, domain);
6779 mono_domain_assemblies_unlock (domain);
6782 typedef struct {
6783 gboolean ignore_case;
6784 char *basename;
6785 GPtrArray *res_classes;
6786 GPtrArray *res_domains;
6787 } GetTypesForSourceFileArgs;
6789 static void
6790 get_types_for_source_file (gpointer key, gpointer value, gpointer user_data)
6792 GHashTableIter iter;
6793 GSList *class_list = NULL;
6794 MonoClass *klass = NULL;
6795 GPtrArray *files = NULL;
6797 GetTypesForSourceFileArgs *ud = (GetTypesForSourceFileArgs*)user_data;
6798 MonoDomain *domain = (MonoDomain*)key;
6800 if (mono_domain_is_unloading (domain))
6801 return;
6803 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
6805 /* Update 'source_file_to_class' cache */
6806 g_hash_table_iter_init (&iter, info->loaded_classes);
6807 while (g_hash_table_iter_next (&iter, NULL, (void**)&klass)) {
6808 if (!g_hash_table_lookup (info->source_files, klass)) {
6809 files = get_source_files_for_type (klass);
6810 g_hash_table_insert (info->source_files, klass, files);
6812 for (int i = 0; i < files->len; ++i) {
6813 char *s = (char *)g_ptr_array_index (files, i);
6814 char *s2 = dbg_path_get_basename (s);
6815 char *s3;
6817 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, s2);
6818 if (!class_list) {
6819 class_list = g_slist_prepend (class_list, klass);
6820 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
6821 } else {
6822 class_list = g_slist_prepend (class_list, klass);
6823 g_hash_table_insert (info->source_file_to_class, s2, class_list);
6826 /* The _ignorecase hash contains the lowercase path */
6827 s3 = strdup_tolower (s2);
6828 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
6829 if (!class_list) {
6830 class_list = g_slist_prepend (class_list, klass);
6831 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
6832 } else {
6833 class_list = g_slist_prepend (class_list, klass);
6834 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
6837 g_free (s2);
6838 g_free (s3);
6843 if (ud->ignore_case) {
6844 char *s;
6846 s = strdup_tolower (ud->basename);
6847 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
6848 g_free (s);
6849 } else {
6850 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, ud->basename);
6853 for (GSList *l = class_list; l; l = l->next) {
6854 klass = (MonoClass *)l->data;
6856 g_ptr_array_add (ud->res_classes, klass);
6857 g_ptr_array_add (ud->res_domains, domain);
6861 static void
6862 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
6864 if (val && val->vtable->klass == mono_defaults.runtimetype_class) {
6865 /* Special case these so the client doesn't have to handle Type objects */
6867 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
6868 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (((MonoReflectionType*)val)->type));
6869 } else if (MONO_TYPE_IS_REFERENCE (t))
6870 buffer_add_value (buf, t, &val, domain);
6871 else
6872 buffer_add_value (buf, t, mono_object_unbox_internal (val), domain);
6875 static ErrorCode
6876 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
6878 int i, j;
6879 int nattrs = 0;
6881 if (!cinfo) {
6882 buffer_add_int (buf, 0);
6883 return ERR_NONE;
6886 SETUP_ICALL_FUNCTION;
6888 for (i = 0; i < cinfo->num_attrs; ++i) {
6889 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
6890 nattrs ++;
6892 buffer_add_int (buf, nattrs);
6894 for (i = 0; i < cinfo->num_attrs; ++i) {
6895 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
6896 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
6897 MonoArray *typed_args, *named_args;
6898 MonoArrayHandleOut typed_args_h, named_args_h;
6899 MonoObjectHandle val_h;
6900 MonoType *t;
6901 CattrNamedArg *arginfo = NULL;
6902 ERROR_DECL (error);
6904 SETUP_ICALL_FRAME;
6905 typed_args_h = MONO_HANDLE_NEW (MonoArray, NULL);
6906 named_args_h = MONO_HANDLE_NEW (MonoArray, NULL);
6907 val_h = MONO_HANDLE_NEW (MonoObject, NULL);
6909 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, typed_args_h, named_args_h, &arginfo, error);
6910 if (!is_ok (error)) {
6911 PRINT_DEBUG_MSG (2, "[dbg] mono_reflection_create_custom_attr_data_args () failed with: '%s'\n", mono_error_get_message (error));
6912 mono_error_cleanup (error);
6913 CLEAR_ICALL_FRAME;
6914 return ERR_LOADER_ERROR;
6916 typed_args = MONO_HANDLE_RAW (typed_args_h);
6917 named_args = MONO_HANDLE_RAW (named_args_h);
6919 buffer_add_methodid (buf, domain, attr->ctor);
6921 /* Ctor args */
6922 if (typed_args) {
6923 buffer_add_int (buf, mono_array_length_internal (typed_args));
6924 for (j = 0; j < mono_array_length_internal (typed_args); ++j) {
6925 MonoObject *val = mono_array_get_internal (typed_args, MonoObject*, j);
6926 MONO_HANDLE_ASSIGN_RAW (val_h, val);
6928 t = mono_method_signature_internal (attr->ctor)->params [j];
6930 buffer_add_cattr_arg (buf, t, domain, val);
6932 } else {
6933 buffer_add_int (buf, 0);
6936 /* Named args */
6937 if (named_args) {
6938 buffer_add_int (buf, mono_array_length_internal (named_args));
6940 for (j = 0; j < mono_array_length_internal (named_args); ++j) {
6941 MonoObject *val = mono_array_get_internal (named_args, MonoObject*, j);
6942 MONO_HANDLE_ASSIGN_RAW (val_h, val);
6944 if (arginfo [j].prop) {
6945 buffer_add_byte (buf, 0x54);
6946 buffer_add_propertyid (buf, domain, arginfo [j].prop);
6947 } else if (arginfo [j].field) {
6948 buffer_add_byte (buf, 0x53);
6949 buffer_add_fieldid (buf, domain, arginfo [j].field);
6950 } else {
6951 g_assert_not_reached ();
6954 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
6956 } else {
6957 buffer_add_int (buf, 0);
6959 g_free (arginfo);
6961 CLEAR_ICALL_FRAME;
6965 return ERR_NONE;
6968 static void add_error_string (Buffer *buf, const char *str)
6970 if (CHECK_PROTOCOL_VERSION (2, 56))
6971 buffer_add_string (buf, str);
6974 static ErrorCode
6975 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6977 switch (command) {
6978 case CMD_VM_VERSION: {
6979 char *build_info, *version;
6981 build_info = mono_get_runtime_build_info ();
6982 version = g_strdup_printf ("mono %s", build_info);
6984 buffer_add_string (buf, version); /* vm version */
6985 buffer_add_int (buf, MAJOR_VERSION);
6986 buffer_add_int (buf, MINOR_VERSION);
6987 g_free (build_info);
6988 g_free (version);
6989 break;
6991 case CMD_VM_SET_PROTOCOL_VERSION: {
6992 major_version = decode_int (p, &p, end);
6993 minor_version = decode_int (p, &p, end);
6994 protocol_version_set = TRUE;
6995 PRINT_DEBUG_MSG (1, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version);
6996 break;
6998 case CMD_VM_ALL_THREADS: {
6999 // FIXME: Domains
7000 gboolean remove_gc_finalizing = FALSE;
7001 mono_loader_lock ();
7002 int count = mono_g_hash_table_size (tid_to_thread_obj);
7003 mono_g_hash_table_foreach (tid_to_thread_obj, count_thread_check_gc_finalizer, &remove_gc_finalizing);
7004 if (remove_gc_finalizing)
7005 count--;
7006 buffer_add_int (buf, count);
7007 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
7009 mono_loader_unlock ();
7010 break;
7012 case CMD_VM_SUSPEND:
7013 suspend_vm ();
7014 wait_for_suspend ();
7015 break;
7016 case CMD_VM_RESUME:
7017 if (suspend_count == 0) {
7018 if (agent_config.defer && !agent_config.suspend)
7019 // Workaround for issue in debugger-libs when running in defer attach mode.
7020 break;
7021 else
7022 return ERR_NOT_SUSPENDED;
7024 resume_vm ();
7025 clear_suspended_objs ();
7026 break;
7027 case CMD_VM_DISPOSE:
7028 dispose_vm ();
7029 break;
7030 case CMD_VM_EXIT: {
7031 MonoInternalThread *thread;
7032 DebuggerTlsData *tls;
7033 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7034 MonoClass *env_class;
7035 #endif
7036 MonoMethod *exit_method = NULL;
7037 gpointer *args;
7038 int exit_code;
7040 exit_code = decode_int (p, &p, end);
7042 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
7044 /* Have to send a reply before exiting */
7045 send_reply_packet (id, 0, buf);
7047 /* Clear all event requests */
7048 mono_loader_lock ();
7049 while (event_requests->len > 0) {
7050 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
7052 clear_event_request (req->id, req->event_kind);
7054 mono_loader_unlock ();
7057 * The JDWP documentation says that the shutdown is not orderly. It doesn't
7058 * specify whenever a VM_DEATH event is sent. We currently do an orderly
7059 * shutdown by hijacking a thread to execute Environment.Exit (). This is
7060 * better than doing the shutdown ourselves, since it avoids various races.
7063 suspend_vm ();
7064 wait_for_suspend ();
7066 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7067 env_class = mono_class_try_load_from_name (mono_defaults.corlib, "System", "Environment");
7068 if (env_class) {
7069 ERROR_DECL (error);
7070 exit_method = mono_class_get_method_from_name_checked (env_class, "Exit", 1, 0, error);
7071 mono_error_assert_ok (error);
7073 #endif
7075 mono_loader_lock ();
7076 thread = (MonoInternalThread *)mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
7077 mono_loader_unlock ();
7079 if (thread && exit_method) {
7080 mono_loader_lock ();
7081 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
7082 mono_loader_unlock ();
7084 args = g_new0 (gpointer, 1);
7085 args [0] = g_malloc (sizeof (int));
7086 *(int*)(args [0]) = exit_code;
7088 tls->pending_invoke = g_new0 (InvokeData, 1);
7089 tls->pending_invoke->method = exit_method;
7090 tls->pending_invoke->args = args;
7091 tls->pending_invoke->nmethods = 1;
7093 while (suspend_count > 0)
7094 resume_vm ();
7095 } else {
7097 * No thread found, do it ourselves.
7098 * FIXME: This can race with normal shutdown etc.
7100 while (suspend_count > 0)
7101 resume_vm ();
7103 if (!mono_runtime_try_shutdown ())
7104 break;
7106 mono_environment_exitcode_set (exit_code);
7108 /* Suspend all managed threads since the runtime is going away */
7109 PRINT_DEBUG_MSG (1, "Suspending all threads...\n");
7110 mono_thread_suspend_all_other_threads ();
7111 PRINT_DEBUG_MSG (1, "Shutting down the runtime...\n");
7112 mono_runtime_quit_internal ();
7113 transport_close2 ();
7114 PRINT_DEBUG_MSG (1, "Exiting...\n");
7116 exit (exit_code);
7118 break;
7120 case CMD_VM_INVOKE_METHOD:
7121 case CMD_VM_INVOKE_METHODS: {
7122 int objid = decode_objid (p, &p, end);
7123 MonoThread *thread;
7124 DebuggerTlsData *tls;
7125 int i, count, flags, nmethods;
7126 ErrorCode err;
7128 err = get_object (objid, (MonoObject**)&thread);
7129 if (err != ERR_NONE)
7130 return err;
7132 flags = decode_int (p, &p, end);
7134 if (command == CMD_VM_INVOKE_METHODS)
7135 nmethods = decode_int (p, &p, end);
7136 else
7137 nmethods = 1;
7139 // Wait for suspending if it already started
7140 if (suspend_count)
7141 wait_for_suspend ();
7142 if (!is_suspended ())
7143 return ERR_NOT_SUSPENDED;
7145 mono_loader_lock ();
7146 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7147 mono_loader_unlock ();
7148 g_assert (tls);
7150 if (!tls->really_suspended)
7151 /* The thread is still running native code, can't do invokes */
7152 return ERR_NOT_SUSPENDED;
7155 * Store the invoke data into tls, the thread will execute it after it is
7156 * resumed.
7158 if (tls->pending_invoke)
7159 return ERR_NOT_SUSPENDED;
7160 tls->pending_invoke = g_new0 (InvokeData, 1);
7161 tls->pending_invoke->id = id;
7162 tls->pending_invoke->flags = flags;
7163 tls->pending_invoke->p = (guint8 *)g_malloc (end - p);
7164 memcpy (tls->pending_invoke->p, p, end - p);
7165 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
7166 tls->pending_invoke->suspend_count = suspend_count;
7167 tls->pending_invoke->nmethods = nmethods;
7169 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
7170 resume_thread (THREAD_TO_INTERNAL (thread));
7172 else {
7173 count = suspend_count;
7174 for (i = 0; i < count; ++i)
7175 resume_vm ();
7177 break;
7179 case CMD_VM_ABORT_INVOKE: {
7180 int objid = decode_objid (p, &p, end);
7181 MonoThread *thread;
7182 DebuggerTlsData *tls;
7183 int invoke_id;
7184 ErrorCode err;
7186 err = get_object (objid, (MonoObject**)&thread);
7187 if (err != ERR_NONE)
7188 return err;
7190 invoke_id = decode_int (p, &p, end);
7192 mono_loader_lock ();
7193 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7194 g_assert (tls);
7196 if (tls->abort_requested) {
7197 PRINT_DEBUG_MSG (1, "Abort already requested.\n");
7198 mono_loader_unlock ();
7199 break;
7203 * Check whether we're still inside the mono_runtime_invoke_checked() and that it's
7204 * actually the correct invocation.
7206 * Careful, we do not stop the thread that's doing the invocation, so we can't
7207 * inspect its stack. However, invoke_method() also acquires the loader lock
7208 * when it's done, so we're safe here.
7212 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
7213 mono_loader_unlock ();
7214 return ERR_NO_INVOCATION;
7217 tls->abort_requested = TRUE;
7219 mono_thread_internal_abort (THREAD_TO_INTERNAL (thread), FALSE);
7220 mono_loader_unlock ();
7221 break;
7224 case CMD_VM_SET_KEEPALIVE: {
7225 int timeout = decode_int (p, &p, end);
7226 agent_config.keepalive = timeout;
7227 // FIXME:
7228 #ifndef DISABLE_SOCKET_TRANSPORT
7229 set_keepalive ();
7230 #else
7231 NOT_IMPLEMENTED;
7232 #endif
7233 break;
7235 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
7236 int i;
7237 char *fname, *basename;
7238 gboolean ignore_case;
7239 GPtrArray *res_classes, *res_domains;
7241 fname = decode_string (p, &p, end);
7242 ignore_case = decode_byte (p, &p, end);
7244 basename = dbg_path_get_basename (fname);
7246 res_classes = g_ptr_array_new ();
7247 res_domains = g_ptr_array_new ();
7249 mono_loader_lock ();
7250 GetTypesForSourceFileArgs args;
7251 memset (&args, 0, sizeof (args));
7252 args.ignore_case = ignore_case;
7253 args.basename = basename;
7254 args.res_classes = res_classes;
7255 args.res_domains = res_domains;
7256 mono_de_foreach_domain (get_types_for_source_file, &args);
7257 mono_loader_unlock ();
7259 g_free (fname);
7260 g_free (basename);
7262 buffer_add_int (buf, res_classes->len);
7263 for (i = 0; i < res_classes->len; ++i)
7264 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7265 g_ptr_array_free (res_classes, TRUE);
7266 g_ptr_array_free (res_domains, TRUE);
7267 break;
7269 case CMD_VM_GET_TYPES: {
7270 ERROR_DECL (error);
7271 int i;
7272 char *name;
7273 gboolean ignore_case;
7274 GPtrArray *res_classes, *res_domains;
7275 MonoTypeNameParse info;
7277 name = decode_string (p, &p, end);
7278 ignore_case = decode_byte (p, &p, end);
7280 if (!mono_reflection_parse_type_checked (name, &info, error)) {
7281 add_error_string (buf, mono_error_get_message (error));
7282 mono_error_cleanup (error);
7283 g_free (name);
7284 mono_reflection_free_type_info (&info);
7285 return ERR_INVALID_ARGUMENT;
7288 res_classes = g_ptr_array_new ();
7289 res_domains = g_ptr_array_new ();
7291 mono_loader_lock ();
7293 GetTypesArgs args;
7294 memset (&args, 0, sizeof (args));
7295 args.info = &info;
7296 args.ignore_case = ignore_case;
7297 args.res_classes = res_classes;
7298 args.res_domains = res_domains;
7300 mono_de_foreach_domain (get_types, &args);
7302 mono_loader_unlock ();
7304 g_free (name);
7305 mono_reflection_free_type_info (&info);
7307 buffer_add_int (buf, res_classes->len);
7308 for (i = 0; i < res_classes->len; ++i)
7309 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7310 g_ptr_array_free (res_classes, TRUE);
7311 g_ptr_array_free (res_domains, TRUE);
7312 break;
7314 case CMD_VM_START_BUFFERING:
7315 case CMD_VM_STOP_BUFFERING:
7316 /* Handled in the main loop */
7317 break;
7318 case CMD_GET_ENC_CAPABILITIES: {
7319 buffer_add_string (buf, "Baseline");
7320 break;
7322 default:
7323 return ERR_NOT_IMPLEMENTED;
7326 return ERR_NONE;
7329 static ErrorCode
7330 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7332 ErrorCode err;
7333 ERROR_DECL (error);
7335 switch (command) {
7336 case CMD_EVENT_REQUEST_SET: {
7337 EventRequest *req;
7338 int i, event_kind, suspend_policy, nmodifiers;
7339 ModifierKind mod;
7340 MonoMethod *method;
7341 long location = 0;
7342 MonoThread *step_thread;
7343 int step_thread_id = 0;
7344 StepDepth depth = STEP_DEPTH_INTO;
7345 StepSize size = STEP_SIZE_MIN;
7346 StepFilter filter = STEP_FILTER_NONE;
7347 MonoDomain *domain;
7348 Modifier *modifier;
7350 event_kind = decode_byte (p, &p, end);
7351 suspend_policy = decode_byte (p, &p, end);
7352 nmodifiers = decode_byte (p, &p, end);
7354 req = (EventRequest *)g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7355 req->id = mono_atomic_inc_i32 (&event_request_id);
7356 req->event_kind = event_kind;
7357 req->suspend_policy = suspend_policy;
7358 req->nmodifiers = nmodifiers;
7360 method = NULL;
7361 for (i = 0; i < nmodifiers; ++i) {
7362 mod = (ModifierKind)decode_byte (p, &p, end);
7364 req->modifiers [i].kind = mod;
7365 if (mod == MOD_KIND_COUNT) {
7366 req->modifiers [i].data.count = decode_int (p, &p, end);
7367 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7368 method = decode_methodid (p, &p, end, &domain, &err);
7369 if (err != ERR_NONE)
7370 return err;
7371 location = decode_long (p, &p, end);
7372 } else if (mod == MOD_KIND_STEP) {
7373 step_thread_id = decode_id (p, &p, end);
7374 size = (StepSize)decode_int (p, &p, end);
7375 depth = (StepDepth)decode_int (p, &p, end);
7376 if (CHECK_PROTOCOL_VERSION (2, 16))
7377 filter = (StepFilter)decode_int (p, &p, end);
7378 req->modifiers [i].data.filter = filter;
7379 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7380 /* Treat STEP_THOUGH the same as HIDDEN */
7381 req->modifiers [i].data.filter = (StepFilter)(req->modifiers [i].data.filter | STEP_FILTER_DEBUGGER_STEP_THROUGH);
7382 } else if (mod == MOD_KIND_THREAD_ONLY) {
7383 int id = decode_id (p, &p, end);
7385 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7386 if (err != ERR_NONE) {
7387 g_free (req);
7388 return err;
7390 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7391 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7393 if (err != ERR_NONE)
7394 return err;
7395 req->modifiers [i].caught = decode_byte (p, &p, end);
7396 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7397 if (CHECK_PROTOCOL_VERSION (2, 25))
7398 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7399 else
7400 req->modifiers [i].subclasses = TRUE;
7401 if (exc_class) {
7402 req->modifiers [i].data.exc_class = exc_class;
7404 if (!mono_class_is_assignable_from_internal (mono_defaults.exception_class, exc_class)) {
7405 g_free (req);
7406 return ERR_INVALID_ARGUMENT;
7409 if (CHECK_PROTOCOL_VERSION (2, 54)) {
7410 req->modifiers [i].not_filtered_feature = decode_byte (p, &p, end);
7411 req->modifiers [i].everything_else = decode_byte (p, &p, end);
7412 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" : "");
7413 } else {
7414 req->modifiers [i].not_filtered_feature = FALSE;
7415 req->modifiers [i].everything_else = FALSE;
7416 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" : "");
7419 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7420 int n = decode_int (p, &p, end);
7421 int j;
7423 // +1 because we don't know length and we use last element to check for end
7424 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n + 1);
7425 for (j = 0; j < n; ++j) {
7426 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7427 if (err != ERR_NONE) {
7428 g_free (req->modifiers [i].data.assemblies);
7429 return err;
7432 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7433 int n = decode_int (p, &p, end);
7434 int j;
7436 modifier = &req->modifiers [i];
7437 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7438 for (j = 0; j < n; ++j) {
7439 char *s = decode_string (p, &p, end);
7440 char *s2;
7442 if (s) {
7443 s2 = strdup_tolower (s);
7444 g_hash_table_insert (modifier->data.source_files, s2, s2);
7445 g_free (s);
7448 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7449 int n = decode_int (p, &p, end);
7450 int j;
7452 modifier = &req->modifiers [i];
7453 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7454 for (j = 0; j < n; ++j) {
7455 char *s = decode_string (p, &p, end);
7457 if (s)
7458 g_hash_table_insert (modifier->data.type_names, s, s);
7460 } else {
7461 g_free (req);
7462 return ERR_NOT_IMPLEMENTED;
7466 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7467 g_assert (method);
7469 req->info = mono_de_set_breakpoint (method, location, req, error);
7470 if (!is_ok (error)) {
7471 g_free (req);
7472 PRINT_DEBUG_MSG (1, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (error));
7473 mono_error_cleanup (error);
7474 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7476 } else if (req->event_kind == EVENT_KIND_STEP) {
7477 g_assert (step_thread_id);
7479 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7480 if (err != ERR_NONE) {
7481 g_free (req);
7482 return err;
7485 mono_loader_lock ();
7486 DebuggerTlsData *tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL(step_thread));
7487 mono_loader_unlock ();
7488 g_assert (tls);
7490 if (tls->terminated) {
7491 /* if the thread is already terminated ignore the single step */
7492 buffer_add_int (buf, req->id);
7493 return ERR_NONE;
7496 err = (ErrorCode)mono_de_ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, filter, req);
7497 if (err != ERR_NONE) {
7498 g_free (req);
7499 return err;
7501 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7502 req->info = mono_de_set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7503 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7504 req->info = mono_de_set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7505 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7506 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7507 } else {
7508 if (req->nmodifiers) {
7509 g_free (req);
7510 return ERR_NOT_IMPLEMENTED;
7514 mono_loader_lock ();
7515 g_ptr_array_add (event_requests, req);
7517 if (agent_config.defer) {
7518 /* Transmit cached data to the client on receipt of the event request */
7519 switch (req->event_kind) {
7520 case EVENT_KIND_APPDOMAIN_CREATE:
7521 /* Emit load events for currently loaded domains */
7522 mono_de_foreach_domain (emit_appdomain_load, NULL);
7523 break;
7524 case EVENT_KIND_ASSEMBLY_LOAD:
7525 /* Emit load events for currently loaded assemblies */
7526 mono_domain_foreach (send_assemblies_for_domain, NULL);
7527 break;
7528 case EVENT_KIND_THREAD_START:
7529 /* Emit start events for currently started threads */
7530 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7531 break;
7532 case EVENT_KIND_TYPE_LOAD:
7533 /* Emit type load events for currently loaded types */
7534 mono_domain_foreach (send_types_for_domain, NULL);
7535 break;
7536 default:
7537 break;
7540 mono_loader_unlock ();
7542 buffer_add_int (buf, req->id);
7543 break;
7545 case CMD_EVENT_REQUEST_CLEAR: {
7546 int etype = decode_byte (p, &p, end);
7547 int req_id = decode_int (p, &p, end);
7549 // FIXME: Make a faster mapping from req_id to request
7550 mono_loader_lock ();
7551 clear_event_request (req_id, etype);
7552 mono_loader_unlock ();
7553 break;
7555 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7556 int i;
7558 mono_loader_lock ();
7559 i = 0;
7560 while (i < event_requests->len) {
7561 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
7563 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7564 mono_de_clear_breakpoint ((MonoBreakpoint *)req->info);
7566 g_ptr_array_remove_index_fast (event_requests, i);
7567 g_free (req);
7568 } else {
7569 i ++;
7572 mono_loader_unlock ();
7573 break;
7575 default:
7576 return ERR_NOT_IMPLEMENTED;
7579 return ERR_NONE;
7582 static ErrorCode
7583 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7585 ErrorCode err;
7586 MonoDomain *domain;
7588 switch (command) {
7589 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7590 buffer_add_domainid (buf, mono_get_root_domain ());
7591 break;
7593 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7594 domain = decode_domainid (p, &p, end, NULL, &err);
7595 if (err != ERR_NONE)
7596 return err;
7597 buffer_add_string (buf, domain->friendly_name);
7598 break;
7600 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7601 GSList *tmp;
7602 MonoAssembly *ass;
7603 int count;
7605 domain = decode_domainid (p, &p, end, NULL, &err);
7606 if (err != ERR_NONE)
7607 return err;
7608 mono_domain_assemblies_lock (domain);
7609 count = 0;
7610 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7611 count ++;
7613 buffer_add_int (buf, count);
7614 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7615 ass = (MonoAssembly *)tmp->data;
7616 buffer_add_assemblyid (buf, domain, ass);
7618 mono_domain_assemblies_unlock (domain);
7619 break;
7621 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7622 domain = decode_domainid (p, &p, end, NULL, &err);
7623 if (err != ERR_NONE)
7624 return err;
7626 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7627 break;
7629 case CMD_APPDOMAIN_GET_CORLIB: {
7630 domain = decode_domainid (p, &p, end, NULL, &err);
7631 if (err != ERR_NONE)
7632 return err;
7634 buffer_add_assemblyid (buf, domain, m_class_get_image (domain->domain->mbr.obj.vtable->klass)->assembly);
7635 break;
7637 case CMD_APPDOMAIN_CREATE_STRING: {
7638 char *s;
7639 MonoString *o;
7640 ERROR_DECL (error);
7642 domain = decode_domainid (p, &p, end, NULL, &err);
7643 if (err != ERR_NONE)
7644 return err;
7645 s = decode_string (p, &p, end);
7647 o = mono_string_new_checked (domain, s, error);
7648 if (!is_ok (error)) {
7649 PRINT_DEBUG_MSG (1, "[dbg] Failed to allocate String object '%s': %s\n", s, mono_error_get_message (error));
7650 mono_error_cleanup (error);
7651 return ERR_INVALID_OBJECT;
7653 buffer_add_objid (buf, (MonoObject*)o);
7654 break;
7656 case CMD_APPDOMAIN_CREATE_BYTE_ARRAY: {
7657 ERROR_DECL (error);
7658 MonoArray *arr;
7659 gpointer elem;
7660 domain = decode_domainid (p, &p, end, NULL, &err);
7661 uintptr_t size = 0;
7662 int len = decode_int (p, &p, end);
7663 size = len;
7664 arr = mono_array_new_full_checked (mono_domain_get (), mono_class_create_array (mono_get_byte_class(), 1), &size, NULL, error);
7665 elem = mono_array_addr_internal (arr, guint8, 0);
7666 memcpy (elem, p, len);
7667 p += len;
7668 buffer_add_objid (buf, (MonoObject*) arr);
7669 break;
7671 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7672 ERROR_DECL (error);
7673 MonoClass *klass;
7674 MonoDomain *domain2;
7675 MonoObject *o;
7677 domain = decode_domainid (p, &p, end, NULL, &err);
7678 if (err != ERR_NONE)
7679 return err;
7680 klass = decode_typeid (p, &p, end, &domain2, &err);
7681 if (err != ERR_NONE)
7682 return err;
7684 // FIXME:
7685 g_assert (domain == domain2);
7687 o = mono_object_new_checked (domain, klass, error);
7688 mono_error_assert_ok (error);
7690 err = decode_value (m_class_get_byval_arg (klass), domain, (guint8 *)mono_object_unbox_internal (o), p, &p, end, TRUE);
7691 if (err != ERR_NONE)
7692 return err;
7694 buffer_add_objid (buf, o);
7695 break;
7697 default:
7698 return ERR_NOT_IMPLEMENTED;
7701 return ERR_NONE;
7704 static ErrorCode
7705 get_assembly_object_command (MonoDomain *domain, MonoAssembly *ass, Buffer *buf, MonoError *error)
7707 HANDLE_FUNCTION_ENTER();
7708 ErrorCode err = ERR_NONE;
7709 error_init (error);
7710 MonoReflectionAssemblyHandle o = mono_assembly_get_object_handle (domain, ass, error);
7711 if (MONO_HANDLE_IS_NULL (o)) {
7712 err = ERR_INVALID_OBJECT;
7713 goto leave;
7715 buffer_add_objid (buf, MONO_HANDLE_RAW (MONO_HANDLE_CAST (MonoObject, o)));
7716 leave:
7717 HANDLE_FUNCTION_RETURN_VAL (err);
7721 static ErrorCode
7722 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7724 ErrorCode err;
7725 MonoAssembly *ass;
7726 MonoDomain *domain;
7728 ass = decode_assemblyid (p, &p, end, &domain, &err);
7729 if (err != ERR_NONE)
7730 return err;
7732 switch (command) {
7733 case CMD_ASSEMBLY_GET_LOCATION: {
7734 buffer_add_string (buf, mono_image_get_filename (ass->image));
7735 break;
7737 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7738 guint32 token;
7739 MonoMethod *m;
7741 if (ass->image->dynamic) {
7742 buffer_add_id (buf, 0);
7743 } else {
7744 token = mono_image_get_entry_point (ass->image);
7745 if (token == 0) {
7746 buffer_add_id (buf, 0);
7747 } else {
7748 ERROR_DECL (error);
7749 m = mono_get_method_checked (ass->image, token, NULL, NULL, error);
7750 if (!m)
7751 mono_error_cleanup (error); /* FIXME don't swallow the error */
7752 buffer_add_methodid (buf, domain, m);
7755 break;
7757 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7758 buffer_add_moduleid (buf, domain, ass->image);
7759 break;
7761 case CMD_ASSEMBLY_GET_OBJECT: {
7762 ERROR_DECL (error);
7763 err = get_assembly_object_command (domain, ass, buf, error);
7764 mono_error_cleanup (error);
7765 return err;
7767 case CMD_ASSEMBLY_GET_DOMAIN: {
7768 buffer_add_domainid (buf, domain);
7769 break;
7771 case CMD_ASSEMBLY_GET_TYPE: {
7772 ERROR_DECL (error);
7773 char *s = decode_string (p, &p, end);
7774 char* original_s = g_strdup_printf ("\"%s\"", s);
7776 gboolean ignorecase = decode_byte (p, &p, end);
7777 MonoTypeNameParse info;
7778 MonoType *t;
7779 gboolean type_resolve, res;
7780 MonoDomain *d = mono_domain_get ();
7781 MonoAssemblyLoadContext *alc = mono_domain_default_alc (d);
7783 /* This is needed to be able to find referenced assemblies */
7784 res = mono_domain_set_fast (domain, FALSE);
7785 g_assert (res);
7787 if (!mono_reflection_parse_type_checked (s, &info, error)) {
7788 mono_error_cleanup (error);
7789 t = NULL;
7790 } else {
7791 if (info.assembly.name) {
7792 mono_reflection_free_type_info (&info);
7793 g_free (s);
7794 mono_domain_set_fast (d, TRUE);
7795 char* error_msg = g_strdup_printf ("Unexpected assembly-qualified type %s was provided", original_s);
7796 add_error_string (buf, error_msg);
7797 g_free (error_msg);
7798 g_free (original_s);
7799 return ERR_INVALID_ARGUMENT;
7801 t = mono_reflection_get_type_checked (alc, ass->image, ass->image, &info, ignorecase, TRUE, &type_resolve, error);
7802 if (!is_ok (error)) {
7803 mono_error_cleanup (error); /* FIXME don't swallow the error */
7804 mono_reflection_free_type_info (&info);
7805 g_free (s);
7806 mono_domain_set_fast (d, TRUE);
7807 char* error_msg = g_strdup_printf ("Invalid type name %s", original_s);
7808 add_error_string (buf, error_msg);
7809 g_free (error_msg);
7810 g_free (original_s);
7811 return ERR_INVALID_ARGUMENT;
7814 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type_internal (t) : NULL);
7815 mono_reflection_free_type_info (&info);
7816 g_free (s);
7817 g_free (original_s);
7818 mono_domain_set_fast (d, TRUE);
7820 break;
7822 case CMD_ASSEMBLY_GET_NAME: {
7823 gchar *name;
7824 MonoAssembly *mass = ass;
7826 name = g_strdup_printf (
7827 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7828 mass->aname.name,
7829 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7830 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7831 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7832 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7834 buffer_add_string (buf, name);
7835 g_free (name);
7836 break;
7838 case CMD_ASSEMBLY_GET_METADATA_BLOB: {
7839 MonoImage* image = ass->image;
7840 if (ass->dynamic) {
7841 return ERR_NOT_IMPLEMENTED;
7843 buffer_add_byte_array (buf, (guint8*)image->raw_data, image->raw_data_len);
7844 break;
7846 case CMD_ASSEMBLY_GET_IS_DYNAMIC: {
7847 buffer_add_byte (buf, ass->dynamic);
7848 break;
7850 case CMD_ASSEMBLY_GET_PDB_BLOB: {
7851 MonoImage* image = ass->image;
7852 MonoDebugHandle* handle = mono_debug_get_handle (image);
7853 if (!handle) {
7854 return ERR_INVALID_ARGUMENT;
7856 MonoPPDBFile* ppdb = handle->ppdb;
7857 if (ppdb) {
7858 image = mono_ppdb_get_image (ppdb);
7859 buffer_add_byte_array (buf, (guint8*)image->raw_data, image->raw_data_len);
7860 } else {
7861 buffer_add_byte_array (buf, NULL, 0);
7863 break;
7865 case CMD_ASSEMBLY_GET_TYPE_FROM_TOKEN: {
7866 if (ass->dynamic) {
7867 return ERR_NOT_IMPLEMENTED;
7869 guint32 token = decode_int (p, &p, end);
7870 ERROR_DECL (error);
7871 error_init (error);
7872 MonoClass* mono_class = mono_class_get_checked (ass->image, token, error);
7873 if (!is_ok (error)) {
7874 add_error_string (buf, mono_error_get_message (error));
7875 mono_error_cleanup (error);
7876 return ERR_INVALID_ARGUMENT;
7878 buffer_add_typeid (buf, domain, mono_class);
7879 mono_error_cleanup (error);
7880 break;
7882 case CMD_ASSEMBLY_GET_METHOD_FROM_TOKEN: {
7883 if (ass->dynamic) {
7884 return ERR_NOT_IMPLEMENTED;
7886 guint32 token = decode_int (p, &p, end);
7887 ERROR_DECL (error);
7888 error_init (error);
7889 MonoMethod* mono_method = mono_get_method_checked (ass->image, token, NULL, NULL, error);
7890 if (!is_ok (error)) {
7891 add_error_string (buf, mono_error_get_message (error));
7892 mono_error_cleanup (error);
7893 return ERR_INVALID_ARGUMENT;
7895 buffer_add_methodid (buf, domain, mono_method);
7896 mono_error_cleanup (error);
7897 break;
7899 case CMD_ASSEMBLY_HAS_DEBUG_INFO: {
7900 buffer_add_byte (buf, !ass->dynamic && mono_debug_image_has_debug_info (ass->image));
7901 break;
7903 case CMD_ASSEMBLY_GET_CATTRS: {
7904 ERROR_DECL (error);
7905 MonoClass *attr_klass;
7906 MonoCustomAttrInfo *cinfo;
7908 attr_klass = decode_typeid (p, &p, end, NULL, &err);
7909 /* attr_klass can be NULL */
7910 if (err != ERR_NONE)
7911 return err;
7913 cinfo = mono_custom_attrs_from_assembly_checked (ass, FALSE, error);
7914 if (!is_ok (error)) {
7915 mono_error_cleanup (error); /* FIXME don't swallow the error message */
7916 return ERR_LOADER_ERROR;
7919 err = buffer_add_cattrs (buf, domain, mono_assembly_get_image_internal (ass), attr_klass, cinfo);
7920 if (err != ERR_NONE)
7921 return err;
7922 break;
7924 case CMD_ASSEMBLY_GET_DEBUG_INFORMATION: {
7925 guint8 pe_guid [16];
7926 gint32 pe_age;
7927 gint32 pe_timestamp;
7928 guint8 *ppdb_data = NULL;
7929 int ppdb_size = 0, ppdb_compressed_size = 0;
7930 char *ppdb_path;
7931 GArray *pdb_checksum_hash_type = g_array_new (FALSE, TRUE, sizeof (char*));
7932 GArray *pdb_checksum = g_array_new (FALSE, TRUE, sizeof (guint8*));
7933 gboolean has_debug_info = mono_get_pe_debug_info_full (ass->image, pe_guid, &pe_age, &pe_timestamp, &ppdb_data, &ppdb_size, &ppdb_compressed_size, &ppdb_path, pdb_checksum_hash_type, pdb_checksum);
7934 if (!has_debug_info || ppdb_size > 0)
7936 buffer_add_byte (buf, 0);
7937 g_array_free (pdb_checksum_hash_type, TRUE);
7938 g_array_free (pdb_checksum, TRUE);
7939 return ERR_NONE;
7941 buffer_add_byte (buf, 1);
7942 buffer_add_int (buf, pe_age);
7943 buffer_add_byte_array (buf, pe_guid, 16);
7944 buffer_add_string (buf, ppdb_path);
7945 buffer_add_int (buf, pdb_checksum_hash_type->len);
7946 for (int i = 0 ; i < pdb_checksum_hash_type->len; ++i) {
7947 char* checksum_hash_type = g_array_index (pdb_checksum_hash_type, char*, i);
7948 buffer_add_string (buf, checksum_hash_type);
7949 if (!strcmp (checksum_hash_type, "SHA256"))
7950 buffer_add_byte_array (buf, g_array_index (pdb_checksum, guint8*, i), 32);
7951 else if (!strcmp (checksum_hash_type, "SHA384"))
7952 buffer_add_byte_array (buf, g_array_index (pdb_checksum, guint8*, i), 48);
7953 else if (!strcmp (checksum_hash_type, "SHA512"))
7954 buffer_add_byte_array (buf, g_array_index (pdb_checksum, guint8*, i), 64);
7956 g_array_free (pdb_checksum_hash_type, TRUE);
7957 g_array_free (pdb_checksum, TRUE);
7958 break;
7960 case CMD_ASSEMBLY_HAS_DEBUG_INFO_LOADED: {
7961 MonoImage* image = ass->image;
7962 MonoDebugHandle* handle = mono_debug_get_handle (image);
7963 if (!handle) {
7964 buffer_add_byte (buf, 0);
7965 return ERR_NONE;
7967 MonoPPDBFile* ppdb = handle->ppdb;
7968 if (ppdb) {
7969 image = mono_ppdb_get_image (ppdb);
7970 buffer_add_byte (buf, image->raw_data_len > 0);
7971 } else {
7972 buffer_add_byte (buf, 0);
7974 break;
7976 default:
7977 return ERR_NOT_IMPLEMENTED;
7980 return ERR_NONE;
7983 static ErrorCode
7984 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7986 ErrorCode err;
7987 MonoDomain *domain;
7989 switch (command) {
7990 case CMD_MODULE_GET_INFO: {
7991 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7992 char *basename, *sourcelink = NULL;
7994 if (CHECK_PROTOCOL_VERSION (2, 48))
7995 sourcelink = mono_debug_image_get_sourcelink (image);
7997 basename = g_path_get_basename (image->name);
7998 buffer_add_string (buf, basename); // name
7999 buffer_add_string (buf, image->module_name); // scopename
8000 buffer_add_string (buf, image->name); // fqname
8001 buffer_add_string (buf, mono_image_get_guid (image)); // guid
8002 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
8003 if (CHECK_PROTOCOL_VERSION (2, 48))
8004 buffer_add_string (buf, sourcelink);
8005 g_free (basename);
8006 g_free (sourcelink);
8007 break;
8009 default:
8010 return ERR_NOT_IMPLEMENTED;
8013 return ERR_NONE;
8016 static ErrorCode
8017 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8019 ErrorCode err;
8020 MonoDomain *domain;
8022 switch (command) {
8023 case CMD_FIELD_GET_INFO: {
8024 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
8026 buffer_add_string (buf, f->name);
8027 buffer_add_typeid (buf, domain, f->parent);
8028 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (f->type));
8029 buffer_add_int (buf, f->type->attrs);
8030 break;
8032 default:
8033 return ERR_NOT_IMPLEMENTED;
8036 return ERR_NONE;
8039 /* FIXME: Code duplication with icall.c */
8040 static void
8041 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
8043 int i;
8044 MonoClass *ic;
8046 mono_class_setup_interfaces (klass, error);
8047 if (!is_ok (error))
8048 return;
8050 int klass_interface_count = m_class_get_interface_count (klass);
8051 MonoClass **klass_interfaces = m_class_get_interfaces (klass);
8052 for (i = 0; i < klass_interface_count; i++) {
8053 ic = klass_interfaces [i];
8054 g_hash_table_insert (ifaces, ic, ic);
8056 collect_interfaces (ic, ifaces, error);
8057 if (!is_ok (error))
8058 return;
8062 static ErrorCode
8063 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8065 HANDLE_FUNCTION_ENTER ();
8067 ERROR_DECL (error);
8068 MonoClass *nested;
8069 MonoType *type;
8070 gpointer iter;
8071 guint8 b;
8072 int nnested;
8073 ErrorCode err;
8074 char *name;
8075 MonoStringHandle string_handle = MONO_HANDLE_NEW (MonoString, NULL); // FIXME? Not always needed.
8077 switch (command) {
8078 case CMD_TYPE_GET_INFO: {
8079 buffer_add_string (buf, m_class_get_name_space (klass));
8080 buffer_add_string (buf, m_class_get_name (klass));
8081 // FIXME: byref
8082 name = mono_type_get_name_full (m_class_get_byval_arg (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
8083 buffer_add_string (buf, name);
8084 g_free (name);
8085 buffer_add_assemblyid (buf, domain, m_class_get_image (klass)->assembly);
8086 buffer_add_moduleid (buf, domain, m_class_get_image (klass));
8087 buffer_add_typeid (buf, domain, m_class_get_parent (klass));
8088 if (m_class_get_rank (klass) || m_class_get_byval_arg (klass)->type == MONO_TYPE_PTR)
8089 buffer_add_typeid (buf, domain, m_class_get_element_class (klass));
8090 else
8091 buffer_add_id (buf, 0);
8092 buffer_add_int (buf, m_class_get_type_token (klass));
8093 buffer_add_byte (buf, m_class_get_rank (klass));
8094 buffer_add_int (buf, mono_class_get_flags (klass));
8095 b = 0;
8096 type = m_class_get_byval_arg (klass);
8097 // FIXME: Can't decide whenever a class represents a byref type
8098 if (FALSE)
8099 b |= (1 << 0);
8100 if (type->type == MONO_TYPE_PTR || type->type == MONO_TYPE_FNPTR)
8101 b |= (1 << 1);
8102 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
8103 b |= (1 << 2);
8104 if (type->type == MONO_TYPE_VALUETYPE)
8105 b |= (1 << 3);
8106 if (m_class_is_enumtype (klass))
8107 b |= (1 << 4);
8108 if (mono_class_is_gtd (klass))
8109 b |= (1 << 5);
8110 if (mono_class_is_gtd (klass) || mono_class_is_ginst (klass))
8111 b |= (1 << 6);
8112 buffer_add_byte (buf, b);
8113 nnested = 0;
8114 iter = NULL;
8115 while ((nested = mono_class_get_nested_types (klass, &iter)))
8116 nnested ++;
8117 buffer_add_int (buf, nnested);
8118 iter = NULL;
8119 while ((nested = mono_class_get_nested_types (klass, &iter)))
8120 buffer_add_typeid (buf, domain, nested);
8121 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8122 if (mono_class_is_gtd (klass))
8123 buffer_add_typeid (buf, domain, klass);
8124 else if (mono_class_is_ginst (klass))
8125 buffer_add_typeid (buf, domain, mono_class_get_generic_class (klass)->container_class);
8126 else
8127 buffer_add_id (buf, 0);
8129 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8130 int count, i;
8132 if (mono_class_is_ginst (klass)) {
8133 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
8135 count = inst->type_argc;
8136 buffer_add_int (buf, count);
8137 for (i = 0; i < count; i++)
8138 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (inst->type_argv [i]));
8139 } else if (mono_class_is_gtd (klass)) {
8140 MonoGenericContainer *container = mono_class_get_generic_container (klass);
8141 MonoClass *pklass;
8143 count = container->type_argc;
8144 buffer_add_int (buf, count);
8145 for (i = 0; i < count; i++) {
8146 pklass = mono_class_create_generic_parameter (mono_generic_container_get_param (container, i));
8147 buffer_add_typeid (buf, domain, pklass);
8149 } else {
8150 buffer_add_int (buf, 0);
8153 break;
8155 case CMD_TYPE_GET_METHODS: {
8156 int nmethods;
8157 int i = 0;
8158 gpointer iter = NULL;
8159 MonoMethod *m;
8161 mono_class_setup_methods (klass);
8163 nmethods = mono_class_num_methods (klass);
8165 buffer_add_int (buf, nmethods);
8167 while ((m = mono_class_get_methods (klass, &iter))) {
8168 buffer_add_methodid (buf, domain, m);
8169 i ++;
8171 g_assert (i == nmethods);
8172 break;
8174 case CMD_TYPE_GET_FIELDS: {
8175 int nfields;
8176 int i = 0;
8177 gpointer iter = NULL;
8178 MonoClassField *f;
8180 nfields = mono_class_num_fields (klass);
8182 buffer_add_int (buf, nfields);
8184 while ((f = mono_class_get_fields_internal (klass, &iter))) {
8185 buffer_add_fieldid (buf, domain, f);
8186 buffer_add_string (buf, f->name);
8187 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (f->type));
8188 buffer_add_int (buf, f->type->attrs);
8189 i ++;
8191 g_assert (i == nfields);
8192 break;
8194 case CMD_TYPE_GET_PROPERTIES: {
8195 int nprops;
8196 int i = 0;
8197 gpointer iter = NULL;
8198 MonoProperty *p;
8200 nprops = mono_class_num_properties (klass);
8202 buffer_add_int (buf, nprops);
8204 while ((p = mono_class_get_properties (klass, &iter))) {
8205 buffer_add_propertyid (buf, domain, p);
8206 buffer_add_string (buf, p->name);
8207 buffer_add_methodid (buf, domain, p->get);
8208 buffer_add_methodid (buf, domain, p->set);
8209 buffer_add_int (buf, p->attrs);
8210 i ++;
8212 g_assert (i == nprops);
8213 break;
8215 case CMD_TYPE_GET_CATTRS: {
8216 MonoClass *attr_klass;
8217 MonoCustomAttrInfo *cinfo;
8219 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8220 /* attr_klass can be NULL */
8221 if (err != ERR_NONE)
8222 goto exit;
8224 cinfo = mono_custom_attrs_from_class_checked (klass, error);
8225 if (!is_ok (error)) {
8226 mono_error_cleanup (error); /* FIXME don't swallow the error message */
8227 goto loader_error;
8230 err = buffer_add_cattrs (buf, domain, m_class_get_image (klass), attr_klass, cinfo);
8231 if (err != ERR_NONE)
8232 goto exit;
8233 break;
8235 case CMD_TYPE_GET_FIELD_CATTRS: {
8236 MonoClass *attr_klass;
8237 MonoCustomAttrInfo *cinfo;
8238 MonoClassField *field;
8240 field = decode_fieldid (p, &p, end, NULL, &err);
8241 if (err != ERR_NONE)
8242 goto exit;
8243 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8244 if (err != ERR_NONE)
8245 goto exit;
8247 cinfo = mono_custom_attrs_from_field_checked (klass, field, error);
8248 if (!is_ok (error)) {
8249 mono_error_cleanup (error); /* FIXME don't swallow the error message */
8250 goto loader_error;
8253 err = buffer_add_cattrs (buf, domain, m_class_get_image (klass), attr_klass, cinfo);
8254 if (err != ERR_NONE)
8255 goto exit;
8256 break;
8258 case CMD_TYPE_GET_PROPERTY_CATTRS: {
8259 MonoClass *attr_klass;
8260 MonoCustomAttrInfo *cinfo;
8261 MonoProperty *prop;
8263 prop = decode_propertyid (p, &p, end, NULL, &err);
8264 if (err != ERR_NONE)
8265 goto exit;
8266 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8267 if (err != ERR_NONE)
8268 goto exit;
8270 cinfo = mono_custom_attrs_from_property_checked (klass, prop, error);
8271 if (!is_ok (error)) {
8272 mono_error_cleanup (error); /* FIXME don't swallow the error message */
8273 goto loader_error;
8276 err = buffer_add_cattrs (buf, domain, m_class_get_image (klass), attr_klass, cinfo);
8277 if (err != ERR_NONE)
8278 goto exit;
8279 break;
8281 case CMD_TYPE_GET_VALUES:
8282 case CMD_TYPE_GET_VALUES_2: {
8283 guint8 *val;
8284 MonoClassField *f;
8285 MonoVTable *vtable;
8286 MonoClass *k;
8287 int len, i;
8288 gboolean found;
8289 MonoThread *thread_obj;
8290 MonoInternalThread *thread = NULL;
8291 guint32 special_static_type;
8293 if (command == CMD_TYPE_GET_VALUES_2) {
8294 int objid = decode_objid (p, &p, end);
8296 err = get_object (objid, (MonoObject**)&thread_obj);
8297 if (err != ERR_NONE)
8298 goto exit;
8300 thread = THREAD_TO_INTERNAL (thread_obj);
8303 len = decode_int (p, &p, end);
8304 for (i = 0; i < len; ++i) {
8305 f = decode_fieldid (p, &p, end, NULL, &err);
8306 if (err != ERR_NONE)
8307 goto exit;
8309 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8310 goto invalid_fieldid;
8312 special_static_type = mono_class_field_get_special_static_type (f);
8313 if (special_static_type != SPECIAL_STATIC_NONE) {
8314 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
8315 goto invalid_fieldid;
8318 /* Check that the field belongs to the object */
8319 found = FALSE;
8320 for (k = klass; k; k = m_class_get_parent (k)) {
8321 if (k == f->parent) {
8322 found = TRUE;
8323 break;
8326 if (!found)
8327 goto invalid_fieldid;
8329 vtable = mono_class_vtable_checked (domain, f->parent, error);
8330 goto_if_nok (error, invalid_fieldid);
8332 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type_internal (f->type)));
8333 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val, string_handle, error);
8334 goto_if_nok (error, invalid_fieldid);
8336 buffer_add_value (buf, f->type, val, domain);
8337 g_free (val);
8339 break;
8341 case CMD_TYPE_SET_VALUES: {
8342 guint8 *val;
8343 MonoClassField *f;
8344 MonoVTable *vtable;
8345 MonoClass *k;
8346 int len, i;
8347 gboolean found;
8349 len = decode_int (p, &p, end);
8350 for (i = 0; i < len; ++i) {
8351 f = decode_fieldid (p, &p, end, NULL, &err);
8352 if (err != ERR_NONE)
8353 goto exit;
8355 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8356 goto invalid_fieldid;
8358 if (mono_class_field_is_special_static (f))
8359 goto invalid_fieldid;
8361 /* Check that the field belongs to the object */
8362 found = FALSE;
8363 for (k = klass; k; k = m_class_get_parent (k)) {
8364 if (k == f->parent) {
8365 found = TRUE;
8366 break;
8369 if (!found)
8370 goto invalid_fieldid;
8372 // FIXME: Check for literal/const
8374 vtable = mono_class_vtable_checked (domain, f->parent, error);
8375 goto_if_nok (error, invalid_fieldid);
8377 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type_internal (f->type)));
8378 err = decode_value (f->type, domain, val, p, &p, end, TRUE);
8379 if (err != ERR_NONE) {
8380 g_free (val);
8381 goto exit;
8383 if (MONO_TYPE_IS_REFERENCE (f->type))
8384 mono_field_static_set_value_internal (vtable, f, *(gpointer*)val);
8385 else
8386 mono_field_static_set_value_internal (vtable, f, val);
8387 g_free (val);
8389 break;
8391 case CMD_TYPE_GET_OBJECT: {
8392 MonoObject *o = (MonoObject*)mono_type_get_object_checked (domain, m_class_get_byval_arg (klass), error);
8393 if (!is_ok (error)) {
8394 mono_error_cleanup (error);
8395 goto invalid_object;
8397 buffer_add_objid (buf, o);
8398 break;
8400 case CMD_TYPE_GET_SOURCE_FILES:
8401 case CMD_TYPE_GET_SOURCE_FILES_2: {
8402 char *source_file, *base;
8403 GPtrArray *files;
8404 int i;
8406 files = get_source_files_for_type (klass);
8408 buffer_add_int (buf, files->len);
8409 for (i = 0; i < files->len; ++i) {
8410 source_file = (char *)g_ptr_array_index (files, i);
8411 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8412 buffer_add_string (buf, source_file);
8413 } else {
8414 base = dbg_path_get_basename (source_file);
8415 buffer_add_string (buf, base);
8416 g_free (base);
8418 g_free (source_file);
8420 g_ptr_array_free (files, TRUE);
8421 break;
8423 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8424 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8426 if (err != ERR_NONE)
8427 goto exit;
8428 if (mono_class_is_assignable_from_internal (klass, oklass))
8429 buffer_add_byte (buf, 1);
8430 else
8431 buffer_add_byte (buf, 0);
8432 break;
8434 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8435 char *name = decode_string (p, &p, end);
8436 int i, flags = decode_int (p, &p, end);
8437 int mlisttype;
8438 if (CHECK_PROTOCOL_VERSION (2, 48))
8439 mlisttype = decode_int (p, &p, end);
8440 else
8441 mlisttype = 0; // MLISTTYPE_All
8442 ERROR_DECL (error);
8443 GPtrArray *array;
8445 error_init (error);
8446 array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, mlisttype, TRUE, error);
8447 if (!is_ok (error)) {
8448 mono_error_cleanup (error);
8449 goto loader_error;
8451 buffer_add_int (buf, array->len);
8452 for (i = 0; i < array->len; ++i) {
8453 MonoMethod *method = (MonoMethod *)g_ptr_array_index (array, i);
8454 buffer_add_methodid (buf, domain, method);
8457 g_ptr_array_free (array, TRUE);
8458 g_free (name);
8459 break;
8461 case CMD_TYPE_GET_INTERFACES: {
8462 MonoClass *parent;
8463 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8464 MonoClass *tclass, *iface;
8465 GHashTableIter iter;
8467 tclass = klass;
8469 for (parent = tclass; parent; parent = m_class_get_parent (parent)) {
8470 mono_class_setup_interfaces (parent, error);
8471 goto_if_nok (error, loader_error);
8473 collect_interfaces (parent, iface_hash, error);
8474 goto_if_nok (error, loader_error);
8477 buffer_add_int (buf, g_hash_table_size (iface_hash));
8479 g_hash_table_iter_init (&iter, iface_hash);
8480 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8481 buffer_add_typeid (buf, domain, iface);
8482 g_hash_table_destroy (iface_hash);
8483 break;
8485 case CMD_TYPE_GET_INTERFACE_MAP: {
8486 int tindex, ioffset;
8487 gboolean variance_used;
8488 MonoClass *iclass;
8489 int len, nmethods, i;
8490 gpointer iter;
8491 MonoMethod *method;
8493 len = decode_int (p, &p, end);
8494 mono_class_setup_vtable (klass);
8496 for (tindex = 0; tindex < len; ++tindex) {
8497 iclass = decode_typeid (p, &p, end, NULL, &err);
8498 if (err != ERR_NONE)
8499 goto exit;
8501 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8502 if (ioffset == -1)
8503 goto invalid_argument;
8505 nmethods = mono_class_num_methods (iclass);
8506 buffer_add_int (buf, nmethods);
8508 iter = NULL;
8509 while ((method = mono_class_get_methods (iclass, &iter))) {
8510 buffer_add_methodid (buf, domain, method);
8512 MonoMethod **klass_vtable = m_class_get_vtable (klass);
8513 for (i = 0; i < nmethods; ++i)
8514 buffer_add_methodid (buf, domain, klass_vtable [i + ioffset]);
8516 break;
8518 case CMD_TYPE_IS_INITIALIZED: {
8519 MonoVTable *vtable = mono_class_vtable_checked (domain, klass, error);
8520 goto_if_nok (error, loader_error);
8522 if (vtable)
8523 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8524 else
8525 buffer_add_int (buf, 0);
8526 break;
8528 case CMD_TYPE_CREATE_INSTANCE: {
8529 ERROR_DECL (error);
8530 MonoObject *obj;
8532 obj = mono_object_new_checked (domain, klass, error);
8533 mono_error_assert_ok (error);
8534 buffer_add_objid (buf, obj);
8535 break;
8537 case CMD_TYPE_GET_VALUE_SIZE: {
8538 int32_t value_size;
8540 value_size = mono_class_value_size (klass, NULL);
8541 buffer_add_int (buf, value_size);
8542 break;
8544 default:
8545 err = ERR_NOT_IMPLEMENTED;
8546 goto exit;
8549 err = ERR_NONE;
8550 goto exit;
8551 invalid_argument:
8552 err = ERR_INVALID_ARGUMENT;
8553 goto exit;
8554 invalid_fieldid:
8555 err = ERR_INVALID_FIELDID;
8556 goto exit;
8557 invalid_object:
8558 err = ERR_INVALID_OBJECT;
8559 goto exit;
8560 loader_error:
8561 err = ERR_LOADER_ERROR;
8562 goto exit;
8563 exit:
8564 HANDLE_FUNCTION_RETURN_VAL (err);
8567 static ErrorCode
8568 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8570 MonoClass *klass;
8571 MonoDomain *old_domain;
8572 MonoDomain *domain;
8573 ErrorCode err;
8575 klass = decode_typeid (p, &p, end, &domain, &err);
8576 if (err != ERR_NONE)
8577 return err;
8579 old_domain = mono_domain_get ();
8581 mono_domain_set_fast (domain, TRUE);
8583 err = type_commands_internal (command, klass, domain, p, end, buf);
8585 mono_domain_set_fast (old_domain, TRUE);
8587 return err;
8590 static ErrorCode
8591 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8593 MonoMethodHeader *header;
8594 ErrorCode err;
8596 switch (command) {
8597 case CMD_METHOD_GET_NAME: {
8598 buffer_add_string (buf, method->name);
8599 break;
8601 case CMD_METHOD_GET_DECLARING_TYPE: {
8602 buffer_add_typeid (buf, domain, method->klass);
8603 break;
8605 case CMD_METHOD_GET_DEBUG_INFO: {
8606 ERROR_DECL (error);
8607 MonoDebugMethodInfo *minfo;
8608 char *source_file;
8609 int i, j, n_il_offsets;
8610 int *source_files;
8611 GPtrArray *source_file_list;
8612 MonoSymSeqPoint *sym_seq_points;
8614 header = mono_method_get_header_checked (method, error);
8615 if (!header) {
8616 mono_error_cleanup (error); /* FIXME don't swallow the error */
8617 buffer_add_int (buf, 0);
8618 buffer_add_string (buf, "");
8619 buffer_add_int (buf, 0);
8620 break;
8623 minfo = mono_debug_lookup_method (method);
8624 if (!minfo) {
8625 buffer_add_int (buf, header->code_size);
8626 buffer_add_string (buf, "");
8627 buffer_add_int (buf, 0);
8628 mono_metadata_free_mh (header);
8629 break;
8632 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, &source_files, &sym_seq_points, &n_il_offsets);
8633 buffer_add_int (buf, header->code_size);
8634 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8635 buffer_add_int (buf, source_file_list->len);
8636 for (i = 0; i < source_file_list->len; ++i) {
8637 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
8638 buffer_add_string (buf, sinfo->source_file);
8639 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8640 for (j = 0; j < 16; ++j)
8641 buffer_add_byte (buf, sinfo->hash [j]);
8644 } else {
8645 buffer_add_string (buf, source_file);
8647 buffer_add_int (buf, n_il_offsets);
8648 PRINT_DEBUG_MSG (10, "Line number table for method %s:\n", mono_method_full_name (method, TRUE));
8649 for (i = 0; i < n_il_offsets; ++i) {
8650 MonoSymSeqPoint *sp = &sym_seq_points [i];
8651 const char *srcfile = "";
8653 if (source_files [i] != -1) {
8654 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, source_files [i]);
8655 srcfile = sinfo->source_file;
8657 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);
8658 buffer_add_int (buf, sp->il_offset);
8659 buffer_add_int (buf, sp->line);
8660 if (CHECK_PROTOCOL_VERSION (2, 13))
8661 buffer_add_int (buf, source_files [i]);
8662 if (CHECK_PROTOCOL_VERSION (2, 19))
8663 buffer_add_int (buf, sp->column);
8664 if (CHECK_PROTOCOL_VERSION (2, 32)) {
8665 buffer_add_int (buf, sp->end_line);
8666 buffer_add_int (buf, sp->end_column);
8669 g_free (source_file);
8670 g_free (source_files);
8671 g_free (sym_seq_points);
8672 g_ptr_array_free (source_file_list, TRUE);
8673 mono_metadata_free_mh (header);
8674 break;
8676 case CMD_METHOD_GET_PARAM_INFO: {
8677 MonoMethodSignature *sig = mono_method_signature_internal (method);
8678 if (!sig)
8679 return ERR_INVALID_ARGUMENT;
8680 guint32 i;
8681 char **names;
8683 /* FIXME: mono_class_from_mono_type_internal () and byrefs */
8685 /* FIXME: Use a smaller encoding */
8686 buffer_add_int (buf, sig->call_convention);
8687 buffer_add_int (buf, sig->param_count);
8688 buffer_add_int (buf, sig->generic_param_count);
8689 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (sig->ret));
8690 for (i = 0; i < sig->param_count; ++i) {
8691 /* FIXME: vararg */
8692 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (sig->params [i]));
8695 /* Emit parameter names */
8696 names = g_new (char *, sig->param_count);
8697 mono_method_get_param_names (method, (const char **) names);
8698 for (i = 0; i < sig->param_count; ++i)
8699 buffer_add_string (buf, names [i]);
8700 g_free (names);
8702 break;
8704 case CMD_METHOD_GET_LOCALS_INFO: {
8705 ERROR_DECL (error);
8706 int i, num_locals;
8707 MonoDebugLocalsInfo *locals;
8708 int *locals_map = NULL;
8710 header = mono_method_get_header_checked (method, error);
8711 if (!header) {
8712 add_error_string (buf, mono_error_get_message (error));
8713 mono_error_cleanup (error); /* FIXME don't swallow the error */
8714 return ERR_INVALID_ARGUMENT;
8717 locals = mono_debug_lookup_locals (method);
8718 if (!locals) {
8719 if (CHECK_PROTOCOL_VERSION (2, 43)) {
8720 /* Scopes */
8721 buffer_add_int (buf, 1);
8722 buffer_add_int (buf, 0);
8723 buffer_add_int (buf, header->code_size);
8725 buffer_add_int (buf, header->num_locals);
8726 /* Types */
8727 for (i = 0; i < header->num_locals; ++i) {
8728 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (header->locals [i]));
8730 /* Names */
8731 for (i = 0; i < header->num_locals; ++i) {
8732 char lname [128];
8733 sprintf (lname, "V_%d", i);
8734 buffer_add_string (buf, lname);
8736 /* Scopes */
8737 for (i = 0; i < header->num_locals; ++i) {
8738 buffer_add_int (buf, 0);
8739 buffer_add_int (buf, header->code_size);
8741 } else {
8742 if (CHECK_PROTOCOL_VERSION (2, 43)) {
8743 /* Scopes */
8744 buffer_add_int (buf, locals->num_blocks);
8745 int last_start = 0;
8746 for (i = 0; i < locals->num_blocks; ++i) {
8747 buffer_add_int (buf, locals->code_blocks [i].start_offset - last_start);
8748 buffer_add_int (buf, locals->code_blocks [i].end_offset - locals->code_blocks [i].start_offset);
8749 last_start = locals->code_blocks [i].start_offset;
8753 num_locals = locals->num_locals;
8754 buffer_add_int (buf, num_locals);
8756 /* Types */
8757 for (i = 0; i < num_locals; ++i) {
8758 g_assert (locals->locals [i].index < header->num_locals);
8759 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (header->locals [locals->locals [i].index]));
8761 /* Names */
8762 for (i = 0; i < num_locals; ++i)
8763 buffer_add_string (buf, locals->locals [i].name);
8764 /* Scopes */
8765 for (i = 0; i < num_locals; ++i) {
8766 if (locals->locals [i].block) {
8767 buffer_add_int (buf, locals->locals [i].block->start_offset);
8768 buffer_add_int (buf, locals->locals [i].block->end_offset);
8769 } else {
8770 buffer_add_int (buf, 0);
8771 buffer_add_int (buf, header->code_size);
8775 mono_metadata_free_mh (header);
8777 if (locals)
8778 mono_debug_free_locals (locals);
8779 g_free (locals_map);
8781 break;
8783 case CMD_METHOD_GET_INFO:
8784 buffer_add_int (buf, method->flags);
8785 buffer_add_int (buf, method->iflags);
8786 buffer_add_int (buf, method->token);
8787 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8788 guint8 attrs = 0;
8789 if (method->is_generic)
8790 attrs |= (1 << 0);
8791 if (mono_method_signature_internal (method)->generic_param_count)
8792 attrs |= (1 << 1);
8793 buffer_add_byte (buf, attrs);
8794 if (method->is_generic || method->is_inflated) {
8795 MonoMethod *result;
8797 if (method->is_generic) {
8798 result = method;
8799 } else {
8800 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8802 result = imethod->declaring;
8803 if (imethod->context.class_inst) {
8804 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8805 /*Generic methods gets the context of the GTD.*/
8806 if (mono_class_get_context (klass)) {
8807 ERROR_DECL (error);
8808 result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), error);
8809 if (!is_ok (error)) {
8810 add_error_string (buf, mono_error_get_message (error));
8811 mono_error_cleanup (error);
8812 return ERR_INVALID_ARGUMENT;
8818 buffer_add_methodid (buf, domain, result);
8819 } else {
8820 buffer_add_id (buf, 0);
8822 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8823 if (mono_method_signature_internal (method)->generic_param_count) {
8824 int count, i;
8826 if (method->is_inflated) {
8827 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
8828 if (inst) {
8829 count = inst->type_argc;
8830 buffer_add_int (buf, count);
8832 for (i = 0; i < count; i++)
8833 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (inst->type_argv [i]));
8834 } else {
8835 buffer_add_int (buf, 0);
8837 } else if (method->is_generic) {
8838 MonoGenericContainer *container = mono_method_get_generic_container (method);
8840 count = mono_method_signature_internal (method)->generic_param_count;
8841 buffer_add_int (buf, count);
8842 for (i = 0; i < count; i++) {
8843 MonoGenericParam *param = mono_generic_container_get_param (container, i);
8844 MonoClass *pklass = mono_class_create_generic_parameter (param);
8845 buffer_add_typeid (buf, domain, pklass);
8847 } else {
8848 buffer_add_int (buf, 0);
8850 } else {
8851 buffer_add_int (buf, 0);
8855 break;
8856 case CMD_METHOD_GET_BODY: {
8857 ERROR_DECL (error);
8858 int i;
8860 header = mono_method_get_header_checked (method, error);
8861 if (!header) {
8862 mono_error_cleanup (error); /* FIXME don't swallow the error */
8863 buffer_add_int (buf, 0);
8865 if (CHECK_PROTOCOL_VERSION (2, 18))
8866 buffer_add_int (buf, 0);
8867 } else {
8868 buffer_add_int (buf, header->code_size);
8869 for (i = 0; i < header->code_size; ++i)
8870 buffer_add_byte (buf, header->code [i]);
8872 if (CHECK_PROTOCOL_VERSION (2, 18)) {
8873 buffer_add_int (buf, header->num_clauses);
8874 for (i = 0; i < header->num_clauses; ++i) {
8875 MonoExceptionClause *clause = &header->clauses [i];
8877 buffer_add_int (buf, clause->flags);
8878 buffer_add_int (buf, clause->try_offset);
8879 buffer_add_int (buf, clause->try_len);
8880 buffer_add_int (buf, clause->handler_offset);
8881 buffer_add_int (buf, clause->handler_len);
8882 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
8883 buffer_add_typeid (buf, domain, clause->data.catch_class);
8884 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8885 buffer_add_int (buf, clause->data.filter_offset);
8889 mono_metadata_free_mh (header);
8892 break;
8894 case CMD_METHOD_RESOLVE_TOKEN: {
8895 guint32 token = decode_int (p, &p, end);
8897 // FIXME: Generics
8898 switch (mono_metadata_token_code (token)) {
8899 case MONO_TOKEN_STRING: {
8900 ERROR_DECL (error);
8901 MonoString *s;
8902 char *s2;
8904 s = mono_ldstr_checked (domain, m_class_get_image (method->klass), mono_metadata_token_index (token), error);
8905 mono_error_assert_ok (error); /* FIXME don't swallow the error */
8907 s2 = mono_string_to_utf8_checked_internal (s, error);
8908 mono_error_assert_ok (error);
8910 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8911 buffer_add_string (buf, s2);
8912 g_free (s2);
8913 break;
8915 default: {
8916 ERROR_DECL (error);
8917 gpointer val;
8918 MonoClass *handle_class;
8920 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8921 val = mono_method_get_wrapper_data (method, token);
8922 handle_class = (MonoClass *)mono_method_get_wrapper_data (method, token + 1);
8924 if (handle_class == NULL) {
8925 // Can't figure out the token type
8926 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8927 break;
8929 } else {
8930 val = mono_ldtoken_checked (m_class_get_image (method->klass), token, &handle_class, NULL, error);
8931 if (!val)
8932 g_error ("Could not load token due to %s", mono_error_get_message (error));
8935 if (handle_class == mono_defaults.typehandle_class) {
8936 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8937 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8938 buffer_add_typeid (buf, domain, (MonoClass *) val);
8939 else
8940 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal ((MonoType*)val));
8941 } else if (handle_class == mono_defaults.fieldhandle_class) {
8942 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8943 buffer_add_fieldid (buf, domain, (MonoClassField *)val);
8944 } else if (handle_class == mono_defaults.methodhandle_class) {
8945 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8946 buffer_add_methodid (buf, domain, (MonoMethod *)val);
8947 } else if (handle_class == mono_defaults.string_class) {
8948 char *s;
8950 s = mono_string_to_utf8_checked_internal ((MonoString *)val, error);
8951 if (!is_ok (error)) {
8952 add_error_string (buf, mono_error_get_message (error));
8953 mono_error_cleanup (error);
8954 g_free (s);
8955 return ERR_INVALID_ARGUMENT;
8957 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8958 buffer_add_string (buf, s);
8959 g_free (s);
8960 } else {
8961 g_assert_not_reached ();
8963 break;
8966 break;
8968 case CMD_METHOD_GET_CATTRS: {
8969 ERROR_DECL (error);
8970 MonoClass *attr_klass;
8971 MonoCustomAttrInfo *cinfo;
8973 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8974 /* attr_klass can be NULL */
8975 if (err != ERR_NONE)
8976 return err;
8978 cinfo = mono_custom_attrs_from_method_checked (method, error);
8979 if (!is_ok (error)) {
8980 mono_error_cleanup (error); /* FIXME don't swallow the error message */
8981 return ERR_LOADER_ERROR;
8984 err = buffer_add_cattrs (buf, domain, m_class_get_image (method->klass), attr_klass, cinfo);
8985 if (err != ERR_NONE)
8986 return err;
8987 break;
8989 case CMD_METHOD_MAKE_GENERIC_METHOD: {
8990 ERROR_DECL (error);
8991 MonoType **type_argv;
8992 int i, type_argc;
8993 MonoDomain *d;
8994 MonoClass *klass;
8995 MonoGenericInst *ginst;
8996 MonoGenericContext tmp_context;
8997 MonoMethod *inflated;
8999 type_argc = decode_int (p, &p, end);
9000 type_argv = g_new0 (MonoType*, type_argc);
9001 for (i = 0; i < type_argc; ++i) {
9002 klass = decode_typeid (p, &p, end, &d, &err);
9003 if (err != ERR_NONE) {
9004 g_free (type_argv);
9005 return err;
9007 if (domain != d) {
9008 g_free (type_argv);
9009 return ERR_INVALID_ARGUMENT;
9011 type_argv [i] = m_class_get_byval_arg (klass);
9013 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
9014 g_free (type_argv);
9015 tmp_context.class_inst = mono_class_is_ginst (method->klass) ? mono_class_get_generic_class (method->klass)->context.class_inst : NULL;
9016 tmp_context.method_inst = ginst;
9018 inflated = mono_class_inflate_generic_method_checked (method, &tmp_context, error);
9019 if (!is_ok (error)) {
9020 add_error_string (buf, mono_error_get_message (error));
9021 mono_error_cleanup (error);
9022 return ERR_INVALID_ARGUMENT;
9024 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
9025 return ERR_INVALID_ARGUMENT;
9026 buffer_add_methodid (buf, domain, inflated);
9027 break;
9029 default:
9030 return ERR_NOT_IMPLEMENTED;
9033 return ERR_NONE;
9036 static ErrorCode
9037 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9039 ErrorCode err;
9040 MonoDomain *old_domain;
9041 MonoDomain *domain;
9042 MonoMethod *method;
9044 method = decode_methodid (p, &p, end, &domain, &err);
9045 if (err != ERR_NONE)
9046 return err;
9048 old_domain = mono_domain_get ();
9050 mono_domain_set_fast (domain, TRUE);
9052 err = method_commands_internal (command, method, domain, p, end, buf);
9054 mono_domain_set_fast (old_domain, TRUE);
9056 return err;
9059 static ErrorCode
9060 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9062 int objid = decode_objid (p, &p, end);
9063 ErrorCode err;
9064 MonoThread *thread_obj;
9065 MonoInternalThread *thread;
9067 err = get_object (objid, (MonoObject**)&thread_obj);
9068 if (err != ERR_NONE)
9069 return err;
9071 thread = THREAD_TO_INTERNAL (thread_obj);
9073 switch (command) {
9074 case CMD_THREAD_GET_NAME: {
9075 char *s = mono_thread_get_name_utf8 (thread_obj);
9077 if (!s) {
9078 buffer_add_int (buf, 0);
9079 } else {
9080 const size_t len = strlen (s);
9081 buffer_add_int (buf, len);
9082 buffer_add_data (buf, (guint8*)s, len);
9083 g_free (s);
9085 break;
9087 case CMD_THREAD_GET_FRAME_INFO: {
9088 DebuggerTlsData *tls;
9089 int i, start_frame, length;
9091 // Wait for suspending if it already started
9092 // FIXME: Races with suspend_count
9093 while (!is_suspended ()) {
9094 if (suspend_count)
9095 wait_for_suspend ();
9098 if (suspend_count)
9099 wait_for_suspend ();
9100 if (!is_suspended ())
9101 return ERR_NOT_SUSPENDED;
9104 start_frame = decode_int (p, &p, end);
9105 length = decode_int (p, &p, end);
9107 if (start_frame != 0 || length != -1)
9108 return ERR_NOT_IMPLEMENTED;
9110 mono_loader_lock ();
9111 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9112 mono_loader_unlock ();
9113 if (tls == NULL)
9114 return ERR_UNLOADED;
9116 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
9118 buffer_add_int (buf, tls->frame_count);
9119 for (i = 0; i < tls->frame_count; ++i) {
9120 buffer_add_int (buf, tls->frames [i]->id);
9121 buffer_add_methodid (buf, tls->frames [i]->de.domain, tls->frames [i]->actual_method);
9122 buffer_add_int (buf, tls->frames [i]->il_offset);
9124 * Instead of passing the frame type directly to the client, we associate
9125 * it with the previous frame using a set of flags. This avoids lots of
9126 * conditional code in the client, since a frame whose type isn't
9127 * FRAME_TYPE_MANAGED has no method, location, etc.
9129 buffer_add_byte (buf, tls->frames [i]->flags);
9132 break;
9134 case CMD_THREAD_GET_STATE:
9135 buffer_add_int (buf, thread->state);
9136 break;
9137 case CMD_THREAD_GET_INFO:
9138 buffer_add_byte (buf, thread->threadpool_thread);
9139 break;
9140 case CMD_THREAD_GET_ID:
9141 buffer_add_long (buf, (guint64)(gsize)thread);
9142 break;
9143 case CMD_THREAD_GET_TID:
9144 buffer_add_long (buf, (guint64)thread->tid);
9145 break;
9146 case CMD_THREAD_SET_IP: {
9147 DebuggerTlsData *tls;
9148 MonoMethod *method;
9149 MonoDomain *domain;
9150 MonoSeqPointInfo *seq_points;
9151 SeqPoint sp;
9152 gboolean found_sp;
9153 gint64 il_offset;
9155 method = decode_methodid (p, &p, end, &domain, &err);
9156 if (err != ERR_NONE)
9157 return err;
9158 il_offset = decode_long (p, &p, end);
9160 while (!is_suspended ()) {
9161 if (suspend_count)
9162 wait_for_suspend ();
9165 mono_loader_lock ();
9166 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9167 mono_loader_unlock ();
9168 g_assert (tls);
9170 compute_frame_info (thread, tls, FALSE);
9171 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
9172 return ERR_INVALID_ARGUMENT;
9174 found_sp = mono_find_seq_point (domain, method, il_offset, &seq_points, &sp);
9176 g_assert (seq_points);
9178 if (!found_sp)
9179 return ERR_INVALID_ARGUMENT;
9181 // FIXME: Check that the ip change is safe
9183 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);
9185 if (tls->frames [0]->de.ji->is_interp) {
9186 MonoJitTlsData *jit_data = thread->thread_info->jit_data;
9187 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);
9188 } else {
9189 MONO_CONTEXT_SET_IP (&tls->restore_state.ctx, (guint8*)tls->frames [0]->de.ji->code_start + sp.native_offset);
9191 break;
9193 case CMD_THREAD_ELAPSED_TIME: {
9194 DebuggerTlsData *tls;
9195 mono_loader_lock ();
9196 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9197 mono_loader_unlock ();
9198 g_assert (tls);
9199 buffer_add_long (buf, (long)mono_stopwatch_elapsed_ms (&tls->step_time));
9200 break;
9202 default:
9203 return ERR_NOT_IMPLEMENTED;
9206 return ERR_NONE;
9209 static ErrorCode
9210 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9212 int objid;
9213 ErrorCode err;
9214 MonoThread *thread_obj;
9215 MonoInternalThread *thread;
9216 int pos, i, len, frame_idx;
9217 DebuggerTlsData *tls;
9218 StackFrame *frame;
9219 MonoDebugMethodJitInfo *jit;
9220 MonoMethodSignature *sig;
9221 gssize id;
9222 MonoMethodHeader *header;
9224 objid = decode_objid (p, &p, end);
9225 err = get_object (objid, (MonoObject**)&thread_obj);
9226 if (err != ERR_NONE)
9227 return err;
9229 thread = THREAD_TO_INTERNAL (thread_obj);
9231 id = decode_id (p, &p, end);
9233 mono_loader_lock ();
9234 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9235 mono_loader_unlock ();
9236 g_assert (tls);
9238 for (i = 0; i < tls->frame_count; ++i) {
9239 if (tls->frames [i]->id == id)
9240 break;
9242 if (i == tls->frame_count)
9243 return ERR_INVALID_FRAMEID;
9245 /* The thread is still running native code, can't get frame variables info */
9246 if (!tls->really_suspended && !tls->async_state.valid)
9247 return ERR_NOT_SUSPENDED;
9248 frame_idx = i;
9249 frame = tls->frames [frame_idx];
9251 /* This is supported for frames without has_ctx etc. set */
9252 if (command == CMD_STACK_FRAME_GET_DOMAIN) {
9253 if (CHECK_PROTOCOL_VERSION (2, 38))
9254 buffer_add_domainid (buf, frame->de.domain);
9255 return ERR_NONE;
9258 if (!frame->has_ctx)
9259 return ERR_ABSENT_INFORMATION;
9261 if (!ensure_jit ((DbgEngineStackFrame*)frame))
9262 return ERR_ABSENT_INFORMATION;
9264 jit = frame->jit;
9266 sig = mono_method_signature_internal (frame->actual_method);
9268 if (!(jit->has_var_info || frame->de.ji->is_interp) || !mono_get_seq_points (frame->de.domain, frame->actual_method))
9270 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
9272 return ERR_ABSENT_INFORMATION;
9274 switch (command) {
9275 case CMD_STACK_FRAME_GET_VALUES: {
9276 ERROR_DECL (error);
9277 len = decode_int (p, &p, end);
9278 header = mono_method_get_header_checked (frame->actual_method, error);
9279 mono_error_assert_ok (error); /* FIXME report error */
9281 for (i = 0; i < len; ++i) {
9282 pos = decode_int (p, &p, end);
9284 if (pos < 0) {
9285 pos = - pos - 1;
9287 PRINT_DEBUG_MSG (4, "[dbg] send arg %d.\n", pos);
9289 if (frame->de.ji->is_interp) {
9290 guint8 *addr;
9292 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_arg (frame->interp_frame, pos);
9294 buffer_add_value_full (buf, sig->params [pos], addr, frame->de.domain, FALSE, NULL, 1);
9295 } else {
9296 g_assert (pos >= 0 && pos < jit->num_params);
9298 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->de.domain, FALSE);
9300 } else {
9301 MonoDebugLocalsInfo *locals;
9303 locals = mono_debug_lookup_locals (frame->de.method);
9304 if (locals) {
9305 g_assert (pos < locals->num_locals);
9306 pos = locals->locals [pos].index;
9307 mono_debug_free_locals (locals);
9310 PRINT_DEBUG_MSG (4, "[dbg] send local %d.\n", pos);
9312 if (frame->de.ji->is_interp) {
9313 guint8 *addr;
9315 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_local (frame->interp_frame, pos);
9317 buffer_add_value_full (buf, header->locals [pos], addr, frame->de.domain, FALSE, NULL, 1);
9318 } else {
9319 g_assert (pos >= 0 && pos < jit->num_locals);
9321 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->de.domain, FALSE);
9325 mono_metadata_free_mh (header);
9326 break;
9328 case CMD_STACK_FRAME_GET_THIS: {
9329 if (frame->de.method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE)
9330 return ERR_ABSENT_INFORMATION;
9331 if (m_class_is_valuetype (frame->api_method->klass)) {
9332 if (!sig->hasthis) {
9333 MonoObject *p = NULL;
9334 buffer_add_value (buf, mono_get_object_type (), &p, frame->de.domain);
9335 } else {
9336 if (frame->de.ji->is_interp) {
9337 guint8 *addr;
9339 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_this (frame->interp_frame);
9341 buffer_add_value_full (buf, m_class_get_this_arg (frame->actual_method->klass), addr, frame->de.domain, FALSE, NULL, 1);
9342 } else {
9343 add_var (buf, jit, m_class_get_this_arg (frame->actual_method->klass), jit->this_var, &frame->ctx, frame->de.domain, TRUE);
9346 } else {
9347 if (!sig->hasthis) {
9348 MonoObject *p = NULL;
9349 buffer_add_value (buf, m_class_get_byval_arg (frame->actual_method->klass), &p, frame->de.domain);
9350 } else {
9351 if (frame->de.ji->is_interp) {
9352 guint8 *addr;
9354 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_this (frame->interp_frame);
9356 buffer_add_value_full (buf, m_class_get_byval_arg (frame->api_method->klass), addr, frame->de.domain, FALSE, NULL, 1);
9357 } else {
9358 add_var (buf, jit, m_class_get_byval_arg (frame->api_method->klass), jit->this_var, &frame->ctx, frame->de.domain, TRUE);
9362 break;
9364 case CMD_STACK_FRAME_SET_VALUES: {
9365 ERROR_DECL (error);
9366 guint8 *val_buf;
9367 MonoType *t;
9368 MonoDebugVarInfo *var = NULL;
9369 gboolean is_arg = FALSE;
9371 len = decode_int (p, &p, end);
9372 header = mono_method_get_header_checked (frame->actual_method, error);
9373 mono_error_assert_ok (error); /* FIXME report error */
9375 for (i = 0; i < len; ++i) {
9376 pos = decode_int (p, &p, end);
9378 if (pos < 0) {
9379 pos = - pos - 1;
9381 g_assert (pos >= 0 && pos < jit->num_params);
9383 t = sig->params [pos];
9384 var = &jit->params [pos];
9385 is_arg = TRUE;
9386 } else {
9387 MonoDebugLocalsInfo *locals;
9389 locals = mono_debug_lookup_locals (frame->de.method);
9390 if (locals) {
9391 g_assert (pos < locals->num_locals);
9392 pos = locals->locals [pos].index;
9393 mono_debug_free_locals (locals);
9395 g_assert (pos >= 0 && pos < jit->num_locals);
9397 t = header->locals [pos];
9398 var = &jit->locals [pos];
9401 if (MONO_TYPE_IS_REFERENCE (t))
9402 val_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
9403 else
9404 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type_internal (t)));
9405 err = decode_value (t, frame->de.domain, val_buf, p, &p, end, TRUE);
9406 if (err != ERR_NONE)
9407 return err;
9409 if (frame->de.ji->is_interp) {
9410 guint8 *addr;
9412 if (is_arg)
9413 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_arg (frame->interp_frame, pos);
9414 else
9415 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_local (frame->interp_frame, pos);
9416 set_interp_var (t, addr, val_buf);
9417 } else {
9418 set_var (t, var, &frame->ctx, frame->de.domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9421 mono_metadata_free_mh (header);
9422 break;
9424 case CMD_STACK_FRAME_GET_DOMAIN: {
9425 if (CHECK_PROTOCOL_VERSION (2, 38))
9426 buffer_add_domainid (buf, frame->de.domain);
9427 break;
9429 case CMD_STACK_FRAME_SET_THIS: {
9430 guint8 *val_buf;
9431 MonoType *t;
9432 MonoDebugVarInfo *var;
9434 t = m_class_get_byval_arg (frame->actual_method->klass);
9435 /* Checked by the sender */
9436 g_assert (MONO_TYPE_ISSTRUCT (t));
9438 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type_internal (t)));
9439 err = decode_value (t, frame->de.domain, val_buf, p, &p, end, TRUE);
9440 if (err != ERR_NONE)
9441 return err;
9443 if (frame->de.ji->is_interp) {
9444 guint8 *addr;
9446 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_this (frame->interp_frame);
9447 set_interp_var (m_class_get_this_arg (frame->actual_method->klass), addr, val_buf);
9448 } else {
9449 var = jit->this_var;
9450 if (!var) {
9451 add_error_string (buf, "Invalid this object");
9452 return ERR_INVALID_ARGUMENT;
9455 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);
9457 break;
9459 default:
9460 return ERR_NOT_IMPLEMENTED;
9463 return ERR_NONE;
9466 static ErrorCode
9467 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9469 MonoArray *arr;
9470 int objid, index, len, i, esize;
9471 ErrorCode err;
9472 gpointer elem;
9474 objid = decode_objid (p, &p, end);
9475 err = get_object (objid, (MonoObject**)&arr);
9476 if (err != ERR_NONE)
9477 return err;
9479 switch (command) {
9480 case CMD_ARRAY_REF_GET_LENGTH:
9481 buffer_add_int (buf, m_class_get_rank (arr->obj.vtable->klass));
9482 if (!arr->bounds) {
9483 buffer_add_int (buf, arr->max_length);
9484 buffer_add_int (buf, 0);
9485 } else {
9486 for (i = 0; i < m_class_get_rank (arr->obj.vtable->klass); ++i) {
9487 buffer_add_int (buf, arr->bounds [i].length);
9488 buffer_add_int (buf, arr->bounds [i].lower_bound);
9491 break;
9492 case CMD_ARRAY_REF_GET_VALUES:
9493 index = decode_int (p, &p, end);
9494 len = decode_int (p, &p, end);
9496 if (index < 0 || len < 0)
9497 return ERR_INVALID_ARGUMENT;
9498 // Reordered to avoid integer overflow
9499 if (index > arr->max_length - len)
9500 return ERR_INVALID_ARGUMENT;
9502 esize = mono_array_element_size (arr->obj.vtable->klass);
9503 for (i = index; i < index + len; ++i) {
9504 elem = (gpointer*)((char*)arr->vector + (i * esize));
9505 buffer_add_value (buf, m_class_get_byval_arg (m_class_get_element_class (arr->obj.vtable->klass)), elem, arr->obj.vtable->domain);
9507 break;
9508 case CMD_ARRAY_REF_SET_VALUES:
9509 index = decode_int (p, &p, end);
9510 len = decode_int (p, &p, end);
9512 if (index < 0 || len < 0)
9513 return ERR_INVALID_ARGUMENT;
9514 // Reordered to avoid integer overflow
9515 if (index > arr->max_length - len)
9516 return ERR_INVALID_ARGUMENT;
9518 esize = mono_array_element_size (arr->obj.vtable->klass);
9519 for (i = index; i < index + len; ++i) {
9520 elem = (gpointer*)((char*)arr->vector + (i * esize));
9522 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);
9524 break;
9525 default:
9526 return ERR_NOT_IMPLEMENTED;
9529 return ERR_NONE;
9532 static ErrorCode
9533 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9535 int objid;
9536 ErrorCode err;
9537 MonoString *str;
9538 char *s;
9539 int i, index, length;
9540 gunichar2 *c;
9541 gboolean use_utf16 = FALSE;
9543 objid = decode_objid (p, &p, end);
9544 err = get_object (objid, (MonoObject**)&str);
9545 if (err != ERR_NONE)
9546 return err;
9548 switch (command) {
9549 case CMD_STRING_REF_GET_VALUE:
9550 if (CHECK_PROTOCOL_VERSION (2, 41)) {
9551 for (i = 0; i < mono_string_length_internal (str); ++i)
9552 if (mono_string_chars_internal (str)[i] == 0)
9553 use_utf16 = TRUE;
9554 buffer_add_byte (buf, use_utf16 ? 1 : 0);
9556 if (use_utf16) {
9557 buffer_add_int (buf, mono_string_length_internal (str) * 2);
9558 buffer_add_utf16 (buf, (guint8*)mono_string_chars_internal (str), mono_string_length_internal (str) * 2);
9559 } else {
9560 ERROR_DECL (error);
9561 s = mono_string_to_utf8_checked_internal (str, error);
9562 if (!is_ok (error)) {
9563 if (s)
9564 g_free (s);
9565 add_error_string (buf, mono_error_get_message (error));
9566 return ERR_INVALID_ARGUMENT;
9568 buffer_add_string (buf, s);
9569 g_free (s);
9571 break;
9572 case CMD_STRING_REF_GET_LENGTH:
9573 buffer_add_long (buf, mono_string_length_internal (str));
9574 break;
9575 case CMD_STRING_REF_GET_CHARS:
9576 index = decode_long (p, &p, end);
9577 length = decode_long (p, &p, end);
9578 if (index > mono_string_length_internal (str) - length)
9579 return ERR_INVALID_ARGUMENT;
9580 c = mono_string_chars_internal (str) + index;
9581 for (i = 0; i < length; ++i)
9582 buffer_add_short (buf, c [i]);
9583 break;
9584 default:
9585 return ERR_NOT_IMPLEMENTED;
9588 return ERR_NONE;
9591 static void
9592 create_file_to_check_memory_address (void)
9594 if (file_check_valid_memory != -1)
9595 return;
9596 char *file_name = g_strdup_printf ("debugger_check_valid_memory.%d", getpid());
9597 filename_check_valid_memory = g_build_filename (g_get_tmp_dir (), file_name, (const char*)NULL);
9598 file_check_valid_memory = open(filename_check_valid_memory, O_CREAT | O_WRONLY | O_APPEND, S_IWUSR);
9599 g_free (file_name);
9602 static gboolean
9603 valid_memory_address (gpointer addr, gint size)
9605 #ifndef _MSC_VER
9606 gboolean ret = TRUE;
9607 create_file_to_check_memory_address ();
9608 if(file_check_valid_memory < 0) {
9609 return TRUE;
9611 write (file_check_valid_memory, (gpointer)addr, 1);
9612 if (errno == EFAULT) {
9613 ret = FALSE;
9615 #else
9616 int i = 0;
9617 gboolean ret = FALSE;
9618 __try {
9619 for (i = 0; i < size; i++)
9620 *((volatile char*)addr+i);
9621 ret = TRUE;
9622 } __except(1) {
9623 return ret;
9625 #endif
9626 return ret;
9629 static ErrorCode
9630 pointer_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9632 ErrorCode err;
9633 gint64 addr;
9634 MonoClass* klass;
9635 MonoDomain* domain = NULL;
9636 MonoType *type = NULL;
9637 int align;
9638 int size = 0;
9640 switch (command) {
9641 case CMD_POINTER_GET_VALUE:
9642 addr = decode_long (p, &p, end);
9643 klass = decode_typeid (p, &p, end, &domain, &err);
9644 if (err != ERR_NONE)
9645 return err;
9647 if (m_class_get_byval_arg (klass)->type != MONO_TYPE_PTR)
9648 return ERR_INVALID_ARGUMENT;
9650 type = m_class_get_byval_arg (m_class_get_element_class (klass));
9651 size = mono_type_size (type, &align);
9653 if (!valid_memory_address((gpointer)addr, size))
9654 return ERR_INVALID_ARGUMENT;
9656 buffer_add_value (buf, type, (gpointer)addr, domain);
9658 break;
9659 default:
9660 return ERR_NOT_IMPLEMENTED;
9663 return ERR_NONE;
9666 static ErrorCode
9667 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9669 HANDLE_FUNCTION_ENTER ();
9671 ERROR_DECL (error);
9672 int objid;
9673 ErrorCode err;
9674 MonoObject *obj;
9675 int len, i;
9676 MonoClassField *f;
9677 MonoClass *k;
9678 gboolean found;
9679 gboolean remote_obj = FALSE;
9680 MonoStringHandle string_handle = MONO_HANDLE_NEW (MonoString, NULL); // FIXME? Not always needed.
9682 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9683 objid = decode_objid (p, &p, end);
9684 err = get_object (objid, &obj);
9685 if (err != ERR_NONE)
9686 buffer_add_int (buf, 1);
9687 else
9688 buffer_add_int (buf, 0);
9689 err = ERR_NONE;
9690 goto exit;
9693 objid = decode_objid (p, &p, end);
9694 err = get_object (objid, &obj);
9695 if (err != ERR_NONE)
9696 goto exit;
9698 MonoClass *obj_type;
9700 obj_type = obj->vtable->klass;
9701 if (mono_class_is_transparent_proxy (obj_type)) {
9702 obj_type = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
9703 remote_obj = TRUE;
9706 g_assert (obj_type);
9708 switch (command) {
9709 case CMD_OBJECT_REF_GET_TYPE:
9710 /* This handles transparent proxies too */
9711 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type_internal (((MonoReflectionType*)obj->vtable->type)->type));
9712 break;
9713 case CMD_OBJECT_REF_GET_VALUES:
9714 len = decode_int (p, &p, end);
9716 for (i = 0; i < len; ++i) {
9717 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9718 if (err != ERR_NONE)
9719 goto exit;
9721 /* Check that the field belongs to the object */
9722 found = FALSE;
9723 for (k = obj_type; k; k = m_class_get_parent (k)) {
9724 if (k == f->parent) {
9725 found = TRUE;
9726 break;
9729 if (!found)
9730 goto invalid_fieldid;
9732 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9733 guint8 *val;
9734 MonoVTable *vtable;
9736 if (mono_class_field_is_special_static (f))
9737 goto invalid_fieldid;
9739 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9740 vtable = mono_class_vtable_checked (obj->vtable->domain, f->parent, error);
9741 if (!is_ok (error)) {
9742 mono_error_cleanup (error);
9743 goto invalid_object;
9745 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type_internal (f->type)));
9746 mono_field_static_get_value_checked (vtable, f, val, string_handle, error);
9747 if (!is_ok (error)) {
9748 mono_error_cleanup (error); /* FIXME report the error */
9749 goto invalid_object;
9751 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9752 g_free (val);
9753 } else {
9754 void *field_value = NULL;
9755 #ifndef DISABLE_REMOTING
9756 void *field_storage = NULL;
9757 #endif
9758 if (remote_obj) {
9759 #ifndef DISABLE_REMOTING
9760 field_value = mono_load_remote_field_checked(obj, obj_type, f, &field_storage, error);
9761 if (!is_ok (error)) {
9762 mono_error_cleanup (error); /* FIXME report the error */
9763 goto invalid_object;
9765 #else
9766 g_assert_not_reached ();
9767 #endif
9768 } else
9769 field_value = (guint8*)obj + f->offset;
9771 buffer_add_value (buf, f->type, field_value, obj->vtable->domain);
9774 break;
9775 case CMD_OBJECT_REF_SET_VALUES:
9776 len = decode_int (p, &p, end);
9778 for (i = 0; i < len; ++i) {
9779 f = decode_fieldid (p, &p, end, NULL, &err);
9780 if (err != ERR_NONE)
9781 goto exit;
9783 /* Check that the field belongs to the object */
9784 found = FALSE;
9785 for (k = obj_type; k; k = m_class_get_parent (k)) {
9786 if (k == f->parent) {
9787 found = TRUE;
9788 break;
9791 if (!found)
9792 goto invalid_fieldid;
9794 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9795 guint8 *val;
9796 MonoVTable *vtable;
9798 if (mono_class_field_is_special_static (f))
9799 goto invalid_fieldid;
9801 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9802 vtable = mono_class_vtable_checked (obj->vtable->domain, f->parent, error);
9803 if (!is_ok (error)) {
9804 mono_error_cleanup (error);
9805 goto invalid_fieldid;
9808 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type_internal (f->type)));
9809 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end, TRUE);
9810 if (err != ERR_NONE) {
9811 g_free (val);
9812 goto exit;
9814 mono_field_static_set_value_internal (vtable, f, val);
9815 g_free (val);
9816 } else {
9817 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end, TRUE);
9818 if (err != ERR_NONE)
9819 goto exit;
9822 break;
9823 case CMD_OBJECT_REF_GET_ADDRESS:
9824 buffer_add_long (buf, (gssize)obj);
9825 break;
9826 case CMD_OBJECT_REF_GET_DOMAIN:
9827 buffer_add_domainid (buf, obj->vtable->domain);
9828 break;
9829 case CMD_OBJECT_REF_GET_INFO:
9830 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type_internal (((MonoReflectionType*)obj->vtable->type)->type));
9831 buffer_add_domainid (buf, obj->vtable->domain);
9832 break;
9833 default:
9834 err = ERR_NOT_IMPLEMENTED;
9835 goto exit;
9838 err = ERR_NONE;
9839 goto exit;
9840 invalid_fieldid:
9841 err = ERR_INVALID_FIELDID;
9842 goto exit;
9843 invalid_object:
9844 err = ERR_INVALID_OBJECT;
9845 goto exit;
9846 exit:
9847 HANDLE_FUNCTION_RETURN_VAL (err);
9850 static const char*
9851 command_set_to_string (CommandSet command_set)
9853 switch (command_set) {
9854 case CMD_SET_VM:
9855 return "VM";
9856 case CMD_SET_OBJECT_REF:
9857 return "OBJECT_REF";
9858 case CMD_SET_STRING_REF:
9859 return "STRING_REF";
9860 case CMD_SET_THREAD:
9861 return "THREAD";
9862 case CMD_SET_ARRAY_REF:
9863 return "ARRAY_REF";
9864 case CMD_SET_EVENT_REQUEST:
9865 return "EVENT_REQUEST";
9866 case CMD_SET_STACK_FRAME:
9867 return "STACK_FRAME";
9868 case CMD_SET_APPDOMAIN:
9869 return "APPDOMAIN";
9870 case CMD_SET_ASSEMBLY:
9871 return "ASSEMBLY";
9872 case CMD_SET_METHOD:
9873 return "METHOD";
9874 case CMD_SET_TYPE:
9875 return "TYPE";
9876 case CMD_SET_MODULE:
9877 return "MODULE";
9878 case CMD_SET_FIELD:
9879 return "FIELD";
9880 case CMD_SET_EVENT:
9881 return "EVENT";
9882 case CMD_SET_POINTER:
9883 return "POINTER";
9884 default:
9885 return "";
9889 static const char* vm_cmds_str [] = {
9890 "VERSION",
9891 "ALL_THREADS",
9892 "SUSPEND",
9893 "RESUME",
9894 "EXIT",
9895 "DISPOSE",
9896 "INVOKE_METHOD",
9897 "SET_PROTOCOL_VERSION",
9898 "ABORT_INVOKE",
9899 "SET_KEEPALIVE",
9900 "GET_TYPES_FOR_SOURCE_FILE",
9901 "GET_TYPES",
9902 "INVOKE_METHODS"
9905 static const char* thread_cmds_str[] = {
9906 "GET_FRAME_INFO",
9907 "GET_NAME",
9908 "GET_STATE",
9909 "GET_INFO",
9910 "GET_ID",
9911 "GET_TID",
9912 "SET_IP"
9915 static const char* event_cmds_str[] = {
9916 "REQUEST_SET",
9917 "REQUEST_CLEAR",
9918 "REQUEST_CLEAR_ALL_BREAKPOINTS"
9921 static const char* appdomain_cmds_str[] = {
9922 "GET_ROOT_DOMAIN",
9923 "GET_FRIENDLY_NAME",
9924 "GET_ASSEMBLIES",
9925 "GET_ENTRY_ASSEMBLY",
9926 "CREATE_STRING",
9927 "GET_CORLIB",
9928 "CREATE_BOXED_VALUE",
9929 "CREATE_BYTE_ARRAY",
9932 static const char* assembly_cmds_str[] = {
9933 "GET_LOCATION",
9934 "GET_ENTRY_POINT",
9935 "GET_MANIFEST_MODULE",
9936 "GET_OBJECT",
9937 "GET_TYPE",
9938 "GET_NAME",
9939 "GET_DOMAIN",
9940 "HAS_DEBUG_INFO"
9943 static const char* module_cmds_str[] = {
9944 "GET_INFO",
9947 static const char* field_cmds_str[] = {
9948 "GET_INFO",
9951 static const char* method_cmds_str[] = {
9952 "GET_NAME",
9953 "GET_DECLARING_TYPE",
9954 "GET_DEBUG_INFO",
9955 "GET_PARAM_INFO",
9956 "GET_LOCALS_INFO",
9957 "GET_INFO",
9958 "GET_BODY",
9959 "RESOLVE_TOKEN",
9960 "GET_CATTRS ",
9961 "MAKE_GENERIC_METHOD"
9964 static const char* type_cmds_str[] = {
9965 "GET_INFO",
9966 "GET_METHODS",
9967 "GET_FIELDS",
9968 "GET_VALUES",
9969 "GET_OBJECT",
9970 "GET_SOURCE_FILES",
9971 "SET_VALUES",
9972 "IS_ASSIGNABLE_FROM",
9973 "GET_PROPERTIES ",
9974 "GET_CATTRS",
9975 "GET_FIELD_CATTRS",
9976 "GET_PROPERTY_CATTRS",
9977 "GET_SOURCE_FILES_2",
9978 "GET_VALUES_2",
9979 "GET_METHODS_BY_NAME_FLAGS",
9980 "GET_INTERFACES",
9981 "GET_INTERFACE_MAP",
9982 "IS_INITIALIZED",
9983 "CREATE_INSTANCE",
9984 "GET_VALUE_SIZE"
9987 static const char* stack_frame_cmds_str[] = {
9988 "GET_VALUES",
9989 "GET_THIS",
9990 "SET_VALUES",
9991 "GET_DOMAIN",
9992 "SET_THIS"
9995 static const char* array_cmds_str[] = {
9996 "GET_LENGTH",
9997 "GET_VALUES",
9998 "SET_VALUES",
10001 static const char* string_cmds_str[] = {
10002 "GET_VALUE",
10003 "GET_LENGTH",
10004 "GET_CHARS"
10007 static const char* pointer_cmds_str[] = {
10008 "GET_VALUE"
10011 static const char* object_cmds_str[] = {
10012 "GET_TYPE",
10013 "GET_VALUES",
10014 "IS_COLLECTED",
10015 "GET_ADDRESS",
10016 "GET_DOMAIN",
10017 "SET_VALUES",
10018 "GET_INFO",
10021 static const char*
10022 cmd_to_string (CommandSet set, int command)
10024 const char **cmds;
10025 int cmds_len = 0;
10027 switch (set) {
10028 case CMD_SET_VM:
10029 cmds = vm_cmds_str;
10030 cmds_len = G_N_ELEMENTS (vm_cmds_str);
10031 break;
10032 case CMD_SET_OBJECT_REF:
10033 cmds = object_cmds_str;
10034 cmds_len = G_N_ELEMENTS (object_cmds_str);
10035 break;
10036 case CMD_SET_STRING_REF:
10037 cmds = string_cmds_str;
10038 cmds_len = G_N_ELEMENTS (string_cmds_str);
10039 break;
10040 case CMD_SET_THREAD:
10041 cmds = thread_cmds_str;
10042 cmds_len = G_N_ELEMENTS (thread_cmds_str);
10043 break;
10044 case CMD_SET_ARRAY_REF:
10045 cmds = array_cmds_str;
10046 cmds_len = G_N_ELEMENTS (array_cmds_str);
10047 break;
10048 case CMD_SET_EVENT_REQUEST:
10049 cmds = event_cmds_str;
10050 cmds_len = G_N_ELEMENTS (event_cmds_str);
10051 break;
10052 case CMD_SET_STACK_FRAME:
10053 cmds = stack_frame_cmds_str;
10054 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
10055 break;
10056 case CMD_SET_APPDOMAIN:
10057 cmds = appdomain_cmds_str;
10058 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
10059 break;
10060 case CMD_SET_ASSEMBLY:
10061 cmds = assembly_cmds_str;
10062 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
10063 break;
10064 case CMD_SET_METHOD:
10065 cmds = method_cmds_str;
10066 cmds_len = G_N_ELEMENTS (method_cmds_str);
10067 break;
10068 case CMD_SET_TYPE:
10069 cmds = type_cmds_str;
10070 cmds_len = G_N_ELEMENTS (type_cmds_str);
10071 break;
10072 case CMD_SET_MODULE:
10073 cmds = module_cmds_str;
10074 cmds_len = G_N_ELEMENTS (module_cmds_str);
10075 break;
10076 case CMD_SET_FIELD:
10077 cmds = field_cmds_str;
10078 cmds_len = G_N_ELEMENTS (field_cmds_str);
10079 break;
10080 case CMD_SET_EVENT:
10081 cmds = event_cmds_str;
10082 cmds_len = G_N_ELEMENTS (event_cmds_str);
10083 break;
10084 case CMD_SET_POINTER:
10085 cmds = pointer_cmds_str;
10086 cmds_len = G_N_ELEMENTS (pointer_cmds_str);
10087 break;
10088 default:
10089 return NULL;
10091 if (command > 0 && command <= cmds_len)
10092 return cmds [command - 1];
10093 else
10094 return NULL;
10097 static gboolean
10098 wait_for_attach (void)
10100 #ifndef DISABLE_SOCKET_TRANSPORT
10101 if (listen_fd == -1) {
10102 PRINT_DEBUG_MSG (1, "[dbg] Invalid listening socket\n");
10103 return FALSE;
10106 /* Block and wait for client connection */
10107 conn_fd = socket_transport_accept (listen_fd);
10109 PRINT_DEBUG_MSG (1, "Accepted connection on %d\n", conn_fd);
10110 if (conn_fd == -1) {
10111 PRINT_DEBUG_MSG (1, "[dbg] Bad client connection\n");
10112 return FALSE;
10114 #else
10115 g_assert_not_reached ();
10116 #endif
10118 /* Handshake */
10119 disconnected = !transport_handshake ();
10120 if (disconnected) {
10121 PRINT_DEBUG_MSG (1, "Transport handshake failed!\n");
10122 return FALSE;
10125 return TRUE;
10129 * debugger_thread:
10131 * This thread handles communication with the debugger client using a JDWP
10132 * like protocol.
10134 static gsize WINAPI
10135 debugger_thread (void *arg)
10137 int res, len, id, flags, command = 0;
10138 CommandSet command_set = (CommandSet)0;
10139 guint8 header [HEADER_LENGTH];
10140 guint8 *data, *p, *end;
10141 Buffer buf;
10142 ErrorCode err;
10143 gboolean no_reply;
10144 gboolean attach_failed = FALSE;
10146 PRINT_DEBUG_MSG (1, "[dbg] Agent thread started, pid=%p\n", (gpointer) (gsize) mono_native_thread_id_get ());
10148 gboolean log_each_step = g_hasenv ("MONO_DEBUGGER_LOG_AFTER_COMMAND");
10150 debugger_thread_id = mono_native_thread_id_get ();
10152 MonoInternalThread *internal = mono_thread_internal_current ();
10153 mono_thread_set_name_constant_ignore_error (internal, "Debugger agent", MonoSetThreadNameFlag_Permanent);
10155 internal->state |= ThreadState_Background;
10156 internal->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
10158 if (agent_config.defer) {
10159 if (!wait_for_attach ()) {
10160 PRINT_DEBUG_MSG (1, "[dbg] Can't attach, aborting debugger thread.\n");
10161 attach_failed = TRUE; // Don't abort process when we can't listen
10162 } else {
10163 mono_set_is_debugger_attached (TRUE);
10164 /* Send start event to client */
10165 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
10167 } else {
10168 mono_set_is_debugger_attached (TRUE);
10171 while (!attach_failed) {
10172 res = transport_recv (header, HEADER_LENGTH);
10174 /* This will break if the socket is closed during shutdown too */
10175 if (res != HEADER_LENGTH) {
10176 PRINT_DEBUG_MSG (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH);
10177 command_set = (CommandSet)0;
10178 command = 0;
10179 dispose_vm ();
10180 break;
10181 } else {
10182 p = header;
10183 end = header + HEADER_LENGTH;
10185 len = decode_int (p, &p, end);
10186 id = decode_int (p, &p, end);
10187 flags = decode_byte (p, &p, end);
10188 command_set = (CommandSet)decode_byte (p, &p, end);
10189 command = decode_byte (p, &p, end);
10192 g_assert (flags == 0);
10193 const char *cmd_str;
10194 char cmd_num [256];
10196 cmd_str = cmd_to_string (command_set, command);
10197 if (!cmd_str) {
10198 sprintf (cmd_num, "%d", command);
10199 cmd_str = cmd_num;
10202 if (log_level) {
10203 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);
10206 data = (guint8 *)g_malloc (len - HEADER_LENGTH);
10207 if (len - HEADER_LENGTH > 0)
10209 res = transport_recv (data, len - HEADER_LENGTH);
10210 if (res != len - HEADER_LENGTH) {
10211 PRINT_DEBUG_MSG (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH);
10212 break;
10216 p = data;
10217 end = data + (len - HEADER_LENGTH);
10219 buffer_init (&buf, 128);
10221 err = ERR_NONE;
10222 no_reply = FALSE;
10224 /* Process the request */
10225 switch (command_set) {
10226 case CMD_SET_VM:
10227 err = vm_commands (command, id, p, end, &buf);
10228 if (err == ERR_NONE && command == CMD_VM_INVOKE_METHOD)
10229 /* Sent after the invoke is complete */
10230 no_reply = TRUE;
10231 break;
10232 case CMD_SET_EVENT_REQUEST:
10233 err = event_commands (command, p, end, &buf);
10234 break;
10235 case CMD_SET_APPDOMAIN:
10236 err = domain_commands (command, p, end, &buf);
10237 break;
10238 case CMD_SET_ASSEMBLY:
10239 err = assembly_commands (command, p, end, &buf);
10240 break;
10241 case CMD_SET_MODULE:
10242 err = module_commands (command, p, end, &buf);
10243 break;
10244 case CMD_SET_FIELD:
10245 err = field_commands (command, p, end, &buf);
10246 break;
10247 case CMD_SET_TYPE:
10248 err = type_commands (command, p, end, &buf);
10249 break;
10250 case CMD_SET_METHOD:
10251 err = method_commands (command, p, end, &buf);
10252 break;
10253 case CMD_SET_THREAD:
10254 err = thread_commands (command, p, end, &buf);
10255 break;
10256 case CMD_SET_STACK_FRAME:
10257 err = frame_commands (command, p, end, &buf);
10258 break;
10259 case CMD_SET_ARRAY_REF:
10260 err = array_commands (command, p, end, &buf);
10261 break;
10262 case CMD_SET_STRING_REF:
10263 err = string_commands (command, p, end, &buf);
10264 break;
10265 case CMD_SET_POINTER:
10266 err = pointer_commands (command, p, end, &buf);
10267 break;
10268 case CMD_SET_OBJECT_REF:
10269 err = object_commands (command, p, end, &buf);
10270 break;
10271 default:
10272 err = ERR_NOT_IMPLEMENTED;
10275 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
10276 buffer_replies = TRUE;
10279 if (!no_reply) {
10280 if (buffer_replies) {
10281 buffer_reply_packet (id, err, &buf);
10282 } else {
10283 send_reply_packet (id, err, &buf);
10284 //PRINT_DEBUG_MSG (1, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000);
10288 mono_debugger_log_command (command_set_to_string (command_set), cmd_str, buf.buf, buffer_len (&buf));
10290 if (err == ERR_NONE && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
10291 send_buffered_reply_packets ();
10292 buffer_replies = FALSE;
10295 g_free (data);
10296 buffer_free (&buf);
10298 if (log_each_step) {
10299 char *debugger_log = mono_debugger_state_str ();
10300 if (debugger_log) {
10301 PRINT_ERROR_MSG ("Debugger state: %s\n", debugger_log);
10302 g_free (debugger_log);
10306 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
10307 break;
10310 mono_set_is_debugger_attached (FALSE);
10312 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
10313 debugger_thread_exited = TRUE;
10314 mono_coop_cond_signal (&debugger_thread_exited_cond);
10315 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
10317 PRINT_DEBUG_MSG (1, "[dbg] Debugger thread exited.\n");
10319 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
10320 PRINT_DEBUG_MSG (2, "[dbg] Detached - restarting clean debugger thread.\n");
10321 ERROR_DECL (error);
10322 start_debugger_thread (error);
10323 mono_error_cleanup (error);
10326 return 0;
10329 void
10330 mono_debugger_agent_init (void)
10332 MonoDebuggerCallbacks cbs;
10334 memset (&cbs, 0, sizeof (cbs));
10335 cbs.version = MONO_DBG_CALLBACKS_VERSION;
10336 cbs.parse_options = debugger_agent_parse_options;
10337 cbs.init = debugger_agent_init;
10338 cbs.breakpoint_hit = debugger_agent_breakpoint_hit;
10339 cbs.single_step_event = debugger_agent_single_step_event;
10340 cbs.single_step_from_context = debugger_agent_single_step_from_context;
10341 cbs.breakpoint_from_context = debugger_agent_breakpoint_from_context;
10342 cbs.free_domain_info = debugger_agent_free_domain_info;
10343 cbs.unhandled_exception = debugger_agent_unhandled_exception;
10344 cbs.handle_exception = debugger_agent_handle_exception;
10345 cbs.begin_exception_filter = debugger_agent_begin_exception_filter;
10346 cbs.end_exception_filter = debugger_agent_end_exception_filter;
10347 cbs.user_break = debugger_agent_user_break;
10348 cbs.debug_log = debugger_agent_debug_log;
10349 cbs.debug_log_is_enabled = debugger_agent_debug_log_is_enabled;
10350 cbs.send_crash = mono_debugger_agent_send_crash;
10352 mini_install_dbg_callbacks (&cbs);
10355 void
10356 mono_debugger_agent_parse_options (char *options)
10358 sdb_options = options;
10361 #endif /* DISABLE_SDB */