[2020-02][debugger] Bump protocol for multi threaded single step implementation ...
[mono-project.git] / mono / mini / debugger-agent.c
blobfac4893af855f2332f92873cc0b1048a1b3a3063
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 typedef struct {
118 gboolean enabled;
119 char *transport;
120 char *address;
121 int log_level;
122 char *log_file;
123 gboolean suspend;
124 gboolean server;
125 gboolean onuncaught;
126 GSList *onthrow;
127 int timeout;
128 char *launch;
129 gboolean embedding;
130 gboolean defer;
131 int keepalive;
132 gboolean setpgid;
133 } AgentConfig;
135 typedef struct
137 //Must be the first field to ensure pointer equivalence
138 DbgEngineStackFrame de;
139 int id;
140 guint32 il_offset;
142 * If method is gshared, this is the actual instance, otherwise this is equal to
143 * method.
145 MonoMethod *actual_method;
147 * This is the method which is visible to debugger clients. Same as method,
148 * except for native-to-managed wrappers.
150 MonoMethod *api_method;
151 MonoContext ctx;
152 MonoDebugMethodJitInfo *jit;
153 MonoInterpFrameHandle interp_frame;
154 gpointer frame_addr;
155 int flags;
156 host_mgreg_t *reg_locations [MONO_MAX_IREGS];
158 * Whenever ctx is set. This is FALSE for the last frame of running threads, since
159 * the frame can become invalid.
161 gboolean has_ctx;
162 } StackFrame;
164 typedef struct _InvokeData InvokeData;
166 struct _InvokeData
168 int id;
169 int flags;
170 guint8 *p;
171 guint8 *endp;
172 /* This is the context which needs to be restored after the invoke */
173 MonoContext ctx;
174 gboolean has_ctx;
176 * If this is set, invoke this method with the arguments given by ARGS.
178 MonoMethod *method;
179 gpointer *args;
180 guint32 suspend_count;
181 int nmethods;
183 InvokeData *last_invoke;
186 struct _DebuggerTlsData {
187 MonoThreadUnwindState context;
189 /* This is computed on demand when it is requested using the wire protocol */
190 /* It is freed up when the thread is resumed */
191 int frame_count;
192 StackFrame **frames;
194 * Whenever the frame info is up-to-date. If not, compute_frame_info () will need to
195 * re-compute it.
197 gboolean frames_up_to_date;
199 * Points to data about a pending invoke which needs to be executed after the thread
200 * resumes.
202 InvokeData *pending_invoke;
204 * Set to TRUE if this thread is suspended in suspend_current () or it is executing
205 * native code.
207 gboolean suspended;
209 * Signals whenever the thread is in the process of suspending, i.e. it will suspend
210 * within a finite amount of time.
212 gboolean suspending;
214 * Set to TRUE if this thread is suspended in suspend_current ().
216 gboolean really_suspended;
217 /* Used to pass the context to the breakpoint/single step handler */
218 MonoContext handler_ctx;
219 /* Whenever thread_stop () was called for this thread */
220 gboolean terminated;
222 /* Whenever to disable breakpoints (used during invokes) */
223 gboolean disable_breakpoints;
226 * Number of times this thread has been resumed using resume_thread ().
228 guint32 resume_count;
229 guint32 resume_count_internal;
230 guint32 suspend_count;
232 MonoInternalThread *thread;
233 intptr_t thread_id;
236 * Information about the frame which transitioned to native code for running
237 * threads.
239 StackFrameInfo async_last_frame;
242 * The context where the stack walk can be started for running threads.
244 MonoThreadUnwindState async_state;
247 * The context used for filter clauses
249 MonoThreadUnwindState filter_state;
251 gboolean abort_requested;
254 * The current mono_runtime_invoke_checked invocation.
256 InvokeData *invoke;
258 StackFrameInfo catch_frame;
259 gboolean has_catch_frame;
262 * The context which needs to be restored after handling a single step/breakpoint
263 * event. This is the same as the ctx at step/breakpoint site, but includes changes
264 * to caller saved registers done by set_var ().
266 MonoThreadUnwindState restore_state;
267 /* Frames computed from restore_state */
268 int restore_frame_count;
269 StackFrame **restore_frames;
271 /* The currently unloading appdomain */
272 MonoDomain *domain_unloading;
274 // The state that the debugger expects the thread to be in
275 MonoDebuggerThreadState thread_state;
276 MonoStopwatch step_time;
278 gboolean gc_finalizing;
281 typedef struct {
282 const char *name;
283 void (*connect) (const char *address);
284 void (*close1) (void);
285 void (*close2) (void);
286 gboolean (*send) (void *buf, int len);
287 int (*recv) (void *buf, int len);
288 } DebuggerTransport;
291 * Wire Protocol definitions
294 #define HEADER_LENGTH 11
296 #define MAJOR_VERSION 2
297 #define MINOR_VERSION 57
299 typedef enum {
300 CMD_SET_VM = 1,
301 CMD_SET_OBJECT_REF = 9,
302 CMD_SET_STRING_REF = 10,
303 CMD_SET_THREAD = 11,
304 CMD_SET_ARRAY_REF = 13,
305 CMD_SET_EVENT_REQUEST = 15,
306 CMD_SET_STACK_FRAME = 16,
307 CMD_SET_APPDOMAIN = 20,
308 CMD_SET_ASSEMBLY = 21,
309 CMD_SET_METHOD = 22,
310 CMD_SET_TYPE = 23,
311 CMD_SET_MODULE = 24,
312 CMD_SET_FIELD = 25,
313 CMD_SET_EVENT = 64,
314 CMD_SET_POINTER = 65
315 } CommandSet;
317 typedef enum {
318 SUSPEND_POLICY_NONE = 0,
319 SUSPEND_POLICY_EVENT_THREAD = 1,
320 SUSPEND_POLICY_ALL = 2
321 } SuspendPolicy;
323 typedef enum {
324 ERR_NONE = 0,
325 ERR_INVALID_OBJECT = 20,
326 ERR_INVALID_FIELDID = 25,
327 ERR_INVALID_FRAMEID = 30,
328 ERR_NOT_IMPLEMENTED = 100,
329 ERR_NOT_SUSPENDED = 101,
330 ERR_INVALID_ARGUMENT = 102,
331 ERR_UNLOADED = 103,
332 ERR_NO_INVOCATION = 104,
333 ERR_ABSENT_INFORMATION = 105,
334 ERR_NO_SEQ_POINT_AT_IL_OFFSET = 106,
335 ERR_INVOKE_ABORTED = 107,
336 ERR_LOADER_ERROR = 200, /*XXX extend the protocol to pass this information down the pipe */
337 } ErrorCode;
339 typedef enum {
340 TOKEN_TYPE_STRING = 0,
341 TOKEN_TYPE_TYPE = 1,
342 TOKEN_TYPE_FIELD = 2,
343 TOKEN_TYPE_METHOD = 3,
344 TOKEN_TYPE_UNKNOWN = 4
345 } DebuggerTokenType;
347 typedef enum {
348 VALUE_TYPE_ID_NULL = 0xf0,
349 VALUE_TYPE_ID_TYPE = 0xf1,
350 VALUE_TYPE_ID_PARENT_VTYPE = 0xf2,
351 VALUE_TYPE_ID_FIXED_ARRAY = 0xf3
352 } ValueTypeId;
354 typedef enum {
355 FRAME_FLAG_DEBUGGER_INVOKE = 1,
356 FRAME_FLAG_NATIVE_TRANSITION = 2
357 } StackFrameFlags;
359 typedef enum {
360 INVOKE_FLAG_DISABLE_BREAKPOINTS = 1,
361 INVOKE_FLAG_SINGLE_THREADED = 2,
362 INVOKE_FLAG_RETURN_OUT_THIS = 4,
363 INVOKE_FLAG_RETURN_OUT_ARGS = 8,
364 INVOKE_FLAG_VIRTUAL = 16
365 } InvokeFlags;
367 typedef enum {
368 BINDING_FLAGS_IGNORE_CASE = 0x70000000,
369 } BindingFlagsExtensions;
371 typedef enum {
372 CMD_VM_VERSION = 1,
373 CMD_VM_ALL_THREADS = 2,
374 CMD_VM_SUSPEND = 3,
375 CMD_VM_RESUME = 4,
376 CMD_VM_EXIT = 5,
377 CMD_VM_DISPOSE = 6,
378 CMD_VM_INVOKE_METHOD = 7,
379 CMD_VM_SET_PROTOCOL_VERSION = 8,
380 CMD_VM_ABORT_INVOKE = 9,
381 CMD_VM_SET_KEEPALIVE = 10,
382 CMD_VM_GET_TYPES_FOR_SOURCE_FILE = 11,
383 CMD_VM_GET_TYPES = 12,
384 CMD_VM_INVOKE_METHODS = 13,
385 CMD_VM_START_BUFFERING = 14,
386 CMD_VM_STOP_BUFFERING = 15
387 } CmdVM;
389 typedef enum {
390 CMD_THREAD_GET_FRAME_INFO = 1,
391 CMD_THREAD_GET_NAME = 2,
392 CMD_THREAD_GET_STATE = 3,
393 CMD_THREAD_GET_INFO = 4,
394 CMD_THREAD_GET_ID = 5,
395 CMD_THREAD_GET_TID = 6,
396 CMD_THREAD_SET_IP = 7,
397 CMD_THREAD_ELAPSED_TIME = 8
398 } CmdThread;
400 typedef enum {
401 CMD_EVENT_REQUEST_SET = 1,
402 CMD_EVENT_REQUEST_CLEAR = 2,
403 CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS = 3
404 } CmdEvent;
406 typedef enum {
407 CMD_COMPOSITE = 100
408 } CmdComposite;
410 typedef enum {
411 CMD_APPDOMAIN_GET_ROOT_DOMAIN = 1,
412 CMD_APPDOMAIN_GET_FRIENDLY_NAME = 2,
413 CMD_APPDOMAIN_GET_ASSEMBLIES = 3,
414 CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY = 4,
415 CMD_APPDOMAIN_CREATE_STRING = 5,
416 CMD_APPDOMAIN_GET_CORLIB = 6,
417 CMD_APPDOMAIN_CREATE_BOXED_VALUE = 7,
418 CMD_APPDOMAIN_CREATE_BYTE_ARRAY = 8,
419 } CmdAppDomain;
421 typedef enum {
422 CMD_ASSEMBLY_GET_LOCATION = 1,
423 CMD_ASSEMBLY_GET_ENTRY_POINT = 2,
424 CMD_ASSEMBLY_GET_MANIFEST_MODULE = 3,
425 CMD_ASSEMBLY_GET_OBJECT = 4,
426 CMD_ASSEMBLY_GET_TYPE = 5,
427 CMD_ASSEMBLY_GET_NAME = 6,
428 CMD_ASSEMBLY_GET_DOMAIN = 7,
429 CMD_ASSEMBLY_GET_METADATA_BLOB = 8,
430 CMD_ASSEMBLY_GET_IS_DYNAMIC = 9,
431 CMD_ASSEMBLY_GET_PDB_BLOB = 10,
432 CMD_ASSEMBLY_GET_TYPE_FROM_TOKEN = 11,
433 CMD_ASSEMBLY_GET_METHOD_FROM_TOKEN = 12,
434 CMD_ASSEMBLY_HAS_DEBUG_INFO = 13
435 } CmdAssembly;
437 typedef enum {
438 CMD_MODULE_GET_INFO = 1,
439 } CmdModule;
441 typedef enum {
442 CMD_FIELD_GET_INFO = 1,
443 } CmdField;
445 typedef enum {
446 CMD_METHOD_GET_NAME = 1,
447 CMD_METHOD_GET_DECLARING_TYPE = 2,
448 CMD_METHOD_GET_DEBUG_INFO = 3,
449 CMD_METHOD_GET_PARAM_INFO = 4,
450 CMD_METHOD_GET_LOCALS_INFO = 5,
451 CMD_METHOD_GET_INFO = 6,
452 CMD_METHOD_GET_BODY = 7,
453 CMD_METHOD_RESOLVE_TOKEN = 8,
454 CMD_METHOD_GET_CATTRS = 9,
455 CMD_METHOD_MAKE_GENERIC_METHOD = 10
456 } CmdMethod;
458 typedef enum {
459 CMD_TYPE_GET_INFO = 1,
460 CMD_TYPE_GET_METHODS = 2,
461 CMD_TYPE_GET_FIELDS = 3,
462 CMD_TYPE_GET_VALUES = 4,
463 CMD_TYPE_GET_OBJECT = 5,
464 CMD_TYPE_GET_SOURCE_FILES = 6,
465 CMD_TYPE_SET_VALUES = 7,
466 CMD_TYPE_IS_ASSIGNABLE_FROM = 8,
467 CMD_TYPE_GET_PROPERTIES = 9,
468 CMD_TYPE_GET_CATTRS = 10,
469 CMD_TYPE_GET_FIELD_CATTRS = 11,
470 CMD_TYPE_GET_PROPERTY_CATTRS = 12,
471 CMD_TYPE_GET_SOURCE_FILES_2 = 13,
472 CMD_TYPE_GET_VALUES_2 = 14,
473 CMD_TYPE_GET_METHODS_BY_NAME_FLAGS = 15,
474 CMD_TYPE_GET_INTERFACES = 16,
475 CMD_TYPE_GET_INTERFACE_MAP = 17,
476 CMD_TYPE_IS_INITIALIZED = 18,
477 CMD_TYPE_CREATE_INSTANCE = 19,
478 CMD_TYPE_GET_VALUE_SIZE = 20
479 } CmdType;
481 typedef enum {
482 CMD_STACK_FRAME_GET_VALUES = 1,
483 CMD_STACK_FRAME_GET_THIS = 2,
484 CMD_STACK_FRAME_SET_VALUES = 3,
485 CMD_STACK_FRAME_GET_DOMAIN = 4,
486 CMD_STACK_FRAME_SET_THIS = 5,
487 } CmdStackFrame;
489 typedef enum {
490 CMD_ARRAY_REF_GET_LENGTH = 1,
491 CMD_ARRAY_REF_GET_VALUES = 2,
492 CMD_ARRAY_REF_SET_VALUES = 3,
493 } CmdArray;
495 typedef enum {
496 CMD_STRING_REF_GET_VALUE = 1,
497 CMD_STRING_REF_GET_LENGTH = 2,
498 CMD_STRING_REF_GET_CHARS = 3
499 } CmdString;
501 typedef enum {
502 CMD_POINTER_GET_VALUE = 1
503 } CmdPointer;
505 typedef enum {
506 CMD_OBJECT_REF_GET_TYPE = 1,
507 CMD_OBJECT_REF_GET_VALUES = 2,
508 CMD_OBJECT_REF_IS_COLLECTED = 3,
509 CMD_OBJECT_REF_GET_ADDRESS = 4,
510 CMD_OBJECT_REF_GET_DOMAIN = 5,
511 CMD_OBJECT_REF_SET_VALUES = 6,
512 CMD_OBJECT_REF_GET_INFO = 7,
513 } CmdObject;
516 * Contains additional information for an event
518 typedef struct {
519 /* For EVENT_KIND_EXCEPTION */
520 MonoObject *exc;
521 MonoContext catch_ctx;
522 gboolean caught;
523 /* For EVENT_KIND_USER_LOG */
524 int level;
525 char *category, *message;
526 /* For EVENT_KIND_TYPE_LOAD */
527 MonoClass *klass;
528 /* For EVENT_KIND_CRASH */
529 char *dump;
530 MonoStackHash *hashes;
531 } EventInfo;
533 typedef struct {
534 guint8 *buf, *p, *end;
535 } Buffer;
537 typedef struct ReplyPacket {
538 int id;
539 int error;
540 Buffer *data;
541 } ReplyPacket;
543 #define DEBUG(level,s) do { if (G_UNLIKELY ((level) <= log_level)) { s; fflush (log_file); } } while (0)
545 #ifdef HOST_ANDROID
546 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { g_print (__VA_ARGS__); } } while (0)
547 #else
548 #define DEBUG_PRINTF(level, ...) do { if (G_UNLIKELY ((level) <= log_level)) { fprintf (log_file, __VA_ARGS__); fflush (log_file); } } while (0)
549 #endif
551 #ifdef HOST_WIN32
552 #define get_last_sock_error() WSAGetLastError()
553 #define MONO_EWOULDBLOCK WSAEWOULDBLOCK
554 #define MONO_EINTR WSAEINTR
555 #else
556 #define get_last_sock_error() errno
557 #define MONO_EWOULDBLOCK EWOULDBLOCK
558 #define MONO_EINTR EINTR
559 #endif
561 #define CHECK_PROTOCOL_VERSION(major,minor) \
562 (protocol_version_set && (major_version > (major) || (major_version == (major) && minor_version >= (minor))))
565 * Globals
568 static AgentConfig agent_config;
571 * Whenever the agent is fully initialized.
572 * When using the onuncaught or onthrow options, only some parts of the agent are
573 * initialized on startup, and the full initialization which includes connection
574 * establishment and the startup of the agent thread is only done in response to
575 * an event.
577 static gint32 inited;
579 #ifndef DISABLE_SOCKET_TRANSPORT
580 static int conn_fd;
581 static int listen_fd;
582 #endif
584 static int packet_id = 0;
586 static int objref_id = 0;
588 static int event_request_id = 0;
590 static int frame_id = 0;
592 static GPtrArray *event_requests;
594 static MonoNativeTlsKey debugger_tls_id;
596 static gboolean vm_start_event_sent, vm_death_event_sent, disconnected;
598 /* Maps MonoInternalThread -> DebuggerTlsData */
599 /* Protected by the loader lock */
600 static MonoGHashTable *thread_to_tls;
602 /* Maps tid -> MonoInternalThread */
603 /* Protected by the loader lock */
604 static MonoGHashTable *tid_to_thread;
606 /* Maps tid -> MonoThread (not MonoInternalThread) */
607 /* Protected by the loader lock */
608 static MonoGHashTable *tid_to_thread_obj;
610 static MonoNativeThreadId debugger_thread_id;
612 static MonoThreadHandle *debugger_thread_handle;
614 static int log_level;
616 static int file_check_valid_memory = -1;
618 static char* filename_check_valid_memory;
620 static gboolean embedding;
622 static FILE *log_file;
624 /* Assemblies whose assembly load event has no been sent yet */
625 /* Protected by the dbg lock */
626 static GPtrArray *pending_assembly_loads;
628 /* Whenever the debugger thread has exited */
629 static gboolean debugger_thread_exited;
631 /* Cond variable used to wait for debugger_thread_exited becoming true */
632 static MonoCoopCond debugger_thread_exited_cond;
634 /* Mutex for the cond var above */
635 static MonoCoopMutex debugger_thread_exited_mutex;
637 /* The protocol version of the client */
638 static int major_version, minor_version;
640 /* Whenever the variables above are set by the client */
641 static gboolean protocol_version_set;
643 /* The number of times the runtime is suspended */
644 static gint32 suspend_count;
646 /* Whenever to buffer reply messages and send them together */
647 static gboolean buffer_replies;
649 /* Buffered reply packets */
650 static ReplyPacket reply_packets [128];
651 static int nreply_packets;
653 #define dbg_lock mono_de_lock
654 #define dbg_unlock mono_de_unlock
656 static void transport_init (void);
657 static void transport_connect (const char *address);
658 static gboolean transport_handshake (void);
659 static void register_transport (DebuggerTransport *trans);
661 static gsize WINAPI debugger_thread (void *arg);
663 static void runtime_initialized (MonoProfiler *prof);
665 static void runtime_shutdown (MonoProfiler *prof);
667 static void thread_startup (MonoProfiler *prof, uintptr_t tid);
669 static void thread_end (MonoProfiler *prof, uintptr_t tid);
671 static void appdomain_load (MonoProfiler *prof, MonoDomain *domain);
673 static void appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain);
675 static void appdomain_unload (MonoProfiler *prof, MonoDomain *domain);
677 static void emit_appdomain_load (gpointer key, gpointer value, gpointer user_data);
679 static void emit_thread_start (gpointer key, gpointer value, gpointer user_data);
681 static void invalidate_each_thread (gpointer key, gpointer value, gpointer user_data);
683 static void assembly_load (MonoProfiler *prof, MonoAssembly *assembly);
685 static void assembly_unload (MonoProfiler *prof, MonoAssembly *assembly);
687 static void gc_finalizing (MonoProfiler *prof);
689 static void gc_finalized (MonoProfiler *prof);
691 static void emit_assembly_load (gpointer assembly, gpointer user_data);
693 static void emit_type_load (gpointer key, gpointer type, gpointer user_data);
695 static void jit_done (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo);
697 static void jit_failed (MonoProfiler *prof, MonoMethod *method);
699 static void jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo);
701 static void suspend_current (void);
703 static void clear_event_requests_for_assembly (MonoAssembly *assembly);
705 static void clear_types_for_assembly (MonoAssembly *assembly);
707 static void process_profiler_event (EventKind event, gpointer arg);
709 /* Submodule init/cleanup */
710 static void event_requests_cleanup (void);
712 static void objrefs_init (void);
713 static void objrefs_cleanup (void);
715 static void ids_init (void);
716 static void ids_cleanup (void);
718 static void suspend_init (void);
720 static void start_debugger_thread (MonoError *error);
721 static void stop_debugger_thread (void);
723 static void finish_agent_init (gboolean on_startup);
725 static void process_profiler_event (EventKind event, gpointer arg);
727 static void invalidate_frames (DebuggerTlsData *tls);
729 /* Callbacks used by debugger-engine */
730 static MonoContext* tls_get_restore_state (void *the_tls);
731 static gboolean try_process_suspend (void *tls, MonoContext *ctx, gboolean from_breakpoint);
732 static gboolean begin_breakpoint_processing (void *tls, MonoContext *ctx, MonoJitInfo *ji, gboolean from_signal);
733 static void begin_single_step_processing (MonoContext *ctx, gboolean from_signal);
734 static void ss_discard_frame_context (void *the_tls);
735 static void ss_calculate_framecount (void *tls, MonoContext *ctx, gboolean force_use_ctx, DbgEngineStackFrame ***frames, int *nframes);
736 static gboolean ensure_jit (DbgEngineStackFrame* the_frame);
737 static int ensure_runtime_is_suspended (void);
738 static int get_this_async_id (DbgEngineStackFrame *frame);
739 static gboolean set_set_notification_for_wait_completion_flag (DbgEngineStackFrame *frame);
740 static MonoMethod* get_notify_debugger_of_wait_completion_method (void);
741 static void* create_breakpoint_events (GPtrArray *ss_reqs, GPtrArray *bp_reqs, MonoJitInfo *ji, EventKind kind);
742 static void process_breakpoint_events (void *_evts, MonoMethod *method, MonoContext *ctx, int il_offset);
743 static int ss_create_init_args (SingleStepReq *ss_req, SingleStepArgs *args);
744 static void ss_args_destroy (SingleStepArgs *ss_args);
745 static int handle_multiple_ss_requests (void);
747 static GENERATE_TRY_GET_CLASS_WITH_CACHE (fixed_buffer, "System.Runtime.CompilerServices", "FixedBufferAttribute")
749 #ifndef DISABLE_SOCKET_TRANSPORT
750 static void
751 register_socket_transport (void);
752 #endif
754 static gboolean
755 is_debugger_thread (void)
757 MonoInternalThread *internal;
759 internal = mono_thread_internal_current ();
760 if (!internal)
761 return FALSE;
763 return internal->debugger_thread;
766 static int
767 parse_address (char *address, char **host, int *port)
769 char *pos = strchr (address, ':');
771 if (pos == NULL || pos == address)
772 return 1;
774 size_t len = pos - address;
775 *host = (char *)g_malloc (len + 1);
776 memcpy (*host, address, len);
777 (*host) [len] = '\0';
779 *port = atoi (pos + 1);
781 return 0;
784 static void
785 print_usage (void)
787 g_printerr ("Usage: mono --debugger-agent=[<option>=<value>,...] ...\n");
788 g_printerr ("Available options:\n");
789 g_printerr (" transport=<transport>\t\tTransport to use for connecting to the debugger (mandatory, possible values: 'dt_socket')\n");
790 g_printerr (" address=<hostname>:<port>\tAddress to connect to (mandatory)\n");
791 g_printerr (" loglevel=<n>\t\t\tLog level (defaults to 0)\n");
792 g_printerr (" logfile=<file>\t\tFile to log to (defaults to stdout)\n");
793 g_printerr (" suspend=y/n\t\t\tWhether to suspend after startup.\n");
794 g_printerr (" timeout=<n>\t\t\tTimeout for connecting in milliseconds.\n");
795 g_printerr (" server=y/n\t\t\tWhether to listen for a client connection.\n");
796 g_printerr (" keepalive=<n>\t\t\tSend keepalive events every n milliseconds.\n");
797 g_printerr (" setpgid=y/n\t\t\tWhether to call setpid(0, 0) after startup.\n");
798 g_printerr (" help\t\t\t\tPrint this help.\n");
801 static gboolean
802 parse_flag (const char *option, char *flag)
804 if (!strcmp (flag, "y"))
805 return TRUE;
806 else if (!strcmp (flag, "n"))
807 return FALSE;
808 else {
809 g_printerr ("debugger-agent: The valid values for the '%s' option are 'y' and 'n'.\n", option);
810 exit (1);
811 return FALSE;
815 static void
816 debugger_agent_parse_options (char *options)
818 char **args, **ptr;
819 char *host;
820 int port;
821 char *extra;
823 #ifndef MONO_ARCH_SOFT_DEBUG_SUPPORTED
824 g_printerr ("--debugger-agent is not supported on this platform.\n");
825 exit (1);
826 #endif
828 extra = g_getenv ("MONO_SDB_ENV_OPTIONS");
829 if (extra) {
830 options = g_strdup_printf ("%s,%s", options, extra);
831 g_free (extra);
834 agent_config.enabled = TRUE;
835 agent_config.suspend = TRUE;
836 agent_config.server = FALSE;
837 agent_config.defer = FALSE;
838 agent_config.address = NULL;
840 //agent_config.log_level = 10;
842 args = g_strsplit (options, ",", -1);
843 for (ptr = args; ptr && *ptr; ptr ++) {
844 char *arg = *ptr;
846 if (strncmp (arg, "transport=", 10) == 0) {
847 agent_config.transport = g_strdup (arg + 10);
848 } else if (strncmp (arg, "address=", 8) == 0) {
849 agent_config.address = g_strdup (arg + 8);
850 } else if (strncmp (arg, "loglevel=", 9) == 0) {
851 agent_config.log_level = atoi (arg + 9);
852 } else if (strncmp (arg, "logfile=", 8) == 0) {
853 agent_config.log_file = g_strdup (arg + 8);
854 } else if (strncmp (arg, "suspend=", 8) == 0) {
855 agent_config.suspend = parse_flag ("suspend", arg + 8);
856 } else if (strncmp (arg, "server=", 7) == 0) {
857 agent_config.server = parse_flag ("server", arg + 7);
858 } else if (strncmp (arg, "onuncaught=", 11) == 0) {
859 agent_config.onuncaught = parse_flag ("onuncaught", arg + 11);
860 } else if (strncmp (arg, "onthrow=", 8) == 0) {
861 /* We support multiple onthrow= options */
862 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (arg + 8));
863 } else if (strncmp (arg, "onthrow", 7) == 0) {
864 agent_config.onthrow = g_slist_append (agent_config.onthrow, g_strdup (""));
865 } else if (strncmp (arg, "help", 4) == 0) {
866 print_usage ();
867 exit (0);
868 } else if (strncmp (arg, "timeout=", 8) == 0) {
869 agent_config.timeout = atoi (arg + 8);
870 } else if (strncmp (arg, "launch=", 7) == 0) {
871 agent_config.launch = g_strdup (arg + 7);
872 } else if (strncmp (arg, "embedding=", 10) == 0) {
873 agent_config.embedding = atoi (arg + 10) == 1;
874 } else if (strncmp (arg, "keepalive=", 10) == 0) {
875 agent_config.keepalive = atoi (arg + 10);
876 } else if (strncmp (arg, "setpgid=", 8) == 0) {
877 agent_config.setpgid = parse_flag ("setpgid", arg + 8);
878 } else {
879 print_usage ();
880 exit (1);
884 if (agent_config.server && !agent_config.suspend) {
885 /* Waiting for deferred attachment */
886 agent_config.defer = TRUE;
887 if (agent_config.address == NULL) {
888 agent_config.address = g_strdup_printf ("0.0.0.0:%u", 56000 + (mono_process_current_pid () % 1000));
892 //agent_config.log_level = 0;
894 if (agent_config.transport == NULL) {
895 g_printerr ("debugger-agent: The 'transport' option is mandatory.\n");
896 exit (1);
899 if (agent_config.address == NULL && !agent_config.server) {
900 g_printerr ("debugger-agent: The 'address' option is mandatory.\n");
901 exit (1);
904 // FIXME:
905 if (!strcmp (agent_config.transport, "dt_socket")) {
906 if (agent_config.address && parse_address (agent_config.address, &host, &port)) {
907 g_printerr ("debugger-agent: The format of the 'address' options is '<host>:<port>'\n");
908 exit (1);
913 void
914 mono_debugger_set_thread_state (DebuggerTlsData *tls, MonoDebuggerThreadState expected, MonoDebuggerThreadState set)
916 g_assertf (tls, "Cannot get state of null thread", NULL);
918 g_assert (tls->thread_state == expected);
920 tls->thread_state = set;
923 MonoDebuggerThreadState
924 mono_debugger_get_thread_state (DebuggerTlsData *tls)
926 g_assertf (tls, "Cannot get state of null thread", NULL);
928 return tls->thread_state;
931 gsize
932 mono_debugger_tls_thread_id (DebuggerTlsData *tls)
934 if (!tls)
935 return 0;
937 return tls->thread_id;
940 // Only call this function with the loader lock held
941 MonoGHashTable *
942 mono_debugger_get_thread_states (void)
944 return thread_to_tls;
947 gboolean
948 mono_debugger_is_disconnected (void)
950 return disconnected;
953 static void
954 debugger_agent_init (void)
956 if (!agent_config.enabled)
957 return;
959 DebuggerEngineCallbacks cbs;
960 memset (&cbs, 0, sizeof (cbs));
961 cbs.tls_get_restore_state = tls_get_restore_state;
962 cbs.try_process_suspend = try_process_suspend;
963 cbs.begin_breakpoint_processing = begin_breakpoint_processing;
964 cbs.begin_single_step_processing = begin_single_step_processing;
965 cbs.ss_discard_frame_context = ss_discard_frame_context;
966 cbs.ss_calculate_framecount = ss_calculate_framecount;
967 cbs.ensure_jit = ensure_jit;
968 cbs.ensure_runtime_is_suspended = ensure_runtime_is_suspended;
969 cbs.get_this_async_id = get_this_async_id;
970 cbs.set_set_notification_for_wait_completion_flag = set_set_notification_for_wait_completion_flag;
971 cbs.get_notify_debugger_of_wait_completion_method = get_notify_debugger_of_wait_completion_method;
972 cbs.create_breakpoint_events = create_breakpoint_events;
973 cbs.process_breakpoint_events = process_breakpoint_events;
974 cbs.ss_create_init_args = ss_create_init_args;
975 cbs.ss_args_destroy = ss_args_destroy;
976 cbs.handle_multiple_ss_requests = handle_multiple_ss_requests;
978 mono_de_init (&cbs);
980 transport_init ();
982 /* Need to know whenever a thread has acquired the loader mutex */
983 mono_loader_lock_track_ownership (TRUE);
985 event_requests = g_ptr_array_new ();
987 mono_coop_mutex_init (&debugger_thread_exited_mutex);
988 mono_coop_cond_init (&debugger_thread_exited_cond);
990 MonoProfilerHandle prof = mono_profiler_create (NULL);
991 mono_profiler_set_runtime_shutdown_end_callback (prof, runtime_shutdown);
992 mono_profiler_set_runtime_initialized_callback (prof, runtime_initialized);
993 mono_profiler_set_domain_loaded_callback (prof, appdomain_load);
994 mono_profiler_set_domain_unloading_callback (prof, appdomain_start_unload);
995 mono_profiler_set_domain_unloaded_callback (prof, appdomain_unload);
996 mono_profiler_set_thread_started_callback (prof, thread_startup);
997 mono_profiler_set_thread_stopped_callback (prof, thread_end);
998 mono_profiler_set_assembly_loaded_callback (prof, assembly_load);
999 mono_profiler_set_assembly_unloading_callback (prof, assembly_unload);
1000 mono_profiler_set_jit_done_callback (prof, jit_done);
1001 mono_profiler_set_jit_failed_callback (prof, jit_failed);
1002 mono_profiler_set_gc_finalizing_callback (prof, gc_finalizing);
1003 mono_profiler_set_gc_finalized_callback (prof, gc_finalized);
1005 mono_native_tls_alloc (&debugger_tls_id, NULL);
1007 /* Needed by the hash_table_new_type () call below */
1008 mono_gc_base_init ();
1010 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");
1012 tid_to_thread = mono_g_hash_table_new_type_internal (NULL, NULL, MONO_HASH_VALUE_GC, MONO_ROOT_SOURCE_DEBUGGER, NULL, "Debugger Thread Table");
1014 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");
1016 pending_assembly_loads = g_ptr_array_new ();
1018 log_level = agent_config.log_level;
1020 embedding = agent_config.embedding;
1021 disconnected = TRUE;
1023 if (agent_config.log_file) {
1024 log_file = fopen (agent_config.log_file, "w+");
1025 if (!log_file) {
1026 g_printerr ("Unable to create log file '%s': %s.\n", agent_config.log_file, strerror (errno));
1027 exit (1);
1029 } else {
1030 log_file = stdout;
1032 mono_de_set_log_level (log_level, log_file);
1034 ids_init ();
1035 objrefs_init ();
1036 suspend_init ();
1038 mini_get_debug_options ()->gen_sdb_seq_points = TRUE;
1040 * This is needed because currently we don't handle liveness info.
1042 mini_get_debug_options ()->mdb_optimizations = TRUE;
1044 #ifndef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
1045 /* This is needed because we can't set local variables in registers yet */
1046 mono_disable_optimizations (MONO_OPT_LINEARS);
1047 #endif
1050 * The stack walk done from thread_interrupt () needs to be signal safe, but it
1051 * isn't, since it can call into mono_aot_find_jit_info () which is not signal
1052 * safe (#3411). So load AOT info eagerly when the debugger is running as a
1053 * workaround.
1055 mini_get_debug_options ()->load_aot_jit_info_eagerly = TRUE;
1057 #ifdef HAVE_SETPGID
1058 if (agent_config.setpgid)
1059 setpgid (0, 0);
1060 #endif
1062 if (!agent_config.onuncaught && !agent_config.onthrow)
1063 finish_agent_init (TRUE);
1067 * finish_agent_init:
1069 * Finish the initialization of the agent. This involves connecting the transport
1070 * and starting the agent thread. This is either done at startup, or
1071 * in response to some event like an unhandled exception.
1073 static void
1074 finish_agent_init (gboolean on_startup)
1076 int res;
1078 if (mono_atomic_cas_i32 (&inited, 1, 0) == 1)
1079 return;
1081 if (agent_config.launch) {
1082 char *argv [16];
1084 // FIXME: Generated address
1085 // FIXME: Races with transport_connect ()
1087 argv [0] = agent_config.launch;
1088 argv [1] = agent_config.transport;
1089 argv [2] = agent_config.address;
1090 argv [3] = NULL;
1092 res = g_spawn_async_with_pipes (NULL, argv, NULL, (GSpawnFlags)0, NULL, NULL, NULL, NULL, NULL, NULL, NULL);
1093 if (!res) {
1094 g_printerr ("Failed to execute '%s'.\n", agent_config.launch);
1095 exit (1);
1099 transport_connect (agent_config.address);
1101 if (!on_startup) {
1102 /* Do some which is usually done after sending the VMStart () event */
1103 vm_start_event_sent = TRUE;
1104 ERROR_DECL (error);
1105 start_debugger_thread (error);
1106 mono_error_assert_ok (error);
1110 static void
1111 mono_debugger_agent_cleanup (void)
1113 if (!inited)
1114 return;
1116 stop_debugger_thread ();
1118 event_requests_cleanup ();
1119 objrefs_cleanup ();
1120 ids_cleanup ();
1122 mono_de_cleanup ();
1124 if (file_check_valid_memory != -1) {
1125 remove (filename_check_valid_memory);
1126 g_free (filename_check_valid_memory);
1127 close (file_check_valid_memory);
1132 * SOCKET TRANSPORT
1135 #ifndef DISABLE_SOCKET_TRANSPORT
1138 * recv_length:
1140 * recv() + handle incomplete reads and EINTR
1142 static int
1143 socket_transport_recv (void *buf, int len)
1145 int res;
1146 int total = 0;
1147 int fd = conn_fd;
1148 int flags = 0;
1149 static gint64 last_keepalive;
1150 gint64 msecs;
1152 MONO_ENTER_GC_SAFE;
1154 do {
1155 again:
1156 res = recv (fd, (char *) buf + total, len - total, flags);
1157 if (res > 0)
1158 total += res;
1159 if (agent_config.keepalive) {
1160 gboolean need_keepalive = FALSE;
1161 if (res == -1 && get_last_sock_error () == MONO_EWOULDBLOCK) {
1162 need_keepalive = TRUE;
1163 } else if (res == -1) {
1164 /* This could happen if recv () is interrupted repeatedly */
1165 msecs = mono_msec_ticks ();
1166 if (msecs - last_keepalive >= agent_config.keepalive) {
1167 need_keepalive = TRUE;
1168 last_keepalive = msecs;
1171 if (need_keepalive) {
1172 process_profiler_event (EVENT_KIND_KEEPALIVE, NULL);
1173 goto again;
1176 } while ((res > 0 && total < len) || (res == -1 && get_last_sock_error () == MONO_EINTR));
1178 MONO_EXIT_GC_SAFE;
1180 return total;
1183 static void
1184 set_keepalive (void)
1186 struct timeval tv;
1187 int result;
1189 if (!agent_config.keepalive || !conn_fd)
1190 return;
1192 tv.tv_sec = agent_config.keepalive / 1000;
1193 tv.tv_usec = (agent_config.keepalive % 1000) * 1000;
1195 result = setsockopt (conn_fd, SOL_SOCKET, SO_RCVTIMEO, (char *) &tv, sizeof(struct timeval));
1196 g_assert (result >= 0);
1199 static int
1200 socket_transport_accept (int socket_fd)
1202 MONO_ENTER_GC_SAFE;
1203 conn_fd = accept (socket_fd, NULL, NULL);
1204 MONO_EXIT_GC_SAFE;
1206 if (conn_fd == -1) {
1207 g_printerr ("debugger-agent: Unable to listen on %d\n", socket_fd);
1208 } else {
1209 DEBUG_PRINTF (1, "Accepted connection from client, connection fd=%d.\n", conn_fd);
1212 return conn_fd;
1215 static gboolean
1216 socket_transport_send (void *data, int len)
1218 int res;
1220 MONO_ENTER_GC_SAFE;
1222 do {
1223 res = send (conn_fd, (const char*)data, len, 0);
1224 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1226 MONO_EXIT_GC_SAFE;
1228 if (res != len)
1229 return FALSE;
1230 else
1231 return TRUE;
1235 * socket_transport_connect:
1237 * Connect/Listen on HOST:PORT. If HOST is NULL, generate an address and listen on it.
1239 static void
1240 socket_transport_connect (const char *address)
1242 MonoAddressInfo *result;
1243 MonoAddressEntry *rp;
1244 int sfd = -1, s, res;
1245 char *host;
1246 int port;
1248 if (agent_config.address) {
1249 res = parse_address (agent_config.address, &host, &port);
1250 g_assert (res == 0);
1251 } else {
1252 host = NULL;
1253 port = 0;
1256 conn_fd = -1;
1257 listen_fd = -1;
1259 if (host) {
1260 int hints[] = {
1261 MONO_HINT_IPV4 | MONO_HINT_NUMERIC_HOST,
1262 MONO_HINT_IPV6 | MONO_HINT_NUMERIC_HOST,
1263 MONO_HINT_UNSPECIFIED
1266 mono_network_init ();
1268 for (int i = 0; i < sizeof(hints) / sizeof(int); i++) {
1269 /* Obtain address(es) matching host/port */
1270 s = mono_get_address_info (host, port, hints[i], &result);
1271 if (s == 0)
1272 break;
1274 if (s != 0) {
1275 g_printerr ("debugger-agent: Unable to resolve %s:%d: %d\n", host, port, s); // FIXME add portable error conversion functions
1276 exit (1);
1280 if (agent_config.server) {
1281 /* Wait for a connection */
1282 if (!host) {
1283 struct sockaddr_in addr;
1284 socklen_t addrlen;
1286 /* No address, generate one */
1287 sfd = socket (AF_INET, SOCK_STREAM, 0);
1288 if (sfd == -1) {
1289 g_printerr ("debugger-agent: Unable to create a socket: %s\n", strerror (get_last_sock_error ()));
1290 exit (1);
1293 /* This will bind the socket to a random port */
1294 res = listen (sfd, 16);
1295 if (res == -1) {
1296 g_printerr ("debugger-agent: Unable to setup listening socket: %s\n", strerror (get_last_sock_error ()));
1297 exit (1);
1299 listen_fd = sfd;
1301 addrlen = sizeof (addr);
1302 memset (&addr, 0, sizeof (addr));
1303 res = getsockname (sfd, (struct sockaddr*)&addr, &addrlen);
1304 g_assert (res == 0);
1306 host = (char*)"127.0.0.1";
1307 port = ntohs (addr.sin_port);
1309 /* Emit the address to stdout */
1310 /* FIXME: Should print another interface, not localhost */
1311 printf ("%s:%d\n", host, port);
1312 } else {
1313 /* Listen on the provided address */
1314 for (rp = result->entries; rp != NULL; rp = rp->next) {
1315 MonoSocketAddress sockaddr;
1316 socklen_t sock_len;
1317 int n = 1;
1319 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1321 sfd = socket (rp->family, rp->socktype,
1322 rp->protocol);
1323 if (sfd == -1)
1324 continue;
1326 if (setsockopt (sfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&n, sizeof(n)) == -1)
1327 continue;
1329 res = bind (sfd, &sockaddr.addr, sock_len);
1330 if (res == -1)
1331 continue;
1333 res = listen (sfd, 16);
1334 if (res == -1)
1335 continue;
1336 listen_fd = sfd;
1337 break;
1340 mono_free_address_info (result);
1343 if (agent_config.defer)
1344 return;
1346 DEBUG_PRINTF (1, "Listening on %s:%d (timeout=%d ms)...\n", host, port, agent_config.timeout);
1348 if (agent_config.timeout) {
1349 fd_set readfds;
1350 struct timeval tv;
1352 tv.tv_sec = 0;
1353 tv.tv_usec = agent_config.timeout * 1000;
1354 FD_ZERO (&readfds);
1355 FD_SET (sfd, &readfds);
1357 MONO_ENTER_GC_SAFE;
1358 res = select (sfd + 1, &readfds, NULL, NULL, &tv);
1359 MONO_EXIT_GC_SAFE;
1361 if (res == 0) {
1362 g_printerr ("debugger-agent: Timed out waiting to connect.\n");
1363 exit (1);
1367 conn_fd = socket_transport_accept (sfd);
1368 if (conn_fd == -1)
1369 exit (1);
1371 DEBUG_PRINTF (1, "Accepted connection from client, socket fd=%d.\n", conn_fd);
1372 } else {
1373 /* Connect to the specified address */
1374 /* FIXME: Respect the timeout */
1375 for (rp = result->entries; rp != NULL; rp = rp->next) {
1376 MonoSocketAddress sockaddr;
1377 socklen_t sock_len;
1379 mono_socket_address_init (&sockaddr, &sock_len, rp->family, &rp->address, port);
1381 sfd = socket (rp->family, rp->socktype,
1382 rp->protocol);
1383 if (sfd == -1)
1384 continue;
1386 MONO_ENTER_GC_SAFE;
1387 res = connect (sfd, &sockaddr.addr, sock_len);
1388 MONO_EXIT_GC_SAFE;
1390 if (res != -1)
1391 break; /* Success */
1393 MONO_ENTER_GC_SAFE;
1394 #ifdef HOST_WIN32
1395 closesocket (sfd);
1396 #else
1397 close (sfd);
1398 #endif
1399 MONO_EXIT_GC_SAFE;
1402 if (rp == 0) {
1403 g_printerr ("debugger-agent: Unable to connect to %s:%d\n", host, port);
1404 exit (1);
1407 conn_fd = sfd;
1409 mono_free_address_info (result);
1412 if (!transport_handshake ())
1413 exit (1);
1416 static void
1417 socket_transport_close1 (void)
1419 /* This will interrupt the agent thread */
1420 /* Close the read part only so it can still send back replies */
1421 /* Also shut down the connection listener so that we can exit normally */
1422 #ifdef HOST_WIN32
1423 /* SD_RECEIVE doesn't break the recv in the debugger thread */
1424 shutdown (conn_fd, SD_BOTH);
1425 shutdown (listen_fd, SD_BOTH);
1426 closesocket (listen_fd);
1427 #else
1428 shutdown (conn_fd, SHUT_RD);
1429 shutdown (listen_fd, SHUT_RDWR);
1430 MONO_ENTER_GC_SAFE;
1431 close (listen_fd);
1432 MONO_EXIT_GC_SAFE;
1433 #endif
1436 static void
1437 socket_transport_close2 (void)
1439 #ifdef HOST_WIN32
1440 shutdown (conn_fd, SD_BOTH);
1441 #else
1442 shutdown (conn_fd, SHUT_RDWR);
1443 #endif
1446 static void
1447 register_socket_transport (void)
1449 DebuggerTransport trans;
1451 trans.name = "dt_socket";
1452 trans.connect = socket_transport_connect;
1453 trans.close1 = socket_transport_close1;
1454 trans.close2 = socket_transport_close2;
1455 trans.send = socket_transport_send;
1456 trans.recv = socket_transport_recv;
1458 register_transport (&trans);
1462 * socket_fd_transport_connect:
1465 static void
1466 socket_fd_transport_connect (const char *address)
1468 int res;
1470 res = sscanf (address, "%d", &conn_fd);
1471 if (res != 1) {
1472 g_printerr ("debugger-agent: socket-fd transport address is invalid: '%s'\n", address);
1473 exit (1);
1476 if (!transport_handshake ())
1477 exit (1);
1480 static void
1481 register_socket_fd_transport (void)
1483 DebuggerTransport trans;
1485 /* This is the same as the 'dt_socket' transport, but receives an already connected socket fd */
1486 trans.name = "socket-fd";
1487 trans.connect = socket_fd_transport_connect;
1488 trans.close1 = socket_transport_close1;
1489 trans.close2 = socket_transport_close2;
1490 trans.send = socket_transport_send;
1491 trans.recv = socket_transport_recv;
1493 register_transport (&trans);
1496 #endif /* DISABLE_SOCKET_TRANSPORT */
1499 * TRANSPORT CODE
1502 #define MAX_TRANSPORTS 16
1504 static DebuggerTransport *transport;
1506 static DebuggerTransport transports [MAX_TRANSPORTS];
1507 static int ntransports;
1509 MONO_API void
1510 mono_debugger_agent_register_transport (DebuggerTransport *trans);
1512 void
1513 mono_debugger_agent_register_transport (DebuggerTransport *trans)
1515 register_transport (trans);
1518 static void
1519 register_transport (DebuggerTransport *trans)
1521 g_assert (ntransports < MAX_TRANSPORTS);
1523 memcpy (&transports [ntransports], trans, sizeof (DebuggerTransport));
1524 ntransports ++;
1527 static void
1528 transport_init (void)
1530 int i;
1532 #ifndef DISABLE_SOCKET_TRANSPORT
1533 register_socket_transport ();
1534 register_socket_fd_transport ();
1535 #endif
1537 for (i = 0; i < ntransports; ++i) {
1538 if (!strcmp (agent_config.transport, transports [i].name))
1539 break;
1541 if (i == ntransports) {
1542 g_printerr ("debugger-agent: The supported values for the 'transport' option are: ");
1543 for (i = 0; i < ntransports; ++i)
1544 g_printerr ("%s'%s'", i > 0 ? ", " : "", transports [i].name);
1545 g_printerr ("\n");
1546 exit (1);
1548 transport = &transports [i];
1551 void
1552 transport_connect (const char *address)
1554 transport->connect (address);
1557 static void
1558 transport_close1 (void)
1560 transport->close1 ();
1563 static void
1564 transport_close2 (void)
1566 transport->close2 ();
1569 static int
1570 transport_send (void *buf, int len)
1572 return transport->send (buf, len);
1575 static int
1576 transport_recv (void *buf, int len)
1578 return transport->recv (buf, len);
1581 gboolean
1582 mono_debugger_agent_transport_handshake (void)
1584 return transport_handshake ();
1587 static gboolean
1588 transport_handshake (void)
1590 char handshake_msg [128];
1591 guint8 buf [128];
1592 int res;
1594 disconnected = TRUE;
1596 /* Write handshake message */
1597 sprintf (handshake_msg, "DWP-Handshake");
1599 do {
1600 res = transport_send (handshake_msg, strlen (handshake_msg));
1601 } while (res == -1 && get_last_sock_error () == MONO_EINTR);
1603 g_assert (res != -1);
1605 /* Read answer */
1606 res = transport_recv (buf, strlen (handshake_msg));
1607 if ((res != strlen (handshake_msg)) || (memcmp (buf, handshake_msg, strlen (handshake_msg)) != 0)) {
1608 g_printerr ("debugger-agent: DWP handshake failed.\n");
1609 return FALSE;
1613 * To support older clients, the client sends its protocol version after connecting
1614 * using a command. Until that is received, default to our protocol version.
1616 major_version = MAJOR_VERSION;
1617 minor_version = MINOR_VERSION;
1618 protocol_version_set = FALSE;
1620 #ifndef DISABLE_SOCKET_TRANSPORT
1621 // FIXME: Move this somewhere else
1623 * Set TCP_NODELAY on the socket so the client receives events/command
1624 * results immediately.
1626 if (conn_fd) {
1627 int flag = 1;
1628 int result = setsockopt (conn_fd,
1629 IPPROTO_TCP,
1630 TCP_NODELAY,
1631 (char *) &flag,
1632 sizeof(int));
1633 g_assert (result >= 0);
1636 set_keepalive ();
1637 #endif
1639 disconnected = FALSE;
1640 return TRUE;
1643 static void
1644 stop_debugger_thread (void)
1646 if (!inited)
1647 return;
1649 transport_close1 ();
1652 * Wait for the thread to exit.
1654 * If we continue with the shutdown without waiting for it, then the client might
1655 * not receive an answer to its last command like a resume.
1657 if (!is_debugger_thread ()) {
1658 do {
1659 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
1660 if (!debugger_thread_exited)
1661 mono_coop_cond_wait (&debugger_thread_exited_cond, &debugger_thread_exited_mutex);
1662 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
1663 } while (!debugger_thread_exited);
1665 if (debugger_thread_handle)
1666 mono_thread_info_wait_one_handle (debugger_thread_handle, MONO_INFINITE_WAIT, TRUE);
1669 transport_close2 ();
1672 static void
1673 start_debugger_thread (MonoError *error)
1675 MonoInternalThread *thread;
1677 thread = mono_thread_create_internal (mono_get_root_domain (), (gpointer)debugger_thread, NULL, MONO_THREAD_CREATE_FLAGS_DEBUGGER, error);
1678 return_if_nok (error);
1680 /* Is it possible for the thread to be dead alreay ? */
1681 debugger_thread_handle = mono_threads_open_thread_handle (thread->handle);
1682 g_assert (debugger_thread_handle);
1687 * Functions to decode protocol data
1690 static int
1691 decode_byte (guint8 *buf, guint8 **endbuf, guint8 *limit)
1693 *endbuf = buf + 1;
1694 g_assert (*endbuf <= limit);
1695 return buf [0];
1698 static int
1699 decode_int (guint8 *buf, guint8 **endbuf, guint8 *limit)
1701 *endbuf = buf + 4;
1702 g_assert (*endbuf <= limit);
1704 return (((int)buf [0]) << 24) | (((int)buf [1]) << 16) | (((int)buf [2]) << 8) | (((int)buf [3]) << 0);
1707 static gint64
1708 decode_long (guint8 *buf, guint8 **endbuf, guint8 *limit)
1710 guint32 high = decode_int (buf, &buf, limit);
1711 guint32 low = decode_int (buf, &buf, limit);
1713 *endbuf = buf;
1715 return ((((guint64)high) << 32) | ((guint64)low));
1718 static int
1719 decode_id (guint8 *buf, guint8 **endbuf, guint8 *limit)
1721 return decode_int (buf, endbuf, limit);
1724 static char*
1725 decode_string (guint8 *buf, guint8 **endbuf, guint8 *limit)
1727 int len = decode_int (buf, &buf, limit);
1728 char *s;
1730 if (len < 0) {
1731 *endbuf = buf;
1732 return NULL;
1735 s = (char *)g_malloc (len + 1);
1736 g_assert (s);
1738 memcpy (s, buf, len);
1739 s [len] = '\0';
1740 buf += len;
1741 *endbuf = buf;
1743 return s;
1747 * Functions to encode protocol data
1750 static void
1751 buffer_init (Buffer *buf, int size)
1753 buf->buf = (guint8 *)g_malloc (size);
1754 buf->p = buf->buf;
1755 buf->end = buf->buf + size;
1758 static int
1759 buffer_len (Buffer *buf)
1761 return buf->p - buf->buf;
1764 static void
1765 buffer_make_room (Buffer *buf, int size)
1767 if (buf->end - buf->p < size) {
1768 int new_size = buf->end - buf->buf + size + 32;
1769 guint8 *p = (guint8 *)g_realloc (buf->buf, new_size);
1770 size = buf->p - buf->buf;
1771 buf->buf = p;
1772 buf->p = p + size;
1773 buf->end = buf->buf + new_size;
1777 static void
1778 buffer_add_byte (Buffer *buf, guint8 val)
1780 buffer_make_room (buf, 1);
1781 buf->p [0] = val;
1782 buf->p++;
1785 static void
1786 buffer_add_short (Buffer *buf, guint32 val)
1788 buffer_make_room (buf, 2);
1789 buf->p [0] = (val >> 8) & 0xff;
1790 buf->p [1] = (val >> 0) & 0xff;
1791 buf->p += 2;
1794 static void
1795 buffer_add_int (Buffer *buf, guint32 val)
1797 buffer_make_room (buf, 4);
1798 buf->p [0] = (val >> 24) & 0xff;
1799 buf->p [1] = (val >> 16) & 0xff;
1800 buf->p [2] = (val >> 8) & 0xff;
1801 buf->p [3] = (val >> 0) & 0xff;
1802 buf->p += 4;
1805 static void
1806 buffer_add_long (Buffer *buf, guint64 l)
1808 buffer_add_int (buf, (l >> 32) & 0xffffffff);
1809 buffer_add_int (buf, (l >> 0) & 0xffffffff);
1812 static void
1813 buffer_add_id (Buffer *buf, int id)
1815 buffer_add_int (buf, (guint64)id);
1818 static void
1819 buffer_add_data (Buffer *buf, guint8 *data, int len)
1821 buffer_make_room (buf, len);
1822 memcpy (buf->p, data, len);
1823 buf->p += len;
1826 static void
1827 buffer_add_string (Buffer *buf, const char *str)
1829 int len;
1831 if (str == NULL) {
1832 buffer_add_int (buf, 0);
1833 } else {
1834 len = strlen (str);
1835 buffer_add_int (buf, len);
1836 buffer_add_data (buf, (guint8*)str, len);
1840 static void
1841 buffer_add_byte_array (Buffer *buf, guint8 *bytes, guint32 arr_len)
1843 buffer_add_int (buf, arr_len);
1844 buffer_add_data (buf, bytes, arr_len);
1847 static void
1848 buffer_add_buffer (Buffer *buf, Buffer *data)
1850 buffer_add_data (buf, data->buf, buffer_len (data));
1853 static void
1854 buffer_free (Buffer *buf)
1856 g_free (buf->buf);
1859 static gboolean
1860 send_packet (int command_set, int command, Buffer *data)
1862 Buffer buf;
1863 int len, id;
1864 gboolean res;
1866 id = mono_atomic_inc_i32 (&packet_id);
1868 len = data->p - data->buf + 11;
1869 buffer_init (&buf, len);
1870 buffer_add_int (&buf, len);
1871 buffer_add_int (&buf, id);
1872 buffer_add_byte (&buf, 0); /* flags */
1873 buffer_add_byte (&buf, command_set);
1874 buffer_add_byte (&buf, command);
1875 memcpy (buf.buf + 11, data->buf, data->p - data->buf);
1877 res = transport_send (buf.buf, len);
1879 buffer_free (&buf);
1881 return res;
1884 static gboolean
1885 send_reply_packets (int npackets, ReplyPacket *packets)
1887 Buffer buf;
1888 int i, len;
1889 gboolean res;
1891 len = 0;
1892 for (i = 0; i < npackets; ++i)
1893 len += buffer_len (packets [i].data) + 11;
1894 buffer_init (&buf, len);
1895 for (i = 0; i < npackets; ++i) {
1896 buffer_add_int (&buf, buffer_len (packets [i].data) + 11);
1897 buffer_add_int (&buf, packets [i].id);
1898 buffer_add_byte (&buf, 0x80); /* flags */
1899 buffer_add_byte (&buf, (packets [i].error >> 8) & 0xff);
1900 buffer_add_byte (&buf, packets [i].error);
1901 buffer_add_buffer (&buf, packets [i].data);
1904 res = transport_send (buf.buf, len);
1906 buffer_free (&buf);
1908 return res;
1911 static gboolean
1912 send_reply_packet (int id, int error, Buffer *data)
1914 ReplyPacket packet;
1916 memset (&packet, 0, sizeof (packet));
1917 packet.id = id;
1918 packet.error = error;
1919 packet.data = data;
1921 return send_reply_packets (1, &packet);
1924 static void
1925 send_buffered_reply_packets (void)
1927 int i;
1929 send_reply_packets (nreply_packets, reply_packets);
1930 for (i = 0; i < nreply_packets; ++i)
1931 buffer_free (reply_packets [i].data);
1932 DEBUG_PRINTF (1, "[dbg] Sent %d buffered reply packets [at=%lx].\n", nreply_packets, (long)mono_100ns_ticks () / 10000);
1933 nreply_packets = 0;
1936 static void
1937 buffer_reply_packet (int id, int error, Buffer *data)
1939 ReplyPacket *p;
1941 if (nreply_packets == 128)
1942 send_buffered_reply_packets ();
1944 p = &reply_packets [nreply_packets];
1945 p->id = id;
1946 p->error = error;
1947 p->data = g_new0 (Buffer, 1);
1948 buffer_init (p->data, buffer_len (data));
1949 buffer_add_buffer (p->data, data);
1950 nreply_packets ++;
1954 /* Maps objid -> ObjRef */
1955 /* Protected by the loader lock */
1956 static GHashTable *objrefs;
1957 /* Protected by the loader lock */
1958 static GHashTable *obj_to_objref;
1959 /* Protected by the dbg lock */
1960 static MonoGHashTable *suspended_objs;
1964 static void
1965 objrefs_init (void)
1967 objrefs = g_hash_table_new_full (NULL, NULL, NULL, mono_debugger_free_objref);
1968 obj_to_objref = g_hash_table_new (NULL, NULL);
1969 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");
1972 static void
1973 objrefs_cleanup (void)
1975 g_hash_table_destroy (objrefs);
1976 objrefs = NULL;
1980 * Return an ObjRef for OBJ.
1982 static ObjRef*
1983 get_objref (MonoObject *obj)
1985 ObjRef *ref;
1986 GSList *reflist = NULL, *l;
1987 int hash = 0;
1989 if (obj == NULL)
1990 return NULL;
1992 if (suspend_count) {
1994 * Have to keep object refs created during suspensions alive for the duration of the suspension, so GCs during invokes don't collect them.
1996 dbg_lock ();
1997 mono_g_hash_table_insert_internal (suspended_objs, obj, NULL);
1998 dbg_unlock ();
2001 mono_loader_lock ();
2003 /* FIXME: The tables can grow indefinitely */
2005 if (mono_gc_is_moving ()) {
2007 * Objects can move, so use a hash table mapping hash codes to lists of
2008 * ObjRef structures.
2010 hash = mono_object_hash_internal (obj);
2012 reflist = (GSList *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (hash));
2013 for (l = reflist; l; l = l->next) {
2014 ref = (ObjRef *)l->data;
2015 if (ref && mono_gchandle_get_target_internal (ref->handle) == obj) {
2016 mono_loader_unlock ();
2017 return ref;
2020 } else {
2021 /* Use a hash table with masked pointers to internalize object references */
2022 ref = (ObjRef *)g_hash_table_lookup (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)));
2023 /* ref might refer to a different object with the same addr which was GCd */
2024 if (ref && mono_gchandle_get_target_internal (ref->handle) == obj) {
2025 mono_loader_unlock ();
2026 return ref;
2030 ref = g_new0 (ObjRef, 1);
2031 ref->id = mono_atomic_inc_i32 (&objref_id);
2032 ref->handle = mono_gchandle_new_weakref_internal (obj, FALSE);
2034 g_hash_table_insert (objrefs, GINT_TO_POINTER (ref->id), ref);
2036 if (mono_gc_is_moving ()) {
2037 reflist = g_slist_append (reflist, ref);
2038 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (hash), reflist);
2039 } else {
2040 g_hash_table_insert (obj_to_objref, GINT_TO_POINTER (~((gsize)obj)), ref);
2043 mono_loader_unlock ();
2045 return ref;
2048 static gboolean
2049 true_pred (gpointer key, gpointer value, gpointer user_data)
2051 return TRUE;
2054 static void
2055 clear_suspended_objs (void)
2057 dbg_lock ();
2058 mono_g_hash_table_foreach_remove (suspended_objs, true_pred, NULL);
2059 dbg_unlock ();
2062 static int
2063 get_objid (MonoObject *obj)
2065 if (!obj)
2066 return 0;
2067 else
2068 return get_objref (obj)->id;
2072 * Set OBJ to the object identified by OBJID.
2073 * Returns 0 or an error code if OBJID is invalid or the object has been garbage
2074 * collected.
2076 static ErrorCode
2077 get_object_allow_null (int objid, MonoObject **obj)
2079 ObjRef *ref;
2081 if (objid == 0) {
2082 *obj = NULL;
2083 return ERR_NONE;
2086 if (!objrefs)
2087 return ERR_INVALID_OBJECT;
2089 mono_loader_lock ();
2091 ref = (ObjRef *)g_hash_table_lookup (objrefs, GINT_TO_POINTER (objid));
2093 if (ref) {
2094 *obj = mono_gchandle_get_target_internal (ref->handle);
2095 mono_loader_unlock ();
2096 if (!(*obj))
2097 return ERR_INVALID_OBJECT;
2098 return ERR_NONE;
2099 } else {
2100 mono_loader_unlock ();
2101 return ERR_INVALID_OBJECT;
2105 static ErrorCode
2106 get_object (int objid, MonoObject **obj)
2108 ErrorCode err = get_object_allow_null (objid, obj);
2110 if (err != ERR_NONE)
2111 return err;
2112 if (!(*obj))
2113 return ERR_INVALID_OBJECT;
2114 return ERR_NONE;
2117 static int
2118 decode_objid (guint8 *buf, guint8 **endbuf, guint8 *limit)
2120 return decode_id (buf, endbuf, limit);
2123 static void
2124 buffer_add_objid (Buffer *buf, MonoObject *o)
2126 buffer_add_id (buf, get_objid (o));
2130 * IDS
2133 typedef enum {
2134 ID_ASSEMBLY = 0,
2135 ID_MODULE = 1,
2136 ID_TYPE = 2,
2137 ID_METHOD = 3,
2138 ID_FIELD = 4,
2139 ID_DOMAIN = 5,
2140 ID_PROPERTY = 6,
2141 ID_NUM
2142 } IdType;
2145 * Represents a runtime structure accessible to the debugger client
2147 typedef struct {
2148 /* Unique id used in the wire protocol */
2149 int id;
2150 /* Domain of the runtime structure, NULL if the domain was unloaded */
2151 MonoDomain *domain;
2152 union {
2153 gpointer val;
2154 MonoClass *klass;
2155 MonoMethod *method;
2156 MonoImage *image;
2157 MonoAssembly *assembly;
2158 MonoClassField *field;
2159 MonoDomain *domain;
2160 MonoProperty *property;
2161 } data;
2162 } Id;
2164 typedef struct {
2165 /* Maps runtime structure -> Id */
2166 /* Protected by the dbg lock */
2167 GHashTable *val_to_id [ID_NUM];
2168 /* Classes whose class load event has been sent */
2169 /* Protected by the loader lock */
2170 GHashTable *loaded_classes;
2171 /* Maps MonoClass->GPtrArray of file names */
2172 GHashTable *source_files;
2173 /* Maps source file basename -> GSList of classes */
2174 GHashTable *source_file_to_class;
2175 /* Same with ignore-case */
2176 GHashTable *source_file_to_class_ignorecase;
2177 } AgentDomainInfo;
2179 /* Maps id -> Id */
2180 /* Protected by the dbg lock */
2181 static GPtrArray *ids [ID_NUM];
2183 static void
2184 ids_init (void)
2186 int i;
2188 for (i = 0; i < ID_NUM; ++i)
2189 ids [i] = g_ptr_array_new ();
2192 static void
2193 ids_cleanup (void)
2195 int i, j;
2197 for (i = 0; i < ID_NUM; ++i) {
2198 if (ids [i]) {
2199 for (j = 0; j < ids [i]->len; ++j)
2200 g_free (g_ptr_array_index (ids [i], j));
2201 g_ptr_array_free (ids [i], TRUE);
2203 ids [i] = NULL;
2207 static void
2208 debugger_agent_free_domain_info (MonoDomain *domain)
2210 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
2211 int i, j;
2212 GHashTableIter iter;
2213 GPtrArray *file_names;
2214 char *basename;
2215 GSList *l;
2217 if (info) {
2218 for (i = 0; i < ID_NUM; ++i)
2219 g_hash_table_destroy (info->val_to_id [i]);
2220 g_hash_table_destroy (info->loaded_classes);
2222 g_hash_table_iter_init (&iter, info->source_files);
2223 while (g_hash_table_iter_next (&iter, NULL, (void**)&file_names)) {
2224 for (i = 0; i < file_names->len; ++i)
2225 g_free (g_ptr_array_index (file_names, i));
2226 g_ptr_array_free (file_names, TRUE);
2229 g_hash_table_iter_init (&iter, info->source_file_to_class);
2230 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2231 g_free (basename);
2232 g_slist_free (l);
2235 g_hash_table_iter_init (&iter, info->source_file_to_class_ignorecase);
2236 while (g_hash_table_iter_next (&iter, (void**)&basename, (void**)&l)) {
2237 g_free (basename);
2238 g_slist_free (l);
2241 g_free (info);
2244 domain_jit_info (domain)->agent_info = NULL;
2246 /* Clear ids referencing structures in the domain */
2247 dbg_lock ();
2248 for (i = 0; i < ID_NUM; ++i) {
2249 if (ids [i]) {
2250 for (j = 0; j < ids [i]->len; ++j) {
2251 Id *id = (Id *)g_ptr_array_index (ids [i], j);
2252 if (id->domain == domain)
2253 id->domain = NULL;
2257 dbg_unlock ();
2259 mono_de_domain_remove (domain);
2262 static AgentDomainInfo*
2263 get_agent_domain_info (MonoDomain *domain)
2265 AgentDomainInfo *info = NULL;
2266 MonoJitDomainInfo *jit_info = domain_jit_info (domain);
2268 info = (AgentDomainInfo *)jit_info->agent_info;
2270 if (info) {
2271 mono_memory_read_barrier ();
2272 return info;
2275 info = g_new0 (AgentDomainInfo, 1);
2276 info->loaded_classes = g_hash_table_new (mono_aligned_addr_hash, NULL);
2277 info->source_files = g_hash_table_new (mono_aligned_addr_hash, NULL);
2278 info->source_file_to_class = g_hash_table_new (g_str_hash, g_str_equal);
2279 info->source_file_to_class_ignorecase = g_hash_table_new (g_str_hash, g_str_equal);
2281 mono_memory_write_barrier ();
2283 gpointer other_info = mono_atomic_cas_ptr (&jit_info->agent_info, info, NULL);
2285 if (other_info != NULL) {
2286 g_hash_table_destroy (info->loaded_classes);
2287 g_hash_table_destroy (info->source_files);
2288 g_hash_table_destroy (info->source_file_to_class);
2289 g_hash_table_destroy (info->source_file_to_class_ignorecase);
2290 g_free (info);
2293 return (AgentDomainInfo *)jit_info->agent_info;
2296 static int
2297 get_id (MonoDomain *domain, IdType type, gpointer val)
2299 Id *id;
2300 AgentDomainInfo *info;
2302 if (val == NULL)
2303 return 0;
2305 info = get_agent_domain_info (domain);
2307 dbg_lock ();
2309 if (info->val_to_id [type] == NULL)
2310 info->val_to_id [type] = g_hash_table_new (mono_aligned_addr_hash, NULL);
2312 id = (Id *)g_hash_table_lookup (info->val_to_id [type], val);
2313 if (id) {
2314 dbg_unlock ();
2315 return id->id;
2318 id = g_new0 (Id, 1);
2319 /* Reserve id 0 */
2320 id->id = ids [type]->len + 1;
2321 id->domain = domain;
2322 id->data.val = val;
2324 g_hash_table_insert (info->val_to_id [type], val, id);
2325 g_ptr_array_add (ids [type], id);
2327 dbg_unlock ();
2329 return id->id;
2332 static gpointer
2333 decode_ptr_id (guint8 *buf, guint8 **endbuf, guint8 *limit, IdType type, MonoDomain **domain, ErrorCode *err)
2335 Id *res;
2337 int id = decode_id (buf, endbuf, limit);
2339 *err = ERR_NONE;
2340 if (domain)
2341 *domain = NULL;
2343 if (id == 0)
2344 return NULL;
2346 // FIXME: error handling
2347 dbg_lock ();
2348 g_assert (id > 0 && id <= ids [type]->len);
2350 res = (Id *)g_ptr_array_index (ids [type], GPOINTER_TO_INT (id - 1));
2351 dbg_unlock ();
2353 if (res->domain == NULL || res->domain->state == MONO_APPDOMAIN_UNLOADED) {
2354 DEBUG_PRINTF (1, "ERR_UNLOADED, id=%d, type=%d.\n", id, type);
2355 *err = ERR_UNLOADED;
2356 return NULL;
2359 if (domain)
2360 *domain = res->domain;
2362 return res->data.val;
2365 static int
2366 buffer_add_ptr_id (Buffer *buf, MonoDomain *domain, IdType type, gpointer val)
2368 int id = get_id (domain, type, val);
2370 buffer_add_id (buf, id);
2371 return id;
2374 static MonoClass*
2375 decode_typeid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2377 MonoClass *klass;
2379 klass = (MonoClass *)decode_ptr_id (buf, endbuf, limit, ID_TYPE, domain, err);
2380 if (G_UNLIKELY (log_level >= 2) && klass) {
2381 char *s;
2383 s = mono_type_full_name (m_class_get_byval_arg (klass));
2384 DEBUG_PRINTF (2, "[dbg] recv class [%s]\n", s);
2385 g_free (s);
2387 return klass;
2390 static MonoAssembly*
2391 decode_assemblyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2393 return (MonoAssembly *)decode_ptr_id (buf, endbuf, limit, ID_ASSEMBLY, domain, err);
2396 static MonoImage*
2397 decode_moduleid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2399 return (MonoImage *)decode_ptr_id (buf, endbuf, limit, ID_MODULE, domain, err);
2402 static MonoMethod*
2403 decode_methodid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2405 MonoMethod *m;
2407 m = (MonoMethod *)decode_ptr_id (buf, endbuf, limit, ID_METHOD, domain, err);
2408 if (G_UNLIKELY (log_level >= 2) && m) {
2409 char *s;
2411 s = mono_method_full_name (m, TRUE);
2412 DEBUG_PRINTF (2, "[dbg] recv method [%s]\n", s);
2413 g_free (s);
2415 return m;
2418 static MonoClassField*
2419 decode_fieldid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2421 return (MonoClassField *)decode_ptr_id (buf, endbuf, limit, ID_FIELD, domain, err);
2424 static MonoDomain*
2425 decode_domainid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2427 return (MonoDomain *)decode_ptr_id (buf, endbuf, limit, ID_DOMAIN, domain, err);
2430 static MonoProperty*
2431 decode_propertyid (guint8 *buf, guint8 **endbuf, guint8 *limit, MonoDomain **domain, ErrorCode *err)
2433 return (MonoProperty *)decode_ptr_id (buf, endbuf, limit, ID_PROPERTY, domain, err);
2436 static void
2437 buffer_add_typeid (Buffer *buf, MonoDomain *domain, MonoClass *klass)
2439 buffer_add_ptr_id (buf, domain, ID_TYPE, klass);
2440 if (G_UNLIKELY (log_level >= 2) && klass) {
2441 char *s;
2443 s = mono_type_full_name (m_class_get_byval_arg (klass));
2444 if (is_debugger_thread ())
2445 DEBUG_PRINTF (2, "[dbg] send class [%s]\n", s);
2446 else
2447 DEBUG_PRINTF (2, "[%p] send class [%s]\n", (gpointer) (gsize) mono_native_thread_id_get (), s);
2448 g_free (s);
2452 static void
2453 buffer_add_methodid (Buffer *buf, MonoDomain *domain, MonoMethod *method)
2455 buffer_add_ptr_id (buf, domain, ID_METHOD, method);
2456 if (G_UNLIKELY (log_level >= 2) && method) {
2457 char *s;
2459 s = mono_method_full_name (method, 1);
2460 if (is_debugger_thread ())
2461 DEBUG_PRINTF (2, "[dbg] send method [%s]\n", s);
2462 else
2463 DEBUG_PRINTF (2, "[%p] send method [%s]\n", (gpointer) (gsize) mono_native_thread_id_get (), s);
2464 g_free (s);
2468 static void
2469 buffer_add_assemblyid (Buffer *buf, MonoDomain *domain, MonoAssembly *assembly)
2471 int id;
2473 id = buffer_add_ptr_id (buf, domain, ID_ASSEMBLY, assembly);
2474 if (G_UNLIKELY (log_level >= 2) && assembly)
2475 DEBUG_PRINTF (2, "[dbg] send assembly [%s][%s][%d]\n", assembly->aname.name, domain->friendly_name, id);
2478 static void
2479 buffer_add_moduleid (Buffer *buf, MonoDomain *domain, MonoImage *image)
2481 buffer_add_ptr_id (buf, domain, ID_MODULE, image);
2484 static void
2485 buffer_add_fieldid (Buffer *buf, MonoDomain *domain, MonoClassField *field)
2487 buffer_add_ptr_id (buf, domain, ID_FIELD, field);
2490 static void
2491 buffer_add_propertyid (Buffer *buf, MonoDomain *domain, MonoProperty *property)
2493 buffer_add_ptr_id (buf, domain, ID_PROPERTY, property);
2496 static void
2497 buffer_add_domainid (Buffer *buf, MonoDomain *domain)
2499 buffer_add_ptr_id (buf, domain, ID_DOMAIN, domain);
2502 static void invoke_method (void);
2505 * SUSPEND/RESUME
2508 static MonoJitInfo*
2509 get_top_method_ji (gpointer ip, MonoDomain **domain, gpointer *out_ip)
2511 MonoJitInfo *ji;
2513 if (out_ip)
2514 *out_ip = ip;
2516 ji = mini_jit_info_table_find (mono_domain_get (), (char*)ip, domain);
2517 if (!ji) {
2518 /* Could be an interpreter method */
2520 MonoLMF *lmf = mono_get_lmf ();
2521 MonoInterpFrameHandle *frame;
2523 g_assert (((gsize)lmf->previous_lmf) & 2);
2524 MonoLMFExt *ext = (MonoLMFExt*)lmf;
2526 g_assert (ext->kind == MONO_LMFEXT_INTERP_EXIT || ext->kind == MONO_LMFEXT_INTERP_EXIT_WITH_CTX);
2527 frame = (MonoInterpFrameHandle*)ext->interp_exit_data;
2528 ji = mini_get_interp_callbacks ()->frame_get_jit_info (frame);
2529 if (domain)
2530 *domain = mono_domain_get ();
2531 if (out_ip)
2532 *out_ip = mini_get_interp_callbacks ()->frame_get_ip (frame);
2534 return ji;
2538 * save_thread_context:
2540 * Set CTX as the current threads context which is used for computing stack traces.
2541 * This function is signal-safe.
2543 static void
2544 save_thread_context (MonoContext *ctx)
2546 DebuggerTlsData *tls;
2548 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2549 g_assert (tls);
2551 if (ctx)
2552 mono_thread_state_init_from_monoctx (&tls->context, ctx);
2553 else
2554 mono_thread_state_init_from_current (&tls->context);
2557 static MonoCoopMutex suspend_mutex;
2559 /* Cond variable used to wait for suspend_count becoming 0 */
2560 static MonoCoopCond suspend_cond;
2562 /* Semaphore used to wait for a thread becoming suspended */
2563 static MonoCoopSem suspend_sem;
2565 static void
2566 suspend_init (void)
2568 mono_coop_mutex_init (&suspend_mutex);
2569 mono_coop_cond_init (&suspend_cond);
2570 mono_coop_sem_init (&suspend_sem, 0);
2573 typedef struct
2575 StackFrameInfo last_frame;
2576 gboolean last_frame_set;
2577 MonoContext ctx;
2578 gpointer lmf;
2579 MonoDomain *domain;
2580 } GetLastFrameUserData;
2582 static gboolean
2583 get_last_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
2585 GetLastFrameUserData *data = (GetLastFrameUserData *)user_data;
2587 if (info->type == FRAME_TYPE_MANAGED_TO_NATIVE || info->type == FRAME_TYPE_TRAMPOLINE)
2588 return FALSE;
2590 if (!data->last_frame_set) {
2591 /* Store the last frame */
2592 memcpy (&data->last_frame, info, sizeof (StackFrameInfo));
2593 data->last_frame_set = TRUE;
2594 return FALSE;
2595 } else {
2596 /* Store the context/lmf for the frame above the last frame */
2597 memcpy (&data->ctx, ctx, sizeof (MonoContext));
2598 data->lmf = info->lmf;
2599 data->domain = info->domain;
2600 return TRUE;
2604 static void
2605 copy_unwind_state_from_frame_data (MonoThreadUnwindState *to, GetLastFrameUserData *data, gpointer jit_tls)
2607 memcpy (&to->ctx, &data->ctx, sizeof (MonoContext));
2609 to->unwind_data [MONO_UNWIND_DATA_DOMAIN] = data->domain;
2610 to->unwind_data [MONO_UNWIND_DATA_LMF] = data->lmf;
2611 to->unwind_data [MONO_UNWIND_DATA_JIT_TLS] = jit_tls;
2612 to->valid = TRUE;
2616 * thread_interrupt:
2618 * Process interruption of a thread. This should be signal safe.
2620 * This always runs in the debugger thread.
2622 static void
2623 thread_interrupt (DebuggerTlsData *tls, MonoThreadInfo *info, MonoJitInfo *ji)
2625 gpointer ip;
2626 MonoNativeThreadId tid;
2628 g_assert (info);
2630 ip = MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx);
2631 tid = mono_thread_info_get_tid (info);
2633 // FIXME: Races when the thread leaves managed code before hitting a single step
2634 // event.
2636 if (ji && !ji->is_trampoline) {
2637 /* Running managed code, will be suspended by the single step code */
2638 DEBUG_PRINTF (1, "[%p] Received interrupt while at %s(%p), continuing.\n", (gpointer)(gsize)tid, jinfo_get_method (ji)->name, ip);
2639 } else {
2641 * Running native code, will be suspended when it returns to/enters
2642 * managed code. Treat it as already suspended.
2643 * This might interrupt the code in mono_de_process_single_step (), we use the
2644 * tls->suspending flag to avoid races when that happens.
2646 if (!tls->suspended && !tls->suspending) {
2647 GetLastFrameUserData data;
2649 // FIXME: printf is not signal safe, but this is only used during
2650 // debugger debugging
2651 if (ip)
2652 DEBUG_PRINTF (1, "[%p] Received interrupt while at %p, treating as suspended.\n", (gpointer)(gsize)tid, ip);
2653 //save_thread_context (&ctx);
2655 if (!tls->thread)
2656 /* Already terminated */
2657 return;
2660 * We are in a difficult position: we want to be able to provide stack
2661 * traces for this thread, but we can't use the current ctx+lmf, since
2662 * the thread is still running, so it might return to managed code,
2663 * making these invalid.
2664 * So we start a stack walk and save the first frame, along with the
2665 * parent frame's ctx+lmf. This (hopefully) works because the thread will be
2666 * suspended when it returns to managed code, so the parent's ctx should
2667 * remain valid.
2669 MonoThreadUnwindState *state = mono_thread_info_get_suspend_state (info);
2671 data.last_frame_set = FALSE;
2672 mono_get_eh_callbacks ()->mono_walk_stack_with_state (get_last_frame, state, MONO_UNWIND_SIGNAL_SAFE, &data);
2673 if (data.last_frame_set) {
2674 gpointer jit_tls = tls->thread->thread_info->jit_data;
2676 memcpy (&tls->async_last_frame, &data.last_frame, sizeof (StackFrameInfo));
2678 if (data.last_frame.type == FRAME_TYPE_INTERP_TO_MANAGED || data.last_frame.type == FRAME_TYPE_INTERP_TO_MANAGED_WITH_CTX) {
2680 * Store the current lmf instead of the parent one, since that
2681 * contains the interp exit data.
2683 data.lmf = state->unwind_data [MONO_UNWIND_DATA_LMF];
2686 copy_unwind_state_from_frame_data (&tls->async_state, &data, jit_tls);
2687 /* Don't set tls->context, it could race with the thread processing a breakpoint etc. */
2688 } else {
2689 tls->async_state.valid = FALSE;
2692 mono_memory_barrier ();
2694 tls->suspended = TRUE;
2695 mono_coop_sem_post (&suspend_sem);
2701 * reset_native_thread_suspend_state:
2703 * Reset the suspended flag and state on native threads
2705 static void
2706 reset_native_thread_suspend_state (gpointer key, gpointer value, gpointer user_data)
2708 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2710 if (!tls->really_suspended && tls->suspended) {
2711 tls->suspended = FALSE;
2713 * The thread might still be running if it was executing native code, so the state won't be invalided by
2714 * suspend_current ().
2716 tls->context.valid = FALSE;
2717 tls->async_state.valid = FALSE;
2718 invalidate_frames (tls);
2720 tls->resume_count_internal++;
2724 typedef struct {
2725 DebuggerTlsData *tls;
2726 gboolean valid_info;
2727 } InterruptData;
2729 static SuspendThreadResult
2730 debugger_interrupt_critical (MonoThreadInfo *info, gpointer user_data)
2732 InterruptData *data = (InterruptData *)user_data;
2733 MonoJitInfo *ji;
2735 data->valid_info = TRUE;
2736 MonoDomain *domain = (MonoDomain *) mono_thread_info_get_suspend_state (info)->unwind_data [MONO_UNWIND_DATA_DOMAIN];
2737 if (!domain) {
2738 /* not attached */
2739 ji = NULL;
2740 } else {
2741 ji = mono_jit_info_table_find_internal ( domain, MONO_CONTEXT_GET_IP (&mono_thread_info_get_suspend_state (info)->ctx), TRUE, TRUE);
2744 /* This is signal safe */
2745 thread_interrupt (data->tls, info, ji);
2746 return MonoResumeThread;
2750 * notify_thread:
2752 * Notify a thread that it needs to suspend.
2754 static void
2755 notify_thread (gpointer key, gpointer value, gpointer user_data)
2757 MonoInternalThread *thread = (MonoInternalThread *)key;
2758 DebuggerTlsData *tls = (DebuggerTlsData *)value;
2759 MonoNativeThreadId tid = MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid);
2761 if (mono_thread_internal_is_current (thread) || tls->terminated)
2762 return;
2764 DEBUG_PRINTF (1, "[%p] Interrupting %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2766 /* This is _not_ equivalent to mono_thread_internal_abort () */
2767 InterruptData interrupt_data = { 0 };
2768 interrupt_data.tls = tls;
2770 mono_thread_info_safe_suspend_and_run ((MonoNativeThreadId)(gsize)thread->tid, FALSE, debugger_interrupt_critical, &interrupt_data);
2771 if (!interrupt_data.valid_info) {
2772 DEBUG_PRINTF (1, "[%p] mono_thread_info_suspend_sync () failed for %p...\n", (gpointer) (gsize) mono_native_thread_id_get (), (gpointer)tid);
2774 * Attached thread which died without detaching.
2776 tls->terminated = TRUE;
2780 static void
2781 process_suspend (DebuggerTlsData *tls, MonoContext *ctx)
2783 guint8 *ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
2784 MonoJitInfo *ji;
2785 MonoMethod *method;
2787 if (mono_loader_lock_is_owned_by_self ()) {
2789 * Shortcut for the check in suspend_current (). This speeds up processing
2790 * when executing long running code inside the loader lock, i.e. assembly load
2791 * hooks.
2793 return;
2796 if (is_debugger_thread ())
2797 return;
2799 /* Prevent races with mono_debugger_agent_thread_interrupt () */
2800 if (suspend_count - tls->resume_count > 0)
2801 tls->suspending = TRUE;
2803 DEBUG_PRINTF (1, "[%p] Received single step event for suspending.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2805 if (suspend_count - tls->resume_count == 0) {
2807 * We are executing a single threaded invoke but the single step for
2808 * suspending is still active.
2809 * FIXME: This slows down single threaded invokes.
2811 DEBUG_PRINTF (1, "[%p] Ignored during single threaded invoke.\n", (gpointer) (gsize) mono_native_thread_id_get ());
2812 return;
2815 ji = get_top_method_ji (ip, NULL, NULL);
2816 g_assert (ji);
2817 /* Can't suspend in these methods */
2818 method = jinfo_get_method (ji);
2819 if (method->klass == mono_defaults.string_class && (!strcmp (method->name, "memset") || strstr (method->name, "memcpy")))
2820 return;
2822 save_thread_context (ctx);
2824 suspend_current ();
2828 /* Conditionally call process_suspend depending oh the current state */
2829 static gboolean
2830 try_process_suspend (void *the_tls, MonoContext *ctx, gboolean from_breakpoint)
2832 DebuggerTlsData *tls = (DebuggerTlsData*)the_tls;
2833 /* if there is a suspend pending that is not executed yes */
2834 if (suspend_count > 0) {
2835 /* Fastpath during invokes, see in process_suspend () */
2836 /* if there is a suspend pending but this thread is already resumed, we shouldn't suspend it again and the breakpoint/ss can run */
2837 if (suspend_count - tls->resume_count == 0)
2838 return FALSE;
2839 /* if there is in a invoke the breakpoint/step should be executed even with the suspend pending */
2840 if (tls->invoke)
2841 return FALSE;
2842 /* with the multithreaded single step check if there is a suspend_count pending in the current thread and not in the vm */
2843 if (from_breakpoint && tls->suspend_count <= tls->resume_count_internal)
2844 return FALSE;
2845 process_suspend (tls, ctx);
2846 return TRUE;
2847 } /* if there isn't any suspend pending, the breakpoint/ss will be executed and will suspend then vm when the event is sent */
2848 return FALSE;
2852 * suspend_vm:
2854 * Increase the suspend count of the VM. While the suspend count is greater
2855 * than 0, runtime threads are suspended at certain points during execution.
2857 static void
2858 suspend_vm (void)
2860 gboolean tp_suspend = FALSE;
2861 mono_loader_lock ();
2863 mono_coop_mutex_lock (&suspend_mutex);
2865 suspend_count ++;
2867 DEBUG_PRINTF (1, "[%p] Suspending vm...\n", (gpointer) (gsize) mono_native_thread_id_get ());
2869 if (suspend_count == 1) {
2870 // FIXME: Is it safe to call this inside the lock ?
2871 mono_de_start_single_stepping ();
2872 mono_g_hash_table_foreach (thread_to_tls, notify_thread, NULL);
2875 mono_coop_mutex_unlock (&suspend_mutex);
2877 if (suspend_count == 1)
2879 * Suspend creation of new threadpool threads, since they cannot run
2881 tp_suspend = TRUE;
2882 mono_loader_unlock ();
2884 #ifndef ENABLE_NETCORE
2885 if (tp_suspend)
2886 mono_threadpool_suspend ();
2887 #endif
2891 * resume_vm:
2893 * Decrease the suspend count of the VM. If the count reaches 0, runtime threads
2894 * are resumed.
2896 static void
2897 resume_vm (void)
2899 g_assert (is_debugger_thread ());
2900 gboolean tp_resume = FALSE;
2902 mono_loader_lock ();
2904 mono_coop_mutex_lock (&suspend_mutex);
2906 g_assert (suspend_count > 0);
2907 suspend_count --;
2909 DEBUG_PRINTF (1, "[%p] Resuming vm, suspend count=%d...\n", (gpointer) (gsize) mono_native_thread_id_get (), suspend_count);
2911 if (suspend_count == 0) {
2912 // FIXME: Is it safe to call this inside the lock ?
2913 mono_de_stop_single_stepping ();
2914 mono_g_hash_table_foreach (thread_to_tls, reset_native_thread_suspend_state, NULL);
2917 /* Signal this even when suspend_count > 0, since some threads might have resume_count > 0 */
2918 mono_coop_cond_broadcast (&suspend_cond);
2920 mono_coop_mutex_unlock (&suspend_mutex);
2921 //g_assert (err == 0);
2923 if (suspend_count == 0)
2924 tp_resume = TRUE;
2925 mono_loader_unlock ();
2927 #ifndef ENABLE_NETCORE
2928 if (tp_resume)
2929 mono_threadpool_resume ();
2930 #endif
2934 * resume_thread:
2936 * Resume just one thread.
2938 static void
2939 resume_thread (MonoInternalThread *thread)
2941 DebuggerTlsData *tls;
2943 g_assert (is_debugger_thread ());
2945 mono_loader_lock ();
2947 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
2948 g_assert (tls);
2950 mono_coop_mutex_lock (&suspend_mutex);
2952 g_assert (suspend_count > 0);
2954 DEBUG_PRINTF (1, "[sdb] Resuming thread %p...\n", (gpointer)(gssize)thread->tid);
2956 tls->resume_count += suspend_count;
2957 tls->resume_count_internal += tls->suspend_count;
2958 tls->suspend_count = 0;
2961 * Signal suspend_count without decreasing suspend_count, the threads will wake up
2962 * but only the one whose resume_count field is > 0 will be resumed.
2964 mono_coop_cond_broadcast (&suspend_cond);
2966 mono_coop_mutex_unlock (&suspend_mutex);
2967 //g_assert (err == 0);
2969 mono_loader_unlock ();
2972 static void
2973 free_frames (StackFrame **frames, int nframes)
2975 int i;
2977 for (i = 0; i < nframes; ++i) {
2978 if (frames [i]->jit)
2979 mono_debug_free_method_jit_info (frames [i]->jit);
2980 g_free (frames [i]);
2982 g_free (frames);
2985 static void
2986 invalidate_frames (DebuggerTlsData *tls)
2988 mono_loader_lock ();
2990 if (!tls)
2991 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
2992 g_assert (tls);
2994 free_frames (tls->frames, tls->frame_count);
2995 tls->frame_count = 0;
2996 tls->frames = NULL;
2998 free_frames (tls->restore_frames, tls->restore_frame_count);
2999 tls->restore_frame_count = 0;
3000 tls->restore_frames = NULL;
3002 mono_loader_unlock ();
3006 * suspend_current:
3008 * Suspend the current thread until the runtime is resumed. If the thread has a
3009 * pending invoke, then the invoke is executed before this function returns.
3011 static void
3012 suspend_current (void)
3014 DebuggerTlsData *tls;
3016 g_assert (!is_debugger_thread ());
3018 if (mono_loader_lock_is_owned_by_self ()) {
3020 * If we own the loader mutex, can't suspend until we release it, since the
3021 * whole runtime can deadlock otherwise.
3023 return;
3026 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3027 g_assert (tls);
3029 gboolean do_resume = FALSE;
3030 while (!do_resume) {
3031 mono_coop_mutex_lock (&suspend_mutex);
3033 tls->suspending = FALSE;
3034 tls->really_suspended = TRUE;
3036 if (!tls->suspended) {
3037 tls->suspended = TRUE;
3038 mono_coop_sem_post (&suspend_sem);
3041 mono_debugger_log_suspend (tls);
3042 DEBUG_PRINTF (1, "[%p] Suspended.\n", (gpointer) (gsize) mono_native_thread_id_get ());
3044 while (suspend_count - tls->resume_count > 0) {
3045 mono_coop_cond_wait (&suspend_cond, &suspend_mutex);
3048 tls->suspended = FALSE;
3049 tls->really_suspended = FALSE;
3051 mono_coop_mutex_unlock (&suspend_mutex);
3053 mono_debugger_log_resume (tls);
3054 DEBUG_PRINTF (1, "[%p] Resumed.\n", (gpointer) (gsize) mono_native_thread_id_get ());
3056 if (tls->pending_invoke) {
3057 /* Save the original context */
3058 tls->pending_invoke->has_ctx = TRUE;
3059 tls->pending_invoke->ctx = tls->context.ctx;
3061 invoke_method ();
3063 /* Have to suspend again */
3064 } else {
3065 do_resume = TRUE;
3069 /* The frame info becomes invalid after a resume */
3070 tls->context.valid = FALSE;
3071 tls->async_state.valid = FALSE;
3072 invalidate_frames (tls);
3073 mono_stopwatch_start (&tls->step_time);
3076 static void
3077 count_thread (gpointer key, gpointer value, gpointer user_data)
3079 DebuggerTlsData *tls = (DebuggerTlsData *)value;
3081 if (!tls->suspended && !tls->terminated && !mono_thread_internal_is_current (tls->thread))
3082 *(int*)user_data = *(int*)user_data + 1;
3085 static int
3086 count_threads_to_wait_for (void)
3088 int count = 0;
3090 mono_loader_lock ();
3091 mono_g_hash_table_foreach (thread_to_tls, count_thread, &count);
3092 mono_loader_unlock ();
3094 return count;
3098 * wait_for_suspend:
3100 * Wait until the runtime is completely suspended.
3102 static void
3103 wait_for_suspend (void)
3105 int nthreads, nwait, err;
3106 gboolean waited = FALSE;
3108 // FIXME: Threads starting/stopping ?
3109 mono_loader_lock ();
3110 nthreads = mono_g_hash_table_size (thread_to_tls);
3111 mono_loader_unlock ();
3113 while (TRUE) {
3114 nwait = count_threads_to_wait_for ();
3115 if (nwait) {
3116 DEBUG_PRINTF (1, "Waiting for %d(%d) threads to suspend...\n", nwait, nthreads);
3117 err = mono_coop_sem_wait (&suspend_sem, MONO_SEM_FLAGS_NONE);
3118 g_assert (err == 0);
3119 waited = TRUE;
3120 } else {
3121 break;
3125 if (waited)
3126 DEBUG_PRINTF (1, "%d threads suspended.\n", nthreads);
3130 * is_suspended:
3132 * Return whenever the runtime is suspended.
3134 static gboolean
3135 is_suspended (void)
3137 return count_threads_to_wait_for () == 0;
3140 static void
3141 no_seq_points_found (MonoMethod *method, int offset)
3144 * This can happen in full-aot mode with assemblies AOTed without the 'soft-debug' option to save space.
3146 printf ("Unable to find seq points for method '%s', offset 0x%x.\n", mono_method_full_name (method, TRUE), offset);
3149 static int
3150 calc_il_offset (MonoDomain *domain, MonoMethod *method, int native_offset, gboolean is_top_frame)
3152 int ret = -1;
3153 if (is_top_frame) {
3154 SeqPoint sp;
3155 /* mono_debug_il_offset_from_address () doesn't seem to be precise enough (#2092) */
3156 if (mono_find_prev_seq_point_for_native_offset (domain, method, native_offset, NULL, &sp))
3157 ret = sp.il_offset;
3159 if (ret == -1)
3160 ret = mono_debug_il_offset_from_address (method, domain, native_offset);
3161 return ret;
3164 typedef struct {
3165 DebuggerTlsData *tls;
3166 GSList *frames;
3167 gboolean set_debugger_flag;
3168 } ComputeFramesUserData;
3170 static gboolean
3171 process_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3173 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3174 StackFrame *frame;
3175 MonoMethod *method, *actual_method, *api_method;
3176 int flags = 0;
3178 mono_loader_lock ();
3179 if (info->type != FRAME_TYPE_MANAGED && info->type != FRAME_TYPE_INTERP && info->type != FRAME_TYPE_MANAGED_TO_NATIVE) {
3180 if (info->type == FRAME_TYPE_DEBUGGER_INVOKE) {
3181 /* Mark the last frame as an invoke frame */
3182 if (ud->frames)
3183 ((StackFrame*)g_slist_last (ud->frames)->data)->flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3184 else
3185 ud->set_debugger_flag = TRUE;
3187 mono_loader_unlock ();
3188 return FALSE;
3191 if (info->ji)
3192 method = jinfo_get_method (info->ji);
3193 else
3194 method = info->method;
3195 actual_method = info->actual_method;
3196 api_method = method;
3198 if (!method) {
3199 mono_loader_unlock ();
3200 return FALSE;
3203 if (!method || (method->wrapper_type && method->wrapper_type != MONO_WRAPPER_DYNAMIC_METHOD && method->wrapper_type != MONO_WRAPPER_MANAGED_TO_NATIVE)) {
3204 mono_loader_unlock ();
3205 return FALSE;
3208 if (info->il_offset == -1) {
3209 info->il_offset = calc_il_offset (info->domain, method, info->native_offset, ud->frames == NULL);
3212 DEBUG_PRINTF (1, "\tFrame: %s:[il=0x%x, native=0x%x] %d\n", mono_method_full_name (method, TRUE), info->il_offset, info->native_offset, info->managed);
3214 if (method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE) {
3215 if (!CHECK_PROTOCOL_VERSION (2, 17)) {
3216 /* Older clients can't handle this flag */
3217 mono_loader_unlock ();
3218 return FALSE;
3220 api_method = mono_marshal_method_from_wrapper (method);
3221 if (!api_method) {
3222 mono_loader_unlock ();
3223 return FALSE;
3225 actual_method = api_method;
3226 flags |= FRAME_FLAG_NATIVE_TRANSITION;
3229 if (ud->set_debugger_flag) {
3230 g_assert (g_slist_length (ud->frames) == 0);
3231 flags |= FRAME_FLAG_DEBUGGER_INVOKE;
3232 ud->set_debugger_flag = FALSE;
3235 frame = g_new0 (StackFrame, 1);
3236 frame->de.ji = info->ji;
3237 frame->de.domain = info->domain;
3238 frame->de.method = method;
3239 frame->de.native_offset = info->native_offset;
3241 frame->actual_method = actual_method;
3242 frame->api_method = api_method;
3243 frame->il_offset = info->il_offset;
3244 frame->flags = flags;
3245 frame->interp_frame = info->interp_frame;
3246 frame->frame_addr = info->frame_addr;
3247 if (info->reg_locations)
3248 memcpy (frame->reg_locations, info->reg_locations, MONO_MAX_IREGS * sizeof (host_mgreg_t*));
3249 if (ctx) {
3250 frame->ctx = *ctx;
3251 frame->has_ctx = TRUE;
3254 ud->frames = g_slist_append (ud->frames, frame);
3256 mono_loader_unlock ();
3257 return FALSE;
3260 static gint32 isFixedSizeArray (MonoClassField *f)
3262 ERROR_DECL (error);
3263 if (!CHECK_PROTOCOL_VERSION (2, 53) || f->type->type != MONO_TYPE_VALUETYPE) {
3264 return 1;
3266 MonoCustomAttrInfo *cinfo;
3267 MonoCustomAttrEntry *attr;
3268 int aindex;
3269 gint32 ret = 1;
3270 cinfo = mono_custom_attrs_from_field_checked (f->parent, f, error);
3271 goto_if_nok (error, leave);
3272 attr = NULL;
3273 if (cinfo) {
3274 for (aindex = 0; aindex < cinfo->num_attrs; ++aindex) {
3275 MonoClass *ctor_class = cinfo->attrs [aindex].ctor->klass;
3276 MonoClass *fixed_size_class = mono_class_try_get_fixed_buffer_class ();
3277 if (fixed_size_class != NULL && mono_class_has_parent (ctor_class, fixed_size_class)) {
3278 attr = &cinfo->attrs [aindex];
3279 gpointer *typed_args, *named_args;
3280 CattrNamedArg *arginfo;
3281 int num_named_args;
3283 mono_reflection_create_custom_attr_data_args_noalloc (mono_defaults.corlib, attr->ctor, attr->data, attr->data_size,
3284 &typed_args, &named_args, &num_named_args, &arginfo, error);
3285 if (!is_ok (error)) {
3286 ret = 0;
3287 goto leave;
3289 ret = *(gint32*)typed_args [1];
3290 g_free (typed_args [1]);
3291 g_free (typed_args);
3292 g_free (named_args);
3293 g_free (arginfo);
3294 return ret;
3298 leave:
3299 mono_error_cleanup (error);
3300 return ret;
3303 static gboolean
3304 process_filter_frame (StackFrameInfo *info, MonoContext *ctx, gpointer user_data)
3306 ComputeFramesUserData *ud = (ComputeFramesUserData *)user_data;
3309 * 'tls->filter_ctx' is the location of the throw site.
3311 * mono_walk_stack() will never actually hit the throw site, but unwind
3312 * directly from the filter to the call site; we abort stack unwinding here
3313 * once this happens and resume from the throw site.
3315 if (info->frame_addr >= MONO_CONTEXT_GET_SP (&ud->tls->filter_state.ctx))
3316 return TRUE;
3318 return process_frame (info, ctx, user_data);
3322 * Return a malloc-ed list of StackFrame structures.
3324 static StackFrame**
3325 compute_frame_info_from (MonoInternalThread *thread, DebuggerTlsData *tls, MonoThreadUnwindState *state, int *out_nframes)
3327 ComputeFramesUserData user_data;
3328 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3329 StackFrame **res;
3330 int i, nframes;
3331 GSList *l;
3333 user_data.tls = tls;
3334 user_data.frames = NULL;
3336 mono_walk_stack_with_state (process_frame, state, opts, &user_data);
3338 nframes = g_slist_length (user_data.frames);
3339 res = g_new0 (StackFrame*, nframes);
3340 l = user_data.frames;
3341 for (i = 0; i < nframes; ++i) {
3342 res [i] = (StackFrame *)l->data;
3343 l = l->next;
3345 *out_nframes = nframes;
3347 return res;
3350 static void
3351 compute_frame_info (MonoInternalThread *thread, DebuggerTlsData *tls, gboolean force_update)
3353 ComputeFramesUserData user_data;
3354 GSList *tmp;
3355 int i, findex, new_frame_count;
3356 StackFrame **new_frames, *f;
3357 MonoUnwindOptions opts = (MonoUnwindOptions)(MONO_UNWIND_DEFAULT | MONO_UNWIND_REG_LOCATIONS);
3359 // FIXME: Locking on tls
3360 if (tls->frames && tls->frames_up_to_date && !force_update)
3361 return;
3363 DEBUG_PRINTF (1, "Frames for %p(tid=%lx):\n", thread, (glong)thread->tid);
3365 if (CHECK_PROTOCOL_VERSION (2, 52)) {
3366 if (tls->restore_state.valid && MONO_CONTEXT_GET_IP (&tls->context.ctx) != MONO_CONTEXT_GET_IP (&tls->restore_state.ctx)) {
3367 new_frames = compute_frame_info_from (thread, tls, &tls->restore_state, &new_frame_count);
3368 invalidate_frames (tls);
3370 tls->frames = new_frames;
3371 tls->frame_count = new_frame_count;
3372 tls->frames_up_to_date = TRUE;
3373 return;
3377 user_data.tls = tls;
3378 user_data.frames = NULL;
3379 if (tls->terminated) {
3380 tls->frame_count = 0;
3381 return;
3382 } if (!tls->really_suspended && tls->async_state.valid) {
3383 /* Have to use the state saved by the signal handler */
3384 process_frame (&tls->async_last_frame, NULL, &user_data);
3385 mono_walk_stack_with_state (process_frame, &tls->async_state, opts, &user_data);
3386 } else if (tls->filter_state.valid) {
3388 * We are inside an exception filter.
3390 * First we add all the frames from inside the filter; 'tls->ctx' has the current context.
3392 if (tls->context.valid) {
3393 mono_walk_stack_with_state (process_filter_frame, &tls->context, opts, &user_data);
3394 DEBUG_PRINTF (1, "\tFrame: <call filter>\n");
3397 * After that, we resume unwinding from the location where the exception has been thrown.
3399 mono_walk_stack_with_state (process_frame, &tls->filter_state, opts, &user_data);
3400 } else if (tls->context.valid) {
3401 mono_walk_stack_with_state (process_frame, &tls->context, opts, &user_data);
3402 } else {
3403 // FIXME:
3404 tls->frame_count = 0;
3405 return;
3408 new_frame_count = g_slist_length (user_data.frames);
3409 new_frames = g_new0 (StackFrame*, new_frame_count);
3410 findex = 0;
3411 for (tmp = user_data.frames; tmp; tmp = tmp->next) {
3412 f = (StackFrame *)tmp->data;
3415 * Reuse the id for already existing stack frames, so invokes don't invalidate
3416 * the still valid stack frames.
3418 for (i = 0; i < tls->frame_count; ++i) {
3419 if (tls->frames [i]->frame_addr == f->frame_addr) {
3420 f->id = tls->frames [i]->id;
3421 break;
3425 if (i >= tls->frame_count)
3426 f->id = mono_atomic_inc_i32 (&frame_id);
3428 new_frames [findex ++] = f;
3431 g_slist_free (user_data.frames);
3433 invalidate_frames (tls);
3435 tls->frames = new_frames;
3436 tls->frame_count = new_frame_count;
3437 tls->frames_up_to_date = TRUE;
3439 if (CHECK_PROTOCOL_VERSION (2, 52)) {
3440 MonoJitTlsData *jit_data = thread->thread_info->jit_data;
3441 gboolean has_interp_resume_state = FALSE;
3442 MonoInterpFrameHandle interp_resume_frame = NULL;
3443 gpointer interp_resume_ip = 0;
3444 mini_get_interp_callbacks ()->get_resume_state (jit_data, &has_interp_resume_state, &interp_resume_frame, &interp_resume_ip);
3445 if (has_interp_resume_state && tls->frame_count > 0) {
3446 StackFrame *top_frame = tls->frames [0];
3447 if (interp_resume_frame == top_frame->interp_frame) {
3448 int native_offset = (int) ((uintptr_t) interp_resume_ip - (uintptr_t) top_frame->de.ji->code_start);
3449 top_frame->il_offset = calc_il_offset (top_frame->de.domain, top_frame->de.method, native_offset, TRUE);
3456 * GHFunc to emit an appdomain creation event
3457 * @param key Don't care
3458 * @param value A loaded appdomain
3459 * @param user_data Don't care
3461 static void
3462 emit_appdomain_load (gpointer key, gpointer value, gpointer user_data)
3464 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, value);
3465 g_hash_table_foreach (get_agent_domain_info ((MonoDomain *)value)->loaded_classes, emit_type_load, NULL);
3469 * GHFunc to emit a thread start event
3470 * @param key A thread id
3471 * @param value A thread object
3472 * @param user_data Don't care
3474 static void
3475 emit_thread_start (gpointer key, gpointer value, gpointer user_data)
3477 g_assert (!mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (GPOINTER_TO_UINT (key)), debugger_thread_id));
3478 process_profiler_event (EVENT_KIND_THREAD_START, value);
3482 * GFunc to emit an assembly load event
3483 * @param value A loaded assembly
3484 * @param user_data Don't care
3486 static void
3487 emit_assembly_load (gpointer value, gpointer user_data)
3489 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, value);
3493 * GFunc to emit a type load event
3494 * @param value A loaded type
3495 * @param user_data Don't care
3497 static void
3498 emit_type_load (gpointer key, gpointer value, gpointer user_data)
3500 process_profiler_event (EVENT_KIND_TYPE_LOAD, value);
3504 static void gc_finalizing (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 = TRUE;
3516 static void gc_finalized (MonoProfiler *prof)
3518 DebuggerTlsData *tls;
3520 if (is_debugger_thread ())
3521 return;
3523 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3524 g_assert (tls);
3525 tls->gc_finalizing = FALSE;
3529 static char*
3530 strdup_tolower (char *s)
3532 char *s2, *p;
3534 s2 = g_strdup (s);
3535 for (p = s2; *p; ++p)
3536 *p = tolower (*p);
3537 return s2;
3541 * Same as g_path_get_basename () but handles windows paths as well,
3542 * which can occur in .mdb files created by pdb2mdb.
3544 static char*
3545 dbg_path_get_basename (const char *filename)
3547 char *r;
3549 if (!filename || strchr (filename, '/') || !strchr (filename, '\\'))
3550 return g_path_get_basename (filename);
3552 /* From gpath.c */
3554 /* No separator -> filename */
3555 r = (char*)strrchr (filename, '\\');
3556 if (r == NULL)
3557 return g_strdup (filename);
3559 /* Trailing slash, remove component */
3560 if (r [1] == 0){
3561 char *copy = g_strdup (filename);
3562 copy [r-filename] = 0;
3563 r = strrchr (copy, '\\');
3565 if (r == NULL){
3566 g_free (copy);
3567 return g_strdup ("/");
3569 r = g_strdup (&r[1]);
3570 g_free (copy);
3571 return r;
3574 return g_strdup (&r[1]);
3577 static void
3578 init_jit_info_dbg_attrs (MonoJitInfo *ji)
3580 ERROR_DECL (error);
3581 MonoCustomAttrInfo *ainfo;
3583 if (ji->dbg_attrs_inited)
3584 return;
3586 MONO_STATIC_POINTER_INIT (MonoClass, hidden_klass)
3587 hidden_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerHiddenAttribute");
3588 MONO_STATIC_POINTER_INIT_END (MonoClass, hidden_klass)
3591 MONO_STATIC_POINTER_INIT (MonoClass, step_through_klass)
3592 step_through_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerStepThroughAttribute");
3593 MONO_STATIC_POINTER_INIT_END (MonoClass, step_through_klass)
3595 MONO_STATIC_POINTER_INIT (MonoClass, non_user_klass)
3596 non_user_klass = mono_class_load_from_name (mono_defaults.corlib, "System.Diagnostics", "DebuggerNonUserCodeAttribute");
3597 MONO_STATIC_POINTER_INIT_END (MonoClass, non_user_klass)
3599 ainfo = mono_custom_attrs_from_method_checked (jinfo_get_method (ji), error);
3600 mono_error_cleanup (error); /* FIXME don't swallow the error? */
3601 if (ainfo) {
3602 if (mono_custom_attrs_has_attr (ainfo, hidden_klass))
3603 ji->dbg_hidden = TRUE;
3604 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3605 ji->dbg_step_through = TRUE;
3606 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3607 ji->dbg_non_user_code = TRUE;
3608 mono_custom_attrs_free (ainfo);
3611 ainfo = mono_custom_attrs_from_class_checked (jinfo_get_method (ji)->klass, error);
3612 mono_error_cleanup (error); /* FIXME don't swallow the error? */
3613 if (ainfo) {
3614 if (mono_custom_attrs_has_attr (ainfo, step_through_klass))
3615 ji->dbg_step_through = TRUE;
3616 if (mono_custom_attrs_has_attr (ainfo, non_user_klass))
3617 ji->dbg_non_user_code = TRUE;
3618 mono_custom_attrs_free (ainfo);
3621 mono_memory_barrier ();
3622 ji->dbg_attrs_inited = TRUE;
3626 * EVENT HANDLING
3630 * create_event_list:
3632 * Return a list of event request ids matching EVENT, starting from REQS, which
3633 * can be NULL to include all event requests. Set SUSPEND_POLICY to the suspend
3634 * policy.
3635 * We return request ids, instead of requests, to simplify threading, since
3636 * requests could be deleted anytime when the loader lock is not held.
3637 * LOCKING: Assumes the loader lock is held.
3639 static GSList*
3640 create_event_list (EventKind event, GPtrArray *reqs, MonoJitInfo *ji, EventInfo *ei, int *suspend_policy)
3642 int i, j;
3643 GSList *events = NULL;
3645 *suspend_policy = SUSPEND_POLICY_NONE;
3647 if (!reqs)
3648 reqs = event_requests;
3650 if (!reqs)
3651 return NULL;
3652 gboolean has_everything_else = FALSE;
3653 gboolean is_new_filtered_exception = FALSE;
3654 gboolean filteredException = TRUE;
3655 gint filtered_suspend_policy = 0;
3656 gint filtered_req_id = 0;
3657 gint everything_else_suspend_policy = 0;
3658 gint everything_else_req_id = 0;
3659 gboolean is_already_filtered = FALSE;
3660 for (i = 0; i < reqs->len; ++i) {
3661 EventRequest *req = (EventRequest *)g_ptr_array_index (reqs, i);
3662 if (req->event_kind == event) {
3663 gboolean filtered = FALSE;
3665 /* Apply filters */
3666 for (j = 0; j < req->nmodifiers; ++j) {
3667 Modifier *mod = &req->modifiers [j];
3669 if (mod->kind == MOD_KIND_COUNT) {
3670 filtered = TRUE;
3671 if (mod->data.count > 0) {
3672 if (mod->data.count > 0) {
3673 mod->data.count --;
3674 if (mod->data.count == 0)
3675 filtered = FALSE;
3678 } else if (mod->kind == MOD_KIND_THREAD_ONLY) {
3679 if (mod->data.thread != mono_thread_internal_current ())
3680 filtered = TRUE;
3681 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && !mod->not_filtered_feature && ei) {
3682 if (mod->data.exc_class && mod->subclasses && !mono_class_is_assignable_from_internal (mod->data.exc_class, ei->exc->vtable->klass))
3683 filtered = TRUE;
3684 if (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)
3685 filtered = TRUE;
3686 if (ei->caught && !mod->caught)
3687 filtered = TRUE;
3688 if (!ei->caught && !mod->uncaught)
3689 filtered = TRUE;
3690 } else if (mod->kind == MOD_KIND_EXCEPTION_ONLY && mod->not_filtered_feature && ei) {
3691 is_new_filtered_exception = TRUE;
3692 if ((mod->data.exc_class && mod->subclasses && mono_class_is_assignable_from_internal (mod->data.exc_class, ei->exc->vtable->klass)) ||
3693 (mod->data.exc_class && !mod->subclasses && mod->data.exc_class != ei->exc->vtable->klass)) {
3694 is_already_filtered = TRUE;
3695 if ((ei->caught && mod->caught) || (!ei->caught && mod->uncaught)) {
3696 filteredException = FALSE;
3697 filtered_suspend_policy = req->suspend_policy;
3698 filtered_req_id = req->id;
3701 if (!mod->data.exc_class && mod->everything_else) {
3702 if ((ei->caught && mod->caught) || (!ei->caught && mod->uncaught)) {
3703 has_everything_else = TRUE;
3704 everything_else_req_id = req->id;
3705 everything_else_suspend_policy = req->suspend_policy;
3708 if (!mod->data.exc_class && !mod->everything_else) {
3709 if ((ei->caught && mod->caught) || (!ei->caught && mod->uncaught)) {
3710 filteredException = FALSE;
3711 filtered_suspend_policy = req->suspend_policy;
3712 filtered_req_id = req->id;
3715 } else if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && ji) {
3716 int k;
3717 gboolean found = FALSE;
3718 MonoAssembly **assemblies = mod->data.assemblies;
3720 if (assemblies) {
3721 for (k = 0; assemblies [k]; ++k)
3722 if (assemblies [k] == m_class_get_image (jinfo_get_method (ji)->klass)->assembly)
3723 found = TRUE;
3725 if (!found)
3726 filtered = TRUE;
3727 } else if (mod->kind == MOD_KIND_SOURCE_FILE_ONLY && ei && ei->klass) {
3728 gpointer iter = NULL;
3729 MonoMethod *method;
3730 MonoDebugSourceInfo *sinfo;
3731 char *s;
3732 gboolean found = FALSE;
3733 int i;
3734 GPtrArray *source_file_list;
3736 while ((method = mono_class_get_methods (ei->klass, &iter))) {
3737 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
3739 if (minfo) {
3740 mono_debug_get_seq_points (minfo, NULL, &source_file_list, NULL, NULL, NULL);
3741 for (i = 0; i < source_file_list->len; ++i) {
3742 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
3744 * Do a case-insesitive match by converting the file name to
3745 * lowercase.
3747 s = strdup_tolower (sinfo->source_file);
3748 if (g_hash_table_lookup (mod->data.source_files, s))
3749 found = TRUE;
3750 else {
3751 char *s2 = dbg_path_get_basename (sinfo->source_file);
3752 char *s3 = strdup_tolower (s2);
3754 if (g_hash_table_lookup (mod->data.source_files, s3))
3755 found = TRUE;
3756 g_free (s2);
3757 g_free (s3);
3759 g_free (s);
3761 g_ptr_array_free (source_file_list, TRUE);
3764 if (!found)
3765 filtered = TRUE;
3766 } else if (mod->kind == MOD_KIND_TYPE_NAME_ONLY && ei && ei->klass) {
3767 char *s;
3769 s = mono_type_full_name (m_class_get_byval_arg (ei->klass));
3770 if (!g_hash_table_lookup (mod->data.type_names, s))
3771 filtered = TRUE;
3772 g_free (s);
3773 } else if (mod->kind == MOD_KIND_STEP) {
3774 if ((mod->data.filter & STEP_FILTER_STATIC_CTOR) && ji &&
3775 (jinfo_get_method (ji)->flags & METHOD_ATTRIBUTE_SPECIAL_NAME) &&
3776 !strcmp (jinfo_get_method (ji)->name, ".cctor") &&
3777 (jinfo_get_method (ji) != ((SingleStepReq*)req->info)->start_method))
3778 filtered = TRUE;
3779 if ((mod->data.filter & STEP_FILTER_DEBUGGER_HIDDEN) && ji) {
3780 init_jit_info_dbg_attrs (ji);
3781 if (ji->dbg_hidden)
3782 filtered = TRUE;
3784 if ((mod->data.filter & STEP_FILTER_DEBUGGER_STEP_THROUGH) && ji) {
3785 init_jit_info_dbg_attrs (ji);
3786 if (ji->dbg_step_through)
3787 filtered = TRUE;
3789 if ((mod->data.filter & STEP_FILTER_DEBUGGER_NON_USER_CODE) && ji) {
3790 init_jit_info_dbg_attrs (ji);
3791 if (ji->dbg_non_user_code)
3792 filtered = TRUE;
3797 if (!filtered && !is_new_filtered_exception) {
3798 *suspend_policy = MAX (*suspend_policy, req->suspend_policy);
3799 events = g_slist_append (events, GINT_TO_POINTER (req->id));
3804 if (has_everything_else && !is_already_filtered) {
3805 filteredException = FALSE;
3806 filtered_suspend_policy = everything_else_suspend_policy;
3807 filtered_req_id = everything_else_req_id;
3810 if (!filteredException) {
3811 *suspend_policy = MAX (*suspend_policy, filtered_suspend_policy);
3812 events = g_slist_append (events, GINT_TO_POINTER (filtered_req_id));
3815 /* Send a VM START/DEATH event by default */
3816 if (event == EVENT_KIND_VM_START)
3817 events = g_slist_append (events, GINT_TO_POINTER (0));
3818 if (event == EVENT_KIND_VM_DEATH)
3819 events = g_slist_append (events, GINT_TO_POINTER (0));
3821 return events;
3824 static G_GNUC_UNUSED const char*
3825 event_to_string (EventKind event)
3827 switch (event) {
3828 case EVENT_KIND_VM_START: return "VM_START";
3829 case EVENT_KIND_VM_DEATH: return "VM_DEATH";
3830 case EVENT_KIND_THREAD_START: return "THREAD_START";
3831 case EVENT_KIND_THREAD_DEATH: return "THREAD_DEATH";
3832 case EVENT_KIND_APPDOMAIN_CREATE: return "APPDOMAIN_CREATE";
3833 case EVENT_KIND_APPDOMAIN_UNLOAD: return "APPDOMAIN_UNLOAD";
3834 case EVENT_KIND_METHOD_ENTRY: return "METHOD_ENTRY";
3835 case EVENT_KIND_METHOD_EXIT: return "METHOD_EXIT";
3836 case EVENT_KIND_ASSEMBLY_LOAD: return "ASSEMBLY_LOAD";
3837 case EVENT_KIND_ASSEMBLY_UNLOAD: return "ASSEMBLY_UNLOAD";
3838 case EVENT_KIND_BREAKPOINT: return "BREAKPOINT";
3839 case EVENT_KIND_STEP: return "STEP";
3840 case EVENT_KIND_TYPE_LOAD: return "TYPE_LOAD";
3841 case EVENT_KIND_EXCEPTION: return "EXCEPTION";
3842 case EVENT_KIND_KEEPALIVE: return "KEEPALIVE";
3843 case EVENT_KIND_USER_BREAK: return "USER_BREAK";
3844 case EVENT_KIND_USER_LOG: return "USER_LOG";
3845 case EVENT_KIND_CRASH: return "CRASH";
3846 default:
3847 g_assert_not_reached ();
3848 return "";
3853 * process_event:
3855 * Send an event to the client, suspending the vm if needed.
3856 * LOCKING: Since this can suspend the calling thread, no locks should be held
3857 * by the caller.
3858 * The EVENTS list is freed by this function.
3860 static void
3861 process_event (EventKind event, gpointer arg, gint32 il_offset, MonoContext *ctx, GSList *events, int suspend_policy)
3863 Buffer buf;
3864 GSList *l;
3865 MonoDomain *domain = mono_domain_get ();
3866 MonoThread *thread = NULL;
3867 MonoObject *keepalive_obj = NULL;
3868 gboolean send_success = FALSE;
3869 static int ecount;
3870 int nevents;
3872 if (!inited) {
3873 DEBUG_PRINTF (2, "Debugger agent not initialized yet: dropping %s\n", event_to_string (event));
3874 return;
3877 if (!vm_start_event_sent && event != EVENT_KIND_VM_START) {
3878 // FIXME: We miss those events
3879 DEBUG_PRINTF (2, "VM start event not sent yet: dropping %s\n", event_to_string (event));
3880 return;
3883 if (vm_death_event_sent) {
3884 DEBUG_PRINTF (2, "VM death event has been sent: dropping %s\n", event_to_string (event));
3885 return;
3888 if (mono_runtime_is_shutting_down () && event != EVENT_KIND_VM_DEATH) {
3889 DEBUG_PRINTF (2, "Mono runtime is shutting down: dropping %s\n", event_to_string (event));
3890 return;
3893 if (disconnected) {
3894 DEBUG_PRINTF (2, "Debugger client is not connected: dropping %s\n", event_to_string (event));
3895 return;
3898 if (event == EVENT_KIND_KEEPALIVE)
3899 suspend_policy = SUSPEND_POLICY_NONE;
3900 else {
3901 if (events == NULL)
3902 return;
3904 if (agent_config.defer) {
3905 if (is_debugger_thread ()) {
3906 /* Don't suspend on events from the debugger thread */
3907 suspend_policy = SUSPEND_POLICY_NONE;
3909 } else {
3910 if (is_debugger_thread () && event != EVENT_KIND_VM_DEATH)
3911 // FIXME: Send these with a NULL thread, don't suspend the current thread
3912 return;
3916 if (event == EVENT_KIND_VM_START)
3917 suspend_policy = agent_config.suspend ? SUSPEND_POLICY_ALL : SUSPEND_POLICY_NONE;
3919 nevents = g_slist_length (events);
3920 buffer_init (&buf, 128);
3921 buffer_add_byte (&buf, suspend_policy);
3922 buffer_add_int (&buf, nevents);
3924 for (l = events; l; l = l->next) {
3925 buffer_add_byte (&buf, event); // event kind
3926 buffer_add_int (&buf, GPOINTER_TO_INT (l->data)); // request id
3928 ecount ++;
3930 if (event == EVENT_KIND_VM_DEATH) {
3931 thread = NULL;
3932 } else {
3933 if (!thread)
3934 thread = is_debugger_thread () ? mono_thread_get_main () : mono_thread_current ();
3936 if (event == EVENT_KIND_VM_START && arg != NULL)
3937 thread = (MonoThread *)arg;
3940 buffer_add_objid (&buf, (MonoObject*)thread); // thread
3942 switch (event) {
3943 case EVENT_KIND_THREAD_START:
3944 case EVENT_KIND_THREAD_DEATH:
3945 break;
3946 case EVENT_KIND_APPDOMAIN_CREATE:
3947 case EVENT_KIND_APPDOMAIN_UNLOAD:
3948 buffer_add_domainid (&buf, (MonoDomain *)arg);
3949 break;
3950 case EVENT_KIND_METHOD_ENTRY:
3951 case EVENT_KIND_METHOD_EXIT:
3952 buffer_add_methodid (&buf, domain, (MonoMethod *)arg);
3953 break;
3954 case EVENT_KIND_ASSEMBLY_LOAD:
3955 buffer_add_assemblyid (&buf, domain, (MonoAssembly *)arg);
3956 break;
3957 case EVENT_KIND_ASSEMBLY_UNLOAD: {
3958 DebuggerTlsData *tls;
3960 /* The domain the assembly belonged to is not equal to the current domain */
3961 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3962 g_assert (tls);
3963 g_assert (tls->domain_unloading);
3965 buffer_add_assemblyid (&buf, tls->domain_unloading, (MonoAssembly *)arg);
3966 break;
3968 case EVENT_KIND_TYPE_LOAD:
3969 buffer_add_typeid (&buf, domain, (MonoClass *)arg);
3970 break;
3971 case EVENT_KIND_BREAKPOINT:
3972 case EVENT_KIND_STEP: {
3973 DebuggerTlsData *tls;
3974 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
3975 g_assert (tls);
3976 mono_stopwatch_stop (&tls->step_time);
3977 MonoMethod *method = (MonoMethod *)arg;
3979 buffer_add_methodid (&buf, domain, method);
3980 buffer_add_long (&buf, il_offset);
3981 break;
3983 case EVENT_KIND_VM_START:
3984 buffer_add_domainid (&buf, mono_get_root_domain ());
3985 break;
3986 case EVENT_KIND_VM_DEATH:
3987 if (CHECK_PROTOCOL_VERSION (2, 27))
3988 buffer_add_int (&buf, mono_environment_exitcode_get ());
3989 break;
3990 case EVENT_KIND_CRASH: {
3991 EventInfo *ei = (EventInfo *)arg;
3992 buffer_add_long (&buf, ei->hashes->offset_free_hash);
3993 buffer_add_string (&buf, ei->dump);
3994 break;
3996 case EVENT_KIND_EXCEPTION: {
3997 EventInfo *ei = (EventInfo *)arg;
3998 buffer_add_objid (&buf, ei->exc);
4000 * We are not yet suspending, so get_objref () will not keep this object alive. So we need to do it
4001 * later after the suspension. (#12494).
4003 keepalive_obj = ei->exc;
4004 break;
4006 case EVENT_KIND_USER_BREAK: {
4007 DebuggerTlsData *tls;
4008 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4009 g_assert (tls);
4010 mono_stopwatch_stop (&tls->step_time);
4011 break;
4013 case EVENT_KIND_USER_LOG: {
4014 EventInfo *ei = (EventInfo *)arg;
4015 buffer_add_int (&buf, ei->level);
4016 buffer_add_string (&buf, ei->category ? ei->category : "");
4017 buffer_add_string (&buf, ei->message ? ei->message : "");
4018 break;
4020 case EVENT_KIND_KEEPALIVE:
4021 suspend_policy = SUSPEND_POLICY_NONE;
4022 break;
4023 default:
4024 g_assert_not_reached ();
4028 if (event == EVENT_KIND_VM_START) {
4029 if (!agent_config.defer) {
4030 ERROR_DECL (error);
4031 start_debugger_thread (error);
4032 mono_error_assert_ok (error);
4036 if (event == EVENT_KIND_VM_DEATH) {
4037 vm_death_event_sent = TRUE;
4038 suspend_policy = SUSPEND_POLICY_NONE;
4041 if (mono_runtime_is_shutting_down ())
4042 suspend_policy = SUSPEND_POLICY_NONE;
4044 if (suspend_policy != SUSPEND_POLICY_NONE) {
4046 * Save the thread context and start suspending before sending the packet,
4047 * since we could be receiving the resume request before send_packet ()
4048 * returns.
4050 save_thread_context (ctx);
4051 DebuggerTlsData *tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, mono_thread_internal_current ());
4052 tls->suspend_count++;
4053 suspend_vm ();
4055 if (keepalive_obj)
4056 /* This will keep this object alive */
4057 get_objref (keepalive_obj);
4060 send_success = send_packet (CMD_SET_EVENT, CMD_COMPOSITE, &buf);
4062 if (send_success) {
4063 DebuggerTlsData *tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4064 mono_debugger_log_event (tls, event_to_string (event), buf.buf, buffer_len (&buf));
4067 buffer_free (&buf);
4069 g_slist_free (events);
4070 events = NULL;
4072 if (!send_success) {
4073 DEBUG_PRINTF (2, "Sending command %s failed.\n", event_to_string (event));
4074 return;
4077 if (event == EVENT_KIND_VM_START) {
4078 vm_start_event_sent = TRUE;
4081 DEBUG_PRINTF (1, "[%p] Sent %d events %s(%d), suspend=%d.\n", (gpointer) (gsize) mono_native_thread_id_get (), nevents, event_to_string (event), ecount, suspend_policy);
4083 switch (suspend_policy) {
4084 case SUSPEND_POLICY_NONE:
4085 break;
4086 case SUSPEND_POLICY_ALL:
4087 suspend_current ();
4088 break;
4089 case SUSPEND_POLICY_EVENT_THREAD:
4090 NOT_IMPLEMENTED;
4091 break;
4092 default:
4093 g_assert_not_reached ();
4097 static void
4098 process_profiler_event (EventKind event, gpointer arg)
4100 int suspend_policy;
4101 GSList *events;
4102 EventInfo ei, *ei_arg = NULL;
4104 if (event == EVENT_KIND_TYPE_LOAD) {
4105 ei.klass = (MonoClass *)arg;
4106 ei_arg = &ei;
4109 mono_loader_lock ();
4110 events = create_event_list (event, NULL, NULL, ei_arg, &suspend_policy);
4111 mono_loader_unlock ();
4113 process_event (event, arg, 0, NULL, events, suspend_policy);
4116 static void
4117 runtime_initialized (MonoProfiler *prof)
4119 process_profiler_event (EVENT_KIND_VM_START, mono_thread_current ());
4120 if (agent_config.defer) {
4121 ERROR_DECL (error);
4122 start_debugger_thread (error);
4123 mono_error_assert_ok (error);
4127 static void
4128 runtime_shutdown (MonoProfiler *prof)
4130 process_profiler_event (EVENT_KIND_VM_DEATH, NULL);
4132 mono_debugger_agent_cleanup ();
4135 static void
4136 thread_startup (MonoProfiler *prof, uintptr_t tid)
4138 MonoInternalThread *thread = mono_thread_internal_current ();
4139 MonoInternalThread *old_thread;
4140 DebuggerTlsData *tls;
4142 if (is_debugger_thread ())
4143 return;
4145 g_assert (mono_native_thread_id_equals (MONO_UINT_TO_NATIVE_THREAD_ID (tid), MONO_UINT_TO_NATIVE_THREAD_ID (thread->tid)));
4147 mono_loader_lock ();
4148 old_thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
4149 mono_loader_unlock ();
4150 if (old_thread) {
4151 if (thread == old_thread) {
4153 * For some reason, thread_startup () might be called for the same thread
4154 * multiple times (attach ?).
4156 DEBUG_PRINTF (1, "[%p] thread_start () called multiple times for %p, ignored.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
4157 return;
4158 } else {
4160 * thread_end () might not be called for some threads, and the tid could
4161 * get reused.
4163 DEBUG_PRINTF (1, "[%p] Removing stale data for tid %p.\n", GUINT_TO_POINTER (tid), GUINT_TO_POINTER (tid));
4164 mono_loader_lock ();
4165 mono_g_hash_table_remove (thread_to_tls, old_thread);
4166 mono_g_hash_table_remove (tid_to_thread, GUINT_TO_POINTER (tid));
4167 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
4168 mono_loader_unlock ();
4172 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4173 g_assert (!tls);
4174 // FIXME: Free this somewhere
4175 tls = g_new0 (DebuggerTlsData, 1);
4176 MONO_GC_REGISTER_ROOT_SINGLE (tls->thread, MONO_ROOT_SOURCE_DEBUGGER, NULL, "Debugger Thread Reference");
4177 tls->thread = thread;
4178 // Do so we have thread id even after termination
4179 tls->thread_id = (intptr_t) thread->tid;
4180 mono_native_tls_set_value (debugger_tls_id, tls);
4182 DEBUG_PRINTF (1, "[%p] Thread started, obj=%p, tls=%p.\n", (gpointer)tid, thread, tls);
4184 mono_loader_lock ();
4185 mono_g_hash_table_insert_internal (thread_to_tls, thread, tls);
4186 mono_g_hash_table_insert_internal (tid_to_thread, (gpointer)tid, thread);
4187 mono_g_hash_table_insert_internal (tid_to_thread_obj, GUINT_TO_POINTER (tid), mono_thread_current ());
4188 mono_loader_unlock ();
4190 process_profiler_event (EVENT_KIND_THREAD_START, thread);
4193 * suspend_vm () could have missed this thread, so wait for a resume.
4196 suspend_current ();
4199 static void
4200 thread_end (MonoProfiler *prof, uintptr_t tid)
4202 MonoInternalThread *thread;
4203 DebuggerTlsData *tls = NULL;
4205 mono_loader_lock ();
4206 thread = (MonoInternalThread *)mono_g_hash_table_lookup (tid_to_thread, GUINT_TO_POINTER (tid));
4207 if (thread) {
4208 mono_g_hash_table_remove (tid_to_thread_obj, GUINT_TO_POINTER (tid));
4209 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
4210 if (tls) {
4211 /* FIXME: Maybe we need to free this instead, but some code can't handle that */
4212 tls->terminated = TRUE;
4213 /* Can't remove from tid_to_thread, as that would defeat the check in thread_start () */
4214 MONO_GC_UNREGISTER_ROOT (tls->thread);
4215 tls->thread = NULL;
4218 mono_loader_unlock ();
4220 /* We might be called for threads started before we registered the start callback */
4221 if (thread) {
4222 DEBUG_PRINTF (1, "[%p] Thread terminated, obj=%p, tls=%p (domain=%p).\n", (gpointer)tid, thread, tls, (gpointer)mono_domain_get ());
4224 if (mono_thread_internal_is_current (thread) &&
4225 (!mono_native_tls_get_value (debugger_tls_id) ||
4226 !mono_domain_get ())
4229 * This can happen on darwin and android since we
4230 * deregister threads using pthread dtors.
4231 * process_profiler_event () and the code it calls
4232 * cannot handle a null TLS value.
4234 return;
4237 process_profiler_event (EVENT_KIND_THREAD_DEATH, thread);
4241 static void
4242 appdomain_load (MonoProfiler *prof, MonoDomain *domain)
4244 mono_de_domain_add (domain);
4246 process_profiler_event (EVENT_KIND_APPDOMAIN_CREATE, domain);
4249 static void
4250 appdomain_start_unload (MonoProfiler *prof, MonoDomain *domain)
4252 DebuggerTlsData *tls;
4254 /* This might be called during shutdown on the debugger thread from the CMD_VM_EXIT code */
4255 if (is_debugger_thread ())
4256 return;
4259 * Remember the currently unloading appdomain as it is needed to generate
4260 * proper ids for unloading assemblies.
4262 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4263 g_assert (tls);
4264 tls->domain_unloading = domain;
4267 static void
4268 appdomain_unload (MonoProfiler *prof, MonoDomain *domain)
4270 DebuggerTlsData *tls;
4272 if (is_debugger_thread ())
4273 return;
4275 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4276 g_assert (tls);
4277 tls->domain_unloading = NULL;
4279 mono_de_clear_breakpoints_for_domain (domain);
4281 mono_loader_lock ();
4282 /* Invalidate each thread's frame stack */
4283 mono_g_hash_table_foreach (thread_to_tls, invalidate_each_thread, NULL);
4284 mono_loader_unlock ();
4286 process_profiler_event (EVENT_KIND_APPDOMAIN_UNLOAD, domain);
4290 * invalidate_each_thread:
4292 * A GHFunc to invalidate frames.
4293 * value must be a DebuggerTlsData*
4295 static void
4296 invalidate_each_thread (gpointer key, gpointer value, gpointer user_data)
4298 invalidate_frames ((DebuggerTlsData *)value);
4301 static void
4302 assembly_load (MonoProfiler *prof, MonoAssembly *assembly)
4304 /* Sent later in jit_end () */
4305 dbg_lock ();
4306 g_ptr_array_add (pending_assembly_loads, assembly);
4307 dbg_unlock ();
4310 static void
4311 assembly_unload (MonoProfiler *prof, MonoAssembly *assembly)
4313 if (is_debugger_thread ())
4314 return;
4316 process_profiler_event (EVENT_KIND_ASSEMBLY_UNLOAD, assembly);
4318 clear_event_requests_for_assembly (assembly);
4319 clear_types_for_assembly (assembly);
4322 static void
4323 send_type_load (MonoClass *klass)
4325 gboolean type_load = FALSE;
4326 MonoDomain *domain = mono_domain_get ();
4327 AgentDomainInfo *info = NULL;
4329 info = get_agent_domain_info (domain);
4331 mono_loader_lock ();
4333 if (!g_hash_table_lookup (info->loaded_classes, klass)) {
4334 type_load = TRUE;
4335 g_hash_table_insert (info->loaded_classes, klass, klass);
4338 mono_loader_unlock ();
4340 if (type_load)
4341 emit_type_load (klass, klass, NULL);
4345 * Emit load events for all types currently loaded in the domain.
4346 * Takes the loader and domain locks.
4347 * user_data is unused.
4349 static void
4350 send_types_for_domain (MonoDomain *domain, void *user_data)
4352 MonoDomain* old_domain;
4353 AgentDomainInfo *info = NULL;
4355 if (mono_domain_is_unloading (domain))
4356 return;
4358 info = get_agent_domain_info (domain);
4359 g_assert (info);
4361 old_domain = mono_domain_get ();
4363 mono_domain_set_fast (domain, TRUE);
4365 mono_loader_lock ();
4366 g_hash_table_foreach (info->loaded_classes, emit_type_load, NULL);
4367 mono_loader_unlock ();
4369 mono_domain_set_fast (old_domain, TRUE);
4372 static void
4373 send_assemblies_for_domain (MonoDomain *domain, void *user_data)
4375 GSList *tmp;
4376 MonoDomain* old_domain;
4378 if (mono_domain_is_unloading (domain))
4379 return;
4381 old_domain = mono_domain_get ();
4383 mono_domain_set_fast (domain, TRUE);
4385 mono_domain_assemblies_lock (domain);
4386 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
4387 MonoAssembly* ass = (MonoAssembly *)tmp->data;
4388 emit_assembly_load (ass, NULL);
4390 mono_domain_assemblies_unlock (domain);
4392 mono_domain_set_fast (old_domain, TRUE);
4395 static void
4396 jit_done (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo)
4398 jit_end (prof, method, jinfo);
4401 static void
4402 jit_failed (MonoProfiler *prof, MonoMethod *method)
4404 jit_end (prof, method, NULL);
4407 static void
4408 jit_end (MonoProfiler *prof, MonoMethod *method, MonoJitInfo *jinfo)
4411 * We emit type load events when the first method of the type is JITted,
4412 * since the class load profiler callbacks might be called with the
4413 * loader lock held. They could also occur in the debugger thread.
4414 * Same for assembly load events.
4416 while (TRUE) {
4417 MonoAssembly *assembly = NULL;
4419 // FIXME: Maybe store this in TLS so the thread of the event is correct ?
4420 dbg_lock ();
4421 if (pending_assembly_loads->len > 0) {
4422 assembly = (MonoAssembly *)g_ptr_array_index (pending_assembly_loads, 0);
4423 g_ptr_array_remove_index (pending_assembly_loads, 0);
4425 dbg_unlock ();
4427 if (assembly) {
4428 process_profiler_event (EVENT_KIND_ASSEMBLY_LOAD, assembly);
4429 } else {
4430 break;
4434 send_type_load (method->klass);
4436 if (jinfo)
4437 mono_de_add_pending_breakpoints (method, jinfo);
4441 * SINGLE STEPPING
4444 static void
4445 event_requests_cleanup (void)
4447 mono_loader_lock ();
4448 int i = 0;
4449 while (i < event_requests->len) {
4450 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
4452 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
4453 mono_de_clear_breakpoint ((MonoBreakpoint *)req->info);
4454 g_ptr_array_remove_index_fast (event_requests, i);
4455 g_free (req);
4456 } else {
4457 i ++;
4460 mono_loader_unlock ();
4464 * ss_calculate_framecount:
4466 * Ensure DebuggerTlsData fields are filled out.
4468 static void
4469 ss_calculate_framecount (void *the_tls, MonoContext *ctx, gboolean force_use_ctx, DbgEngineStackFrame ***frames, int *nframes)
4471 DebuggerTlsData *tls = (DebuggerTlsData*)the_tls;
4473 if (force_use_ctx || !tls->context.valid)
4474 mono_thread_state_init_from_monoctx (&tls->context, ctx);
4475 compute_frame_info (tls->thread, tls, FALSE);
4476 if (frames)
4477 *frames = (DbgEngineStackFrame**)tls->frames;
4478 if (nframes)
4479 *nframes = tls->frame_count;
4483 * ss_discard_frame_data:
4485 * Discard frame data and invalidate any context
4487 static void
4488 ss_discard_frame_context (void *the_tls)
4490 DebuggerTlsData *tls = (DebuggerTlsData*)the_tls;
4491 tls->context.valid = FALSE;
4492 tls->async_state.valid = FALSE;
4493 invalidate_frames (tls);
4496 static MonoContext*
4497 tls_get_restore_state (void *the_tls)
4499 DebuggerTlsData *tls = (DebuggerTlsData*)the_tls;
4501 return &tls->restore_state.ctx;
4504 static gboolean
4505 ensure_jit (DbgEngineStackFrame* the_frame)
4507 StackFrame *frame = (StackFrame*)the_frame;
4508 if (!frame->jit) {
4509 frame->jit = mono_debug_find_method (frame->api_method, frame->de.domain);
4510 if (!frame->jit && frame->api_method->is_inflated)
4511 frame->jit = mono_debug_find_method(mono_method_get_declaring_generic_method (frame->api_method), frame->de.domain);
4512 if (!frame->jit) {
4513 char *s;
4515 /* This could happen for aot images with no jit debug info */
4516 s = mono_method_full_name (frame->api_method, TRUE);
4517 DEBUG_PRINTF(1, "[dbg] No debug information found for '%s'.\n", s);
4518 g_free (s);
4519 return FALSE;
4522 return TRUE;
4525 static gboolean
4526 breakpoint_matches_assembly (MonoBreakpoint *bp, MonoAssembly *assembly)
4528 return bp->method && m_class_get_image (bp->method->klass)->assembly == assembly;
4531 static gpointer
4532 get_this_addr (DbgEngineStackFrame *the_frame)
4534 StackFrame *frame = (StackFrame *)the_frame;
4535 if (frame->de.ji->is_interp)
4536 return mini_get_interp_callbacks ()->frame_get_this (frame->interp_frame);
4538 MonoDebugVarInfo *var = frame->jit->this_var;
4539 if ((var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS) != MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET)
4540 return NULL;
4542 guint8 *addr = (guint8 *)mono_arch_context_get_int_reg (&frame->ctx, var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS);
4543 addr += (gint32)var->offset;
4544 return addr;
4547 static MonoMethod*
4548 get_set_notification_method (MonoClass* async_builder_class)
4550 ERROR_DECL (error);
4551 GPtrArray* array = mono_class_get_methods_by_name (async_builder_class, "SetNotificationForWaitCompletion", 0x24, 1, FALSE, error);
4552 mono_error_assert_ok (error);
4553 if (array->len == 0) {
4554 g_ptr_array_free (array, TRUE);
4555 return NULL;
4557 MonoMethod* set_notification_method = (MonoMethod *)g_ptr_array_index (array, 0);
4558 g_ptr_array_free (array, TRUE);
4559 return set_notification_method;
4562 static MonoMethod*
4563 get_object_id_for_debugger_method (MonoClass* async_builder_class)
4565 ERROR_DECL (error);
4566 GPtrArray *array = mono_class_get_methods_by_name (async_builder_class, "get_ObjectIdForDebugger", 0x24, 1, FALSE, error);
4567 mono_error_assert_ok (error);
4568 g_assert (array->len == 1);
4569 MonoMethod *method = (MonoMethod *)g_ptr_array_index (array, 0);
4570 g_ptr_array_free (array, TRUE);
4571 return method;
4574 static MonoClass *
4575 get_class_to_get_builder_field(DbgEngineStackFrame *frame)
4577 ERROR_DECL (error);
4578 gpointer this_addr = get_this_addr (frame);
4579 MonoClass *original_class = frame->method->klass;
4580 MonoClass *ret;
4581 if (!m_class_is_valuetype (original_class) && mono_class_is_open_constructed_type (m_class_get_byval_arg (original_class))) {
4582 MonoObject *this_obj = *(MonoObject**)this_addr;
4583 MonoGenericContext context;
4584 MonoType *inflated_type;
4586 g_assert (this_obj);
4587 context = mono_get_generic_context_from_stack_frame (frame->ji, this_obj->vtable);
4588 inflated_type = mono_class_inflate_generic_type_checked (m_class_get_byval_arg (original_class), &context, error);
4589 mono_error_assert_ok (error); /* FIXME don't swallow the error */
4591 ret = mono_class_from_mono_type_internal (inflated_type);
4592 mono_metadata_free_type (inflated_type);
4593 return ret;
4595 return original_class;
4599 /* Return the address of the AsyncMethodBuilder struct belonging to the state machine method pointed to by FRAME */
4600 static gpointer
4601 get_async_method_builder (DbgEngineStackFrame *frame)
4603 MonoObject *this_obj;
4604 MonoClassField *builder_field;
4605 gpointer builder;
4606 gpointer this_addr;
4607 MonoClass* klass = frame->method->klass;
4609 klass = get_class_to_get_builder_field(frame);
4610 builder_field = mono_class_get_field_from_name_full (klass, "<>t__builder", NULL);
4611 g_assert (builder_field);
4613 this_addr = get_this_addr (frame);
4614 if (!this_addr)
4615 return NULL;
4617 if (m_class_is_valuetype (klass)) {
4618 builder = mono_vtype_get_field_addr (*(guint8**)this_addr, builder_field);
4619 } else {
4620 this_obj = *(MonoObject**)this_addr;
4621 builder = (char*)this_obj + builder_field->offset;
4624 return builder;
4627 //This ID is used to figure out if breakpoint hit on resumeOffset belongs to us or not
4628 //since thread probably changed...
4629 static int
4630 get_this_async_id (DbgEngineStackFrame *frame)
4632 MonoClassField *builder_field;
4633 gpointer builder;
4634 MonoMethod *method;
4635 MonoObject *ex;
4636 ERROR_DECL (error);
4637 MonoObject *obj;
4638 gboolean old_disable_breakpoints = FALSE;
4639 DebuggerTlsData *tls;
4642 * FRAME points to a method in a state machine class/struct.
4643 * Call the ObjectIdForDebugger method of the associated method builder type.
4645 builder = get_async_method_builder (frame);
4646 if (!builder)
4647 return 0;
4649 builder_field = mono_class_get_field_from_name_full (get_class_to_get_builder_field(frame), "<>t__builder", NULL);
4650 g_assert (builder_field);
4652 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4653 if (tls) {
4654 old_disable_breakpoints = tls->disable_breakpoints;
4655 tls->disable_breakpoints = TRUE;
4658 method = get_object_id_for_debugger_method (mono_class_from_mono_type_internal (builder_field->type));
4659 obj = mono_runtime_try_invoke (method, builder, NULL, &ex, error);
4660 mono_error_assert_ok (error);
4662 if (tls)
4663 tls->disable_breakpoints = old_disable_breakpoints;
4665 return get_objid (obj);
4668 // Returns true if TaskBuilder has NotifyDebuggerOfWaitCompletion method
4669 // false if not(AsyncVoidBuilder)
4670 static gboolean
4671 set_set_notification_for_wait_completion_flag (DbgEngineStackFrame *frame)
4673 MonoClassField *builder_field = mono_class_get_field_from_name_full (get_class_to_get_builder_field(frame), "<>t__builder", NULL);
4674 g_assert (builder_field);
4675 gpointer builder = get_async_method_builder (frame);
4676 g_assert (builder);
4678 MonoMethod* method = get_set_notification_method (mono_class_from_mono_type_internal (builder_field->type));
4679 if (method == NULL)
4680 return FALSE;
4681 gboolean arg = TRUE;
4682 ERROR_DECL (error);
4683 void *args [ ] = { &arg };
4684 mono_runtime_invoke_checked (method, builder, args, error);
4685 mono_error_assert_ok (error);
4686 return TRUE;
4689 static MonoMethod* notify_debugger_of_wait_completion_method_cache;
4691 static MonoMethod*
4692 get_notify_debugger_of_wait_completion_method (void)
4694 if (notify_debugger_of_wait_completion_method_cache != NULL)
4695 return notify_debugger_of_wait_completion_method_cache;
4696 ERROR_DECL (error);
4697 MonoClass* task_class = mono_class_load_from_name (mono_defaults.corlib, "System.Threading.Tasks", "Task");
4698 GPtrArray* array = mono_class_get_methods_by_name (task_class, "NotifyDebuggerOfWaitCompletion", 0x24, 1, FALSE, error);
4699 mono_error_assert_ok (error);
4700 g_assert (array->len == 1);
4701 notify_debugger_of_wait_completion_method_cache = (MonoMethod *)g_ptr_array_index (array, 0);
4702 g_ptr_array_free (array, TRUE);
4703 return notify_debugger_of_wait_completion_method_cache;
4706 static gboolean
4707 begin_breakpoint_processing (void *the_tls, MonoContext *ctx, MonoJitInfo *ji, gboolean from_signal)
4709 DebuggerTlsData *tls = (DebuggerTlsData*)the_tls;
4712 * Skip the instruction causing the breakpoint signal.
4714 if (from_signal)
4715 mono_arch_skip_breakpoint (ctx, ji);
4717 if (tls->disable_breakpoints)
4718 return FALSE;
4719 return TRUE;
4722 typedef struct {
4723 GSList *bp_events, *ss_events, *enter_leave_events;
4724 EventKind kind;
4725 int suspend_policy;
4726 } BreakPointEvents;
4728 static void*
4729 create_breakpoint_events (GPtrArray *ss_reqs, GPtrArray *bp_reqs, MonoJitInfo *ji, EventKind kind)
4731 int suspend_policy = 0;
4732 BreakPointEvents *evts = g_new0 (BreakPointEvents, 1);
4733 if (ss_reqs && ss_reqs->len > 0)
4734 evts->ss_events = create_event_list (EVENT_KIND_STEP, ss_reqs, ji, NULL, &suspend_policy);
4735 else if (bp_reqs && bp_reqs->len > 0)
4736 evts->bp_events = create_event_list (EVENT_KIND_BREAKPOINT, bp_reqs, ji, NULL, &suspend_policy);
4737 else if (kind != EVENT_KIND_BREAKPOINT)
4738 evts->enter_leave_events = create_event_list (kind, NULL, ji, NULL, &suspend_policy);
4740 evts->kind = kind;
4741 evts->suspend_policy = suspend_policy;
4742 return evts;
4745 static void
4746 process_breakpoint_events (void *_evts, MonoMethod *method, MonoContext *ctx, int il_offset)
4748 BreakPointEvents *evts = (BreakPointEvents*)_evts;
4750 * FIXME: The first event will suspend, so the second will only be sent after the
4751 * resume.
4753 if (evts->ss_events)
4754 process_event (EVENT_KIND_STEP, method, il_offset, ctx, evts->ss_events, evts->suspend_policy);
4755 if (evts->bp_events)
4756 process_event (evts->kind, method, il_offset, ctx, evts->bp_events, evts->suspend_policy);
4757 if (evts->enter_leave_events)
4758 process_event (evts->kind, method, il_offset, ctx, evts->enter_leave_events, evts->suspend_policy);
4760 g_free (evts);
4763 /* Process a breakpoint/single step event after resuming from a signal handler */
4764 static void
4765 process_signal_event (void (*func) (void*, gboolean))
4767 DebuggerTlsData *tls;
4768 MonoThreadUnwindState orig_restore_state;
4769 MonoContext ctx;
4771 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4772 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4773 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4774 mono_thread_state_init_from_monoctx (&tls->restore_state, &tls->handler_ctx);
4776 func (tls, TRUE);
4778 /* This is called when resuming from a signal handler, so it shouldn't return */
4779 memcpy (&ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4780 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4781 mono_restore_context (&ctx);
4782 g_assert_not_reached ();
4785 static void
4786 process_breakpoint_from_signal (void)
4788 process_signal_event (mono_de_process_breakpoint);
4791 static void
4792 resume_from_signal_handler (void *sigctx, void *func)
4794 DebuggerTlsData *tls;
4795 MonoContext ctx;
4797 /* Save the original context in TLS */
4798 // FIXME: This might not work on an altstack ?
4799 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4800 if (!tls)
4801 g_printerr ("Thread %p is not attached to the JIT.\n", (gpointer) (gsize) mono_native_thread_id_get ());
4802 g_assert (tls);
4804 // FIXME: MonoContext usually doesn't include the fp registers, so these are
4805 // clobbered by a single step/breakpoint event. If this turns out to be a problem,
4806 // clob:c could be added to op_seq_point.
4808 mono_sigctx_to_monoctx (sigctx, &ctx);
4809 memcpy (&tls->handler_ctx, &ctx, sizeof (MonoContext));
4810 #ifdef MONO_ARCH_HAVE_SETUP_RESUME_FROM_SIGNAL_HANDLER_CTX
4811 mono_arch_setup_resume_sighandler_ctx (&ctx, func);
4812 #else
4813 MONO_CONTEXT_SET_IP (&ctx, func);
4814 #endif
4815 mono_monoctx_to_sigctx (&ctx, sigctx);
4818 static void
4819 debugger_agent_breakpoint_hit (void *sigctx)
4822 * We are called from a signal handler, and running code there causes all kinds of
4823 * problems, like the original signal is disabled, libgc can't handle altstack, etc.
4824 * So set up the signal context to return to the real breakpoint handler function.
4826 resume_from_signal_handler (sigctx, (gpointer)process_breakpoint_from_signal);
4829 typedef struct {
4830 gboolean found;
4831 MonoContext *ctx;
4832 } UserBreakCbData;
4834 static gboolean
4835 user_break_cb (StackFrameInfo *frame, MonoContext *ctx, gpointer user_data)
4837 UserBreakCbData *data = (UserBreakCbData*)user_data;
4839 if (frame->type == FRAME_TYPE_INTERP_TO_MANAGED || frame->type == FRAME_TYPE_INTERP_TO_MANAGED_WITH_CTX) {
4840 data->found = TRUE;
4841 return TRUE;
4843 if (frame->managed) {
4844 data->found = TRUE;
4845 *data->ctx = *ctx;
4847 return TRUE;
4849 return FALSE;
4853 * Called by System.Diagnostics.Debugger:Break ().
4855 static void
4856 debugger_agent_user_break (void)
4858 if (agent_config.enabled) {
4859 MonoContext ctx;
4860 int suspend_policy;
4861 GSList *events;
4862 UserBreakCbData data;
4864 memset (&data, 0, sizeof (data));
4865 data.ctx = &ctx;
4867 /* Obtain a context */
4868 MONO_CONTEXT_SET_IP (&ctx, NULL);
4869 mono_walk_stack_with_ctx (user_break_cb, NULL, (MonoUnwindOptions)0, &data);
4870 g_assert (data.found);
4872 mono_loader_lock ();
4873 events = create_event_list (EVENT_KIND_USER_BREAK, NULL, NULL, NULL, &suspend_policy);
4874 mono_loader_unlock ();
4876 process_event (EVENT_KIND_USER_BREAK, NULL, 0, &ctx, events, suspend_policy);
4877 } else if (mini_debug_options.native_debugger_break) {
4878 G_BREAKPOINT ();
4882 static void
4883 begin_single_step_processing (MonoContext *ctx, gboolean from_signal)
4885 if (from_signal)
4886 mono_arch_skip_single_step (ctx);
4889 static void
4890 process_single_step (void)
4892 process_signal_event (mono_de_process_single_step);
4896 * debugger_agent_single_step_event:
4898 * Called from a signal handler to handle a single step event.
4900 static void
4901 debugger_agent_single_step_event (void *sigctx)
4903 /* Resume to process_single_step through the signal context */
4905 // FIXME: Since step out/over is implemented using step in, the step in case should
4906 // be as fast as possible. Move the relevant code from mono_de_process_single_step ()
4907 // here
4909 if (is_debugger_thread ()) {
4911 * This could happen despite our best effors when the runtime calls
4912 * assembly/type resolve hooks.
4913 * FIXME: Breakpoints too.
4915 MonoContext ctx;
4917 mono_sigctx_to_monoctx (sigctx, &ctx);
4918 mono_arch_skip_single_step (&ctx);
4919 mono_monoctx_to_sigctx (&ctx, sigctx);
4920 return;
4923 resume_from_signal_handler (sigctx, (gpointer)process_single_step);
4926 static void
4927 debugger_agent_single_step_from_context (MonoContext *ctx)
4929 DebuggerTlsData *tls;
4930 MonoThreadUnwindState orig_restore_state;
4932 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4933 /* Fastpath during invokes, see in process_suspend () */
4934 if (tls && suspend_count && suspend_count - tls->resume_count == 0)
4935 return;
4937 if (is_debugger_thread ())
4938 return;
4940 g_assert (tls);
4942 tls->terminated = FALSE;
4944 /* Have to save/restore the restore_ctx as we can be called recursively during invokes etc. */
4945 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4946 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
4947 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
4949 mono_de_process_single_step (tls, FALSE);
4951 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4952 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4955 static void
4956 debugger_agent_breakpoint_from_context (MonoContext *ctx)
4958 DebuggerTlsData *tls;
4959 MonoThreadUnwindState orig_restore_state;
4960 guint8 *orig_ip;
4962 if (is_debugger_thread ())
4963 return;
4965 orig_ip = (guint8 *)MONO_CONTEXT_GET_IP (ctx);
4966 MONO_CONTEXT_SET_IP (ctx, orig_ip - 1);
4968 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
4969 g_assert (tls);
4971 //if a thread was suspended and doesn't have any managed stack, it was considered as terminated,
4972 //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
4973 tls->terminated = FALSE;
4975 memcpy (&orig_restore_state, &tls->restore_state, sizeof (MonoThreadUnwindState));
4976 mono_thread_state_init_from_monoctx (&tls->restore_state, ctx);
4977 memcpy (&tls->handler_ctx, ctx, sizeof (MonoContext));
4979 mono_de_process_breakpoint (tls, FALSE);
4981 memcpy (ctx, &tls->restore_state.ctx, sizeof (MonoContext));
4982 memcpy (&tls->restore_state, &orig_restore_state, sizeof (MonoThreadUnwindState));
4983 if (MONO_CONTEXT_GET_IP (ctx) == orig_ip - 1)
4984 MONO_CONTEXT_SET_IP (ctx, orig_ip);
4986 static void
4987 ss_args_destroy (SingleStepArgs *ss_args)
4989 if (ss_args->frames)
4990 free_frames ((StackFrame**)ss_args->frames, ss_args->nframes);
4993 static int
4994 handle_multiple_ss_requests (void)
4996 if (!CHECK_PROTOCOL_VERSION (2, 57))
4997 return DE_ERR_NOT_IMPLEMENTED;
4998 return 1;
5001 static int
5002 ensure_runtime_is_suspended (void)
5004 if (suspend_count == 0)
5005 return ERR_NOT_SUSPENDED;
5007 wait_for_suspend ();
5009 return ERR_NONE;
5012 static int
5013 ss_create_init_args (SingleStepReq *ss_req, SingleStepArgs *args)
5015 MonoSeqPointInfo *info = NULL;
5016 gboolean found_sp;
5017 MonoMethod *method = NULL;
5018 MonoDebugMethodInfo *minfo;
5019 gboolean step_to_catch = FALSE;
5020 gboolean set_ip = FALSE;
5021 StackFrame **frames = NULL;
5022 int nframes = 0;
5024 mono_loader_lock ();
5025 DebuggerTlsData *tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, ss_req->thread);
5026 mono_loader_unlock ();
5027 g_assert (tls);
5028 if (!tls->context.valid) {
5029 DEBUG_PRINTF (1, "Received a single step request on a thread with no managed frames.");
5030 return ERR_INVALID_ARGUMENT;
5033 if (tls->restore_state.valid && MONO_CONTEXT_GET_IP (&tls->context.ctx) != MONO_CONTEXT_GET_IP (&tls->restore_state.ctx)) {
5035 * Need to start single stepping from restore_state and not from the current state
5037 set_ip = TRUE;
5038 frames = compute_frame_info_from (ss_req->thread, tls, &tls->restore_state, &nframes);
5041 ss_req->start_sp = ss_req->last_sp = MONO_CONTEXT_GET_SP (&tls->context.ctx);
5043 if (tls->has_catch_frame) {
5044 StackFrameInfo frame;
5047 * We are stopped at a throw site. Stepping should go to the catch site.
5049 frame = tls->catch_frame;
5050 g_assert (frame.type == FRAME_TYPE_MANAGED || frame.type == FRAME_TYPE_INTERP);
5053 * Find the seq point corresponding to the landing site ip, which is the first seq
5054 * point after ip.
5056 found_sp = mono_find_next_seq_point_for_native_offset (frame.domain, frame.method, frame.native_offset, &info, &args->sp);
5057 if (!found_sp)
5058 no_seq_points_found (frame.method, frame.native_offset);
5059 g_assert (found_sp);
5061 method = frame.method;
5063 step_to_catch = TRUE;
5064 /* This make sure the seq point is not skipped by process_single_step () */
5065 ss_req->last_sp = NULL;
5068 if (!step_to_catch) {
5069 StackFrame *frame = NULL;
5071 if (set_ip) {
5072 if (frames && nframes)
5073 frame = frames [0];
5074 } else {
5075 compute_frame_info (ss_req->thread, tls, FALSE);
5077 if (tls->frame_count)
5078 frame = tls->frames [0];
5081 if (ss_req->size == STEP_SIZE_LINE) {
5082 if (frame) {
5083 ss_req->last_method = frame->de.method;
5084 ss_req->last_line = -1;
5086 minfo = mono_debug_lookup_method (frame->de.method);
5087 if (minfo && frame->il_offset != -1) {
5088 MonoDebugSourceLocation *loc = mono_debug_method_lookup_location (minfo, frame->il_offset);
5090 if (loc) {
5091 ss_req->last_line = loc->row;
5092 g_free (loc);
5098 if (frame) {
5099 if (!method && frame->il_offset != -1) {
5100 /* FIXME: Sort the table and use a binary search */
5101 found_sp = mono_find_prev_seq_point_for_native_offset (frame->de.domain, frame->de.method, frame->de.native_offset, &info, &args->sp);
5102 if (!found_sp)
5103 no_seq_points_found (frame->de.method, frame->de.native_offset);
5104 g_assert (found_sp);
5105 method = frame->de.method;
5110 ss_req->start_method = method;
5112 args->method = method;
5113 args->ctx = set_ip ? &tls->restore_state.ctx : &tls->context.ctx;
5114 args->tls = tls;
5115 args->step_to_catch = step_to_catch;
5116 args->info = info;
5117 args->frames = (DbgEngineStackFrame**)frames;
5118 args->nframes = nframes;
5120 return ERR_NONE;
5123 static void
5124 ss_clear_for_assembly (SingleStepReq *req, MonoAssembly *assembly)
5126 GSList *l;
5127 gboolean found = TRUE;
5129 while (found) {
5130 found = FALSE;
5131 for (l = req->bps; l; l = l->next) {
5132 if (breakpoint_matches_assembly ((MonoBreakpoint *)l->data, assembly)) {
5133 mono_de_clear_breakpoint ((MonoBreakpoint *)l->data);
5134 req->bps = g_slist_delete_link (req->bps, l);
5135 found = TRUE;
5136 break;
5143 * This takes a lot of locks and stuff. Do this at the end, after
5144 * other things have dumped us, so that getting stuck here won't
5145 * prevent seeing other crash information
5147 static void
5148 mono_debugger_agent_send_crash (char *json_dump, MonoStackHash *hashes, int pause)
5150 #ifndef DISABLE_CRASH_REPORTING
5151 int suspend_policy;
5152 GSList *events;
5153 EventInfo ei;
5155 if (!agent_config.enabled)
5156 return;
5158 // Don't send the event if the client doesn't expect it
5159 if (!CHECK_PROTOCOL_VERSION (2, 49))
5160 return;
5162 // It doesn't make sense to wait for lldb/gdb to finish if we're not
5163 // actually enabled. Therefore we do the wait here.
5164 sleep (pause);
5166 // Don't heap allocate when we can avoid it
5167 EventRequest request;
5168 memset (&request, 0, sizeof (request));
5169 request.event_kind = EVENT_KIND_CRASH;
5171 gpointer pdata [1];
5172 pdata [0] = &request;
5173 GPtrArray array;
5174 memset (&array, 0, sizeof (array));
5175 array.pdata = pdata;
5176 array.len = 1;
5178 mono_loader_lock ();
5179 events = create_event_list (EVENT_KIND_CRASH, &array, NULL, NULL, &suspend_policy);
5180 mono_loader_unlock ();
5182 ei.dump = json_dump;
5183 ei.hashes = hashes;
5185 g_assert (events != NULL);
5187 process_event (EVENT_KIND_CRASH, &ei, 0, NULL, events, suspend_policy);
5189 // Don't die before it is sent.
5190 sleep (4);
5191 #endif
5195 * Called from metadata by the icall for System.Diagnostics.Debugger:Log ().
5197 static void
5198 debugger_agent_debug_log (int level, MonoString *category, MonoString *message)
5200 ERROR_DECL (error);
5201 int suspend_policy;
5202 GSList *events;
5203 EventInfo ei;
5205 if (!agent_config.enabled)
5206 return;
5208 memset (&ei, 0, sizeof (ei));
5210 mono_loader_lock ();
5211 events = create_event_list (EVENT_KIND_USER_LOG, NULL, NULL, NULL, &suspend_policy);
5212 mono_loader_unlock ();
5214 ei.level = level;
5215 if (category) {
5216 ei.category = mono_string_to_utf8_checked_internal (category, error);
5217 mono_error_cleanup (error);
5218 error_init (error);
5220 if (message) {
5221 ei.message = mono_string_to_utf8_checked_internal (message, error);
5222 mono_error_cleanup (error);
5225 process_event (EVENT_KIND_USER_LOG, &ei, 0, NULL, events, suspend_policy);
5227 g_free (ei.category);
5228 g_free (ei.message);
5231 static gboolean
5232 debugger_agent_debug_log_is_enabled (void)
5234 /* Treat this as true even if there is no event request for EVENT_KIND_USER_LOG */
5235 return agent_config.enabled;
5238 static void
5239 debugger_agent_unhandled_exception (MonoException *exc)
5241 int suspend_policy;
5242 GSList *events;
5243 EventInfo ei;
5245 if (!inited)
5246 return;
5248 memset (&ei, 0, sizeof (ei));
5249 ei.exc = (MonoObject*)exc;
5251 mono_loader_lock ();
5252 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, NULL, &ei, &suspend_policy);
5253 mono_loader_unlock ();
5255 process_event (EVENT_KIND_EXCEPTION, &ei, 0, NULL, events, suspend_policy);
5258 static void
5259 debugger_agent_handle_exception (MonoException *exc, MonoContext *throw_ctx,
5260 MonoContext *catch_ctx, StackFrameInfo *catch_frame)
5262 if (catch_ctx == NULL && catch_frame == NULL && mini_debug_options.suspend_on_unhandled && mono_object_class (exc) != mono_defaults.threadabortexception_class) {
5263 mono_runtime_printf_err ("Unhandled exception, suspending...");
5264 while (1)
5268 int i, j, suspend_policy;
5269 GSList *events;
5270 MonoJitInfo *ji, *catch_ji;
5271 EventInfo ei;
5272 DebuggerTlsData *tls = NULL;
5274 if (thread_to_tls != NULL) {
5275 MonoInternalThread *thread = mono_thread_internal_current ();
5277 mono_loader_lock ();
5278 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
5279 mono_loader_unlock ();
5281 if (tls && tls->abort_requested)
5282 return;
5283 if (tls && tls->disable_breakpoints)
5284 return;
5287 memset (&ei, 0, sizeof (ei));
5289 /* Just-In-Time debugging */
5290 if (!catch_ctx) {
5291 if (agent_config.onuncaught && !inited) {
5292 finish_agent_init (FALSE);
5295 * Send an unsolicited EXCEPTION event with a dummy request id.
5297 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5298 ei.exc = (MonoObject*)exc;
5299 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5300 return;
5302 } else if (agent_config.onthrow && !inited) {
5303 GSList *l;
5304 gboolean found = FALSE;
5306 for (l = agent_config.onthrow; l; l = l->next) {
5307 char *ex_type = (char *)l->data;
5308 char *f = mono_type_full_name (m_class_get_byval_arg (exc->object.vtable->klass));
5310 if (!strcmp (ex_type, "") || !strcmp (ex_type, f))
5311 found = TRUE;
5313 g_free (f);
5316 if (found) {
5317 finish_agent_init (FALSE);
5320 * Send an unsolicited EXCEPTION event with a dummy request id.
5322 events = g_slist_append (NULL, GUINT_TO_POINTER (0xffffff));
5323 ei.exc = (MonoObject*)exc;
5324 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, SUSPEND_POLICY_ALL);
5325 return;
5329 if (!inited)
5330 return;
5332 ji = mini_jit_info_table_find (mono_domain_get (), (char *)MONO_CONTEXT_GET_IP (throw_ctx), NULL);
5333 if (catch_frame)
5334 catch_ji = catch_frame->ji;
5335 else
5336 catch_ji = NULL;
5338 ei.exc = (MonoObject*)exc;
5339 ei.caught = catch_ctx != NULL;
5341 mono_loader_lock ();
5343 /* Treat exceptions which are caught in non-user code as unhandled */
5344 for (i = 0; i < event_requests->len; ++i) {
5345 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
5346 if (req->event_kind != EVENT_KIND_EXCEPTION)
5347 continue;
5349 for (j = 0; j < req->nmodifiers; ++j) {
5350 Modifier *mod = &req->modifiers [j];
5352 if (mod->kind == MOD_KIND_ASSEMBLY_ONLY && catch_ji) {
5353 int k;
5354 gboolean found = FALSE;
5355 MonoAssembly **assemblies = mod->data.assemblies;
5357 if (assemblies) {
5358 for (k = 0; assemblies [k]; ++k)
5359 if (assemblies [k] == m_class_get_image (jinfo_get_method (catch_ji)->klass)->assembly)
5360 found = TRUE;
5362 if (!found)
5363 ei.caught = FALSE;
5368 events = create_event_list (EVENT_KIND_EXCEPTION, NULL, ji, &ei, &suspend_policy);
5369 mono_loader_unlock ();
5371 if (tls && ei.caught && catch_ctx) {
5372 if (catch_frame) {
5373 tls->has_catch_frame = TRUE;
5374 tls->catch_frame = *catch_frame;
5375 } else {
5376 memset (&tls->catch_frame, 0, sizeof (tls->catch_frame));
5380 process_event (EVENT_KIND_EXCEPTION, &ei, 0, throw_ctx, events, suspend_policy);
5382 if (tls)
5383 tls->has_catch_frame = FALSE;
5386 static void
5387 debugger_agent_begin_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5389 DebuggerTlsData *tls;
5391 if (!inited)
5392 return;
5394 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5395 if (!tls)
5396 return;
5399 * We're about to invoke an exception filter during the first pass of exception handling.
5401 * 'ctx' is the context that'll get passed to the filter ('call_filter (ctx, ei->data.filter)'),
5402 * 'orig_ctx' is the context where the exception has been thrown.
5405 * See mcs/class/Mono.Debugger.Soft/Tests/dtest-excfilter.il for an example.
5407 * If we're stopped in Filter(), normal stack unwinding would first unwind to
5408 * the call site (line 37) and then continue to Main(), but it would never
5409 * include the throw site (line 32).
5411 * Since exception filters are invoked during the first pass of exception handling,
5412 * the stack frames of the throw site are still intact, so we should include them
5413 * in a stack trace.
5415 * We do this here by saving the context of the throw site in 'tls->filter_state'.
5417 * Exception filters are used by MonoDroid, where we want to stop inside a call filter,
5418 * but report the location of the 'throw' to the user.
5422 g_assert (mono_thread_state_init_from_monoctx (&tls->filter_state, orig_ctx));
5425 static void
5426 debugger_agent_end_exception_filter (MonoException *exc, MonoContext *ctx, MonoContext *orig_ctx)
5428 DebuggerTlsData *tls;
5430 if (!inited)
5431 return;
5433 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
5434 if (!tls)
5435 return;
5437 tls->filter_state.valid = FALSE;
5440 static void
5441 buffer_add_fixed_array (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5442 gboolean as_vtype, GHashTable *parent_vtypes, gint32 len_fixed_array)
5444 buffer_add_byte (buf, VALUE_TYPE_ID_FIXED_ARRAY);
5445 buffer_add_byte (buf, t->type);
5446 buffer_add_int (buf, len_fixed_array );
5447 for (int i = 0; i < len_fixed_array; i++) {
5448 switch (t->type) {
5449 case MONO_TYPE_BOOLEAN:
5450 case MONO_TYPE_I1:
5451 case MONO_TYPE_U1:
5452 buffer_add_int (buf, ((gint8*)addr)[i]);
5453 break;
5454 case MONO_TYPE_CHAR:
5455 case MONO_TYPE_I2:
5456 case MONO_TYPE_U2:
5457 buffer_add_int (buf, ((gint16*)addr)[i]);
5458 break;
5459 case MONO_TYPE_I4:
5460 case MONO_TYPE_U4:
5461 case MONO_TYPE_R4:
5462 buffer_add_int (buf, ((gint32*)addr)[i]);
5463 break;
5464 case MONO_TYPE_I8:
5465 case MONO_TYPE_U8:
5466 case MONO_TYPE_R8:
5467 buffer_add_long (buf, ((gint64*)addr)[i]);
5468 break;
5469 case MONO_TYPE_PTR: {
5470 gssize val = *(gssize*)addr;
5472 buffer_add_byte (buf, t->type);
5473 buffer_add_long (buf, val);
5474 if (CHECK_PROTOCOL_VERSION(2, 46))
5475 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (t));
5476 break;
5482 * buffer_add_value_full:
5484 * Add the encoding of the value at ADDR described by T to the buffer.
5485 * AS_VTYPE determines whenever to treat primitive types as primitive types or
5486 * vtypes.
5488 static void
5489 buffer_add_value_full (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain,
5490 gboolean as_vtype, GHashTable *parent_vtypes, gint32 len_fixed_array)
5492 MonoObject *obj;
5493 gboolean boxed_vtype = FALSE;
5495 if (t->byref) {
5496 if (!(*(void**)addr)) {
5497 /* This can happen with compiler generated locals */
5498 //printf ("%s\n", mono_type_full_name (t));
5499 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5500 return;
5502 g_assert (*(void**)addr);
5503 addr = *(void**)addr;
5506 if (as_vtype) {
5507 switch (t->type) {
5508 case MONO_TYPE_BOOLEAN:
5509 case MONO_TYPE_I1:
5510 case MONO_TYPE_U1:
5511 case MONO_TYPE_CHAR:
5512 case MONO_TYPE_I2:
5513 case MONO_TYPE_U2:
5514 case MONO_TYPE_I4:
5515 case MONO_TYPE_U4:
5516 case MONO_TYPE_R4:
5517 case MONO_TYPE_I8:
5518 case MONO_TYPE_U8:
5519 case MONO_TYPE_R8:
5520 case MONO_TYPE_I:
5521 case MONO_TYPE_U:
5522 case MONO_TYPE_PTR:
5523 goto handle_vtype;
5524 break;
5525 default:
5526 break;
5530 if (len_fixed_array > 1 && t->type != MONO_TYPE_VALUETYPE && CHECK_PROTOCOL_VERSION (2, 53))
5532 buffer_add_fixed_array(buf, t, addr, domain, as_vtype, parent_vtypes, len_fixed_array);
5533 return;
5535 switch (t->type) {
5536 case MONO_TYPE_VOID:
5537 buffer_add_byte (buf, t->type);
5538 break;
5539 case MONO_TYPE_BOOLEAN:
5540 case MONO_TYPE_I1:
5541 case MONO_TYPE_U1:
5542 buffer_add_byte (buf, t->type);
5543 buffer_add_int (buf, *(gint8*)addr);
5544 break;
5545 case MONO_TYPE_CHAR:
5546 case MONO_TYPE_I2:
5547 case MONO_TYPE_U2:
5548 buffer_add_byte (buf, t->type);
5549 buffer_add_int (buf, *(gint16*)addr);
5550 break;
5551 case MONO_TYPE_I4:
5552 case MONO_TYPE_U4:
5553 case MONO_TYPE_R4:
5554 buffer_add_byte (buf, t->type);
5555 buffer_add_int (buf, *(gint32*)addr);
5556 break;
5557 case MONO_TYPE_I8:
5558 case MONO_TYPE_U8:
5559 case MONO_TYPE_R8:
5560 buffer_add_byte (buf, t->type);
5561 buffer_add_long (buf, *(gint64*)addr);
5562 break;
5563 case MONO_TYPE_I:
5564 case MONO_TYPE_U:
5565 /* Treat it as a vtype */
5566 goto handle_vtype;
5567 case MONO_TYPE_PTR: {
5568 gssize val = *(gssize*)addr;
5570 buffer_add_byte (buf, t->type);
5571 buffer_add_long (buf, val);
5572 if (CHECK_PROTOCOL_VERSION(2, 46))
5573 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (t));
5574 break;
5576 handle_ref:
5577 case MONO_TYPE_STRING:
5578 case MONO_TYPE_SZARRAY:
5579 case MONO_TYPE_OBJECT:
5580 case MONO_TYPE_CLASS:
5581 case MONO_TYPE_ARRAY:
5582 obj = *(MonoObject**)addr;
5584 if (!obj) {
5585 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5586 } else {
5587 if (m_class_is_valuetype (obj->vtable->klass)) {
5588 t = m_class_get_byval_arg (obj->vtable->klass);
5589 addr = mono_object_unbox_internal (obj);
5590 boxed_vtype = TRUE;
5591 goto handle_vtype;
5592 } else if (m_class_get_rank (obj->vtable->klass)) {
5593 buffer_add_byte (buf, m_class_get_byval_arg (obj->vtable->klass)->type);
5594 } else if (m_class_get_byval_arg (obj->vtable->klass)->type == MONO_TYPE_GENERICINST) {
5595 buffer_add_byte (buf, MONO_TYPE_CLASS);
5596 } else {
5597 buffer_add_byte (buf, m_class_get_byval_arg (obj->vtable->klass)->type);
5599 buffer_add_objid (buf, obj);
5601 break;
5602 handle_vtype:
5603 case MONO_TYPE_VALUETYPE:
5604 case MONO_TYPE_TYPEDBYREF: {
5605 int nfields;
5606 gpointer iter;
5607 MonoClassField *f;
5608 MonoClass *klass = mono_class_from_mono_type_internal (t);
5609 int vtype_index;
5611 if (boxed_vtype) {
5613 * Handle boxed vtypes recursively referencing themselves using fields.
5615 if (!parent_vtypes)
5616 parent_vtypes = g_hash_table_new (NULL, NULL);
5617 vtype_index = GPOINTER_TO_INT (g_hash_table_lookup (parent_vtypes, addr));
5618 if (vtype_index) {
5619 if (CHECK_PROTOCOL_VERSION (2, 33)) {
5620 buffer_add_byte (buf, VALUE_TYPE_ID_PARENT_VTYPE);
5621 buffer_add_int (buf, vtype_index - 1);
5622 } else {
5623 /* The client can't handle PARENT_VTYPE */
5624 buffer_add_byte (buf, VALUE_TYPE_ID_NULL);
5626 break;
5627 } else {
5628 g_hash_table_insert (parent_vtypes, addr, GINT_TO_POINTER (g_hash_table_size (parent_vtypes) + 1));
5632 buffer_add_byte (buf, MONO_TYPE_VALUETYPE);
5633 buffer_add_byte (buf, m_class_is_enumtype (klass));
5634 buffer_add_typeid (buf, domain, klass);
5636 nfields = 0;
5637 iter = NULL;
5638 while ((f = mono_class_get_fields_internal (klass, &iter))) {
5639 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5640 continue;
5641 if (mono_field_is_deleted (f))
5642 continue;
5643 nfields ++;
5645 buffer_add_int (buf, nfields);
5647 iter = NULL;
5648 while ((f = mono_class_get_fields_internal (klass, &iter))) {
5649 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5650 continue;
5651 if (mono_field_is_deleted (f))
5652 continue;
5653 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));
5656 if (boxed_vtype) {
5657 g_hash_table_remove (parent_vtypes, addr);
5658 if (g_hash_table_size (parent_vtypes) == 0) {
5659 g_hash_table_destroy (parent_vtypes);
5660 parent_vtypes = NULL;
5663 break;
5665 case MONO_TYPE_GENERICINST:
5666 if (mono_type_generic_inst_is_valuetype (t)) {
5667 goto handle_vtype;
5668 } else {
5669 goto handle_ref;
5671 break;
5672 default:
5673 NOT_IMPLEMENTED;
5677 static void
5678 buffer_add_value (Buffer *buf, MonoType *t, void *addr, MonoDomain *domain)
5680 buffer_add_value_full (buf, t, addr, domain, FALSE, NULL, 1);
5683 static gboolean
5684 obj_is_of_type (MonoObject *obj, MonoType *t)
5686 MonoClass *klass = obj->vtable->klass;
5687 if (!mono_class_is_assignable_from_internal (mono_class_from_mono_type_internal (t), klass)) {
5688 if (mono_class_is_transparent_proxy (klass)) {
5689 klass = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
5690 if (mono_class_is_assignable_from_internal (mono_class_from_mono_type_internal (t), klass)) {
5691 return TRUE;
5694 return FALSE;
5696 return TRUE;
5699 static ErrorCode
5700 decode_value (MonoType *t, MonoDomain *domain, gpointer void_addr, gpointer void_buf, guint8 **endbuf, guint8 *limit, gboolean check_field_datatype);
5702 static ErrorCode
5703 decode_vtype (MonoType *t, MonoDomain *domain, gpointer void_addr, gpointer void_buf, guint8 **endbuf, guint8 *limit, gboolean check_field_datatype)
5705 guint8 *addr = (guint8*)void_addr;
5706 guint8 *buf = (guint8*)void_buf;
5707 gboolean is_enum;
5708 MonoClass *klass;
5709 MonoClassField *f;
5710 int nfields;
5711 gpointer iter = NULL;
5712 MonoDomain *d;
5713 ErrorCode err;
5715 is_enum = decode_byte (buf, &buf, limit);
5716 /* Enums are sent as a normal vtype */
5717 if (is_enum)
5718 return ERR_NOT_IMPLEMENTED;
5719 klass = decode_typeid (buf, &buf, limit, &d, &err);
5720 if (err != ERR_NONE)
5721 return err;
5723 if (t && klass != mono_class_from_mono_type_internal (t)) {
5724 char *name = mono_type_full_name (t);
5725 char *name2 = mono_type_full_name (m_class_get_byval_arg (klass));
5726 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got %s.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, name2);
5727 g_free (name);
5728 g_free (name2);
5729 return ERR_INVALID_ARGUMENT;
5732 nfields = decode_int (buf, &buf, limit);
5733 while ((f = mono_class_get_fields_internal (klass, &iter))) {
5734 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC)
5735 continue;
5736 if (mono_field_is_deleted (f))
5737 continue;
5738 err = decode_value (f->type, domain, mono_vtype_get_field_addr (addr, f), buf, &buf, limit, check_field_datatype);
5739 if (err != ERR_NONE)
5740 return err;
5741 nfields --;
5743 g_assert (nfields == 0);
5745 *endbuf = buf;
5747 return ERR_NONE;
5749 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)
5751 ErrorCode err = ERR_NONE;
5752 int fixedSizeLen = 1;
5753 int newType = MONO_TYPE_END;
5754 if (CHECK_PROTOCOL_VERSION (2, 53)) {
5755 newType = decode_byte (buf, &buf, limit);
5756 fixedSizeLen = decode_int (buf, &buf, limit);
5757 //t->type = newType;
5759 for (int i = 0 ; i < fixedSizeLen; i++) {
5760 switch (newType) {
5761 case MONO_TYPE_BOOLEAN:
5762 ((guint8*)addr)[i] = decode_int (buf, &buf, limit);
5763 break;
5764 case MONO_TYPE_CHAR:
5765 ((gunichar2*)addr)[i] = decode_int (buf, &buf, limit);
5766 break;
5767 case MONO_TYPE_I1:
5768 ((gint8*)addr)[i] = decode_int (buf, &buf, limit);
5769 break;
5770 case MONO_TYPE_U1:
5771 ((guint8*)addr)[i] = decode_int (buf, &buf, limit);
5772 break;
5773 case MONO_TYPE_I2:
5774 ((gint16*)addr)[i] = decode_int (buf, &buf, limit);
5775 break;
5776 case MONO_TYPE_U2:
5777 ((guint16*)addr)[i] = decode_int (buf, &buf, limit);
5778 break;
5779 case MONO_TYPE_I4:
5780 ((gint32*)addr)[i] = decode_int (buf, &buf, limit);
5781 break;
5782 case MONO_TYPE_U4:
5783 ((guint32*)addr)[i] = decode_int (buf, &buf, limit);
5784 break;
5785 case MONO_TYPE_I8:
5786 ((gint64*)addr)[i] = decode_long (buf, &buf, limit);
5787 break;
5788 case MONO_TYPE_U8:
5789 ((guint64*)addr)[i] = decode_long (buf, &buf, limit);
5790 break;
5791 case MONO_TYPE_R4:
5792 ((guint32*)addr)[i] = decode_int (buf, &buf, limit);
5793 break;
5794 case MONO_TYPE_R8:
5795 ((guint64*)addr)[i] = decode_long (buf, &buf, limit);
5796 break;
5799 *endbuf = buf;
5800 return err;
5802 static ErrorCode
5803 decode_value_internal (MonoType *t, int type, MonoDomain *domain, guint8 *addr, guint8 *buf, guint8 **endbuf, guint8 *limit, gboolean check_field_datatype)
5805 ErrorCode err;
5806 if (type != t->type && !MONO_TYPE_IS_REFERENCE (t) &&
5807 !(t->type == MONO_TYPE_I && type == MONO_TYPE_VALUETYPE) &&
5808 !(type == VALUE_TYPE_ID_FIXED_ARRAY) &&
5809 !(t->type == MONO_TYPE_U && type == MONO_TYPE_VALUETYPE) &&
5810 !(t->type == MONO_TYPE_PTR && type == MONO_TYPE_I8) &&
5811 !(t->type == MONO_TYPE_GENERICINST && type == MONO_TYPE_VALUETYPE) &&
5812 !(t->type == MONO_TYPE_VALUETYPE && type == MONO_TYPE_OBJECT)) {
5813 char *name = mono_type_full_name (t);
5814 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
5815 g_free (name);
5816 return ERR_INVALID_ARGUMENT;
5818 if (type == VALUE_TYPE_ID_FIXED_ARRAY && t->type != MONO_TYPE_VALUETYPE) {
5819 decode_fixed_size_array_internal (t, type, domain, addr, buf, endbuf, limit, check_field_datatype);
5820 return ERR_NONE;
5823 switch (t->type) {
5824 case MONO_TYPE_BOOLEAN:
5825 *(guint8*)addr = decode_int (buf, &buf, limit);
5826 break;
5827 case MONO_TYPE_CHAR:
5828 *(gunichar2*)addr = decode_int (buf, &buf, limit);
5829 break;
5830 case MONO_TYPE_I1:
5831 *(gint8*)addr = decode_int (buf, &buf, limit);
5832 break;
5833 case MONO_TYPE_U1:
5834 *(guint8*)addr = decode_int (buf, &buf, limit);
5835 break;
5836 case MONO_TYPE_I2:
5837 *(gint16*)addr = decode_int (buf, &buf, limit);
5838 break;
5839 case MONO_TYPE_U2:
5840 *(guint16*)addr = decode_int (buf, &buf, limit);
5841 break;
5842 case MONO_TYPE_I4:
5843 *(gint32*)addr = decode_int (buf, &buf, limit);
5844 break;
5845 case MONO_TYPE_U4:
5846 *(guint32*)addr = decode_int (buf, &buf, limit);
5847 break;
5848 case MONO_TYPE_I8:
5849 *(gint64*)addr = decode_long (buf, &buf, limit);
5850 break;
5851 case MONO_TYPE_U8:
5852 *(guint64*)addr = decode_long (buf, &buf, limit);
5853 break;
5854 case MONO_TYPE_R4:
5855 *(guint32*)addr = decode_int (buf, &buf, limit);
5856 break;
5857 case MONO_TYPE_R8:
5858 *(guint64*)addr = decode_long (buf, &buf, limit);
5859 break;
5860 case MONO_TYPE_PTR:
5861 /* We send these as I8, so we get them back as such */
5862 g_assert (type == MONO_TYPE_I8);
5863 *(gssize*)addr = decode_long (buf, &buf, limit);
5864 break;
5865 case MONO_TYPE_GENERICINST:
5866 if (MONO_TYPE_ISSTRUCT (t)) {
5867 /* The client sends these as a valuetype */
5868 goto handle_vtype;
5869 } else {
5870 goto handle_ref;
5872 break;
5873 case MONO_TYPE_I:
5874 case MONO_TYPE_U:
5875 /* We send these as vtypes, so we get them back as such */
5876 g_assert (type == MONO_TYPE_VALUETYPE);
5877 /* Fall through */
5878 handle_vtype:
5879 case MONO_TYPE_VALUETYPE:
5880 if (type == MONO_TYPE_OBJECT) {
5881 /* Boxed vtype */
5882 int objid = decode_objid (buf, &buf, limit);
5883 ErrorCode err;
5884 MonoObject *obj;
5886 err = get_object (objid, (MonoObject**)&obj);
5887 if (err != ERR_NONE)
5888 return err;
5889 if (!obj)
5890 return ERR_INVALID_ARGUMENT;
5891 if (obj->vtable->klass != mono_class_from_mono_type_internal (t)) {
5892 DEBUG_PRINTF (1, "Expected type '%s', got object '%s'\n", mono_type_full_name (t), m_class_get_name (obj->vtable->klass));
5893 return ERR_INVALID_ARGUMENT;
5895 memcpy (addr, mono_object_unbox_internal (obj), mono_class_value_size (obj->vtable->klass, NULL));
5896 } else {
5897 err = decode_vtype (t, domain, addr, buf, &buf, limit, check_field_datatype);
5898 if (err != ERR_NONE)
5899 return err;
5901 break;
5902 handle_ref:
5903 default:
5904 if (MONO_TYPE_IS_REFERENCE (t)) {
5905 if (type == MONO_TYPE_OBJECT) {
5906 int objid = decode_objid (buf, &buf, limit);
5907 ErrorCode err;
5908 MonoObject *obj;
5910 err = get_object (objid, (MonoObject**)&obj);
5911 if (err != ERR_NONE)
5912 return err;
5914 if (obj) {
5915 if (!obj_is_of_type (obj, t)) {
5916 if (check_field_datatype) { //if it's not executing a invoke method check the datatypes.
5917 DEBUG_PRINTF (1, "Expected type '%s', got '%s'\n", mono_type_full_name (t), m_class_get_name (obj->vtable->klass));
5918 return ERR_INVALID_ARGUMENT;
5922 if (obj && obj->vtable->domain != domain)
5923 return ERR_INVALID_ARGUMENT;
5925 mono_gc_wbarrier_generic_store_internal (addr, obj);
5926 } else if (type == VALUE_TYPE_ID_NULL) {
5927 *(MonoObject**)addr = NULL;
5928 } else if (type == MONO_TYPE_VALUETYPE) {
5929 ERROR_DECL (error);
5930 guint8 *buf2;
5931 gboolean is_enum;
5932 MonoClass *klass;
5933 MonoDomain *d;
5934 guint8 *vtype_buf;
5935 int vtype_buf_size;
5937 /* This can happen when round-tripping boxed vtypes */
5939 * Obtain vtype class.
5940 * Same as the beginning of the handle_vtype case above.
5942 buf2 = buf;
5943 is_enum = decode_byte (buf, &buf, limit);
5944 if (is_enum)
5945 return ERR_NOT_IMPLEMENTED;
5946 klass = decode_typeid (buf, &buf, limit, &d, &err);
5947 if (err != ERR_NONE)
5948 return err;
5950 /* Decode the vtype into a temporary buffer, then box it. */
5951 vtype_buf_size = mono_class_value_size (klass, NULL);
5952 vtype_buf = (guint8 *)g_malloc0 (vtype_buf_size);
5953 g_assert (vtype_buf);
5955 buf = buf2;
5956 err = decode_vtype (NULL, domain, vtype_buf, buf, &buf, limit, check_field_datatype);
5957 if (err != ERR_NONE) {
5958 g_free (vtype_buf);
5959 return err;
5961 *(MonoObject**)addr = mono_value_box_checked (d, klass, vtype_buf, error);
5962 mono_error_cleanup (error);
5963 g_free (vtype_buf);
5964 } else {
5965 char *name = mono_type_full_name (t);
5966 DEBUG_PRINTF (1, "[%p] Expected value of type %s, got 0x%0x.\n", (gpointer) (gsize) mono_native_thread_id_get (), name, type);
5967 g_free (name);
5968 return ERR_INVALID_ARGUMENT;
5970 } else if ((t->type == MONO_TYPE_GENERICINST) &&
5971 mono_metadata_generic_class_is_valuetype (t->data.generic_class) &&
5972 m_class_is_enumtype (t->data.generic_class->container_class)){
5973 err = decode_vtype (t, domain, addr, buf, &buf, limit, check_field_datatype);
5974 if (err != ERR_NONE)
5975 return err;
5976 } else {
5977 NOT_IMPLEMENTED;
5979 break;
5983 *endbuf = buf;
5985 return ERR_NONE;
5988 static ErrorCode
5989 decode_value (MonoType *t, MonoDomain *domain, gpointer void_addr, gpointer void_buf, guint8 **endbuf, guint8 *limit, gboolean check_field_datatype)
5991 guint8 *addr = (guint8*)void_addr;
5992 guint8 *buf = (guint8*)void_buf;
5994 ERROR_DECL (error);
5995 ErrorCode err;
5996 int type = decode_byte (buf, &buf, limit);
5998 if (t->type == MONO_TYPE_GENERICINST && mono_class_is_nullable (mono_class_from_mono_type_internal (t))) {
5999 MonoType *targ = t->data.generic_class->context.class_inst->type_argv [0];
6000 guint8 *nullable_buf;
6003 * First try decoding it as a Nullable`1
6005 err = decode_value_internal (t, type, domain, addr, buf, endbuf, limit, check_field_datatype);
6006 if (err == ERR_NONE)
6007 return err;
6010 * Then try decoding as a primitive value or null.
6012 if (targ->type == type) {
6013 nullable_buf = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type_internal (targ)));
6014 err = decode_value_internal (targ, type, domain, nullable_buf, buf, endbuf, limit, check_field_datatype);
6015 if (err != ERR_NONE) {
6016 g_free (nullable_buf);
6017 return err;
6019 MonoObject *boxed = mono_value_box_checked (domain, mono_class_from_mono_type_internal (targ), nullable_buf, error);
6020 if (!is_ok (error)) {
6021 mono_error_cleanup (error);
6022 return ERR_INVALID_OBJECT;
6024 mono_nullable_init (addr, boxed, mono_class_from_mono_type_internal (t));
6025 g_free (nullable_buf);
6026 *endbuf = buf;
6027 return ERR_NONE;
6028 } else if (type == VALUE_TYPE_ID_NULL) {
6029 mono_nullable_init (addr, NULL, mono_class_from_mono_type_internal (t));
6030 *endbuf = buf;
6031 return ERR_NONE;
6035 return decode_value_internal (t, type, domain, addr, buf, endbuf, limit, check_field_datatype);
6038 static void
6039 add_var (Buffer *buf, MonoDebugMethodJitInfo *jit, MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, gboolean as_vtype)
6041 guint32 flags;
6042 int reg;
6043 guint8 *addr, *gaddr;
6044 host_mgreg_t reg_val;
6046 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6047 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6049 switch (flags) {
6050 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER:
6051 reg_val = mono_arch_context_get_int_reg (ctx, reg);
6053 buffer_add_value_full (buf, t, &reg_val, domain, as_vtype, NULL, 1);
6054 break;
6055 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6056 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6057 addr += (gint32)var->offset;
6059 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6061 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL, 1);
6062 break;
6063 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6064 NOT_IMPLEMENTED;
6065 break;
6066 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6067 case MONO_DEBUG_VAR_ADDRESS_MODE_VTADDR:
6068 /* Same as regoffset, but with an indirection */
6069 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6070 addr += (gint32)var->offset;
6072 gaddr = (guint8 *)*(gpointer*)addr;
6073 g_assert (gaddr);
6074 buffer_add_value_full (buf, t, gaddr, domain, as_vtype, NULL, 1);
6075 break;
6076 case MONO_DEBUG_VAR_ADDRESS_MODE_GSHAREDVT_LOCAL: {
6077 MonoDebugVarInfo *info_var = jit->gsharedvt_info_var;
6078 MonoDebugVarInfo *locals_var = jit->gsharedvt_locals_var;
6079 MonoGSharedVtMethodRuntimeInfo *info;
6080 guint8 *locals;
6081 int idx;
6083 idx = reg;
6085 g_assert (info_var);
6086 g_assert (locals_var);
6088 flags = info_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6089 reg = info_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6090 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6091 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6092 addr += (gint32)info_var->offset;
6093 info = (MonoGSharedVtMethodRuntimeInfo *)*(gpointer*)addr;
6094 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6095 info = (MonoGSharedVtMethodRuntimeInfo *)mono_arch_context_get_int_reg (ctx, reg);
6096 } else {
6097 g_assert_not_reached ();
6099 g_assert (info);
6101 flags = locals_var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6102 reg = locals_var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6103 if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET) {
6104 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6105 addr += (gint32)locals_var->offset;
6106 locals = (guint8 *)*(gpointer*)addr;
6107 } else if (flags == MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER) {
6108 locals = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6109 } else {
6110 g_assert_not_reached ();
6112 g_assert (locals);
6114 addr = locals + GPOINTER_TO_INT (info->entries [idx]);
6116 buffer_add_value_full (buf, t, addr, domain, as_vtype, NULL, 1);
6117 break;
6120 default:
6121 g_assert_not_reached ();
6125 static void
6126 set_var (MonoType *t, MonoDebugVarInfo *var, MonoContext *ctx, MonoDomain *domain, guint8 *val, host_mgreg_t **reg_locations, MonoContext *restore_ctx)
6128 guint32 flags;
6129 int reg, size;
6130 guint8 *addr, *gaddr;
6132 flags = var->index & MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6133 reg = var->index & ~MONO_DEBUG_VAR_ADDRESS_MODE_FLAGS;
6135 if (MONO_TYPE_IS_REFERENCE (t))
6136 size = sizeof (gpointer);
6137 else
6138 size = mono_class_value_size (mono_class_from_mono_type_internal (t), NULL);
6140 switch (flags) {
6141 case MONO_DEBUG_VAR_ADDRESS_MODE_REGISTER: {
6142 #ifdef MONO_ARCH_HAVE_CONTEXT_SET_INT_REG
6143 host_mgreg_t v;
6144 gboolean is_signed = FALSE;
6146 if (t->byref) {
6147 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6149 if (addr) {
6150 // FIXME: Write barriers
6151 mono_gc_memmove_atomic (addr, val, size);
6153 break;
6156 if (!t->byref && (t->type == MONO_TYPE_I1 || t->type == MONO_TYPE_I2 || t->type == MONO_TYPE_I4 || t->type == MONO_TYPE_I8))
6157 is_signed = TRUE;
6159 switch (size) {
6160 case 1:
6161 v = is_signed ? *(gint8*)val : *(guint8*)val;
6162 break;
6163 case 2:
6164 v = is_signed ? *(gint16*)val : *(guint16*)val;
6165 break;
6166 case 4:
6167 v = is_signed ? *(gint32*)val : *(guint32*)val;
6168 break;
6169 case 8:
6170 v = is_signed ? *(gint64*)val : *(guint64*)val;
6171 break;
6172 default:
6173 g_assert_not_reached ();
6176 /* Set value on the stack or in the return ctx */
6177 if (reg_locations [reg]) {
6178 /* Saved on the stack */
6179 DEBUG_PRINTF (1, "[dbg] Setting stack location %p for reg %x to %p.\n", reg_locations [reg], reg, (gpointer)v);
6180 *(reg_locations [reg]) = v;
6181 } else {
6182 /* Not saved yet */
6183 DEBUG_PRINTF (1, "[dbg] Setting context location for reg %x to %p.\n", reg, (gpointer)v);
6184 mono_arch_context_set_int_reg (restore_ctx, reg, v);
6187 // FIXME: Move these to mono-context.h/c.
6188 mono_arch_context_set_int_reg (ctx, reg, v);
6189 #else
6190 // FIXME: Can't set registers, so we disable linears
6191 NOT_IMPLEMENTED;
6192 #endif
6193 break;
6195 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET:
6196 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6197 addr += (gint32)var->offset;
6199 //printf ("[R%d+%d] = %p\n", reg, var->offset, addr);
6201 if (t->byref) {
6202 addr = *(guint8**)addr;
6204 if (!addr)
6205 break;
6208 // FIXME: Write barriers
6209 mono_gc_memmove_atomic (addr, val, size);
6210 break;
6211 case MONO_DEBUG_VAR_ADDRESS_MODE_REGOFFSET_INDIR:
6212 /* Same as regoffset, but with an indirection */
6213 addr = (guint8 *)mono_arch_context_get_int_reg (ctx, reg);
6214 addr += (gint32)var->offset;
6216 gaddr = (guint8 *)*(gpointer*)addr;
6217 g_assert (gaddr);
6218 // FIXME: Write barriers
6219 mono_gc_memmove_atomic (gaddr, val, size);
6220 break;
6221 case MONO_DEBUG_VAR_ADDRESS_MODE_DEAD:
6222 NOT_IMPLEMENTED;
6223 break;
6224 default:
6225 g_assert_not_reached ();
6229 static void
6230 set_interp_var (MonoType *t, gpointer addr, guint8 *val_buf)
6232 int size;
6234 if (t->byref) {
6235 addr = *(gpointer*)addr;
6236 g_assert (addr);
6239 if (MONO_TYPE_IS_REFERENCE (t))
6240 size = sizeof (gpointer);
6241 else
6242 size = mono_class_value_size (mono_class_from_mono_type_internal (t), NULL);
6244 memcpy (addr, val_buf, size);
6247 static void
6248 clear_event_request (int req_id, int etype)
6250 int i;
6252 mono_loader_lock ();
6253 for (i = 0; i < event_requests->len; ++i) {
6254 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6256 if (req->id == req_id && req->event_kind == etype) {
6257 if (req->event_kind == EVENT_KIND_BREAKPOINT)
6258 mono_de_clear_breakpoint ((MonoBreakpoint *)req->info);
6259 if (req->event_kind == EVENT_KIND_STEP) {
6260 mono_de_cancel_ss ((SingleStepReq *)req->info);
6262 if (req->event_kind == EVENT_KIND_METHOD_ENTRY)
6263 mono_de_clear_breakpoint ((MonoBreakpoint *)req->info);
6264 if (req->event_kind == EVENT_KIND_METHOD_EXIT)
6265 mono_de_clear_breakpoint ((MonoBreakpoint *)req->info);
6266 g_ptr_array_remove_index_fast (event_requests, i);
6267 g_free (req);
6268 break;
6271 mono_loader_unlock ();
6274 static void
6275 clear_assembly_from_modifier (EventRequest *req, Modifier *m, MonoAssembly *assembly)
6277 int i;
6279 if (m->kind == MOD_KIND_EXCEPTION_ONLY && m->data.exc_class && m_class_get_image (m->data.exc_class)->assembly == assembly)
6280 m->kind = MOD_KIND_NONE;
6281 if (m->kind == MOD_KIND_ASSEMBLY_ONLY && m->data.assemblies) {
6282 int count = 0, match_count = 0, pos;
6283 MonoAssembly **newassemblies;
6285 for (i = 0; m->data.assemblies [i]; ++i) {
6286 count ++;
6287 if (m->data.assemblies [i] == assembly)
6288 match_count ++;
6291 if (match_count) {
6292 // +1 because we don't know length and we use last element to check for end
6293 newassemblies = g_new0 (MonoAssembly*, count - match_count + 1);
6295 pos = 0;
6296 for (i = 0; i < count; ++i)
6297 if (m->data.assemblies [i] != assembly)
6298 newassemblies [pos ++] = m->data.assemblies [i];
6299 g_assert (pos == count - match_count);
6300 g_free (m->data.assemblies);
6301 m->data.assemblies = newassemblies;
6306 static void
6307 clear_assembly_from_modifiers (EventRequest *req, MonoAssembly *assembly)
6309 int i;
6311 for (i = 0; i < req->nmodifiers; ++i) {
6312 Modifier *m = &req->modifiers [i];
6314 clear_assembly_from_modifier (req, m, assembly);
6319 * clear_event_requests_for_assembly:
6321 * Clear all events requests which reference ASSEMBLY.
6323 static void
6324 clear_event_requests_for_assembly (MonoAssembly *assembly)
6326 int i;
6327 gboolean found;
6329 mono_loader_lock ();
6330 found = TRUE;
6331 while (found) {
6332 found = FALSE;
6333 for (i = 0; i < event_requests->len; ++i) {
6334 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
6336 clear_assembly_from_modifiers (req, assembly);
6338 if (req->event_kind == EVENT_KIND_BREAKPOINT && breakpoint_matches_assembly ((MonoBreakpoint *)req->info, assembly)) {
6339 clear_event_request (req->id, req->event_kind);
6340 found = TRUE;
6341 break;
6344 if (req->event_kind == EVENT_KIND_STEP)
6345 ss_clear_for_assembly ((SingleStepReq *)req->info, assembly);
6348 mono_loader_unlock ();
6352 * type_comes_from_assembly:
6354 * GHRFunc that returns TRUE if klass comes from assembly
6356 static gboolean
6357 type_comes_from_assembly (gpointer klass, gpointer also_klass, gpointer assembly)
6359 return mono_type_in_image (m_class_get_byval_arg ((MonoClass*)klass), mono_assembly_get_image_internal ((MonoAssembly*)assembly));
6363 * clear_types_for_assembly:
6365 * Clears types from loaded_classes for a given assembly
6367 static void
6368 clear_types_for_assembly (MonoAssembly *assembly)
6370 MonoDomain *domain = mono_domain_get ();
6371 AgentDomainInfo *info = NULL;
6373 if (!domain || !domain_jit_info (domain))
6374 /* Can happen during shutdown */
6375 return;
6377 info = get_agent_domain_info (domain);
6379 mono_loader_lock ();
6380 g_hash_table_foreach_remove (info->loaded_classes, type_comes_from_assembly, assembly);
6381 mono_loader_unlock ();
6384 static void
6385 dispose_vm (void)
6387 /* Clear all event requests */
6388 mono_loader_lock ();
6389 while (event_requests->len > 0) {
6390 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
6392 clear_event_request (req->id, req->event_kind);
6394 mono_loader_unlock ();
6396 while (suspend_count > 0)
6397 resume_vm ();
6398 disconnected = TRUE;
6399 vm_start_event_sent = FALSE;
6402 static void
6403 count_thread_check_gc_finalizer (gpointer key, gpointer value, gpointer user_data)
6405 MonoThread *thread = (MonoThread *)value;
6406 gboolean *ret = (gboolean *)user_data;
6407 if (mono_gc_is_finalizer_internal_thread(thread->internal_thread)) {
6408 DebuggerTlsData *tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread->internal_thread);
6409 if (!tls->gc_finalizing) { //GC Finalizer is not running some finalizer code, so ignore it
6410 *ret = TRUE;
6411 return;
6416 static void
6417 add_thread (gpointer key, gpointer value, gpointer user_data)
6419 MonoThread *thread = (MonoThread *)value;
6420 Buffer *buf = (Buffer *)user_data;
6421 if (mono_gc_is_finalizer_internal_thread(thread->internal_thread)) {
6422 DebuggerTlsData *tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread->internal_thread);
6423 if (!tls->gc_finalizing) //GC Finalizer is not running some finalizer code, so ignore it
6424 return;
6426 buffer_add_objid (buf, (MonoObject*)thread);
6430 static ErrorCode
6431 do_invoke_method (DebuggerTlsData *tls, Buffer *buf, InvokeData *invoke, guint8 *p, guint8 **endp)
6433 ERROR_DECL (error);
6434 guint8 *end = invoke->endp;
6435 MonoMethod *m;
6436 int i, nargs;
6437 ErrorCode err;
6438 MonoMethodSignature *sig;
6439 guint8 **arg_buf;
6440 void **args;
6441 MonoObject *this_arg, *res, *exc = NULL;
6442 MonoDomain *domain;
6443 guint8 *this_buf;
6444 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6445 MonoLMFExt ext;
6446 #endif
6447 MonoStopwatch watch;
6449 if (invoke->method) {
6451 * Invoke this method directly, currently only Environment.Exit () is supported.
6453 this_arg = NULL;
6454 DEBUG_PRINTF (1, "[%p] Invoking method '%s' on receiver '%s'.\n", (gpointer) (gsize) mono_native_thread_id_get (), mono_method_full_name (invoke->method, TRUE), this_arg ? m_class_get_name (this_arg->vtable->klass) : "<null>");
6456 mono_runtime_try_invoke (invoke->method, NULL, invoke->args, &exc, error);
6457 mono_error_assert_ok (error);
6458 g_assert_not_reached ();
6461 m = decode_methodid (p, &p, end, &domain, &err);
6462 if (err != ERR_NONE)
6463 return err;
6464 sig = mono_method_signature_internal (m);
6466 if (m_class_is_valuetype (m->klass))
6467 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6468 else
6469 this_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
6471 if (m->is_generic) {
6472 DEBUG_PRINTF (1, "[%p] Error: Attempting to invoke uninflated generic method %s.\n", (gpointer)(gsize)mono_native_thread_id_get (), mono_method_full_name (m, TRUE));
6473 return ERR_INVALID_ARGUMENT;
6474 } else if (m_class_is_valuetype (m->klass) && (m->flags & METHOD_ATTRIBUTE_STATIC)) {
6475 /* Should be null */
6476 int type = decode_byte (p, &p, end);
6477 if (type != VALUE_TYPE_ID_NULL) {
6478 DEBUG_PRINTF (1, "[%p] Error: Static vtype method invoked with this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6479 return ERR_INVALID_ARGUMENT;
6481 memset (this_buf, 0, mono_class_instance_size (m->klass));
6482 } else if (m_class_is_valuetype (m->klass) && !strcmp (m->name, ".ctor")) {
6483 /* Could be null */
6484 guint8 *tmp_p;
6486 int type = decode_byte (p, &tmp_p, end);
6487 if (type == VALUE_TYPE_ID_NULL) {
6488 memset (this_buf, 0, mono_class_instance_size (m->klass));
6489 p = tmp_p;
6490 } else {
6491 err = decode_value (m_class_get_byval_arg (m->klass), domain, this_buf, p, &p, end, FALSE);
6492 if (err != ERR_NONE)
6493 return err;
6495 } else {
6496 err = decode_value (m_class_get_byval_arg (m->klass), domain, this_buf, p, &p, end, FALSE);
6497 if (err != ERR_NONE)
6498 return err;
6501 if (!m_class_is_valuetype (m->klass))
6502 this_arg = *(MonoObject**)this_buf;
6503 else
6504 this_arg = NULL;
6506 if (MONO_CLASS_IS_INTERFACE_INTERNAL (m->klass)) {
6507 if (!this_arg) {
6508 DEBUG_PRINTF (1, "[%p] Error: Interface method invoked without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6509 return ERR_INVALID_ARGUMENT;
6511 m = mono_object_get_virtual_method_internal (this_arg, m);
6512 /* Transform this to the format the rest of the code expects it to be */
6513 if (m_class_is_valuetype (m->klass)) {
6514 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6515 memcpy (this_buf, mono_object_unbox_internal (this_arg), mono_class_instance_size (m->klass));
6517 } else if ((m->flags & METHOD_ATTRIBUTE_VIRTUAL) && !m_class_is_valuetype (m->klass) && invoke->flags & INVOKE_FLAG_VIRTUAL) {
6518 if (!this_arg) {
6519 DEBUG_PRINTF (1, "[%p] Error: invoke with INVOKE_FLAG_VIRTUAL flag set without this argument.\n", (gpointer) (gsize) mono_native_thread_id_get ());
6520 return ERR_INVALID_ARGUMENT;
6522 m = mono_object_get_virtual_method_internal (this_arg, m);
6523 if (m_class_is_valuetype (m->klass)) {
6524 this_buf = (guint8 *)g_alloca (mono_class_instance_size (m->klass));
6525 memcpy (this_buf, mono_object_unbox_internal (this_arg), mono_class_instance_size (m->klass));
6529 DEBUG_PRINTF (1, "[%p] Invoking method '%s' on receiver '%s'.\n", (gpointer) (gsize) mono_native_thread_id_get (), mono_method_full_name (m, TRUE), this_arg ? m_class_get_name (this_arg->vtable->klass) : "<null>");
6531 if (this_arg && this_arg->vtable->domain != domain)
6532 NOT_IMPLEMENTED;
6534 if (!m_class_is_valuetype (m->klass) && !(m->flags & METHOD_ATTRIBUTE_STATIC) && !this_arg) {
6535 if (!strcmp (m->name, ".ctor")) {
6536 if (mono_class_is_abstract (m->klass))
6537 return ERR_INVALID_ARGUMENT;
6538 else {
6539 ERROR_DECL (error);
6540 this_arg = mono_object_new_checked (domain, m->klass, error);
6541 mono_error_assert_ok (error);
6543 } else {
6544 return ERR_INVALID_ARGUMENT;
6548 if (this_arg && !obj_is_of_type (this_arg, m_class_get_byval_arg (m->klass)))
6549 return ERR_INVALID_ARGUMENT;
6551 nargs = decode_int (p, &p, end);
6552 if (nargs != sig->param_count)
6553 return ERR_INVALID_ARGUMENT;
6554 /* Use alloca to get gc tracking */
6555 arg_buf = (guint8 **)g_alloca (nargs * sizeof (gpointer));
6556 memset (arg_buf, 0, nargs * sizeof (gpointer));
6557 args = (gpointer *)g_alloca (nargs * sizeof (gpointer));
6558 for (i = 0; i < nargs; ++i) {
6559 if (MONO_TYPE_IS_REFERENCE (sig->params [i])) {
6560 err = decode_value (sig->params [i], domain, (guint8*)&args [i], p, &p, end, TRUE);
6561 if (err != ERR_NONE)
6562 break;
6563 if (args [i] && ((MonoObject*)args [i])->vtable->domain != domain)
6564 NOT_IMPLEMENTED;
6566 if (sig->params [i]->byref) {
6567 arg_buf [i] = g_newa (guint8, sizeof (gpointer));
6568 *(gpointer*)arg_buf [i] = args [i];
6569 args [i] = arg_buf [i];
6571 } else {
6572 MonoClass *arg_class = mono_class_from_mono_type_internal (sig->params [i]);
6573 arg_buf [i] = (guint8 *)g_alloca (mono_class_instance_size (arg_class));
6574 err = decode_value (sig->params [i], domain, arg_buf [i], p, &p, end, TRUE);
6575 if (err != ERR_NONE)
6576 break;
6577 if (mono_class_is_nullable (arg_class)) {
6578 args [i] = mono_nullable_box (arg_buf [i], arg_class, error);
6579 mono_error_assert_ok (error);
6580 } else {
6581 args [i] = arg_buf [i];
6586 if (i < nargs)
6587 return err;
6589 if (invoke->flags & INVOKE_FLAG_DISABLE_BREAKPOINTS)
6590 tls->disable_breakpoints = TRUE;
6591 else
6592 tls->disable_breakpoints = FALSE;
6595 * Add an LMF frame to link the stack frames on the invoke method with our caller.
6597 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6598 if (invoke->has_ctx) {
6599 /* Setup our lmf */
6600 memset (&ext, 0, sizeof (ext));
6601 ext.kind = MONO_LMFEXT_DEBUGGER_INVOKE;
6602 memcpy (&ext.ctx, &invoke->ctx, sizeof (MonoContext));
6604 mono_push_lmf (&ext);
6606 #endif
6608 mono_stopwatch_start (&watch);
6609 res = mono_runtime_try_invoke (m, m_class_is_valuetype (m->klass) ? (gpointer) this_buf : (gpointer) this_arg, args, &exc, error);
6610 if (!is_ok (error) && exc == NULL) {
6611 exc = (MonoObject*) mono_error_convert_to_exception (error);
6612 } else {
6613 mono_error_cleanup (error); /* FIXME report error */
6615 mono_stopwatch_stop (&watch);
6616 DEBUG_PRINTF (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));
6617 if (exc) {
6618 buffer_add_byte (buf, 0);
6619 buffer_add_value (buf, mono_get_object_type (), &exc, domain);
6620 } else {
6621 gboolean out_this = FALSE;
6622 gboolean out_args = FALSE;
6624 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_THIS) && CHECK_PROTOCOL_VERSION (2, 35))
6625 out_this = TRUE;
6626 if ((invoke->flags & INVOKE_FLAG_RETURN_OUT_ARGS) && CHECK_PROTOCOL_VERSION (2, 35))
6627 out_args = TRUE;
6628 buffer_add_byte (buf, 1 + (out_this ? 2 : 0) + (out_args ? 4 : 0));
6629 if (m->string_ctor) {
6630 buffer_add_value (buf, m_class_get_byval_arg (mono_get_string_class ()), &res, domain);
6631 } else if (sig->ret->type == MONO_TYPE_VOID && !m->string_ctor) {
6632 if (!strcmp (m->name, ".ctor")) {
6633 if (!m_class_is_valuetype (m->klass))
6634 buffer_add_value (buf, mono_get_object_type (), &this_arg, domain);
6635 else
6636 buffer_add_value (buf, m_class_get_byval_arg (m->klass), this_buf, domain);
6637 } else {
6638 buffer_add_value (buf, mono_get_void_type (), NULL, domain);
6640 } else if (MONO_TYPE_IS_REFERENCE (sig->ret)) {
6641 if (sig->ret->byref) {
6642 MonoType* ret_byval = m_class_get_byval_arg (mono_class_from_mono_type_internal (sig->ret));
6643 buffer_add_value (buf, ret_byval, &res, domain);
6644 } else {
6645 buffer_add_value (buf, sig->ret, &res, domain);
6647 } 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) {
6648 if (mono_class_is_nullable (mono_class_from_mono_type_internal (sig->ret))) {
6649 MonoClass *k = mono_class_from_mono_type_internal (sig->ret);
6650 guint8 *nullable_buf = (guint8 *)g_alloca (mono_class_value_size (k, NULL));
6652 g_assert (nullable_buf);
6653 mono_nullable_init (nullable_buf, res, k);
6654 buffer_add_value (buf, sig->ret, nullable_buf, domain);
6655 } else {
6656 g_assert (res);
6658 if (sig->ret->byref) {
6659 MonoType* ret_byval = m_class_get_byval_arg (mono_class_from_mono_type_internal (sig->ret));
6660 buffer_add_value (buf, ret_byval, mono_object_unbox_internal (res), domain);
6661 } else {
6662 buffer_add_value (buf, sig->ret, mono_object_unbox_internal (res), domain);
6665 } else {
6666 NOT_IMPLEMENTED;
6668 if (out_this)
6669 /* Return the new value of the receiver after the call */
6670 buffer_add_value (buf, m_class_get_byval_arg (m->klass), this_buf, domain);
6671 if (out_args) {
6672 buffer_add_int (buf, nargs);
6673 for (i = 0; i < nargs; ++i) {
6674 if (MONO_TYPE_IS_REFERENCE (sig->params [i]))
6675 buffer_add_value (buf, sig->params [i], &args [i], domain);
6676 else if (sig->params [i]->byref)
6677 /* add_value () does an indirection */
6678 buffer_add_value (buf, sig->params [i], &arg_buf [i], domain);
6679 else
6680 buffer_add_value (buf, sig->params [i], arg_buf [i], domain);
6685 tls->disable_breakpoints = FALSE;
6687 #ifdef MONO_ARCH_SOFT_DEBUG_SUPPORTED
6688 if (invoke->has_ctx)
6689 mono_pop_lmf ((MonoLMF*)&ext);
6690 #endif
6692 *endp = p;
6693 // FIXME: byref arguments
6694 // FIXME: varargs
6695 return ERR_NONE;
6699 * invoke_method:
6701 * Invoke the method given by tls->pending_invoke in the current thread.
6703 static void
6704 invoke_method (void)
6706 DebuggerTlsData *tls;
6707 InvokeData *invoke;
6708 int id;
6709 int i, mindex;
6710 ErrorCode err;
6711 Buffer buf;
6712 MonoContext restore_ctx;
6713 guint8 *p;
6715 tls = (DebuggerTlsData *)mono_native_tls_get_value (debugger_tls_id);
6716 g_assert (tls);
6719 * Store the `InvokeData *' in `tls->invoke' until we're done with
6720 * the invocation, so CMD_VM_ABORT_INVOKE can check it.
6723 mono_loader_lock ();
6725 invoke = tls->pending_invoke;
6726 g_assert (invoke);
6727 tls->pending_invoke = NULL;
6729 invoke->last_invoke = tls->invoke;
6730 tls->invoke = invoke;
6732 mono_loader_unlock ();
6734 tls->frames_up_to_date = FALSE;
6736 id = invoke->id;
6738 p = invoke->p;
6739 err = ERR_NONE;
6740 for (mindex = 0; mindex < invoke->nmethods; ++mindex) {
6741 buffer_init (&buf, 128);
6743 if (err) {
6744 /* Fail the other invokes as well */
6745 } else {
6746 err = do_invoke_method (tls, &buf, invoke, p, &p);
6749 if (tls->abort_requested) {
6750 if (CHECK_PROTOCOL_VERSION (2, 42))
6751 err = ERR_INVOKE_ABORTED;
6754 /* Start suspending before sending the reply */
6755 if (mindex == invoke->nmethods - 1) {
6756 if (!(invoke->flags & INVOKE_FLAG_SINGLE_THREADED)) {
6757 for (i = 0; i < invoke->suspend_count; ++i)
6758 suspend_vm ();
6762 send_reply_packet (id, err, &buf);
6764 buffer_free (&buf);
6767 memcpy (&restore_ctx, &invoke->ctx, sizeof (MonoContext));
6769 if (invoke->has_ctx)
6770 save_thread_context (&restore_ctx);
6772 if (invoke->flags & INVOKE_FLAG_SINGLE_THREADED) {
6773 g_assert (tls->resume_count);
6774 tls->resume_count -= invoke->suspend_count;
6777 DEBUG_PRINTF (1, "[%p] Invoke finished (%d), resume_count = %d.\n", (gpointer) (gsize) mono_native_thread_id_get (), err, tls->resume_count);
6780 * Take the loader lock to avoid race conditions with CMD_VM_ABORT_INVOKE:
6782 * It is possible that mono_thread_internal_abort () was called
6783 * after the mono_runtime_invoke_checked() already returned, but it doesn't matter
6784 * because we reset the abort here.
6787 mono_loader_lock ();
6789 if (tls->abort_requested)
6790 mono_thread_internal_reset_abort (tls->thread);
6792 tls->invoke = tls->invoke->last_invoke;
6793 tls->abort_requested = FALSE;
6795 mono_loader_unlock ();
6797 g_free (invoke->p);
6798 g_free (invoke);
6801 static gboolean
6802 is_really_suspended (gpointer key, gpointer value, gpointer user_data)
6804 MonoThread *thread = (MonoThread *)value;
6805 DebuggerTlsData *tls;
6806 gboolean res;
6808 mono_loader_lock ();
6809 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
6810 g_assert (tls);
6811 res = tls->really_suspended;
6812 mono_loader_unlock ();
6814 return res;
6817 static GPtrArray*
6818 get_source_files_for_type (MonoClass *klass)
6820 gpointer iter = NULL;
6821 MonoMethod *method;
6822 MonoDebugSourceInfo *sinfo;
6823 GPtrArray *files;
6824 int i, j;
6826 files = g_ptr_array_new ();
6828 while ((method = mono_class_get_methods (klass, &iter))) {
6829 MonoDebugMethodInfo *minfo = mono_debug_lookup_method (method);
6830 GPtrArray *source_file_list;
6832 if (minfo) {
6833 mono_debug_get_seq_points (minfo, NULL, &source_file_list, NULL, NULL, NULL);
6834 for (j = 0; j < source_file_list->len; ++j) {
6835 sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, j);
6836 for (i = 0; i < files->len; ++i)
6837 if (!strcmp ((const char*)g_ptr_array_index (files, i), (const char*)sinfo->source_file))
6838 break;
6839 if (i == files->len)
6840 g_ptr_array_add (files, g_strdup (sinfo->source_file));
6842 g_ptr_array_free (source_file_list, TRUE);
6846 return files;
6850 typedef struct {
6851 MonoTypeNameParse *info;
6852 gboolean ignore_case;
6853 GPtrArray *res_classes;
6854 GPtrArray *res_domains;
6855 } GetTypesArgs;
6857 static void
6858 get_types (gpointer key, gpointer value, gpointer user_data)
6860 MonoAssembly *ass;
6861 gboolean type_resolve;
6862 MonoType *t;
6863 GSList *tmp;
6864 MonoDomain *domain = (MonoDomain*)key;
6866 if (mono_domain_is_unloading (domain))
6867 return;
6869 MonoAssemblyLoadContext *alc = mono_domain_default_alc (domain);
6870 GetTypesArgs *ud = (GetTypesArgs*)user_data;
6872 mono_domain_assemblies_lock (domain);
6873 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
6874 ass = (MonoAssembly *)tmp->data;
6876 if (ass->image) {
6877 ERROR_DECL (probe_type_error);
6878 /* FIXME really okay to call while holding locks? */
6879 t = mono_reflection_get_type_checked (alc, ass->image, ass->image, ud->info, ud->ignore_case, TRUE, &type_resolve, probe_type_error);
6880 mono_error_cleanup (probe_type_error);
6881 if (t) {
6882 g_ptr_array_add (ud->res_classes, mono_type_get_class_internal (t));
6883 g_ptr_array_add (ud->res_domains, domain);
6887 mono_domain_assemblies_unlock (domain);
6890 typedef struct {
6891 gboolean ignore_case;
6892 char *basename;
6893 GPtrArray *res_classes;
6894 GPtrArray *res_domains;
6895 } GetTypesForSourceFileArgs;
6897 static void
6898 get_types_for_source_file (gpointer key, gpointer value, gpointer user_data)
6900 GHashTableIter iter;
6901 GSList *class_list = NULL;
6902 MonoClass *klass = NULL;
6903 GPtrArray *files = NULL;
6905 GetTypesForSourceFileArgs *ud = (GetTypesForSourceFileArgs*)user_data;
6906 MonoDomain *domain = (MonoDomain*)key;
6908 if (mono_domain_is_unloading (domain))
6909 return;
6911 AgentDomainInfo *info = (AgentDomainInfo *)domain_jit_info (domain)->agent_info;
6913 /* Update 'source_file_to_class' cache */
6914 g_hash_table_iter_init (&iter, info->loaded_classes);
6915 while (g_hash_table_iter_next (&iter, NULL, (void**)&klass)) {
6916 if (!g_hash_table_lookup (info->source_files, klass)) {
6917 files = get_source_files_for_type (klass);
6918 g_hash_table_insert (info->source_files, klass, files);
6920 for (int i = 0; i < files->len; ++i) {
6921 char *s = (char *)g_ptr_array_index (files, i);
6922 char *s2 = dbg_path_get_basename (s);
6923 char *s3;
6925 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, s2);
6926 if (!class_list) {
6927 class_list = g_slist_prepend (class_list, klass);
6928 g_hash_table_insert (info->source_file_to_class, g_strdup (s2), class_list);
6929 } else {
6930 class_list = g_slist_prepend (class_list, klass);
6931 g_hash_table_insert (info->source_file_to_class, s2, class_list);
6934 /* The _ignorecase hash contains the lowercase path */
6935 s3 = strdup_tolower (s2);
6936 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s3);
6937 if (!class_list) {
6938 class_list = g_slist_prepend (class_list, klass);
6939 g_hash_table_insert (info->source_file_to_class_ignorecase, g_strdup (s3), class_list);
6940 } else {
6941 class_list = g_slist_prepend (class_list, klass);
6942 g_hash_table_insert (info->source_file_to_class_ignorecase, s3, class_list);
6945 g_free (s2);
6946 g_free (s3);
6951 if (ud->ignore_case) {
6952 char *s;
6954 s = strdup_tolower (ud->basename);
6955 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class_ignorecase, s);
6956 g_free (s);
6957 } else {
6958 class_list = (GSList *)g_hash_table_lookup (info->source_file_to_class, ud->basename);
6961 for (GSList *l = class_list; l; l = l->next) {
6962 klass = (MonoClass *)l->data;
6964 g_ptr_array_add (ud->res_classes, klass);
6965 g_ptr_array_add (ud->res_domains, domain);
6969 static void add_error_string (Buffer *buf, const char *str)
6971 if (CHECK_PROTOCOL_VERSION (2, 56))
6972 buffer_add_string (buf, str);
6975 static ErrorCode
6976 vm_commands (int command, int id, guint8 *p, guint8 *end, Buffer *buf)
6978 switch (command) {
6979 case CMD_VM_VERSION: {
6980 char *build_info, *version;
6982 build_info = mono_get_runtime_build_info ();
6983 version = g_strdup_printf ("mono %s", build_info);
6985 buffer_add_string (buf, version); /* vm version */
6986 buffer_add_int (buf, MAJOR_VERSION);
6987 buffer_add_int (buf, MINOR_VERSION);
6988 g_free (build_info);
6989 g_free (version);
6990 break;
6992 case CMD_VM_SET_PROTOCOL_VERSION: {
6993 major_version = decode_int (p, &p, end);
6994 minor_version = decode_int (p, &p, end);
6995 protocol_version_set = TRUE;
6996 DEBUG_PRINTF (1, "[dbg] Protocol version %d.%d, client protocol version %d.%d.\n", MAJOR_VERSION, MINOR_VERSION, major_version, minor_version);
6997 break;
6999 case CMD_VM_ALL_THREADS: {
7000 // FIXME: Domains
7001 gboolean remove_gc_finalizing = FALSE;
7002 mono_loader_lock ();
7003 int count = mono_g_hash_table_size (tid_to_thread_obj);
7004 mono_g_hash_table_foreach (tid_to_thread_obj, count_thread_check_gc_finalizer, &remove_gc_finalizing);
7005 if (remove_gc_finalizing)
7006 count--;
7007 buffer_add_int (buf, count);
7008 mono_g_hash_table_foreach (tid_to_thread_obj, add_thread, buf);
7010 mono_loader_unlock ();
7011 break;
7013 case CMD_VM_SUSPEND:
7014 suspend_vm ();
7015 wait_for_suspend ();
7016 break;
7017 case CMD_VM_RESUME:
7018 if (suspend_count == 0)
7019 return ERR_NOT_SUSPENDED;
7020 resume_vm ();
7021 clear_suspended_objs ();
7022 break;
7023 case CMD_VM_DISPOSE:
7024 dispose_vm ();
7025 break;
7026 case CMD_VM_EXIT: {
7027 MonoInternalThread *thread;
7028 DebuggerTlsData *tls;
7029 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7030 MonoClass *env_class;
7031 #endif
7032 MonoMethod *exit_method = NULL;
7033 gpointer *args;
7034 int exit_code;
7036 exit_code = decode_int (p, &p, end);
7038 // FIXME: What if there is a VM_DEATH event request with SUSPEND_ALL ?
7040 /* Have to send a reply before exiting */
7041 send_reply_packet (id, 0, buf);
7043 /* Clear all event requests */
7044 mono_loader_lock ();
7045 while (event_requests->len > 0) {
7046 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, 0);
7048 clear_event_request (req->id, req->event_kind);
7050 mono_loader_unlock ();
7053 * The JDWP documentation says that the shutdown is not orderly. It doesn't
7054 * specify whenever a VM_DEATH event is sent. We currently do an orderly
7055 * shutdown by hijacking a thread to execute Environment.Exit (). This is
7056 * better than doing the shutdown ourselves, since it avoids various races.
7059 suspend_vm ();
7060 wait_for_suspend ();
7062 #ifdef TRY_MANAGED_SYSTEM_ENVIRONMENT_EXIT
7063 env_class = mono_class_try_load_from_name (mono_defaults.corlib, "System", "Environment");
7064 if (env_class) {
7065 ERROR_DECL (error);
7066 exit_method = mono_class_get_method_from_name_checked (env_class, "Exit", 1, 0, error);
7067 mono_error_assert_ok (error);
7069 #endif
7071 mono_loader_lock ();
7072 thread = (MonoInternalThread *)mono_g_hash_table_find (tid_to_thread, is_really_suspended, NULL);
7073 mono_loader_unlock ();
7075 if (thread && exit_method) {
7076 mono_loader_lock ();
7077 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
7078 mono_loader_unlock ();
7080 args = g_new0 (gpointer, 1);
7081 args [0] = g_malloc (sizeof (int));
7082 *(int*)(args [0]) = exit_code;
7084 tls->pending_invoke = g_new0 (InvokeData, 1);
7085 tls->pending_invoke->method = exit_method;
7086 tls->pending_invoke->args = args;
7087 tls->pending_invoke->nmethods = 1;
7089 while (suspend_count > 0)
7090 resume_vm ();
7091 } else {
7093 * No thread found, do it ourselves.
7094 * FIXME: This can race with normal shutdown etc.
7096 while (suspend_count > 0)
7097 resume_vm ();
7099 if (!mono_runtime_try_shutdown ())
7100 break;
7102 mono_environment_exitcode_set (exit_code);
7104 /* Suspend all managed threads since the runtime is going away */
7105 #ifndef ENABLE_NETCORE
7106 DEBUG_PRINTF (1, "Suspending all threads...\n");
7107 mono_thread_suspend_all_other_threads ();
7108 #endif
7109 DEBUG_PRINTF (1, "Shutting down the runtime...\n");
7110 mono_runtime_quit_internal ();
7111 transport_close2 ();
7112 DEBUG_PRINTF (1, "Exiting...\n");
7114 exit (exit_code);
7116 break;
7118 case CMD_VM_INVOKE_METHOD:
7119 case CMD_VM_INVOKE_METHODS: {
7120 int objid = decode_objid (p, &p, end);
7121 MonoThread *thread;
7122 DebuggerTlsData *tls;
7123 int i, count, flags, nmethods;
7124 ErrorCode err;
7126 err = get_object (objid, (MonoObject**)&thread);
7127 if (err != ERR_NONE)
7128 return err;
7130 flags = decode_int (p, &p, end);
7132 if (command == CMD_VM_INVOKE_METHODS)
7133 nmethods = decode_int (p, &p, end);
7134 else
7135 nmethods = 1;
7137 // Wait for suspending if it already started
7138 if (suspend_count)
7139 wait_for_suspend ();
7140 if (!is_suspended ())
7141 return ERR_NOT_SUSPENDED;
7143 mono_loader_lock ();
7144 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7145 mono_loader_unlock ();
7146 g_assert (tls);
7148 if (!tls->really_suspended)
7149 /* The thread is still running native code, can't do invokes */
7150 return ERR_NOT_SUSPENDED;
7153 * Store the invoke data into tls, the thread will execute it after it is
7154 * resumed.
7156 if (tls->pending_invoke)
7157 return ERR_NOT_SUSPENDED;
7158 tls->pending_invoke = g_new0 (InvokeData, 1);
7159 tls->pending_invoke->id = id;
7160 tls->pending_invoke->flags = flags;
7161 tls->pending_invoke->p = (guint8 *)g_malloc (end - p);
7162 memcpy (tls->pending_invoke->p, p, end - p);
7163 tls->pending_invoke->endp = tls->pending_invoke->p + (end - p);
7164 tls->pending_invoke->suspend_count = suspend_count;
7165 tls->pending_invoke->nmethods = nmethods;
7167 if (flags & INVOKE_FLAG_SINGLE_THREADED) {
7168 resume_thread (THREAD_TO_INTERNAL (thread));
7170 else {
7171 count = suspend_count;
7172 for (i = 0; i < count; ++i)
7173 resume_vm ();
7175 break;
7177 case CMD_VM_ABORT_INVOKE: {
7178 int objid = decode_objid (p, &p, end);
7179 MonoThread *thread;
7180 DebuggerTlsData *tls;
7181 int invoke_id;
7182 ErrorCode err;
7184 err = get_object (objid, (MonoObject**)&thread);
7185 if (err != ERR_NONE)
7186 return err;
7188 invoke_id = decode_int (p, &p, end);
7190 mono_loader_lock ();
7191 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL (thread));
7192 g_assert (tls);
7194 if (tls->abort_requested) {
7195 DEBUG_PRINTF (1, "Abort already requested.\n");
7196 mono_loader_unlock ();
7197 break;
7201 * Check whether we're still inside the mono_runtime_invoke_checked() and that it's
7202 * actually the correct invocation.
7204 * Careful, we do not stop the thread that's doing the invocation, so we can't
7205 * inspect its stack. However, invoke_method() also acquires the loader lock
7206 * when it's done, so we're safe here.
7210 if (!tls->invoke || (tls->invoke->id != invoke_id)) {
7211 mono_loader_unlock ();
7212 return ERR_NO_INVOCATION;
7215 tls->abort_requested = TRUE;
7217 mono_thread_internal_abort (THREAD_TO_INTERNAL (thread), FALSE);
7218 mono_loader_unlock ();
7219 break;
7222 case CMD_VM_SET_KEEPALIVE: {
7223 int timeout = decode_int (p, &p, end);
7224 agent_config.keepalive = timeout;
7225 // FIXME:
7226 #ifndef DISABLE_SOCKET_TRANSPORT
7227 set_keepalive ();
7228 #else
7229 NOT_IMPLEMENTED;
7230 #endif
7231 break;
7233 case CMD_VM_GET_TYPES_FOR_SOURCE_FILE: {
7234 int i;
7235 char *fname, *basename;
7236 gboolean ignore_case;
7237 GPtrArray *res_classes, *res_domains;
7239 fname = decode_string (p, &p, end);
7240 ignore_case = decode_byte (p, &p, end);
7242 basename = dbg_path_get_basename (fname);
7244 res_classes = g_ptr_array_new ();
7245 res_domains = g_ptr_array_new ();
7247 mono_loader_lock ();
7248 GetTypesForSourceFileArgs args;
7249 memset (&args, 0, sizeof (args));
7250 args.ignore_case = ignore_case;
7251 args.basename = basename;
7252 args.res_classes = res_classes;
7253 args.res_domains = res_domains;
7254 mono_de_foreach_domain (get_types_for_source_file, &args);
7255 mono_loader_unlock ();
7257 g_free (fname);
7258 g_free (basename);
7260 buffer_add_int (buf, res_classes->len);
7261 for (i = 0; i < res_classes->len; ++i)
7262 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7263 g_ptr_array_free (res_classes, TRUE);
7264 g_ptr_array_free (res_domains, TRUE);
7265 break;
7267 case CMD_VM_GET_TYPES: {
7268 ERROR_DECL (error);
7269 int i;
7270 char *name;
7271 gboolean ignore_case;
7272 GPtrArray *res_classes, *res_domains;
7273 MonoTypeNameParse info;
7275 name = decode_string (p, &p, end);
7276 ignore_case = decode_byte (p, &p, end);
7278 if (!mono_reflection_parse_type_checked (name, &info, error)) {
7279 add_error_string (buf, mono_error_get_message (error));
7280 mono_error_cleanup (error);
7281 g_free (name);
7282 mono_reflection_free_type_info (&info);
7283 return ERR_INVALID_ARGUMENT;
7286 res_classes = g_ptr_array_new ();
7287 res_domains = g_ptr_array_new ();
7289 mono_loader_lock ();
7291 GetTypesArgs args;
7292 memset (&args, 0, sizeof (args));
7293 args.info = &info;
7294 args.ignore_case = ignore_case;
7295 args.res_classes = res_classes;
7296 args.res_domains = res_domains;
7298 mono_de_foreach_domain (get_types, &args);
7300 mono_loader_unlock ();
7302 g_free (name);
7303 mono_reflection_free_type_info (&info);
7305 buffer_add_int (buf, res_classes->len);
7306 for (i = 0; i < res_classes->len; ++i)
7307 buffer_add_typeid (buf, (MonoDomain *)g_ptr_array_index (res_domains, i), (MonoClass *)g_ptr_array_index (res_classes, i));
7308 g_ptr_array_free (res_classes, TRUE);
7309 g_ptr_array_free (res_domains, TRUE);
7310 break;
7312 case CMD_VM_START_BUFFERING:
7313 case CMD_VM_STOP_BUFFERING:
7314 /* Handled in the main loop */
7315 break;
7316 default:
7317 return ERR_NOT_IMPLEMENTED;
7320 return ERR_NONE;
7323 static ErrorCode
7324 event_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7326 ErrorCode err;
7327 ERROR_DECL (error);
7329 switch (command) {
7330 case CMD_EVENT_REQUEST_SET: {
7331 EventRequest *req;
7332 int i, event_kind, suspend_policy, nmodifiers;
7333 ModifierKind mod;
7334 MonoMethod *method;
7335 long location = 0;
7336 MonoThread *step_thread;
7337 int step_thread_id = 0;
7338 StepDepth depth = STEP_DEPTH_INTO;
7339 StepSize size = STEP_SIZE_MIN;
7340 StepFilter filter = STEP_FILTER_NONE;
7341 MonoDomain *domain;
7342 Modifier *modifier;
7344 event_kind = decode_byte (p, &p, end);
7345 suspend_policy = decode_byte (p, &p, end);
7346 nmodifiers = decode_byte (p, &p, end);
7348 req = (EventRequest *)g_malloc0 (sizeof (EventRequest) + (nmodifiers * sizeof (Modifier)));
7349 req->id = mono_atomic_inc_i32 (&event_request_id);
7350 req->event_kind = event_kind;
7351 req->suspend_policy = suspend_policy;
7352 req->nmodifiers = nmodifiers;
7354 method = NULL;
7355 for (i = 0; i < nmodifiers; ++i) {
7356 mod = (ModifierKind)decode_byte (p, &p, end);
7358 req->modifiers [i].kind = mod;
7359 if (mod == MOD_KIND_COUNT) {
7360 req->modifiers [i].data.count = decode_int (p, &p, end);
7361 } else if (mod == MOD_KIND_LOCATION_ONLY) {
7362 method = decode_methodid (p, &p, end, &domain, &err);
7363 if (err != ERR_NONE)
7364 return err;
7365 location = decode_long (p, &p, end);
7366 } else if (mod == MOD_KIND_STEP) {
7367 step_thread_id = decode_id (p, &p, end);
7368 size = (StepSize)decode_int (p, &p, end);
7369 depth = (StepDepth)decode_int (p, &p, end);
7370 if (CHECK_PROTOCOL_VERSION (2, 16))
7371 filter = (StepFilter)decode_int (p, &p, end);
7372 req->modifiers [i].data.filter = filter;
7373 if (!CHECK_PROTOCOL_VERSION (2, 26) && (req->modifiers [i].data.filter & STEP_FILTER_DEBUGGER_HIDDEN))
7374 /* Treat STEP_THOUGH the same as HIDDEN */
7375 req->modifiers [i].data.filter = (StepFilter)(req->modifiers [i].data.filter | STEP_FILTER_DEBUGGER_STEP_THROUGH);
7376 } else if (mod == MOD_KIND_THREAD_ONLY) {
7377 int id = decode_id (p, &p, end);
7379 err = get_object (id, (MonoObject**)&req->modifiers [i].data.thread);
7380 if (err != ERR_NONE) {
7381 g_free (req);
7382 return err;
7384 } else if (mod == MOD_KIND_EXCEPTION_ONLY) {
7385 MonoClass *exc_class = decode_typeid (p, &p, end, &domain, &err);
7387 if (err != ERR_NONE)
7388 return err;
7389 req->modifiers [i].caught = decode_byte (p, &p, end);
7390 req->modifiers [i].uncaught = decode_byte (p, &p, end);
7391 if (CHECK_PROTOCOL_VERSION (2, 25))
7392 req->modifiers [i].subclasses = decode_byte (p, &p, end);
7393 else
7394 req->modifiers [i].subclasses = TRUE;
7395 if (exc_class) {
7396 req->modifiers [i].data.exc_class = exc_class;
7398 if (!mono_class_is_assignable_from_internal (mono_defaults.exception_class, exc_class)) {
7399 g_free (req);
7400 return ERR_INVALID_ARGUMENT;
7403 if (CHECK_PROTOCOL_VERSION (2, 54)) {
7404 req->modifiers [i].not_filtered_feature = decode_byte (p, &p, end);
7405 req->modifiers [i].everything_else = decode_byte (p, &p, end);
7406 DEBUG_PRINTF (1, "[dbg] \tEXCEPTION_ONLY 2 filter (%s%s%s%s).\n", exc_class ? m_class_get_name (exc_class) : (req->modifiers [i].everything_else ? "everything else" : "all"), req->modifiers [i].caught ? ", caught" : "", req->modifiers [i].uncaught ? ", uncaught" : "", req->modifiers [i].subclasses ? ", include-subclasses" : "");
7407 } else {
7408 req->modifiers [i].not_filtered_feature = FALSE;
7409 req->modifiers [i].everything_else = FALSE;
7410 DEBUG_PRINTF (1, "[dbg] \tEXCEPTION_ONLY filter (%s%s%s%s).\n", exc_class ? m_class_get_name (exc_class) : "all", req->modifiers [i].caught ? ", caught" : "", req->modifiers [i].uncaught ? ", uncaught" : "", req->modifiers [i].subclasses ? ", include-subclasses" : "");
7413 } else if (mod == MOD_KIND_ASSEMBLY_ONLY) {
7414 int n = decode_int (p, &p, end);
7415 int j;
7417 // +1 because we don't know length and we use last element to check for end
7418 req->modifiers [i].data.assemblies = g_new0 (MonoAssembly*, n + 1);
7419 for (j = 0; j < n; ++j) {
7420 req->modifiers [i].data.assemblies [j] = decode_assemblyid (p, &p, end, &domain, &err);
7421 if (err != ERR_NONE) {
7422 g_free (req->modifiers [i].data.assemblies);
7423 return err;
7426 } else if (mod == MOD_KIND_SOURCE_FILE_ONLY) {
7427 int n = decode_int (p, &p, end);
7428 int j;
7430 modifier = &req->modifiers [i];
7431 modifier->data.source_files = g_hash_table_new (g_str_hash, g_str_equal);
7432 for (j = 0; j < n; ++j) {
7433 char *s = decode_string (p, &p, end);
7434 char *s2;
7436 if (s) {
7437 s2 = strdup_tolower (s);
7438 g_hash_table_insert (modifier->data.source_files, s2, s2);
7439 g_free (s);
7442 } else if (mod == MOD_KIND_TYPE_NAME_ONLY) {
7443 int n = decode_int (p, &p, end);
7444 int j;
7446 modifier = &req->modifiers [i];
7447 modifier->data.type_names = g_hash_table_new (g_str_hash, g_str_equal);
7448 for (j = 0; j < n; ++j) {
7449 char *s = decode_string (p, &p, end);
7451 if (s)
7452 g_hash_table_insert (modifier->data.type_names, s, s);
7454 } else {
7455 g_free (req);
7456 return ERR_NOT_IMPLEMENTED;
7460 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7461 g_assert (method);
7463 req->info = mono_de_set_breakpoint (method, location, req, error);
7464 if (!is_ok (error)) {
7465 g_free (req);
7466 DEBUG_PRINTF (1, "[dbg] Failed to set breakpoint: %s\n", mono_error_get_message (error));
7467 mono_error_cleanup (error);
7468 return ERR_NO_SEQ_POINT_AT_IL_OFFSET;
7470 } else if (req->event_kind == EVENT_KIND_STEP) {
7471 g_assert (step_thread_id);
7473 err = get_object (step_thread_id, (MonoObject**)&step_thread);
7474 if (err != ERR_NONE) {
7475 g_free (req);
7476 return err;
7479 mono_loader_lock ();
7480 DebuggerTlsData *tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, THREAD_TO_INTERNAL(step_thread));
7481 mono_loader_unlock ();
7482 g_assert (tls);
7484 if (tls->terminated) {
7485 /* if the thread is already terminated ignore the single step */
7486 buffer_add_int (buf, req->id);
7487 return ERR_NONE;
7490 err = (ErrorCode)mono_de_ss_create (THREAD_TO_INTERNAL (step_thread), size, depth, filter, req);
7491 if (err != ERR_NONE) {
7492 g_free (req);
7493 return err;
7495 } else if (req->event_kind == EVENT_KIND_METHOD_ENTRY) {
7496 req->info = mono_de_set_breakpoint (NULL, METHOD_ENTRY_IL_OFFSET, req, NULL);
7497 } else if (req->event_kind == EVENT_KIND_METHOD_EXIT) {
7498 req->info = mono_de_set_breakpoint (NULL, METHOD_EXIT_IL_OFFSET, req, NULL);
7499 } else if (req->event_kind == EVENT_KIND_EXCEPTION) {
7500 } else if (req->event_kind == EVENT_KIND_TYPE_LOAD) {
7501 } else {
7502 if (req->nmodifiers) {
7503 g_free (req);
7504 return ERR_NOT_IMPLEMENTED;
7508 mono_loader_lock ();
7509 g_ptr_array_add (event_requests, req);
7511 if (agent_config.defer) {
7512 /* Transmit cached data to the client on receipt of the event request */
7513 switch (req->event_kind) {
7514 case EVENT_KIND_APPDOMAIN_CREATE:
7515 /* Emit load events for currently loaded domains */
7516 mono_de_foreach_domain (emit_appdomain_load, NULL);
7517 break;
7518 case EVENT_KIND_ASSEMBLY_LOAD:
7519 /* Emit load events for currently loaded assemblies */
7520 mono_domain_foreach (send_assemblies_for_domain, NULL);
7521 break;
7522 case EVENT_KIND_THREAD_START:
7523 /* Emit start events for currently started threads */
7524 mono_g_hash_table_foreach (tid_to_thread, emit_thread_start, NULL);
7525 break;
7526 case EVENT_KIND_TYPE_LOAD:
7527 /* Emit type load events for currently loaded types */
7528 mono_domain_foreach (send_types_for_domain, NULL);
7529 break;
7530 default:
7531 break;
7534 mono_loader_unlock ();
7536 buffer_add_int (buf, req->id);
7537 break;
7539 case CMD_EVENT_REQUEST_CLEAR: {
7540 int etype = decode_byte (p, &p, end);
7541 int req_id = decode_int (p, &p, end);
7543 // FIXME: Make a faster mapping from req_id to request
7544 mono_loader_lock ();
7545 clear_event_request (req_id, etype);
7546 mono_loader_unlock ();
7547 break;
7549 case CMD_EVENT_REQUEST_CLEAR_ALL_BREAKPOINTS: {
7550 int i;
7552 mono_loader_lock ();
7553 i = 0;
7554 while (i < event_requests->len) {
7555 EventRequest *req = (EventRequest *)g_ptr_array_index (event_requests, i);
7557 if (req->event_kind == EVENT_KIND_BREAKPOINT) {
7558 mono_de_clear_breakpoint ((MonoBreakpoint *)req->info);
7560 g_ptr_array_remove_index_fast (event_requests, i);
7561 g_free (req);
7562 } else {
7563 i ++;
7566 mono_loader_unlock ();
7567 break;
7569 default:
7570 return ERR_NOT_IMPLEMENTED;
7573 return ERR_NONE;
7576 static ErrorCode
7577 domain_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7579 ErrorCode err;
7580 MonoDomain *domain;
7582 switch (command) {
7583 case CMD_APPDOMAIN_GET_ROOT_DOMAIN: {
7584 buffer_add_domainid (buf, mono_get_root_domain ());
7585 break;
7587 case CMD_APPDOMAIN_GET_FRIENDLY_NAME: {
7588 domain = decode_domainid (p, &p, end, NULL, &err);
7589 if (err != ERR_NONE)
7590 return err;
7591 buffer_add_string (buf, domain->friendly_name);
7592 break;
7594 case CMD_APPDOMAIN_GET_ASSEMBLIES: {
7595 GSList *tmp;
7596 MonoAssembly *ass;
7597 int count;
7599 domain = decode_domainid (p, &p, end, NULL, &err);
7600 if (err != ERR_NONE)
7601 return err;
7602 mono_domain_assemblies_lock (domain);
7603 count = 0;
7604 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7605 count ++;
7607 buffer_add_int (buf, count);
7608 for (tmp = domain->domain_assemblies; tmp; tmp = tmp->next) {
7609 ass = (MonoAssembly *)tmp->data;
7610 buffer_add_assemblyid (buf, domain, ass);
7612 mono_domain_assemblies_unlock (domain);
7613 break;
7615 case CMD_APPDOMAIN_GET_ENTRY_ASSEMBLY: {
7616 domain = decode_domainid (p, &p, end, NULL, &err);
7617 if (err != ERR_NONE)
7618 return err;
7620 buffer_add_assemblyid (buf, domain, domain->entry_assembly);
7621 break;
7623 case CMD_APPDOMAIN_GET_CORLIB: {
7624 domain = decode_domainid (p, &p, end, NULL, &err);
7625 if (err != ERR_NONE)
7626 return err;
7628 buffer_add_assemblyid (buf, domain, m_class_get_image (domain->domain->mbr.obj.vtable->klass)->assembly);
7629 break;
7631 case CMD_APPDOMAIN_CREATE_STRING: {
7632 char *s;
7633 MonoString *o;
7634 ERROR_DECL (error);
7636 domain = decode_domainid (p, &p, end, NULL, &err);
7637 if (err != ERR_NONE)
7638 return err;
7639 s = decode_string (p, &p, end);
7641 o = mono_string_new_checked (domain, s, error);
7642 if (!is_ok (error)) {
7643 DEBUG_PRINTF (1, "[dbg] Failed to allocate String object '%s': %s\n", s, mono_error_get_message (error));
7644 mono_error_cleanup (error);
7645 return ERR_INVALID_OBJECT;
7647 buffer_add_objid (buf, (MonoObject*)o);
7648 break;
7650 case CMD_APPDOMAIN_CREATE_BYTE_ARRAY: {
7651 ERROR_DECL (error);
7652 MonoArray *arr;
7653 gpointer elem;
7654 domain = decode_domainid (p, &p, end, NULL, &err);
7655 uintptr_t size = 0;
7656 int len = decode_int (p, &p, end);
7657 size = len;
7658 arr = mono_array_new_full_checked (mono_domain_get (), mono_class_create_array (mono_get_byte_class(), 1), &size, NULL, error);
7659 elem = mono_array_addr_internal (arr, guint8, 0);
7660 memcpy (elem, p, len);
7661 p += len;
7662 buffer_add_objid (buf, (MonoObject*) arr);
7663 break;
7665 case CMD_APPDOMAIN_CREATE_BOXED_VALUE: {
7666 ERROR_DECL (error);
7667 MonoClass *klass;
7668 MonoDomain *domain2;
7669 MonoObject *o;
7671 domain = decode_domainid (p, &p, end, NULL, &err);
7672 if (err != ERR_NONE)
7673 return err;
7674 klass = decode_typeid (p, &p, end, &domain2, &err);
7675 if (err != ERR_NONE)
7676 return err;
7678 // FIXME:
7679 g_assert (domain == domain2);
7681 o = mono_object_new_checked (domain, klass, error);
7682 mono_error_assert_ok (error);
7684 err = decode_value (m_class_get_byval_arg (klass), domain, (guint8 *)mono_object_unbox_internal (o), p, &p, end, TRUE);
7685 if (err != ERR_NONE)
7686 return err;
7688 buffer_add_objid (buf, o);
7689 break;
7691 default:
7692 return ERR_NOT_IMPLEMENTED;
7695 return ERR_NONE;
7698 static ErrorCode
7699 get_assembly_object_command (MonoDomain *domain, MonoAssembly *ass, Buffer *buf, MonoError *error)
7701 HANDLE_FUNCTION_ENTER();
7702 ErrorCode err = ERR_NONE;
7703 error_init (error);
7704 MonoReflectionAssemblyHandle o = mono_assembly_get_object_handle (domain, ass, error);
7705 if (MONO_HANDLE_IS_NULL (o)) {
7706 err = ERR_INVALID_OBJECT;
7707 goto leave;
7709 buffer_add_objid (buf, MONO_HANDLE_RAW (MONO_HANDLE_CAST (MonoObject, o)));
7710 leave:
7711 HANDLE_FUNCTION_RETURN_VAL (err);
7715 static ErrorCode
7716 assembly_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7718 ErrorCode err;
7719 MonoAssembly *ass;
7720 MonoDomain *domain;
7722 ass = decode_assemblyid (p, &p, end, &domain, &err);
7723 if (err != ERR_NONE)
7724 return err;
7726 switch (command) {
7727 case CMD_ASSEMBLY_GET_LOCATION: {
7728 buffer_add_string (buf, mono_image_get_filename (ass->image));
7729 break;
7731 case CMD_ASSEMBLY_GET_ENTRY_POINT: {
7732 guint32 token;
7733 MonoMethod *m;
7735 if (ass->image->dynamic) {
7736 buffer_add_id (buf, 0);
7737 } else {
7738 token = mono_image_get_entry_point (ass->image);
7739 if (token == 0) {
7740 buffer_add_id (buf, 0);
7741 } else {
7742 ERROR_DECL (error);
7743 m = mono_get_method_checked (ass->image, token, NULL, NULL, error);
7744 if (!m)
7745 mono_error_cleanup (error); /* FIXME don't swallow the error */
7746 buffer_add_methodid (buf, domain, m);
7749 break;
7751 case CMD_ASSEMBLY_GET_MANIFEST_MODULE: {
7752 buffer_add_moduleid (buf, domain, ass->image);
7753 break;
7755 case CMD_ASSEMBLY_GET_OBJECT: {
7756 ERROR_DECL (error);
7757 err = get_assembly_object_command (domain, ass, buf, error);
7758 mono_error_cleanup (error);
7759 return err;
7761 case CMD_ASSEMBLY_GET_DOMAIN: {
7762 buffer_add_domainid (buf, domain);
7763 break;
7765 case CMD_ASSEMBLY_GET_TYPE: {
7766 ERROR_DECL (error);
7767 char *s = decode_string (p, &p, end);
7768 char* original_s = g_strdup_printf ("\"%s\"", s);
7770 gboolean ignorecase = decode_byte (p, &p, end);
7771 MonoTypeNameParse info;
7772 MonoType *t;
7773 gboolean type_resolve, res;
7774 MonoDomain *d = mono_domain_get ();
7775 MonoAssemblyLoadContext *alc = mono_domain_default_alc (d);
7777 /* This is needed to be able to find referenced assemblies */
7778 res = mono_domain_set_fast (domain, FALSE);
7779 g_assert (res);
7781 if (!mono_reflection_parse_type_checked (s, &info, error)) {
7782 mono_error_cleanup (error);
7783 t = NULL;
7784 } else {
7785 if (info.assembly.name) {
7786 mono_reflection_free_type_info (&info);
7787 g_free (s);
7788 mono_domain_set_fast (d, TRUE);
7789 char* error_msg = g_strdup_printf ("Unexpected assembly-qualified type %s was provided", original_s);
7790 add_error_string (buf, error_msg);
7791 g_free (error_msg);
7792 g_free (original_s);
7793 return ERR_INVALID_ARGUMENT;
7795 t = mono_reflection_get_type_checked (alc, ass->image, ass->image, &info, ignorecase, TRUE, &type_resolve, error);
7796 if (!is_ok (error)) {
7797 mono_error_cleanup (error); /* FIXME don't swallow the error */
7798 mono_reflection_free_type_info (&info);
7799 g_free (s);
7800 mono_domain_set_fast (d, TRUE);
7801 char* error_msg = g_strdup_printf ("Invalid type name %s", original_s);
7802 add_error_string (buf, error_msg);
7803 g_free (error_msg);
7804 g_free (original_s);
7805 return ERR_INVALID_ARGUMENT;
7808 buffer_add_typeid (buf, domain, t ? mono_class_from_mono_type_internal (t) : NULL);
7809 mono_reflection_free_type_info (&info);
7810 g_free (s);
7811 g_free (original_s);
7812 mono_domain_set_fast (d, TRUE);
7814 break;
7816 case CMD_ASSEMBLY_GET_NAME: {
7817 gchar *name;
7818 MonoAssembly *mass = ass;
7820 name = g_strdup_printf (
7821 "%s, Version=%d.%d.%d.%d, Culture=%s, PublicKeyToken=%s%s",
7822 mass->aname.name,
7823 mass->aname.major, mass->aname.minor, mass->aname.build, mass->aname.revision,
7824 mass->aname.culture && *mass->aname.culture? mass->aname.culture: "neutral",
7825 mass->aname.public_key_token [0] ? (char *)mass->aname.public_key_token : "null",
7826 (mass->aname.flags & ASSEMBLYREF_RETARGETABLE_FLAG) ? ", Retargetable=Yes" : "");
7828 buffer_add_string (buf, name);
7829 g_free (name);
7830 break;
7832 case CMD_ASSEMBLY_GET_METADATA_BLOB: {
7833 MonoImage* image = ass->image;
7834 if (ass->dynamic) {
7835 return ERR_NOT_IMPLEMENTED;
7837 buffer_add_byte_array (buf, (guint8*)image->raw_data, image->raw_data_len);
7838 break;
7840 case CMD_ASSEMBLY_GET_IS_DYNAMIC: {
7841 buffer_add_byte (buf, ass->dynamic);
7842 break;
7844 case CMD_ASSEMBLY_GET_PDB_BLOB: {
7845 MonoImage* image = ass->image;
7846 MonoDebugHandle* handle = mono_debug_get_handle (image);
7847 if (!handle) {
7848 return ERR_INVALID_ARGUMENT;
7850 MonoPPDBFile* ppdb = handle->ppdb;
7851 if (ppdb) {
7852 image = mono_ppdb_get_image (ppdb);
7853 buffer_add_byte_array (buf, (guint8*)image->raw_data, image->raw_data_len);
7854 } else {
7855 buffer_add_byte_array (buf, NULL, 0);
7857 break;
7859 case CMD_ASSEMBLY_GET_TYPE_FROM_TOKEN: {
7860 if (ass->dynamic) {
7861 return ERR_NOT_IMPLEMENTED;
7863 guint32 token = decode_int (p, &p, end);
7864 ERROR_DECL (error);
7865 error_init (error);
7866 MonoClass* mono_class = mono_class_get_checked (ass->image, token, error);
7867 if (!is_ok (error)) {
7868 add_error_string (buf, mono_error_get_message (error));
7869 mono_error_cleanup (error);
7870 return ERR_INVALID_ARGUMENT;
7872 buffer_add_typeid (buf, domain, mono_class);
7873 mono_error_cleanup (error);
7874 break;
7876 case CMD_ASSEMBLY_GET_METHOD_FROM_TOKEN: {
7877 if (ass->dynamic) {
7878 return ERR_NOT_IMPLEMENTED;
7880 guint32 token = decode_int (p, &p, end);
7881 ERROR_DECL (error);
7882 error_init (error);
7883 MonoMethod* mono_method = mono_get_method_checked (ass->image, token, NULL, NULL, error);
7884 if (!is_ok (error)) {
7885 add_error_string (buf, mono_error_get_message (error));
7886 mono_error_cleanup (error);
7887 return ERR_INVALID_ARGUMENT;
7889 buffer_add_methodid (buf, domain, mono_method);
7890 mono_error_cleanup (error);
7891 break;
7893 case CMD_ASSEMBLY_HAS_DEBUG_INFO: {
7894 buffer_add_byte (buf, !ass->dynamic && mono_debug_image_has_debug_info (ass->image));
7895 break;
7897 default:
7898 return ERR_NOT_IMPLEMENTED;
7901 return ERR_NONE;
7904 static ErrorCode
7905 module_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7907 ErrorCode err;
7908 MonoDomain *domain;
7910 switch (command) {
7911 case CMD_MODULE_GET_INFO: {
7912 MonoImage *image = decode_moduleid (p, &p, end, &domain, &err);
7913 char *basename, *sourcelink = NULL;
7915 if (CHECK_PROTOCOL_VERSION (2, 48))
7916 sourcelink = mono_debug_image_get_sourcelink (image);
7918 basename = g_path_get_basename (image->name);
7919 buffer_add_string (buf, basename); // name
7920 buffer_add_string (buf, image->module_name); // scopename
7921 buffer_add_string (buf, image->name); // fqname
7922 buffer_add_string (buf, mono_image_get_guid (image)); // guid
7923 buffer_add_assemblyid (buf, domain, image->assembly); // assembly
7924 if (CHECK_PROTOCOL_VERSION (2, 48))
7925 buffer_add_string (buf, sourcelink);
7926 g_free (basename);
7927 g_free (sourcelink);
7928 break;
7930 default:
7931 return ERR_NOT_IMPLEMENTED;
7934 return ERR_NONE;
7937 static ErrorCode
7938 field_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
7940 ErrorCode err;
7941 MonoDomain *domain;
7943 switch (command) {
7944 case CMD_FIELD_GET_INFO: {
7945 MonoClassField *f = decode_fieldid (p, &p, end, &domain, &err);
7947 buffer_add_string (buf, f->name);
7948 buffer_add_typeid (buf, domain, f->parent);
7949 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (f->type));
7950 buffer_add_int (buf, f->type->attrs);
7951 break;
7953 default:
7954 return ERR_NOT_IMPLEMENTED;
7957 return ERR_NONE;
7960 static void
7961 buffer_add_cattr_arg (Buffer *buf, MonoType *t, MonoDomain *domain, MonoObject *val)
7963 if (val && val->vtable->klass == mono_defaults.runtimetype_class) {
7964 /* Special case these so the client doesn't have to handle Type objects */
7966 buffer_add_byte (buf, VALUE_TYPE_ID_TYPE);
7967 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (((MonoReflectionType*)val)->type));
7968 } else if (MONO_TYPE_IS_REFERENCE (t))
7969 buffer_add_value (buf, t, &val, domain);
7970 else
7971 buffer_add_value (buf, t, mono_object_unbox_internal (val), domain);
7974 static ErrorCode
7975 buffer_add_cattrs (Buffer *buf, MonoDomain *domain, MonoImage *image, MonoClass *attr_klass, MonoCustomAttrInfo *cinfo)
7977 int i, j;
7978 int nattrs = 0;
7980 if (!cinfo) {
7981 buffer_add_int (buf, 0);
7982 return ERR_NONE;
7985 SETUP_ICALL_FUNCTION;
7987 for (i = 0; i < cinfo->num_attrs; ++i) {
7988 if (!attr_klass || mono_class_has_parent (cinfo->attrs [i].ctor->klass, attr_klass))
7989 nattrs ++;
7991 buffer_add_int (buf, nattrs);
7993 for (i = 0; i < cinfo->num_attrs; ++i) {
7994 MonoCustomAttrEntry *attr = &cinfo->attrs [i];
7995 if (!attr_klass || mono_class_has_parent (attr->ctor->klass, attr_klass)) {
7996 MonoArray *typed_args, *named_args;
7997 MonoArrayHandleOut typed_args_h, named_args_h;
7998 MonoObjectHandle val_h;
7999 MonoType *t;
8000 CattrNamedArg *arginfo = NULL;
8001 ERROR_DECL (error);
8003 SETUP_ICALL_FRAME;
8004 typed_args_h = MONO_HANDLE_NEW (MonoArray, NULL);
8005 named_args_h = MONO_HANDLE_NEW (MonoArray, NULL);
8006 val_h = MONO_HANDLE_NEW (MonoObject, NULL);
8008 mono_reflection_create_custom_attr_data_args (image, attr->ctor, attr->data, attr->data_size, typed_args_h, named_args_h, &arginfo, error);
8009 if (!is_ok (error)) {
8010 DEBUG_PRINTF (2, "[dbg] mono_reflection_create_custom_attr_data_args () failed with: '%s'\n", mono_error_get_message (error));
8011 mono_error_cleanup (error);
8012 CLEAR_ICALL_FRAME;
8013 return ERR_LOADER_ERROR;
8015 typed_args = MONO_HANDLE_RAW (typed_args_h);
8016 named_args = MONO_HANDLE_RAW (named_args_h);
8018 buffer_add_methodid (buf, domain, attr->ctor);
8020 /* Ctor args */
8021 if (typed_args) {
8022 buffer_add_int (buf, mono_array_length_internal (typed_args));
8023 for (j = 0; j < mono_array_length_internal (typed_args); ++j) {
8024 MonoObject *val = mono_array_get_internal (typed_args, MonoObject*, j);
8025 MONO_HANDLE_ASSIGN_RAW (val_h, val);
8027 t = mono_method_signature_internal (attr->ctor)->params [j];
8029 buffer_add_cattr_arg (buf, t, domain, val);
8031 } else {
8032 buffer_add_int (buf, 0);
8035 /* Named args */
8036 if (named_args) {
8037 buffer_add_int (buf, mono_array_length_internal (named_args));
8039 for (j = 0; j < mono_array_length_internal (named_args); ++j) {
8040 MonoObject *val = mono_array_get_internal (named_args, MonoObject*, j);
8041 MONO_HANDLE_ASSIGN_RAW (val_h, val);
8043 if (arginfo [j].prop) {
8044 buffer_add_byte (buf, 0x54);
8045 buffer_add_propertyid (buf, domain, arginfo [j].prop);
8046 } else if (arginfo [j].field) {
8047 buffer_add_byte (buf, 0x53);
8048 buffer_add_fieldid (buf, domain, arginfo [j].field);
8049 } else {
8050 g_assert_not_reached ();
8053 buffer_add_cattr_arg (buf, arginfo [j].type, domain, val);
8055 } else {
8056 buffer_add_int (buf, 0);
8058 g_free (arginfo);
8060 CLEAR_ICALL_FRAME;
8064 return ERR_NONE;
8067 /* FIXME: Code duplication with icall.c */
8068 static void
8069 collect_interfaces (MonoClass *klass, GHashTable *ifaces, MonoError *error)
8071 int i;
8072 MonoClass *ic;
8074 mono_class_setup_interfaces (klass, error);
8075 if (!is_ok (error))
8076 return;
8078 int klass_interface_count = m_class_get_interface_count (klass);
8079 MonoClass **klass_interfaces = m_class_get_interfaces (klass);
8080 for (i = 0; i < klass_interface_count; i++) {
8081 ic = klass_interfaces [i];
8082 g_hash_table_insert (ifaces, ic, ic);
8084 collect_interfaces (ic, ifaces, error);
8085 if (!is_ok (error))
8086 return;
8090 static ErrorCode
8091 type_commands_internal (int command, MonoClass *klass, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8093 HANDLE_FUNCTION_ENTER ();
8095 ERROR_DECL (error);
8096 MonoClass *nested;
8097 MonoType *type;
8098 gpointer iter;
8099 guint8 b;
8100 int nnested;
8101 ErrorCode err;
8102 char *name;
8103 MonoStringHandle string_handle = MONO_HANDLE_NEW (MonoString, NULL); // FIXME? Not always needed.
8105 switch (command) {
8106 case CMD_TYPE_GET_INFO: {
8107 buffer_add_string (buf, m_class_get_name_space (klass));
8108 buffer_add_string (buf, m_class_get_name (klass));
8109 // FIXME: byref
8110 name = mono_type_get_name_full (m_class_get_byval_arg (klass), MONO_TYPE_NAME_FORMAT_FULL_NAME);
8111 buffer_add_string (buf, name);
8112 g_free (name);
8113 buffer_add_assemblyid (buf, domain, m_class_get_image (klass)->assembly);
8114 buffer_add_moduleid (buf, domain, m_class_get_image (klass));
8115 buffer_add_typeid (buf, domain, m_class_get_parent (klass));
8116 if (m_class_get_rank (klass) || m_class_get_byval_arg (klass)->type == MONO_TYPE_PTR)
8117 buffer_add_typeid (buf, domain, m_class_get_element_class (klass));
8118 else
8119 buffer_add_id (buf, 0);
8120 buffer_add_int (buf, m_class_get_type_token (klass));
8121 buffer_add_byte (buf, m_class_get_rank (klass));
8122 buffer_add_int (buf, mono_class_get_flags (klass));
8123 b = 0;
8124 type = m_class_get_byval_arg (klass);
8125 // FIXME: Can't decide whenever a class represents a byref type
8126 if (FALSE)
8127 b |= (1 << 0);
8128 if (type->type == MONO_TYPE_PTR)
8129 b |= (1 << 1);
8130 if (!type->byref && (((type->type >= MONO_TYPE_BOOLEAN) && (type->type <= MONO_TYPE_R8)) || (type->type == MONO_TYPE_I) || (type->type == MONO_TYPE_U)))
8131 b |= (1 << 2);
8132 if (type->type == MONO_TYPE_VALUETYPE)
8133 b |= (1 << 3);
8134 if (m_class_is_enumtype (klass))
8135 b |= (1 << 4);
8136 if (mono_class_is_gtd (klass))
8137 b |= (1 << 5);
8138 if (mono_class_is_gtd (klass) || mono_class_is_ginst (klass))
8139 b |= (1 << 6);
8140 buffer_add_byte (buf, b);
8141 nnested = 0;
8142 iter = NULL;
8143 while ((nested = mono_class_get_nested_types (klass, &iter)))
8144 nnested ++;
8145 buffer_add_int (buf, nnested);
8146 iter = NULL;
8147 while ((nested = mono_class_get_nested_types (klass, &iter)))
8148 buffer_add_typeid (buf, domain, nested);
8149 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8150 if (mono_class_is_gtd (klass))
8151 buffer_add_typeid (buf, domain, klass);
8152 else if (mono_class_is_ginst (klass))
8153 buffer_add_typeid (buf, domain, mono_class_get_generic_class (klass)->container_class);
8154 else
8155 buffer_add_id (buf, 0);
8157 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8158 int count, i;
8160 if (mono_class_is_ginst (klass)) {
8161 MonoGenericInst *inst = mono_class_get_generic_class (klass)->context.class_inst;
8163 count = inst->type_argc;
8164 buffer_add_int (buf, count);
8165 for (i = 0; i < count; i++)
8166 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (inst->type_argv [i]));
8167 } else if (mono_class_is_gtd (klass)) {
8168 MonoGenericContainer *container = mono_class_get_generic_container (klass);
8169 MonoClass *pklass;
8171 count = container->type_argc;
8172 buffer_add_int (buf, count);
8173 for (i = 0; i < count; i++) {
8174 pklass = mono_class_create_generic_parameter (mono_generic_container_get_param (container, i));
8175 buffer_add_typeid (buf, domain, pklass);
8177 } else {
8178 buffer_add_int (buf, 0);
8181 break;
8183 case CMD_TYPE_GET_METHODS: {
8184 int nmethods;
8185 int i = 0;
8186 gpointer iter = NULL;
8187 MonoMethod *m;
8189 mono_class_setup_methods (klass);
8191 nmethods = mono_class_num_methods (klass);
8193 buffer_add_int (buf, nmethods);
8195 while ((m = mono_class_get_methods (klass, &iter))) {
8196 buffer_add_methodid (buf, domain, m);
8197 i ++;
8199 g_assert (i == nmethods);
8200 break;
8202 case CMD_TYPE_GET_FIELDS: {
8203 int nfields;
8204 int i = 0;
8205 gpointer iter = NULL;
8206 MonoClassField *f;
8208 nfields = mono_class_num_fields (klass);
8210 buffer_add_int (buf, nfields);
8212 while ((f = mono_class_get_fields_internal (klass, &iter))) {
8213 buffer_add_fieldid (buf, domain, f);
8214 buffer_add_string (buf, f->name);
8215 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (f->type));
8216 buffer_add_int (buf, f->type->attrs);
8217 i ++;
8219 g_assert (i == nfields);
8220 break;
8222 case CMD_TYPE_GET_PROPERTIES: {
8223 int nprops;
8224 int i = 0;
8225 gpointer iter = NULL;
8226 MonoProperty *p;
8228 nprops = mono_class_num_properties (klass);
8230 buffer_add_int (buf, nprops);
8232 while ((p = mono_class_get_properties (klass, &iter))) {
8233 buffer_add_propertyid (buf, domain, p);
8234 buffer_add_string (buf, p->name);
8235 buffer_add_methodid (buf, domain, p->get);
8236 buffer_add_methodid (buf, domain, p->set);
8237 buffer_add_int (buf, p->attrs);
8238 i ++;
8240 g_assert (i == nprops);
8241 break;
8243 case CMD_TYPE_GET_CATTRS: {
8244 MonoClass *attr_klass;
8245 MonoCustomAttrInfo *cinfo;
8247 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8248 /* attr_klass can be NULL */
8249 if (err != ERR_NONE)
8250 goto exit;
8252 cinfo = mono_custom_attrs_from_class_checked (klass, error);
8253 if (!is_ok (error)) {
8254 mono_error_cleanup (error); /* FIXME don't swallow the error message */
8255 goto loader_error;
8258 err = buffer_add_cattrs (buf, domain, m_class_get_image (klass), attr_klass, cinfo);
8259 if (err != ERR_NONE)
8260 goto exit;
8261 break;
8263 case CMD_TYPE_GET_FIELD_CATTRS: {
8264 MonoClass *attr_klass;
8265 MonoCustomAttrInfo *cinfo;
8266 MonoClassField *field;
8268 field = decode_fieldid (p, &p, end, NULL, &err);
8269 if (err != ERR_NONE)
8270 goto exit;
8271 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8272 if (err != ERR_NONE)
8273 goto exit;
8275 cinfo = mono_custom_attrs_from_field_checked (klass, field, error);
8276 if (!is_ok (error)) {
8277 mono_error_cleanup (error); /* FIXME don't swallow the error message */
8278 goto loader_error;
8281 err = buffer_add_cattrs (buf, domain, m_class_get_image (klass), attr_klass, cinfo);
8282 if (err != ERR_NONE)
8283 goto exit;
8284 break;
8286 case CMD_TYPE_GET_PROPERTY_CATTRS: {
8287 MonoClass *attr_klass;
8288 MonoCustomAttrInfo *cinfo;
8289 MonoProperty *prop;
8291 prop = decode_propertyid (p, &p, end, NULL, &err);
8292 if (err != ERR_NONE)
8293 goto exit;
8294 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8295 if (err != ERR_NONE)
8296 goto exit;
8298 cinfo = mono_custom_attrs_from_property_checked (klass, prop, error);
8299 if (!is_ok (error)) {
8300 mono_error_cleanup (error); /* FIXME don't swallow the error message */
8301 goto loader_error;
8304 err = buffer_add_cattrs (buf, domain, m_class_get_image (klass), attr_klass, cinfo);
8305 if (err != ERR_NONE)
8306 goto exit;
8307 break;
8309 case CMD_TYPE_GET_VALUES:
8310 case CMD_TYPE_GET_VALUES_2: {
8311 guint8 *val;
8312 MonoClassField *f;
8313 MonoVTable *vtable;
8314 MonoClass *k;
8315 int len, i;
8316 gboolean found;
8317 MonoThread *thread_obj;
8318 MonoInternalThread *thread = NULL;
8319 guint32 special_static_type;
8321 if (command == CMD_TYPE_GET_VALUES_2) {
8322 int objid = decode_objid (p, &p, end);
8324 err = get_object (objid, (MonoObject**)&thread_obj);
8325 if (err != ERR_NONE)
8326 goto exit;
8328 thread = THREAD_TO_INTERNAL (thread_obj);
8331 len = decode_int (p, &p, end);
8332 for (i = 0; i < len; ++i) {
8333 f = decode_fieldid (p, &p, end, NULL, &err);
8334 if (err != ERR_NONE)
8335 goto exit;
8337 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8338 goto invalid_fieldid;
8340 special_static_type = mono_class_field_get_special_static_type (f);
8341 if (special_static_type != SPECIAL_STATIC_NONE) {
8342 if (!(thread && special_static_type == SPECIAL_STATIC_THREAD))
8343 goto invalid_fieldid;
8346 /* Check that the field belongs to the object */
8347 found = FALSE;
8348 for (k = klass; k; k = m_class_get_parent (k)) {
8349 if (k == f->parent) {
8350 found = TRUE;
8351 break;
8354 if (!found)
8355 goto invalid_fieldid;
8357 vtable = mono_class_vtable_checked (domain, f->parent, error);
8358 goto_if_nok (error, invalid_fieldid);
8360 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type_internal (f->type)));
8361 mono_field_static_get_value_for_thread (thread ? thread : mono_thread_internal_current (), vtable, f, val, string_handle, error);
8362 goto_if_nok (error, invalid_fieldid);
8364 buffer_add_value (buf, f->type, val, domain);
8365 g_free (val);
8367 break;
8369 case CMD_TYPE_SET_VALUES: {
8370 guint8 *val;
8371 MonoClassField *f;
8372 MonoVTable *vtable;
8373 MonoClass *k;
8374 int len, i;
8375 gboolean found;
8377 len = decode_int (p, &p, end);
8378 for (i = 0; i < len; ++i) {
8379 f = decode_fieldid (p, &p, end, NULL, &err);
8380 if (err != ERR_NONE)
8381 goto exit;
8383 if (!(f->type->attrs & FIELD_ATTRIBUTE_STATIC))
8384 goto invalid_fieldid;
8386 if (mono_class_field_is_special_static (f))
8387 goto invalid_fieldid;
8389 /* Check that the field belongs to the object */
8390 found = FALSE;
8391 for (k = klass; k; k = m_class_get_parent (k)) {
8392 if (k == f->parent) {
8393 found = TRUE;
8394 break;
8397 if (!found)
8398 goto invalid_fieldid;
8400 // FIXME: Check for literal/const
8402 vtable = mono_class_vtable_checked (domain, f->parent, error);
8403 goto_if_nok (error, invalid_fieldid);
8405 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type_internal (f->type)));
8406 err = decode_value (f->type, domain, val, p, &p, end, TRUE);
8407 if (err != ERR_NONE) {
8408 g_free (val);
8409 goto exit;
8411 if (MONO_TYPE_IS_REFERENCE (f->type))
8412 mono_field_static_set_value_internal (vtable, f, *(gpointer*)val);
8413 else
8414 mono_field_static_set_value_internal (vtable, f, val);
8415 g_free (val);
8417 break;
8419 case CMD_TYPE_GET_OBJECT: {
8420 MonoObject *o = (MonoObject*)mono_type_get_object_checked (domain, m_class_get_byval_arg (klass), error);
8421 if (!is_ok (error)) {
8422 mono_error_cleanup (error);
8423 goto invalid_object;
8425 buffer_add_objid (buf, o);
8426 break;
8428 case CMD_TYPE_GET_SOURCE_FILES:
8429 case CMD_TYPE_GET_SOURCE_FILES_2: {
8430 char *source_file, *base;
8431 GPtrArray *files;
8432 int i;
8434 files = get_source_files_for_type (klass);
8436 buffer_add_int (buf, files->len);
8437 for (i = 0; i < files->len; ++i) {
8438 source_file = (char *)g_ptr_array_index (files, i);
8439 if (command == CMD_TYPE_GET_SOURCE_FILES_2) {
8440 buffer_add_string (buf, source_file);
8441 } else {
8442 base = dbg_path_get_basename (source_file);
8443 buffer_add_string (buf, base);
8444 g_free (base);
8446 g_free (source_file);
8448 g_ptr_array_free (files, TRUE);
8449 break;
8451 case CMD_TYPE_IS_ASSIGNABLE_FROM: {
8452 MonoClass *oklass = decode_typeid (p, &p, end, NULL, &err);
8454 if (err != ERR_NONE)
8455 goto exit;
8456 if (mono_class_is_assignable_from_internal (klass, oklass))
8457 buffer_add_byte (buf, 1);
8458 else
8459 buffer_add_byte (buf, 0);
8460 break;
8462 case CMD_TYPE_GET_METHODS_BY_NAME_FLAGS: {
8463 char *name = decode_string (p, &p, end);
8464 int i, flags = decode_int (p, &p, end);
8465 int mlisttype;
8466 if (CHECK_PROTOCOL_VERSION (2, 48))
8467 mlisttype = decode_int (p, &p, end);
8468 else
8469 mlisttype = 0; // MLISTTYPE_All
8470 ERROR_DECL (error);
8471 GPtrArray *array;
8473 error_init (error);
8474 array = mono_class_get_methods_by_name (klass, name, flags & ~BINDING_FLAGS_IGNORE_CASE, mlisttype, TRUE, error);
8475 if (!is_ok (error)) {
8476 mono_error_cleanup (error);
8477 goto loader_error;
8479 buffer_add_int (buf, array->len);
8480 for (i = 0; i < array->len; ++i) {
8481 MonoMethod *method = (MonoMethod *)g_ptr_array_index (array, i);
8482 buffer_add_methodid (buf, domain, method);
8485 g_ptr_array_free (array, TRUE);
8486 g_free (name);
8487 break;
8489 case CMD_TYPE_GET_INTERFACES: {
8490 MonoClass *parent;
8491 GHashTable *iface_hash = g_hash_table_new (NULL, NULL);
8492 MonoClass *tclass, *iface;
8493 GHashTableIter iter;
8495 tclass = klass;
8497 for (parent = tclass; parent; parent = m_class_get_parent (parent)) {
8498 mono_class_setup_interfaces (parent, error);
8499 goto_if_nok (error, loader_error);
8501 collect_interfaces (parent, iface_hash, error);
8502 goto_if_nok (error, loader_error);
8505 buffer_add_int (buf, g_hash_table_size (iface_hash));
8507 g_hash_table_iter_init (&iter, iface_hash);
8508 while (g_hash_table_iter_next (&iter, NULL, (void**)&iface))
8509 buffer_add_typeid (buf, domain, iface);
8510 g_hash_table_destroy (iface_hash);
8511 break;
8513 case CMD_TYPE_GET_INTERFACE_MAP: {
8514 int tindex, ioffset;
8515 gboolean variance_used;
8516 MonoClass *iclass;
8517 int len, nmethods, i;
8518 gpointer iter;
8519 MonoMethod *method;
8521 len = decode_int (p, &p, end);
8522 mono_class_setup_vtable (klass);
8524 for (tindex = 0; tindex < len; ++tindex) {
8525 iclass = decode_typeid (p, &p, end, NULL, &err);
8526 if (err != ERR_NONE)
8527 goto exit;
8529 ioffset = mono_class_interface_offset_with_variance (klass, iclass, &variance_used);
8530 if (ioffset == -1)
8531 goto invalid_argument;
8533 nmethods = mono_class_num_methods (iclass);
8534 buffer_add_int (buf, nmethods);
8536 iter = NULL;
8537 while ((method = mono_class_get_methods (iclass, &iter))) {
8538 buffer_add_methodid (buf, domain, method);
8540 MonoMethod **klass_vtable = m_class_get_vtable (klass);
8541 for (i = 0; i < nmethods; ++i)
8542 buffer_add_methodid (buf, domain, klass_vtable [i + ioffset]);
8544 break;
8546 case CMD_TYPE_IS_INITIALIZED: {
8547 MonoVTable *vtable = mono_class_vtable_checked (domain, klass, error);
8548 goto_if_nok (error, loader_error);
8550 if (vtable)
8551 buffer_add_int (buf, (vtable->initialized || vtable->init_failed) ? 1 : 0);
8552 else
8553 buffer_add_int (buf, 0);
8554 break;
8556 case CMD_TYPE_CREATE_INSTANCE: {
8557 ERROR_DECL (error);
8558 MonoObject *obj;
8560 obj = mono_object_new_checked (domain, klass, error);
8561 mono_error_assert_ok (error);
8562 buffer_add_objid (buf, obj);
8563 break;
8565 case CMD_TYPE_GET_VALUE_SIZE: {
8566 int32_t value_size;
8568 value_size = mono_class_value_size (klass, NULL);
8569 buffer_add_int (buf, value_size);
8570 break;
8572 default:
8573 err = ERR_NOT_IMPLEMENTED;
8574 goto exit;
8577 err = ERR_NONE;
8578 goto exit;
8579 invalid_argument:
8580 err = ERR_INVALID_ARGUMENT;
8581 goto exit;
8582 invalid_fieldid:
8583 err = ERR_INVALID_FIELDID;
8584 goto exit;
8585 invalid_object:
8586 err = ERR_INVALID_OBJECT;
8587 goto exit;
8588 loader_error:
8589 err = ERR_LOADER_ERROR;
8590 goto exit;
8591 exit:
8592 HANDLE_FUNCTION_RETURN_VAL (err);
8595 static ErrorCode
8596 type_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
8598 MonoClass *klass;
8599 MonoDomain *old_domain;
8600 MonoDomain *domain;
8601 ErrorCode err;
8603 klass = decode_typeid (p, &p, end, &domain, &err);
8604 if (err != ERR_NONE)
8605 return err;
8607 old_domain = mono_domain_get ();
8609 mono_domain_set_fast (domain, TRUE);
8611 err = type_commands_internal (command, klass, domain, p, end, buf);
8613 mono_domain_set_fast (old_domain, TRUE);
8615 return err;
8618 static ErrorCode
8619 method_commands_internal (int command, MonoMethod *method, MonoDomain *domain, guint8 *p, guint8 *end, Buffer *buf)
8621 MonoMethodHeader *header;
8622 ErrorCode err;
8624 switch (command) {
8625 case CMD_METHOD_GET_NAME: {
8626 buffer_add_string (buf, method->name);
8627 break;
8629 case CMD_METHOD_GET_DECLARING_TYPE: {
8630 buffer_add_typeid (buf, domain, method->klass);
8631 break;
8633 case CMD_METHOD_GET_DEBUG_INFO: {
8634 ERROR_DECL (error);
8635 MonoDebugMethodInfo *minfo;
8636 char *source_file;
8637 int i, j, n_il_offsets;
8638 int *source_files;
8639 GPtrArray *source_file_list;
8640 MonoSymSeqPoint *sym_seq_points;
8642 header = mono_method_get_header_checked (method, error);
8643 if (!header) {
8644 mono_error_cleanup (error); /* FIXME don't swallow the error */
8645 buffer_add_int (buf, 0);
8646 buffer_add_string (buf, "");
8647 buffer_add_int (buf, 0);
8648 break;
8651 minfo = mono_debug_lookup_method (method);
8652 if (!minfo) {
8653 buffer_add_int (buf, header->code_size);
8654 buffer_add_string (buf, "");
8655 buffer_add_int (buf, 0);
8656 mono_metadata_free_mh (header);
8657 break;
8660 mono_debug_get_seq_points (minfo, &source_file, &source_file_list, &source_files, &sym_seq_points, &n_il_offsets);
8661 buffer_add_int (buf, header->code_size);
8662 if (CHECK_PROTOCOL_VERSION (2, 13)) {
8663 buffer_add_int (buf, source_file_list->len);
8664 for (i = 0; i < source_file_list->len; ++i) {
8665 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, i);
8666 buffer_add_string (buf, sinfo->source_file);
8667 if (CHECK_PROTOCOL_VERSION (2, 14)) {
8668 for (j = 0; j < 16; ++j)
8669 buffer_add_byte (buf, sinfo->hash [j]);
8672 } else {
8673 buffer_add_string (buf, source_file);
8675 buffer_add_int (buf, n_il_offsets);
8676 DEBUG_PRINTF (10, "Line number table for method %s:\n", mono_method_full_name (method, TRUE));
8677 for (i = 0; i < n_il_offsets; ++i) {
8678 MonoSymSeqPoint *sp = &sym_seq_points [i];
8679 const char *srcfile = "";
8681 if (source_files [i] != -1) {
8682 MonoDebugSourceInfo *sinfo = (MonoDebugSourceInfo *)g_ptr_array_index (source_file_list, source_files [i]);
8683 srcfile = sinfo->source_file;
8685 DEBUG_PRINTF (10, "IL%x -> %s:%d %d %d %d\n", sp->il_offset, srcfile, sp->line, sp->column, sp->end_line, sp->end_column);
8686 buffer_add_int (buf, sp->il_offset);
8687 buffer_add_int (buf, sp->line);
8688 if (CHECK_PROTOCOL_VERSION (2, 13))
8689 buffer_add_int (buf, source_files [i]);
8690 if (CHECK_PROTOCOL_VERSION (2, 19))
8691 buffer_add_int (buf, sp->column);
8692 if (CHECK_PROTOCOL_VERSION (2, 32)) {
8693 buffer_add_int (buf, sp->end_line);
8694 buffer_add_int (buf, sp->end_column);
8697 g_free (source_file);
8698 g_free (source_files);
8699 g_free (sym_seq_points);
8700 g_ptr_array_free (source_file_list, TRUE);
8701 mono_metadata_free_mh (header);
8702 break;
8704 case CMD_METHOD_GET_PARAM_INFO: {
8705 MonoMethodSignature *sig = mono_method_signature_internal (method);
8706 guint32 i;
8707 char **names;
8709 /* FIXME: mono_class_from_mono_type_internal () and byrefs */
8711 /* FIXME: Use a smaller encoding */
8712 buffer_add_int (buf, sig->call_convention);
8713 buffer_add_int (buf, sig->param_count);
8714 buffer_add_int (buf, sig->generic_param_count);
8715 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (sig->ret));
8716 for (i = 0; i < sig->param_count; ++i) {
8717 /* FIXME: vararg */
8718 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (sig->params [i]));
8721 /* Emit parameter names */
8722 names = g_new (char *, sig->param_count);
8723 mono_method_get_param_names (method, (const char **) names);
8724 for (i = 0; i < sig->param_count; ++i)
8725 buffer_add_string (buf, names [i]);
8726 g_free (names);
8728 break;
8730 case CMD_METHOD_GET_LOCALS_INFO: {
8731 ERROR_DECL (error);
8732 int i, num_locals;
8733 MonoDebugLocalsInfo *locals;
8734 int *locals_map = NULL;
8736 header = mono_method_get_header_checked (method, error);
8737 if (!header) {
8738 add_error_string (buf, mono_error_get_message (error));
8739 mono_error_cleanup (error); /* FIXME don't swallow the error */
8740 return ERR_INVALID_ARGUMENT;
8743 locals = mono_debug_lookup_locals (method);
8744 if (!locals) {
8745 if (CHECK_PROTOCOL_VERSION (2, 43)) {
8746 /* Scopes */
8747 buffer_add_int (buf, 1);
8748 buffer_add_int (buf, 0);
8749 buffer_add_int (buf, header->code_size);
8751 buffer_add_int (buf, header->num_locals);
8752 /* Types */
8753 for (i = 0; i < header->num_locals; ++i) {
8754 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (header->locals [i]));
8756 /* Names */
8757 for (i = 0; i < header->num_locals; ++i) {
8758 char lname [128];
8759 sprintf (lname, "V_%d", i);
8760 buffer_add_string (buf, lname);
8762 /* Scopes */
8763 for (i = 0; i < header->num_locals; ++i) {
8764 buffer_add_int (buf, 0);
8765 buffer_add_int (buf, header->code_size);
8767 } else {
8768 if (CHECK_PROTOCOL_VERSION (2, 43)) {
8769 /* Scopes */
8770 buffer_add_int (buf, locals->num_blocks);
8771 int last_start = 0;
8772 for (i = 0; i < locals->num_blocks; ++i) {
8773 buffer_add_int (buf, locals->code_blocks [i].start_offset - last_start);
8774 buffer_add_int (buf, locals->code_blocks [i].end_offset - locals->code_blocks [i].start_offset);
8775 last_start = locals->code_blocks [i].start_offset;
8779 num_locals = locals->num_locals;
8780 buffer_add_int (buf, num_locals);
8782 /* Types */
8783 for (i = 0; i < num_locals; ++i) {
8784 g_assert (locals->locals [i].index < header->num_locals);
8785 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (header->locals [locals->locals [i].index]));
8787 /* Names */
8788 for (i = 0; i < num_locals; ++i)
8789 buffer_add_string (buf, locals->locals [i].name);
8790 /* Scopes */
8791 for (i = 0; i < num_locals; ++i) {
8792 if (locals->locals [i].block) {
8793 buffer_add_int (buf, locals->locals [i].block->start_offset);
8794 buffer_add_int (buf, locals->locals [i].block->end_offset);
8795 } else {
8796 buffer_add_int (buf, 0);
8797 buffer_add_int (buf, header->code_size);
8801 mono_metadata_free_mh (header);
8803 if (locals)
8804 mono_debug_free_locals (locals);
8805 g_free (locals_map);
8807 break;
8809 case CMD_METHOD_GET_INFO:
8810 buffer_add_int (buf, method->flags);
8811 buffer_add_int (buf, method->iflags);
8812 buffer_add_int (buf, method->token);
8813 if (CHECK_PROTOCOL_VERSION (2, 12)) {
8814 guint8 attrs = 0;
8815 if (method->is_generic)
8816 attrs |= (1 << 0);
8817 if (mono_method_signature_internal (method)->generic_param_count)
8818 attrs |= (1 << 1);
8819 buffer_add_byte (buf, attrs);
8820 if (method->is_generic || method->is_inflated) {
8821 MonoMethod *result;
8823 if (method->is_generic) {
8824 result = method;
8825 } else {
8826 MonoMethodInflated *imethod = (MonoMethodInflated *)method;
8828 result = imethod->declaring;
8829 if (imethod->context.class_inst) {
8830 MonoClass *klass = ((MonoMethod *) imethod)->klass;
8831 /*Generic methods gets the context of the GTD.*/
8832 if (mono_class_get_context (klass)) {
8833 ERROR_DECL (error);
8834 result = mono_class_inflate_generic_method_full_checked (result, klass, mono_class_get_context (klass), error);
8835 g_assert (is_ok (error)); /* FIXME don't swallow the error */
8840 buffer_add_methodid (buf, domain, result);
8841 } else {
8842 buffer_add_id (buf, 0);
8844 if (CHECK_PROTOCOL_VERSION (2, 15)) {
8845 if (mono_method_signature_internal (method)->generic_param_count) {
8846 int count, i;
8848 if (method->is_inflated) {
8849 MonoGenericInst *inst = mono_method_get_context (method)->method_inst;
8850 if (inst) {
8851 count = inst->type_argc;
8852 buffer_add_int (buf, count);
8854 for (i = 0; i < count; i++)
8855 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal (inst->type_argv [i]));
8856 } else {
8857 buffer_add_int (buf, 0);
8859 } else if (method->is_generic) {
8860 MonoGenericContainer *container = mono_method_get_generic_container (method);
8862 count = mono_method_signature_internal (method)->generic_param_count;
8863 buffer_add_int (buf, count);
8864 for (i = 0; i < count; i++) {
8865 MonoGenericParam *param = mono_generic_container_get_param (container, i);
8866 MonoClass *pklass = mono_class_create_generic_parameter (param);
8867 buffer_add_typeid (buf, domain, pklass);
8869 } else {
8870 buffer_add_int (buf, 0);
8872 } else {
8873 buffer_add_int (buf, 0);
8877 break;
8878 case CMD_METHOD_GET_BODY: {
8879 ERROR_DECL (error);
8880 int i;
8882 header = mono_method_get_header_checked (method, error);
8883 if (!header) {
8884 mono_error_cleanup (error); /* FIXME don't swallow the error */
8885 buffer_add_int (buf, 0);
8887 if (CHECK_PROTOCOL_VERSION (2, 18))
8888 buffer_add_int (buf, 0);
8889 } else {
8890 buffer_add_int (buf, header->code_size);
8891 for (i = 0; i < header->code_size; ++i)
8892 buffer_add_byte (buf, header->code [i]);
8894 if (CHECK_PROTOCOL_VERSION (2, 18)) {
8895 buffer_add_int (buf, header->num_clauses);
8896 for (i = 0; i < header->num_clauses; ++i) {
8897 MonoExceptionClause *clause = &header->clauses [i];
8899 buffer_add_int (buf, clause->flags);
8900 buffer_add_int (buf, clause->try_offset);
8901 buffer_add_int (buf, clause->try_len);
8902 buffer_add_int (buf, clause->handler_offset);
8903 buffer_add_int (buf, clause->handler_len);
8904 if (clause->flags == MONO_EXCEPTION_CLAUSE_NONE)
8905 buffer_add_typeid (buf, domain, clause->data.catch_class);
8906 else if (clause->flags == MONO_EXCEPTION_CLAUSE_FILTER)
8907 buffer_add_int (buf, clause->data.filter_offset);
8911 mono_metadata_free_mh (header);
8914 break;
8916 case CMD_METHOD_RESOLVE_TOKEN: {
8917 guint32 token = decode_int (p, &p, end);
8919 // FIXME: Generics
8920 switch (mono_metadata_token_code (token)) {
8921 case MONO_TOKEN_STRING: {
8922 ERROR_DECL (error);
8923 MonoString *s;
8924 char *s2;
8926 s = mono_ldstr_checked (domain, m_class_get_image (method->klass), mono_metadata_token_index (token), error);
8927 mono_error_assert_ok (error); /* FIXME don't swallow the error */
8929 s2 = mono_string_to_utf8_checked_internal (s, error);
8930 mono_error_assert_ok (error);
8932 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8933 buffer_add_string (buf, s2);
8934 g_free (s2);
8935 break;
8937 default: {
8938 ERROR_DECL (error);
8939 gpointer val;
8940 MonoClass *handle_class;
8942 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD) {
8943 val = mono_method_get_wrapper_data (method, token);
8944 handle_class = (MonoClass *)mono_method_get_wrapper_data (method, token + 1);
8946 if (handle_class == NULL) {
8947 // Can't figure out the token type
8948 buffer_add_byte (buf, TOKEN_TYPE_UNKNOWN);
8949 break;
8951 } else {
8952 val = mono_ldtoken_checked (m_class_get_image (method->klass), token, &handle_class, NULL, error);
8953 if (!val)
8954 g_error ("Could not load token due to %s", mono_error_get_message (error));
8957 if (handle_class == mono_defaults.typehandle_class) {
8958 buffer_add_byte (buf, TOKEN_TYPE_TYPE);
8959 if (method->wrapper_type == MONO_WRAPPER_DYNAMIC_METHOD)
8960 buffer_add_typeid (buf, domain, (MonoClass *) val);
8961 else
8962 buffer_add_typeid (buf, domain, mono_class_from_mono_type_internal ((MonoType*)val));
8963 } else if (handle_class == mono_defaults.fieldhandle_class) {
8964 buffer_add_byte (buf, TOKEN_TYPE_FIELD);
8965 buffer_add_fieldid (buf, domain, (MonoClassField *)val);
8966 } else if (handle_class == mono_defaults.methodhandle_class) {
8967 buffer_add_byte (buf, TOKEN_TYPE_METHOD);
8968 buffer_add_methodid (buf, domain, (MonoMethod *)val);
8969 } else if (handle_class == mono_defaults.string_class) {
8970 char *s;
8972 s = mono_string_to_utf8_checked_internal ((MonoString *)val, error);
8973 mono_error_assert_ok (error);
8974 buffer_add_byte (buf, TOKEN_TYPE_STRING);
8975 buffer_add_string (buf, s);
8976 g_free (s);
8977 } else {
8978 g_assert_not_reached ();
8980 break;
8983 break;
8985 case CMD_METHOD_GET_CATTRS: {
8986 ERROR_DECL (error);
8987 MonoClass *attr_klass;
8988 MonoCustomAttrInfo *cinfo;
8990 attr_klass = decode_typeid (p, &p, end, NULL, &err);
8991 /* attr_klass can be NULL */
8992 if (err != ERR_NONE)
8993 return err;
8995 cinfo = mono_custom_attrs_from_method_checked (method, error);
8996 if (!is_ok (error)) {
8997 mono_error_cleanup (error); /* FIXME don't swallow the error message */
8998 return ERR_LOADER_ERROR;
9001 err = buffer_add_cattrs (buf, domain, m_class_get_image (method->klass), attr_klass, cinfo);
9002 if (err != ERR_NONE)
9003 return err;
9004 break;
9006 case CMD_METHOD_MAKE_GENERIC_METHOD: {
9007 ERROR_DECL (error);
9008 MonoType **type_argv;
9009 int i, type_argc;
9010 MonoDomain *d;
9011 MonoClass *klass;
9012 MonoGenericInst *ginst;
9013 MonoGenericContext tmp_context;
9014 MonoMethod *inflated;
9016 type_argc = decode_int (p, &p, end);
9017 type_argv = g_new0 (MonoType*, type_argc);
9018 for (i = 0; i < type_argc; ++i) {
9019 klass = decode_typeid (p, &p, end, &d, &err);
9020 if (err != ERR_NONE) {
9021 g_free (type_argv);
9022 return err;
9024 if (domain != d) {
9025 g_free (type_argv);
9026 return ERR_INVALID_ARGUMENT;
9028 type_argv [i] = m_class_get_byval_arg (klass);
9030 ginst = mono_metadata_get_generic_inst (type_argc, type_argv);
9031 g_free (type_argv);
9032 tmp_context.class_inst = mono_class_is_ginst (method->klass) ? mono_class_get_generic_class (method->klass)->context.class_inst : NULL;
9033 tmp_context.method_inst = ginst;
9035 inflated = mono_class_inflate_generic_method_checked (method, &tmp_context, error);
9036 g_assert (is_ok (error)); /* FIXME don't swallow the error */
9037 if (!mono_verifier_is_method_valid_generic_instantiation (inflated))
9038 return ERR_INVALID_ARGUMENT;
9039 buffer_add_methodid (buf, domain, inflated);
9040 break;
9042 default:
9043 return ERR_NOT_IMPLEMENTED;
9046 return ERR_NONE;
9049 static ErrorCode
9050 method_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9052 ErrorCode err;
9053 MonoDomain *old_domain;
9054 MonoDomain *domain;
9055 MonoMethod *method;
9057 method = decode_methodid (p, &p, end, &domain, &err);
9058 if (err != ERR_NONE)
9059 return err;
9061 old_domain = mono_domain_get ();
9063 mono_domain_set_fast (domain, TRUE);
9065 err = method_commands_internal (command, method, domain, p, end, buf);
9067 mono_domain_set_fast (old_domain, TRUE);
9069 return err;
9072 static ErrorCode
9073 thread_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9075 int objid = decode_objid (p, &p, end);
9076 ErrorCode err;
9077 MonoThread *thread_obj;
9078 MonoInternalThread *thread;
9080 err = get_object (objid, (MonoObject**)&thread_obj);
9081 if (err != ERR_NONE)
9082 return err;
9084 thread = THREAD_TO_INTERNAL (thread_obj);
9086 switch (command) {
9087 case CMD_THREAD_GET_NAME: {
9088 char *s = mono_thread_get_name_utf8 (thread_obj);
9090 if (!s) {
9091 buffer_add_int (buf, 0);
9092 } else {
9093 const size_t len = strlen (s);
9094 buffer_add_int (buf, len);
9095 buffer_add_data (buf, (guint8*)s, len);
9096 g_free (s);
9098 break;
9100 case CMD_THREAD_GET_FRAME_INFO: {
9101 DebuggerTlsData *tls;
9102 int i, start_frame, length;
9104 // Wait for suspending if it already started
9105 // FIXME: Races with suspend_count
9106 while (!is_suspended ()) {
9107 if (suspend_count)
9108 wait_for_suspend ();
9111 if (suspend_count)
9112 wait_for_suspend ();
9113 if (!is_suspended ())
9114 return ERR_NOT_SUSPENDED;
9117 start_frame = decode_int (p, &p, end);
9118 length = decode_int (p, &p, end);
9120 if (start_frame != 0 || length != -1)
9121 return ERR_NOT_IMPLEMENTED;
9123 mono_loader_lock ();
9124 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9125 mono_loader_unlock ();
9126 g_assert (tls);
9128 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
9130 buffer_add_int (buf, tls->frame_count);
9131 for (i = 0; i < tls->frame_count; ++i) {
9132 buffer_add_int (buf, tls->frames [i]->id);
9133 buffer_add_methodid (buf, tls->frames [i]->de.domain, tls->frames [i]->actual_method);
9134 buffer_add_int (buf, tls->frames [i]->il_offset);
9136 * Instead of passing the frame type directly to the client, we associate
9137 * it with the previous frame using a set of flags. This avoids lots of
9138 * conditional code in the client, since a frame whose type isn't
9139 * FRAME_TYPE_MANAGED has no method, location, etc.
9141 buffer_add_byte (buf, tls->frames [i]->flags);
9144 break;
9146 case CMD_THREAD_GET_STATE:
9147 buffer_add_int (buf, thread->state);
9148 break;
9149 case CMD_THREAD_GET_INFO:
9150 buffer_add_byte (buf, thread->threadpool_thread);
9151 break;
9152 case CMD_THREAD_GET_ID:
9153 buffer_add_long (buf, (guint64)(gsize)thread);
9154 break;
9155 case CMD_THREAD_GET_TID:
9156 buffer_add_long (buf, (guint64)thread->tid);
9157 break;
9158 case CMD_THREAD_SET_IP: {
9159 DebuggerTlsData *tls;
9160 MonoMethod *method;
9161 MonoDomain *domain;
9162 MonoSeqPointInfo *seq_points;
9163 SeqPoint sp;
9164 gboolean found_sp;
9165 gint64 il_offset;
9167 method = decode_methodid (p, &p, end, &domain, &err);
9168 if (err != ERR_NONE)
9169 return err;
9170 il_offset = decode_long (p, &p, end);
9172 while (!is_suspended ()) {
9173 if (suspend_count)
9174 wait_for_suspend ();
9177 mono_loader_lock ();
9178 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9179 mono_loader_unlock ();
9180 g_assert (tls);
9182 compute_frame_info (thread, tls, FALSE);
9183 if (tls->frame_count == 0 || tls->frames [0]->actual_method != method)
9184 return ERR_INVALID_ARGUMENT;
9186 found_sp = mono_find_seq_point (domain, method, il_offset, &seq_points, &sp);
9188 g_assert (seq_points);
9190 if (!found_sp)
9191 return ERR_INVALID_ARGUMENT;
9193 // FIXME: Check that the ip change is safe
9195 DEBUG_PRINTF (1, "[dbg] Setting IP to %s:0x%0x(0x%0x)\n", tls->frames [0]->actual_method->name, (int)sp.il_offset, (int)sp.native_offset);
9197 if (tls->frames [0]->de.ji->is_interp) {
9198 MonoJitTlsData *jit_data = thread->thread_info->jit_data;
9199 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);
9200 } else {
9201 MONO_CONTEXT_SET_IP (&tls->restore_state.ctx, (guint8*)tls->frames [0]->de.ji->code_start + sp.native_offset);
9203 break;
9205 case CMD_THREAD_ELAPSED_TIME: {
9206 DebuggerTlsData *tls;
9207 mono_loader_lock ();
9208 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9209 mono_loader_unlock ();
9210 g_assert (tls);
9211 buffer_add_long (buf, (long)mono_stopwatch_elapsed_ms (&tls->step_time));
9212 break;
9214 default:
9215 return ERR_NOT_IMPLEMENTED;
9218 return ERR_NONE;
9221 static ErrorCode
9222 frame_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9224 int objid;
9225 ErrorCode err;
9226 MonoThread *thread_obj;
9227 MonoInternalThread *thread;
9228 int pos, i, len, frame_idx;
9229 DebuggerTlsData *tls;
9230 StackFrame *frame;
9231 MonoDebugMethodJitInfo *jit;
9232 MonoMethodSignature *sig;
9233 gssize id;
9234 MonoMethodHeader *header;
9236 objid = decode_objid (p, &p, end);
9237 err = get_object (objid, (MonoObject**)&thread_obj);
9238 if (err != ERR_NONE)
9239 return err;
9241 thread = THREAD_TO_INTERNAL (thread_obj);
9243 id = decode_id (p, &p, end);
9245 mono_loader_lock ();
9246 tls = (DebuggerTlsData *)mono_g_hash_table_lookup (thread_to_tls, thread);
9247 mono_loader_unlock ();
9248 g_assert (tls);
9250 for (i = 0; i < tls->frame_count; ++i) {
9251 if (tls->frames [i]->id == id)
9252 break;
9254 if (i == tls->frame_count)
9255 return ERR_INVALID_FRAMEID;
9257 /* The thread is still running native code, can't get frame variables info */
9258 if (!tls->really_suspended && !tls->async_state.valid)
9259 return ERR_NOT_SUSPENDED;
9260 frame_idx = i;
9261 frame = tls->frames [frame_idx];
9263 /* This is supported for frames without has_ctx etc. set */
9264 if (command == CMD_STACK_FRAME_GET_DOMAIN) {
9265 if (CHECK_PROTOCOL_VERSION (2, 38))
9266 buffer_add_domainid (buf, frame->de.domain);
9267 return ERR_NONE;
9270 if (!frame->has_ctx)
9271 return ERR_ABSENT_INFORMATION;
9273 if (!ensure_jit ((DbgEngineStackFrame*)frame))
9274 return ERR_ABSENT_INFORMATION;
9276 jit = frame->jit;
9278 sig = mono_method_signature_internal (frame->actual_method);
9280 if (!(jit->has_var_info || frame->de.ji->is_interp) || !mono_get_seq_points (frame->de.domain, frame->actual_method))
9282 * The method is probably from an aot image compiled without soft-debug, variables might be dead, etc.
9284 return ERR_ABSENT_INFORMATION;
9286 switch (command) {
9287 case CMD_STACK_FRAME_GET_VALUES: {
9288 ERROR_DECL (error);
9289 len = decode_int (p, &p, end);
9290 header = mono_method_get_header_checked (frame->actual_method, error);
9291 mono_error_assert_ok (error); /* FIXME report error */
9293 for (i = 0; i < len; ++i) {
9294 pos = decode_int (p, &p, end);
9296 if (pos < 0) {
9297 pos = - pos - 1;
9299 DEBUG_PRINTF (4, "[dbg] send arg %d.\n", pos);
9301 if (frame->de.ji->is_interp) {
9302 guint8 *addr;
9304 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_arg (frame->interp_frame, pos);
9306 buffer_add_value_full (buf, sig->params [pos], addr, frame->de.domain, FALSE, NULL, 1);
9307 } else {
9308 g_assert (pos >= 0 && pos < jit->num_params);
9310 add_var (buf, jit, sig->params [pos], &jit->params [pos], &frame->ctx, frame->de.domain, FALSE);
9312 } else {
9313 MonoDebugLocalsInfo *locals;
9315 locals = mono_debug_lookup_locals (frame->de.method);
9316 if (locals) {
9317 g_assert (pos < locals->num_locals);
9318 pos = locals->locals [pos].index;
9319 mono_debug_free_locals (locals);
9322 DEBUG_PRINTF (4, "[dbg] send local %d.\n", pos);
9324 if (frame->de.ji->is_interp) {
9325 guint8 *addr;
9327 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_local (frame->interp_frame, pos);
9329 buffer_add_value_full (buf, header->locals [pos], addr, frame->de.domain, FALSE, NULL, 1);
9330 } else {
9331 g_assert (pos >= 0 && pos < jit->num_locals);
9333 add_var (buf, jit, header->locals [pos], &jit->locals [pos], &frame->ctx, frame->de.domain, FALSE);
9337 mono_metadata_free_mh (header);
9338 break;
9340 case CMD_STACK_FRAME_GET_THIS: {
9341 if (frame->de.method->wrapper_type == MONO_WRAPPER_MANAGED_TO_NATIVE)
9342 return ERR_ABSENT_INFORMATION;
9343 if (m_class_is_valuetype (frame->api_method->klass)) {
9344 if (!sig->hasthis) {
9345 MonoObject *p = NULL;
9346 buffer_add_value (buf, mono_get_object_type (), &p, frame->de.domain);
9347 } else {
9348 if (frame->de.ji->is_interp) {
9349 guint8 *addr;
9351 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_this (frame->interp_frame);
9353 buffer_add_value_full (buf, m_class_get_this_arg (frame->actual_method->klass), addr, frame->de.domain, FALSE, NULL, 1);
9354 } else {
9355 add_var (buf, jit, m_class_get_this_arg (frame->actual_method->klass), jit->this_var, &frame->ctx, frame->de.domain, TRUE);
9358 } else {
9359 if (!sig->hasthis) {
9360 MonoObject *p = NULL;
9361 buffer_add_value (buf, m_class_get_byval_arg (frame->actual_method->klass), &p, frame->de.domain);
9362 } else {
9363 if (frame->de.ji->is_interp) {
9364 guint8 *addr;
9366 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_this (frame->interp_frame);
9368 buffer_add_value_full (buf, m_class_get_byval_arg (frame->api_method->klass), addr, frame->de.domain, FALSE, NULL, 1);
9369 } else {
9370 add_var (buf, jit, m_class_get_byval_arg (frame->api_method->klass), jit->this_var, &frame->ctx, frame->de.domain, TRUE);
9374 break;
9376 case CMD_STACK_FRAME_SET_VALUES: {
9377 ERROR_DECL (error);
9378 guint8 *val_buf;
9379 MonoType *t;
9380 MonoDebugVarInfo *var = NULL;
9381 gboolean is_arg = FALSE;
9383 len = decode_int (p, &p, end);
9384 header = mono_method_get_header_checked (frame->actual_method, error);
9385 mono_error_assert_ok (error); /* FIXME report error */
9387 for (i = 0; i < len; ++i) {
9388 pos = decode_int (p, &p, end);
9390 if (pos < 0) {
9391 pos = - pos - 1;
9393 g_assert (pos >= 0 && pos < jit->num_params);
9395 t = sig->params [pos];
9396 var = &jit->params [pos];
9397 is_arg = TRUE;
9398 } else {
9399 MonoDebugLocalsInfo *locals;
9401 locals = mono_debug_lookup_locals (frame->de.method);
9402 if (locals) {
9403 g_assert (pos < locals->num_locals);
9404 pos = locals->locals [pos].index;
9405 mono_debug_free_locals (locals);
9407 g_assert (pos >= 0 && pos < jit->num_locals);
9409 t = header->locals [pos];
9410 var = &jit->locals [pos];
9413 if (MONO_TYPE_IS_REFERENCE (t))
9414 val_buf = (guint8 *)g_alloca (sizeof (MonoObject*));
9415 else
9416 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type_internal (t)));
9417 err = decode_value (t, frame->de.domain, val_buf, p, &p, end, TRUE);
9418 if (err != ERR_NONE)
9419 return err;
9421 if (frame->de.ji->is_interp) {
9422 guint8 *addr;
9424 if (is_arg)
9425 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_arg (frame->interp_frame, pos);
9426 else
9427 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_local (frame->interp_frame, pos);
9428 set_interp_var (t, addr, val_buf);
9429 } else {
9430 set_var (t, var, &frame->ctx, frame->de.domain, val_buf, frame->reg_locations, &tls->restore_state.ctx);
9433 mono_metadata_free_mh (header);
9434 break;
9436 case CMD_STACK_FRAME_GET_DOMAIN: {
9437 if (CHECK_PROTOCOL_VERSION (2, 38))
9438 buffer_add_domainid (buf, frame->de.domain);
9439 break;
9441 case CMD_STACK_FRAME_SET_THIS: {
9442 guint8 *val_buf;
9443 MonoType *t;
9444 MonoDebugVarInfo *var;
9446 t = m_class_get_byval_arg (frame->actual_method->klass);
9447 /* Checked by the sender */
9448 g_assert (MONO_TYPE_ISSTRUCT (t));
9450 val_buf = (guint8 *)g_alloca (mono_class_instance_size (mono_class_from_mono_type_internal (t)));
9451 err = decode_value (t, frame->de.domain, val_buf, p, &p, end, TRUE);
9452 if (err != ERR_NONE)
9453 return err;
9455 if (frame->de.ji->is_interp) {
9456 guint8 *addr;
9458 addr = (guint8*)mini_get_interp_callbacks ()->frame_get_this (frame->interp_frame);
9459 set_interp_var (m_class_get_this_arg (frame->actual_method->klass), addr, val_buf);
9460 } else {
9461 var = jit->this_var;
9462 g_assert (var);
9464 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);
9466 break;
9468 default:
9469 return ERR_NOT_IMPLEMENTED;
9472 return ERR_NONE;
9475 static ErrorCode
9476 array_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9478 MonoArray *arr;
9479 int objid, index, len, i, esize;
9480 ErrorCode err;
9481 gpointer elem;
9483 objid = decode_objid (p, &p, end);
9484 err = get_object (objid, (MonoObject**)&arr);
9485 if (err != ERR_NONE)
9486 return err;
9488 switch (command) {
9489 case CMD_ARRAY_REF_GET_LENGTH:
9490 buffer_add_int (buf, m_class_get_rank (arr->obj.vtable->klass));
9491 if (!arr->bounds) {
9492 buffer_add_int (buf, arr->max_length);
9493 buffer_add_int (buf, 0);
9494 } else {
9495 for (i = 0; i < m_class_get_rank (arr->obj.vtable->klass); ++i) {
9496 buffer_add_int (buf, arr->bounds [i].length);
9497 buffer_add_int (buf, arr->bounds [i].lower_bound);
9500 break;
9501 case CMD_ARRAY_REF_GET_VALUES:
9502 index = decode_int (p, &p, end);
9503 len = decode_int (p, &p, end);
9505 g_assert (index >= 0 && len >= 0);
9506 // Reordered to avoid integer overflow
9507 g_assert (!(index > arr->max_length - len));
9509 esize = mono_array_element_size (arr->obj.vtable->klass);
9510 for (i = index; i < index + len; ++i) {
9511 elem = (gpointer*)((char*)arr->vector + (i * esize));
9512 buffer_add_value (buf, m_class_get_byval_arg (m_class_get_element_class (arr->obj.vtable->klass)), elem, arr->obj.vtable->domain);
9514 break;
9515 case CMD_ARRAY_REF_SET_VALUES:
9516 index = decode_int (p, &p, end);
9517 len = decode_int (p, &p, end);
9519 g_assert (index >= 0 && len >= 0);
9520 // Reordered to avoid integer overflow
9521 g_assert (!(index > arr->max_length - len));
9523 esize = mono_array_element_size (arr->obj.vtable->klass);
9524 for (i = index; i < index + len; ++i) {
9525 elem = (gpointer*)((char*)arr->vector + (i * esize));
9527 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);
9529 break;
9530 default:
9531 return ERR_NOT_IMPLEMENTED;
9534 return ERR_NONE;
9537 static ErrorCode
9538 string_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9540 int objid;
9541 ErrorCode err;
9542 MonoString *str;
9543 char *s;
9544 int i, index, length;
9545 gunichar2 *c;
9546 gboolean use_utf16 = FALSE;
9548 objid = decode_objid (p, &p, end);
9549 err = get_object (objid, (MonoObject**)&str);
9550 if (err != ERR_NONE)
9551 return err;
9553 switch (command) {
9554 case CMD_STRING_REF_GET_VALUE:
9555 if (CHECK_PROTOCOL_VERSION (2, 41)) {
9556 for (i = 0; i < mono_string_length_internal (str); ++i)
9557 if (mono_string_chars_internal (str)[i] == 0)
9558 use_utf16 = TRUE;
9559 buffer_add_byte (buf, use_utf16 ? 1 : 0);
9561 if (use_utf16) {
9562 buffer_add_int (buf, mono_string_length_internal (str) * 2);
9563 buffer_add_data (buf, (guint8*)mono_string_chars_internal (str), mono_string_length_internal (str) * 2);
9564 } else {
9565 ERROR_DECL (error);
9566 s = mono_string_to_utf8_checked_internal (str, error);
9567 if (!is_ok (error)) {
9568 if (s)
9569 g_free (s);
9570 add_error_string (buf, mono_error_get_message (error));
9571 return ERR_INVALID_ARGUMENT;
9573 buffer_add_string (buf, s);
9574 g_free (s);
9576 break;
9577 case CMD_STRING_REF_GET_LENGTH:
9578 buffer_add_long (buf, mono_string_length_internal (str));
9579 break;
9580 case CMD_STRING_REF_GET_CHARS:
9581 index = decode_long (p, &p, end);
9582 length = decode_long (p, &p, end);
9583 if (index > mono_string_length_internal (str) - length)
9584 return ERR_INVALID_ARGUMENT;
9585 c = mono_string_chars_internal (str) + index;
9586 for (i = 0; i < length; ++i)
9587 buffer_add_short (buf, c [i]);
9588 break;
9589 default:
9590 return ERR_NOT_IMPLEMENTED;
9593 return ERR_NONE;
9596 static void
9597 create_file_to_check_memory_address (void)
9599 if (file_check_valid_memory != -1)
9600 return;
9601 char *file_name = g_strdup_printf ("debugger_check_valid_memory.%d", getpid());
9602 filename_check_valid_memory = g_build_filename (g_get_tmp_dir (), file_name, (const char*)NULL);
9603 file_check_valid_memory = open(filename_check_valid_memory, O_CREAT | O_WRONLY | O_APPEND, S_IWUSR);
9604 g_free (file_name);
9607 static gboolean
9608 valid_memory_address (gpointer addr, gint size)
9610 #ifndef _MSC_VER
9611 gboolean ret = TRUE;
9612 create_file_to_check_memory_address ();
9613 if(file_check_valid_memory < 0) {
9614 return TRUE;
9616 write (file_check_valid_memory, (gpointer)addr, 1);
9617 if (errno == EFAULT) {
9618 ret = FALSE;
9620 #else
9621 int i = 0;
9622 gboolean ret = FALSE;
9623 __try {
9624 for (i = 0; i < size; i++)
9625 *((volatile char*)addr+i);
9626 ret = TRUE;
9627 } __except(1) {
9628 return ret;
9630 #endif
9631 return ret;
9634 static ErrorCode
9635 pointer_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9637 ErrorCode err;
9638 gint64 addr;
9639 MonoClass* klass;
9640 MonoDomain* domain = NULL;
9641 MonoType *type = NULL;
9642 int align;
9643 int size = 0;
9645 switch (command) {
9646 case CMD_POINTER_GET_VALUE:
9647 addr = decode_long (p, &p, end);
9648 klass = decode_typeid (p, &p, end, &domain, &err);
9649 if (err != ERR_NONE)
9650 return err;
9652 if (m_class_get_byval_arg (klass)->type != MONO_TYPE_PTR)
9653 return ERR_INVALID_ARGUMENT;
9655 type = m_class_get_byval_arg (m_class_get_element_class (klass));
9656 size = mono_type_size (type, &align);
9658 if (!valid_memory_address((gpointer)addr, size))
9659 return ERR_INVALID_ARGUMENT;
9661 buffer_add_value (buf, type, (gpointer)addr, domain);
9663 break;
9664 default:
9665 return ERR_NOT_IMPLEMENTED;
9668 return ERR_NONE;
9671 static ErrorCode
9672 object_commands (int command, guint8 *p, guint8 *end, Buffer *buf)
9674 HANDLE_FUNCTION_ENTER ();
9676 ERROR_DECL (error);
9677 int objid;
9678 ErrorCode err;
9679 MonoObject *obj;
9680 int len, i;
9681 MonoClassField *f;
9682 MonoClass *k;
9683 gboolean found;
9684 gboolean remote_obj = FALSE;
9685 MonoStringHandle string_handle = MONO_HANDLE_NEW (MonoString, NULL); // FIXME? Not always needed.
9687 if (command == CMD_OBJECT_REF_IS_COLLECTED) {
9688 objid = decode_objid (p, &p, end);
9689 err = get_object (objid, &obj);
9690 if (err != ERR_NONE)
9691 buffer_add_int (buf, 1);
9692 else
9693 buffer_add_int (buf, 0);
9694 err = ERR_NONE;
9695 goto exit;
9698 objid = decode_objid (p, &p, end);
9699 err = get_object (objid, &obj);
9700 if (err != ERR_NONE)
9701 goto exit;
9703 MonoClass *obj_type;
9705 obj_type = obj->vtable->klass;
9706 if (mono_class_is_transparent_proxy (obj_type)) {
9707 obj_type = ((MonoTransparentProxy *)obj)->remote_class->proxy_class;
9708 remote_obj = TRUE;
9711 g_assert (obj_type);
9713 switch (command) {
9714 case CMD_OBJECT_REF_GET_TYPE:
9715 /* This handles transparent proxies too */
9716 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type_internal (((MonoReflectionType*)obj->vtable->type)->type));
9717 break;
9718 case CMD_OBJECT_REF_GET_VALUES:
9719 len = decode_int (p, &p, end);
9721 for (i = 0; i < len; ++i) {
9722 MonoClassField *f = decode_fieldid (p, &p, end, NULL, &err);
9723 if (err != ERR_NONE)
9724 goto exit;
9726 /* Check that the field belongs to the object */
9727 found = FALSE;
9728 for (k = obj_type; k; k = m_class_get_parent (k)) {
9729 if (k == f->parent) {
9730 found = TRUE;
9731 break;
9734 if (!found)
9735 goto invalid_fieldid;
9737 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9738 guint8 *val;
9739 MonoVTable *vtable;
9741 if (mono_class_field_is_special_static (f))
9742 goto invalid_fieldid;
9744 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9745 vtable = mono_class_vtable_checked (obj->vtable->domain, f->parent, error);
9746 if (!is_ok (error)) {
9747 mono_error_cleanup (error);
9748 goto invalid_object;
9750 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type_internal (f->type)));
9751 mono_field_static_get_value_checked (vtable, f, val, string_handle, error);
9752 if (!is_ok (error)) {
9753 mono_error_cleanup (error); /* FIXME report the error */
9754 goto invalid_object;
9756 buffer_add_value (buf, f->type, val, obj->vtable->domain);
9757 g_free (val);
9758 } else {
9759 void *field_value = NULL;
9760 #ifndef DISABLE_REMOTING
9761 void *field_storage = NULL;
9762 #endif
9763 if (remote_obj) {
9764 #ifndef DISABLE_REMOTING
9765 field_value = mono_load_remote_field_checked(obj, obj_type, f, &field_storage, error);
9766 if (!is_ok (error)) {
9767 mono_error_cleanup (error); /* FIXME report the error */
9768 goto invalid_object;
9770 #else
9771 g_assert_not_reached ();
9772 #endif
9773 } else
9774 field_value = (guint8*)obj + f->offset;
9776 buffer_add_value (buf, f->type, field_value, obj->vtable->domain);
9779 break;
9780 case CMD_OBJECT_REF_SET_VALUES:
9781 len = decode_int (p, &p, end);
9783 for (i = 0; i < len; ++i) {
9784 f = decode_fieldid (p, &p, end, NULL, &err);
9785 if (err != ERR_NONE)
9786 goto exit;
9788 /* Check that the field belongs to the object */
9789 found = FALSE;
9790 for (k = obj_type; k; k = m_class_get_parent (k)) {
9791 if (k == f->parent) {
9792 found = TRUE;
9793 break;
9796 if (!found)
9797 goto invalid_fieldid;
9799 if (f->type->attrs & FIELD_ATTRIBUTE_STATIC) {
9800 guint8 *val;
9801 MonoVTable *vtable;
9803 if (mono_class_field_is_special_static (f))
9804 goto invalid_fieldid;
9806 g_assert (f->type->attrs & FIELD_ATTRIBUTE_STATIC);
9807 vtable = mono_class_vtable_checked (obj->vtable->domain, f->parent, error);
9808 if (!is_ok (error)) {
9809 mono_error_cleanup (error);
9810 goto invalid_fieldid;
9813 val = (guint8 *)g_malloc (mono_class_instance_size (mono_class_from_mono_type_internal (f->type)));
9814 err = decode_value (f->type, obj->vtable->domain, val, p, &p, end, TRUE);
9815 if (err != ERR_NONE) {
9816 g_free (val);
9817 goto exit;
9819 mono_field_static_set_value_internal (vtable, f, val);
9820 g_free (val);
9821 } else {
9822 err = decode_value (f->type, obj->vtable->domain, (guint8*)obj + f->offset, p, &p, end, TRUE);
9823 if (err != ERR_NONE)
9824 goto exit;
9827 break;
9828 case CMD_OBJECT_REF_GET_ADDRESS:
9829 buffer_add_long (buf, (gssize)obj);
9830 break;
9831 case CMD_OBJECT_REF_GET_DOMAIN:
9832 buffer_add_domainid (buf, obj->vtable->domain);
9833 break;
9834 case CMD_OBJECT_REF_GET_INFO:
9835 buffer_add_typeid (buf, obj->vtable->domain, mono_class_from_mono_type_internal (((MonoReflectionType*)obj->vtable->type)->type));
9836 buffer_add_domainid (buf, obj->vtable->domain);
9837 break;
9838 default:
9839 err = ERR_NOT_IMPLEMENTED;
9840 goto exit;
9843 err = ERR_NONE;
9844 goto exit;
9845 invalid_fieldid:
9846 err = ERR_INVALID_FIELDID;
9847 goto exit;
9848 invalid_object:
9849 err = ERR_INVALID_OBJECT;
9850 goto exit;
9851 exit:
9852 HANDLE_FUNCTION_RETURN_VAL (err);
9855 static const char*
9856 command_set_to_string (CommandSet command_set)
9858 switch (command_set) {
9859 case CMD_SET_VM:
9860 return "VM";
9861 case CMD_SET_OBJECT_REF:
9862 return "OBJECT_REF";
9863 case CMD_SET_STRING_REF:
9864 return "STRING_REF";
9865 case CMD_SET_THREAD:
9866 return "THREAD";
9867 case CMD_SET_ARRAY_REF:
9868 return "ARRAY_REF";
9869 case CMD_SET_EVENT_REQUEST:
9870 return "EVENT_REQUEST";
9871 case CMD_SET_STACK_FRAME:
9872 return "STACK_FRAME";
9873 case CMD_SET_APPDOMAIN:
9874 return "APPDOMAIN";
9875 case CMD_SET_ASSEMBLY:
9876 return "ASSEMBLY";
9877 case CMD_SET_METHOD:
9878 return "METHOD";
9879 case CMD_SET_TYPE:
9880 return "TYPE";
9881 case CMD_SET_MODULE:
9882 return "MODULE";
9883 case CMD_SET_FIELD:
9884 return "FIELD";
9885 case CMD_SET_EVENT:
9886 return "EVENT";
9887 case CMD_SET_POINTER:
9888 return "POINTER";
9889 default:
9890 return "";
9894 static const char* vm_cmds_str [] = {
9895 "VERSION",
9896 "ALL_THREADS",
9897 "SUSPEND",
9898 "RESUME",
9899 "EXIT",
9900 "DISPOSE",
9901 "INVOKE_METHOD",
9902 "SET_PROTOCOL_VERSION",
9903 "ABORT_INVOKE",
9904 "SET_KEEPALIVE"
9905 "GET_TYPES_FOR_SOURCE_FILE",
9906 "GET_TYPES",
9907 "INVOKE_METHODS"
9910 static const char* thread_cmds_str[] = {
9911 "GET_FRAME_INFO",
9912 "GET_NAME",
9913 "GET_STATE",
9914 "GET_INFO",
9915 "GET_ID",
9916 "GET_TID",
9917 "SET_IP"
9920 static const char* event_cmds_str[] = {
9921 "REQUEST_SET",
9922 "REQUEST_CLEAR",
9923 "REQUEST_CLEAR_ALL_BREAKPOINTS"
9926 static const char* appdomain_cmds_str[] = {
9927 "GET_ROOT_DOMAIN",
9928 "GET_FRIENDLY_NAME",
9929 "GET_ASSEMBLIES",
9930 "GET_ENTRY_ASSEMBLY",
9931 "CREATE_STRING",
9932 "GET_CORLIB",
9933 "CREATE_BOXED_VALUE",
9934 "CREATE_BYTE_ARRAY",
9937 static const char* assembly_cmds_str[] = {
9938 "GET_LOCATION",
9939 "GET_ENTRY_POINT",
9940 "GET_MANIFEST_MODULE",
9941 "GET_OBJECT",
9942 "GET_TYPE",
9943 "GET_NAME",
9944 "GET_DOMAIN",
9945 "HAS_DEBUG_INFO"
9948 static const char* module_cmds_str[] = {
9949 "GET_INFO",
9952 static const char* field_cmds_str[] = {
9953 "GET_INFO",
9956 static const char* method_cmds_str[] = {
9957 "GET_NAME",
9958 "GET_DECLARING_TYPE",
9959 "GET_DEBUG_INFO",
9960 "GET_PARAM_INFO",
9961 "GET_LOCALS_INFO",
9962 "GET_INFO",
9963 "GET_BODY",
9964 "RESOLVE_TOKEN",
9965 "GET_CATTRS ",
9966 "MAKE_GENERIC_METHOD"
9969 static const char* type_cmds_str[] = {
9970 "GET_INFO",
9971 "GET_METHODS",
9972 "GET_FIELDS",
9973 "GET_VALUES",
9974 "GET_OBJECT",
9975 "GET_SOURCE_FILES",
9976 "SET_VALUES",
9977 "IS_ASSIGNABLE_FROM",
9978 "GET_PROPERTIES ",
9979 "GET_CATTRS",
9980 "GET_FIELD_CATTRS",
9981 "GET_PROPERTY_CATTRS",
9982 "GET_SOURCE_FILES_2",
9983 "GET_VALUES_2",
9984 "GET_METHODS_BY_NAME_FLAGS",
9985 "GET_INTERFACES",
9986 "GET_INTERFACE_MAP",
9987 "IS_INITIALIZED",
9988 "CREATE_INSTANCE",
9989 "GET_VALUE_SIZE"
9992 static const char* stack_frame_cmds_str[] = {
9993 "GET_VALUES",
9994 "GET_THIS",
9995 "SET_VALUES",
9996 "GET_DOMAIN",
9997 "SET_THIS"
10000 static const char* array_cmds_str[] = {
10001 "GET_LENGTH",
10002 "GET_VALUES",
10003 "SET_VALUES",
10006 static const char* string_cmds_str[] = {
10007 "GET_VALUE",
10008 "GET_LENGTH",
10009 "GET_CHARS"
10012 static const char* pointer_cmds_str[] = {
10013 "GET_VALUE"
10016 static const char* object_cmds_str[] = {
10017 "GET_TYPE",
10018 "GET_VALUES",
10019 "IS_COLLECTED",
10020 "GET_ADDRESS",
10021 "GET_DOMAIN",
10022 "SET_VALUES",
10023 "GET_INFO",
10026 static const char*
10027 cmd_to_string (CommandSet set, int command)
10029 const char **cmds;
10030 int cmds_len = 0;
10032 switch (set) {
10033 case CMD_SET_VM:
10034 cmds = vm_cmds_str;
10035 cmds_len = G_N_ELEMENTS (vm_cmds_str);
10036 break;
10037 case CMD_SET_OBJECT_REF:
10038 cmds = object_cmds_str;
10039 cmds_len = G_N_ELEMENTS (object_cmds_str);
10040 break;
10041 case CMD_SET_STRING_REF:
10042 cmds = string_cmds_str;
10043 cmds_len = G_N_ELEMENTS (string_cmds_str);
10044 break;
10045 case CMD_SET_THREAD:
10046 cmds = thread_cmds_str;
10047 cmds_len = G_N_ELEMENTS (thread_cmds_str);
10048 break;
10049 case CMD_SET_ARRAY_REF:
10050 cmds = array_cmds_str;
10051 cmds_len = G_N_ELEMENTS (array_cmds_str);
10052 break;
10053 case CMD_SET_EVENT_REQUEST:
10054 cmds = event_cmds_str;
10055 cmds_len = G_N_ELEMENTS (event_cmds_str);
10056 break;
10057 case CMD_SET_STACK_FRAME:
10058 cmds = stack_frame_cmds_str;
10059 cmds_len = G_N_ELEMENTS (stack_frame_cmds_str);
10060 break;
10061 case CMD_SET_APPDOMAIN:
10062 cmds = appdomain_cmds_str;
10063 cmds_len = G_N_ELEMENTS (appdomain_cmds_str);
10064 break;
10065 case CMD_SET_ASSEMBLY:
10066 cmds = assembly_cmds_str;
10067 cmds_len = G_N_ELEMENTS (assembly_cmds_str);
10068 break;
10069 case CMD_SET_METHOD:
10070 cmds = method_cmds_str;
10071 cmds_len = G_N_ELEMENTS (method_cmds_str);
10072 break;
10073 case CMD_SET_TYPE:
10074 cmds = type_cmds_str;
10075 cmds_len = G_N_ELEMENTS (type_cmds_str);
10076 break;
10077 case CMD_SET_MODULE:
10078 cmds = module_cmds_str;
10079 cmds_len = G_N_ELEMENTS (module_cmds_str);
10080 break;
10081 case CMD_SET_FIELD:
10082 cmds = field_cmds_str;
10083 cmds_len = G_N_ELEMENTS (field_cmds_str);
10084 break;
10085 case CMD_SET_EVENT:
10086 cmds = event_cmds_str;
10087 cmds_len = G_N_ELEMENTS (event_cmds_str);
10088 break;
10089 case CMD_SET_POINTER:
10090 cmds = pointer_cmds_str;
10091 cmds_len = G_N_ELEMENTS (pointer_cmds_str);
10092 break;
10093 default:
10094 return NULL;
10096 if (command > 0 && command <= cmds_len)
10097 return cmds [command - 1];
10098 else
10099 return NULL;
10102 static gboolean
10103 wait_for_attach (void)
10105 #ifndef DISABLE_SOCKET_TRANSPORT
10106 if (listen_fd == -1) {
10107 DEBUG_PRINTF (1, "[dbg] Invalid listening socket\n");
10108 return FALSE;
10111 /* Block and wait for client connection */
10112 conn_fd = socket_transport_accept (listen_fd);
10114 DEBUG_PRINTF (1, "Accepted connection on %d\n", conn_fd);
10115 if (conn_fd == -1) {
10116 DEBUG_PRINTF (1, "[dbg] Bad client connection\n");
10117 return FALSE;
10119 #else
10120 g_assert_not_reached ();
10121 #endif
10123 /* Handshake */
10124 disconnected = !transport_handshake ();
10125 if (disconnected) {
10126 DEBUG_PRINTF (1, "Transport handshake failed!\n");
10127 return FALSE;
10130 return TRUE;
10134 * debugger_thread:
10136 * This thread handles communication with the debugger client using a JDWP
10137 * like protocol.
10139 static gsize WINAPI
10140 debugger_thread (void *arg)
10142 int res, len, id, flags, command = 0;
10143 CommandSet command_set = (CommandSet)0;
10144 guint8 header [HEADER_LENGTH];
10145 guint8 *data, *p, *end;
10146 Buffer buf;
10147 ErrorCode err;
10148 gboolean no_reply;
10149 gboolean attach_failed = FALSE;
10151 DEBUG_PRINTF (1, "[dbg] Agent thread started, pid=%p\n", (gpointer) (gsize) mono_native_thread_id_get ());
10153 gboolean log_each_step = g_hasenv ("MONO_DEBUGGER_LOG_AFTER_COMMAND");
10155 debugger_thread_id = mono_native_thread_id_get ();
10157 MonoInternalThread *internal = mono_thread_internal_current ();
10158 mono_thread_set_name_constant_ignore_error (internal, "Debugger agent", MonoSetThreadNameFlag_Permanent);
10160 internal->state |= ThreadState_Background;
10161 internal->flags |= MONO_THREAD_FLAG_DONT_MANAGE;
10163 if (agent_config.defer) {
10164 if (!wait_for_attach ()) {
10165 DEBUG_PRINTF (1, "[dbg] Can't attach, aborting debugger thread.\n");
10166 attach_failed = TRUE; // Don't abort process when we can't listen
10167 } else {
10168 mono_set_is_debugger_attached (TRUE);
10169 /* Send start event to client */
10170 process_profiler_event (EVENT_KIND_VM_START, mono_thread_get_main ());
10172 } else {
10173 mono_set_is_debugger_attached (TRUE);
10176 while (!attach_failed) {
10177 res = transport_recv (header, HEADER_LENGTH);
10179 /* This will break if the socket is closed during shutdown too */
10180 if (res != HEADER_LENGTH) {
10181 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, HEADER_LENGTH);
10182 command_set = (CommandSet)0;
10183 command = 0;
10184 dispose_vm ();
10185 break;
10186 } else {
10187 p = header;
10188 end = header + HEADER_LENGTH;
10190 len = decode_int (p, &p, end);
10191 id = decode_int (p, &p, end);
10192 flags = decode_byte (p, &p, end);
10193 command_set = (CommandSet)decode_byte (p, &p, end);
10194 command = decode_byte (p, &p, end);
10197 g_assert (flags == 0);
10198 const char *cmd_str;
10199 char cmd_num [256];
10201 cmd_str = cmd_to_string (command_set, command);
10202 if (!cmd_str) {
10203 sprintf (cmd_num, "%d", command);
10204 cmd_str = cmd_num;
10207 if (log_level) {
10208 DEBUG_PRINTF (1, "[dbg] Command %s(%s) [%d][at=%lx].\n", command_set_to_string (command_set), cmd_str, id, (long)mono_100ns_ticks () / 10000);
10211 data = (guint8 *)g_malloc (len - HEADER_LENGTH);
10212 if (len - HEADER_LENGTH > 0)
10214 res = transport_recv (data, len - HEADER_LENGTH);
10215 if (res != len - HEADER_LENGTH) {
10216 DEBUG_PRINTF (1, "[dbg] transport_recv () returned %d, expected %d.\n", res, len - HEADER_LENGTH);
10217 break;
10221 p = data;
10222 end = data + (len - HEADER_LENGTH);
10224 buffer_init (&buf, 128);
10226 err = ERR_NONE;
10227 no_reply = FALSE;
10229 /* Process the request */
10230 switch (command_set) {
10231 case CMD_SET_VM:
10232 err = vm_commands (command, id, p, end, &buf);
10233 if (err == ERR_NONE && command == CMD_VM_INVOKE_METHOD)
10234 /* Sent after the invoke is complete */
10235 no_reply = TRUE;
10236 break;
10237 case CMD_SET_EVENT_REQUEST:
10238 err = event_commands (command, p, end, &buf);
10239 break;
10240 case CMD_SET_APPDOMAIN:
10241 err = domain_commands (command, p, end, &buf);
10242 break;
10243 case CMD_SET_ASSEMBLY:
10244 err = assembly_commands (command, p, end, &buf);
10245 break;
10246 case CMD_SET_MODULE:
10247 err = module_commands (command, p, end, &buf);
10248 break;
10249 case CMD_SET_FIELD:
10250 err = field_commands (command, p, end, &buf);
10251 break;
10252 case CMD_SET_TYPE:
10253 err = type_commands (command, p, end, &buf);
10254 break;
10255 case CMD_SET_METHOD:
10256 err = method_commands (command, p, end, &buf);
10257 break;
10258 case CMD_SET_THREAD:
10259 err = thread_commands (command, p, end, &buf);
10260 break;
10261 case CMD_SET_STACK_FRAME:
10262 err = frame_commands (command, p, end, &buf);
10263 break;
10264 case CMD_SET_ARRAY_REF:
10265 err = array_commands (command, p, end, &buf);
10266 break;
10267 case CMD_SET_STRING_REF:
10268 err = string_commands (command, p, end, &buf);
10269 break;
10270 case CMD_SET_POINTER:
10271 err = pointer_commands (command, p, end, &buf);
10272 break;
10273 case CMD_SET_OBJECT_REF:
10274 err = object_commands (command, p, end, &buf);
10275 break;
10276 default:
10277 err = ERR_NOT_IMPLEMENTED;
10280 if (command_set == CMD_SET_VM && command == CMD_VM_START_BUFFERING) {
10281 buffer_replies = TRUE;
10284 if (!no_reply) {
10285 if (buffer_replies) {
10286 buffer_reply_packet (id, err, &buf);
10287 } else {
10288 send_reply_packet (id, err, &buf);
10289 //DEBUG_PRINTF (1, "[dbg] Sent reply to %d [at=%lx].\n", id, (long)mono_100ns_ticks () / 10000);
10293 mono_debugger_log_command (command_set_to_string (command_set), cmd_str, buf.buf, buffer_len (&buf));
10295 if (err == ERR_NONE && command_set == CMD_SET_VM && command == CMD_VM_STOP_BUFFERING) {
10296 send_buffered_reply_packets ();
10297 buffer_replies = FALSE;
10300 g_free (data);
10301 buffer_free (&buf);
10303 if (log_each_step) {
10304 char *debugger_log = mono_debugger_state_str ();
10305 if (debugger_log) {
10306 fprintf (stderr, "Debugger state: %s\n", debugger_log);
10307 g_free (debugger_log);
10311 if (command_set == CMD_SET_VM && (command == CMD_VM_DISPOSE || command == CMD_VM_EXIT))
10312 break;
10315 mono_set_is_debugger_attached (FALSE);
10317 mono_coop_mutex_lock (&debugger_thread_exited_mutex);
10318 debugger_thread_exited = TRUE;
10319 mono_coop_cond_signal (&debugger_thread_exited_cond);
10320 mono_coop_mutex_unlock (&debugger_thread_exited_mutex);
10322 DEBUG_PRINTF (1, "[dbg] Debugger thread exited.\n");
10324 if (!attach_failed && command_set == CMD_SET_VM && command == CMD_VM_DISPOSE && !(vm_death_event_sent || mono_runtime_is_shutting_down ())) {
10325 DEBUG_PRINTF (2, "[dbg] Detached - restarting clean debugger thread.\n");
10326 ERROR_DECL (error);
10327 start_debugger_thread (error);
10328 mono_error_cleanup (error);
10331 return 0;
10334 void
10335 mono_debugger_agent_init (void)
10337 MonoDebuggerCallbacks cbs;
10339 memset (&cbs, 0, sizeof (cbs));
10340 cbs.version = MONO_DBG_CALLBACKS_VERSION;
10341 cbs.parse_options = debugger_agent_parse_options;
10342 cbs.init = debugger_agent_init;
10343 cbs.breakpoint_hit = debugger_agent_breakpoint_hit;
10344 cbs.single_step_event = debugger_agent_single_step_event;
10345 cbs.single_step_from_context = debugger_agent_single_step_from_context;
10346 cbs.breakpoint_from_context = debugger_agent_breakpoint_from_context;
10347 cbs.free_domain_info = debugger_agent_free_domain_info;
10348 cbs.unhandled_exception = debugger_agent_unhandled_exception;
10349 cbs.handle_exception = debugger_agent_handle_exception;
10350 cbs.begin_exception_filter = debugger_agent_begin_exception_filter;
10351 cbs.end_exception_filter = debugger_agent_end_exception_filter;
10352 cbs.user_break = debugger_agent_user_break;
10353 cbs.debug_log = debugger_agent_debug_log;
10354 cbs.debug_log_is_enabled = debugger_agent_debug_log_is_enabled;
10355 cbs.send_crash = mono_debugger_agent_send_crash;
10357 mini_install_dbg_callbacks (&cbs);
10360 void
10361 mono_debugger_agent_parse_options (char *options)
10363 sdb_options = options;
10366 #endif /* DISABLE_SDB */